ktstr 0.4.14

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
//! `#[ktstr_test]` entry registration and scheduler configuration.
//!
//! Every `#[ktstr_test]` proc-macro expansion writes a static
//! [`KtstrTestEntry`] into [`KTSTR_TESTS`] via `linkme`; programmatic
//! callers can do the same by pushing their own `KtstrTestEntry` values
//! into the slice. [`find_test`] is the name-to-entry lookup used by
//! host-side dispatch. [`validate_entry_flags`] runs at discovery time
//! to catch flag typos before they produce silent skips.
//!
//! Each entry points at a [`Scheduler`] definition — a `&'static` value
//! that captures the scheduler binary ([`SchedulerSpec`]), flag
//! declarations, guest [`Sysctl`]s, kernel args, [`CgroupPath`] parent,
//! topology and [`TopologyConstraints`], and monitor assertions.
//! [`BpfMapWrite`] describes a host-side map write the runtime performs
//! mid-run.

use anyhow::Result;
use linkme::distributed_slice;
use std::time::Duration;

use crate::assert::AssertResult;
use crate::scenario::Ctx;
use crate::scenario::flags::FlagDecl;

/// Re-exports of topology types for use in [`KtstrTestEntry`] statics
/// generated by the `#[ktstr_test]` macro and `#[derive(Scheduler)]`.
pub use crate::vmm::topology::{MemSideCache, NumaDistance, NumaNode, Topology};

/// How to specify the scheduler for an `#[ktstr_test]`.
///
/// The four variants form a semantic taxonomy, not a syntactic one:
/// [`Eevdf`](Self::Eevdf) is the no-scx control ("kernel default,
/// don't launch anything"); [`Discover`](Self::Discover) and
/// [`Path`](Self::Path) both locate a userspace scheduler binary, by
/// name-lookup vs. explicit filesystem path respectively; and
/// [`KernelBuiltin`](Self::KernelBuiltin) activates an in-kernel
/// scheduling policy via shell commands rather than any binary.
pub enum SchedulerSpec {
    /// No userspace scheduler — run under the kernel's default
    /// scheduler. On current kernels that's EEVDF; the variant
    /// name is fixed so the assertion isn't coupled to the kernel
    /// version's default.
    Eevdf,
    /// Auto-discover the scheduler binary by name (looks in
    /// `KTSTR_SCHEDULER` env, the ktstr binary's sibling dir,
    /// `target/debug/`, `target/release/`, and invokes
    /// `cargo build` if nothing's found).
    Discover(&'static str),
    /// Explicit filesystem path to a scheduler binary. The file must
    /// already exist; `resolve_scheduler` does not auto-build this
    /// variant.
    Path(&'static str),
    /// Kernel-built scheduler (e.g. BPF-less sched_ext or
    /// debugfs-tuned). Activated/deactivated via shell commands
    /// rather than a userspace binary.
    KernelBuiltin {
        /// Shell commands invoked before the scenario runs to switch
        /// the kernel into this scheduling policy (e.g. write to
        /// `/sys/kernel/debug/sched/...`).
        enable: &'static [&'static str],
        /// Shell commands invoked after the scenario finishes to
        /// restore the kernel's baseline scheduling policy.
        disable: &'static [&'static str],
    },
}

impl SchedulerSpec {
    /// Whether this spec represents an active scheduling policy
    /// (anything other than the kernel default EEVDF).
    pub const fn has_active_scheduling(&self) -> bool {
        !matches!(self, SchedulerSpec::Eevdf)
    }

    /// Short, human-readable name for logging and sidecar output.
    ///
    /// Maps `Eevdf` → `"eevdf"`, `Discover(n)` → `n`, `Path(p)` → `p`,
    /// `KernelBuiltin { .. }` → `"kernel"`. Single source of truth
    /// for "what do we call this scheduler when telling the user" —
    /// sidecar serialization and failure-header formatting both use
    /// this, and any future consumer gets identical naming for free.
    pub const fn display_name(&self) -> &'static str {
        match self {
            SchedulerSpec::Eevdf => "eevdf",
            SchedulerSpec::Discover(n) => n,
            SchedulerSpec::Path(p) => p,
            SchedulerSpec::KernelBuiltin { .. } => "kernel",
        }
    }

    /// Best-effort git commit of the scheduler binary used for this
    /// run, or `None` when the commit cannot be determined honestly.
    ///
    /// Currently ALWAYS returns `None`. The field is reserved on the
    /// sidecar schema so stats tooling can enrich it once a reliable
    /// source exists, but no variant today has one:
    ///
    /// - `Eevdf` — no userspace scheduler binary at all. Kernel
    ///   default; the running kernel's identity belongs in
    ///   `host.kernel_release`, not here.
    /// - `Discover(_)` — `resolve_scheduler` has a 5-path cascade
    ///   (`KTSTR_SCHEDULER` env override → sibling of the ktstr
    ///   binary → `target/debug/` → `target/release/` → cargo
    ///   rebuild fallback). Only the rebuild path guarantees the
    ///   resulting binary was built from the current tree; the
    ///   four pre-built discovery paths can point at a binary
    ///   whose commit is unknown to this process. Synthesizing a
    ///   commit would be a lie in 4 of 5 cases and would silently
    ///   attribute regressions to the wrong commit. A future
    ///   enhancement can probe the binary itself (e.g.
    ///   `--version` output, an ELF note) and return `Some(..)`
    ///   ONLY when the actual commit is introspected; until then,
    ///   `None` is the only honest answer.
    /// - `Path(p)` — arbitrary externally-built binary. No
    ///   reliable introspection path (no shared ABI, no required
    ///   `--version` format).
    /// - `KernelBuiltin` — in-kernel scheduler, no userspace
    ///   binary commit to record.
    ///
    /// Returning `None` rather than `Some("unknown")` keeps the
    /// sidecar schema's nullable semantics honest: `stats compare`
    /// distinguishes "unset" from "set to a sentinel" without a
    /// magic string, and a future enhancement that learns to
    /// introspect a scheduler binary can flip a single arm to
    /// `Some(..)` without retrofitting consumers to strip a
    /// sentinel.
    pub const fn scheduler_commit(&self) -> Option<&'static str> {
        match self {
            SchedulerSpec::Eevdf
            | SchedulerSpec::Discover(_)
            | SchedulerSpec::Path(_)
            | SchedulerSpec::KernelBuiltin { .. } => None,
        }
    }
}

/// A `key=value` sysctl applied to the guest before the scheduler
/// starts, injected into the guest kernel cmdline as
/// `sysctl.<key>=<value>`.
///
/// Use the **dot-separated** form for `key` (e.g. `"kernel.foo"`, not
/// `"kernel/foo"`). Duplicate keys in a scheduler's sysctls slice are
/// applied in order; the last write wins.
///
/// Use [`Sysctl::new`] to construct in `const` context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sysctl {
    /// Dotted sysctl name (e.g. `"kernel.sched_cfs_bandwidth_slice_us"`).
    pub key: &'static str,
    /// Value written to the sysctl file as a string.
    pub value: &'static str,
}

impl Sysctl {
    /// Const constructor for use in `static`/`const` context.
    pub const fn new(key: &'static str, value: &'static str) -> Self {
        Self { key, value }
    }
}

/// Validated cgroup parent path.
///
/// Wraps a `&'static str` that is guaranteed to start with `/` and not
/// be `"/"` alone. Construct via [`CgroupPath::new`] (which const-panics
/// on invalid input) or the [`Scheduler::cgroup_parent`] builder.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CgroupPath(&'static str);

impl CgroupPath {
    /// Const constructor. Panics at compile time (or const-eval time)
    /// if `path` does not start with `/` or is `"/"` alone.
    pub const fn new(path: &'static str) -> Self {
        assert!(
            !path.is_empty() && path.as_bytes()[0] == b'/',
            "CgroupPath must begin with '/' (e.g. \"/ktstr\")"
        );
        assert!(
            path.len() > 1,
            "CgroupPath must not be \"/\" alone (that is the cgroup root)"
        );
        Self(path)
    }

    /// The raw path string (e.g. `"/ktstr"`).
    pub const fn as_str(&self) -> &'static str {
        self.0
    }

    /// The full sysfs cgroup directory (e.g. `"/sys/fs/cgroup/ktstr"`).
    pub fn sysfs_path(&self) -> String {
        format!("/sys/fs/cgroup{}", self.0)
    }
}

impl std::ops::Deref for CgroupPath {
    type Target = str;
    fn deref(&self) -> &str {
        self.0
    }
}

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

/// Host-side BPF map write performed during VM execution.
///
/// The write is event-driven: the host polls for BPF map discoverability
/// (scheduler loaded), then polls the SHM ring for scenario start, then
/// writes.
pub struct BpfMapWrite {
    /// Map name suffix to match (e.g. ".bss").
    pub map_name_suffix: &'static str,
    /// Byte offset within the map's value region.
    pub offset: usize,
    /// u32 value to write.
    pub value: u32,
}

/// Gauntlet topology filtering constraints.
///
/// Controls which gauntlet presets are eligible for a test entry.
/// Presets that don't meet all constraints are skipped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TopologyConstraints {
    /// Minimum number of NUMA nodes.
    pub min_numa_nodes: u32,
    /// Maximum number of NUMA nodes.
    pub max_numa_nodes: Option<u32>,
    /// Minimum number of LLCs.
    pub min_llcs: u32,
    /// Maximum number of LLCs.
    pub max_llcs: Option<u32>,
    /// Whether the test requires SMT (threads_per_core > 1).
    pub requires_smt: bool,
    /// Minimum total CPU count.
    pub min_cpus: u32,
    /// Maximum total CPU count.
    pub max_cpus: Option<u32>,
}

impl TopologyConstraints {
    /// Conservative default constraints: single NUMA node, 1-12 LLCs,
    /// no SMT requirement, 1-192 CPUs. Accepts most single-node
    /// gauntlet presets ktstr ships while rejecting multi-NUMA presets
    /// (numa2-*, numa4-*) and the scale-boundary single-node presets
    /// that exceed the CPU/LLC caps (near-max-llc, max-cpu, and their
    /// -nosmt variants). Test authors that want broader coverage must
    /// raise `max_numa_nodes`, `max_llcs`, or `max_cpus` explicitly.
    pub const DEFAULT: TopologyConstraints = TopologyConstraints {
        min_numa_nodes: 1,
        max_numa_nodes: Some(1),
        min_llcs: 1,
        max_llcs: Some(12),
        requires_smt: false,
        min_cpus: 1,
        max_cpus: Some(192),
    };

    /// Whether a topology preset is eligible under these constraints
    /// and the host's physical limits.
    pub fn accepts(
        &self,
        topo: &Topology,
        host_cpus: u32,
        host_llcs: u32,
        host_max_cpus_per_llc: u32,
    ) -> bool {
        topo.num_numa_nodes() >= self.min_numa_nodes
            && self
                .max_numa_nodes
                .is_none_or(|max| topo.num_numa_nodes() <= max)
            && topo.num_llcs() >= self.min_llcs
            && self.max_llcs.is_none_or(|max| topo.num_llcs() <= max)
            && (!self.requires_smt || topo.threads_per_core >= 2)
            && topo.total_cpus() >= self.min_cpus
            && self.max_cpus.is_none_or(|max| topo.total_cpus() <= max)
            && topo.total_cpus() <= host_cpus
            && topo.num_llcs() <= host_llcs
            && topo.cores_per_llc * topo.threads_per_core <= host_max_cpus_per_llc
    }
}

/// Definition of a scheduler for the test framework.
///
/// Captures everything the framework needs to know about a scheduler:
/// its binary, flag declarations, sysctls, kernel args, cgroup parent,
/// scheduler args, topology constraints, and monitor thresholds.
pub struct Scheduler {
    /// Short human name for the scheduler, used in logs and sidecar
    /// metadata.
    pub name: &'static str,
    /// Source of the scheduler: a built-in spec variant (`Eevdf`,
    /// `Discover`, `Path`, or `KernelBuiltin`).
    pub binary: SchedulerSpec,
    /// Flag declarations from which gauntlet profiles are generated.
    pub flags: &'static [&'static FlagDecl],
    /// Guest sysctls applied before the scheduler starts (injected
    /// into the guest kernel cmdline as `sysctl.<key>=<value>`).
    /// Applied in order; duplicate keys last-write-wins.
    pub sysctls: &'static [Sysctl],
    /// Extra guest kernel command-line arguments appended when booting
    /// the VM. This is the GUEST KERNEL cmdline, not the scheduler
    /// binary's CLI — use [`sched_args`](field@Self::sched_args) for that.
    ///
    /// Do not override the kargs ktstr injects itself (`console=`,
    /// `loglevel=`, `init=`): those break guest-side init
    /// and leave the VM unable to run tests.
    pub kargs: &'static [&'static str],
    /// Scheduler-wide assertion overrides merged on top of
    /// `Assert::default_checks()` and below each per-entry `assert`.
    pub assert: crate::assert::Assert,
    /// Cgroup parent path. Must begin with `/` and must not be `"/"`
    /// alone (that is the cgroup root). Example: `"/ktstr"`.
    /// When set, the init creates the sysfs directory before starting
    /// the scheduler, and `--cell-parent-cgroup {path}` is injected
    /// into scheduler args.
    pub cgroup_parent: Option<CgroupPath>,
    /// Scheduler CLI args, prepended before per-test `extra_sched_args`.
    pub sched_args: &'static [&'static str],
    /// Default VM topology for tests using this scheduler. Tests inherit
    /// this topology unless they override `numa_nodes`, `llcs`, `cores`,
    /// or `threads` explicitly in `#[ktstr_test]`.
    pub topology: Topology,
    /// Gauntlet topology constraints. Tests inherit these unless they
    /// override specific fields in `#[ktstr_test]`.
    pub constraints: TopologyConstraints,
    /// Host-side path to an opaque config file passed to the scheduler
    /// binary inside the VM. The file is included in the initramfs at
    /// `/include-files/{filename}` and `--config /include-files/{filename}`
    /// is prepended to `sched_args`.
    pub config_file: Option<&'static str>,
}

impl Scheduler {
    /// Placeholder scheduler representing "no scx scheduler." Tests
    /// that use `Scheduler::EEVDF` run under the kernel's default
    /// scheduler (EEVDF on current kernels), with no scheduler binary
    /// launched. Useful as a baseline and for tests that exercise
    /// framework behavior independent of any scx scheduler.
    ///
    /// The `.name` is the compile-time-fixed string `"eevdf"` — NOT
    /// runtime-derived from the live kernel. A sidecar written on a
    /// kernel whose default is a successor scheduling class still
    /// records `"eevdf"` here as long as the test attributes this
    /// `Scheduler` to a run.
    ///
    /// The pairing with
    /// [`Payload::KERNEL_DEFAULT`](crate::test_support::Payload::KERNEL_DEFAULT)
    /// (`"kernel_default"`) makes two static labels available at
    /// runtime — `"kernel_default"` (author intent) and `"eevdf"`
    /// (scheduling class the placeholder was authored against) —
    /// but only one of them, `"eevdf"`, reaches the sidecar's
    /// `scheduler` field via `scheduler_name()`; `"kernel_default"`
    /// stays in-memory only. See the canonical explanation on
    /// [`Payload::KERNEL_DEFAULT`](crate::test_support::Payload::KERNEL_DEFAULT)
    /// for which question each label answers, the sidecar-
    /// serialization split, and how to filter by author intent vs.
    /// by scheduling class.
    ///
    /// The sidecar itself does not carry the mapping from kernel
    /// version to scheduling class: the `host.kernel_release`
    /// field records the live kernel's release string (`6.6.12`,
    /// `6.14.2`, …) and nothing else. Consumers that need to answer
    /// "did this run actually use EEVDF?" must combine
    /// `host.kernel_release` with version-to-class knowledge
    /// maintained OUTSIDE the sidecar — e.g. an external lookup
    /// table that records the default scheduling class per upstream
    /// kernel release. A sidecar alone cannot distinguish a true
    /// EEVDF run from a run on a successor-class kernel that
    /// reused the same `"eevdf"` label via
    /// [`Scheduler::EEVDF`]'s compile-time-fixed `.name`.
    pub const EEVDF: Scheduler = Scheduler {
        name: "eevdf",
        binary: SchedulerSpec::Eevdf,
        flags: &[],
        sysctls: &[],
        kargs: &[],
        assert: crate::assert::Assert::NO_OVERRIDES,
        cgroup_parent: None,
        sched_args: &[],
        topology: Topology {
            llcs: 1,
            cores_per_llc: 2,
            threads_per_core: 1,
            numa_nodes: 1,
            nodes: None,
            distances: None,
        },
        constraints: TopologyConstraints::DEFAULT,
        config_file: None,
    };

    /// Const constructor for defining schedulers in static context.
    pub const fn new(name: &'static str) -> Scheduler {
        Scheduler {
            name,
            binary: SchedulerSpec::Eevdf,
            flags: &[],
            sysctls: &[],
            kargs: &[],
            assert: crate::assert::Assert::NO_OVERRIDES,
            cgroup_parent: None,
            sched_args: &[],
            topology: Topology {
                llcs: 1,
                cores_per_llc: 2,
                threads_per_core: 1,
                numa_nodes: 1,
                nodes: None,
                distances: None,
            },
            constraints: TopologyConstraints::DEFAULT,
            config_file: None,
        }
    }

    /// Set the binary spec. Returns self for const chaining.
    pub const fn binary(mut self, binary: SchedulerSpec) -> Self {
        self.binary = binary;
        self
    }

    /// Set flag declarations. Returns self for const chaining.
    pub const fn flags(mut self, flags: &'static [&'static FlagDecl]) -> Self {
        self.flags = flags;
        self
    }

    /// Set sysctls. Returns self for const chaining.
    pub const fn sysctls(mut self, sysctls: &'static [Sysctl]) -> Self {
        self.sysctls = sysctls;
        self
    }

    /// Set kernel args. Returns self for const chaining.
    pub const fn kargs(mut self, kargs: &'static [&'static str]) -> Self {
        self.kargs = kargs;
        self
    }

    /// Set assertion config. Returns self for const chaining.
    pub const fn assert(mut self, assert: crate::assert::Assert) -> Self {
        self.assert = assert;
        self
    }

    /// Set cgroup parent path. See the [`cgroup_parent`](field@Self::cgroup_parent)
    /// field for path format requirements (must begin with `/`, must
    /// not be `"/"` alone).
    pub const fn cgroup_parent(mut self, path: &'static str) -> Self {
        self.cgroup_parent = Some(CgroupPath::new(path));
        self
    }

    /// Set scheduler CLI args prepended before per-test
    /// `extra_sched_args`.
    pub const fn sched_args(mut self, args: &'static [&'static str]) -> Self {
        self.sched_args = args;
        self
    }

    /// Set the default VM topology for tests using this scheduler.
    /// Tests inherit this unless they override individual dimensions
    /// explicitly in `#[ktstr_test]`.
    pub const fn topology(mut self, numa_nodes: u32, llcs: u32, cores: u32, threads: u32) -> Self {
        self.topology = Topology {
            llcs,
            cores_per_llc: cores,
            threads_per_core: threads,
            numa_nodes,
            nodes: None,
            distances: None,
        };
        self
    }

    /// Set gauntlet topology constraints. Tests inherit these unless
    /// they override specific fields in `#[ktstr_test]`.
    pub const fn constraints(mut self, constraints: TopologyConstraints) -> Self {
        self.constraints = constraints;
        self
    }

    /// Set minimum number of NUMA nodes.
    pub const fn min_numa_nodes(mut self, n: u32) -> Self {
        self.constraints.min_numa_nodes = n;
        self
    }

    /// Set maximum number of NUMA nodes.
    pub const fn max_numa_nodes(mut self, n: u32) -> Self {
        self.constraints.max_numa_nodes = Some(n);
        self
    }

    /// Set minimum number of LLCs.
    pub const fn min_llcs(mut self, n: u32) -> Self {
        self.constraints.min_llcs = n;
        self
    }

    /// Set maximum number of LLCs.
    pub const fn max_llcs(mut self, n: u32) -> Self {
        self.constraints.max_llcs = Some(n);
        self
    }

    /// Set whether the scheduler requires SMT.
    pub const fn requires_smt(mut self, v: bool) -> Self {
        self.constraints.requires_smt = v;
        self
    }

    /// Set minimum total CPU count.
    pub const fn min_cpus(mut self, n: u32) -> Self {
        self.constraints.min_cpus = n;
        self
    }

    /// Set maximum total CPU count.
    pub const fn max_cpus(mut self, n: u32) -> Self {
        self.constraints.max_cpus = Some(n);
        self
    }

    /// Set a host-side config file path. The file is included in the
    /// guest initramfs and `--config` is injected into scheduler args.
    pub const fn config_file(mut self, path: &'static str) -> Self {
        self.config_file = Some(path);
        self
    }

    /// Names of all flags this scheduler supports.
    pub fn supported_flag_names(&self) -> Vec<&str> {
        self.flags.iter().map(|f| f.name).collect()
    }

    /// Dependencies of a flag (from its `FlagDecl.requires`).
    pub fn flag_requires(&self, name: &str) -> Vec<&str> {
        self.flags
            .iter()
            .find(|f| f.name == name)
            .map(|f| f.requires.iter().map(|r| r.name).collect())
            .unwrap_or_default()
    }

    /// Extra CLI arguments associated with a flag.
    pub fn flag_args(&self, name: &str) -> Option<&'static [&'static str]> {
        self.flags.iter().find(|f| f.name == name).map(|f| f.args)
    }

    /// Generate flag profiles scoped to this scheduler's supported flags.
    ///
    /// Dependency constraints come from each flag's `FlagDecl::requires`
    /// list: the result contains every valid combination of the
    /// scheduler's flags that honours those `requires` edges while also
    /// including the caller-supplied `required` flags and excluding
    /// `excluded` flags.
    pub fn generate_profiles(
        &self,
        required: &[&'static str],
        excluded: &[&'static str],
    ) -> Vec<crate::scenario::FlagProfile> {
        let all: Vec<&'static str> = self.flags.iter().map(|f| f.name).collect();
        // Requires edges come from each declaration's `requires` list.
        // Promote from `Vec<&str>` to `Vec<&'static str>` via a fixed
        // lookup against `self.flags` so the shared generator's
        // lifetime-unified input type is satisfied.
        let requires_fn = |&f: &&'static str| -> Vec<&'static str> {
            self.flag_requires(f)
                .into_iter()
                .filter_map(|name| self.flags.iter().map(|d| d.name).find(|n| *n == name))
                .collect()
        };
        crate::scenario::compute_flag_profiles(&all, requires_fn, required, excluded)
            .into_iter()
            .map(|flags| crate::scenario::FlagProfile { flags })
            .collect()
    }
}

/// Registration entry for an `#[ktstr_test]`-annotated function.
pub struct KtstrTestEntry {
    /// Fully qualified test name as it appears in nextest output.
    pub name: &'static str,
    /// Entry point invoked once per replica, inside the guest VM when
    /// `host_only` is false and on the host when it is true.
    pub func: fn(&Ctx) -> Result<AssertResult>,
    /// Base virtual topology; gauntlet expansion produces additional
    /// variants layered on top of this baseline.
    pub topology: Topology,
    /// Host-topology constraints (CPU and LLC bounds) that gate
    /// whether this entry is eligible on the current machine.
    pub constraints: TopologyConstraints,
    /// Guest memory in MB.
    pub memory_mb: u32,
    /// Primary payload that drives the test. Defaults to
    /// `Payload::KERNEL_DEFAULT` (the no-scx-scheduler placeholder).
    ///
    /// For scheduler-centric tests this is a scheduler-kind
    /// `Payload` (typically the `{NAME}_PAYLOAD` wrapper emitted by
    /// `#[derive(Scheduler)]`); for pure binary workloads it is a
    /// binary-kind `Payload` built via `#[derive(Payload)]`. The
    /// slot accepts either because `Payload` is the unified
    /// primitive — callers that need scheduler-specific fields go
    /// through forwarding accessors like
    /// [`Payload::sysctls`](crate::test_support::Payload::sysctls)
    /// which return empty slices for binary-kind values.
    pub scheduler: &'static crate::test_support::Payload,
    /// Optional binary payload to run as the primary workload. When
    /// `Some`, the test runs the referenced [`Payload`](crate::test_support::Payload)
    /// (which must be [`PayloadKind::Binary`](crate::test_support::PayloadKind::Binary))
    /// alongside the configured scheduler. When `None`, the test runs
    /// a scheduler-only scenario.
    ///
    /// Populated by `#[ktstr_test(payload = SOME_BIN)]`; direct
    /// programmatic callers may also set this.
    pub payload: Option<&'static crate::test_support::Payload>,
    /// Additional binary payloads composed with the primary. Each
    /// entry is launched via [`Ctx::payload`](crate::scenario::Ctx)
    /// in the test body.
    ///
    /// Populated by `#[ktstr_test(workloads = [A, B])]`.
    pub workloads: &'static [&'static crate::test_support::Payload],
    /// When true, a crash triggers an auto-repro run with BPF probes
    /// attached to the crash call chain.
    pub auto_repro: bool,
    /// Per-entry assertion overrides merged on top of
    /// `Assert::default_checks()` and the scheduler's `assert`.
    pub assert: crate::assert::Assert,
    /// Extra CLI arguments appended to the scheduler invocation.
    pub extra_sched_args: &'static [&'static str],
    /// `scx_sched.watchdog_timeout` override applied to the guest kernel.
    pub watchdog_timeout: Duration,
    /// Host-side BPF map writes to perform during VM execution.
    ///
    /// Empty slice (the default) means "no writes." Setup failures
    /// (accessor init, map resolution, probes-ready wait) abort before
    /// any writes are attempted. Within the write phase itself, every
    /// entry is attempted; individual write failures are logged but do
    /// not abort remaining writes — partial success suppresses the
    /// final signal to the guest so it times out rather than observing
    /// half-applied state.
    pub bpf_map_write: &'static [&'static BpfMapWrite],
    /// Flags that must be present in every flag profile for this test.
    pub required_flags: &'static [&'static str],
    /// Flags that must not be present in any flag profile for this test.
    pub excluded_flags: &'static [&'static str],
    /// Pin vCPU threads to host cores matching the virtual topology's LLC
    /// structure, use 2MB hugepages for guest memory, NUMA mbind guest
    /// memory to pinned vCPU nodes, and promote vCPU threads to
    /// SCHED_FIFO. Validates that the host has enough CPUs and LLCs to
    /// satisfy the request without oversubscription.
    ///
    /// On x86_64, additionally: set KVM_HINTS_REALTIME CPUID hint
    /// (disables PV spinlocks, PV TLB flush, PV sched_yield; enables
    /// haltpoll cpuidle), disable PAUSE and HLT VM exits via
    /// KVM_CAP_X86_DISABLE_EXITS (HLT falls back to PAUSE-only when
    /// mitigate_smt_rsb is active), skip KVM_CAP_HALT_POLL (guest
    /// haltpoll cpuidle disables host halt polling via
    /// MSR_KVM_POLL_CONTROL), and check TSC stability.
    ///
    /// On aarch64, KVM exit suppression and CPUID hints are not
    /// available. The four host-side optimizations (vCPU pinning,
    /// hugepages, NUMA mbind, RT scheduling) apply.
    pub performance_mode: bool,
    /// Workload duration.
    pub duration: Duration,
    /// Workers per cgroup.
    pub workers_per_cgroup: u32,
    /// When true, the test expects run_ktstr_test to return Err.
    /// Disables auto_repro (no point probing a deliberately failing test).
    pub expect_err: bool,
    /// When true, the test runs directly on the host instead of
    /// booting a VM. Used for tests that need host tools (cargo,
    /// nested VMs) unavailable in the guest initramfs.
    pub host_only: bool,
    /// Extra host-side file specs beyond what the entry's
    /// [`scheduler`](Self::scheduler) / [`payload`](Self::payload) /
    /// [`workloads`](Self::workloads) declare. Unions with those
    /// per-payload specs at `run_ktstr_test` time; see
    /// [`all_include_files`](Self::all_include_files) for the
    /// aggregation contract. Use this slot for test-level
    /// dependencies that don't belong on a specific Payload —
    /// auxiliary data files, per-test helper scripts, fixtures.
    pub extra_include_files: &'static [&'static str],
    /// Maximum acceptable wall-clock duration of host-side VM teardown
    /// (BSP exit through SHM drain). Compared against
    /// [`VmResult::cleanup_duration`](crate::vmm::VmResult::cleanup_duration)
    /// in `evaluate_vm_result`; when the budget is exceeded the test's
    /// `AssertResult` is folded with a failing
    /// [`AssertDetail`](crate::assert::AssertDetail). Catches
    /// sub-watchdog cleanup regressions (e.g. a 30s teardown that the
    /// 60s host watchdog would silently absorb) at the test that
    /// declares the budget rather than at gross-timeout failure.
    /// `None` (the default) disables the check, leaving the watchdog
    /// as the only guard. Populated by
    /// `#[ktstr_test(cleanup_budget_ms = N)]` or by direct entry
    /// construction.
    pub cleanup_budget: Option<Duration>,
    /// Optional virtio-blk disk attached to the VM at `/dev/vda`.
    /// `None` (the default) boots without a disk; `Some(cfg)` calls
    /// [`crate::vmm::KtstrVmBuilder::disk`] in
    /// [`crate::test_support::runtime::build_vm_builder_base`] so the
    /// guest sees a raw block device sized per `cfg.capacity_mb`.
    /// The `#[ktstr_test]` macro does not currently surface this
    /// slot — direct construction via `..KtstrTestEntry::DEFAULT`
    /// is the only path. Mutually exclusive with `host_only`:
    /// `validate` rejects the combination because `host_only`
    /// skips the VM boot that owns the disk lifecycle.
    pub disk: Option<crate::vmm::disk_config::DiskConfig>,
    /// Host-side callback invoked after `vm.run()` returns, with
    /// access to the full `VmResult`. Runs on the HOST, not inside
    /// the guest. Use for assertions that need host-side state
    /// (e.g., `VmResult.snapshot_bridge` content after a snapshot
    /// capture pipeline fires inside the VM).
    ///
    /// `None` (the default) skips the callback. When `Some`, the
    /// closure receives `&VmResult` and returns `Result<()>` — an
    /// `Err` fails the test with the returned message.
    pub post_vm: Option<fn(&crate::vmm::VmResult) -> Result<()>>,
}

/// Placeholder function for [`KtstrTestEntry::DEFAULT`].
///
/// Returns `Err` — NOT a panic — so a programmatic caller that
/// accidentally uses `KtstrTestEntry::DEFAULT` without overriding
/// `func` gets an immediate actionable failure inside the test-run
/// loop rather than taking down the whole dispatch process. The
/// `..KtstrTestEntry::DEFAULT` struct-update spread only populates
/// unfilled fields; if the caller spread the default without
/// setting `func`, this stub runs and bails with a message pointing
/// at the mistake.
fn default_test_func(_ctx: &Ctx) -> Result<AssertResult> {
    anyhow::bail!("KtstrTestEntry::DEFAULT func called — override func before use")
}

impl KtstrTestEntry {
    /// Sensible defaults for all fields. Override `name`, `func`, and
    /// `scheduler` (at minimum) via struct update syntax. Manual
    /// consumers should also set `auto_repro` explicitly: the default
    /// `true` boots a second VM with BPF probes attached on failure,
    /// which roughly doubles a failing test's wall-clock time.
    ///
    /// ```
    /// use ktstr::prelude::*;
    /// use ktstr::test_support::{KTSTR_TESTS, KtstrTestEntry, Payload};
    ///
    /// fn my_test_fn(_ctx: &Ctx) -> Result<AssertResult> {
    ///     Ok(AssertResult::pass())
    /// }
    ///
    /// #[ktstr::__private::linkme::distributed_slice(KTSTR_TESTS)]
    /// #[linkme(crate = ktstr::__private::linkme)]
    /// static ENTRY: KtstrTestEntry = KtstrTestEntry {
    ///     name: "my_test",
    ///     func: my_test_fn,
    ///     scheduler: &Payload::KERNEL_DEFAULT,
    ///     ..KtstrTestEntry::DEFAULT
    /// };
    /// ```
    pub const DEFAULT: KtstrTestEntry = KtstrTestEntry {
        name: "",
        func: default_test_func,
        topology: Topology {
            llcs: 1,
            cores_per_llc: 2,
            threads_per_core: 1,
            numa_nodes: 1,
            nodes: None,
            distances: None,
        },
        constraints: TopologyConstraints::DEFAULT,
        memory_mb: 2048,
        scheduler: &crate::test_support::Payload::KERNEL_DEFAULT,
        payload: None,
        workloads: &[],
        auto_repro: true,
        assert: crate::assert::Assert::NO_OVERRIDES,
        extra_sched_args: &[],
        watchdog_timeout: Duration::from_secs(5),
        bpf_map_write: &[],
        required_flags: &[],
        excluded_flags: &[],
        performance_mode: false,
        duration: Duration::from_secs(12),
        workers_per_cgroup: 2,
        expect_err: false,
        host_only: false,
        extra_include_files: &[],
        cleanup_budget: None,
        disk: None,
        post_vm: None,
    };

    /// Reject values that would boot a broken VM or leave assertions
    /// vacuously passing. The `#[ktstr_test]` proc macro enforces the
    /// same constraints at compile time for attribute-built entries;
    /// this method covers directly-constructed entries (library
    /// callers building `KtstrTestEntry` values to push into
    /// [`KTSTR_TESTS`] programmatically).
    ///
    /// Rules:
    /// - `name` must be non-empty (empty names collapse into each
    ///   other in nextest output and in sidecar lookups).
    /// - `name` must not contain `/` or `\` (path separators embed in
    ///   sidecar filenames and nextest test IDs; a separator would
    ///   create a synthetic subdirectory in sidecar output and
    ///   mangle `cargo nextest run -E 'test(name)'` filtering).
    /// - `memory_mb` must be `> 0` (a VM with zero memory cannot boot).
    /// - `duration` must be `> 0` (a zero-duration run never exercises
    ///   the scheduler and produces no telemetry).
    /// - `workers_per_cgroup` must be `> 0` (zero workers emit no
    ///   `WorkerReport`s so assertions again pass vacuously).
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.name.is_empty() {
            anyhow::bail!(
                "KtstrTestEntry.name must be non-empty (empty names \
                 collide in nextest output and sidecar lookups)"
            );
        }
        if self.name.contains('/') || self.name.contains('\\') {
            anyhow::bail!(
                "KtstrTestEntry '{}' name must not contain path \
                 separators ('/' or '\\') — they embed in sidecar \
                 filenames and nextest test IDs, creating synthetic \
                 subdirectories in sidecar output and mangling \
                 nextest -E 'test(name)' filtering",
                self.name,
            );
        }
        if self.memory_mb == 0 {
            anyhow::bail!(
                "KtstrTestEntry '{}'.memory_mb must be > 0 (a VM with \
                 zero memory cannot boot)",
                self.name,
            );
        }
        if self.duration.is_zero() {
            anyhow::bail!(
                "KtstrTestEntry '{}'.duration must be > 0 (a zero-duration \
                 run never exercises the scheduler and produces no data \
                 for assertions)",
                self.name,
            );
        }
        if self.workers_per_cgroup == 0 {
            anyhow::bail!(
                "KtstrTestEntry '{}'.workers_per_cgroup must be > 0 (a \
                 zero-worker cgroup emits no WorkerReports and assertions \
                 vacuously pass)",
                self.name,
            );
        }
        if let Some(p) = self.payload
            && p.is_scheduler()
        {
            anyhow::bail!(
                "KtstrTestEntry '{}'.payload must be PayloadKind::Binary, \
                 not Scheduler-kind (schedulers belong in the `scheduler` \
                 slot; the `payload` slot is for userspace binaries \
                 composed under the scheduler)",
                self.name,
            );
        }
        if self.host_only && self.disk.is_some() {
            anyhow::bail!(
                "KtstrTestEntry '{}'.host_only=true with disk=Some(..) — \
                 host_only skips the VM boot that owns the virtio-blk \
                 device lifecycle, so the disk would never be attached. \
                 Drop one of host_only or disk.",
                self.name,
            );
        }
        // Mirror the payload-slot gate for every workload entry. The
        // `workloads` slot is for userspace binaries composed with
        // the primary payload under the scheduler; a scheduler-kind
        // Payload here would be silently ignored at spawn time and
        // is almost always a `Payload::KERNEL_DEFAULT`-shaped typo in a
        // `workloads = [...]` attribute.
        for (idx, w) in self.workloads.iter().enumerate() {
            if w.is_scheduler() {
                anyhow::bail!(
                    "KtstrTestEntry '{}'.workloads[{idx}] (name='{}') must be \
                     PayloadKind::Binary, not Scheduler-kind (schedulers belong \
                     in the `scheduler` slot; the `workloads` slot is for \
                     userspace binaries composed under the scheduler)",
                    self.name,
                    w.name,
                );
            }
        }
        Ok(())
    }

    /// Aggregate every declared include-file spec: the entry's
    /// [`scheduler`](Self::scheduler) and (if present) its primary
    /// [`payload`](Self::payload) contribute their
    /// [`Payload::include_files`](crate::test_support::Payload::include_files),
    /// each entry in [`workloads`](Self::workloads) contributes its
    /// own, and [`extra_include_files`](Self::extra_include_files)
    /// contributes test-level extras. Pre-dedupe aggregation order:
    /// scheduler → payload → workloads (in declaration order) →
    /// extras. Duplicate spec strings at this layer are NOT deduped
    /// — the framework's include-file pipeline at `run_ktstr_test`
    /// resolves each entry to a `(archive_path, host_path)` pair
    /// and dedupes on identical pairs while erroring on
    /// archive_path collisions with conflicting host_paths. This
    /// aggregation order does NOT survive downstream: the final
    /// resolved list is sorted alphabetically by archive_path after
    /// deduplication. Alphabetical ordering ensures deterministic
    /// initramfs layout regardless of declaration order.
    pub fn all_include_files(&self) -> Vec<&'static str> {
        let mut out: Vec<&'static str> = Vec::new();
        out.extend(self.scheduler.include_files.iter().copied());
        if let Some(p) = self.payload {
            out.extend(p.include_files.iter().copied());
        }
        for w in self.workloads {
            out.extend(w.include_files.iter().copied());
        }
        out.extend(self.extra_include_files.iter().copied());
        out
    }
}

/// Distributed slice collecting all `#[ktstr_test]` entries via linkme.
#[distributed_slice]
pub static KTSTR_TESTS: [KtstrTestEntry];

/// Look up a registered test function by name.
pub fn find_test(name: &str) -> Option<&'static KtstrTestEntry> {
    KTSTR_TESTS.iter().find(|e| e.name == name)
}

/// Validate that `required_flags` and `excluded_flags` on an entry
/// reference flags the scheduler actually declares.
///
/// # Panics
///
/// - when the entry names a flag the scheduler doesn't declare
/// - when the scheduler has zero flag declarations but the entry
///   still specifies `required_flags` or `excluded_flags`
/// - when a flag appears in both lists
///
/// All three are user mistakes in an attribute-built (or
/// programmatically-built) [`KtstrTestEntry`] — they indicate a typo
/// or a scheduler/entry-table mismatch that cannot be recovered
/// from at runtime. Panicking here runs during nextest test
/// discovery (`list_tests_all` / `list_tests_budget`), so the error
/// surfaces BEFORE any VM boot, with the entry name + scheduler name
/// + flag name in the message. A returning variant would force every
///   discovery-time caller to either ignore the error (hiding the
///   mistake) or propagate via nextest's custom-test-exit protocol
///   (whose error reporting is much weaker than a panic's backtrace).
///   The panic IS the actionable feedback path.
pub(crate) fn validate_entry_flags(entry: &KtstrTestEntry) {
    if entry.scheduler.flags().is_empty() {
        if !entry.required_flags.is_empty() || !entry.excluded_flags.is_empty() {
            panic!(
                "ktstr_test: '{}' specifies flags but scheduler '{}' has no flag declarations",
                entry.name,
                entry.scheduler.scheduler_name(),
            );
        }
        return;
    }
    let valid: Vec<&str> = entry.scheduler.supported_flag_names();
    for &flag in entry.required_flags {
        if !valid.contains(&flag) {
            panic!(
                "ktstr_test: '{}' references unknown required_flag '{}'; valid flags for scheduler '{}': {}",
                entry.name,
                flag,
                entry.scheduler.scheduler_name(),
                valid.join(", "),
            );
        }
    }
    for &flag in entry.excluded_flags {
        if !valid.contains(&flag) {
            panic!(
                "ktstr_test: '{}' references unknown excluded_flag '{}'; valid flags for scheduler '{}': {}",
                entry.name,
                flag,
                entry.scheduler.scheduler_name(),
                valid.join(", "),
            );
        }
    }
    for &flag in entry.required_flags {
        if entry.excluded_flags.contains(&flag) {
            panic!(
                "ktstr_test: '{}' has flag '{}' in both required_flags and excluded_flags",
                entry.name, flag,
            );
        }
    }
}

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

    /// Minimal Ctx for invoking `default_test_func` without booting a
    /// real workload. The func signature only requires `&Ctx`; the
    /// stub returns Err unconditionally so no field on Ctx is read.
    fn dummy_ctx() -> (crate::cgroup::CgroupManager, crate::topology::TestTopology) {
        let cgroups = crate::cgroup::CgroupManager::new("/sys/fs/cgroup/ktstr-dummy");
        let topo = crate::topology::TestTopology::from_vm_topology(&Topology {
            llcs: 1,
            cores_per_llc: 1,
            threads_per_core: 1,
            numa_nodes: 1,
            nodes: None,
            distances: None,
        });
        (cgroups, topo)
    }

    #[test]
    fn ktstr_test_entry_default_fields() {
        let d = KtstrTestEntry::DEFAULT;
        assert_eq!(d.name, "");
        // func is the stub — verified separately in
        // default_test_func_returns_err.
        assert_eq!(d.topology.llcs, 1);
        assert_eq!(d.topology.cores_per_llc, 2);
        assert_eq!(d.topology.threads_per_core, 1);
        assert_eq!(d.topology.numa_nodes, 1);
        assert!(d.topology.nodes.is_none());
        assert!(d.topology.distances.is_none());
        assert_eq!(d.constraints, TopologyConstraints::DEFAULT);
        assert_eq!(d.memory_mb, 2048);
        // scheduler defaults to the crate's &Payload::KERNEL_DEFAULT.
        // `Payload::scheduler_name()` forwards to the inner
        // `Scheduler::EEVDF.name` on the scheduler-kind path, so the
        // returned string is `"eevdf"` (the kernel scheduler name),
        // not the payload's own `"kernel_default"` wire name.
        assert_eq!(d.scheduler.scheduler_name(), "eevdf");
        assert!(!d.scheduler.has_active_scheduling());
        assert!(d.auto_repro);
        assert!(d.extra_sched_args.is_empty());
        assert_eq!(d.watchdog_timeout, Duration::from_secs(5));
        assert!(d.bpf_map_write.is_empty());
        assert!(d.required_flags.is_empty());
        assert!(d.excluded_flags.is_empty());
        assert!(!d.performance_mode);
        assert_eq!(d.duration, Duration::from_secs(12));
        assert_eq!(d.workers_per_cgroup, 2);
        assert!(!d.expect_err);
        assert!(!d.host_only);
        // Payload slot defaults to None (scheduler-only entry); workloads
        // slice defaults to empty. Macro emits these as explicit None/&[]
        // so struct-update spreaders also get the right values.
        assert!(d.payload.is_none());
        assert!(d.workloads.is_empty());
    }

    #[test]
    fn ktstr_test_entry_payload_slot_can_be_populated() {
        use crate::test_support::{OutputFormat, Payload, PayloadKind};
        const FIO: Payload = Payload {
            name: "fio",
            kind: PayloadKind::Binary("fio"),
            output: OutputFormat::Json,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        let entry = KtstrTestEntry {
            name: "payload_entry",
            payload: Some(&FIO),
            ..KtstrTestEntry::DEFAULT
        };
        let p = entry.payload.expect("payload set");
        assert_eq!(p.name, "fio");
        assert!(!p.is_scheduler());
    }

    #[test]
    fn ktstr_test_entry_workloads_slot_accepts_multiple_payloads() {
        use crate::test_support::{OutputFormat, Payload, PayloadKind};
        const FIO: Payload = Payload {
            name: "fio",
            kind: PayloadKind::Binary("fio"),
            output: OutputFormat::Json,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        // stress-ng emits progress / metrics / summaries to stderr; stdout
        // is blank. `OutputFormat::Json` yields zero metrics — stdout has
        // nothing JSON-shaped to parse, and the stderr fallback sees prose
        // rather than JSON so the extraction pipeline returns empty.
        // `OutputFormat::LlmExtract` MAY extract numbers from the stderr
        // fallback, but results depend on the local model's tolerance for
        // stress-ng's prose format — unstable without a stderr→stdout
        // redirect wired into `default_args`. Keep `ExitCode` unless you
        // are prepared for that tradeoff.
        const STRESS_NG: Payload = Payload {
            name: "stress-ng",
            kind: PayloadKind::Binary("stress-ng"),
            output: OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        let entry = KtstrTestEntry {
            name: "multi_workload",
            workloads: &[&FIO, &STRESS_NG],
            ..KtstrTestEntry::DEFAULT
        };
        assert_eq!(entry.workloads.len(), 2);
        assert_eq!(entry.workloads[0].name, "fio");
        assert_eq!(entry.workloads[1].name, "stress-ng");
    }

    /// `validate()` rejects any `workloads[i]` that is a
    /// Scheduler-kind Payload — symmetric with the existing
    /// `payload`-slot rejection. Catches the typo where a test
    /// author writes `workloads = [Payload::KERNEL_DEFAULT]` instead of a
    /// binary payload.
    #[test]
    fn validate_rejects_scheduler_kind_in_workloads() {
        use crate::test_support::{OutputFormat, Payload, PayloadKind};
        const GOOD: Payload = Payload {
            name: "fio",
            kind: PayloadKind::Binary("fio"),
            output: OutputFormat::Json,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        fn good_test_func(_: &Ctx) -> Result<AssertResult> {
            Ok(AssertResult::pass())
        }
        let entry = KtstrTestEntry {
            name: "mixed_kinds",
            func: good_test_func,
            // Second workload is scheduler-kind → must bail.
            workloads: &[&GOOD, &Payload::KERNEL_DEFAULT],
            ..KtstrTestEntry::DEFAULT
        };
        let err = entry.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("workloads[1]") && msg.contains("Scheduler-kind"),
            "expected workloads[1] Scheduler-kind bail, got: {msg}"
        );
        assert!(
            msg.contains("kernel_default"),
            "error must name the offending workload entry, got: {msg}"
        );
    }

    /// Binary-only workloads slip past `validate()` cleanly — the
    /// Scheduler-kind check does not over-reject. Pins the happy
    /// path against the rejection path so future edits to the
    /// workloads loop don't flip polarity.
    #[test]
    fn validate_accepts_binary_only_workloads() {
        use crate::test_support::{OutputFormat, Payload, PayloadKind};
        const FIO: Payload = Payload {
            name: "fio",
            kind: PayloadKind::Binary("fio"),
            output: OutputFormat::Json,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        // stress-ng emits progress / metrics / summaries to stderr; stdout
        // is blank. `OutputFormat::Json` yields zero metrics — stdout has
        // nothing JSON-shaped to parse, and the stderr fallback sees prose
        // rather than JSON so the extraction pipeline returns empty.
        // `OutputFormat::LlmExtract` MAY extract numbers from the stderr
        // fallback, but results depend on the local model's tolerance for
        // stress-ng's prose format — unstable without a stderr→stdout
        // redirect wired into `default_args`. Keep `ExitCode` unless you
        // are prepared for that tradeoff.
        const STRESS_NG: Payload = Payload {
            name: "stress-ng",
            kind: PayloadKind::Binary("stress-ng"),
            output: OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        fn good_test_func(_: &Ctx) -> Result<AssertResult> {
            Ok(AssertResult::pass())
        }
        let entry = KtstrTestEntry {
            name: "all_binary",
            func: good_test_func,
            workloads: &[&FIO, &STRESS_NG],
            ..KtstrTestEntry::DEFAULT
        };
        entry.validate().expect("binary-only workloads must pass");
    }

    /// `validate()` rejects `host_only=true` paired with a
    /// `Some(DiskConfig)`. The combination is unsatisfiable today:
    /// `host_only` skips the VM boot that owns the virtio-blk device
    /// lifecycle, so the disk never attaches. Catching it at validate
    /// time surfaces the misconfiguration during nextest discovery
    /// instead of after a confusing host-only run that silently
    /// ignored the disk request.
    #[test]
    fn validate_rejects_host_only_with_disk() {
        fn good_test_func(_: &Ctx) -> Result<AssertResult> {
            Ok(AssertResult::pass())
        }
        let entry = KtstrTestEntry {
            name: "host_only_with_disk",
            func: good_test_func,
            host_only: true,
            disk: Some(crate::vmm::disk_config::DiskConfig::default()),
            ..KtstrTestEntry::DEFAULT
        };
        let err = entry
            .validate()
            .expect_err("host_only=true + disk=Some must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("host_only=true") && msg.contains("disk"),
            "expected host_only+disk diagnostic, got: {msg}",
        );
        assert!(
            msg.contains("host_only_with_disk"),
            "error must name the offending entry, got: {msg}",
        );
    }

    /// `host_only=true` with `disk=None` is the legitimate host-side
    /// shape: a host-only test running without any VM device. Pins
    /// the happy path against the rejection path so future edits
    /// to the host_only/disk gate don't flip polarity (rejecting a
    /// legitimate combination would silently break every host-only
    /// test author).
    #[test]
    fn validate_accepts_host_only_without_disk() {
        fn good_test_func(_: &Ctx) -> Result<AssertResult> {
            Ok(AssertResult::pass())
        }
        let entry = KtstrTestEntry {
            name: "host_only_no_disk",
            func: good_test_func,
            host_only: true,
            disk: None,
            ..KtstrTestEntry::DEFAULT
        };
        entry
            .validate()
            .expect("host_only=true + disk=None must validate");
    }

    /// `host_only=false` (the default) with `disk=Some(..)` is the
    /// canonical disk-attached VM test. Pins that the gate fires
    /// only on the actual conflict (host_only=true) and not on any
    /// `disk=Some(..)` entry — a future tightening that rejected
    /// every Some(DiskConfig) would break the entire #18/#165 disk
    /// integration test surface.
    #[test]
    fn validate_accepts_vm_with_disk() {
        fn good_test_func(_: &Ctx) -> Result<AssertResult> {
            Ok(AssertResult::pass())
        }
        let entry = KtstrTestEntry {
            name: "vm_with_disk",
            func: good_test_func,
            host_only: false,
            disk: Some(crate::vmm::disk_config::DiskConfig::default()),
            ..KtstrTestEntry::DEFAULT
        };
        entry
            .validate()
            .expect("host_only=false + disk=Some must validate");
    }

    #[test]
    fn ktstr_test_entry_default_rejected_by_empty_name() {
        // DEFAULT has name = "" which validate() rejects — so the
        // stub entry cannot accidentally dispatch. This pins that
        // invariant.
        let err = KtstrTestEntry::DEFAULT.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("name") && msg.contains("non-empty"),
            "expected name-non-empty bail, got: {msg}"
        );
    }

    #[test]
    fn default_test_func_returns_err() {
        // The stub bails with Err — NOT a panic. Callers that
        // accidentally leave `func: default_test_func` in their
        // entry must see a clean Err to surface the mistake.
        let (cgroups, topo) = dummy_ctx();
        let ctx = Ctx::builder(&cgroups, &topo)
            .duration(Duration::from_millis(1))
            .assert(crate::assert::Assert::NO_OVERRIDES)
            .build();
        let result = default_test_func(&ctx);
        let err = result.expect_err("default_test_func must return Err, not Ok");
        let msg = format!("{err}");
        assert!(
            msg.contains("KtstrTestEntry::DEFAULT func called"),
            "expected DEFAULT-called bail message, got: {msg}"
        );
        assert!(
            msg.contains("override func before use"),
            "expected actionable hint, got: {msg}"
        );
    }

    // -- Scheduler method tests --

    use super::super::test_helpers::{
        FLAGS_A, FLAGS_AB, FLAGS_BORROW_LONG, FLAGS_BORROW_REBAL, FLAGS_LLC_STEAL, FLAGS_STEAL_LLC,
        validate_entry,
    };

    #[test]
    fn scheduler_eevdf_defaults() {
        let s = &Scheduler::EEVDF;
        assert_eq!(s.name, "eevdf");
        assert!(s.flags.is_empty());
        assert!(s.sysctls.is_empty());
        assert!(s.kargs.is_empty());
        assert!(s.assert.not_starved.is_none());
        assert!(s.assert.max_imbalance_ratio.is_none());
    }

    #[test]
    fn scheduler_new_builder() {
        static TEST_SYSCTLS: &[Sysctl] =
            &[Sysctl::new("kernel.sched_cfs_bandwidth_slice_us", "1000")];
        let s = Scheduler::new("test_sched")
            .binary(SchedulerSpec::Discover("test_bin"))
            .flags(FLAGS_A)
            .sysctls(TEST_SYSCTLS)
            .kargs(&["nosmt"]);
        assert_eq!(s.name, "test_sched");
        assert_eq!(s.flags.len(), 1);
        assert_eq!(s.sysctls.len(), 1);
        assert_eq!(s.kargs.len(), 1);
    }

    #[test]
    fn scheduler_supported_flag_names() {
        let s = Scheduler::new("sched").flags(FLAGS_BORROW_REBAL);
        let names = s.supported_flag_names();
        assert_eq!(names, vec!["borrow", "rebal"]);
    }

    #[test]
    fn scheduler_flag_requires_found() {
        let s = Scheduler::new("sched").flags(FLAGS_STEAL_LLC);
        assert_eq!(s.flag_requires("steal"), vec!["llc"]);
        assert!(s.flag_requires("llc").is_empty());
    }

    #[test]
    fn scheduler_flag_requires_not_found() {
        let s = Scheduler::new("sched").flags(&[]);
        assert!(s.flag_requires("nonexistent").is_empty());
    }

    #[test]
    fn scheduler_flag_args_found() {
        let s = Scheduler::new("sched").flags(FLAGS_BORROW_LONG);
        assert_eq!(s.flag_args("borrow"), Some(["--enable-borrow"].as_slice()));
    }

    #[test]
    fn scheduler_flag_args_not_found() {
        let s = Scheduler::new("sched").flags(&[]);
        assert!(s.flag_args("nonexistent").is_none());
    }

    #[test]
    fn scheduler_generate_profiles_no_flags() {
        let s = Scheduler::new("sched");
        let profiles = s.generate_profiles(&[], &[]);
        assert_eq!(profiles.len(), 1);
        assert!(profiles[0].flags.is_empty());
    }

    #[test]
    fn scheduler_generate_profiles_all_optional() {
        let s = Scheduler::new("sched").flags(FLAGS_AB);
        let profiles = s.generate_profiles(&[], &[]);
        assert_eq!(profiles.len(), 4);
    }

    #[test]
    fn scheduler_generate_profiles_with_required() {
        let s = Scheduler::new("sched").flags(FLAGS_AB);
        let profiles = s.generate_profiles(&["a"], &[]);
        assert_eq!(profiles.len(), 2);
        for p in &profiles {
            assert!(p.flags.contains(&"a"));
        }
    }

    #[test]
    fn scheduler_generate_profiles_with_excluded() {
        let s = Scheduler::new("sched").flags(FLAGS_AB);
        let profiles = s.generate_profiles(&[], &["a"]);
        assert_eq!(profiles.len(), 2);
        for p in &profiles {
            assert!(!p.flags.contains(&"a"));
        }
    }

    #[test]
    fn scheduler_generate_profiles_dependency_filter() {
        let s = Scheduler::new("sched").flags(FLAGS_LLC_STEAL);
        let profiles = s.generate_profiles(&[], &[]);
        assert_eq!(profiles.len(), 3);
        let steal_alone = profiles
            .iter()
            .any(|p| p.flags.contains(&"steal") && !p.flags.contains(&"llc"));
        assert!(!steal_alone);
    }

    #[test]
    fn scheduler_with_check() {
        let v = crate::assert::Assert::NO_OVERRIDES
            .check_not_starved()
            .max_imbalance_ratio(3.0);
        let s = Scheduler::new("sched").assert(v);
        assert_eq!(s.assert.not_starved, Some(true));
        assert_eq!(s.assert.max_imbalance_ratio, Some(3.0));
    }

    // -- KtstrTestEntry::validate coverage --

    #[test]
    fn ktstr_test_entry_validate_accepts_defaults() {
        let e = validate_entry("ok", 512, Duration::from_secs(2), 2);
        e.validate().unwrap();
    }

    #[test]
    fn ktstr_test_entry_validate_rejects_empty_name() {
        let e = validate_entry("", 512, Duration::from_secs(2), 2);
        let err = e.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("name") && msg.contains("non-empty"),
            "got: {msg}"
        );
    }

    #[test]
    fn ktstr_test_entry_validate_rejects_zero_memory() {
        let e = validate_entry("t", 0, Duration::from_secs(2), 2);
        let err = e.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("memory_mb") && msg.contains("> 0") && msg.contains("'t'"),
            "got: {msg}"
        );
    }

    #[test]
    fn ktstr_test_entry_validate_rejects_zero_duration() {
        let e = validate_entry("t", 512, Duration::ZERO, 2);
        let err = e.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("duration") && msg.contains("> 0"),
            "got: {msg}"
        );
    }

    #[test]
    fn ktstr_test_entry_validate_rejects_zero_workers() {
        let e = validate_entry("t", 512, Duration::from_secs(2), 0);
        let err = e.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("workers_per_cgroup") && msg.contains("> 0"),
            "got: {msg}"
        );
    }

    // -- TopologyConstraints tests --

    #[test]
    fn topology_constraints_default_has_max_values() {
        let c = TopologyConstraints::DEFAULT;
        assert_eq!(c.max_llcs, Some(12));
        assert_eq!(c.max_numa_nodes, Some(1));
        assert_eq!(c.max_cpus, Some(192));
    }

    #[test]
    fn topology_constraints_max_fields_set() {
        let c = TopologyConstraints {
            max_llcs: Some(16),
            max_numa_nodes: Some(4),
            max_cpus: Some(128),
            ..TopologyConstraints::DEFAULT
        };
        assert_eq!(c.max_llcs, Some(16));
        assert_eq!(c.max_numa_nodes, Some(4));
        assert_eq!(c.max_cpus, Some(128));
        assert_eq!(c.min_numa_nodes, 1);
        assert_eq!(c.min_llcs, 1);
        assert_eq!(c.min_cpus, 1);
    }

    #[test]
    fn topology_constraints_equality() {
        let a = TopologyConstraints::DEFAULT;
        let b = TopologyConstraints::DEFAULT;
        assert_eq!(a, b);

        let c = TopologyConstraints {
            max_llcs: Some(8),
            ..TopologyConstraints::DEFAULT
        };
        assert_ne!(a, c);
    }

    #[test]
    fn accepts_default_allows_within_limits() {
        let c = TopologyConstraints::DEFAULT;
        // 1 NUMA, 8 LLCs, 4 cores, 2 threads = 64 CPUs
        let t = Topology::new(1, 8, 4, 2);
        assert!(c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_default_rejects_multi_numa() {
        let c = TopologyConstraints::DEFAULT;
        // 2 NUMA, 8 LLCs, 4 cores, 2 threads = 64 CPUs
        let t = Topology::new(2, 8, 4, 2);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_default_rejects_too_many_llcs() {
        let c = TopologyConstraints::DEFAULT;
        // 16 LLCs exceeds max_llcs=12
        let t = Topology::new(1, 16, 2, 1);
        assert!(!c.accepts(&t, 128, 32, 32));
    }

    #[test]
    fn accepts_none_means_no_limit() {
        let c = TopologyConstraints {
            max_llcs: None,
            max_numa_nodes: None,
            max_cpus: None,
            ..TopologyConstraints::DEFAULT
        };
        // 4 NUMA, 16 LLCs, 8 cores, 2 threads = 256 CPUs
        let t = Topology::new(4, 16, 8, 2);
        assert!(c.accepts(&t, 512, 32, 32));
    }

    #[test]
    fn accepts_rejects_too_many_llcs() {
        let c = TopologyConstraints {
            max_llcs: Some(4),
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(1, 8, 2, 1);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_allows_llcs_at_max() {
        let c = TopologyConstraints {
            max_llcs: Some(4),
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(1, 4, 2, 1);
        assert!(c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_too_many_numa_nodes() {
        let c = TopologyConstraints {
            max_numa_nodes: Some(2),
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(4, 4, 2, 1);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_allows_numa_at_max() {
        let c = TopologyConstraints {
            max_numa_nodes: Some(2),
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(2, 4, 2, 1);
        assert!(c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_too_many_cpus() {
        let c = TopologyConstraints {
            max_cpus: Some(16),
            ..TopologyConstraints::DEFAULT
        };
        // 4 LLCs * 4 cores * 2 threads = 32 CPUs
        let t = Topology::new(1, 4, 4, 2);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_allows_cpus_at_max() {
        let c = TopologyConstraints {
            max_cpus: Some(16),
            ..TopologyConstraints::DEFAULT
        };
        // 2 LLCs * 4 cores * 2 threads = 16 CPUs
        let t = Topology::new(1, 2, 4, 2);
        assert!(c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_too_few_llcs() {
        let c = TopologyConstraints {
            min_llcs: 4,
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(1, 2, 4, 1);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_exceeding_host_cpus() {
        let c = TopologyConstraints::DEFAULT;
        let t = Topology::new(1, 4, 4, 2); // 32 CPUs
        assert!(!c.accepts(&t, 16, 16, 32)); // host has only 16
    }

    #[test]
    fn accepts_rejects_exceeding_host_llcs() {
        let c = TopologyConstraints::DEFAULT;
        let t = Topology::new(1, 8, 2, 1);
        assert!(!c.accepts(&t, 128, 4, 32)); // host has only 4 LLCs
    }

    #[test]
    fn accepts_combined_min_and_max() {
        let c = TopologyConstraints {
            min_llcs: 2,
            max_llcs: Some(8),
            min_cpus: 4,
            max_cpus: Some(32),
            ..TopologyConstraints::DEFAULT
        };
        // 1 LLC, 4 CPUs -- rejected (min_llcs=2)
        assert!(!c.accepts(&Topology::new(1, 1, 4, 1), 128, 16, 32));
        // 2 LLCs, 4 CPUs -- accepted
        assert!(c.accepts(&Topology::new(1, 2, 2, 1), 128, 16, 32));
        // 16 LLCs, 32 CPUs -- rejected (max_llcs=8)
        assert!(!c.accepts(&Topology::new(1, 16, 2, 1), 128, 16, 32));
        // 8 LLCs, 16 CPUs -- accepted
        assert!(c.accepts(&Topology::new(1, 8, 2, 1), 128, 16, 32));
    }

    #[test]
    fn accepts_requires_smt() {
        let c = TopologyConstraints {
            requires_smt: true,
            ..TopologyConstraints::DEFAULT
        };
        let no_smt = Topology::new(1, 2, 4, 1);
        let with_smt = Topology::new(1, 2, 4, 2);
        assert!(!c.accepts(&no_smt, 128, 16, 32));
        assert!(c.accepts(&with_smt, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_too_few_numa_nodes() {
        let c = TopologyConstraints {
            min_numa_nodes: 2,
            max_numa_nodes: None,
            ..TopologyConstraints::DEFAULT
        };
        let t = Topology::new(1, 4, 4, 1);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_too_few_cpus() {
        let c = TopologyConstraints {
            min_cpus: 32,
            ..TopologyConstraints::DEFAULT
        };
        // 2 LLCs * 4 cores * 2 threads = 16 CPUs
        let t = Topology::new(1, 2, 4, 2);
        assert!(!c.accepts(&t, 128, 16, 32));
    }

    #[test]
    fn accepts_rejects_exceeding_host_cpus_per_llc() {
        let c = TopologyConstraints::DEFAULT;
        // cores_per_llc=8, threads_per_core=2 → 16 CPUs/LLC
        let t = Topology::new(1, 2, 8, 2);
        assert!(!c.accepts(&t, 128, 16, 8));
    }

    // -- validate_entry_flags panic paths --

    #[test]
    #[should_panic(expected = "unknown required_flag")]
    fn validate_entry_flags_unknown_required() {
        static SCHED: Scheduler = Scheduler::new("sched").flags(FLAGS_AB);
        static SCHED_PAYLOAD: crate::test_support::Payload = crate::test_support::Payload {
            name: "sched",
            kind: crate::test_support::PayloadKind::Scheduler(&SCHED),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        let entry = KtstrTestEntry {
            name: "bad_required",
            scheduler: &SCHED_PAYLOAD,
            required_flags: &["nonexistent"],
            ..KtstrTestEntry::DEFAULT
        };
        validate_entry_flags(&entry);
    }

    #[test]
    #[should_panic(expected = "in both required_flags and excluded_flags")]
    fn validate_entry_flags_both_required_and_excluded() {
        static SCHED: Scheduler = Scheduler::new("sched").flags(FLAGS_AB);
        static SCHED_PAYLOAD: crate::test_support::Payload = crate::test_support::Payload {
            name: "sched",
            kind: crate::test_support::PayloadKind::Scheduler(&SCHED),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &[],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        let entry = KtstrTestEntry {
            name: "bad_both",
            scheduler: &SCHED_PAYLOAD,
            required_flags: &["a"],
            excluded_flags: &["a"],
            ..KtstrTestEntry::DEFAULT
        };
        validate_entry_flags(&entry);
    }

    // -- SchedulerSpec::display_name --

    #[test]
    fn display_name_eevdf() {
        assert_eq!(SchedulerSpec::Eevdf.display_name(), "eevdf");
    }

    #[test]
    fn display_name_discover_returns_binary_name() {
        assert_eq!(
            SchedulerSpec::Discover("scx_mitosis").display_name(),
            "scx_mitosis"
        );
    }

    #[test]
    fn display_name_path_returns_path_string() {
        assert_eq!(
            SchedulerSpec::Path("/usr/bin/scx_my_sched").display_name(),
            "/usr/bin/scx_my_sched"
        );
    }

    #[test]
    fn display_name_kernel_builtin_returns_kernel() {
        assert_eq!(
            SchedulerSpec::KernelBuiltin {
                enable: &[],
                disable: &[],
            }
            .display_name(),
            "kernel"
        );
    }

    // -- SchedulerSpec::scheduler_commit --
    //
    // Conservative by design: EVERY variant currently returns
    // None, including `Discover(_)`. `resolve_scheduler`'s 5-path
    // cascade can pick up a binary whose commit is unknown to this
    // process in four of the five paths, so `Discover` returns
    // None to avoid lying. The sidecar's nullable
    // semantics distinguish "unset" from a sentinel so consumers
    // can tell "no userspace binary" (Eevdf, KernelBuiltin) from
    // "external binary, commit unknown" (Path) and "discovered
    // binary, provenance unverified" (Discover). A future
    // introspection path (`binary --version`, ELF note, BuildId
    // lookup) can flip a variant to Some(..) when an authoritative
    // commit is available; until then, None keeps consumers from
    // attributing regressions to the wrong commit. See the method
    // doc for the per-variant rationale.

    #[test]
    fn scheduler_commit_eevdf_returns_none() {
        assert!(
            SchedulerSpec::Eevdf.scheduler_commit().is_none(),
            "Eevdf has no userspace binary — scheduler_commit must \
             be None so the sidecar field distinguishes this case \
             from `Path(_)` (external, unknown commit). Got: {:?}",
            SchedulerSpec::Eevdf.scheduler_commit(),
        );
    }

    #[test]
    fn scheduler_commit_discover_returns_none() {
        // `Discover` is resolved by `resolve_scheduler`'s 5-path
        // cascade. Only the rebuild fallback guarantees the binary
        // matches the current tree; the four pre-built discovery
        // paths (KTSTR_SCHEDULER env, ktstr-binary sibling dir,
        // target/debug/, target/release/) can pick up a binary
        // whose commit is unknown to this process. Synthesizing a
        // commit would be a lie in 4 of 5 cases — so the honest
        // answer today is `None`. A future enhancement that probes
        // the binary (e.g. `--version`, ELF note) can flip this to
        // `Some(..)` when an authoritative commit is available;
        // until then, `None` keeps consumers from attributing
        // regressions to the wrong commit.
        assert!(
            SchedulerSpec::Discover("scx_mitosis")
                .scheduler_commit()
                .is_none(),
            "Discover(_) must return None — resolve_scheduler's \
             cascade can pick up a binary whose commit doesn't \
             match the workspace. Got: {:?}",
            SchedulerSpec::Discover("scx_mitosis").scheduler_commit(),
        );
    }

    #[test]
    fn scheduler_commit_path_returns_none() {
        // External binaries have no reliable introspection path;
        // synthesizing a commit here would be a lie when the
        // binary was built from a different tree.
        assert!(
            SchedulerSpec::Path("/usr/bin/scx_external")
                .scheduler_commit()
                .is_none(),
            "Path(_) points at an externally-built binary — \
             scheduler_commit must be None so consumers don't treat \
             a fabricated commit as authoritative. Got: {:?}",
            SchedulerSpec::Path("/usr/bin/scx_external").scheduler_commit(),
        );
    }

    #[test]
    fn scheduler_commit_kernel_builtin_returns_none() {
        // In-kernel schedulers have no userspace binary. The
        // running kernel's identity belongs in
        // `host.kernel_release`, not here.
        let spec = SchedulerSpec::KernelBuiltin {
            enable: &[],
            disable: &[],
        };
        assert!(
            spec.scheduler_commit().is_none(),
            "KernelBuiltin has no userspace binary — \
             scheduler_commit must be None. Got: {:?}",
            spec.scheduler_commit(),
        );
    }

    // -- all_include_files aggregation tests --
    //
    // Pins the scheduler → payload → workloads → extras order. The
    // dedupe + archive-collision policy lives downstream in
    // `eval::dedupe_include_files`; this aggregator just gathers
    // raw spec strings.

    /// No Payload and no extras declare include_files → empty result.
    /// Regression guard for `all_include_files` returning an implicit
    /// non-empty list (e.g. leaking a default).
    #[test]
    fn all_include_files_empty_when_nothing_declared() {
        let entry = KtstrTestEntry {
            name: "t",
            ..KtstrTestEntry::DEFAULT
        };
        assert!(entry.all_include_files().is_empty());
    }

    /// Scheduler + payload + workloads + extras merge in declaration
    /// order. Pins:
    /// - order is scheduler → payload → workloads (preserving the
    ///   slice order) → extra_include_files
    /// - duplicates are NOT deduped at this layer (that's eval's job)
    #[test]
    fn all_include_files_merges_sources_in_order() {
        static SCHED_PAYLOAD: crate::test_support::Payload = crate::test_support::Payload {
            name: "sched",
            kind: crate::test_support::PayloadKind::Scheduler(
                &crate::test_support::Scheduler::EEVDF,
            ),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &["sched-helper"],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        static PRIMARY: crate::test_support::Payload = crate::test_support::Payload {
            name: "primary",
            kind: crate::test_support::PayloadKind::Binary("fio"),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &["fio"],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        static WL_A: crate::test_support::Payload = crate::test_support::Payload {
            name: "wl_a",
            kind: crate::test_support::PayloadKind::Binary("stress-ng"),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &["stress-ng"],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        static WL_B: crate::test_support::Payload = crate::test_support::Payload {
            name: "wl_b",
            kind: crate::test_support::PayloadKind::Binary("schbench"),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &["schbench"],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        static WORKLOADS: &[&crate::test_support::Payload] = &[&WL_A, &WL_B];
        let entry = KtstrTestEntry {
            name: "t",
            scheduler: &SCHED_PAYLOAD,
            payload: Some(&PRIMARY),
            workloads: WORKLOADS,
            extra_include_files: &["test-fixture.json"],
            ..KtstrTestEntry::DEFAULT
        };
        let got = entry.all_include_files();
        assert_eq!(
            got,
            vec![
                "sched-helper",
                "fio",
                "stress-ng",
                "schbench",
                "test-fixture.json",
            ],
            "aggregation order must be scheduler → payload → workloads → extras",
        );
    }

    /// Absent optional `payload` slot contributes nothing — the
    /// aggregator skips it without the `None → empty-push` misbehavior
    /// a future refactor might introduce.
    #[test]
    fn all_include_files_skips_absent_payload() {
        static SCHED_PAYLOAD: crate::test_support::Payload = crate::test_support::Payload {
            name: "sched",
            kind: crate::test_support::PayloadKind::Scheduler(
                &crate::test_support::Scheduler::EEVDF,
            ),
            output: crate::test_support::OutputFormat::ExitCode,
            default_args: &[],
            default_checks: &[],
            metrics: &[],
            include_files: &["sched-helper"],
            uses_parent_pgrp: false,
            known_flags: None,
            metric_bounds: None,
        };
        let entry = KtstrTestEntry {
            name: "t",
            scheduler: &SCHED_PAYLOAD,
            payload: None,
            workloads: &[],
            extra_include_files: &[],
            ..KtstrTestEntry::DEFAULT
        };
        assert_eq!(entry.all_include_files(), vec!["sched-helper"]);
    }
}