ktstr 0.4.19

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
//! Process-level dispatch and nextest protocol handling.
//!
//! This module owns every code path that runs before (or in lieu of)
//! the user's `main()`:
//!
//! - [`ktstr_test_early_dispatch`]: the `#[ctor]` that fires in every
//!   ktstr-linked binary. Routes the process to guest init, host-side
//!   VM launch, guest-side test execution, or nextest protocol handling.
//! - [`ktstr_main`]: the nextest protocol handler — `--list` returns
//!   `ktstr/` and `gauntlet/` test names, `--exact` runs a single test.
//! - [`run_ktstr_test`]: programmatic entry point used by library
//!   consumers and the macro-generated `#[test]` wrappers.
//! - [`analyze_sidecars`]: collects sidecar JSON from a run directory
//!   and renders the full gauntlet analysis (rows + verifier + callback
//!   profile + KVM stats) into a string.
//!
//! The heavy lifting lives in sibling submodules: `eval` (host-side
//! result judgment — `run_ktstr_test_inner` and `evaluate_vm_result`),
//! `sidecar` (per-run JSON), `probe` (auto-repro + BPF probe pipeline),
//! `args` (CLI extraction), and the [`crate::vmm`] VM launcher.

use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::atomic::{AtomicPtr, Ordering};

use anyhow::Result;

use crate::assert::AssertResult;

/// Deferred nextest dispatch name set by the ctor's argv rewrite.
/// When the ctor sees `--exact ktstr/...` or `--exact gauntlet/...`,
/// it stores the full prefixed name here and overwrites the argv
/// bytes to the bare test name so libtest can match the `#[test]`
/// wrapper at main-time (after C++ static constructors complete).
/// `run_ktstr_test` checks this global to resolve the gauntlet
/// topology or multi-kernel variant from the original name.
static DEFERRED_DISPATCH: Mutex<Option<String>> = Mutex::new(None);

/// Raw argv pointer captured at process startup via the
/// `.init_array.00001` constructor below. `AtomicPtr` rather than
/// `static mut` so the capture (Release) and the later read in
/// `rewrite_argv_exact` (Acquire) form a happens-before edge — the
/// argv string bytes glibc placed before invoking `.init_array`
/// callbacks are visible to the rewrite via that synchronization
/// edge. The element type is `*mut libc::c_char` (matching argv's
/// `*const *mut c_char` shape); cast back to `*const *mut c_char`
/// before indexing in the consumer.
static RAW_ARGV: AtomicPtr<*mut libc::c_char> = AtomicPtr::new(std::ptr::null_mut());

/// Numbered link section `.init_array.00001` to force CAPTURE_ARGV
/// to run BEFORE the unprioritized dispatch ctor (`.init_array`
/// without a numeric suffix). GNU ld sorts numbered
/// `.init_array.NN` sections numerically and places them before
/// plain `.init_array`. The profraw ctor in profraw.rs uses ctor's
/// `priority = 0` mechanism (which expands to `.init_array.0`) for
/// the same reason; this entry uses `.00001` so profraw still runs
/// first, then CAPTURE_ARGV, then the unprioritized dispatch ctor
/// at `ktstr_test_early_dispatch`.
///
/// Cannot use `#[ctor::ctor(priority = N)]` directly because the
/// ctor crate's macro emits a 0-arg `extern "C" fn() -> CtorRetType`.
/// glibc passes `(argc, argv, envp)` to `.init_array` callbacks and
/// argv capture requires the 2-arg signature. Without the numbered
/// section, link order between this static and the dispatch ctor is
/// unspecified, so the dispatch ctor's argv-rewrite step would race
/// against capture and observe a null `RAW_ARGV`.
#[unsafe(link_section = ".init_array.00001")]
#[used]
static CAPTURE_ARGV: unsafe extern "C" fn(libc::c_int, *const *mut libc::c_char) = {
    unsafe extern "C" fn capture(_argc: libc::c_int, argv: *const *mut libc::c_char) {
        // Release pairs with Acquire in `rewrite_argv_exact`.
        RAW_ARGV.store(argv as *mut *mut libc::c_char, Ordering::Release);
    }
    capture
};

use super::{
    KTSTR_TESTS, KtstrTestEntry, TopoOverride, collect_sidecars, extract_export_output_arg,
    extract_export_test_arg, extract_flags_arg, extract_test_fn_arg, extract_topo_arg, find_test,
    format_callback_profile, format_kvm_stats, format_verifier_stats, maybe_dispatch_vm_test,
    parse_topo_string, propagate_rust_env_from_cmdline, record_skip_sidecar, resolve_test_kernel,
    run_ktstr_test_inner, sidecar_dir, try_flush_profraw, validate_entry_flags,
};

/// Check if an `anyhow::Error` carries a [`ResourceContention`].
///
/// Walks the FULL error chain via `e.chain().any(...)` so a
/// `ResourceContention` wrapped in `.context(...)` (e.g. the
/// `eval.rs` `"build ktstr_test VM"` and `"run ktstr_test VM"`
/// wrappers) is still recognised — the macro's match arm depends on
/// this.
///
/// Used by the `#[ktstr_test]` macro expansion to short-circuit on
/// host-resource contention (LLC slots / CPUs unavailable, KVM fd
/// budget exhausted, ENOMEM): the macro emits the canonical
/// `ktstr: SKIP: resource contention: ...` banner and early-returns
/// so libtest sees pass. The skip sidecar is recorded at every
/// contention site inside `run_ktstr_test_inner`, so stats tooling
/// still sees the skip without a panic-driven nextest retry. `pub`
/// because the macro-generated `#[test]` body in `ktstr-macros`
/// references it by absolute path; `#[doc(hidden)]` keeps it out
/// of rustdoc's public surface — it is plumbing, not user API.
///
/// [`ResourceContention`]: crate::vmm::host_topology::ResourceContention
/// Check if an error is a host topology mismatch (e.g. test
/// requests 2 LLCs but host has 1). String-match because the
/// error is a plain `anyhow::Error`, not a typed error.
#[doc(hidden)]
pub fn is_topology_insufficient(e: &anyhow::Error) -> bool {
    let msg = format!("{e:#}");
    msg.contains("need") && (msg.contains("LLC") || msg.contains("CPU"))
}

#[doc(hidden)]
pub fn is_resource_contention(e: &anyhow::Error) -> bool {
    e.chain().any(|cause| {
        cause
            .downcast_ref::<crate::vmm::host_topology::ResourceContention>()
            .is_some()
    })
}

/// Predicate: walks the [`anyhow::Error`] chain looking for a
/// [`KernelUnavailable`] cause. Used by the `#[ktstr_test]`
/// macro's wrapper to distinguish "harness not configured" (skip)
/// from "test failed" (panic).
///
/// The harness signals "I have no kernel to boot, the binary was
/// likely invoked outside `cargo ktstr test`" by surfacing
/// [`KernelUnavailable`] rather than a generic
/// `anyhow::bail!`. The macro wrapper emits the canonical
/// `ktstr: SKIP: harness not configured: ...` banner and
/// early-returns so libtest sees pass — same shape as the
/// resource-contention SKIP arm. `pub` because the macro-generated
/// `#[test]` body in `ktstr-macros` references it by absolute
/// path; `#[doc(hidden)]` keeps it out of rustdoc — plumbing, not
/// user API.
///
/// [`KernelUnavailable`]: crate::test_support::eval::KernelUnavailable
#[doc(hidden)]
pub fn is_kernel_unavailable(e: &anyhow::Error) -> bool {
    e.chain().any(|cause| {
        cause
            .downcast_ref::<crate::test_support::eval::KernelUnavailable>()
            .is_some()
    })
}

/// Overwrite the argv string at index `arg_idx` with `replacement`.
///
/// Uses `RAW_ARGV` captured by the `.init_array.00001` constructor
/// above. The replacement MUST be shorter than or equal to the
/// original string — the function null-terminates within the
/// existing buffer.
///
/// When `RAW_ARGV` is still null (the capture ctor did not fire,
/// or fired AFTER this caller — a regression in `.init_array`
/// ordering), emits a stderr diagnostic and returns. Without the
/// warning, the deferred-dispatch path would silently fail to
/// rewrite argv and libtest would not match the bare test name,
/// surfacing as an opaque "no test matches" failure further
/// downstream rather than a clear ordering regression.
fn rewrite_argv_exact(arg_idx: usize, replacement: &str) {
    // Acquire pairs with Release in CAPTURE_ARGV's `capture`.
    let raw = RAW_ARGV.load(Ordering::Acquire) as *const *mut libc::c_char;
    if raw.is_null() {
        eprintln!(
            "ktstr: rewrite_argv_exact called before CAPTURE_ARGV ctor fired \
             (RAW_ARGV is null). Deferred dispatch will not match libtest's \
             test name and the run will likely fail. This indicates a \
             regression in `.init_array` ordering — the `.init_array.00001` \
             section above must be linked before the unprioritized dispatch \
             ctor.",
        );
        return;
    }
    // SAFETY:
    //   (a) RAW_ARGV was set by glibc passing the live `argv` array
    //       to CAPTURE_ARGV — the array is the program's actual
    //       argument vector and remains valid for the lifetime of
    //       the process.
    //   (b) argv strings on Linux live in the high end of the
    //       process stack and are writable by the program (the
    //       `setproctitle(3)`-style argv-overwrite trick relies on
    //       exactly this). POSIX does not require this, but on
    //       Linux/glibc — the only platform ktstr targets — argv
    //       string memory is mutable.
    //   (c) `replacement.len() <= original_len` is checked before
    //       any write, so the in-place overwrite + null terminator
    //       stays inside the original allocation. No bytes past
    //       the original null terminator are touched.
    //   (d) This function is only reachable from
    //       `ktstr_test_early_dispatch`, an `.init_array` ctor.
    //       glibc invokes `.init_array` callbacks on the main
    //       thread before any user thread has spawned, so the
    //       argv overwrite is single-threaded and race-free.
    unsafe {
        let arg = *raw.add(arg_idx);
        if arg.is_null() {
            return;
        }
        let original_len = libc::strlen(arg as *const libc::c_char);
        if replacement.len() > original_len {
            return;
        }
        let dst = arg as *mut u8;
        std::ptr::copy_nonoverlapping(replacement.as_ptr(), dst, replacement.len());
        *dst.add(replacement.len()) = 0;
    }
}

/// A nextest-safe kernel identifier whose construction is gated
/// through [`sanitize_kernel_label`] — once a value of this type
/// exists, the contained string is GUARANTEED to match the
/// `kernel_[a-z0-9_]+` shape that nextest's test-name parsing
/// accepts. The wrapped `String` is private so a future caller
/// cannot bypass [`Self::new`] and stuff a raw label into the
/// invariant.
///
/// Constructed by [`Self::new`] (which always calls
/// [`sanitize_kernel_label`]). Read access is via
/// [`Self::as_str`] / `Display` / `AsRef<str>` — both of which
/// expose the sanitized form unchanged.
///
/// `pub(crate)` because every consumer (this module, the
/// production parser at [`parse_kernel_list`], and the encoder
/// helpers in `cargo-ktstr` that thread labels through
/// `parse_kernel_list`) lives inside the workspace; no external
/// surface is needed today. If a future external consumer needs
/// to construct a `SanitizedKernelLabel` directly, expose
/// `Self::new` as `pub` then — but the private inner stays a
/// private invariant either way.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SanitizedKernelLabel(String);

impl SanitizedKernelLabel {
    /// Sanitize `raw` via [`sanitize_kernel_label`] and wrap the
    /// result in the invariant-preserving newtype. The only path
    /// that produces a `SanitizedKernelLabel`; bypassing it is
    /// impossible because the inner field is private to this
    /// module.
    pub(crate) fn new(raw: &str) -> Self {
        Self(sanitize_kernel_label(raw))
    }

    /// Read access to the sanitized identifier. Returns `&str`
    /// rather than `&String` so callers can compose with
    /// `format!` / `starts_with` / `strip_suffix` without
    /// chaining `.as_str().as_str()`.
    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SanitizedKernelLabel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for SanitizedKernelLabel {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

// `PartialEq<&str>` and `PartialEq<str>` impls let `assert_eq!`
// against a string literal stay readable in tests
// (`assert_eq!(entries[0].sanitized, "kernel_6_14_2")`) without
// forcing every consumer to chain `.as_str()`. The wrapped
// `String` is private to this module, so impls comparing
// against external `&str` values cannot break the
// "constructor enforces sanitization" invariant — the
// invariant attaches to value PRODUCTION, not to value
// COMPARISON.
impl PartialEq<&str> for SanitizedKernelLabel {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<str> for SanitizedKernelLabel {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

#[cfg(test)]
impl SanitizedKernelLabel {
    /// Test-only escape hatch: wrap a string that's ALREADY in
    /// the sanitized shape (`kernel_[a-z0-9_]+`) without running
    /// the sanitizer. Used by unit-test fixtures that hand-roll
    /// `KernelEntry` values whose `sanitized` field is meant to
    /// be a literal — running [`Self::new`] on `"kernel_6_14_2"`
    /// would double-prefix to `"kernel_kernel_6_14_2"`.
    ///
    /// Production code must NEVER call this — invariant
    /// violation here means callers can stuff arbitrary strings
    /// into the field, defeating the point of the newtype.
    /// `#[cfg(test)]` enforces that at compile time.
    pub(crate) fn from_pre_sanitized_for_test(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// One resolved kernel entry from `KTSTR_KERNEL_LIST` (the multi-
/// kernel fan-out wire format that `cargo ktstr test --kernel A
/// --kernel B` exports before exec'ing into `cargo nextest`).
///
/// `sanitized` is the nextest-safe identifier appended to test names
/// so `cargo nextest run -E 'test(kernel_6_14_2)'` filters work
/// natively. The producer-side encoder in `cargo-ktstr` emits a
/// semantic, operator-readable label per kernel:
/// - Version / Range expansion: the version string verbatim
///   (`6.14.2`, `6.15-rc3`).
/// - CacheKey: the version prefix (everything before the
///   `-tarball-` / `-git-` source tag).
/// - Git: `git_{owner}_{repo}_{ref}` extracted from the URL.
/// - Path: `path_{basename}_{hash6}` — basename + 6-char crc32 of
///   the canonical path, disambiguating two `linux` directories
///   under different parents.
///
/// [`SanitizedKernelLabel::new`] (which calls [`sanitize_kernel_label`])
/// applies the `kernel_` prefix and `[a-z0-9_]+` normalization
/// downstream. The newtype on this field makes the invariant
/// compile-checked: a future caller cannot construct a
/// `KernelEntry` whose `sanitized` field skipped sanitization.
///
/// `kernel_dir` is the canonical absolute path to the kernel-build
/// directory the per-variant subprocess re-exports as
/// `KTSTR_KERNEL`.
#[derive(Clone, Debug)]
pub(crate) struct KernelEntry {
    pub(crate) sanitized: SanitizedKernelLabel,
    pub(crate) kernel_dir: PathBuf,
}

/// Parse the multi-kernel wire format `KTSTR_KERNEL_LIST` into a
/// `Vec<KernelEntry>`. Format: `label1=path1;label2=path2;...`,
/// semicolon-separated entries, `=` separating label from path. Empty
/// / unset env returns an empty vec — callers treat that as
/// "single-kernel mode" and fall through to `KTSTR_KERNEL`.
///
/// Malformed entries (missing `=`, empty label, empty path) are
/// dropped silently — the producer is `cargo ktstr` which encodes
/// the format under our control, so a malformed entry indicates a
/// regression in the producer rather than operator input that
/// deserves a clear error. Silent drop preserves the `len() <= 1` →
/// "treat as single-kernel" invariant in the readers downstream.
pub(crate) fn parse_kernel_list(raw: &str) -> Vec<KernelEntry> {
    raw.split(';')
        .filter_map(|seg| {
            let seg = seg.trim();
            if seg.is_empty() {
                return None;
            }
            let (label, path) = seg.split_once('=')?;
            let label = label.trim();
            let path = path.trim();
            if label.is_empty() || path.is_empty() {
                return None;
            }
            Some(KernelEntry {
                sanitized: SanitizedKernelLabel::new(label),
                kernel_dir: PathBuf::from(path),
            })
        })
        .collect()
}

/// Read [`crate::KTSTR_KERNEL_LIST_ENV`] and parse it into a
/// `Vec<KernelEntry>`. Empty / unset / malformed → empty vec
/// (single-kernel mode at the call site).
pub(crate) fn read_kernel_list() -> Vec<KernelEntry> {
    std::env::var(crate::KTSTR_KERNEL_LIST_ENV)
        .ok()
        .map(|v| parse_kernel_list(&v))
        .unwrap_or_default()
}

/// Sanitise a kernel label (the producer-side identity emitted by
/// `cargo ktstr`'s resolver) into a nextest-safe identifier of the
/// shape `kernel_[a-z0-9_]+`.
///
/// Replaces every `[^A-Za-z0-9]` byte with `_`, lowercases, collapses
/// runs of `_`, and prefixes with `kernel_`. Empty / pathologically-
/// short input collapses to `kernel_` alone, which the parser
/// downstream still recognises as a valid suffix (the empty
/// `sanitized` marker just won't disambiguate two kernels — but the
/// producer side guarantees non-empty labels, so the empty case is
/// defensive only).
///
/// Example mappings:
/// - `6.14.2` → `kernel_6_14_2`
/// - `6.15-rc3` → `kernel_6_15_rc3`
/// - `git_tj_sched_ext_for-next` → `kernel_git_tj_sched_ext_for_next`
/// - `path_linux_a3f2b1` → `kernel_path_linux_a3f2b1`
pub fn sanitize_kernel_label(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len() + 7);
    out.push_str("kernel_");
    let mut last_underscore = true; // suppress leading `_` after `kernel_`
    for ch in raw.chars() {
        let c = ch.to_ascii_lowercase();
        if c.is_ascii_alphanumeric() {
            out.push(c);
            last_underscore = false;
        } else if !last_underscore {
            out.push('_');
            last_underscore = true;
        }
    }
    // Strip a trailing `_` so a label like `for-next-` doesn't
    // produce a dangling separator.
    if out.ends_with('_') && out.len() > "kernel_".len() {
        out.pop();
    }
    out
}

/// Early dispatch for `#[ktstr_test]` test execution.
///
/// Runs before `main()` in any binary that links against ktstr.
///
/// When running as PID 1 (the binary is `/init` in the VM), calls
/// `ktstr_guest_init()` which handles the full init lifecycle and never
/// returns.
///
/// - `--ktstr-test-fn=NAME --ktstr-topo=NnNlNcNt`: host-side dispatch —
///   boots a VM with the specified topology and runs the test inside it.
/// - `--ktstr-test-fn=NAME` (without `--ktstr-topo`): guest-side dispatch —
///   runs the test function directly (inside a VM that was already booted).
/// - nextest protocol (`--list`/`--exact`): intercepted when running
///   under nextest (`NEXTEST` env var set), delegates to [`ktstr_main`].
/// - Otherwise: no-op (falls through to the standard test harness).
#[doc(hidden)]
#[ctor::ctor]
pub fn ktstr_test_early_dispatch() {
    // PID 1: the binary is /init in the VM. Perform full init lifecycle
    // (mounts, scheduler, test dispatch, reboot). Never returns.
    if unsafe { libc::getpid() } == 1 {
        crate::vmm::rust_init::ktstr_guest_init();
    }

    // Export-self dispatch runs BEFORE host/guest test dispatch.
    // `cargo ktstr export` is a router that exec's the test binary
    // with `--ktstr-export-test=NAME`; the binary reads its own
    // `KTSTR_TESTS` registry, embeds itself via `current_exe`, and
    // writes the .run file. Running this check first means the
    // export path never accidentally triggers VM boot if the
    // operator simultaneously passes `--ktstr-test-fn` (the export
    // arg wins because export is a one-shot tool, not a test
    // execution).
    if let Some(code) = maybe_dispatch_export() {
        std::process::exit(code);
    }
    if let Some(code) = maybe_dispatch_host_test() {
        std::process::exit(code);
    }
    // Propagate RUST_BACKTRACE / RUST_LOG from /proc/cmdline before
    // `maybe_dispatch_vm_test` runs: ctor context is single-threaded
    // (`.init_array` runs before any user thread exists), so this
    // `set_var` is sound and the later guest-side code that spawns
    // the probe thread observes the correct env.
    propagate_rust_env_from_cmdline();
    if let Some(code) = maybe_dispatch_vm_test() {
        // The LLVM profiling runtime registers its atexit handler via a
        // .init_array entry (C++ global initializer). Our ctor also lives
        // in .init_array, and the execution order between them is
        // non-deterministic. If our ctor runs first, the atexit handler
        // was never registered, so std::process::exit() won't write the
        // profraw. Serialize profraw to a buffer and write it to the SHM
        // ring for host-side extraction.
        try_flush_profraw();
        std::process::exit(code);
    }

    // nextest protocol: intercept --list and --exact when running under
    // nextest. Under cargo test, fall through to the standard harness
    // which runs the #[test] wrappers generated by #[ktstr_test].
    //
    // Binaries with real #[ktstr_test] entries need the ctor to handle
    // listing (gauntlet expansion) and dispatch (VM booting). The lib
    // test binary has only the dummy entry and no gauntlet variants —
    // skip interception so the standard harness discovers #[cfg(test)]
    // module #[test] functions (unit tests).
    //
    // For `--list`, ktstr_main prints the gauntlet/ktstr names and
    // RETURNS so the standard libtest harness can print its own list
    // of `#[test]` items afterward. This makes plain `#[test]`
    // functions inside a ktstr_test integration-test binary visible
    // to nextest — without the fall-through, libtest never runs and
    // those test names are silently dropped from the listing.
    //
    // For `--exact`, ktstr_main runs only when the test name starts
    // with `ktstr/` or `gauntlet/` — names ktstr owns. Other names
    // (libtest #[test] items, including the per-entry wrappers
    // emitted by `#[ktstr_test]` itself) fall through to libtest's
    // dispatch. Without this guard, run_named_test would fail
    // `find_test` for a plain `#[test]` name and exit 1, blocking
    // nextest from running it.
    if std::env::var_os("NEXTEST").is_some() {
        let has_real_tests = KTSTR_TESTS.iter().any(|e| !is_test_sentinel(e.name));
        if has_real_tests {
            let args: Vec<String> = std::env::args().collect();
            if args.iter().any(|a| a == "--list") {
                ktstr_list_only();
                list_plain_tests();
                std::process::exit(0);
            } else if let Some(pos) = args.iter().position(|a| a == "--exact")
                && let Some(name) = args.get(pos + 1)
                && (name.starts_with("ktstr/") || name.starts_with("gauntlet/"))
            {
                let bare = name
                    .strip_prefix("ktstr/")
                    .or_else(|| name.strip_prefix("gauntlet/"))
                    .unwrap_or(name)
                    .split('/')
                    .next()
                    .unwrap_or(name);

                // Reject malformed names like `gauntlet/` (trailing slash,
                // no test name) and `ktstr/`. Writing an empty replacement
                // into argv would null-terminate at offset 0, leaving an
                // empty string libtest would fail to match against any
                // `#[test]` wrapper — surfacing as an opaque "no test
                // matches" error instead of a clear malformed-name error.
                if bare.is_empty() {
                    eprintln!(
                        "ktstr: malformed --exact test name {name:?} \
                         (resolves to an empty bare name after prefix strip)",
                    );
                    std::process::exit(1);
                }

                *DEFERRED_DISPATCH.lock().unwrap() = Some(name.to_string());
                rewrite_argv_exact(pos + 1, bare);
            }
        }
    } else {
        // cargo-test-direct path: the standard rustc test harness
        // runs only the bare `#[test]` wrappers `#[ktstr_test]`
        // generates. Gauntlet expansion (flag-profile × topology-
        // preset combinations) lives inside `ktstr_main`'s `--list`
        // + `--exact` handlers and is reachable ONLY under nextest.
        // Every real ktstr entry produces topology-preset variants
        // under nextest (`for_each_gauntlet_variant` iterates
        // `crate::vm::gauntlet_presets()` regardless of whether the
        // scheduler declares flags — the flag set only determines
        // the profile half of the `presets × profiles` product).
        // Without nextest those variants would silently not run —
        // coverage loss with no error. Emit a one-shot stderr
        // `warning:` diagnostic (see the `eprintln!` below) when the
        // binary carries any real entry so the user sees the gap
        // instead of trusting a false green. Print once per process
        // (cargo test invokes one test binary per crate; the ctor
        // runs exactly once per test binary) so there is no need to
        // gate with a std::sync::Once.
        //
        // `KTSTR_CARGO_TEST_MODE=1` opts out of the warning: the
        // operator deliberately picked the cargo-test-direct path
        // (e.g. for a single-test debug iteration without the
        // nextest harness) and accepts that gauntlet variants
        // won't run. The warning is still emitted under bare
        // `cargo test` without the env var set so unaware users
        // see the coverage gap.
        if !super::runtime::cargo_test_mode_active() {
            let total = KTSTR_TESTS.len();
            let real = KTSTR_TESTS
                .iter()
                .filter(|e| !is_test_sentinel(e.name))
                .count();
            if real > 0 {
                eprintln!(
                    "warning: {real} of {total} ktstr test entries registered in this binary \
                     will not generate their flag-profile / topology-preset gauntlet variants — \
                     NEXTEST env var is not set and the standard rustc harness does not expand \
                     them. Use `cargo nextest run` (or `cargo ktstr test`) to exercise the full \
                     gauntlet, or set KTSTR_CARGO_TEST_MODE=1 to opt into single-variant \
                     bare-`cargo test` mode without this warning.",
                );
            }
        }
    }
}

/// Predicate for "this entry is a unit-test sentinel, not a real
/// `#[ktstr_test]` user entry." The lib-test binary registers a
/// single sentinel entry (currently `"__unit_test_dummy__"`) so
/// the dispatch + gauntlet plumbing has something to exercise
/// under `cargo test --lib`; real user entries look like
/// `"module::test_name"` or similar PascalCase-with-dots names.
///
/// Matching the sentinel by convention (`__` prefix + `__`
/// suffix + `_test_` or `_dummy_` infix) rather than by literal
/// equality keeps the filter robust when the sentinel is
/// renamed, or when future scaffolding adds additional
/// sentinel-shaped entries (e.g. `__unit_test_panics__`,
/// `__unit_test_timeout__`). The literal-equality form would
/// silently admit those future sentinels into the real-entry
/// population and double-fire the "NEXTEST env var not set"
/// warning or spuriously enable --list interception.
fn is_test_sentinel(name: &str) -> bool {
    // Real user-authored `#[ktstr_test]` entry names
    // conventionally do not match the `__unit_test_*__` pattern
    // (Rust's reserved-identifier convention for
    // language-implementation and framework-internal names).
    // The `#[ktstr_test]` proc macro does not validate this, so
    // the predicate admits a real user entry in the unlikely
    // case someone names one with the `__unit_test_*__` shape —
    // collision would double-fire the "NEXTEST env var not set"
    // warning / spuriously enable --list interception, but
    // that's a diagnostic glitch, not a correctness failure.
    name.starts_with("__unit_test_") && name.ends_with("__")
}

/// Export-self dispatch: if `--ktstr-export-test=NAME` is present in
/// argv, look up `NAME` in the binary's own `KTSTR_TESTS` registry,
/// build a self-extracting `.run` file embedding `current_exe()`
/// (this binary), and exit. Returns `Some(exit_code)` when dispatched,
/// `None` when the flag is absent.
///
/// `cargo ktstr export <NAME>` (the cargo-ktstr binary) is a router
/// that compiles the workspace's tests, locates the test binary that
/// owns `NAME`, and exec's it with this arg. The test binary embeds
/// ITSELF — without that indirection, cargo-ktstr would package its
/// own binary, which has no `#[ktstr_test]` registrations from the
/// user's crate and can't reproduce the test on bare metal.
///
/// `--ktstr-export-output=PATH` overrides the default output path
/// (`<NAME>.run` in the cwd). Both flags are leniently parsed by the
/// helpers in `args.rs`; an empty NAME (`--ktstr-export-test=`)
/// surfaces with diagnostic "requires a non-empty test name" and
/// exit 1 so the router moves on to the next candidate.
///
/// # Exit-code contract
///
/// The router (`cargo-ktstr.rs::run_export`) discriminates between
/// "this binary doesn't know the test" (exit 1) and "this binary
/// has the test but rejects it" (exit 2). When ANY candidate exits
/// 2, the router surfaces THAT candidate's stderr (the rejection
/// reason: host_only, bpf_map_write, KernelBuiltin) rather than
/// the generic "not found in any workspace test binary" message.
/// Without the differentiation, an operator who exports a
/// host_only test would see the misleading "not found" diagnostic
/// even though the test exists.
fn maybe_dispatch_export() -> Option<i32> {
    let args: Vec<String> = std::env::args().collect();
    let name = extract_export_test_arg(&args)?;
    let output = extract_export_output_arg(&args).map(std::path::PathBuf::from);

    // Empty name: surface as a hard error rather than silently
    // succeeding. The router's "first binary that exits 0 wins"
    // protocol relies on the absent-test path returning a non-zero
    // exit so the next candidate is tried.
    if name.is_empty() {
        eprintln!("ktstr export: --ktstr-export-test= requires a non-empty test name");
        return Some(1);
    }

    // Look up the test ourselves so we can discriminate "not
    // registered here" (exit 1, router falls through) from
    // "registered but rejected" (exit 2, router surfaces this
    // stderr). `export_test` itself returns anyhow::Error for both
    // cases, which would conflate them at the exit-code level.
    if find_test(name).is_none() {
        eprintln!("ktstr export: no registered test named '{name}'");
        return Some(1);
    }

    match crate::export::export_test(name, output) {
        Ok(()) => Some(0),
        Err(e) => {
            eprintln!("ktstr export: {e:#}");
            // The test exists in this binary but the export pipeline
            // refused it (host_only / bpf_map_write / KernelBuiltin /
            // I/O error). Exit 2 so the router prefers this stderr
            // over a sibling binary's exit-1 "not registered" miss.
            Some(2)
        }
    }
}

/// Host-side dispatch: if both `--ktstr-test-fn` and `--ktstr-topo` are
/// present, boot a VM with the specified topology and run the test
/// inside it. Returns `Some(exit_code)` if dispatched, `None` otherwise.
fn maybe_dispatch_host_test() -> Option<i32> {
    let args: Vec<String> = std::env::args().collect();
    let name = extract_test_fn_arg(&args)?;
    let topo_str = extract_topo_arg(&args)?;

    let entry = match find_test(name) {
        Some(e) => e,
        None => {
            eprintln!("ktstr_test: unknown test function '{name}'");
            return Some(1);
        }
    };

    let (numa_nodes, llcs, cores, threads) = match parse_topo_string(&topo_str) {
        Some(t) => t,
        None => {
            eprintln!(
                "ktstr_test: invalid --ktstr-topo format '{topo_str}' (expected NnNlNcNt, e.g. 1n2l4c2t)"
            );
            return Some(1);
        }
    };

    let cpus = llcs * cores * threads;
    let memory_mb = (cpus * 64).max(256).max(entry.memory_mb);
    let topo = TopoOverride {
        numa_nodes,
        llcs,
        cores,
        threads,
        memory_mb,
    };

    let active_flags = extract_flags_arg(&args).unwrap_or_default();
    match run_ktstr_test_with_topo_and_flags(entry, &topo, &active_flags) {
        Ok(_) => Some(0),
        Err(e) => {
            eprintln!("ktstr_test: {e:#}");
            Some(1)
        }
    }
}

/// Host-side entry point: build a VM, boot it with `--ktstr-test-fn=NAME`,
/// extract profraw from SHM, and return the test result.
///
/// Validates KVM access and auto-discovers a kernel image via
/// `resolve_test_kernel()` when `KTSTR_TEST_KERNEL` is not set.
pub fn run_ktstr_test(entry: &KtstrTestEntry) -> Result<AssertResult> {
    // Directly-constructed entries bypass the proc-macro's
    // compile-time checks. Call `validate` here so programmatic
    // consumers (library callers pushing into `KTSTR_TESTS`
    // dynamically) hit the same bail messages the macro produces at
    // compile time.
    entry.validate()?;

    // Check if the ctor deferred a prefixed dispatch name via argv
    // rewrite. If so, resolve the topology and flags from the full
    // gauntlet/multi-kernel name instead of using the entry defaults.
    if let Some(deferred) = DEFERRED_DISPATCH.lock().unwrap().take() {
        return run_deferred_dispatch(entry, &deferred);
    }

    if entry.host_only {
        return run_host_only_test_inner(entry);
    }
    if !entry.bpf_map_write.is_empty()
        && let Ok(kernel) = resolve_test_kernel()
        && crate::vmm::find_vmlinux(&kernel).is_none()
    {
        anyhow::bail!("vmlinux not found, bpf_map_write requires vmlinux");
    }
    let active_flags: Vec<String> = entry.required_flags.iter().map(|s| s.to_string()).collect();
    run_ktstr_test_inner(entry, None, &active_flags)
}

/// Dispatch a test using the full prefixed name that the ctor stored
/// in [`DEFERRED_DISPATCH`] before rewriting argv. Resolves gauntlet
/// topology, multi-kernel suffix, and flag profile from the name,
/// then calls `run_ktstr_test_inner` directly — NOT through the
/// `run_named_test` → `result_to_exit_code` path, so
/// `ResourceContention` propagates as `Err` rather than being
/// swallowed as exit code 0. Called at main-time from the `#[test]`
/// wrapper, so C++ static constructors have completed.
fn run_deferred_dispatch(_entry: &KtstrTestEntry, deferred_name: &str) -> Result<AssertResult> {
    let kernel_list = read_kernel_list();
    let (test_name, kernel_entry) = strip_kernel_suffix(deferred_name, &kernel_list)
        .map_err(|e| anyhow::anyhow!("deferred dispatch for '{deferred_name}': {e}"))?;
    if let Some(ke) = kernel_entry {
        export_kernel_for_variant(ke);
    }

    if let Some(rest) = test_name.strip_prefix("gauntlet/") {
        let parts: Vec<&str> = rest.splitn(3, '/').collect();
        anyhow::ensure!(parts.len() == 3, "invalid gauntlet name: gauntlet/{rest}");
        let (bare, preset_name, profile_name) = (parts[0], parts[1], parts[2]);
        let entry = find_test(bare).ok_or_else(|| anyhow::anyhow!("unknown test: {bare}"))?;
        let presets = crate::vm::gauntlet_presets();
        let preset = presets
            .iter()
            .find(|p| p.name == preset_name)
            .ok_or_else(|| anyhow::anyhow!("unknown preset: {preset_name}"))?;
        let t = &preset.topology;
        let memory_mb = (t.total_cpus() * 64).max(256).max(entry.memory_mb);
        let topo = TopoOverride {
            numa_nodes: t.numa_nodes,
            llcs: t.llcs,
            cores: t.cores_per_llc,
            threads: t.threads_per_core,
            memory_mb,
        };
        let profiles = entry
            .scheduler
            .generate_profiles(entry.required_flags, entry.excluded_flags);
        let flags: Vec<String> = profiles
            .iter()
            .find(|p| p.name() == profile_name)
            .map(|p| p.flags.iter().map(|s| s.to_string()).collect())
            .unwrap_or_default();
        return run_ktstr_test_inner(entry, Some(&topo), &flags);
    }

    let bare = test_name.strip_prefix("ktstr/").unwrap_or(test_name);
    let entry = find_test(bare).ok_or_else(|| anyhow::anyhow!("unknown test: {bare}"))?;
    let active_flags: Vec<String> = entry.required_flags.iter().map(|s| s.to_string()).collect();
    run_ktstr_test_inner(entry, None, &active_flags)
}

/// Like `run_ktstr_test` but with an explicit topology override and
/// active flags that map to scheduler CLI args via
/// `Scheduler::flag_args()`. Only consumed inside this module by
/// `maybe_dispatch_host_test`; kept as a named helper so the
/// `--ktstr-test-fn` + `--ktstr-topo` dispatch path reads symmetrically
/// with the zero-override [`run_ktstr_test`] library entry point.
fn run_ktstr_test_with_topo_and_flags(
    entry: &KtstrTestEntry,
    topo: &TopoOverride,
    active_flags: &[String],
) -> Result<AssertResult> {
    run_ktstr_test_inner(entry, Some(topo), active_flags)
}

/// Run a test result through expect_err logic and return an exit code.
///
/// Returns 0 on pass, 1 on failure. `ResourceContention` returns
/// 0 — the test never ran, not a real failure. The skip sidecar for
/// this case is written upstream in `run_ktstr_test_inner` at the
/// ResourceContention propagation site so every caller (including
/// the library entry point `run_ktstr_test`) records it, not just
/// the nextest dispatch path.
///
/// `ResourceContention` detection walks the FULL error chain via
/// [`is_resource_contention`] (chain-walk predicate) plus a
/// matching `e.chain().find_map(...)` extraction for the reason
/// string. The eval-side `eval.rs` `"build ktstr_test VM"` and
/// `"run ktstr_test VM"` wrappers nest the contention error under
/// `.context(...)`, so a top-level `downcast_ref` on the outer
/// error misses the inner cause. Without the chain walk a wrapped
/// contention would land in the `Err(e)` arm below as a regular
/// failure (exit 1) rather than the skip path (exit 0), turning
/// every host-resource-exhausted run into a hard test failure.
fn result_to_exit_code(result: Result<AssertResult>, expect_err: bool) -> i32 {
    let no_skip = std::env::var_os("KTSTR_NO_SKIP_MODE").is_some();
    match result {
        Ok(_) if expect_err => {
            eprintln!("expected error but test passed");
            1
        }
        Ok(_) => 0,
        Err(e) if is_resource_contention(&e) => {
            let reason = e
                .chain()
                .find_map(|c| {
                    c.downcast_ref::<crate::vmm::host_topology::ResourceContention>()
                        .map(|rc| rc.reason.clone())
                })
                .unwrap_or_else(|| "<unknown>".to_string());
            if no_skip {
                eprintln!(
                    "ktstr: FAIL: resource contention under --no-skip-mode: {reason}. \
                     Either provision hardware that satisfies the test's topology \
                     requirement, or drop --no-skip-mode / KTSTR_NO_SKIP_MODE to \
                     accept the skip."
                );
                1
            } else {
                crate::report::test_skip(format_args!("resource contention: {reason}"));
                0
            }
        }
        Err(e) if is_topology_insufficient(&e) => {
            if no_skip {
                eprintln!(
                    "ktstr: FAIL: host topology insufficient under --no-skip-mode: {e:#}. \
                     Either provision a host with the required CPU / LLC count, or drop \
                     --no-skip-mode / KTSTR_NO_SKIP_MODE to accept the skip."
                );
                1
            } else {
                crate::report::test_skip(format_args!("host topology insufficient: {e:#}"));
                0
            }
        }
        Err(_) if expect_err => 0,
        Err(e) => {
            eprintln!("{e:#}");
            1
        }
    }
}

/// Whether a base test entry is "ignored" (skipped by default).
///
/// Tests whose names start with `demo_` are ignored -- they are
/// demonstration/benchmarking tests that require manual opt-in.
fn is_ignored(entry: &KtstrTestEntry) -> bool {
    entry.name.starts_with("demo_")
}

/// Walk [`KTSTR_TESTS`] once per process and emit a stderr
/// `warning:` line for every duplicate `name` found.
///
/// Two entries with the same name would both match `find_test(name)`
/// (which returns the FIRST match), so the second registration is
/// silently shadowed — `cargo ktstr` would dispatch the first entry
/// and the second entry's body would never run, with no diagnostic
/// surfaced. The warning surfaces the collision so an operator can
/// rename one of the `#[ktstr_test]` functions; discovery itself
/// proceeds (find_test's first-wins behavior continues) so nextest's
/// `--list` output still lands in stdout. A panic here would abort
/// the whole listing — nextest would see no tests at all rather
/// than a partial set with a clear warning. The first-wins
/// shadowing remains a real bug, but the diagnostic is louder than
/// silence and the tradeoff (operator sees the warning AND a
/// usable test list) beats the alternative (operator sees a
/// panic backtrace and no test list).
///
/// `OnceLock<()>` gates the walk to fire EXACTLY ONCE per process:
/// every gauntlet variant resolves through `list_tests` (under
/// nextest's discovery and budget paths), so without the gate a
/// run with N variants would re-walk the slice N times and emit
/// the same warning N times. Each duplicate name surfaces exactly
/// once via the inner `seen`/`warned` HashSet pair so a
/// triple-collision (three entries sharing one name) does not
/// double-print the warning.
///
/// The pure detection logic lives in
/// [`warn_duplicate_test_names_inner`] so the duplicate-walker
/// is testable without process-wide global state. This wrapper
/// only owns the `OnceLock<()>` gate and the
/// `(KTSTR_TESTS, stderr)` plumbing.
fn warn_duplicate_test_names_once() {
    static CHECKED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
    CHECKED.get_or_init(|| {
        warn_duplicate_test_names_inner(KTSTR_TESTS.iter().map(|e| e.name), &mut std::io::stderr());
    });
}

/// Pure walker behind [`warn_duplicate_test_names_once`]: walks
/// the test-name iterator and emits one `warning:` line per
/// duplicate name to `sink`. Each duplicate name surfaces
/// exactly once (a triple-collision does NOT double-print)
/// via the inner `warned` HashSet.
///
/// Extracted from the OnceLock-gated wrapper so the duplicate
/// detection logic is testable without process-wide global
/// state — the wrapper handles "fire once per process" via its
/// own `OnceLock<()>` gate; this inner is a pure function over
/// `(names, sink)`. The wrapper passes
/// `KTSTR_TESTS.iter().map(|e| e.name)` as the iterator and
/// `std::io::stderr()` as the sink.
///
/// `Result<(), std::io::Error>` is collapsed to ignore-on-write
/// because the production wrapper writes to stderr where IO
/// errors are unrecoverable; tests pass a `Vec<u8>` sink which
/// never errors. The function name says "warn" — diagnostic
/// channel — and matches the wrapper's pre-existing
/// `eprintln!` semantics.
fn warn_duplicate_test_names_inner<'a, W: std::io::Write>(
    names: impl IntoIterator<Item = &'a str>,
    sink: &mut W,
) {
    use std::collections::HashSet;
    let names: Vec<&'a str> = names.into_iter().collect();
    let mut seen: HashSet<&'a str> = HashSet::with_capacity(names.len());
    let mut warned: HashSet<&'a str> = HashSet::new();
    for name in names {
        if !seen.insert(name) && warned.insert(name) {
            let _ = writeln!(
                sink,
                "warning: ktstr_test: duplicate test name {name:?} registered in KTSTR_TESTS — \
                 two `#[ktstr_test]` entries share this name; the SECOND entry is \
                 silently shadowed (find_test returns the first registration). \
                 rename one of the functions to disambiguate.",
            );
        }
    }
}

/// Collect test names for nextest discovery (--list --format terse).
///
/// Nextest calls the binary twice:
/// - Without `--ignored`: prints ALL tests (ignored and non-ignored).
/// - With `--ignored`: prints ONLY ignored tests.
///
/// Gauntlet variants are always ignored. Base tests are ignored when
/// their name starts with `demo_`.
///
/// When `KTSTR_BUDGET_SECS` is set, applies greedy coverage maximization
/// to select the subset of tests that maximizes feature coverage within
/// the time budget. Only selected tests are printed.
///
/// Calls [`warn_duplicate_test_names_once`] on the first invocation per
/// process so duplicate registrations surface a stderr `warning:`
/// line BEFORE any test name is printed (discovery itself proceeds
/// — find_test's first-wins behavior continues, but the operator
/// sees which name collided). Subsequent invocations are no-ops via
/// the inner `OnceLock` gate.
fn list_tests(ignored_only: bool) {
    warn_duplicate_test_names_once();
    let raw = std::env::var("KTSTR_BUDGET_SECS").ok();
    let budget_secs: Option<f64> = raw.as_deref().and_then(|s| match s.parse::<f64>() {
        Ok(v) if v > 0.0 => Some(v),
        Ok(v) => {
            eprintln!("ktstr_test: KTSTR_BUDGET_SECS={v}: must be positive, ignoring");
            None
        }
        Err(e) => {
            eprintln!("ktstr_test: KTSTR_BUDGET_SECS={s:?}: {e}, ignoring");
            None
        }
    });

    if let Some(budget) = budget_secs {
        list_tests_budget(ignored_only, budget);
    } else {
        list_tests_all(ignored_only);
    }
}

/// Host capacity inputs for `TopologyConstraints::accepts`.
///
/// `list_tests_all` and `list_tests_budget` both need the same
/// `(cpus, llcs, max_cpus_per_llc)` triple to filter gauntlet presets
/// against what the host can actually schedule. Reading sysfs here
/// once per listing (instead of per-entry) keeps the signal-to-noise
/// of each lister high and makes the host-query decision explicit.
fn host_capacity() -> (u32, u32, u32) {
    let host_cpus = std::thread::available_parallelism()
        .map(|n| n.get() as u32)
        .unwrap_or(1);
    let host_topo = crate::vmm::host_topology::HostTopology::from_sysfs().ok();
    let host_llcs = host_topo
        .as_ref()
        .map(|t| t.llc_groups.len() as u32)
        .unwrap_or(1);
    let host_max_cpus_per_llc = host_topo
        .as_ref()
        .map(|t| t.max_cores_per_llc() as u32)
        .unwrap_or(host_cpus);
    (host_cpus, host_llcs, host_max_cpus_per_llc)
}

/// Iterate (preset, profile) pairs that both fit the host capacity
/// and match the entry's `TopologyConstraints`. Shared between the
/// eager ("print every name") and budgeted ("push a candidate")
/// listers in `list_tests_*`.
fn for_each_gauntlet_variant<F>(
    entry: &KtstrTestEntry,
    presets: &[crate::vm::TopoPreset],
    host_cpus: u32,
    host_llcs: u32,
    host_max_cpus_per_llc: u32,
    mut visit: F,
) where
    F: FnMut(&crate::vm::TopoPreset, &crate::scenario::FlagProfile),
{
    let profiles = entry
        .scheduler
        .generate_profiles(entry.required_flags, entry.excluded_flags);
    let no_perf_mode = super::runtime::no_perf_mode_for_entry(entry);
    for preset in presets {
        // No-perf-mode tests run KVM-emulated topology — guest sees the
        // declared NUMA / LLC / per-LLC layout regardless of host
        // hardware — so the host-side LLC count and per-LLC CPU width
        // do not constrain preset eligibility. Only the total-CPU
        // budget survives.
        let accepted = if no_perf_mode {
            entry
                .constraints
                .accepts_no_perf_mode(&preset.topology, host_cpus)
        } else {
            entry.constraints.accepts(
                &preset.topology,
                host_cpus,
                host_llcs,
                host_max_cpus_per_llc,
            )
        };
        if !accepted {
            continue;
        }
        for profile in &profiles {
            visit(preset, profile);
        }
    }
}

/// List all tests without budget filtering.
///
/// When `KTSTR_KERNEL_LIST` carries 2 or more entries, every test
/// name carries an extra `/{sanitized_kernel_label}` suffix so each
/// (test × kernel) pair becomes a distinct nextest test case;
/// nextest's parallelism, retries, and `-E` filtering all apply
/// natively. Single-kernel mode (0 or 1 entries) preserves the
/// historical `gauntlet/{name}/{preset}/{profile}` shape so existing
/// CI baselines, test-name filters, and per-test config overrides
/// keep matching.
///
/// `KTSTR_CARGO_TEST_MODE=1` skips gauntlet variant emission and
/// the multi-kernel suffix path: each test gets exactly one
/// `ktstr/{name}: test` line. Bare `cargo test` doesn't have
/// access to the cargo-ktstr resolver that produces
/// `KTSTR_KERNEL_LIST`, so the multi-kernel branch can't apply
/// even if it were enabled — pin both behaviors explicitly so
/// the listing matches what the dispatch path will actually run.
fn list_tests_all(ignored_only: bool) {
    let cargo_test_mode = super::runtime::cargo_test_mode_active();
    let presets = crate::vm::gauntlet_presets();
    let has_vmlinux = resolve_test_kernel()
        .ok()
        .and_then(|k| crate::vmm::find_vmlinux(&k))
        .is_some();
    let (host_cpus, host_llcs, host_max_cpus_per_llc) = host_capacity();

    let kernel_list = read_kernel_list();
    let multi_kernel = kernel_list.len() > 1 && !cargo_test_mode;
    // Single-kernel mode (no list, or list has exactly one entry)
    // emits one variant per (test × preset × profile) tuple with no
    // kernel suffix. Multi-kernel mode iterates every kernel as an
    // outer loop and appends `/{sanitized}` per variant. The empty-
    // suffix sentinel below is what the single-kernel branch passes
    // to keep the print path uniform.
    let kernel_suffixes: Vec<&str> = if multi_kernel {
        kernel_list.iter().map(|k| k.sanitized.as_str()).collect()
    } else {
        vec![""]
    };

    for entry in KTSTR_TESTS.iter() {
        validate_entry_flags(entry);

        // bpf_map_write tests require vmlinux to resolve BPF map
        // addresses. Don't list them when vmlinux is unavailable —
        // they cannot run and would produce false PASS results.
        if !entry.bpf_map_write.is_empty() && !has_vmlinux {
            continue;
        }

        if !ignored_only || is_ignored(entry) {
            if entry.host_only {
                println!("ktstr/{}: test", entry.name);
            } else {
                for suffix in &kernel_suffixes {
                    if suffix.is_empty() {
                        println!("ktstr/{}: test", entry.name);
                    } else {
                        println!("ktstr/{}/{suffix}: test", entry.name);
                    }
                }
            }
        }

        // Host-only tests run on the host without a VM -- gauntlet
        // topology variants are meaningless.
        if entry.host_only {
            continue;
        }

        // KTSTR_CARGO_TEST_MODE: skip gauntlet expansion. The
        // operator picked the bare-`cargo test` path; emit only
        // the base name so each `#[ktstr_test]` runs once with its
        // declared topology.
        if cargo_test_mode {
            continue;
        }

        // Gauntlet variants are always ignored — users opt in with
        // --run-ignored. Presets that exceed the host's CPU count or
        // LLC count are filtered from the listing entirely.
        for_each_gauntlet_variant(
            entry,
            &presets,
            host_cpus,
            host_llcs,
            host_max_cpus_per_llc,
            |preset, profile| {
                for suffix in &kernel_suffixes {
                    if suffix.is_empty() {
                        println!(
                            "gauntlet/{}/{}/{}: test",
                            entry.name,
                            preset.name,
                            profile.name()
                        );
                    } else {
                        println!(
                            "gauntlet/{}/{}/{}/{suffix}: test",
                            entry.name,
                            preset.name,
                            profile.name()
                        );
                    }
                }
            },
        );
    }
}

/// List tests with budget-based coverage maximization.
///
/// Collects all eligible tests as candidates, runs greedy selection,
/// and prints only the selected subset. Multi-kernel mode adds the
/// kernel suffix as a feature dimension so the budget selector
/// picks per-kernel coverage; single-kernel mode is unchanged.
///
/// `KTSTR_CARGO_TEST_MODE=1` is treated identically to
/// `list_tests_all`: the budget pipeline runs only over base test
/// candidates (no gauntlet-variant candidates, no multi-kernel
/// fan-out). The greedy selector still applies — a low budget
/// can still trim the base list — but the candidate set is the
/// same set that the dispatch path would actually run.
fn list_tests_budget(ignored_only: bool, budget_secs: f64) {
    use crate::budget::{TestCandidate, estimate_duration, extract_features, select};

    let cargo_test_mode = super::runtime::cargo_test_mode_active();
    let presets = crate::vm::gauntlet_presets();
    let has_vmlinux = resolve_test_kernel()
        .ok()
        .and_then(|k| crate::vmm::find_vmlinux(&k))
        .is_some();
    let (host_cpus, host_llcs, host_max_cpus_per_llc) = host_capacity();
    let mut candidates: Vec<TestCandidate> = Vec::new();

    let kernel_list = read_kernel_list();
    let multi_kernel = kernel_list.len() > 1 && !cargo_test_mode;
    let kernel_suffixes: Vec<&str> = if multi_kernel {
        kernel_list.iter().map(|k| k.sanitized.as_str()).collect()
    } else {
        vec![""]
    };

    for entry in KTSTR_TESTS.iter() {
        validate_entry_flags(entry);

        if !entry.bpf_map_write.is_empty() && !has_vmlinux {
            continue;
        }

        let base_ignored = is_ignored(entry);
        let base_topo = entry.topology;

        // Base test
        if !ignored_only || base_ignored {
            // host_only tests never boot a VM, so the kernel never
            // affects what runs — push one candidate without a
            // kernel suffix even in multi-kernel mode. Otherwise the
            // budget selector would consider N identical copies of
            // the same host-side function.
            if entry.host_only {
                candidates.push(TestCandidate {
                    name: format!("ktstr/{}: test", entry.name),
                    features: extract_features(entry, &base_topo, &[], false, entry.name),
                    estimated_secs: estimate_duration(entry, &base_topo),
                });
            } else {
                for suffix in &kernel_suffixes {
                    let name = if suffix.is_empty() {
                        format!("ktstr/{}: test", entry.name)
                    } else {
                        format!("ktstr/{}/{suffix}: test", entry.name)
                    };
                    candidates.push(TestCandidate {
                        name,
                        features: extract_features(entry, &base_topo, &[], false, entry.name),
                        estimated_secs: estimate_duration(entry, &base_topo),
                    });
                }
            }
        }

        if entry.host_only {
            continue;
        }

        if cargo_test_mode {
            // No gauntlet candidates in cargo-test mode — the
            // dispatch path will never execute them and including
            // them in the budget candidate set would shift greedy
            // selection toward variants that resolve to "no test"
            // at run time.
            continue;
        }

        for_each_gauntlet_variant(
            entry,
            &presets,
            host_cpus,
            host_llcs,
            host_max_cpus_per_llc,
            |preset, profile| {
                for suffix in &kernel_suffixes {
                    let test_name = if suffix.is_empty() {
                        format!("gauntlet/{}/{}/{}", entry.name, preset.name, profile.name())
                    } else {
                        format!(
                            "gauntlet/{}/{}/{}/{suffix}",
                            entry.name,
                            preset.name,
                            profile.name(),
                        )
                    };
                    candidates.push(TestCandidate {
                        name: format!("{test_name}: test"),
                        features: extract_features(
                            entry,
                            &preset.topology,
                            &profile.flags,
                            true,
                            &test_name,
                        ),
                        estimated_secs: estimate_duration(entry, &preset.topology),
                    });
                }
            },
        );
    }

    let selected = select(&candidates, budget_secs);
    for &i in &selected {
        println!("{}", candidates[i].name);
    }

    let stats = crate::budget::selection_stats(&candidates, &selected, budget_secs);
    eprintln!(
        "ktstr budget: {}/{} tests, {:.0}/{:.0}s used, {}/{} configurations covered",
        stats.selected,
        stats.total,
        stats.budget_used,
        stats.budget_total,
        stats.bits_covered,
        stats.bits_possible,
    );
}

/// Strip an optional `/{sanitized_kernel_label}` suffix from `name`,
/// look up the matching [`KernelEntry`] in the multi-kernel list,
/// and re-export `KTSTR_KERNEL` to that entry's directory. Returns
/// the prefix-only name for the dispatch caller.
///
/// When `KTSTR_KERNEL_LIST` is unset / single-entry, the function
/// is a no-op pass-through: returns `(name, None)` and does not
/// touch the env. When the list has 2+ entries, the suffix is
/// REQUIRED and missing it surfaces as `Err` (the early-dispatch
/// caller turns that into exit code 1 with an actionable message)
/// — the suffix is part of every test name `--list` emitted, so a
/// `--exact` invocation that omits it can only come from operator
/// hand-construction or tooling that hasn't been taught the
/// multi-kernel naming.
fn strip_kernel_suffix<'a>(
    name: &'a str,
    kernel_list: &'a [KernelEntry],
) -> Result<(&'a str, Option<&'a KernelEntry>), String> {
    if kernel_list.len() <= 1 {
        return Ok((name, None));
    }
    // Multi-kernel: every test name carries `/kernel_…` as its
    // final segment. Iterate the labels rather than splitting on
    // `/` — the suffix always has exactly one extra `/` separator
    // before `kernel_…`, but the body of the test name CAN contain
    // `/` (gauntlet variants already do), so a naive
    // `rsplit_once('/')` would accidentally peel the gauntlet's
    // profile segment instead.
    //
    // Distinct kernels in the same `KTSTR_KERNEL_LIST` produce
    // distinct sanitized labels in practice — the producer emits
    // semantic identifiers (version strings, git owner/repo/ref,
    // path basename + 6-char hash) that don't share suffixes
    // among the resolved set. If a future regression DID produce
    // labels where one is a strict suffix of another (e.g.
    // `kernel_6_14` vs `kernel_x_kernel_6_14`), the iterate-and-
    // first-match below would pick whichever appears first in
    // the kernel_list — deterministic but potentially wrong.
    // Producer-side regression detection would catch that
    // class of collision before it reaches this peeler.
    for entry in kernel_list {
        let needle = format!("/{}", entry.sanitized);
        if let Some(stripped) = name.strip_suffix(&needle) {
            return Ok((stripped, Some(entry)));
        }
    }
    Err(format!(
        "test name {name:?} has no recognised kernel suffix (KTSTR_KERNEL_LIST \
         carries {n} kernels — every test name must end with `/kernel_…`)",
        n = kernel_list.len(),
    ))
}

/// Re-export `KTSTR_KERNEL` to the kernel directory carried by a
/// resolved [`KernelEntry`]. Called when a multi-kernel `--exact`
/// dispatch peels off the per-test kernel suffix.
///
/// SAFETY: nextest invokes the test binary's `--exact` handler in a
/// single-threaded context — there are no other readers of the env
/// at this point. The eventual VM-launch site reads `KTSTR_KERNEL`
/// via `find_kernel` after this returns; that read is sequenced
/// after the write per the program order.
fn export_kernel_for_variant(entry: &KernelEntry) {
    // SAFETY: see fn-level doc — single-threaded ctor / nextest
    // dispatch context.
    unsafe { std::env::set_var(crate::KTSTR_KERNEL_ENV, &entry.kernel_dir) };
}

/// Parse a nextest-style test name and run it.
///
/// Handles base tests (`ktstr/{name}`), gauntlet variants
/// (`gauntlet/{name}/{preset}/{profile}`), and bare names
/// (backward compat). When `KTSTR_KERNEL_LIST` carries 2+ kernels,
/// VM-bound test names additionally end with
/// `/{sanitized_kernel_label}` — that suffix is peeled here and
/// the matching kernel directory is re-exported via
/// [`KTSTR_KERNEL_ENV`] before the dispatch continues. `host_only`
/// tests are short-circuited BEFORE the suffix peel: they never
/// boot a VM, so the kernel-suffix listing path emits one
/// `ktstr/{name}: test` entry without a kernel suffix regardless
/// of the kernel-list cardinality (see `list_tests_all` /
/// `list_tests_budget`), and routing them through
/// `strip_kernel_suffix` would surface as a "no recognised kernel
/// suffix" exit-1 error. Returns an exit code.
pub(crate) fn run_named_test(test_name: &str) -> i32 {
    let kernel_list = read_kernel_list();

    // host_only short-circuit: in multi-kernel mode, host_only tests
    // are listed without a `/{sanitized_kernel_label}` suffix (see
    // `list_tests_all` / `list_tests_budget`, which emit a single
    // `ktstr/{name}: test` line for host_only entries regardless of
    // the kernel-list cardinality — a host_only test never boots a
    // VM, so the kernel never affects what runs). Calling
    // `strip_kernel_suffix` on such a name in multi-kernel mode
    // would fail with the "no recognised kernel suffix" error and
    // misroute every host_only dispatch to exit 1.
    //
    // Resolve the host_only check from `find_test` BEFORE the
    // suffix peel so the multi-kernel branch only applies to
    // VM-bound tests. Single-kernel mode is unaffected — the
    // pass-through arm in `strip_kernel_suffix` returns the input
    // verbatim either way.
    let bare_for_lookup = test_name.strip_prefix("ktstr/").unwrap_or(test_name);
    if let Some(entry) = find_test(bare_for_lookup)
        && entry.host_only
    {
        return run_host_only_test(entry);
    }

    let (test_name, kernel_entry) = match strip_kernel_suffix(test_name, &kernel_list) {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("{e}");
            return 1;
        }
    };
    if let Some(entry) = kernel_entry {
        export_kernel_for_variant(entry);
    }

    if let Some(rest) = test_name.strip_prefix("gauntlet/") {
        return run_gauntlet_test(rest);
    }

    let bare_name = test_name.strip_prefix("ktstr/").unwrap_or(test_name);
    let entry = match find_test(bare_name) {
        Some(e) => e,
        None => {
            eprintln!("unknown test: {test_name}");
            return 1;
        }
    };

    // Defense-in-depth: host_only re-check after suffix peel for the
    // edge case where the bare_for_lookup pre-strip lookup missed
    // (e.g. a future test name shape that doesn't match the
    // pre-strip form but does after the suffix peel).
    if entry.host_only {
        return run_host_only_test(entry);
    }

    // Base tests don't carry a gauntlet profile, but the entry's
    // `required_flags` must still be activated for tests whose
    // scheduler-arg contract requires them (per the invariant
    // enforced by validate_entry_flags: every gauntlet profile
    // contains required_flags). Using an empty flags list would run
    // the scheduler without its required CLI args and produce
    // incorrect sidecar metadata.
    let active_flags: Vec<String> = entry.required_flags.iter().map(|s| s.to_string()).collect();

    if entry.performance_mode && super::runtime::no_perf_mode_active() {
        crate::report::test_skip(format_args!(
            "{}: test requires performance_mode but --no-perf-mode or KTSTR_NO_PERF_MODE is active",
            bare_name,
        ));
        // See run_ktstr_test_inner for the sidecar-emission rationale.
        record_skip_sidecar(entry, &active_flags);
        return 0;
    }

    if !entry.bpf_map_write.is_empty()
        && let Ok(kernel) = resolve_test_kernel()
        && crate::vmm::find_vmlinux(&kernel).is_none()
    {
        eprintln!("FAIL: vmlinux not found, bpf_map_write requires vmlinux");
        return 1;
    }

    let result = run_ktstr_test_inner(entry, None, &active_flags);
    result_to_exit_code(result, entry.expect_err)
}

/// Run a host-only test directly without booting a VM.
/// Returns an exit code for nextest dispatch.
fn run_host_only_test(entry: &KtstrTestEntry) -> i32 {
    let result = run_host_only_test_inner(entry);
    result_to_exit_code(result, entry.expect_err)
}

/// Inner host-only dispatch returning `Result<AssertResult>`.
///
/// Builds a minimal Ctx and calls the test function on the host.
/// Used for tests that need host tools (cargo, nested VMs).
fn run_host_only_test_inner(entry: &KtstrTestEntry) -> Result<AssertResult> {
    let topo = crate::topology::TestTopology::from_vm_topology(&entry.topology);
    let cgroups = crate::cgroup::CgroupManager::new("/sys/fs/cgroup/ktstr");
    let workers_per_cgroup = entry.workers_per_cgroup as usize;
    let merged_assert = crate::assert::Assert::default_checks()
        .merge(entry.scheduler.assert())
        .merge(&entry.assert);
    let ctx = crate::scenario::Ctx::builder(&cgroups, &topo)
        .duration(entry.duration)
        .workers_per_cgroup(workers_per_cgroup)
        .settle(std::time::Duration::ZERO)
        .assert(merged_assert)
        .build();
    (entry.func)(&ctx)
}

/// Run a gauntlet variant test. `rest` is `{name}/{preset}/{profile}`.
pub(crate) fn run_gauntlet_test(rest: &str) -> i32 {
    let parts: Vec<&str> = rest.splitn(3, '/').collect();
    if parts.len() != 3 {
        eprintln!("invalid gauntlet test name: gauntlet/{rest}");
        return 1;
    }
    let (test_name, preset_name, profile_name) = (parts[0], parts[1], parts[2]);

    let entry = match find_test(test_name) {
        Some(e) => e,
        None => {
            eprintln!("unknown test: {test_name}");
            return 1;
        }
    };
    validate_entry_flags(entry);

    let presets = crate::vm::gauntlet_presets();
    let preset = match presets.iter().find(|p| p.name == preset_name) {
        Some(p) => p,
        None => {
            eprintln!("unknown gauntlet preset: {preset_name}");
            return 1;
        }
    };

    let t = &preset.topology;
    let cpus = t.total_cpus();

    let memory_mb = (cpus * 64).max(256).max(entry.memory_mb);
    let topo = TopoOverride {
        numa_nodes: t.numa_nodes,
        llcs: t.llcs,
        cores: t.cores_per_llc,
        threads: t.threads_per_core,
        memory_mb,
    };

    let profiles = entry
        .scheduler
        .generate_profiles(entry.required_flags, entry.excluded_flags);
    let flags: Vec<String> = match profiles.iter().find(|p| p.name() == profile_name) {
        Some(p) => p.flags.iter().map(|s| s.to_string()).collect(),
        None => {
            eprintln!("unknown flag profile: {profile_name}");
            return 1;
        }
    };

    if entry.performance_mode && super::runtime::no_perf_mode_active() {
        crate::report::test_skip(format_args!(
            "{}: test requires performance_mode but --no-perf-mode or KTSTR_NO_PERF_MODE is active",
            test_name,
        ));
        record_skip_sidecar(entry, &flags);
        return 0;
    }

    if !entry.bpf_map_write.is_empty()
        && let Ok(kernel) = resolve_test_kernel()
        && crate::vmm::find_vmlinux(&kernel).is_none()
    {
        eprintln!("FAIL: vmlinux not found, bpf_map_write requires vmlinux");
        return 1;
    }

    let result = run_ktstr_test_inner(entry, Some(&topo), &flags);
    result_to_exit_code(result, entry.expect_err)
}

/// Collect sidecar JSON files and return the full gauntlet analysis.
///
/// When `dir` is `Some`, reads sidecars from that directory. Otherwise
/// uses the default sidecar directory (`KTSTR_SIDECAR_DIR` override, or
/// `{CARGO_TARGET_DIR or "target"}/ktstr/{kernel}-{project_commit}/`,
/// where `{project_commit}` is the project HEAD short hex with
/// `-dirty` when the worktree differs).
///
/// Returns the concatenated output of `analyze_rows`, verifier stats,
/// callback profile, and KVM stats. Returns an empty string when no
/// sidecars are found.
pub fn analyze_sidecars(dir: Option<&std::path::Path>) -> String {
    let default_dir;
    let dir = match dir {
        Some(d) => d,
        None => {
            default_dir = sidecar_dir();
            &default_dir
        }
    };
    let sidecars = collect_sidecars(dir);
    if sidecars.is_empty() {
        return String::new();
    }
    let mut out = String::new();
    let rows: Vec<_> = sidecars.iter().map(crate::stats::sidecar_to_row).collect();
    if !rows.is_empty() {
        out.push_str(&crate::stats::analyze_rows(&rows));
    }
    let vstats = format_verifier_stats(&sidecars);
    if !vstats.is_empty() {
        out.push_str(&vstats);
    }
    let cprofile = format_callback_profile(&sidecars);
    if !cprofile.is_empty() {
        out.push_str(&cprofile);
    }
    let kstats = format_kvm_stats(&sidecars);
    if !kstats.is_empty() {
        out.push_str(&kstats);
    }
    out
}

/// Discover plain `#[test]` items by re-invoking the binary without
/// NEXTEST, reading libtest's `--list` output, and printing only
/// names that don't match any KTSTR_TESTS entry. This lets plain
/// tests coexist with `#[ktstr_test]` in the same binary without
/// duplicating the ktstr entries.
fn list_plain_tests() {
    use std::collections::HashSet;
    let ktstr_names: HashSet<&str> = KTSTR_TESTS.iter().map(|e| e.name).collect();

    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(_) => return,
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.env_remove("NEXTEST");
    cmd.args(["--list", "--format", "terse"]);
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::null());
    let output = match cmd.output() {
        Ok(o) => o,
        Err(_) => return,
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        let name = line.strip_suffix(": test").unwrap_or(line);
        if !ktstr_names.contains(name) && !name.is_empty() {
            println!("{line}");
        }
    }
}

/// `--list` subprotocol: emit ktstr/gauntlet test names without
/// exiting so the standard libtest harness can also print its own
/// test list afterward. This is what makes plain `#[test]` items
/// inside a ktstr_test integration-test binary visible to nextest.
///
/// Honours `--ignored` the same way [`ktstr_main`] does — when set,
/// only the ignored subset (gauntlet variants and `demo_` base
/// tests) is printed. Unlike `ktstr_main`, this function returns to
/// the caller after listing so the ctor's caller can fall through
/// to libtest's `main`.
fn ktstr_list_only() {
    let args: Vec<String> = std::env::args().collect();
    let ignored_only = args.iter().any(|a| a == "--ignored");
    list_tests(ignored_only);
}

/// Nextest protocol handler.
///
/// Called automatically by [`ktstr_test_early_dispatch`] when running
/// under nextest with `--exact <ktstr_or_gauntlet_name>`.
/// Not intended for direct use.
///
/// - `--list --format terse`: output `ktstr/{name}: test\n` for base
///   tests and `gauntlet/{name}/{preset}/{profile}: test\n` for
///   gauntlet variants. (Discovery uses [`ktstr_list_only`] instead
///   to allow libtest to print its own list afterward; this branch
///   is preserved for direct callers of `ktstr_main`.)
/// - `--exact NAME --nocapture`: run the named test, exit 0/1.
pub fn ktstr_main() -> ! {
    let args: Vec<String> = std::env::args().collect();

    // Discovery mode: --list --format terse [--ignored]
    if args.iter().any(|a| a == "--list") {
        let ignored_only = args.iter().any(|a| a == "--ignored");
        list_tests(ignored_only);
        std::process::exit(0);
    }

    // Execution mode: --exact NAME [--nocapture] [--ignored] [--bench]
    if let Some(pos) = args.iter().position(|a| a == "--exact") {
        if let Some(name) = args.get(pos + 1) {
            let code = run_named_test(name);
            std::process::exit(code);
        }
        eprintln!("--exact requires a test name");
        std::process::exit(1);
    }

    // Fallback: no recognized arguments.
    eprintln!("usage: <binary> --list --format terse [--ignored]");
    eprintln!("       <binary> --exact <test_name> --nocapture");
    std::process::exit(1)
}

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

    // ---------------------------------------------------------------
    // is_test_sentinel — convention-based sentinel-name predicate
    // ---------------------------------------------------------------

    /// Accepted shapes: `__unit_test_*__` (the established
    /// sentinel convention — double-underscore prefix with
    /// `unit_test_` tag, arbitrary inner suffix, double-underscore
    /// suffix).
    #[test]
    fn is_test_sentinel_accepts_convention_shaped_names() {
        assert!(is_test_sentinel("__unit_test_dummy__"));
        assert!(is_test_sentinel("__unit_test_panics__"));
        // Any inner body after the prefix is accepted, as long as
        // the `__` suffix is also present.
        assert!(is_test_sentinel("__unit_test_foo_bar_baz__"));
    }

    /// Rejected shapes: real user names, unrelated
    /// double-underscore names, and partial matches.
    #[test]
    fn is_test_sentinel_rejects_non_convention_names() {
        // Real user-authored name.
        assert!(!is_test_sentinel("my_test"));
        // Double-underscore wrapping but not the `__unit_test_` tag.
        assert!(!is_test_sentinel("__foo__"));
        // Empty string.
        assert!(!is_test_sentinel(""));
        // Has the prefix but no `__` suffix (ends with just `_`).
        assert!(!is_test_sentinel("__unit_test_"));
        // Has the prefix, has `__` suffix, but the prefix itself
        // is truncated — missing the trailing `_` of `__unit_test_`.
        assert!(!is_test_sentinel("__unit__"));
    }

    // ---------------------------------------------------------------
    // run_named_test / run_gauntlet_test — nextest dispatch routing
    // ---------------------------------------------------------------
    //
    // These tests cover the `test_name → function` routing without
    // booting a VM. The happy paths require KVM and a kernel image,
    // so the assertions here target the failure branches that return
    // exit code 1 before any VM spawn:
    //   - `ktstr/` prefix with unknown bare name
    //   - `gauntlet/` prefix with malformed parts / unknown preset /
    //     unknown profile
    //   - bare names fall through to `ktstr/` lookup
    //
    // The routing invariant: `gauntlet/` always delegates to
    // `run_gauntlet_test`, every other prefix (including none)
    // delegates to the base-test path inside `run_named_test`.

    #[test]
    fn run_named_test_gauntlet_prefix_routes_to_run_gauntlet_test() {
        // Gauntlet names require three slash-separated parts after
        // the prefix; a name missing them is rejected by
        // `run_gauntlet_test`, proving the prefix routed there and
        // not into the base-test path (which would print
        // `unknown test: gauntlet/...` instead of the gauntlet-
        // specific error and still return 1 but via a different
        // branch).
        let exit = run_named_test("gauntlet/__unit_test_dummy__");
        assert_eq!(exit, 1, "malformed gauntlet names must exit 1");
    }

    #[test]
    fn run_named_test_bare_unknown_exits_nonzero() {
        // `run_named_test` strips `ktstr/` when present; a bare
        // unknown name falls through to `find_test` which returns
        // None, producing exit code 1.
        let exit = run_named_test("__definitely_not_a_real_test__");
        assert_eq!(exit, 1);
    }

    #[test]
    fn run_named_test_ktstr_prefix_unknown_exits_nonzero() {
        // `ktstr/` prefix is stripped; the bare name (also unknown)
        // returns 1 via the find_test None path.
        let exit = run_named_test("ktstr/__definitely_not_a_real_test__");
        assert_eq!(exit, 1);
    }

    #[test]
    fn run_gauntlet_test_rejects_name_with_fewer_than_three_parts() {
        // `rest` must split into exactly 3 parts
        // (`{name}/{preset}/{profile}`). Two parts is a format error.
        let exit = run_gauntlet_test("some_test/some_preset");
        assert_eq!(exit, 1);
    }

    #[test]
    fn run_gauntlet_test_rejects_empty_rest() {
        // Empty rest splits into one empty string — also a format
        // error.
        let exit = run_gauntlet_test("");
        assert_eq!(exit, 1);
    }

    #[test]
    fn run_gauntlet_test_rejects_unknown_test_name() {
        // Well-formed three-part name whose test is not registered
        // in KTSTR_TESTS. Returns 1 via the find_test None branch,
        // never reaching preset lookup or VM spawn.
        let exit = run_gauntlet_test("__not_a_test__/tiny-1llc/default");
        assert_eq!(exit, 1);
    }

    #[test]
    fn run_gauntlet_test_rejects_unknown_preset() {
        // `__unit_test_dummy__` is registered in test_support::tests;
        // combined with a preset name that is not in
        // `gauntlet_presets`, the function returns 1 at the preset-
        // lookup branch.
        let exit = run_gauntlet_test("__unit_test_dummy__/__no_such_preset__/__default__");
        assert_eq!(exit, 1);
    }

    // ---------------------------------------------------------------
    // warn_duplicate_test_names_inner — pure duplicate-walker
    // ---------------------------------------------------------------
    //
    // The OnceLock-gated `warn_duplicate_test_names_once` wrapper is
    // process-wide and reads `KTSTR_TESTS` directly, so its emit-once
    // semantics aren't observable from a unit test (the gate may
    // already have fired from the production listing path during
    // nextest discovery, or from a sibling test in this file). The
    // pure inner walker is exposed exactly so its detection logic
    // is testable without that global state — these tests pin the
    // dedup invariants that actually matter:
    //   1. No duplicates → no output (zero-emit on clean input).
    //   2. Each duplicate name surfaces EXACTLY once even when the
    //      same name appears 3+ times (the warned-set prevents
    //      double-prints).
    //   3. The emitted line embeds the offending name in
    //      double-quoted form (the canonical `{name:?}` debug
    //      format the production message uses) so tooling can
    //      grep operator output for the collision.
    //   4. Distinct duplicate names each produce one line —
    //      independent collision groups must not blur into one.
    //   5. An empty input is a no-op (defensive: exhaust early
    //      before any HashSet alloc).

    /// No duplicates → empty sink. Pins the zero-emit base case.
    #[test]
    fn warn_duplicate_test_names_inner_no_duplicates_writes_nothing() {
        let mut sink = Vec::<u8>::new();
        warn_duplicate_test_names_inner(["alpha", "beta", "gamma"], &mut sink);
        assert!(
            sink.is_empty(),
            "clean input must produce zero diagnostic bytes; got {:?}",
            String::from_utf8_lossy(&sink),
        );
    }

    /// Empty input → no walking, no output. Defensive against a
    /// regression that would crash on a zero-element HashSet
    /// allocation or emit a spurious line on the empty path.
    #[test]
    fn warn_duplicate_test_names_inner_empty_input_writes_nothing() {
        let mut sink = Vec::<u8>::new();
        warn_duplicate_test_names_inner(std::iter::empty::<&str>(), &mut sink);
        assert!(
            sink.is_empty(),
            "empty input must emit nothing; got {:?}",
            String::from_utf8_lossy(&sink),
        );
    }

    /// One duplicate name appearing twice → exactly one warning
    /// line containing the duplicated name. Pins the basic
    /// emit-on-collision contract.
    #[test]
    fn warn_duplicate_test_names_inner_emits_warning_for_duplicate() {
        let mut sink = Vec::<u8>::new();
        warn_duplicate_test_names_inner(["alpha", "beta", "alpha"], &mut sink);
        let out = String::from_utf8(sink).expect("sink is utf-8");
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(
            lines.len(),
            1,
            "single duplicate must emit exactly one line; got {lines:?}",
        );
        let line = lines[0];
        assert!(
            line.contains("warning: ktstr_test:"),
            "warning prefix must be present (operator-actionable signal); \
             got line: {line:?}",
        );
        // The duplicated name must appear in the canonical `{name:?}`
        // double-quoted form so grep tooling can pull it out.
        assert!(
            line.contains("\"alpha\""),
            "the duplicated name must appear in quoted form; got: {line:?}",
        );
        assert!(
            !line.contains("\"beta\""),
            "non-duplicate names must NOT appear in any warning; got: {line:?}",
        );
    }

    /// A triple-collision (same name appearing 3 times) emits the
    /// warning EXACTLY ONCE — the inner `warned` HashSet
    /// suppresses the second and third occurrences. Pins the
    /// "one warning per duplicated name" contract documented on
    /// the public wrapper.
    #[test]
    fn warn_duplicate_test_names_inner_triple_collision_emits_once() {
        let mut sink = Vec::<u8>::new();
        warn_duplicate_test_names_inner(["dup", "dup", "dup"], &mut sink);
        let out = String::from_utf8(sink).expect("sink is utf-8");
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(
            lines.len(),
            1,
            "triple-collision must emit exactly one warning, not one-per-extra; \
             got {lines:?} — a regression that drops the warned-set guard would \
             surface here as 2 lines (one for the second, one for the third).",
        );
        assert!(
            lines[0].contains("\"dup\""),
            "warning must name the duplicated entry; got: {:?}",
            lines[0],
        );
    }

    /// Two distinct duplicate names → two warning lines (one per
    /// collision group). A regression that collapses every
    /// duplicate into a single warning would surface here as one
    /// line instead of two.
    #[test]
    fn warn_duplicate_test_names_inner_independent_duplicates_each_warn() {
        let mut sink = Vec::<u8>::new();
        warn_duplicate_test_names_inner(["alpha", "beta", "alpha", "gamma", "beta"], &mut sink);
        let out = String::from_utf8(sink).expect("sink is utf-8");
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(
            lines.len(),
            2,
            "two independent collision groups must produce two warnings; \
             got {lines:?}",
        );
        let body = lines.join("\n");
        assert!(
            body.contains("\"alpha\""),
            "first duplicate name must appear in output; got: {body:?}",
        );
        assert!(
            body.contains("\"beta\""),
            "second duplicate name must appear in output; got: {body:?}",
        );
        assert!(
            !body.contains("\"gamma\""),
            "non-duplicate `gamma` must NOT trigger a warning; got: {body:?}",
        );
    }

    // -- host_capacity --

    #[test]
    fn host_capacity_returns_plausible_triple() {
        // `host_capacity` reads `available_parallelism` and sysfs topology.
        // The exact values depend on the test host, but the invariants
        // hold on any sane Linux machine:
        //   - cpus >= 1
        //   - llcs >= 1 (at least one cache domain)
        //   - max_cpus_per_llc >= 1
        //   - max_cpus_per_llc <= cpus (no LLC wider than the whole host)
        let (cpus, llcs, max_cpus_per_llc) = host_capacity();
        assert!(cpus >= 1, "cpus >= 1, got {cpus}");
        assert!(llcs >= 1, "llcs >= 1, got {llcs}");
        assert!(
            max_cpus_per_llc >= 1,
            "max_cpus_per_llc >= 1, got {max_cpus_per_llc}"
        );
        assert!(
            max_cpus_per_llc <= cpus,
            "max_cpus_per_llc ({max_cpus_per_llc}) must not exceed cpus ({cpus})"
        );
    }

    // -- for_each_gauntlet_variant --

    #[test]
    fn for_each_gauntlet_variant_skips_presets_exceeding_host_capacity() {
        // Pass host_cpus=1/host_llcs=1 against the preset list: every
        // current preset has total_cpus >= 4 (see `gauntlet_presets()`
        // in src/vm.rs), so every preset fails
        // `TopologyConstraints::accepts` and `visit` must never be
        // called. Any entry works since the constraint check runs
        // before the visit — use the test dummy.
        let presets = crate::vm::gauntlet_presets();
        // Precondition for the assertion below: if a future preset
        // with total_cpus <= 1 is added, this test must be updated to
        // account for it instead of silently under-asserting.
        let every_preset_needs_more_than_one_cpu = presets
            .iter()
            .all(|p| p.topology.total_cpus() > 1 || p.topology.llcs > 1);
        assert!(
            presets.is_empty() || every_preset_needs_more_than_one_cpu,
            "test assumes every preset requires >1 CPU or >1 LLC; \
             found a single-CPU preset — update the assertion below"
        );

        let mut visited: Vec<String> = Vec::new();
        for_each_gauntlet_variant(
            find_test("__unit_test_dummy__").unwrap(),
            &presets,
            1,
            1,
            1,
            |preset, _| visited.push(preset.name.to_string()),
        );
        assert!(
            visited.is_empty(),
            "with host_cpus=1 host_llcs=1, no preset should be visited; \
             visited: {visited:?}"
        );
    }

    #[test]
    fn for_each_gauntlet_variant_visits_every_fitting_preset_x_profile() {
        // With generous host capacity (u32::MAX cpus/llcs), every
        // preset that the dummy entry's constraints accept yields at
        // least one `FlagProfile` visit (every scheduler generates a
        // default profile when no flags are required/excluded).
        let presets = crate::vm::gauntlet_presets();
        let mut count = 0;
        for_each_gauntlet_variant(
            find_test("__unit_test_dummy__").unwrap(),
            &presets,
            u32::MAX,
            u32::MAX,
            u32::MAX,
            |_, _| count += 1,
        );
        // `__unit_test_dummy__` defaults to Payload::KERNEL_DEFAULT
        // (which wraps Scheduler::EEVDF) and Scheduler::EEVDF has no
        // flags → exactly one profile per accepted preset.
        // Asserting `count >= 1` proves at least one preset was
        // accepted and visited. Coupling to the exact preset count
        // would fail if the preset list changes.
        if !presets.is_empty() {
            assert!(
                count >= 1,
                "expected at least one visit with unlimited host capacity, got {count}"
            );
        }
    }

    #[test]
    fn for_each_gauntlet_variant_monotonic_in_host_capacity() {
        // Comparative-baseline: giving the function MORE host capacity
        // can only let MORE presets pass the cap-size filter, never
        // fewer. The upper-bound assertion in
        // `for_each_gauntlet_variant_skips_presets_exceeding_host_capacity`
        // and the lower-bound assertion in
        // `..._visits_every_fitting_preset_x_profile` both check one
        // extreme; this test anchors the monotonic relationship
        // between them. A regression that inverted the host-cap
        // comparison (e.g. `host_cpus < preset_cpus` → accept) would
        // pass both endpoint tests but fail here.
        let presets = crate::vm::gauntlet_presets();
        if presets.is_empty() {
            return;
        }
        let entry = find_test("__unit_test_dummy__").unwrap();
        let count_for = |cpus: u32, llcs: u32| {
            let mut n = 0;
            for_each_gauntlet_variant(entry, &presets, cpus, llcs, u32::MAX, |_, _| n += 1);
            n
        };
        let tight = count_for(1, 1);
        let loose = count_for(u32::MAX, u32::MAX);
        assert!(
            loose >= tight,
            "host-capacity monotonicity violated: tight=(1,1) yielded {tight} \
             visits, loose=(u32::MAX,u32::MAX) yielded {loose}; loose \
             must admit at least as many presets as tight",
        );
    }

    // ---------------------------------------------------------------
    // KTSTR_KERNEL_LIST parsing + sanitization + suffix dispatch
    // ---------------------------------------------------------------

    #[test]
    fn parse_kernel_list_empty_returns_empty() {
        assert!(parse_kernel_list("").is_empty());
        assert!(parse_kernel_list(";").is_empty());
        assert!(parse_kernel_list(";;;").is_empty());
        assert!(parse_kernel_list("   ").is_empty());
    }

    #[test]
    fn parse_kernel_list_basic_pair() {
        // Producer emits semantic labels (the version string for
        // Version specs); the parser is shape-agnostic and just
        // splits on `;` and `=` then sanitizes. A version-only
        // label sanitizes to `kernel_6_14_2`.
        let entries = parse_kernel_list("6.14.2=/cache/foo");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].kernel_dir, PathBuf::from("/cache/foo"));
        assert_eq!(entries[0].sanitized, "kernel_6_14_2");
    }

    #[test]
    fn parse_kernel_list_two_entries() {
        let entries = parse_kernel_list("6.14.2=/a;6.15.0=/b");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].kernel_dir, PathBuf::from("/a"));
        assert_eq!(entries[0].sanitized, "kernel_6_14_2");
        assert_eq!(entries[1].kernel_dir, PathBuf::from("/b"));
        assert_eq!(entries[1].sanitized, "kernel_6_15_0");
    }

    #[test]
    fn parse_kernel_list_drops_malformed() {
        // Missing `=`, empty label, empty path — all silently
        // dropped. Producer is `cargo ktstr` which encodes the
        // format under our control; a malformed entry indicates a
        // regression in the producer rather than operator input
        // that deserves a clear error.
        let entries = parse_kernel_list("noeq;=onlypath;onlylabel=;valid=/foo");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].kernel_dir, PathBuf::from("/foo"));
    }

    #[test]
    fn parse_kernel_list_trims_whitespace() {
        let entries = parse_kernel_list("  6.14.2=/a  ;  6.15.0=/b  ");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].sanitized, "kernel_6_14_2");
        assert_eq!(entries[1].sanitized, "kernel_6_15_0");
    }

    #[test]
    fn sanitize_kernel_label_pure_version() {
        assert_eq!(sanitize_kernel_label("6.14.2"), "kernel_6_14_2");
    }

    #[test]
    fn sanitize_kernel_label_rc_suffix() {
        assert_eq!(sanitize_kernel_label("6.15-rc3"), "kernel_6_15_rc3");
    }

    /// The sanitizer is shape-agnostic — it normalizes any input
    /// that happens to flow in. The producer-side encoder now
    /// emits semantic labels, but a future regression that
    /// surfaced a raw cache-key basename would still produce a
    /// valid (if uglier) nextest identifier rather than crashing.
    /// Pinned via a synthetic full-cache-key input.
    #[test]
    fn sanitize_kernel_label_handles_full_cache_key_shape() {
        assert_eq!(
            sanitize_kernel_label("6.14.2-tarball-x86_64-kcabc1234"),
            "kernel_6_14_2_tarball_x86_64_kcabc1234",
        );
    }

    /// Git-source semantic label `git_tj_sched_ext_for-next` from
    /// the producer-side encoder maps to the dash-stripped form
    /// the sanitizer produces.
    #[test]
    fn sanitize_kernel_label_git_semantic_label() {
        assert_eq!(
            sanitize_kernel_label("git_tj_sched_ext_for-next"),
            "kernel_git_tj_sched_ext_for_next",
        );
    }

    /// Path-source semantic label `path_linux_a3f2b1` is already
    /// `[a-z0-9_]+` so the sanitizer only adds the `kernel_`
    /// prefix.
    #[test]
    fn sanitize_kernel_label_path_semantic_label() {
        assert_eq!(
            sanitize_kernel_label("path_linux_a3f2b1"),
            "kernel_path_linux_a3f2b1",
        );
    }

    #[test]
    fn sanitize_kernel_label_lowercases() {
        assert_eq!(sanitize_kernel_label("ABC-DEF"), "kernel_abc_def");
    }

    #[test]
    fn sanitize_kernel_label_collapses_repeated_separators() {
        assert_eq!(sanitize_kernel_label("a..b...c"), "kernel_a_b_c");
    }

    #[test]
    fn sanitize_kernel_label_strips_trailing_underscore() {
        assert_eq!(sanitize_kernel_label("for-next-"), "kernel_for_next");
    }

    #[test]
    fn sanitize_kernel_label_empty_input() {
        assert_eq!(sanitize_kernel_label(""), "kernel_");
    }

    // ---------------------------------------------------------------
    // SanitizedKernelLabel — newtype invariants
    // ---------------------------------------------------------------
    //
    // `SanitizedKernelLabel::new(raw)` is the only production
    // path that yields a value of the type, and it always routes
    // through `sanitize_kernel_label`. The tests below pin each
    // surface (constructor, accessors, `PartialEq` impls) directly
    // so a regression that bypassed the sanitizer (e.g. a future
    // `From<String>` impl that wraps verbatim) or dropped one of
    // the comparison-ergonomics impls would surface as a unit-test
    // failure rather than as a downstream filter mismatch.

    /// `SanitizedKernelLabel::new(raw)` yields a value whose
    /// `as_str()` equals `sanitize_kernel_label(raw)` byte-for-
    /// byte. Pins the constructor's "always sanitize" contract:
    /// the only path that builds a `SanitizedKernelLabel` MUST run
    /// `sanitize_kernel_label`, otherwise a future caller could
    /// stuff a raw label into the field via a regression that
    /// forgot to invoke the sanitizer. Multiple inputs covered to
    /// distinguish "happens to match" from "truly routes through
    /// the sanitizer" — version, RC suffix, mixed case, embedded
    /// dots-vs-dashes.
    #[test]
    fn sanitized_kernel_label_new_runs_sanitizer() {
        for raw in [
            "6.14.2",
            "6.15-rc3",
            "ABC-DEF",
            "git_tj_sched_ext_for-next",
            "",
        ] {
            let label = SanitizedKernelLabel::new(raw);
            assert_eq!(
                label.as_str(),
                sanitize_kernel_label(raw),
                "SanitizedKernelLabel::new({raw:?}).as_str() must equal \
                 sanitize_kernel_label({raw:?}); a regression that wrapped \
                 raw input verbatim would surface here",
            );
        }
    }

    /// `as_str()` returns the sanitized inner string, NOT the raw
    /// input. Round-trip through `as_str()` matches what the
    /// sanitizer produced — distinct from
    /// `sanitized_kernel_label_new_runs_sanitizer` which checks
    /// the constructor wires through; this checks that read-side
    /// access exposes the SAME bytes the constructor wrote.
    #[test]
    fn sanitized_kernel_label_as_str_returns_sanitized_form() {
        let label = SanitizedKernelLabel::new("6.14.2");
        assert_eq!(label.as_str(), "kernel_6_14_2");
        // A regression that returned the raw input from `as_str()`
        // would surface here because the raw input contains `.`
        // which is `_` after sanitization.
        assert_ne!(label.as_str(), "6.14.2");
    }

    /// `PartialEq<&str>` lets `assert_eq!(label, "kernel_6_14_2")`
    /// stay readable at every consumer (and is what
    /// `parse_kernel_list_*` tests already use). A regression that
    /// dropped or narrowed the impl (e.g. switched to `PartialEq<
    /// String>` only) would force every consumer to chain
    /// `.as_str()` and break the existing test suite.
    #[test]
    fn sanitized_kernel_label_partial_eq_with_str_ref() {
        let label = SanitizedKernelLabel::new("6.14.2");
        let want: &str = "kernel_6_14_2";
        assert_eq!(label, want);
        // Symmetric inequality: distinct sanitization output must
        // NOT compare equal to a different `&str`.
        let other: &str = "kernel_6_15_0";
        assert_ne!(label, other);
    }

    /// `PartialEq<str>` covers the unsized-`str` comparison path
    /// (e.g. dereferenced `String` slice) distinct from the
    /// `&str` path above. Both impls are explicit because Rust's
    /// auto-deref to `&str` does not bridge the `PartialEq<str>`
    /// case for some assert macros / generic comparators. A
    /// regression that dropped just the `PartialEq<str>` impl
    /// would compile most consumer sites but break callers that
    /// land on the unsized form.
    #[test]
    fn sanitized_kernel_label_partial_eq_with_str_unsized() {
        let label = SanitizedKernelLabel::new("6.14.2");
        let owned: String = "kernel_6_14_2".to_string();
        // `*owned` is `str` (unsized) — exercises `PartialEq<str>`
        // rather than `PartialEq<&str>`. Wrap with `&` to satisfy
        // `PartialEq::eq`'s `&Self`-vs-`&Other` shape; the impl
        // body still operates on the unsized `str`.
        assert!(
            label == *owned.as_str(),
            "PartialEq<str> impl missing — assert against unsized str failed",
        );
        // Symmetric inequality for the unsized path.
        let other: String = "kernel_6_15_0".to_string();
        assert!(label != *other.as_str());
    }

    /// `strip_kernel_suffix` is a no-op for single-kernel mode (0 or
    /// 1 entries) — returns the input verbatim and signals "no
    /// kernel override needed."
    #[test]
    fn strip_kernel_suffix_single_kernel_passthrough() {
        let kernel_list = vec![KernelEntry {
            sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_14_2"),
            kernel_dir: PathBuf::from("/a"),
        }];
        let (stripped, entry) =
            strip_kernel_suffix("gauntlet/eevdf/2llc/default", &kernel_list).unwrap();
        assert_eq!(stripped, "gauntlet/eevdf/2llc/default");
        assert!(entry.is_none());

        let (stripped, entry) = strip_kernel_suffix("ktstr/eevdf", &[]).unwrap();
        assert_eq!(stripped, "ktstr/eevdf");
        assert!(entry.is_none());
    }

    /// In multi-kernel mode (2+ entries), the suffix is required and
    /// peeled off. The matching `KernelEntry` is returned.
    #[test]
    fn strip_kernel_suffix_multi_kernel_peels_suffix() {
        let kernel_list = vec![
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_14_2"),
                kernel_dir: PathBuf::from("/a"),
            },
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_15_0"),
                kernel_dir: PathBuf::from("/b"),
            },
        ];
        let (stripped, entry) =
            strip_kernel_suffix("gauntlet/eevdf/2llc/default/kernel_6_14_2", &kernel_list).unwrap();
        assert_eq!(stripped, "gauntlet/eevdf/2llc/default");
        assert_eq!(entry.unwrap().kernel_dir, PathBuf::from("/a"));

        let (stripped, entry) =
            strip_kernel_suffix("gauntlet/eevdf/2llc/default/kernel_6_15_0", &kernel_list).unwrap();
        assert_eq!(stripped, "gauntlet/eevdf/2llc/default");
        assert_eq!(entry.unwrap().kernel_dir, PathBuf::from("/b"));
    }

    /// In multi-kernel mode, a test name that lacks the kernel
    /// suffix surfaces an actionable error rather than silently
    /// using the first kernel — the suffix is part of every test
    /// name `--list` emitted, so a missing suffix indicates
    /// operator hand-construction or stale tooling.
    #[test]
    fn strip_kernel_suffix_multi_kernel_missing_suffix_errors() {
        let kernel_list = vec![
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_14_2"),
                kernel_dir: PathBuf::from("/a"),
            },
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_15_0"),
                kernel_dir: PathBuf::from("/b"),
            },
        ];
        let err = strip_kernel_suffix("gauntlet/eevdf/2llc/default", &kernel_list)
            .expect_err("missing suffix in multi-kernel mode must error");
        assert!(
            err.contains("no recognised kernel suffix"),
            "error must mention missing suffix, got: {err}",
        );
    }

    /// Suffix peeling is anchored at the end of the test name —
    /// gauntlet variants whose body contains `/` (the preset /
    /// profile separator) are not accidentally peeled. A naive
    /// `rsplit_once('/')` would peel the profile segment instead.
    #[test]
    fn strip_kernel_suffix_does_not_peel_profile_segment() {
        let kernel_list = vec![
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_14_2"),
                kernel_dir: PathBuf::from("/a"),
            },
            KernelEntry {
                sanitized: SanitizedKernelLabel::from_pre_sanitized_for_test("kernel_6_15_0"),
                kernel_dir: PathBuf::from("/b"),
            },
        ];
        // The profile name is `default`, NOT `kernel_6_14_2` — the
        // peeler must require an EXACT match against a known
        // sanitized label, not just any `/<word>` ending.
        let (stripped, entry) =
            strip_kernel_suffix("gauntlet/eevdf/2llc/default/kernel_6_14_2", &kernel_list).unwrap();
        // Stripped name still contains all three of the original
        // path segments (eevdf, 2llc, default).
        assert_eq!(stripped, "gauntlet/eevdf/2llc/default");
        assert!(entry.is_some());
    }

    // ---------------------------------------------------------------
    // host_only kernel-suffix skip — multi-kernel listing
    // ---------------------------------------------------------------
    //
    // `list_tests_all` and `list_tests_budget` short-circuit
    // `host_only` entries: a host_only test never boots a VM, so the
    // kernel never affects what runs. Both listers emit ONE entry per
    // host_only test regardless of `KTSTR_KERNEL_LIST` cardinality —
    // otherwise N identical copies of the same host-side function
    // would land in nextest's plan.
    //
    // The tests below register a dedicated `host_only=true` entry in
    // `KTSTR_TESTS` via `linkme::distributed_slice`, set
    // `KTSTR_KERNEL_LIST` to a 2-entry payload, and capture stdout
    // while invoking each lister. The capture asserts the host_only
    // entry name appears EXACTLY once and never with a `/kernel_…`
    // suffix.

    /// Process-wide mutex serializing every stdout-capture call in
    /// this module. `fd 1 → tempfile` redirection is a non-reentrant
    /// process-global mutation — two concurrent callers would see
    /// each other's output land in their sink. Mirrors the
    /// `STDERR_CAPTURE_LOCK` pattern in `test_support::test_helpers`
    /// (see `capture_stderr_serializes_concurrent_callers` for the
    /// rationale and the failure mode without serialization).
    static STDOUT_CAPTURE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// RAII guard that restores the saved stdout fd on Drop, even if
    /// the captured closure panics under the `panic = "unwind"` test
    /// profile. Without this guard a panicking closure would leak the
    /// fd-1 swap and every subsequent stdout write in the test
    /// process would land in the orphaned tempfile. `saved` is
    /// `Option` so Drop can `take()` and consume it without an `&mut`
    /// borrow fight. Mirrors `StderrRestoreGuard` in
    /// `test_support::test_helpers`.
    struct StdoutRestoreGuard {
        saved: Option<std::os::fd::OwnedFd>,
    }
    impl Drop for StdoutRestoreGuard {
        fn drop(&mut self) {
            if let Some(saved) = self.saved.take() {
                let _ = nix::unistd::dup2_stdout(&saved);
            }
        }
    }

    /// Run `f` with stdout redirected to an in-memory tempfile;
    /// return both `f`'s value and the captured bytes. Uses
    /// [`STDOUT_CAPTURE_LOCK`] to serialize against every other
    /// stdout-capture call in this module. The RAII
    /// [`StdoutRestoreGuard`] restores fd 1 even if `f` panics
    /// under `panic = "unwind"`. Mirrors `capture_stderr` in
    /// `test_support::test_helpers`.
    fn capture_stdout<R>(f: impl FnOnce() -> R) -> (R, Vec<u8>) {
        use std::io::{Read, Seek, SeekFrom, Write};
        let _lock = STDOUT_CAPTURE_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let mut sink = tempfile::tempfile().expect("create stdout-capture tempfile");
        // Flush before redirect: println! is line-buffered behind
        // the Stdout lock; pre-call bytes need to reach the
        // ORIGINAL fd 1 or they leak into the captured tempfile.
        std::io::stdout().flush().ok();
        let saved = nix::unistd::dup(std::io::stdout()).expect("dup(stdout)");
        nix::unistd::dup2_stdout(&sink).expect("dup2_stdout(sink)");
        let guard = StdoutRestoreGuard { saved: Some(saved) };
        let result = f();
        std::io::stdout().flush().ok();
        drop(guard);
        sink.seek(SeekFrom::Start(0)).expect("rewind sink");
        let mut bytes = Vec::new();
        sink.read_to_end(&mut bytes).expect("read sink");
        (result, bytes)
    }

    /// Stub func for the host_only listing-test entry. The listers
    /// never invoke `func` — they only iterate `KTSTR_TESTS` to
    /// emit names — so an Err-returning stub is sufficient and
    /// matches the pattern `default_test_func` uses in
    /// `entry::DEFAULT`. If a future regression accidentally drove
    /// dispatch through this entry, the bail message would surface
    /// the misroute rather than silently passing.
    fn host_only_listing_stub(
        _ctx: &crate::scenario::Ctx,
    ) -> anyhow::Result<crate::assert::AssertResult> {
        anyhow::bail!(
            "host_only_listing_test_entry::func called — entry exists \
             only to drive the host_only kernel-suffix skip tests in \
             list_tests_all / list_tests_budget; func should never run"
        )
    }

    /// Distinct sentinel name so the listing-output filters in the
    /// tests below match this entry and not the `__unit_test_dummy__`
    /// (also registered in `KTSTR_TESTS` from the
    /// `test_support::tests` module) or any other entry that may be
    /// added later. The `__unit_test_…__` shape collides with
    /// `is_test_sentinel` (see the predicate at the top of this
    /// module) so the `cargo test` harness still classifies it as a
    /// sentinel and the early-dispatch warning logic does not
    /// double-fire.
    const HOST_ONLY_LISTING_NAME: &str = "__unit_test_host_only_listing__";

    #[linkme::distributed_slice(KTSTR_TESTS)]
    static __HOST_ONLY_LISTING_ENTRY: KtstrTestEntry = KtstrTestEntry {
        name: HOST_ONLY_LISTING_NAME,
        func: host_only_listing_stub,
        host_only: true,
        ..KtstrTestEntry::DEFAULT
    };

    /// Two-kernel KTSTR_KERNEL_LIST payload reused by the listing
    /// tests below. Both labels sanitize to distinct nextest
    /// suffixes (`kernel_6_14_2`, `kernel_6_15_0`), so a regression
    /// that started emitting `/kernel_…` suffixes for the host_only
    /// entry would surface as either `2` matches (one per kernel)
    /// rather than the expected `1`, or as suffix substrings on the
    /// emitted line.
    const TWO_KERNEL_LIST: &str = "6.14.2=/cache/a;6.15.0=/cache/b";

    /// Filter the captured listing output to only the lines that
    /// reference `HOST_ONLY_LISTING_NAME`. Other lines from the
    /// `__unit_test_dummy__` entry (and from any future entries
    /// registered in this binary's `KTSTR_TESTS`) are intentionally
    /// dropped so the assertions key on this fixture's behaviour
    /// alone.
    fn host_only_listing_lines(captured: &[u8]) -> Vec<String> {
        std::str::from_utf8(captured)
            .expect("capture must be UTF-8")
            .lines()
            .filter(|l| l.contains(HOST_ONLY_LISTING_NAME))
            .map(str::to_owned)
            .collect()
    }

    /// `list_tests_all` in multi-kernel mode emits exactly ONE line
    /// for a `host_only` entry, with NO `/kernel_…` suffix. Pins the
    /// `if entry.host_only { println!("ktstr/{}: test", entry.name); }`
    /// branch at the top of `list_tests_all` against a regression
    /// that fell through into the kernel-suffix loop. A regression
    /// would yield 2 matches (one per kernel) and at least one line
    /// would carry a `/kernel_6_14_2` or `/kernel_6_15_0` suffix.
    ///
    /// Holds [`crate::test_support::test_helpers::lock_env`] for the
    /// full save/mutate/restore window — `KTSTR_KERNEL_LIST` is
    /// process-wide, and the budget-test sibling below also rewrites
    /// env vars. Without the lock, a concurrent test mutating a
    /// different env key could observe a transiently-corrupt
    /// `KTSTR_KERNEL_LIST` value.
    #[test]
    fn list_tests_all_host_only_skips_kernel_suffix_under_multi_kernel() {
        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
        let _env_lock = lock_env();
        let _kernel_list = EnvVarGuard::set(crate::KTSTR_KERNEL_LIST_ENV, TWO_KERNEL_LIST);
        // Suppress the budget-mode branch — `KTSTR_BUDGET_SECS` would
        // route the dispatcher through `list_tests_budget` instead of
        // `list_tests_all`, but we are calling the lister directly so
        // the dispatcher path is irrelevant. Removing the env var here
        // is defensive against a parallel test that set it without
        // restoring (would not affect this call's output, but keeps
        // the test's runtime hypothesis explicit).
        let _budget_guard = EnvVarGuard::remove("KTSTR_BUDGET_SECS");

        let (_, captured) = capture_stdout(|| list_tests_all(false));
        let lines = host_only_listing_lines(&captured);

        assert_eq!(
            lines.len(),
            1,
            "list_tests_all must emit exactly 1 line for a host_only entry \
             under multi-kernel mode (saw {n}): {lines:?}",
            n = lines.len(),
        );
        let line = &lines[0];
        // Expected exact form (mirrors the `println!("ktstr/{}: test", entry.name)`
        // in the host_only branch of `list_tests_all`).
        assert_eq!(
            line,
            &format!("ktstr/{HOST_ONLY_LISTING_NAME}: test"),
            "host_only line must be `ktstr/<name>: test` with no kernel suffix",
        );
        // Belt-and-suspenders: neither sanitized kernel label appears
        // anywhere on the line, even as a substring.
        assert!(
            !line.contains("kernel_6_14_2") && !line.contains("kernel_6_15_0"),
            "host_only line must carry NO sanitized kernel suffix — \
             a regression that emitted `/kernel_…` would surface here. line: {line:?}",
        );
    }

    /// `list_tests_budget` mirror: in multi-kernel mode, the
    /// budget-selecting lister emits exactly ONE candidate for a
    /// `host_only` entry without a kernel suffix. Pins the second
    /// `if entry.host_only { … } else { … }` branch in
    /// `list_tests_budget` against the same regression class as the
    /// `list_tests_all` sibling.
    ///
    /// Budget is set generously (10000 secs) so the greedy selector
    /// in `crate::budget::select` picks every distinct-feature
    /// candidate including this fixture (the `HOST_ONLY_SHIFT` bit
    /// in `extract_features` makes the host_only entry's feature set
    /// uniquely contributory — see `budget::extract_features`).
    /// The selector prints to stdout AND `eprintln!`s a summary
    /// line to stderr; only stdout is captured here, so the stderr
    /// summary lands on the test runner's normal stderr.
    #[test]
    fn list_tests_budget_host_only_skips_kernel_suffix_under_multi_kernel() {
        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
        let _env_lock = lock_env();
        let _kernel_list = EnvVarGuard::set(crate::KTSTR_KERNEL_LIST_ENV, TWO_KERNEL_LIST);

        let (_, captured) = capture_stdout(|| list_tests_budget(false, 10_000.0));
        let lines = host_only_listing_lines(&captured);

        assert_eq!(
            lines.len(),
            1,
            "list_tests_budget must emit exactly 1 candidate line for a \
             host_only entry under multi-kernel mode (saw {n}): {lines:?}",
            n = lines.len(),
        );
        let line = &lines[0];
        assert_eq!(
            line,
            &format!("ktstr/{HOST_ONLY_LISTING_NAME}: test"),
            "host_only candidate name must be `ktstr/<name>: test` with no kernel suffix",
        );
        assert!(
            !line.contains("kernel_6_14_2") && !line.contains("kernel_6_15_0"),
            "host_only candidate must carry NO sanitized kernel suffix — \
             a regression that emitted `/kernel_…` would surface here. line: {line:?}",
        );
    }

    // ---------------------------------------------------------------
    // KTSTR_CARGO_TEST_MODE listing behavior
    // ---------------------------------------------------------------
    //
    // `list_tests_all` and `list_tests_budget` skip gauntlet
    // emission when `KTSTR_CARGO_TEST_MODE` is active. Pins the
    // dispatch contract: bare `cargo test` runs each test once
    // with its declared topology, no preset × profile fan-out.
    // Multi-kernel suffix emission is also suppressed because the
    // cargo-ktstr resolver that produces `KTSTR_KERNEL_LIST` is
    // not on the cargo-test path.

    /// Under `KTSTR_CARGO_TEST_MODE=1`, `list_tests_all` emits
    /// exactly one `ktstr/{name}: test` line per registered entry
    /// — no `gauntlet/...` lines. Pins the gauntlet-skip branch.
    #[test]
    fn list_tests_all_cargo_test_mode_skips_gauntlet() {
        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
        let _env_lock = lock_env();
        let _cargo = EnvVarGuard::set("KTSTR_CARGO_TEST_MODE", "1");
        let _no_kernel_list = EnvVarGuard::remove(crate::KTSTR_KERNEL_LIST_ENV);
        let _budget_guard = EnvVarGuard::remove("KTSTR_BUDGET_SECS");

        let (_, captured) = capture_stdout(|| list_tests_all(false));
        let stdout = std::str::from_utf8(&captured).expect("utf-8");
        let gauntlet_lines: Vec<&str> = stdout
            .lines()
            .filter(|l| l.starts_with("gauntlet/"))
            .collect();
        assert!(
            gauntlet_lines.is_empty(),
            "cargo-test-mode must suppress every `gauntlet/...` line; \
             got {} lines: {gauntlet_lines:?}",
            gauntlet_lines.len(),
        );
    }

    /// Multi-kernel suffix emission is suppressed in
    /// cargo-test mode even when `KTSTR_KERNEL_LIST` is set —
    /// the bare `cargo test` path doesn't drive the cargo-ktstr
    /// resolver, so any `KTSTR_KERNEL_LIST` is a stale leftover
    /// from a prior session and must not influence listing.
    #[test]
    fn list_tests_all_cargo_test_mode_ignores_kernel_list() {
        use crate::test_support::test_helpers::{EnvVarGuard, lock_env};
        let _env_lock = lock_env();
        let _cargo = EnvVarGuard::set("KTSTR_CARGO_TEST_MODE", "1");
        let _kernel_list = EnvVarGuard::set(crate::KTSTR_KERNEL_LIST_ENV, TWO_KERNEL_LIST);
        let _budget_guard = EnvVarGuard::remove("KTSTR_BUDGET_SECS");

        let (_, captured) = capture_stdout(|| list_tests_all(false));
        let stdout = std::str::from_utf8(&captured).expect("utf-8");
        assert!(
            !stdout.contains("kernel_6_14_2") && !stdout.contains("kernel_6_15_0"),
            "cargo-test-mode must suppress multi-kernel suffix emission \
             even when KTSTR_KERNEL_LIST is set; got stdout containing a \
             sanitized kernel label:\n{stdout}",
        );
    }
}