ktstr 0.23.0

Test harness for Linux process schedulers
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
//! BPF verifier log parsing, cycle detection, and output formatting.
//!
//! Provides:
//! - [`VerifierStats`] / [`ProgStats`] / [`DiffRow`] — data types
//! - [`collect_verifier_output`] — boot VM, collect stats via host introspection
//! - [`format_verifier_output`] / [`format_verifier_diff`] — text formatting
//! - [`extract_verifier_log`] — extract verifier trace from libbpf log blob
//! - [`parse_verifier_stats`] — extract insn/state counts from verifier log
//! - [`normalize_verifier_line`] — strip variable register state annotations
//! - [`detect_cycle`] / [`collapse_cycles`] — loop iteration compression
//! - [`build_b_map`] / [`build_diff_rows`] — A/B comparison helpers
//! - `SCHED_OUTPUT_START` / `SCHED_OUTPUT_END` — delimiters the
//!   guest's rust_init emits over the bulk port (as `MSG_TYPE_SCHED_LOG`
//!   frames) around the scheduler log region;
//!   `parse_sched_output` extracts the enclosed block

use std::collections::HashMap;

/// Delimiter the guest's rust_init emits over the bulk port (as a
/// `MSG_TYPE_SCHED_LOG` frame) immediately before the scheduler log
/// block. Paired with [`SCHED_OUTPUT_END`].
pub(crate) const SCHED_OUTPUT_START: &str = "===SCHED_OUTPUT_START===";
/// Delimiter the guest's rust_init emits over the bulk port (as a
/// `MSG_TYPE_SCHED_LOG` frame) immediately after the scheduler log
/// block. Paired with [`SCHED_OUTPUT_START`].
pub(crate) const SCHED_OUTPUT_END: &str = "===SCHED_OUTPUT_END===";

/// Extract the scheduler log from guest output between
/// [`SCHED_OUTPUT_START`] and [`SCHED_OUTPUT_END`]. Returns `None` if
/// the delimiters are absent or the enclosed content is empty after
/// trimming.
///
/// Uses `find` on the start marker and `rfind` on the end marker: if
/// the scheduler log itself contains the end sentinel string (e.g. a
/// stack trace that quotes the marker), `rfind` anchors on the last
/// occurrence, which is the real terminator emitted by the guest's
/// post-scenario shutdown path.
pub(crate) fn parse_sched_output(output: &str) -> Option<&str> {
    let start = output.find(SCHED_OUTPUT_START)?;
    let end = output.rfind(SCHED_OUTPUT_END)?;
    let after_marker = start + SCHED_OUTPUT_START.len();
    if after_marker >= end {
        return None;
    }
    let content = output[after_marker..end].trim();
    if content.is_empty() {
        return None;
    }
    Some(content)
}

/// Concatenate every CRC-valid `MSG_TYPE_SCHED_LOG` chunk in the
/// bulk-port drain into one `String`, in arrival order.
///
/// The guest's `dump_sched_output` emits the `SCHED_OUTPUT_START`
/// and `SCHED_OUTPUT_END` markers as their own
/// [`crate::vmm::wire::MsgType::SchedLog`] frames, with the file
/// content split across one or more intermediate frames. Replaying
/// the chunks back-to-back reproduces the byte-for-byte stream the
/// prior COM2 path appended to `output`, so [`parse_sched_output`]
/// runs unchanged on the result.
///
/// Empty / `None` drain yields an empty string.
pub(crate) fn concat_sched_log_chunks(
    drain: Option<&crate::vmm::host_comms::BulkDrainResult>,
) -> String {
    let Some(drain) = drain else {
        return String::new();
    };
    let mut acc = String::new();
    for e in &drain.entries {
        if e.msg_type != crate::vmm::wire::MSG_TYPE_SCHED_LOG || !e.crc_ok {
            continue;
        }
        acc.push_str(&String::from_utf8_lossy(&e.payload));
    }
    acc
}

/// Extract scheduler log content even when the closing delimiter is
/// absent. Tries [`parse_sched_output`] first (well-formed
/// open+close); on failure, returns the slice from
/// [`SCHED_OUTPUT_START`] to the end of `output` when only the start
/// marker is present. Returns `None` only when neither marker is
/// found or every candidate slice is empty after trimming.
///
/// Used by the auto-repro path: a scheduler that crashes mid-run
/// emits SCHED_OUTPUT_START but never reaches the post-scenario
/// shutdown that writes SCHED_OUTPUT_END. The partial content still
/// holds the stack frames the probe pipeline needs to seed kprobe
/// targets, so discarding it would lose the only crash signal.
pub(crate) fn parse_sched_output_partial(output: &str) -> Option<&str> {
    if let Some(content) = parse_sched_output(output) {
        return Some(content);
    }
    let start = output.find(SCHED_OUTPUT_START)?;
    let after_marker = start + SCHED_OUTPUT_START.len();
    let content = output[after_marker..].trim();
    if content.is_empty() {
        return None;
    }
    Some(content)
}

/// Parsed verifier stats from the kernel log line:
/// `processed N insns (limit M) max_states_per_insn X total_states Y peak_states Z mark_read W`
pub struct VerifierStats {
    /// Instructions processed during verification.
    pub processed_insns: u64,
    /// Total explored verifier states.
    pub total_states: u64,
    /// Peak concurrent explored states.
    pub peak_states: u64,
    /// Total verification wall time in microseconds, when
    /// BPF_LOG_STATS emitted a "verification time" line.
    pub time_usec: Option<u64>,
    /// Stack depth in the format `"<prog>+<subprog>+<main>"` (e.g.
    /// `"32+16+8"`) when BPF_LOG_STATS emitted a "stack depth" line.
    pub stack_depth: Option<String>,
}

/// Per-program verifier statistics collected from a VM run.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProgStats {
    /// Program name as registered with the kernel.
    pub name: String,
    /// Instructions processed by the verifier (from host-side
    /// `bpf_prog_aux->verified_insns`).
    pub verified_insns: u32,
}

/// A single row in the A/B diff output.
pub struct DiffRow {
    /// Program name present in both A and B runs.
    pub name: String,
    /// `verified_insns` from the A run.
    pub a: u64,
    /// `verified_insns` from the B run.
    pub b: u64,
    /// Signed delta (`b - a`); positive means B's verifier cost grew
    /// relative to A.
    pub delta: i64,
}

/// Parse `raw` as `u64`, warning with `field` context on failure.
/// Returns 0 on parse error. Centralizes the
/// warn-and-default-to-zero path for the three count words
/// (`processed_insns`, `total_states`, `peak_states`) so their
/// error handling stays in lock-step.
fn parse_or_warn(raw: &str, field: &str) -> u64 {
    match raw.parse() {
        Ok(n) => n,
        Err(e) => {
            tracing::warn!(
                field,
                word = raw,
                err = %e,
                "malformed BPF verifier count; leaving 0",
            );
            0
        }
    }
}

/// Parse verifier stats from the log output.
///
/// The kernel always emits a "processed N insns ..." line. When
/// BPF_LOG_STATS is set, it also emits "verification time" and
/// "stack depth" lines.
pub fn parse_verifier_stats(log: &str) -> VerifierStats {
    let mut stats = VerifierStats {
        processed_insns: 0,
        total_states: 0,
        peak_states: 0,
        time_usec: None,
        stack_depth: None,
    };

    let mut found_insns = false;
    let mut found_time = false;
    let mut found_stack = false;

    for line in log.lines().rev() {
        if !found_insns && line.starts_with("processed ") {
            found_insns = true;
            let words: Vec<&str> = line.split_whitespace().collect();
            if words.len() >= 2 {
                stats.processed_insns = parse_or_warn(words[1], "processed_insns");
            }
            for (i, &w) in words.iter().enumerate() {
                if w == "total_states"
                    && let Some(v) = words.get(i + 1)
                {
                    stats.total_states = parse_or_warn(v, "total_states");
                }
                if w == "peak_states"
                    && let Some(v) = words.get(i + 1)
                {
                    stats.peak_states = parse_or_warn(v, "peak_states");
                }
            }
        }
        if !found_time && line.contains("verification time") {
            found_time = true;
            for word in line.split_whitespace() {
                if let Ok(n) = word.parse::<u64>() {
                    stats.time_usec = Some(n);
                    break;
                }
            }
        }
        if !found_stack && line.contains("stack depth") {
            found_stack = true;
            if let Some(pos) = line.find("stack depth") {
                let after = &line[pos + "stack depth".len()..];
                let depth_str = after.trim();
                if !depth_str.is_empty() {
                    stats.stack_depth = Some(depth_str.to_string());
                }
            }
        }
        if found_insns && found_time && found_stack {
            break;
        }
    }

    stats
}

/// Normalize a BPF verifier log line by stripping variable register-state
/// annotations so that lines from different loop iterations compare equal.
///
/// Handles:
/// - Instruction with `; frame` annotation: `3006: (07) r9 += 1  ; frame1: R9_w=2`
/// - Instruction with `; R` + digit annotation: `9: (15) if r7 == 0x0 goto pc+1  ; R7=scalar(...)`
/// - Branch with inline target state: `3026: (b5) if r6 <= 0x11dc0 goto pc+2 3029: frame1: R0=1`
/// - Standalone register dump with frame: `3041: frame1: R0_w=scalar()`
/// - Standalone register dump without frame: `3029: R0=1 R6=scalar()`
///
/// Preserves source comments (`; for (int j = 0; ...)`) and non-annotation
/// semicolons (`; Return value`) -- these serve as cycle anchors.
pub fn normalize_verifier_line(line: &str) -> &str {
    let trimmed = line.trim();
    if trimmed.is_empty() || !trimmed.as_bytes()[0].is_ascii_digit() {
        return trimmed;
    }
    // "3041: frame1: ..." or "3041: R0_w=scalar()" — standalone register dump.
    // State-only lines; keep just the instruction index.
    if let Some(colon) = trimmed.find(": ") {
        let after = &trimmed[colon + 2..];
        if after.starts_with("frame")
            || (after.starts_with('R')
                && after.as_bytes().get(1).is_some_and(|b| b.is_ascii_digit()))
        {
            return &trimmed[..colon + 1];
        }
    }
    // "; frame" annotation on instruction line
    if let Some(pos) = trimmed.find("; frame") {
        return trimmed[..pos].trim_end();
    }
    // "; R" followed by digit — register annotation without frame prefix
    if let Some(pos) = trimmed.find("; R")
        && trimmed
            .as_bytes()
            .get(pos + 3)
            .is_some_and(|b| b.is_ascii_digit())
    {
        return trimmed[..pos].trim_end();
    }
    // Inline branch-target state: "goto pc+2 3029: frame1: ..."
    if let Some(goto_pos) = trimmed.find("goto pc") {
        let after_goto = &trimmed[goto_pos + 7..];
        let end = after_goto
            .find(|c: char| c != '+' && c != '-' && !c.is_ascii_digit())
            .unwrap_or(after_goto.len());
        let insn_end = goto_pos + 7 + end;
        if insn_end < trimmed.len() {
            return trimmed[..insn_end].trim_end();
        }
    }
    trimmed
}

/// Normalize for cycle detection: strip register annotations (via
/// `normalize_verifier_line`) then strip the leading instruction address
/// (`NNN: `). Unrolled loops place each copy at different addresses, so
/// the address must be removed for block comparison to find repeats.
fn normalize_for_cycle_detection(line: &str) -> &str {
    let n = normalize_verifier_line(line);
    // Strip leading digits + ": " prefix (e.g. "42: (07) r1 += 8" -> "(07) r1 += 8").
    if let Some(colon) = n.find(": ") {
        let before = &n[..colon];
        if !before.is_empty() && before.bytes().all(|b| b.is_ascii_digit()) {
            return &n[colon + 2..];
        }
    }
    n
}

/// Detect a single repeating cycle in a slice of lines.
///
/// Returns `Some((start, period, count))` where the cycle begins at
/// `start`, each iteration is `period` lines, and it repeats `count` times.
pub fn detect_cycle(lines: &[&str]) -> Option<(usize, usize, usize)> {
    const MIN_PERIOD: usize = 5;
    const MIN_REPS: usize = 3;

    if lines.len() < MIN_PERIOD * MIN_REPS {
        return None;
    }

    // Two normalization levels:
    // - anchor_norms: keeps addresses, strips register annotations. Used for
    //   anchor frequency counting — prevents within-period duplicates at
    //   different addresses from inflating frequency.
    // - block_norms: also strips addresses. Used for block equality comparison
    //   so unrolled loops (same instructions at different addresses) can match.
    let anchor_norms: Vec<&str> = lines.iter().map(|l| normalize_verifier_line(l)).collect();
    let block_norms: Vec<&str> = lines
        .iter()
        .map(|l| normalize_for_cycle_detection(l))
        .collect();

    // Find most frequent non-trivial anchor-normalized line.
    let mut sorted_norms: Vec<&str> = anchor_norms
        .iter()
        .filter(|l| l.len() >= 10)
        .copied()
        .collect();
    sorted_norms.sort_unstable();

    let mut best_anchor: Option<(&str, usize)> = None;
    let mut i = 0;
    while i < sorted_norms.len() {
        let mut j = i + 1;
        while j < sorted_norms.len() && sorted_norms[j] == sorted_norms[i] {
            j += 1;
        }
        let count = j - i;
        if count >= MIN_REPS && best_anchor.is_none_or(|(_, best)| count > best) {
            best_anchor = Some((sorted_norms[i], count));
        }
        i = j;
    }

    // If address-preserving anchor search found nothing (unrolled loops
    // where every address is unique), fall back to address-stripped norms.
    let (anchor, use_block_norms_for_positions) = match best_anchor {
        Some((a, _)) => (a, false),
        None => {
            let mut sorted_block: Vec<&str> = block_norms
                .iter()
                .filter(|l| l.len() >= 10)
                .copied()
                .collect();
            sorted_block.sort_unstable();
            let mut ba: Option<(&str, usize)> = None;
            let mut bi = 0;
            while bi < sorted_block.len() {
                let mut bj = bi + 1;
                while bj < sorted_block.len() && sorted_block[bj] == sorted_block[bi] {
                    bj += 1;
                }
                let c = bj - bi;
                if c >= MIN_REPS && ba.is_none_or(|(_, best)| c > best) {
                    ba = Some((sorted_block[bi], c));
                }
                bi = bj;
            }
            match ba {
                Some((a, _)) => (a, true),
                None => return None,
            }
        }
    };

    let norms_for_pos = if use_block_norms_for_positions {
        &block_norms
    } else {
        &anchor_norms
    };
    let positions: Vec<usize> = norms_for_pos
        .iter()
        .enumerate()
        .filter(|(_, l)| **l == anchor)
        .map(|(i, _)| i)
        .collect();

    // Try strides 1..=3 to handle anchors appearing K times per cycle.
    for stride in 1..=3usize {
        if positions.len() <= stride {
            continue;
        }

        let mut gaps: Vec<usize> = positions
            .windows(stride + 1)
            .map(|w| w[stride] - w[0])
            .filter(|g| *g >= MIN_PERIOD)
            .collect();
        gaps.sort_unstable();

        let mut best_period = 0;
        let mut best_gap_count = 0;
        let mut gi = 0;
        while gi < gaps.len() {
            let mut gj = gi + 1;
            while gj < gaps.len() && gaps[gj] == gaps[gi] {
                gj += 1;
            }
            let count = gj - gi;
            if count > best_gap_count {
                best_gap_count = count;
                best_period = gaps[gi];
            }
            gi = gj;
        }
        if best_period == 0 || best_gap_count < MIN_REPS - 1 {
            continue;
        }
        let period = best_period;

        for &pos in &positions {
            if pos + 2 * period > lines.len() {
                break;
            }
            if block_norms[pos..pos + period] == block_norms[pos + period..pos + 2 * period] {
                let first_block = &block_norms[pos..pos + period];
                let mut count = 1;
                while pos + (count + 1) * period <= lines.len() {
                    if block_norms[pos + count * period..pos + (count + 1) * period] != *first_block
                    {
                        break;
                    }
                    count += 1;
                }
                // Try earlier starts to find best alignment.
                let mut best_start = pos;
                let mut best_count = count;
                for offset in 1..period {
                    let Some(cand) = pos.checked_sub(offset) else {
                        break;
                    };
                    if cand + 2 * period > lines.len() {
                        continue;
                    }
                    if block_norms[cand..cand + period]
                        != block_norms[cand + period..cand + 2 * period]
                    {
                        continue;
                    }
                    let mut c = 2;
                    while cand + (c + 1) * period <= lines.len()
                        && block_norms[cand + c * period..cand + (c + 1) * period]
                            == block_norms[cand..cand + period]
                    {
                        c += 1;
                    }
                    if c > best_count {
                        best_start = cand;
                        best_count = c;
                    }
                }
                if best_count >= MIN_REPS {
                    return Some((best_start, period, best_count));
                }
            }
        }
    }

    None
}

/// Collapse repeating cycles in a verifier log.
///
/// Runs cycle detection iteratively (up to 5 passes for nested loops).
/// Each cycle is replaced with:
/// - `--- Nx of the following M lines ---` (count header, no closing marker)
/// - first iteration (with original register annotations)
/// - `--- K identical iterations omitted ---` (omission marker)
/// - last iteration (with original register annotations)
/// - `--- end repeat ---` (closes the omission)
pub fn collapse_cycles(log: &str) -> String {
    const MAX_PASSES: usize = 5;
    let mut text = log.to_string();

    for _ in 0..MAX_PASSES {
        let lines: Vec<&str> = text.lines().collect();
        let (start, period, count) = match detect_cycle(&lines) {
            Some(c) => c,
            None => break,
        };

        let mut out = String::new();
        for line in &lines[..start] {
            out.push_str(line);
            out.push('\n');
        }
        out.push_str(&format!(
            "--- {}x of the following {} lines ---\n",
            count, period
        ));
        for line in &lines[start..start + period] {
            out.push_str(line);
            out.push('\n');
        }
        out.push_str(&format!(
            "--- {} identical iterations omitted ---\n",
            count - 2
        ));
        let last_start = start + (count - 1) * period;
        for line in &lines[last_start..last_start + period] {
            out.push_str(line);
            out.push('\n');
        }
        out.push_str("--- end repeat ---\n");
        let suffix_start = start + count * period;
        for line in &lines[suffix_start..] {
            out.push_str(line);
            out.push('\n');
        }
        text = out;
    }

    text
}

/// Build diff rows from A stats and B lookup map.
pub fn build_diff_rows(stats_a: &[ProgStats], b_map: &HashMap<String, u64>) -> Vec<DiffRow> {
    let mut rows = Vec::new();
    for ps in stats_a {
        let a = ps.verified_insns as u64;
        let b = b_map.get(&ps.name).copied().unwrap_or(0);
        rows.push(DiffRow {
            name: ps.name.clone(),
            a,
            b,
            delta: a as i64 - b as i64,
        });
    }
    rows
}

/// Build the B-side lookup map from collected stats.
pub fn build_b_map(stats_b: &[ProgStats]) -> HashMap<String, u64> {
    stats_b
        .iter()
        .map(|ps| (ps.name.clone(), ps.verified_insns as u64))
        .collect()
}

// ---------------------------------------------------------------------------
// VM-based verifier collection
// ---------------------------------------------------------------------------

/// Whether the scheduler positively confirmed it turned on during a
/// verifier VM run.
///
/// The guest init's attach gate (`poll_startup` + `poll_scx_attached`
/// in `crate::vmm::rust_init::scheduler`) already runs on every verifier
/// VM boot: it confirms the scheduler process survived BPF load AND that
/// `/sys/kernel/sched_ext/state` reached `enabled`. The kernel sets
/// `enabled` only after `ops.init`, per-task init, and switching
/// eligible tasks to the sched_ext class (`kernel/sched/ext.c`
/// `scx_root_enable_workfn`), so `enabled` proves the scheduler turned
/// on and is scheduling — not merely that its BPF loaded.
///
/// The verdict is POSITIVE-confirmation, not absence-of-failure: a
/// verifier cell PASSes only when the guest reached its post-attach
/// dispatch phase — a `PayloadStarting` lifecycle frame, emitted at
/// `ktstr_guest_init` Phase 5, which is reached ONLY if `start_scheduler`
/// succeeded in Phase 3. On attach failure the guest emits
/// `SchedulerDied` / `SchedulerNotAttached` and force-reboots in Phase 3
/// BEFORE Phase 5, so no `PayloadStarting` arrives. A guest that vanishes
/// before Phase 5 with NO frame at all — e.g. a kernel panic, which
/// reboots via the guest's `panic=-1` (an i8042 reset →
/// `ExitAction::Shutdown`, NOT a host watchdog timeout) — is
/// [`AttachOutcome::Unconfirmed`], also a FAIL. Absence-of-failure alone
/// would false-PASS that vanish case. [`collect_verifier_output`]
/// consumes this verdict instead of discarding it. Scheduler-agnostic
/// (kernel sysfs state), so it holds for every declared scheduler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AttachOutcome {
    /// The guest reached its post-attach dispatch phase (a
    /// `PayloadStarting` frame) with no failure frame: the scheduler
    /// loaded, stayed alive, and reached sched_ext `enabled`.
    Attached,
    /// Scheduler process exited during BPF load / startup
    /// (`LifecyclePhase::SchedulerDied`).
    Died,
    /// Scheduler stayed alive but never reached `enabled`
    /// (`LifecyclePhase::SchedulerNotAttached`); carries the guest's
    /// reason suffix when present.
    NotAttached(String),
    /// No failure frame AND no `PayloadStarting` frame: the guest never
    /// reached the post-attach dispatch phase, so attach was never
    /// positively confirmed (e.g. an early guest kernel panic that
    /// reboots via `panic=-1` before Phase 3 — emitting no lifecycle
    /// frame and NOT tripping the host watchdog).
    Unconfirmed,
}

impl AttachOutcome {
    /// Human-readable failure reason, or `None` when attached.
    pub fn failure_reason(&self) -> Option<String> {
        match self {
            AttachOutcome::Attached => None,
            AttachOutcome::Died => {
                Some("scheduler process exited during BPF load/startup".to_string())
            }
            AttachOutcome::NotAttached(reason) if reason.is_empty() => {
                Some("scheduler never reached sched_ext 'enabled'".to_string())
            }
            AttachOutcome::NotAttached(reason) => Some(format!(
                "scheduler never reached sched_ext 'enabled': {reason}"
            )),
            AttachOutcome::Unconfirmed => Some(
                "scheduler attach unconfirmed — guest never reached the dispatch phase \
                 (no PayloadStarting frame; possible early guest kernel panic)"
                    .to_string(),
            ),
        }
    }
}

/// Derive the [`AttachOutcome`] from a VM run's bulk-port lifecycle
/// frames using a POSITIVE-confirmation rule:
/// - a `SchedulerDied` frame ⇒ [`AttachOutcome::Died`] (wins outright —
///   a process that exited cannot have attached);
/// - else a `SchedulerNotAttached` frame ⇒ [`AttachOutcome::NotAttached`]
///   (with its reason suffix);
/// - else a `PayloadStarting` frame ⇒ [`AttachOutcome::Attached`] (the
///   guest reached its post-attach dispatch phase, so the scheduler
///   turned on);
/// - else [`AttachOutcome::Unconfirmed`] — no failure AND no positive
///   frame, so attach was never confirmed (e.g. an early guest kernel
///   panic that reboots before Phase 5 without emitting any frame).
///
/// Corrupt frames (`crc_ok == false`) and empty payloads are skipped. A
/// `None` `guest_messages` (no frames at all) is
/// [`AttachOutcome::Unconfirmed`].
pub(crate) fn attach_outcome_from_messages(
    guest_messages: Option<&crate::vmm::host_comms::BulkDrainResult>,
) -> AttachOutcome {
    let Some(drain) = guest_messages else {
        return AttachOutcome::Unconfirmed;
    };
    let mut not_attached: Option<String> = None;
    let mut payload_starting = false;
    for e in &drain.entries {
        if e.msg_type != crate::vmm::wire::MSG_TYPE_LIFECYCLE || !e.crc_ok || e.payload.is_empty() {
            continue;
        }
        match crate::vmm::wire::LifecyclePhase::from_wire(e.payload[0]) {
            Some(crate::vmm::wire::LifecyclePhase::SchedulerDied) => return AttachOutcome::Died,
            Some(crate::vmm::wire::LifecyclePhase::SchedulerNotAttached) => {
                not_attached = Some(String::from_utf8_lossy(&e.payload[1..]).into_owned());
            }
            Some(crate::vmm::wire::LifecyclePhase::PayloadStarting) => {
                payload_starting = true;
            }
            _ => {}
        }
    }
    if let Some(reason) = not_attached {
        AttachOutcome::NotAttached(reason)
    } else if payload_starting {
        AttachOutcome::Attached
    } else {
        AttachOutcome::Unconfirmed
    }
}

/// Whether the guest confirmed workload dispatch: at least one
/// `WorkloadDispatched` lifecycle frame (crc-ok, non-empty payload) in
/// the run's bulk-port frames. Emitted by `ktstr_guest_init` Phase 5 only
/// when the injected SpinWait workload recorded a worker with non-zero
/// `iterations` under a confirmed SCHED_EXT policy (`sched_policy_error`
/// is None) after the scheduler attached — so a fair-class fallback
/// cannot false-confirm — a positive, scheduler-agnostic proof the
/// scheduler dispatched a task onto a CPU.
/// Corrupt frames (`crc_ok == false`) and empty payloads are skipped. A
/// `None` `guest_messages` (no frames at all) is `false`.
fn dispatch_confirmed_from_messages(
    guest_messages: Option<&crate::vmm::host_comms::BulkDrainResult>,
) -> bool {
    let Some(drain) = guest_messages else {
        return false;
    };
    drain.entries.iter().any(|e| {
        e.msg_type == crate::vmm::wire::MSG_TYPE_LIFECYCLE
            && e.crc_ok
            && !e.payload.is_empty()
            && crate::vmm::wire::LifecyclePhase::from_wire(e.payload[0])
                == Some(crate::vmm::wire::LifecyclePhase::WorkloadDispatched)
    })
}

/// Result of collecting verifier output from a VM run.
pub struct VerifierVmResult {
    /// Per-program verifier statistics from host-side memory
    /// introspection (`bpf_prog_aux->verified_insns`).
    pub stats: Vec<ProgStats>,
    /// Scheduler log (stdout+stderr) from the VM. Contains libbpf's
    /// verifier instruction traces when BPF load fails.
    pub scheduler_log: String,
    /// Whether the scheduler positively confirmed attach. Derived from
    /// the guest's lifecycle frames ([`AttachOutcome`]). Attach is
    /// necessary but NOT sufficient for a cell PASS: this must be
    /// [`AttachOutcome::Attached`] (the guest reached its post-attach
    /// dispatch phase) AND [`Self::dispatched`] must be true. Verification
    /// alone (non-empty `stats`) is not enough — a scheduler whose BPF
    /// loads but never reaches sched_ext `enabled`, or a guest that
    /// vanishes before the dispatch phase, is a real failure.
    pub attach: AttachOutcome,
    /// Whether the guest confirmed the injected verifier workload
    /// dispatched — a `WorkloadDispatched` lifecycle frame, emitted by
    /// `ktstr_guest_init` Phase 5 when the SpinWait probe recorded a
    /// worker with non-zero `iterations` under a confirmed SCHED_EXT
    /// policy after attach (so a fair-class fallback cannot false-confirm).
    /// A cell PASSes only
    /// when this is true AND [`Self::attach`] is
    /// [`AttachOutcome::Attached`]: a scheduler that turns on (sched_ext
    /// `enabled`) but never dispatches a runnable task is a real, distinct
    /// failure — worse than never attaching — that the attach verdict
    /// alone cannot catch. Derived from the run's lifecycle frames;
    /// scheduler-agnostic — the probe runs as SCHED_EXT, so the BPF
    /// scheduler dispatches it under any switch mode (full or
    /// `SCX_OPS_SWITCH_PARTIAL`) and non-zero worker progress proves
    /// dispatch, unlike an scx-specific `nr_dispatched` counter.
    pub dispatched: bool,
    /// The host watchdog fired (hard-deadline hang) before the guest
    /// exited. Orthogonal to [`Self::attach`]: the attach verdict already
    /// fails a guest that vanished BEFORE the dispatch phase — an early
    /// kernel panic reboots via `panic=-1` (an i8042 reset →
    /// `ExitAction::Shutdown`, `timed_out == false`) and is
    /// [`AttachOutcome::Unconfirmed`]. This flag catches the remaining
    /// case: a guest that wedges AFTER attaching (during teardown), which
    /// leaves `attach == Attached` but never exits. A verifier cell FAILs
    /// on it too — but NOT on the guest exit code, which is `1` even on
    /// the verifier success path (no `#[ktstr_test]` body to dispatch).
    pub timed_out: bool,
}

impl VerifierVmResult {
    /// The verifier cell PASS/FAIL verdict: `Ok(())` when the scheduler
    /// verified its BPF, attached (sched_ext `enabled`), AND dispatched
    /// the injected workload; `Err(reason)` naming the first failing gate
    /// otherwise. Gate order — `timed_out` (a post-attach teardown hang),
    /// then attach (did it turn on?), then dispatch (did it schedule a
    /// task?) — so the root-cause failure is reported first: an attach
    /// failure is named before the dispatch gate it necessarily also
    /// trips. Does NOT key on the guest exit code, which is `1` even on
    /// the verifier success path (no `#[ktstr_test]` body to dispatch).
    pub fn cell_verdict(&self) -> Result<(), String> {
        // A hard-deadline hang. The attach verdict (Unconfirmed) already
        // fails a guest that vanished BEFORE the dispatch phase (an early
        // panic reboots via panic=-1 with timed_out=false), so this
        // catches the orthogonal case: a guest that wedges AFTER attaching,
        // during teardown.
        if self.timed_out {
            return Err("VM timed out (hung after attach, before exit)".to_string());
        }
        // PASS requires the scheduler to have turned ON, not just to have
        // loaded + verified its BPF.
        if let Some(reason) = self.attach.failure_reason() {
            return Err(format!("scheduler did not turn on — {reason}"));
        }
        // PASS also requires DISPATCH: the guest injects a SpinWait
        // workload after attach and only emits WorkloadDispatched when a
        // SCHED_EXT worker makes forward progress. A scheduler that turns
        // on but never dispatches a runnable task is a distinct, worse
        // failure the attach gate can't catch.
        if !self.dispatched {
            return Err(
                "scheduler attached but did not dispatch the injected workload (0 iterations)"
                    .to_string(),
            );
        }
        Ok(())
    }
}

/// Boot a VM and collect verifier statistics via host-side memory
/// introspection. Per-program `verified_insns` comes from
/// `bpf_prog_aux->verified_insns` read through the guest's physical
/// memory. On load failure, libbpf prints the verifier log to stderr;
/// the returned `scheduler_log` field contains the scheduler's captured
/// output from the VM.
///
/// `topology` selects the verifier VM's emulated topology via
/// [`crate::test_support::TopologyJson`] — the same named-field
/// shape carried in the per-scheduler `--ktstr-list-schedulers`
/// JSON. The named fields force callers to spell every dimension
/// at the call site, preventing position-swap misorders. The sole
/// caller is the sweep cell handler (`crate::test_support::dispatch`'s
/// `run_verifier_cell`), which passes the topology of the gauntlet
/// preset named in the cell — the verifier sweeps each scheduler across
/// every preset its constraints accept under no_perf_mode.
pub fn collect_verifier_output(
    sched_bin: &std::path::Path,
    ktstr_bin: &std::path::Path,
    kernel: &std::path::Path,
    extra_sched_args: &[String],
    topology: crate::test_support::TopologyJson,
) -> anyhow::Result<VerifierVmResult> {
    use anyhow::Context;

    // Pre-validate via TryFrom so a clean "topology rejected" error
    // surfaces here instead of the builder's Topology::new panic on
    // bad input.
    let validated: crate::vmm::topology::Topology = topology
        .try_into()
        .map_err(|e: String| anyhow::anyhow!("invalid topology {topology:?}: {e}"))?;

    let sched_args: Vec<String> = extra_sched_args.to_vec();

    // The verifier only loads the scheduler's BPF and reads the kernel
    // verifier's load-time `verified_insns` counts via host-side
    // introspection — a value fixed at BPF load, wholly INDEPENDENT of
    // perf-mode tuning (CPU pinning, RT priority, hugepages, NUMA mbind,
    // KVM exit suppression). So the verifier VM ALWAYS runs with
    // performance mode disabled: it needs none of that tuning. Disabling
    // perf mode also moves the run OFF the default run-lock path — whose
    // per-offset `LOCK_SH` search hard-fails "all N LLC slots busy
    // (LOCK_SH)" (`acquire_default_run_locks`, src/vmm/mod.rs) when no
    // candidate offset is free, the failure the verifier was hitting —
    // ONTO the no-perf-mode plan, which reserves a shared (`LOCK_SH`)
    // SUBSET of LLCs via `acquire_llc_plan`. `LOCK_SH` holders are
    // mutually compatible, so parallel verifier / no-perf cells no longer
    // starve each other on the LLC lock; a `performance_mode` peer holding
    // `LOCK_EX` on those LLCs can still defer a cell (nextest retries it),
    // which is correct — the verifier must not perturb an isolated peer's
    // pinned CPUs. Note `no_perf_mode(true)` does NOT skip the reservation
    // ENTIRELY — only `KTSTR_BYPASS_LLC_LOCKS=1` does; see
    // [`crate::vmm::KtstrVmBuilder::no_perf_mode`].
    // Pass the validated Topology directly so misorder cannot occur
    // at the builder boundary (the TryFrom above already enforces the
    // type-level invariants).
    let vm = crate::vmm::KtstrVm::builder()
        .kernel(kernel)
        .init_binary(ktstr_bin)
        .scheduler_binary(sched_bin)
        .sched_args(&sched_args)
        // Boot the guest into the verifier dispatch probe: the sweep VM
        // has no `#[ktstr_test]` body, so Phase 5 spawns a SpinWait
        // workload and emits `WorkloadDispatched` on confirmed progress.
        // The PASS verdict requires that frame in addition to attach.
        .run_args(&[crate::test_support::VERIFIER_WORKLOAD_FLAG.to_string()])
        .topology(validated)
        .memory_mib(2048)
        .timeout(std::time::Duration::from_secs(120))
        .no_perf_mode(true)
        .build()
        .context("build verifier VM")?;

    let result = vm.run().context("run verifier VM")?;

    // Concatenate bulk-port `MSG_TYPE_SCHED_LOG` chunks, then run
    // the marker-pair extractor on the merged stream — the
    // SCHED_OUTPUT_START/END markers travel verbatim inside chunk
    // bytes so the existing parser slices the same content the
    // prior COM2 dump produced. Falls back to `result.output` when
    // the bulk-port drain has no SchedLog frames (verifier VM
    // running on a kernel without the bulk port, for instance).
    let merged = concat_sched_log_chunks(result.guest_messages.as_ref());
    let scheduler_log = if !merged.is_empty() {
        parse_sched_output(&merged).unwrap_or("").to_string()
    } else {
        parse_sched_output(&result.output).unwrap_or("").to_string()
    };

    // Build ProgStats from host-side ProgVerifierStats. Each program
    // that loaded successfully is visible in prog_idr with its
    // verified_insns count.
    let stats: Vec<ProgStats> = result
        .verifier_stats
        .iter()
        .map(|pvs| ProgStats {
            name: pvs.name.clone(),
            verified_insns: pvs.verified_insns,
        })
        .collect();

    let attach = attach_outcome_from_messages(result.guest_messages.as_ref());
    let dispatched = dispatch_confirmed_from_messages(result.guest_messages.as_ref());

    Ok(VerifierVmResult {
        stats,
        scheduler_log,
        attach,
        dispatched,
        timed_out: result.timed_out,
    })
}

/// Extract the verifier instruction trace from a scheduler log blob.
///
/// libbpf wraps the kernel verifier log between marker lines:
///   `-- BEGIN PROG LOAD LOG --`
///   `-- END PROG LOAD LOG --`
///
/// Returns the content between the first pair of markers, or `None` if
/// no markers are found (backward compat with logs that contain only
/// raw verifier output).
pub fn extract_verifier_log(scheduler_log: &str) -> Option<&str> {
    const BEGIN: &str = "-- BEGIN PROG LOAD LOG --";
    const END: &str = "-- END PROG LOAD LOG --";

    let begin_pos = scheduler_log.find(BEGIN)?;
    let content_start = begin_pos + BEGIN.len();
    // Skip the newline after the BEGIN marker if present.
    let content_start = if scheduler_log.as_bytes().get(content_start) == Some(&b'\n') {
        content_start + 1
    } else {
        content_start
    };
    let end_pos = scheduler_log[content_start..].find(END)?;
    let content = &scheduler_log[content_start..content_start + end_pos];
    // The END marker may appear mid-line (e.g. "libbpf: -- END ...").
    // Trim back to the last newline to drop the partial prefix.
    let content = content
        .rfind('\n')
        .map(|p| &content[..p])
        .unwrap_or(content);
    Some(content.trim_end_matches('\n'))
}

/// Format verifier results as text: brief lines per program and collapsed
/// logs.
pub fn format_verifier_output(label: &str, result: &VerifierVmResult, raw: bool) -> String {
    let mut out = String::new();
    out.push_str(&format!("\n{label}\n"));
    if result.timed_out {
        out.push_str("  scheduler: UNKNOWN — VM timed out before exit\n");
    } else {
        match result.attach.failure_reason() {
            None => {
                out.push_str("  scheduler: attached (sched_ext enabled)\n");
                if result.dispatched {
                    out.push_str("  dispatch: confirmed (injected workload ran)\n");
                } else {
                    out.push_str(
                        "  dispatch: NOT CONFIRMED — attached but injected workload made no progress\n",
                    );
                }
            }
            Some(reason) => out.push_str(&format!("  scheduler: NOT ATTACHED — {reason}\n")),
        }
    }
    for ps in &result.stats {
        out.push_str(&format!(
            "  {:<40} verified_insns={}\n",
            ps.name, ps.verified_insns
        ));
    }

    if !result.scheduler_log.is_empty() {
        // Extract the verifier log from between libbpf's markers.
        // Falls back to the full scheduler_log when no markers exist.
        let verifier_log =
            extract_verifier_log(&result.scheduler_log).unwrap_or(&result.scheduler_log);

        let vs = parse_verifier_stats(verifier_log);
        if vs.processed_insns > 0 {
            out.push_str(&format!("\n{label} --- verifier stats ---\n"));
            out.push_str(&format!(
                "  processed={}  states={}/{}",
                vs.processed_insns, vs.peak_states, vs.total_states
            ));
            if let Some(t) = vs.time_usec {
                out.push_str(&format!("  time={t}us"));
            }
            if let Some(ref s) = vs.stack_depth {
                out.push_str(&format!("  stack={s}"));
            }
            out.push('\n');
        }

        out.push_str(&format!("\n{label} --- scheduler log ---\n"));
        if raw {
            out.push_str(&result.scheduler_log);
        } else {
            out.push_str(&collapse_cycles(verifier_log));
        }
    }

    out
}

/// Format an A/B diff table comparing two sets of verifier stats.
pub fn format_verifier_diff(
    label_a: &str,
    stats_a: &[ProgStats],
    label_b: &str,
    stats_b: &[ProgStats],
) -> String {
    let b_map = build_b_map(stats_b);
    let diff_rows = build_diff_rows(stats_a, &b_map);

    let mut out = String::new();
    out.push_str(&format!("\ndelta A/B diff: {label_a} vs {label_b}\n"));
    let mut table = crate::cli::new_table();
    table.set_header(vec!["program", "A", "B", "delta"]);
    for row in &diff_rows {
        table.add_row(vec![
            row.name.clone(),
            row.a.to_string(),
            row.b.to_string(),
            format!("{:+}", row.delta),
        ]);
    }
    out.push_str(&table.to_string());
    out.push('\n');
    out
}

// ---------------------------------------------------------------------------
// Per-cell PASS/FAIL result capture (for the run-summary table)
// ---------------------------------------------------------------------------

/// One `cargo ktstr verifier` cell's outcome. The cell process writes it
/// (via `write_cell_record`) into the directory named by
/// [`crate::KTSTR_VERIFIER_RESULT_DIR_ENV`]; after nextest returns the
/// dispatcher reads them back (via [`read_cell_records`]) and renders the
/// per-(topology × scheduler) summary table. A cell is one
/// (scheduler, kernel, topology): the verifier sweeps each declared
/// scheduler across topologies, so topology IS a result axis — a
/// scheduler can pass on one topology and fail on another.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct VerifierCellRecord {
    /// Declared scheduler name (the `<sched>` cell-name segment).
    pub scheduler: String,
    /// Sanitized kernel label (the `<kernel>` cell-name segment).
    pub kernel: String,
    /// Gauntlet topology preset (the `<preset>` cell-name segment).
    pub topology: String,
    /// Whether the cell passed (exit 0 from the cell handler).
    pub passed: bool,
    /// Per-program stats (program name + its `verified_insns` count)
    /// captured for this cell, copied from the VM run's
    /// [`VerifierVmResult::stats`]. Empty when the cell failed before
    /// producing stats. Drives the per-scheduler `verified_insns` tables
    /// ([`render_instruction_count_tables`], rows = kernel, cols = BPF
    /// program, cell = the count summarized across topologies) that the
    /// dispatcher prints before the PASS/FAIL grid.
    pub stats: Vec<ProgStats>,
}

/// Map a cell's full name to a filesystem-safe record filename: every
/// non-alphanumeric byte becomes `_`. The input is the cell's full name
/// (`verifier/<sched>/<kernel>/<preset>`, unique per cell), so the
/// mapping is unique per cell — a nextest RETRY of the same cell overwrites its
/// own prior record, so the FINAL attempt's outcome wins (a cell that
/// failed then passed on retry records PASS).
fn cell_record_filename(full_name: &str) -> String {
    let mut s: String = full_name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();
    s.push_str(".json");
    s
}

/// Write a cell's PASS/FAIL record into `dir`. Parses `full_name`
/// (`verifier/<sched>/<kernel>/<preset>`); a name that does not fit that
/// shape is skipped (the cell already errored on the malformed name).
/// Best-effort: a write failure is logged and swallowed — the summary
/// table is a convenience over the per-cell nextest output, so a lost
/// record must never turn an otherwise-passing cell into a failure.
///
/// `pub(crate)`: the only writer is the cell handler in
/// `test_support::dispatch` (same crate); the reader side
/// ([`read_cell_records`] / [`render_result_table`]) is `pub` for the
/// `cargo-ktstr` binary crate.
pub(crate) fn write_cell_record(
    dir: &std::path::Path,
    full_name: &str,
    passed: bool,
    stats: &[ProgStats],
) {
    let Some(rest) = full_name.strip_prefix("verifier/") else {
        return;
    };
    let parts: Vec<&str> = rest.splitn(3, '/').collect();
    if parts.len() != 3 {
        return;
    }
    let record = VerifierCellRecord {
        scheduler: parts[0].to_string(),
        kernel: parts[1].to_string(),
        topology: parts[2].to_string(),
        passed,
        stats: stats.to_vec(),
    };
    let path = dir.join(cell_record_filename(full_name));
    match serde_json::to_vec(&record) {
        Ok(bytes) => {
            if let Err(e) = std::fs::write(&path, bytes) {
                eprintln!(
                    "ktstr verifier: warning: could not write result record {}: {e}",
                    path.display(),
                );
            }
        }
        Err(e) => eprintln!("ktstr verifier: warning: serialize result record: {e}"),
    }
}

/// Read every `*.json` cell record under `dir` (non-recursive). A missing
/// dir or an unparseable record is skipped (best-effort). Returns records
/// in filesystem-iteration order; [`render_result_table`] sorts for a
/// deterministic render.
pub fn read_cell_records(dir: &std::path::Path) -> Vec<VerifierCellRecord> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .flatten()
        .filter(|e| {
            e.path()
                .extension()
                .is_some_and(|x| x.eq_ignore_ascii_case("json"))
        })
        .filter_map(|e| std::fs::read(e.path()).ok())
        .filter_map(|bytes| serde_json::from_slice::<VerifierCellRecord>(&bytes).ok())
        .collect()
}

/// Decide the `cargo ktstr verifier` run outcome from nextest's exit
/// success, whether any per-cell records were produced, and the optional
/// `--scheduler` filter.
///
/// The dispatcher runs nextest with `--no-tests=pass`, so a run that
/// selects zero verifier cells exits 0 (success) with empty records
/// rather than nextest's generic "no tests to run" (exit 4). That lets
/// the dispatcher diagnose the empty case itself instead of surfacing a
/// cryptic nextest exit:
/// - `--scheduler <NAME>` set + no records: the name is not a declared
///   scheduler, or no topology preset fits this host for it.
/// - no `--scheduler` + no records: no `declare_scheduler!` is linked into
///   a test binary the sweep sees, or every declared scheduler's
///   constraints rejected all topology presets on this host.
///
/// A genuine build/exec failure still fails nextest (exit non-zero, which
/// `--no-tests=pass` does not mask), surfaced via the `exit_code` arm.
pub fn classify_run_outcome(
    success: bool,
    records_empty: bool,
    scheduler: Option<&str>,
    exit_code: Option<i32>,
) -> Result<(), String> {
    if !success {
        let code = exit_code.map_or_else(|| "signal".to_string(), |c| c.to_string());
        return Err(format!("cargo nextest run exited with {code}"));
    }
    if records_empty {
        return Err(match scheduler {
            Some(name) => format!(
                "--scheduler {name:?}: matched no verifier cell — no declared BPF \
                 scheduler by that name, or no topology preset fits this host for \
                 it. Run `cargo ktstr verifier` with no --scheduler to see the \
                 swept set."
            ),
            None => "no verifier cells ran — no scheduler is declared via \
                 declare_scheduler! in a linked test binary, or every declared \
                 scheduler's constraints rejected all topology presets on this \
                 host."
                .to_string(),
        });
    }
    Ok(())
}

/// Build the `cargo nextest run` argument vector for the verifier sweep.
///
/// Load-bearing tokens:
/// - `--run-ignored all`: verifier cells are emitted ignore-gated, so
///   nextest skips them unless opted in.
/// - `--no-tests pass`: a zero-cell selection exits 0 (not nextest's
///   default exit-4 "no tests to run"), so [`classify_run_outcome`] can
///   emit a targeted diagnostic instead of a cryptic nextest exit.
/// - `-E 'test(/^verifier/) & !test(/^verifier::/)'`: the `verifier/...`
///   cells, excluding the verifier module's own `verifier::tests::*`.
///
/// `nextest_profile`, if set, becomes nextest's `--profile <NAME>`,
/// emitted before `forward` so a forwarded token cannot shadow it.
/// `forward` is the user's trailing cargo/nextest args, appended verbatim.
pub fn build_nextest_args(nextest_profile: Option<&str>, forward: &[String]) -> Vec<String> {
    let mut args = vec![
        "nextest".to_string(),
        "run".to_string(),
        "--run-ignored".to_string(),
        "all".to_string(),
        "--no-tests".to_string(),
        "pass".to_string(),
        "-E".to_string(),
        "test(/^verifier/) & !test(/^verifier::/)".to_string(),
    ];
    if let Some(np) = nextest_profile {
        args.push("--profile".to_string());
        args.push(np.to_string());
    }
    args.extend(forward.iter().cloned());
    args
}

/// Render the per-cell records into a summary grid: one row per topology
/// preset, one column per scheduler, aggregating across kernels. Each
/// cell is:
/// - ✅ every kernel that ran this (topology, scheduler) passed,
/// - ❌ every kernel that ran it failed,
/// - 🇽 mixed — at least one kernel passed AND at least one failed,
/// - `-` no kernel ran this (topology, scheduler) (e.g. the scheduler's
///   constraints rejected the preset).
///
/// After the grid, the specific failing `(scheduler, kernel, topology)`
/// combinations are listed so a ❌ or 🇽 cell can be drilled to the exact
/// kernel(s) that failed. Returns `None` for an empty record set (the
/// caller prints nothing).
///
/// Rows, columns, and the failing list are BTreeSet-sorted so the same
/// run renders the same output (shell-pipeline stable). The header line
/// carries a ✅/❌/🇽 tally counting grid cells.
pub fn render_result_table(records: &[VerifierCellRecord]) -> Option<String> {
    if records.is_empty() {
        return None;
    }
    use std::collections::{BTreeMap, BTreeSet};
    let mut schedulers: BTreeSet<String> = BTreeSet::new(); // columns
    let mut rows: BTreeSet<String> = BTreeSet::new(); // topology presets
    // (topology, scheduler) -> (passes, fails) aggregated across kernels.
    let mut agg: BTreeMap<(String, String), (u32, u32)> = BTreeMap::new();
    // Distinct failing (scheduler, kernel, topology) combinations.
    let mut failing: BTreeSet<(String, String, String)> = BTreeSet::new();
    for r in records {
        schedulers.insert(r.scheduler.clone());
        rows.insert(r.topology.clone());
        let counts = agg
            .entry((r.topology.clone(), r.scheduler.clone()))
            .or_insert((0, 0));
        if r.passed {
            counts.0 += 1;
        } else {
            counts.1 += 1;
            failing.insert((r.scheduler.clone(), r.kernel.clone(), r.topology.clone()));
        }
    }

    let (mut n_pass, mut n_fail, mut n_mixed) = (0usize, 0usize, 0usize);
    let mut table = crate::cli::new_table();
    let mut header: Vec<String> = vec!["topology".to_string()];
    for sched in &schedulers {
        header.push(sched.clone());
    }
    table.set_header(header);
    for topo in &rows {
        let mut line: Vec<String> = vec![topo.clone()];
        for sched in &schedulers {
            // An entry only exists with >= 1 record, so (_, 0) means all
            // passed, (0, _) means all failed, and both-nonzero is mixed.
            let text = match agg.get(&(topo.clone(), sched.clone())) {
                None => "-",
                Some((_, 0)) => {
                    n_pass += 1;
                    ""
                }
                Some((0, _)) => {
                    n_fail += 1;
                    ""
                }
                Some(_) => {
                    n_mixed += 1;
                    "🇽"
                }
            };
            line.push(text.to_string());
        }
        table.add_row(line);
    }

    let mut out = format!("\nverifier summary: {n_pass}{n_fail}{n_mixed} 🇽\n{table}\n");
    if !failing.is_empty() {
        out.push_str("\nfailing combinations (scheduler / kernel / topology):\n");
        for (sched, kernel, topo) in &failing {
            out.push_str(&format!("  {sched} / {kernel} / {topo}\n"));
        }
    }
    Some(out)
}

/// Render one `verified_insns` table per declared scheduler. Within each
/// scheduler's section: rows = kernel version, columns = BPF program, and
/// each cell is that program's `verified_insns` for the (scheduler,
/// kernel) summarized ACROSS the topologies that ran it — a single number
/// when topology-invariant, `lo..hi` when it varies (`-` when that program
/// reported no stats on that kernel).
///
/// `verified_insns` is the verifier's PROCESSED-instruction count
/// (`env->insn_processed`) — fixed per load, but NOT topology-invariant
/// (a scheduler whose verification path depends on topology-derived
/// `.rodata`, e.g. `nr_cpus`, processes a different count per topology).
/// So topology is folded into the cell as a range rather than shown as its
/// own (usually all-identical) axis; the axes it genuinely varies on — BPF
/// program (x) and kernel version (y) — are the table axes, sectioned per
/// declared scheduler. Identical-binary declarations are sectioned
/// separately on purpose (they are run separately). Returns `None` when no
/// record carries any per-program stats (the caller prints nothing).
///
/// Schedulers, kernels, and programs are BTree-sorted so the same run
/// renders the same output (shell-pipeline stable). The range drops which
/// topology produced which count; a per-topology breakdown is a separate
/// detailed view, not this summary.
pub fn render_instruction_count_tables(records: &[VerifierCellRecord]) -> Option<String> {
    use std::collections::{BTreeMap, BTreeSet};
    // scheduler -> kernel -> program -> (min, max) verified_insns across
    // the topologies that ran it. Topology is folded into the (min, max)
    // range: a flat scheduler has min == max (one number), a
    // topology-sensitive one has min < max (`lo..hi`).
    type VerifiedInsnSpans = BTreeMap<String, BTreeMap<String, BTreeMap<String, (u32, u32)>>>;
    let mut by_sched: VerifiedInsnSpans = BTreeMap::new();
    // scheduler -> the union of program names it reported (the columns).
    let mut sched_progs: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for r in records {
        for s in &r.stats {
            let span = by_sched
                .entry(r.scheduler.clone())
                .or_default()
                .entry(r.kernel.clone())
                .or_default()
                .entry(s.name.clone())
                .or_insert((s.verified_insns, s.verified_insns));
            span.0 = span.0.min(s.verified_insns);
            span.1 = span.1.max(s.verified_insns);
            sched_progs
                .entry(r.scheduler.clone())
                .or_default()
                .insert(s.name.clone());
        }
    }
    if by_sched.is_empty() {
        return None;
    }

    let mut out = String::from(
        "\nverifier verified_insns (per scheduler; rows: kernel, cols: BPF program, \
         cell: range across topologies):\n",
    );
    for (sched, kernels) in &by_sched {
        let progs = &sched_progs[sched];
        let mut table = crate::cli::new_table();
        let mut header: Vec<String> = vec!["kernel".to_string()];
        for p in progs {
            header.push(p.clone());
        }
        table.set_header(header);
        for (kernel, prog_map) in kernels {
            let mut line: Vec<String> = vec![kernel.clone()];
            for p in progs {
                let text = match prog_map.get(p) {
                    Some((lo, hi)) if lo == hi => lo.to_string(),
                    Some((lo, hi)) => format!("{lo}..{hi}"),
                    None => "-".to_string(),
                };
                line.push(text);
            }
            table.add_row(line);
        }
        out.push_str(&format!("\n{sched}:\n{table}\n"));
    }
    Some(out)
}

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

    // -----------------------------------------------------------------------
    // per-cell result capture + summary table
    // -----------------------------------------------------------------------

    /// A malformed cell name is skipped (no record); a well-formed
    /// 3-segment cell records (scheduler/kernel/topology); and a nextest
    /// RETRY of the same cell overwrites its own prior record so the
    /// FINAL outcome wins (fail-then-pass -> PASS).
    #[test]
    fn cell_record_write_read_roundtrip_and_retry_overwrites() {
        let dir = std::env::temp_dir().join(format!("ktstr-verif-rec-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("mk temp dir");
        // Malformed: no verifier/ prefix, and a 2-segment name (no
        // <preset> after the kernel) — both skipped.
        write_cell_record(&dir, "not_a_cell", true, &[]);
        write_cell_record(&dir, "verifier/only/two", true, &[]);
        // Well-formed cell: fail, then a retry passes -> overwrites.
        let name = "verifier/scx_a/kernel_6_14/tiny-1llc";
        write_cell_record(&dir, name, false, &[]);
        // The retry passes and carries per-program verified_insns, so the
        // final record has both the PASS outcome and the stats.
        let stats = [
            ProgStats {
                name: "ktstr_dispatch".into(),
                verified_insns: 321,
            },
            ProgStats {
                name: "ktstr_enqueue".into(),
                verified_insns: 123,
            },
        ];
        write_cell_record(&dir, name, true, &stats);
        let recs = read_cell_records(&dir);
        assert_eq!(
            recs.len(),
            1,
            "malformed names skipped; the retry overwrote its own record (one file): {recs:?}",
        );
        assert_eq!(recs[0].scheduler, "scx_a");
        assert_eq!(recs[0].kernel, "kernel_6_14");
        assert_eq!(recs[0].topology, "tiny-1llc");
        assert!(
            recs[0].passed,
            "final retry outcome (PASS) wins over the earlier FAIL"
        );
        // Per-program verified_insns survive the JSON roundtrip and reflect
        // the final (retry) write, not the earlier stat-less fail.
        assert_eq!(recs[0].stats, stats, "stats roundtrip via serde");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The summary grid aggregates across kernels per (topology,
    /// scheduler): all-pass -> ✅, all-fail -> ❌, with a ✅/❌/🇽 tally.
    /// Failing (scheduler, kernel, topology) combinations are listed after
    /// the grid; an empty record set renders nothing.
    #[test]
    fn render_result_table_matrix_tally_and_empty() {
        let recs = vec![
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "tiny-1llc".into(),
                passed: true,
                stats: vec![],
            },
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "large-4llc".into(),
                passed: false,
                stats: vec![],
            },
        ];
        let out = render_result_table(&recs).expect("non-empty records -> Some");
        assert!(
            out.contains("verifier summary: 1 ✅  1 ❌  0 🇽"),
            "tally: {out}"
        );
        // Columns are scheduler-only (kernels fold into the cell), so no
        // `scheduler @ kernel` labeling appears.
        assert!(
            out.contains("scx_a") && !out.contains(" @ "),
            "columns: {out}"
        );
        // The emoji must render in the GRID CELLS, not merely the tally
        // line: locate each topology's row and assert its cell glyph
        // (neither topology name appears on the `verifier summary:` line).
        let pass_row = out
            .lines()
            .find(|l| l.contains("tiny-1llc"))
            .expect("tiny-1llc row present");
        assert!(
            pass_row.contains(''),
            "all-pass cell renders ✅ in the grid row: {pass_row}"
        );
        let fail_row = out
            .lines()
            .find(|l| l.contains("large-4llc"))
            .expect("large-4llc row present");
        assert!(
            fail_row.contains(''),
            "all-fail cell renders ❌ in the grid row: {fail_row}"
        );
        // The single failure is listed after the grid.
        assert!(
            out.contains("failing combinations (scheduler / kernel / topology):")
                && out.contains("scx_a / kernel_6_14 / large-4llc"),
            "failing combinations listed: {out}"
        );
        assert!(render_result_table(&[]).is_none(), "empty -> None");
    }

    /// A (topology, scheduler) where one kernel passes and another fails
    /// renders 🇽 (mixed); an all-pass (topology, scheduler) across kernels
    /// renders ✅. Only the failing kernel appears in the failing list.
    #[test]
    fn render_result_table_mixed_kernels_blue_x() {
        let recs = vec![
            // tiny-1llc / scx_a: 6_14 passes, 6_15 fails -> mixed -> 🇽.
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "tiny-1llc".into(),
                passed: true,
                stats: vec![],
            },
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_15".into(),
                topology: "tiny-1llc".into(),
                passed: false,
                stats: vec![],
            },
            // smt-2llc / scx_a: both kernels pass -> ✅.
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "smt-2llc".into(),
                passed: true,
                stats: vec![],
            },
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_15".into(),
                topology: "smt-2llc".into(),
                passed: true,
                stats: vec![],
            },
        ];
        let out = render_result_table(&recs).expect("Some");
        assert!(
            out.contains("verifier summary: 1 ✅  0 ❌  1 🇽"),
            "tally counts one all-pass + one mixed cell: {out}"
        );
        let mixed_row = out
            .lines()
            .find(|l| l.contains("tiny-1llc"))
            .expect("tiny-1llc row present");
        assert!(
            mixed_row.contains('🇽'),
            "mixed (some pass, some fail) cell renders 🇽: {mixed_row}"
        );
        let pass_row = out
            .lines()
            .find(|l| l.contains("smt-2llc"))
            .expect("smt-2llc row present");
        assert!(
            pass_row.contains(''),
            "all-kernels-pass cell renders ✅: {pass_row}"
        );
        // Only the failing kernel is listed after the grid.
        assert!(
            out.contains("scx_a / kernel_6_15 / tiny-1llc"),
            "the failing kernel is listed: {out}"
        );
        assert!(
            !out.contains("kernel_6_14 / tiny-1llc"),
            "the passing kernel on the mixed topology is not listed: {out}"
        );
        assert!(
            !out.contains("/ smt-2llc"),
            "the all-pass topology contributes no failing combination: {out}"
        );
    }

    /// Per-scheduler verified_insns tables: one section per declared
    /// scheduler; within it rows = kernel version, columns = BPF program,
    /// each cell that program's verified_insns across the topologies that
    /// ran it — a single number when topology-invariant, `lo..hi` when it
    /// varies. A (kernel, program) that reported no stats shows `-`; an
    /// empty record set renders nothing.
    #[test]
    fn instruction_count_tables_per_scheduler_kernel_program_range() {
        let recs = vec![
            // scx_a / kernel_6_14 on two topologies with IDENTICAL counts
            // -> the cell collapses to a single number (topology-flat).
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "tiny".into(),
                passed: true,
                stats: vec![
                    ProgStats {
                        name: "ktstr_dispatch".into(),
                        verified_insns: 128,
                    },
                    ProgStats {
                        name: "ktstr_enqueue".into(),
                        verified_insns: 64,
                    },
                ],
            },
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_14".into(),
                topology: "large".into(),
                passed: true,
                stats: vec![
                    ProgStats {
                        name: "ktstr_dispatch".into(),
                        verified_insns: 128,
                    },
                    ProgStats {
                        name: "ktstr_enqueue".into(),
                        verified_insns: 64,
                    },
                ],
            },
            // scx_a / kernel_6_15: ktstr_dispatch DIFFERS across topologies
            // -> `lo..hi` range; ktstr_enqueue is absent on this kernel
            // -> `-` in that column's kernel_6_15 row.
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_15".into(),
                topology: "tiny".into(),
                passed: true,
                stats: vec![ProgStats {
                    name: "ktstr_dispatch".into(),
                    verified_insns: 130,
                }],
            },
            VerifierCellRecord {
                scheduler: "scx_a".into(),
                kernel: "kernel_6_15".into(),
                topology: "large".into(),
                passed: true,
                stats: vec![ProgStats {
                    name: "ktstr_dispatch".into(),
                    verified_insns: 150,
                }],
            },
            // scx_b: a separate section (its own declaration).
            VerifierCellRecord {
                scheduler: "scx_b".into(),
                kernel: "kernel_6_14".into(),
                topology: "tiny".into(),
                passed: true,
                stats: vec![ProgStats {
                    name: "ktstr_dispatch".into(),
                    verified_insns: 200,
                }],
            },
        ];
        let out = render_instruction_count_tables(&recs).expect("stats present -> Some");
        // One section per declared scheduler.
        assert!(
            out.contains("scx_a:") && out.contains("scx_b:"),
            "one section per declared scheduler: {out}"
        );
        // Columns = BPF programs; rows = kernel version.
        assert!(
            out.contains("ktstr_dispatch") && out.contains("ktstr_enqueue"),
            "BPF-program columns: {out}"
        );
        assert!(
            out.contains("kernel_6_14") && out.contains("kernel_6_15"),
            "kernel-version rows: {out}"
        );
        // Topology folded into the cell as a range: flat -> "128",
        // varies across topologies -> "130..150".
        assert!(
            out.contains("128"),
            "topology-flat cell is a single number: {out}"
        );
        assert!(
            out.contains("130..150"),
            "topology-varying cell is a lo..hi range: {out}"
        );
        assert!(
            out.contains("64") && out.contains("200"),
            "other counts render: {out}"
        );
        // ktstr_enqueue reported no stats on kernel_6_15 -> `-`.
        assert!(
            out.contains('-'),
            "a (kernel, program) with no stats renders '-': {out}"
        );
        // Topology is NOT a table axis (folded into the range), so no
        // topology label appears in the output.
        assert!(
            !out.contains("tiny") && !out.contains("large"),
            "topology is not a table axis: {out}"
        );

        // No record carries stats -> nothing to render.
        let bare = vec![VerifierCellRecord {
            scheduler: "scx_a".into(),
            kernel: "kernel_6_14".into(),
            topology: "tiny".into(),
            passed: false,
            stats: vec![],
        }];
        assert!(
            render_instruction_count_tables(&bare).is_none(),
            "no stats -> None"
        );
    }

    /// classify_run_outcome: a build/exec failure surfaces nextest's exit;
    /// a successful-but-empty run is diagnosed by the dispatcher (friendly
    /// no-such-scheduler message when --scheduler was set, no-cells-ran
    /// message otherwise); a successful run with records is Ok.
    #[test]
    fn classify_run_outcome_cases() {
        // Records present + success -> Ok regardless of --scheduler.
        assert!(classify_run_outcome(true, false, None, Some(0)).is_ok());
        assert!(classify_run_outcome(true, false, Some("ktstr_sched"), Some(0)).is_ok());

        // Success + empty + --scheduler -> friendly "no such scheduler".
        // Reachable ONLY because --no-tests=pass turns a 0-cell match into
        // exit 0; under the old `auto` default a 0-match exited 4 -> the
        // failure arm, leaving this message dead.
        let e = classify_run_outcome(true, true, Some("nope"), Some(0)).unwrap_err();
        assert!(
            e.contains("--scheduler \"nope\"") && e.contains("matched no verifier cell"),
            "scheduler-empty diagnostic: {e}"
        );

        // Success + empty + no --scheduler -> "no cells ran" diagnosis
        // (must NOT silently succeed under --no-tests=pass).
        let e = classify_run_outcome(true, true, None, Some(0)).unwrap_err();
        assert!(
            e.contains("no verifier cells ran") && e.contains("declare_scheduler!"),
            "no-cells diagnostic: {e}"
        );

        // Failure surfaces nextest's exit code; a signal (no code) renders
        // as "signal".
        assert_eq!(
            classify_run_outcome(false, true, None, Some(4)).unwrap_err(),
            "cargo nextest run exited with 4"
        );
        assert_eq!(
            classify_run_outcome(false, false, Some("x"), None).unwrap_err(),
            "cargo nextest run exited with signal"
        );
    }

    /// build_nextest_args carries the flags that make the friendly
    /// diagnostic reachable: `--run-ignored all` (cells are ignore-gated)
    /// and `--no-tests pass` (a 0-cell selection exits 0 so
    /// classify_run_outcome runs instead of nextest's exit-4). Guards
    /// against a future edit silently dropping either, plus the
    /// profile-before-forwarded-args ordering.
    #[test]
    fn build_nextest_args_carries_load_bearing_flags() {
        let args = build_nextest_args(None, &[]);
        let ri = args
            .iter()
            .position(|a| a == "--run-ignored")
            .expect("--run-ignored present");
        assert_eq!(args[ri + 1], "all", "--run-ignored all");
        let nt = args
            .iter()
            .position(|a| a == "--no-tests")
            .expect("--no-tests present");
        assert_eq!(args[nt + 1], "pass", "--no-tests pass");
        assert!(
            args.iter()
                .any(|a| a == "test(/^verifier/) & !test(/^verifier::/)"),
            "verifier-cell filter present: {args:?}"
        );

        // --profile <NAME> is emitted before forwarded args so a forwarded
        // token cannot shadow it.
        let args = build_nextest_args(Some("ci"), &["--features".to_string(), "wprof".to_string()]);
        let p = args
            .iter()
            .position(|a| a == "--profile")
            .expect("--profile present");
        assert_eq!(args[p + 1], "ci");
        let f = args
            .iter()
            .position(|a| a == "--features")
            .expect("forwarded --features present");
        assert!(p < f, "profile emitted before forwarded args: {args:?}");
    }

    // -----------------------------------------------------------------------
    // scheduler attach verdict
    // -----------------------------------------------------------------------

    /// attach_outcome_from_messages positive-confirmation rule:
    /// Died > NotAttached > PayloadStarting(=Attached) > Unconfirmed.
    /// Absence of a positive PayloadStarting frame is Unconfirmed (FAIL),
    /// NOT a blind pass — this is what catches an early guest panic that
    /// reboots emitting no frame. Corrupt / empty / non-LIFECYCLE /
    /// unknown frames are skipped.
    #[test]
    fn attach_outcome_from_lifecycle_frames() {
        use crate::vmm::host_comms::BulkDrainResult;
        use crate::vmm::wire::{LifecyclePhase, MSG_TYPE_LIFECYCLE, ShmEntry};

        let frame = |phase: LifecyclePhase, reason: &str| -> ShmEntry {
            let mut payload = vec![phase.wire_value()];
            payload.extend_from_slice(reason.as_bytes());
            ShmEntry {
                msg_type: MSG_TYPE_LIFECYCLE,
                payload,
                crc_ok: true,
            }
        };
        let drain = |entries: Vec<ShmEntry>| BulkDrainResult { entries };

        // No frames at all -> Unconfirmed (guest vanished before any
        // phase; e.g. an early kernel panic that reboots via panic=-1).
        assert_eq!(
            attach_outcome_from_messages(None),
            AttachOutcome::Unconfirmed,
        );

        // Reached init but NOT the dispatch phase -> Unconfirmed.
        let init_only = drain(vec![frame(LifecyclePhase::InitStarted, "")]);
        assert_eq!(
            attach_outcome_from_messages(Some(&init_only)),
            AttachOutcome::Unconfirmed,
        );

        // Reached the dispatch phase (PayloadStarting), no failure -> Attached.
        let progress = drain(vec![
            frame(LifecyclePhase::InitStarted, ""),
            frame(LifecyclePhase::PayloadStarting, ""),
        ]);
        assert_eq!(
            attach_outcome_from_messages(Some(&progress)),
            AttachOutcome::Attached,
        );

        // SchedulerNotAttached carries its reason suffix verbatim.
        let not_attached = drain(vec![frame(LifecyclePhase::SchedulerNotAttached, "timeout")]);
        assert_eq!(
            attach_outcome_from_messages(Some(&not_attached)),
            AttachOutcome::NotAttached("timeout".to_string()),
        );

        // A failure frame wins over a (defensively) co-present
        // PayloadStarting.
        let fail_beats_positive = drain(vec![
            frame(LifecyclePhase::PayloadStarting, ""),
            frame(LifecyclePhase::SchedulerNotAttached, "sysfs absent"),
        ]);
        assert_eq!(
            attach_outcome_from_messages(Some(&fail_beats_positive)),
            AttachOutcome::NotAttached("sysfs absent".to_string()),
        );

        // SchedulerDied wins over NotAttached, in BOTH orders.
        for entries in [
            vec![
                frame(LifecyclePhase::SchedulerNotAttached, "timeout"),
                frame(LifecyclePhase::SchedulerDied, ""),
            ],
            vec![
                frame(LifecyclePhase::SchedulerDied, ""),
                frame(LifecyclePhase::SchedulerNotAttached, "timeout"),
            ],
        ] {
            let d = drain(entries);
            assert_eq!(attach_outcome_from_messages(Some(&d)), AttachOutcome::Died);
        }

        // Died wins even over a PayloadStarting.
        let died_beats_positive = drain(vec![
            frame(LifecyclePhase::PayloadStarting, ""),
            frame(LifecyclePhase::SchedulerDied, ""),
        ]);
        assert_eq!(
            attach_outcome_from_messages(Some(&died_beats_positive)),
            AttachOutcome::Died,
        );

        // Skipped frames (corrupt crc / empty payload / non-LIFECYCLE /
        // unknown discriminant) must NOT suppress a real PayloadStarting:
        // pairing each with a valid PayloadStarting must still resolve
        // Attached — proving the frame was skipped, not acted on (a
        // corrupt/non-LIFECYCLE Died byte would otherwise force Died).
        let corrupt_died = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE,
            payload: vec![LifecyclePhase::SchedulerDied.wire_value()],
            crc_ok: false,
        };
        let empty = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE,
            payload: Vec::new(),
            crc_ok: true,
        };
        let non_lifecycle_died = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE + 1,
            payload: vec![LifecyclePhase::SchedulerDied.wire_value()],
            crc_ok: true,
        };
        let unknown_phase = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE,
            payload: vec![250],
            crc_ok: true,
        };
        for skipped in [corrupt_died, empty, non_lifecycle_died, unknown_phase] {
            let d = drain(vec![skipped, frame(LifecyclePhase::PayloadStarting, "")]);
            assert_eq!(
                attach_outcome_from_messages(Some(&d)),
                AttachOutcome::Attached,
                "a skipped frame must not suppress a valid PayloadStarting",
            );
        }
    }

    /// dispatch_confirmed_from_messages: true only when a crc-ok,
    /// non-empty WorkloadDispatched frame is present; false for None / no
    /// such frame / corrupt / empty / non-LIFECYCLE.
    #[test]
    fn dispatch_confirmed_from_lifecycle_frames() {
        use crate::vmm::host_comms::BulkDrainResult;
        use crate::vmm::wire::{LifecyclePhase, MSG_TYPE_LIFECYCLE, ShmEntry};

        let frame = |phase: LifecyclePhase| -> ShmEntry {
            ShmEntry {
                msg_type: MSG_TYPE_LIFECYCLE,
                payload: vec![phase.wire_value()],
                crc_ok: true,
            }
        };
        let drain = |entries: Vec<ShmEntry>| BulkDrainResult { entries };

        // No frames at all -> false.
        assert!(!dispatch_confirmed_from_messages(None));

        // PayloadStarting but no WorkloadDispatched -> false (attached,
        // never dispatched).
        let attached_only = drain(vec![frame(LifecyclePhase::PayloadStarting)]);
        assert!(!dispatch_confirmed_from_messages(Some(&attached_only)));

        // WorkloadDispatched present -> true.
        let dispatched = drain(vec![
            frame(LifecyclePhase::PayloadStarting),
            frame(LifecyclePhase::WorkloadDispatched),
        ]);
        assert!(dispatch_confirmed_from_messages(Some(&dispatched)));

        // Corrupt crc / empty payload / non-LIFECYCLE WorkloadDispatched
        // frames are skipped and must not confirm dispatch.
        let corrupt = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE,
            payload: vec![LifecyclePhase::WorkloadDispatched.wire_value()],
            crc_ok: false,
        };
        let empty = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE,
            payload: Vec::new(),
            crc_ok: true,
        };
        let non_lifecycle = ShmEntry {
            msg_type: MSG_TYPE_LIFECYCLE + 1,
            payload: vec![LifecyclePhase::WorkloadDispatched.wire_value()],
            crc_ok: true,
        };
        for skipped in [corrupt, empty, non_lifecycle] {
            let d = drain(vec![skipped]);
            assert!(
                !dispatch_confirmed_from_messages(Some(&d)),
                "a corrupt/empty/non-LIFECYCLE frame must not confirm dispatch",
            );
        }
    }

    /// VerifierVmResult::cell_verdict gate order + messages: timed_out >
    /// attach failure > dispatch failure > PASS.
    #[test]
    fn cell_verdict_gate_order_and_messages() {
        let base = |attach: AttachOutcome, dispatched: bool, timed_out: bool| VerifierVmResult {
            stats: Vec::new(),
            scheduler_log: String::new(),
            attach,
            dispatched,
            timed_out,
        };

        // Verified + attached + dispatched, no hang -> PASS.
        assert_eq!(
            base(AttachOutcome::Attached, true, false).cell_verdict(),
            Ok(()),
        );

        // Attached but 0-dispatch -> FAIL naming the dispatch gate.
        let no_dispatch = base(AttachOutcome::Attached, false, false).cell_verdict();
        assert!(
            no_dispatch
                .as_ref()
                .unwrap_err()
                .contains("did not dispatch"),
            "dispatch gate must name the failure: {no_dispatch:?}",
        );

        // Attach failure -> FAIL naming attach, even if dispatched is
        // (defensively) true.
        let attach_fail = base(AttachOutcome::Died, true, false).cell_verdict();
        assert!(
            attach_fail
                .as_ref()
                .unwrap_err()
                .contains("did not turn on"),
            "attach gate must win over dispatch: {attach_fail:?}",
        );

        // timed_out wins over everything, even a clean attach + dispatch.
        let hung = base(AttachOutcome::Attached, true, true).cell_verdict();
        assert!(
            hung.as_ref().unwrap_err().contains("timed out"),
            "timed_out must win: {hung:?}",
        );

        // Attach failure outranks a co-present dispatch failure (root
        // cause reported first).
        let both = base(AttachOutcome::Died, false, false).cell_verdict();
        assert!(
            both.as_ref().unwrap_err().contains("did not turn on"),
            "attach failure reported before dispatch failure: {both:?}",
        );
    }

    /// AttachOutcome::failure_reason surfaces (None when attached, the
    /// distinct Died / NotAttached reasons otherwise).
    #[test]
    fn attach_outcome_failure_reason() {
        assert_eq!(AttachOutcome::Attached.failure_reason(), None);
        assert!(
            AttachOutcome::Died
                .failure_reason()
                .unwrap()
                .contains("exited during BPF load"),
        );
        assert!(
            AttachOutcome::NotAttached(String::new())
                .failure_reason()
                .unwrap()
                .contains("never reached sched_ext 'enabled'"),
        );
        assert_eq!(
            AttachOutcome::NotAttached("sysfs absent".to_string()).failure_reason(),
            Some("scheduler never reached sched_ext 'enabled': sysfs absent".to_string()),
        );
        assert!(
            AttachOutcome::Unconfirmed
                .failure_reason()
                .unwrap()
                .contains("attach unconfirmed"),
        );
    }

    /// A timed-out run shows UNKNOWN (not attached), overriding the
    /// attach line — catches a post-attach teardown hang (the frame scan
    /// + Unconfirmed already handle a guest that vanishes before attach).
    #[test]
    fn format_verifier_output_timed_out_shows_unknown() {
        let result = VerifierVmResult {
            stats: Vec::new(),
            scheduler_log: String::new(),
            attach: AttachOutcome::Attached,
            dispatched: false,
            timed_out: true,
        };
        let out = format_verifier_output("verifier", &result, false);
        assert!(
            out.contains("scheduler: UNKNOWN — VM timed out"),
            "timed-out run must show UNKNOWN: {out}",
        );
        assert!(
            !out.contains("scheduler: attached"),
            "timed-out run must not claim attached: {out}",
        );
    }

    /// An attached-but-not-dispatched run shows the attach line AND a
    /// "dispatch: NOT CONFIRMED" line — the signal that the scheduler
    /// turned on but never dispatched the injected workload.
    /// Guards the `format_verifier_output` dispatched==false render branch,
    /// which the snapshot tests (dispatched==true / Died) do not reach.
    #[test]
    fn format_verifier_output_attached_not_dispatched_shows_not_confirmed() {
        let result = VerifierVmResult {
            stats: Vec::new(),
            scheduler_log: String::new(),
            attach: AttachOutcome::Attached,
            dispatched: false,
            timed_out: false,
        };
        let out = format_verifier_output("verifier", &result, false);
        assert!(
            out.contains("scheduler: attached"),
            "attached run must show the attach line: {out}",
        );
        assert!(
            out.contains("dispatch: NOT CONFIRMED"),
            "attached-but-not-dispatched must render the NOT CONFIRMED signal: {out}",
        );
    }

    // -----------------------------------------------------------------------
    // parse_verifier_stats
    // -----------------------------------------------------------------------

    #[test]
    fn parse_verifier_stats_full_line() {
        let log = "processed 1234 insns (limit 1000000) max_states_per_insn 5 total_states 200 peak_states 50 mark_read 10\nverification time 42 usec\nstack depth 32+0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 1234);
        assert_eq!(vs.total_states, 200);
        assert_eq!(vs.peak_states, 50);
        assert_eq!(vs.time_usec, Some(42));
        assert_eq!(vs.stack_depth.as_deref(), Some("32+0"));
    }

    #[test]
    fn parse_verifier_stats_insns_only() {
        let log = "processed 500 insns (limit 1000000) max_states_per_insn 1 total_states 10 peak_states 3 mark_read 0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 500);
        assert_eq!(vs.total_states, 10);
        assert_eq!(vs.peak_states, 3);
        assert!(vs.time_usec.is_none());
        assert!(vs.stack_depth.is_none());
    }

    #[test]
    fn parse_verifier_stats_empty() {
        let vs = parse_verifier_stats("");
        assert_eq!(vs.processed_insns, 0);
        assert_eq!(vs.total_states, 0);
        assert_eq!(vs.peak_states, 0);
        assert!(vs.time_usec.is_none());
        assert!(vs.stack_depth.is_none());
    }

    #[test]
    fn parse_verifier_stats_garbage_lines() {
        let log = "some random output\nnot a stats line\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 0);
        assert_eq!(vs.total_states, 0);
        assert!(vs.time_usec.is_none());
    }

    #[test]
    fn parse_verifier_stats_time_without_insns() {
        let log = "verification time 100 usec\nstack depth 64\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 0);
        assert_eq!(vs.time_usec, Some(100));
        assert_eq!(vs.stack_depth.as_deref(), Some("64"));
    }

    #[test]
    fn parse_verifier_stats_multi_subprogram_stack() {
        let log = "processed 42 insns (limit 1000000) max_states_per_insn 1 total_states 5 peak_states 2 mark_read 0\nstack depth 32+16+8\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 42);
        assert_eq!(vs.stack_depth.as_deref(), Some("32+16+8"));
    }

    #[test]
    fn parse_verifier_stats_noise_between_lines() {
        let log = "\
libbpf: loading something
processed 999 insns (limit 1000000) max_states_per_insn 3 total_states 77 peak_states 20 mark_read 5
libbpf: prog 'dispatch': attached
verification time 7 usec
stack depth 48+0
";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 999);
        assert_eq!(vs.total_states, 77);
        assert_eq!(vs.peak_states, 20);
        assert_eq!(vs.time_usec, Some(7));
        assert_eq!(vs.stack_depth.as_deref(), Some("48+0"));
    }

    #[test]
    fn parse_verifier_stats_partial_insns_line() {
        let log = "processed 123\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 123);
        assert_eq!(vs.total_states, 0);
        assert_eq!(vs.peak_states, 0);
    }

    #[test]
    fn parse_verifier_stats_only_stack_depth() {
        let log = "stack depth 128\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.stack_depth.as_deref(), Some("128"));
        assert_eq!(vs.processed_insns, 0);
    }

    #[test]
    fn parse_verifier_stats_zero_insns() {
        let log = "processed 0 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 0);
        assert_eq!(vs.total_states, 0);
        assert_eq!(vs.peak_states, 0);
    }

    #[test]
    fn parse_verifier_stats_large_values() {
        let log = "processed 999999 insns (limit 1000000) max_states_per_insn 100 total_states 50000 peak_states 12345 mark_read 9999\nverification time 123456 usec\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 999999);
        assert_eq!(vs.total_states, 50000);
        assert_eq!(vs.peak_states, 12345);
        assert_eq!(vs.time_usec, Some(123456));
    }

    #[test]
    fn parse_verifier_stats_stack_depth_single() {
        let log = "stack depth 64\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.stack_depth.as_deref(), Some("64"));
    }

    #[test]
    fn parse_verifier_stats_stack_depth_many_subprograms() {
        let log = "stack depth 32+16+8+0+0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.stack_depth.as_deref(), Some("32+16+8+0+0"));
    }

    #[test]
    fn parse_verifier_stats_multiple_processed_lines_takes_last() {
        let log = "processed 100 insns (limit 1000000) max_states_per_insn 1 total_states 5 peak_states 2 mark_read 0\nprocessed 200 insns (limit 1000000) max_states_per_insn 2 total_states 10 peak_states 4 mark_read 0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 200);
        assert_eq!(vs.total_states, 10);
    }

    #[test]
    fn parse_verifier_stats_complexity_error_with_stats() {
        let log = "\
func#0 @0
0: R1=ctx() R10=fp0
1: (bf) r6 = r1                       ; R1=ctx() R6_w=ctx()
back-edge from insn 42 to 10
BPF program is too complex
processed 131071 insns (limit 131072) max_states_per_insn 12 total_states 9999 peak_states 5000 mark_read 800
verification time 250000 usec
stack depth 96+32
";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 131071);
        assert_eq!(vs.total_states, 9999);
        assert_eq!(vs.peak_states, 5000);
        assert_eq!(vs.time_usec, Some(250000));
        assert_eq!(vs.stack_depth.as_deref(), Some("96+32"));
    }

    #[test]
    fn parse_verifier_stats_complexity_error_no_stats() {
        let log = "\
func#0 @0
0: R1=ctx() R10=fp0
R1 type=ctx expected=fp
";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 0);
        assert_eq!(vs.total_states, 0);
        assert!(vs.time_usec.is_none());
        assert!(vs.stack_depth.is_none());
    }

    #[test]
    fn parse_verifier_stats_loop_warning_with_stats() {
        let log = "\
infinite loop detected at insn 15
back-edge from insn 30 to 15
processed 500 insns (limit 1000000) max_states_per_insn 3 total_states 40 peak_states 15 mark_read 5
verification time 100 usec
";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 500);
        assert_eq!(vs.total_states, 40);
        assert_eq!(vs.peak_states, 15);
        assert_eq!(vs.time_usec, Some(100));
    }

    #[test]
    fn parse_verifier_stats_processed_no_number() {
        let log = "processed\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 0);
    }

    #[test]
    fn parse_verifier_stats_keyword_at_end_no_value() {
        let log = "processed 100 insns (limit 1000000) max_states_per_insn 1 total_states\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 100);
        assert_eq!(vs.total_states, 0);
    }

    #[test]
    fn parse_verifier_stats_non_numeric_values() {
        let log = "processed 100 insns (limit 1000000) max_states_per_insn 1 total_states abc peak_states xyz mark_read 0\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 100);
        assert_eq!(vs.total_states, 0);
        assert_eq!(vs.peak_states, 0);
    }

    #[test]
    fn parse_verifier_stats_verification_time_no_number() {
        let log = "verification time unknown usec\n";
        let vs = parse_verifier_stats(log);
        assert!(vs.time_usec.is_none());
    }

    #[test]
    fn parse_verifier_stats_stack_depth_empty() {
        let log = "stack depth   \n";
        let vs = parse_verifier_stats(log);
        assert!(vs.stack_depth.is_none());
    }

    #[test]
    fn parse_verifier_stats_peak_states_at_end() {
        let log = "processed 50 insns (limit 1000000) max_states_per_insn 1 total_states 10 peak_states\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 50);
        assert_eq!(vs.total_states, 10);
        assert_eq!(vs.peak_states, 0);
    }

    #[test]
    fn parse_verifier_stats_windows_line_endings() {
        let log = "processed 42 insns (limit 1000000) max_states_per_insn 1 total_states 5 peak_states 2 mark_read 0\r\nverification time 10 usec\r\nstack depth 16\r\n";
        let vs = parse_verifier_stats(log);
        assert_eq!(vs.processed_insns, 42);
        assert_eq!(vs.time_usec, Some(10));
        assert!(vs.stack_depth.is_some());
    }

    // -----------------------------------------------------------------------
    // normalize_verifier_line
    // -----------------------------------------------------------------------

    #[test]
    fn normalize_plain_instruction() {
        assert_eq!(
            normalize_verifier_line("100: (07) r1 += 8"),
            "100: (07) r1 += 8"
        );
    }

    #[test]
    fn normalize_strips_frame_annotation() {
        assert_eq!(
            normalize_verifier_line("3006: (07) r9 += 1  ; frame1: R9_w=2"),
            "3006: (07) r9 += 1"
        );
    }

    #[test]
    fn normalize_strips_register_annotation() {
        assert_eq!(
            normalize_verifier_line("42: (bf) r6 = r1 ; R1=ctx() R6_w=ctx()"),
            "42: (bf) r6 = r1"
        );
    }

    #[test]
    fn normalize_standalone_register_dump() {
        assert_eq!(
            normalize_verifier_line("3041: frame1: R0_w=scalar()"),
            "3041:"
        );
    }

    #[test]
    fn normalize_goto_inline_state() {
        assert_eq!(
            normalize_verifier_line(
                "3026: (b5) if r6 <= 0x11dc0 goto pc+2 3029: frame1: R0=1 R6=scalar()"
            ),
            "3026: (b5) if r6 <= 0x11dc0 goto pc+2"
        );
    }

    #[test]
    fn normalize_goto_no_inline_state() {
        assert_eq!(
            normalize_verifier_line("50: (05) goto pc+10"),
            "50: (05) goto pc+10"
        );
    }

    #[test]
    fn normalize_non_instruction_line() {
        assert_eq!(normalize_verifier_line("func#0 @0"), "func#0 @0");
    }

    #[test]
    fn normalize_empty() {
        assert_eq!(normalize_verifier_line(""), "");
    }

    #[test]
    fn normalize_goto_negative_offset() {
        assert_eq!(
            normalize_verifier_line("50: (05) goto pc-10 60: frame1: R0=1"),
            "50: (05) goto pc-10"
        );
    }

    #[test]
    fn normalize_semicolon_source_comment() {
        let line = "100: (07) r1 += 8 ; for (int j = 0; j < n; j++)";
        assert_eq!(normalize_verifier_line(line), line);
    }

    #[test]
    fn normalize_semicolon_return_value_comment() {
        let line = "200: (b7) r0 = 0 ; Return value";
        assert_eq!(normalize_verifier_line(line), line);
    }

    #[test]
    fn normalize_standalone_bare_register_dump() {
        assert_eq!(
            normalize_verifier_line("3029: R0=1 R6=scalar(id=1)"),
            "3029:"
        );
    }

    #[test]
    fn normalize_standalone_r10_dump() {
        assert_eq!(normalize_verifier_line("42: R10=fp0"), "42:");
    }

    // -----------------------------------------------------------------------
    // detect_cycle / collapse_cycles
    // -----------------------------------------------------------------------

    fn repeating_log(prefix: usize, period: usize, reps: usize, suffix: usize) -> String {
        let mut lines = Vec::new();
        for i in 0..prefix {
            lines.push(format!("{}: (07) r1 += {i}", 1000 + i));
        }
        for rep in 0..reps {
            for j in 0..period {
                let insn = 100 + j;
                lines.push(format!(
                    "{insn}: (bf) r{} = r{} ; frame1: R{}_w={}",
                    j % 10,
                    (j + 1) % 10,
                    j % 10,
                    rep * 100 + j
                ));
            }
        }
        for i in 0..suffix {
            lines.push(format!("{}: (95) exit_{i}", 2000 + i));
        }
        lines.join("\n")
    }

    #[test]
    fn detect_cycle_basic() {
        let log = repeating_log(0, 10, 8, 0);
        let lines: Vec<&str> = log.lines().collect();
        let result = detect_cycle(&lines);
        assert!(result.is_some(), "should detect cycle");
        let (start, period, count) = result.unwrap();
        assert_eq!(period, 10);
        assert!(count >= 6, "count={count}");
        assert_eq!(start, 0);
    }

    #[test]
    fn detect_cycle_with_prefix_suffix() {
        let log = repeating_log(5, 10, 8, 5);
        let lines: Vec<&str> = log.lines().collect();
        let result = detect_cycle(&lines);
        assert!(result.is_some(), "should detect cycle with prefix/suffix");
        let (_start, period, count) = result.unwrap();
        assert_eq!(period, 10);
        assert!(count >= 6);
    }

    #[test]
    fn detect_cycle_too_few_reps() {
        let log = repeating_log(0, 10, 2, 0);
        let lines: Vec<&str> = log.lines().collect();
        assert!(detect_cycle(&lines).is_none());
    }

    #[test]
    fn detect_cycle_too_few_lines() {
        let lines: Vec<String> = (0..20)
            .map(|i| format!("{}: (07) r1 += {i}", 100 + i % 3))
            .collect();
        let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        assert!(detect_cycle(&refs).is_none());
    }

    #[test]
    fn detect_cycle_no_cycle() {
        let lines: Vec<String> = (0..100).map(|i| format!("{i}: unique_insn_{i}")).collect();
        let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        assert!(detect_cycle(&refs).is_none());
    }

    #[test]
    fn detect_cycle_empty() {
        let empty: Vec<&str> = vec![];
        assert!(detect_cycle(&empty).is_none());
    }

    #[test]
    fn detect_cycle_exact_boundary() {
        let log = repeating_log(0, 5, 6, 0);
        let lines: Vec<&str> = log.lines().collect();
        assert_eq!(lines.len(), 30);
        let result = detect_cycle(&lines);
        assert!(result.is_some(), "boundary case should detect cycle");
        let (_start, period, count) = result.unwrap();
        assert_eq!(period, 5);
        assert_eq!(count, 6);
    }

    #[test]
    fn collapse_cycles_empty_string() {
        assert_eq!(collapse_cycles(""), "");
    }

    #[test]
    fn collapse_cycles_basic() {
        let log = repeating_log(2, 10, 8, 2);
        let collapsed = collapse_cycles(&log);
        assert!(collapsed.contains("identical iterations omitted"));
        assert!(collapsed.contains("8x of the following 10 lines"));
        assert!(collapsed.contains("end repeat"));
        assert!(collapsed.lines().count() < log.lines().count());
    }

    #[test]
    fn collapse_cycles_no_cycle() {
        let log = "line 1\nline 2\nline 3\n";
        let collapsed = collapse_cycles(log);
        assert_eq!(collapsed, log);
    }

    #[test]
    fn collapse_cycles_preserves_stats() {
        let mut log = repeating_log(0, 10, 8, 0);
        log.push_str("\nprocessed 1000 insns (limit 1000000) max_states_per_insn 5 total_states 100 peak_states 30 mark_read 10\n");
        let collapsed = collapse_cycles(&log);
        assert!(collapsed.contains("processed 1000 insns"));
    }

    #[test]
    fn collapse_cycles_with_register_annotations() {
        let mut lines = Vec::new();
        lines.push("0: (07) r1 += 1".to_string());
        for rep in 0..8 {
            for j in 0..6 {
                let insn = 100 + j;
                lines.push(format!(
                    "{insn}: (bf) r{} = r{} ; frame1: R{}_w={}",
                    j % 10,
                    (j + 1) % 10,
                    j % 10,
                    rep * 100 + j
                ));
            }
        }
        lines.push("200: (95) exit".to_string());
        let log = lines.join("\n");
        let collapsed = collapse_cycles(&log);
        assert!(collapsed.contains("identical iterations omitted"));
    }

    // -----------------------------------------------------------------------
    // build_b_map / build_diff_rows
    // -----------------------------------------------------------------------

    fn prog(name: &str, verified_insns: u32) -> ProgStats {
        ProgStats {
            name: name.to_string(),
            verified_insns,
        }
    }

    #[test]
    fn build_b_map_basic() {
        let stats_b = vec![prog("dispatch", 500)];
        let map = build_b_map(&stats_b);
        assert_eq!(map.get("dispatch"), Some(&500));
    }

    #[test]
    fn build_b_map_empty() {
        let map = build_b_map(&[]);
        assert!(map.is_empty());
    }

    #[test]
    fn build_diff_rows_matching_programs() {
        let stats_a = vec![prog("dispatch", 500)];
        let mut b_map = HashMap::new();
        b_map.insert("dispatch".to_string(), 300u64);
        let rows = build_diff_rows(&stats_a, &b_map);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].name, "dispatch");
        assert_eq!(rows[0].a, 500);
        assert_eq!(rows[0].b, 300);
        assert_eq!(rows[0].delta, 200);
    }

    #[test]
    fn build_diff_rows_program_missing_from_b() {
        let stats_a = vec![prog("new_prog", 100)];
        let b_map = HashMap::new();
        let rows = build_diff_rows(&stats_a, &b_map);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].a, 100);
        assert_eq!(rows[0].b, 0);
        assert_eq!(rows[0].delta, 100);
    }

    #[test]
    fn build_diff_rows_negative_delta() {
        let stats_a = vec![prog("dispatch", 200)];
        let mut b_map = HashMap::new();
        b_map.insert("dispatch".to_string(), 500u64);
        let rows = build_diff_rows(&stats_a, &b_map);
        assert_eq!(rows[0].delta, -300);
    }

    #[test]
    fn build_diff_rows_empty_a() {
        let b_map = HashMap::new();
        let rows = build_diff_rows(&[], &b_map);
        assert!(rows.is_empty());
    }

    /// Simulates the verifier trace produced by #pragma unroll loops.
    /// Each copy is at a different base address but has the same
    /// instruction sequence. After normalize_for_cycle_detection strips
    /// addresses and register annotations, all copies look identical.
    fn unrolled_verifier_log(copies: usize, body_len: usize) -> String {
        let ops = [
            "(85) call bpf_ktime_get_ns#5",
            "(bf) r2 = r0",
            "(77) r0 >>= 16",
            "(af) r1 ^= r0",
            "(77) r2 >>= 32",
            "(0f) r1 += r2",
            "(24) w1 *= 7",
            "(04) w1 += 1",
        ];
        let mut lines = Vec::new();
        lines.push("func#0 @0".to_string());
        lines.push("0: R1=ctx() R10=fp0".to_string());
        let mut addr = 10;
        for copy in 0..copies {
            for (j, op) in ops.iter().enumerate().take(body_len) {
                lines.push(format!(
                    "{}: {op} ; R0_w=scalar(id={})",
                    addr,
                    copy * 100 + j
                ));
                addr += 1;
            }
        }
        lines.push(format!("{addr}: (05) goto pc-1"));
        lines.push(
            "processed 1000 insns (limit 1000000) max_states_per_insn 3 \
             total_states 50 peak_states 20 mark_read 5"
                .to_string(),
        );
        lines.join("\n")
    }

    #[test]
    fn detect_cycle_unrolled_loop() {
        let log = unrolled_verifier_log(8, 6);
        let lines: Vec<&str> = log.lines().collect();
        let result = detect_cycle(&lines);
        assert!(result.is_some(), "should detect cycle in unrolled loop");
        let (_start, period, count) = result.unwrap();
        assert_eq!(period, 6);
        assert!(count >= 6, "count={count}");
    }

    #[test]
    fn collapse_cycles_unrolled_loop() {
        let log = unrolled_verifier_log(8, 6);
        let collapsed = collapse_cycles(&log);
        assert!(
            collapsed.contains("identical iterations omitted"),
            "should collapse unrolled loop"
        );
        assert!(collapsed.lines().count() < log.lines().count());
    }

    // -----------------------------------------------------------------------
    // extract_verifier_log
    // -----------------------------------------------------------------------

    #[test]
    fn extract_verifier_log_basic() {
        let log = "\
libbpf: prog 'dispatch': BPF program load failed: -22
-- BEGIN PROG LOAD LOG --
func#0 @0
0: R1=ctx() R10=fp0
processed 100 insns (limit 1000000) max_states_per_insn 1 total_states 5 peak_states 2 mark_read 0
-- END PROG LOAD LOG --
libbpf: failed to load object 'ktstr_ops'
";
        let extracted = extract_verifier_log(log);
        assert!(extracted.is_some());
        let v = extracted.unwrap();
        assert!(v.starts_with("func#0 @0"));
        assert!(v.contains("processed 100 insns"));
        assert!(!v.contains("BEGIN PROG LOAD LOG"));
        assert!(!v.contains("END PROG LOAD LOG"));
        assert!(!v.contains("libbpf:"));
    }

    #[test]
    fn extract_verifier_log_none_without_markers() {
        let log = "func#0 @0\n0: R1=ctx()\nprocessed 50 insns\n";
        assert!(extract_verifier_log(log).is_none());
    }

    #[test]
    fn extract_verifier_log_empty() {
        assert!(extract_verifier_log("").is_none());
    }

    /// Attack 1: libbpf wraps verifier output with "libbpf: " prefix lines.
    /// `parse_verifier_stats` looks for `starts_with("processed ")` which
    /// won't match `libbpf: processed ...`. Without extraction, stats
    /// parsing fails on blobs where the `processed` line is only inside
    /// the markers.
    #[test]
    fn extract_verifier_log_attack1_stats_parse() {
        let blob = "\
libbpf: prog 'ktstr_ops_dispatch': BPF program load failed: -22
libbpf: -- BEGIN PROG LOAD LOG --
func#0 @0
0: R1=ctx() R10=fp0
1: (bf) r6 = r1 ; R1=ctx() R6_w=ctx()
back-edge from insn 42 to 10
BPF program is too complex
processed 131071 insns (limit 131072) max_states_per_insn 12 total_states 9999 peak_states 5000 mark_read 800
verification time 250000 usec
stack depth 96+32
libbpf: -- END PROG LOAD LOG --
libbpf: failed to load BPF skeleton 'ktstr_ops': -22
";
        let extracted = extract_verifier_log(blob);
        assert!(extracted.is_some(), "should find markers");
        let v = extracted.unwrap();
        let vs = parse_verifier_stats(v);
        assert_eq!(vs.processed_insns, 131071);
        assert_eq!(vs.total_states, 9999);
        assert_eq!(vs.peak_states, 5000);
        assert_eq!(vs.time_usec, Some(250000));
        assert_eq!(vs.stack_depth.as_deref(), Some("96+32"));

        // Without extraction, parsing the full blob must also work
        // because the "processed" line doesn't have a "libbpf: " prefix
        // inside the markers. But verify extraction gives cleaner input.
        let vs_raw = parse_verifier_stats(blob);
        assert_eq!(vs_raw.processed_insns, 131071);
    }

    /// Attack 3: three distinct program load logs in a single blob.
    /// Each has different instructions. `collapse_cycles` must NOT treat
    /// them as a repeating cycle.
    #[test]
    fn extract_verifier_log_attack3_no_false_collapse() {
        let blob = "\
libbpf: prog 'init': BPF program load failed: -22
libbpf: -- BEGIN PROG LOAD LOG --
func#0 @0
0: R1=ctx() R10=fp0
1: (bf) r6 = r1
2: (07) r6 += 8
3: (61) r0 = *(u32 *)(r6 + 0)
4: (95) exit
processed 5 insns (limit 1000000) max_states_per_insn 1 total_states 3 peak_states 1 mark_read 0
libbpf: -- END PROG LOAD LOG --
libbpf: prog 'dispatch': BPF program load failed: -22
libbpf: -- BEGIN PROG LOAD LOG --
func#1 @10
10: R1=ctx() R10=fp0
11: (bf) r7 = r1
12: (85) call bpf_ktime_get_ns#5
13: (77) r0 >>= 32
14: (95) exit
processed 5 insns (limit 1000000) max_states_per_insn 1 total_states 3 peak_states 1 mark_read 0
libbpf: -- END PROG LOAD LOG --
libbpf: prog 'enqueue': BPF program load failed: -22
libbpf: -- BEGIN PROG LOAD LOG --
func#2 @20
20: R1=ctx() R10=fp0
21: (b7) r0 = 0
22: (63) *(u32 *)(r10 - 4) = r0
23: (61) r1 = *(u32 *)(r10 - 4)
24: (95) exit
processed 5 insns (limit 1000000) max_states_per_insn 1 total_states 3 peak_states 1 mark_read 0
libbpf: -- END PROG LOAD LOG --
libbpf: failed to load BPF skeleton 'ktstr_ops': -22
";
        // extract_verifier_log returns the FIRST log section.
        let extracted = extract_verifier_log(blob);
        assert!(extracted.is_some());
        let v = extracted.unwrap();
        assert!(v.contains("func#0 @0"), "should get first program's log");
        assert!(!v.contains("func#1"), "should not include second program");

        // collapse_cycles on the extracted first section must not
        // collapse — it's only 7 lines total.
        let collapsed = collapse_cycles(v);
        assert!(
            !collapsed.contains("identical iterations omitted"),
            "must not false-collapse distinct program logs"
        );
    }

    // -- insta snapshot tests --

    #[test]
    fn snapshot_format_verifier_output_no_log() {
        let result = VerifierVmResult {
            stats: vec![
                ProgStats {
                    name: "enqueue".into(),
                    verified_insns: 500,
                },
                ProgStats {
                    name: "dispatch".into(),
                    verified_insns: 1200,
                },
                ProgStats {
                    name: "init".into(),
                    verified_insns: 300,
                },
            ],
            scheduler_log: String::new(),
            attach: AttachOutcome::Attached,
            dispatched: true,
            timed_out: false,
        };
        insta::assert_snapshot!(format_verifier_output("default", &result, false));
    }

    #[test]
    fn snapshot_format_verifier_output_with_log() {
        let log = "\
-- BEGIN PROG LOAD LOG --\n\
func#0 @0\n\
0: R1=ctx() R10=fp0\n\
processed 42 insns (limit 1000000) max_states_per_insn 1 total_states 10 peak_states 8 mark_read 5\n\
-- END PROG LOAD LOG --";
        let result = VerifierVmResult {
            stats: vec![ProgStats {
                name: "enqueue".into(),
                verified_insns: 42,
            }],
            scheduler_log: log.into(),
            // A load log present means the scheduler printed a verifier
            // trace then exited — the SchedulerDied failure path.
            attach: AttachOutcome::Died,
            dispatched: false,
            timed_out: false,
        };
        insta::assert_snapshot!(format_verifier_output("llc+steal", &result, false));
    }

    #[test]
    fn snapshot_format_verifier_diff() {
        let stats_a = vec![
            ProgStats {
                name: "enqueue".into(),
                verified_insns: 500,
            },
            ProgStats {
                name: "dispatch".into(),
                verified_insns: 1200,
            },
            ProgStats {
                name: "init".into(),
                verified_insns: 300,
            },
        ];
        let stats_b = vec![
            ProgStats {
                name: "enqueue".into(),
                verified_insns: 480,
            },
            ProgStats {
                name: "dispatch".into(),
                verified_insns: 1350,
            },
            ProgStats {
                name: "init".into(),
                verified_insns: 300,
            },
        ];
        insta::assert_snapshot!(format_verifier_diff("default", &stats_a, "llc", &stats_b));
    }

    #[test]
    fn snapshot_format_verifier_diff_missing_program() {
        let stats_a = vec![
            ProgStats {
                name: "enqueue".into(),
                verified_insns: 500,
            },
            ProgStats {
                name: "new_prog".into(),
                verified_insns: 100,
            },
        ];
        let stats_b = vec![ProgStats {
            name: "enqueue".into(),
            verified_insns: 500,
        }];
        insta::assert_snapshot!(format_verifier_diff("A", &stats_a, "B", &stats_b));
    }

    // -----------------------------------------------------------------------
    // extract_verifier_log — log extraction + cross-check against
    // parse_sched_output so the two slicers stay consistent on shared input.
    // -----------------------------------------------------------------------

    #[test]
    fn extract_verifier_log_between_begin_end_markers() {
        // libbpf wraps the verifier log between explicit marker lines;
        // the extractor returns the content between them, trimmed of
        // the BEGIN newline and the trailing libbpf END prefix.
        let blob = "\
            unrelated preamble\n\
            libbpf: -- BEGIN PROG LOAD LOG --\n\
            processed 1234 insns (limit 1000000) max_states_per_insn 5 total_states 200 peak_states 50 mark_read 10\n\
            libbpf: -- END PROG LOAD LOG --\n\
            trailing diagnostics\n";
        let log = extract_verifier_log(blob).expect("markers present");
        assert!(log.contains("processed 1234 insns"));
        assert!(!log.contains("BEGIN PROG LOAD LOG"));
        assert!(!log.contains("END PROG LOAD LOG"));
    }

    #[test]
    fn extract_verifier_log_returns_none_when_markers_absent() {
        // Backward compat: logs without the libbpf markers are treated
        // as "no markers" — the caller falls back to using the raw blob.
        assert!(extract_verifier_log("no markers in here").is_none());
        assert!(extract_verifier_log("only BEGIN marker -- BEGIN PROG LOAD LOG --").is_none());
    }

    #[test]
    fn extract_verifier_log_consistent_with_parse_sched_output() {
        // `collect_verifier_output` chains parse_sched_output →
        // extract_verifier_log on the VM stdout blob. Both slicers
        // operate on the same input without duplicating work, so a
        // single SCHED_OUTPUT block that wraps a libbpf-marked verifier
        // log must produce the same verifier text when extracted in
        // that order.
        let sched_inner = "\
            libbpf: -- BEGIN PROG LOAD LOG --\n\
            processed 7 insns (limit 1000000) max_states_per_insn 1 total_states 1 peak_states 1 mark_read 0\n\
            libbpf: -- END PROG LOAD LOG --\n";
        let vm_output = format!(
            "kernel boot junk\n{SCHED_OUTPUT_START}\n{sched_inner}{SCHED_OUTPUT_END}\nafterward\n",
        );
        let sched = parse_sched_output(&vm_output).expect("SCHED_OUTPUT block");
        let verifier_log = extract_verifier_log(sched).expect("verifier markers");
        assert!(verifier_log.contains("processed 7 insns"));
        assert!(!verifier_log.contains("SCHED_OUTPUT"));
        assert!(!verifier_log.contains("BEGIN PROG LOAD LOG"));
    }

    #[test]
    fn parse_sched_output_valid() {
        let output = format!(
            "noise\n{SCHED_OUTPUT_START}\nscheduler log line 1\nline 2\n{SCHED_OUTPUT_END}\nmore"
        );
        let parsed = parse_sched_output(&output);
        assert!(parsed.is_some());
        let content = parsed.unwrap();
        assert!(content.contains("scheduler log line 1"));
        assert!(content.contains("line 2"));
    }

    #[test]
    fn parse_sched_output_missing_start() {
        let output = format!("no start\n{SCHED_OUTPUT_END}\n");
        assert!(parse_sched_output(&output).is_none());
    }

    #[test]
    fn parse_sched_output_missing_end() {
        let output = format!("{SCHED_OUTPUT_START}\nsome content");
        assert!(parse_sched_output(&output).is_none());
    }

    #[test]
    fn parse_sched_output_empty_content() {
        let output = format!("{SCHED_OUTPUT_START}\n\n{SCHED_OUTPUT_END}");
        assert!(parse_sched_output(&output).is_none());
    }

    #[test]
    fn parse_sched_output_with_stack_traces() {
        let stack = "do_enqueue_task+0x1a0/0x380\nbalance_one+0x50/0x100\n";
        let output = format!("{SCHED_OUTPUT_START}\n{stack}\n{SCHED_OUTPUT_END}");
        let parsed = parse_sched_output(&output).unwrap();
        assert!(parsed.contains("do_enqueue_task"));
        assert!(parsed.contains("balance_one"));
    }

    #[test]
    fn parse_sched_output_rfind_survives_end_marker_in_content() {
        // Regression: if the scheduler log echoes the END marker
        // inside its own content (e.g. a shell heredoc, a diagnostic
        // that quotes the sentinel), `find` truncated the section at
        // the first occurrence — which was inside the content, not
        // at the terminator. `rfind` anchors on the last occurrence,
        // which is the real terminator.
        let content = format!("line1\nfake {SCHED_OUTPUT_END} inside\nline3");
        let output = format!("{SCHED_OUTPUT_START}\n{content}\n{SCHED_OUTPUT_END}\n");
        let parsed = parse_sched_output(&output).unwrap();
        assert!(
            parsed.contains("line3"),
            "rfind must keep content after an embedded END marker: {parsed:?}"
        );
        assert!(
            parsed.contains("fake"),
            "content before the embedded marker must also survive: {parsed:?}"
        );
    }

    // -- parse_sched_output_partial --

    #[test]
    fn parse_sched_output_partial_well_formed_matches_strict() {
        // When both delimiters are present, the partial parser
        // returns the same content as the strict parser.
        let output = format!(
            "noise\n{SCHED_OUTPUT_START}\nscheduler log line 1\nline 2\n{SCHED_OUTPUT_END}\nmore"
        );
        assert_eq!(
            parse_sched_output_partial(&output),
            parse_sched_output(&output),
        );
    }

    #[test]
    fn parse_sched_output_partial_missing_end_returns_partial() {
        // When SCHED_OUTPUT_END is absent (scheduler crashed mid-run
        // before writing the closing delimiter), the partial parser
        // returns content from after SCHED_OUTPUT_START to end of
        // buffer. The strict parser returns None for the same input.
        let output = format!("{SCHED_OUTPUT_START}\nstack frame 1\nstack frame 2");
        assert!(parse_sched_output(&output).is_none());
        let partial = parse_sched_output_partial(&output).unwrap();
        assert!(partial.contains("stack frame 1"));
        assert!(partial.contains("stack frame 2"));
    }

    #[test]
    fn parse_sched_output_partial_missing_start_returns_none() {
        // No start marker → no content recoverable. The end-marker-
        // only case is unrecoverable: we cannot infer where the log
        // begins.
        let output = format!("garbage\n{SCHED_OUTPUT_END}\n");
        assert!(parse_sched_output_partial(&output).is_none());
    }

    #[test]
    fn parse_sched_output_partial_empty_content_returns_none() {
        // Start marker present but no payload after it.
        let output = format!("{SCHED_OUTPUT_START}\n");
        assert!(parse_sched_output_partial(&output).is_none());
    }
}