ktstr 0.2.0

Test harness for Linux process schedulers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
//! Host-side guest memory monitor and BPF map introspection.
//!
//! Reads per-CPU runqueue structures from guest VM memory via BTF-resolved
//! offsets. Observes scheduler state without instrumenting the guest
//! kernel or the scheduler under test.
//!
//! The [`bpf_map`] module provides host-side discovery and read/write
//! access to BPF maps in guest memory. The [`bpf_prog`] module provides
//! host-side enumeration of BPF programs and their verifier/runtime stats.
//! Both locate kernel objects by walking IDR xarrays (shared infrastructure
//! in the [`idr`] module) through page table translation. No guest
//! cooperation is needed.
//!
//! See the [Monitor](https://likewhatevs.github.io/ktstr/guide/architecture/monitor.html)
//! chapter of the guide.

pub mod bpf_map;
pub mod bpf_prog;
pub mod btf_offsets;
pub mod guest;
pub mod idr;
pub mod reader;
pub mod symbols;

/// DSQ depth above this value indicates uninitialized guest memory.
/// Real kernels never queue this many tasks on a single CPU's local DSQ.
pub const DSQ_PLAUSIBILITY_CEILING: u32 = 10_000;

/// Number of tick periods a vCPU must have run before rq_clock is expected
/// to have advanced. 10 ticks gives the scheduler tick multiple chances
/// to fire and update rq_clock.
const PREEMPTION_TICK_MULTIPLE: u64 = 10;

/// Default HZ when CONFIG_HZ cannot be determined from the kernel.
/// 250 is the most conservative common value (longest tick period =
/// highest threshold), avoiding false stall detection.
const DEFAULT_HZ: u64 = 250;

/// Compute the vCPU preemption threshold for a given kernel.
///
/// Tries to determine CONFIG_HZ from (in order):
/// 1. Embedded IKCONFIG in the vmlinux (gzip blob after `IKCFG_ST` marker)
/// 2. `.config` next to the kernel image (build directory)
/// 3. Host `/boot/config-$(uname -r)` (covers virtme default: host == guest)
/// 4. Falls back to 250 (40ms threshold)
///
/// Returns the threshold in nanoseconds: `(1e9 / HZ) * 10`.
pub(crate) fn vcpu_preemption_threshold_ns(kernel_path: Option<&std::path::Path>) -> u64 {
    let hz = guest_kernel_hz(kernel_path);
    let tick_ns = 1_000_000_000u64 / hz;
    tick_ns * PREEMPTION_TICK_MULTIPLE
}

/// Determine CONFIG_HZ for the guest kernel.
pub(crate) fn guest_kernel_hz(kernel_path: Option<&std::path::Path>) -> u64 {
    if let Some(kp) = kernel_path {
        // Try embedded IKCONFIG in the vmlinux.
        if let Some(vmlinux) = find_vmlinux(kp)
            && let Some(hz) = read_hz_from_ikconfig(&vmlinux)
        {
            return hz;
        }

        // Try .config next to the kernel image.
        if let Some(hz) = read_hz_from_kernel_dir(kp) {
            return hz;
        }
    }

    // Try host /boot/config-$(uname -r).
    if let Some(hz) = read_hz_from_boot_config() {
        return hz;
    }

    DEFAULT_HZ
}

use crate::vmm::find_vmlinux;

/// IKCONFIG marker: gzip data starts immediately after this 8-byte sequence.
const IKCONFIG_MAGIC: &[u8] = b"IKCFG_ST";

/// Extract CONFIG_HZ from the embedded IKCONFIG blob in a vmlinux ELF.
///
/// The kernel (when built with CONFIG_IKCONFIG) embeds a gzip-compressed
/// copy of `.config` in `.rodata`, bracketed by `IKCFG_ST` / `IKCFG_ED`
/// markers. This function scans the raw bytes for the marker, decompresses
/// the gzip data, and parses CONFIG_HZ from the result.
fn read_hz_from_ikconfig(vmlinux_path: &std::path::Path) -> Option<u64> {
    let data = std::fs::read(vmlinux_path).ok()?;
    let pos = data
        .windows(IKCONFIG_MAGIC.len())
        .position(|w| w == IKCONFIG_MAGIC)?;
    let gz_start = pos + IKCONFIG_MAGIC.len();
    if gz_start >= data.len() {
        return None;
    }
    let cursor = std::io::Cursor::new(&data[gz_start..]);
    let mut decoder = flate2::read::GzDecoder::new(cursor);
    let mut config = String::new();
    std::io::Read::read_to_string(&mut decoder, &mut config).ok()?;
    parse_config_hz(&config)
}

/// Look for a `.config` file in the kernel's build directory and parse
/// CONFIG_HZ from it. Walks up from the kernel image path (e.g.
/// `<root>/arch/x86/boot/bzImage`) toward the build root.
fn read_hz_from_kernel_dir(kernel_path: &std::path::Path) -> Option<u64> {
    let mut dir = kernel_path.parent()?;
    // Walk up at most 4 levels (arch/x86/boot/bzImage -> root).
    for _ in 0..4 {
        let config = dir.join(".config");
        if config.exists() {
            let contents = std::fs::read_to_string(&config).ok()?;
            return parse_config_hz(&contents);
        }
        dir = dir.parent()?;
    }
    None
}

/// Parse CONFIG_HZ=N from `/boot/config-$(uname -r)`.
fn read_hz_from_boot_config() -> Option<u64> {
    let mut uname: libc::utsname = unsafe { std::mem::zeroed() };
    if unsafe { libc::uname(&mut uname) } != 0 {
        return None;
    }
    let release = unsafe { std::ffi::CStr::from_ptr(uname.release.as_ptr()) }
        .to_str()
        .ok()?;
    let path = format!("/boot/config-{release}");
    let contents = std::fs::read_to_string(path).ok()?;
    parse_config_hz(&contents)
}

/// Extract `CONFIG_HZ=N` from kernel config text.
fn parse_config_hz(config: &str) -> Option<u64> {
    for line in config.lines() {
        let line = line.trim();
        if let Some(val) = line.strip_prefix("CONFIG_HZ=") {
            return val.parse().ok();
        }
    }
    None
}

/// Check whether a single monitor sample contains plausible data.
///
/// Returns false when any CPU's local_dsq_depth exceeds the plausibility
/// ceiling, indicating uninitialized guest memory rather than real
/// scheduler state.
pub fn sample_looks_valid(sample: &MonitorSample) -> bool {
    sample
        .cpus
        .iter()
        .all(|cpu| cpu.local_dsq_depth <= DSQ_PLAUSIBILITY_CEILING)
}

/// Find a vmlinux for tests.
///
/// Resolution order (first match wins):
/// 1. `LINUX_ROOT` env var — joined with `/vmlinux`, or used directly if
///    the path itself is a file named `vmlinux`.
/// 2. `./linux/vmlinux` (workspace-local kernel).
/// 3. `../linux/vmlinux` (sibling directory).
/// 4. `/sys/kernel/btf/vmlinux` (host kernel raw BTF — no ELF symbols).
#[cfg(test)]
pub fn find_test_vmlinux() -> Option<std::path::PathBuf> {
    if let Ok(root) = std::env::var("LINUX_ROOT") {
        let p = std::path::Path::new(&root).join("vmlinux");
        if p.exists() {
            return Some(p);
        }
        let p = std::path::PathBuf::from(&root);
        if p.exists() && p.file_name().is_some_and(|n| n == "vmlinux") {
            return Some(p);
        }
    }
    let p = std::path::Path::new("linux/vmlinux");
    if p.exists() {
        return Some(p.to_path_buf());
    }
    let p = std::path::Path::new("../linux/vmlinux");
    if p.exists() {
        return Some(p.to_path_buf());
    }
    let p = std::path::Path::new("/sys/kernel/btf/vmlinux");
    if p.exists() {
        return Some(p.to_path_buf());
    }
    None
}

/// Collected monitor data from a VM run.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MonitorReport {
    /// Periodic snapshots of per-CPU state.
    pub samples: Vec<MonitorSample>,
    /// Aggregated summary statistics.
    pub summary: MonitorSummary,
    /// vCPU preemption threshold (ns) derived from the guest kernel's
    /// CONFIG_HZ at the time the VM ran. Used by evaluate() to gate
    /// stall detection. 0 means use a default.
    #[serde(default)]
    pub preemption_threshold_ns: u64,
}

/// Tracks consecutive threshold violations and records the worst run.
///
/// Used by `MonitorThresholds::evaluate` for imbalance, DSQ depth, fallback
/// rate, keep-last rate, and stall checks. Call `record(true)` on
/// violation, `record(false)` on pass.
#[derive(Debug, Clone, Default)]
struct SustainedViolationTracker {
    consecutive: usize,
    worst_run: usize,
    worst_value: f64,
    worst_at: usize,
}

impl SustainedViolationTracker {
    /// Record a sample. `violated`: whether the threshold was exceeded.
    /// `value`: the metric value for this sample. `at`: sample index.
    fn record(&mut self, violated: bool, value: f64, at: usize) {
        if violated {
            self.consecutive += 1;
            if self.consecutive > self.worst_run {
                self.worst_run = self.consecutive;
                self.worst_value = value;
                self.worst_at = at;
            }
        } else {
            self.consecutive = 0;
        }
    }

    /// Whether the worst run met or exceeded the sustained threshold.
    fn sustained(&self, threshold: usize) -> bool {
        self.worst_run >= threshold
    }
}

/// Point-in-time snapshot of all CPUs.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MonitorSample {
    /// Milliseconds since VM start.
    pub elapsed_ms: u64,
    /// Per-CPU state at this instant.
    pub cpus: Vec<CpuSnapshot>,
    /// Per-program BPF runtime stats (summed across CPUs).
    /// None when no struct_ops programs are loaded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prog_stats: Option<Vec<bpf_prog::ProgRuntimeStats>>,
}

impl MonitorSample {
    /// Create a sample with no prog_stats.
    pub fn new(elapsed_ms: u64, cpus: Vec<CpuSnapshot>) -> Self {
        Self {
            elapsed_ms,
            cpus,
            prog_stats: None,
        }
    }

    /// Compute the imbalance ratio for this sample: max(nr_running) / max(1, min(nr_running)).
    /// Returns 1.0 for empty samples, 0.0 when all CPUs have nr_running=0.
    pub fn imbalance_ratio(&self) -> f64 {
        if self.cpus.is_empty() {
            return 1.0;
        }
        let mut min_nr = u32::MAX;
        let mut max_nr = 0u32;
        for cpu in &self.cpus {
            min_nr = min_nr.min(cpu.nr_running);
            max_nr = max_nr.max(cpu.nr_running);
        }
        max_nr as f64 / min_nr.max(1) as f64
    }

    /// Sum a field from event counters across all CPUs.
    /// Returns `None` if no CPU has event counters.
    pub fn sum_event_field(&self, f: fn(&ScxEventCounters) -> i64) -> Option<i64> {
        let mut total = 0i64;
        let mut any = false;
        for cpu in &self.cpus {
            if let Some(ev) = &cpu.event_counters {
                total += f(ev);
                any = true;
            }
        }
        any.then_some(total)
    }
}

/// Per-CPU state read from guest VM memory.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct CpuSnapshot {
    /// Total runnable tasks on this CPU (`rq.nr_running`).
    pub nr_running: u32,
    /// Tasks managed by the sched_ext scheduler (`scx_rq.nr_running`).
    pub scx_nr_running: u32,
    /// Depth of the scx local dispatch queue (`scx_rq.local_dsq.nr`).
    pub local_dsq_depth: u32,
    /// Runqueue clock value (`rq.clock`). Non-advancing clock indicates a stall.
    pub rq_clock: u64,
    /// sched_ext flags for this CPU (`scx_rq.flags`).
    pub scx_flags: u32,
    /// scx event counters (cumulative). None when event counter
    /// offsets are unavailable or scx_root is not set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_counters: Option<ScxEventCounters>,
    /// Runqueue schedstat fields (cumulative). None when CONFIG_SCHEDSTATS
    /// is not enabled (schedstat offsets unavailable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schedstat: Option<RqSchedstat>,
    /// Cumulative CPU time (ns) of the vCPU thread hosting this CPU.
    /// Used by evaluate() to distinguish real stalls from host preemption.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vcpu_cpu_time_ns: Option<u64>,
    /// Sched domain tree for this CPU. Each entry is one domain level,
    /// ordered from lowest (e.g. SMT) to highest (e.g. NUMA). None when
    /// sched_domain offsets are unavailable or `rq->sd` is null.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sched_domains: Option<Vec<SchedDomainSnapshot>>,
}

/// Per-CPU runqueue schedstat fields read from guest memory.
///
/// Matches kernel `struct rq` schedstat fields (guarded by CONFIG_SCHEDSTATS).
/// `run_delay` and `pcount` come from the embedded `struct sched_info`;
/// the remaining fields are direct members of `struct rq`.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct RqSchedstat {
    /// Cumulative scheduling delay (ns) on this CPU (`rq.rq_sched_info.run_delay`).
    pub run_delay: u64,
    /// Count of non-idle task arrivals on this CPU (`rq.rq_sched_info.pcount`).
    pub pcount: u64,
    /// Yield count (`rq.yld_count`).
    pub yld_count: u32,
    /// Context switch count (`rq.sched_count`).
    pub sched_count: u32,
    /// Go-idle count (`rq.sched_goidle`).
    pub sched_goidle: u32,
    /// Try-to-wake-up count (`rq.ttwu_count`).
    pub ttwu_count: u32,
    /// Try-to-wake-up local count (`rq.ttwu_local`).
    pub ttwu_local: u32,
}

/// Snapshot of one `struct sched_domain` level for a single CPU.
///
/// Domains are ordered from lowest (e.g. SMT, level 0) to highest
/// (e.g. NUMA, level N) following the kernel's `sd->parent` chain.
/// Runtime fields are always present. CONFIG_SCHEDSTATS load balancing
/// stats are in the optional `stats` field.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SchedDomainSnapshot {
    /// Domain level number (`sd->level`). 0 = innermost (e.g. SMT).
    pub level: i32,
    /// Domain name from `sd->name` (e.g. "SMT", "MC", "DIE", "NUMA").
    pub name: String,
    /// Domain flags (`sd->flags`). SD_* values.
    pub flags: i32,
    /// Number of CPUs in this domain's span (`sd->span_weight`).
    pub span_weight: u32,

    // -- Runtime fields (always present) --
    /// Current balance interval in ms (`sd->balance_interval`).
    pub balance_interval: u32,
    /// Consecutive load balance failures (`sd->nr_balance_failed`).
    pub nr_balance_failed: u32,
    /// Number of newidle balance calls (`sd->newidle_call`).
    pub newidle_call: u32,
    /// Successful newidle balance calls (`sd->newidle_success`).
    pub newidle_success: u32,
    /// Newidle balance ratio (`sd->newidle_ratio`).
    pub newidle_ratio: u32,
    /// Max cost of newidle load balancing in ns (`sd->max_newidle_lb_cost`).
    pub max_newidle_lb_cost: u64,

    /// CONFIG_SCHEDSTATS load balancing stats. None when
    /// CONFIG_SCHEDSTATS is not enabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stats: Option<SchedDomainStats>,
}

/// CONFIG_SCHEDSTATS load balancing stats for one `struct sched_domain`.
///
/// Array fields have `CPU_MAX_IDLE_TYPES` (3) elements indexed by
/// `cpu_idle_type`: \[0\] = CPU_NOT_IDLE, \[1\] = CPU_IDLE,
/// \[2\] = CPU_NEWLY_IDLE. All counters are cumulative — compute
/// deltas between samples to get rates.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SchedDomainStats {
    /// `sd->lb_count[CPU_MAX_IDLE_TYPES]`: number of load balance calls.
    pub lb_count: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_failed[CPU_MAX_IDLE_TYPES]`: load balance calls that found
    /// imbalance but failed to move any task.
    pub lb_failed: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_balanced[CPU_MAX_IDLE_TYPES]`: load balance calls that
    /// found no imbalance.
    pub lb_balanced: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_imbalance_load[CPU_MAX_IDLE_TYPES]`: times imbalance was
    /// load-based.
    pub lb_imbalance_load: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_imbalance_util[CPU_MAX_IDLE_TYPES]`: times imbalance was
    /// utilization-based.
    pub lb_imbalance_util: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_imbalance_task[CPU_MAX_IDLE_TYPES]`: times imbalance was
    /// task-count-based.
    pub lb_imbalance_task: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_imbalance_misfit[CPU_MAX_IDLE_TYPES]`: times imbalance was
    /// due to misfit task.
    pub lb_imbalance_misfit: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_gained[CPU_MAX_IDLE_TYPES]`: tasks pulled during load balance.
    pub lb_gained: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_hot_gained[CPU_MAX_IDLE_TYPES]`: cache-hot tasks pulled.
    pub lb_hot_gained: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_nobusyg[CPU_MAX_IDLE_TYPES]`: times no busy group was found.
    pub lb_nobusyg: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],
    /// `sd->lb_nobusyq[CPU_MAX_IDLE_TYPES]`: times no busy queue was found.
    pub lb_nobusyq: [u32; btf_offsets::CPU_MAX_IDLE_TYPES],

    /// `sd->alb_count`: active load balance attempts.
    pub alb_count: u32,
    /// `sd->alb_failed`: active load balance failures.
    pub alb_failed: u32,
    /// `sd->alb_pushed`: tasks pushed via active load balancing.
    pub alb_pushed: u32,

    /// `sd->sbe_count`: exec balance attempts.
    pub sbe_count: u32,
    /// `sd->sbe_balanced`: exec balance found no imbalance.
    pub sbe_balanced: u32,
    /// `sd->sbe_pushed`: tasks pushed via exec balancing.
    pub sbe_pushed: u32,

    /// `sd->sbf_count`: fork balance attempts.
    pub sbf_count: u32,
    /// `sd->sbf_balanced`: fork balance found no imbalance.
    pub sbf_balanced: u32,
    /// `sd->sbf_pushed`: tasks pushed via fork balancing.
    pub sbf_pushed: u32,

    /// `sd->ttwu_wake_remote`: wakeups targeting a remote CPU.
    pub ttwu_wake_remote: u32,
    /// `sd->ttwu_move_affine`: wakeups moved to an affine CPU.
    pub ttwu_move_affine: u32,
    /// `sd->ttwu_move_balance`: wakeups moved for load balance.
    pub ttwu_move_balance: u32,
}

/// Cumulative scx event counter values for a single CPU.
/// These are s64 in the kernel but always non-negative; stored as i64.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ScxEventCounters {
    /// `SCX_EV_SELECT_CPU_FALLBACK`: scheduler's `ops.select_cpu()` failed to find a CPU.
    pub select_cpu_fallback: i64,
    /// `SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE`: dispatch to an offline CPU's local DSQ.
    pub dispatch_local_dsq_offline: i64,
    /// `SCX_EV_DISPATCH_KEEP_LAST`: CPU re-dispatched the previously running task.
    pub dispatch_keep_last: i64,
    /// `SCX_EV_ENQ_SKIP_EXITING`: enqueue skipped because the task is exiting.
    pub enq_skip_exiting: i64,
    /// `SCX_EV_ENQ_SKIP_MIGRATION_DISABLED`: enqueue skipped because migration is disabled.
    pub enq_skip_migration_disabled: i64,
}

/// Aggregated monitor statistics from a set of samples.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MonitorSummary {
    /// Number of samples collected.
    pub total_samples: usize,
    /// Peak imbalance ratio across all samples: `max(nr_running) / max(1, min(nr_running))`.
    pub max_imbalance_ratio: f64,
    /// Peak local DSQ depth across all CPUs and samples.
    pub max_local_dsq_depth: u32,
    /// Whether any CPU's `rq_clock` failed to advance between consecutive
    /// samples. Idle CPUs (`nr_running == 0` in both samples) are exempt.
    pub stall_detected: bool,
    /// Average imbalance ratio across valid samples.
    #[serde(default)]
    pub avg_imbalance_ratio: f64,
    /// Average nr_running per CPU across valid samples.
    #[serde(default)]
    pub avg_nr_running: f64,
    /// Average local DSQ depth per CPU across valid samples.
    #[serde(default)]
    pub avg_local_dsq_depth: f64,
    /// Aggregate event counter deltas over the monitoring window.
    /// None when event counters are not available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_deltas: Option<ScxEventDeltas>,
    /// Aggregate schedstat deltas over the monitoring window.
    /// None when CONFIG_SCHEDSTATS is not enabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schedstat_deltas: Option<SchedstatDeltas>,
    /// Per-program BPF callback profile over the monitoring window.
    /// None when no struct_ops programs are loaded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prog_stats_deltas: Option<Vec<ProgStatsDelta>>,
}

/// Per-program BPF callback profile computed from first/last monitor samples.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ProgStatsDelta {
    /// Program name.
    pub name: String,
    /// Total invocations over the monitoring window.
    pub cnt: u64,
    /// Total CPU time in nanoseconds over the monitoring window.
    pub nsecs: u64,
    /// Average nanoseconds per call (nsecs / cnt). 0 when cnt is 0.
    pub nsecs_per_call: f64,
}

/// Aggregate schedstat deltas computed from first/last monitor samples.
///
/// All values are summed across CPUs and represent the delta over the
/// monitoring window. Rates are per second.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SchedstatDeltas {
    /// Total scheduling delay increase (ns) across all CPUs.
    pub total_run_delay: u64,
    /// Run delay per second (ns/s) across all CPUs.
    pub run_delay_rate: f64,
    /// Total pcount increase across all CPUs.
    pub total_pcount: u64,
    /// Total context switch increase across all CPUs.
    pub total_sched_count: u64,
    /// Context switches per second across all CPUs.
    pub sched_count_rate: f64,
    /// Total yield count increase across all CPUs.
    pub total_yld_count: u64,
    /// Total go-idle count increase across all CPUs.
    pub total_sched_goidle: u64,
    /// Total ttwu count increase across all CPUs.
    pub total_ttwu_count: u64,
    /// Total ttwu_local count increase across all CPUs.
    pub total_ttwu_local: u64,
}

/// Aggregate event counter statistics computed from first/last samples.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ScxEventDeltas {
    /// Total select_cpu_fallback events across all CPUs over the window.
    pub total_fallback: i64,
    /// Fallback events per second (total_fallback / duration_secs).
    pub fallback_rate: f64,
    /// Max single-sample delta of fallback across all CPUs.
    pub max_fallback_burst: i64,
    /// Total dispatch_local_dsq_offline events.
    pub total_dispatch_offline: i64,
    /// Total dispatch_keep_last events.
    pub total_dispatch_keep_last: i64,
    /// Keep-last events per second (total_dispatch_keep_last / duration_secs).
    pub keep_last_rate: f64,
    /// Total enq_skip_exiting events.
    pub total_enq_skip_exiting: i64,
    /// Total enq_skip_migration_disabled events.
    pub total_enq_skip_migration_disabled: i64,
}

impl MonitorSummary {
    pub fn from_samples(samples: &[MonitorSample]) -> Self {
        Self::from_samples_with_threshold(samples, 0)
    }

    /// Like [`from_samples`](Self::from_samples) but uses an explicit
    /// preemption threshold (ns) for stall detection. Pass 0 to derive
    /// the threshold from the host kernel's CONFIG_HZ.
    pub fn from_samples_with_threshold(
        samples: &[MonitorSample],
        preemption_threshold_ns: u64,
    ) -> Self {
        if samples.is_empty() {
            return Self::default();
        }

        let mut max_imbalance_ratio: f64 = 1.0;
        let mut max_local_dsq_depth: u32 = 0;
        let mut sum_imbalance_ratio: f64 = 0.0;
        let mut sum_nr_running: f64 = 0.0;
        let mut sum_local_dsq_depth: f64 = 0.0;
        let mut valid_sample_count: usize = 0;
        let mut total_cpu_readings: usize = 0;

        for sample in samples {
            if sample.cpus.is_empty() || !sample_looks_valid(sample) {
                continue;
            }
            valid_sample_count += 1;
            for cpu in &sample.cpus {
                max_local_dsq_depth = max_local_dsq_depth.max(cpu.local_dsq_depth);
                sum_nr_running += cpu.nr_running as f64;
                sum_local_dsq_depth += cpu.local_dsq_depth as f64;
                total_cpu_readings += 1;
            }
            let ratio = sample.imbalance_ratio();
            sum_imbalance_ratio += ratio;
            if ratio > max_imbalance_ratio {
                max_imbalance_ratio = ratio;
            }
        }

        let avg_imbalance_ratio = if valid_sample_count > 0 {
            sum_imbalance_ratio / valid_sample_count as f64
        } else {
            0.0
        };
        let avg_nr_running = if total_cpu_readings > 0 {
            sum_nr_running / total_cpu_readings as f64
        } else {
            0.0
        };
        let avg_local_dsq_depth = if total_cpu_readings > 0 {
            sum_local_dsq_depth / total_cpu_readings as f64
        } else {
            0.0
        };

        // Stall detection: any CPU whose rq_clock did not advance between
        // consecutive samples. Skip invalid samples.
        // Exempt idle CPUs: nr_running==0 in both samples means the tick
        // is stopped (NOHZ) and rq_clock legitimately does not advance.
        // Exempt preempted vCPUs: vcpu_cpu_time_ns didn't advance enough
        // means the host preempted the vCPU thread.
        let threshold = if preemption_threshold_ns > 0 {
            preemption_threshold_ns
        } else {
            vcpu_preemption_threshold_ns(None)
        };
        let mut stall_detected = false;
        let valid_samples: Vec<&MonitorSample> = samples
            .iter()
            .filter(|s| !s.cpus.is_empty() && sample_looks_valid(s))
            .collect();
        for w in valid_samples.windows(2) {
            let prev = w[0];
            let curr = w[1];
            let cpu_count = prev.cpus.len().min(curr.cpus.len());
            for cpu in 0..cpu_count {
                let idle = curr.cpus[cpu].nr_running == 0 && prev.cpus[cpu].nr_running == 0;
                let cpu_time_advanced = match (
                    curr.cpus[cpu].vcpu_cpu_time_ns,
                    prev.cpus[cpu].vcpu_cpu_time_ns,
                ) {
                    (Some(curr_t), Some(prev_t)) => curr_t.saturating_sub(prev_t) >= threshold,
                    _ => true,
                };
                if curr.cpus[cpu].rq_clock != 0
                    && curr.cpus[cpu].rq_clock == prev.cpus[cpu].rq_clock
                    && !idle
                    && cpu_time_advanced
                {
                    stall_detected = true;
                    break;
                }
            }
            if stall_detected {
                break;
            }
        }

        let event_deltas = Self::compute_event_deltas(samples);
        let schedstat_deltas = Self::compute_schedstat_deltas(samples);
        let prog_stats_deltas = Self::compute_prog_stats_deltas(samples);

        Self {
            total_samples: samples.len(),
            max_imbalance_ratio,
            max_local_dsq_depth,
            stall_detected,
            avg_imbalance_ratio,
            avg_nr_running,
            avg_local_dsq_depth,
            event_deltas,
            schedstat_deltas,
            prog_stats_deltas,
        }
    }

    /// Compute event counter deltas from the sample series.
    /// Returns None if no samples have event counters.
    fn compute_event_deltas(samples: &[MonitorSample]) -> Option<ScxEventDeltas> {
        // Find first and last samples that have event counters on any CPU.
        let has_events = |s: &MonitorSample| s.cpus.iter().any(|c| c.event_counters.is_some());
        let first = samples.iter().find(|s| has_events(s))?;
        let last = samples.iter().rev().find(|s| has_events(s))?;

        let total_fallback = last.sum_event_field(|e| e.select_cpu_fallback).unwrap_or(0)
            - first
                .sum_event_field(|e| e.select_cpu_fallback)
                .unwrap_or(0);
        let total_keep_last = last.sum_event_field(|e| e.dispatch_keep_last).unwrap_or(0)
            - first.sum_event_field(|e| e.dispatch_keep_last).unwrap_or(0);

        // Compute rates.
        let duration_ms = last.elapsed_ms.saturating_sub(first.elapsed_ms);
        let duration_secs = duration_ms as f64 / 1000.0;
        let fallback_rate = if duration_secs > 0.0 {
            total_fallback as f64 / duration_secs
        } else {
            0.0
        };
        let keep_last_rate = if duration_secs > 0.0 {
            total_keep_last as f64 / duration_secs
        } else {
            0.0
        };

        // Max per-sample fallback burst: largest delta between consecutive
        // samples, summed across all CPUs.
        let mut max_fallback_burst: i64 = 0;
        for w in samples.windows(2) {
            let prev_sum = w[0].sum_event_field(|e| e.select_cpu_fallback).unwrap_or(0);
            let curr_sum = w[1].sum_event_field(|e| e.select_cpu_fallback).unwrap_or(0);
            let delta = curr_sum - prev_sum;
            if delta > max_fallback_burst {
                max_fallback_burst = delta;
            }
        }

        let delta = |f: fn(&ScxEventCounters) -> i64| -> i64 {
            last.sum_event_field(f).unwrap_or(0) - first.sum_event_field(f).unwrap_or(0)
        };

        Some(ScxEventDeltas {
            total_fallback,
            fallback_rate,
            max_fallback_burst,
            total_dispatch_offline: delta(|e| e.dispatch_local_dsq_offline),
            total_dispatch_keep_last: total_keep_last,
            keep_last_rate,
            total_enq_skip_exiting: delta(|e| e.enq_skip_exiting),
            total_enq_skip_migration_disabled: delta(|e| e.enq_skip_migration_disabled),
        })
    }

    /// Compute schedstat deltas from the sample series.
    /// Returns None if no samples have schedstat data on any CPU.
    fn compute_schedstat_deltas(samples: &[MonitorSample]) -> Option<SchedstatDeltas> {
        let has_schedstat = |s: &MonitorSample| s.cpus.iter().any(|c| c.schedstat.is_some());
        let first = samples.iter().find(|s| has_schedstat(s))?;
        let last = samples.iter().rev().find(|s| has_schedstat(s))?;

        let sum_field = |s: &MonitorSample, f: fn(&RqSchedstat) -> u64| -> u64 {
            s.cpus
                .iter()
                .filter_map(|c| c.schedstat.as_ref().map(&f))
                .sum()
        };
        let sum_field_u32 = |s: &MonitorSample, f: fn(&RqSchedstat) -> u32| -> u64 {
            s.cpus
                .iter()
                .filter_map(|c| c.schedstat.as_ref().map(|ss| f(ss) as u64))
                .sum()
        };

        let total_run_delay =
            sum_field(last, |ss| ss.run_delay).saturating_sub(sum_field(first, |ss| ss.run_delay));
        let total_pcount =
            sum_field(last, |ss| ss.pcount).saturating_sub(sum_field(first, |ss| ss.pcount));
        let total_sched_count = sum_field_u32(last, |ss| ss.sched_count)
            .saturating_sub(sum_field_u32(first, |ss| ss.sched_count));
        let total_yld_count = sum_field_u32(last, |ss| ss.yld_count)
            .saturating_sub(sum_field_u32(first, |ss| ss.yld_count));
        let total_sched_goidle = sum_field_u32(last, |ss| ss.sched_goidle)
            .saturating_sub(sum_field_u32(first, |ss| ss.sched_goidle));
        let total_ttwu_count = sum_field_u32(last, |ss| ss.ttwu_count)
            .saturating_sub(sum_field_u32(first, |ss| ss.ttwu_count));
        let total_ttwu_local = sum_field_u32(last, |ss| ss.ttwu_local)
            .saturating_sub(sum_field_u32(first, |ss| ss.ttwu_local));

        let duration_ms = last.elapsed_ms.saturating_sub(first.elapsed_ms);
        let duration_secs = duration_ms as f64 / 1000.0;
        let run_delay_rate = if duration_secs > 0.0 {
            total_run_delay as f64 / duration_secs
        } else {
            0.0
        };
        let sched_count_rate = if duration_secs > 0.0 {
            total_sched_count as f64 / duration_secs
        } else {
            0.0
        };

        Some(SchedstatDeltas {
            total_run_delay,
            run_delay_rate,
            total_pcount,
            total_sched_count,
            sched_count_rate,
            total_yld_count,
            total_sched_goidle,
            total_ttwu_count,
            total_ttwu_local,
        })
    }

    /// Compute per-program callback profile from first/last samples
    /// that contain prog_stats.
    fn compute_prog_stats_deltas(samples: &[MonitorSample]) -> Option<Vec<ProgStatsDelta>> {
        let first = samples.iter().find(|s| s.prog_stats.is_some())?;
        let last = samples.iter().rev().find(|s| s.prog_stats.is_some())?;

        let first_progs = first.prog_stats.as_ref()?;
        let last_progs = last.prog_stats.as_ref()?;

        let deltas: Vec<ProgStatsDelta> = last_progs
            .iter()
            .map(|lp| {
                let fp = first_progs.iter().find(|p| p.name == lp.name);
                let cnt = lp.cnt.saturating_sub(fp.map_or(0, |p| p.cnt));
                let nsecs = lp.nsecs.saturating_sub(fp.map_or(0, |p| p.nsecs));
                let nsecs_per_call = if cnt > 0 {
                    nsecs as f64 / cnt as f64
                } else {
                    0.0
                };
                ProgStatsDelta {
                    name: lp.name.clone(),
                    cnt,
                    nsecs,
                    nsecs_per_call,
                }
            })
            .collect();

        if deltas.is_empty() {
            None
        } else {
            Some(deltas)
        }
    }
}

/// Configurable thresholds for monitor-based pass/fail verdicts.
#[derive(Debug, Clone, Copy)]
pub struct MonitorThresholds {
    /// Max allowed imbalance ratio (max_nr_running / max(1, min_nr_running)).
    pub max_imbalance_ratio: f64,
    /// Max allowed local DSQ depth on any CPU in any sample.
    pub max_local_dsq_depth: u32,
    /// Fail when any CPU's rq_clock does not advance between consecutive samples.
    pub fail_on_stall: bool,
    /// Number of consecutive samples that must violate a threshold before failing.
    pub sustained_samples: usize,
    /// Max sustained select_cpu_fallback events/s across all CPUs.
    pub max_fallback_rate: f64,
    /// Max sustained dispatch_keep_last events/s across all CPUs.
    pub max_keep_last_rate: f64,
}

impl MonitorThresholds {
    /// Default thresholds, usable in const context.
    ///
    /// - imbalance 4.0: a scheduler that can't keep CPUs within 4x
    ///   load for `sustained_samples` consecutive reads has a real
    ///   balancing problem. Lower ratios (2-3) false-positive during
    ///   cpuset transitions when cgroups are being created/destroyed.
    /// - DSQ depth 50: local DSQ is a per-CPU overflow queue. Sustained
    ///   depth > 50 means the scheduler is not consuming dispatched tasks.
    ///   Transient spikes during cpuset changes are filtered by the
    ///   sustained_samples window.
    /// - fail_on_stall true: rq_clock not advancing on a CPU with
    ///   runnable tasks means the scheduler stalled. Idle CPUs
    ///   (nr_running==0 in both samples) are exempt because NOHZ
    ///   stops the tick. Preempted vCPUs are exempt when the vCPU
    ///   thread's CPU time didn't advance past the preemption
    ///   threshold. Uses the sustained_samples window.
    /// - sustained_samples 5: at ~100ms sample interval, requires ~500ms
    ///   of sustained violation. Filters transient spikes from cpuset
    ///   reconfiguration, cgroup creation, and scheduler restart.
    /// - max_fallback_rate 200.0: select_cpu_fallback fires when the
    ///   scheduler's ops.select_cpu() fails to find a CPU. Sustained
    ///   200/s across all CPUs indicates systematic select_cpu failure.
    /// - max_keep_last_rate 100.0: dispatch_keep_last fires when a CPU
    ///   re-dispatches the previously running task because the scheduler
    ///   provided nothing. Sustained 100/s indicates dispatch starvation.
    pub const DEFAULT: MonitorThresholds = MonitorThresholds {
        max_imbalance_ratio: 4.0,
        max_local_dsq_depth: 50,
        fail_on_stall: true,
        sustained_samples: 5,
        max_fallback_rate: 200.0,
        max_keep_last_rate: 100.0,
    };
}

impl Default for MonitorThresholds {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Verdict from evaluating monitor data against thresholds.
#[derive(Debug, Clone)]
pub struct MonitorVerdict {
    /// `true` if all thresholds were met.
    pub passed: bool,
    /// Per-violation detail messages (empty when `passed` is true).
    pub details: Vec<String>,
    /// One-line summary: "monitor OK" or "monitor FAILED: N violation(s)".
    pub summary: String,
}

impl MonitorThresholds {
    /// Evaluate a MonitorReport against these thresholds.
    ///
    /// Returns a passing verdict when samples are empty or when the monitor
    /// data appears to be uninitialized guest memory (all rq_clocks identical
    /// across every CPU and sample, or DSQ depths above a plausibility
    /// ceiling). The monitor thread reads raw guest memory via BTF offsets;
    /// in short-lived VMs the kernel may not have populated the per-CPU
    /// runqueue structures before the monitor starts sampling.
    pub fn evaluate(&self, report: &MonitorReport) -> MonitorVerdict {
        let mut details = Vec::new();

        if report.samples.is_empty() {
            return MonitorVerdict {
                passed: true,
                details: vec![],
                summary: "no monitor samples".into(),
            };
        }

        // Validity check: detect uninitialized guest memory.
        // If all rq_clock values across every CPU in every sample are
        // identical, the kernel never wrote to these fields — the monitor
        // was reading zeroed or garbage memory.
        if !Self::data_looks_valid(&report.samples) {
            return MonitorVerdict {
                passed: true,
                details: vec![],
                summary: "monitor data not yet initialized".into(),
            };
        }

        let mut imbalance = SustainedViolationTracker::default();
        let mut dsq = SustainedViolationTracker::default();
        let mut worst_dsq_cpu = 0usize;

        for (i, sample) in report.samples.iter().enumerate() {
            if sample.cpus.is_empty() {
                imbalance.record(false, 0.0, i);
                dsq.record(false, 0.0, i);
                continue;
            }

            // Imbalance check.
            let ratio = sample.imbalance_ratio();
            imbalance.record(ratio > self.max_imbalance_ratio, ratio, i);

            // DSQ depth check.
            let mut dsq_violated = false;
            let mut sample_worst_depth = 0u32;
            let mut sample_worst_cpu = 0usize;
            for (cpu_idx, cpu) in sample.cpus.iter().enumerate() {
                if cpu.local_dsq_depth > self.max_local_dsq_depth
                    && cpu.local_dsq_depth > sample_worst_depth
                {
                    dsq_violated = true;
                    sample_worst_depth = cpu.local_dsq_depth;
                    sample_worst_cpu = cpu_idx;
                }
            }
            dsq.record(dsq_violated, sample_worst_depth as f64, i);
            if dsq_violated && dsq.worst_value == sample_worst_depth as f64 {
                worst_dsq_cpu = sample_worst_cpu;
            }
        }

        let mut failed = false;

        if imbalance.sustained(self.sustained_samples) {
            failed = true;
            details.push(format!(
                "imbalance ratio {:.1} exceeded threshold {:.1} for {} consecutive samples (ending at sample {})",
                imbalance.worst_value,
                self.max_imbalance_ratio,
                imbalance.worst_run,
                imbalance.worst_at,
            ));
        }

        if dsq.sustained(self.sustained_samples) {
            failed = true;
            details.push(format!(
                "local DSQ depth {} on cpu{} exceeded threshold {} for {} consecutive samples (ending at sample {})",
                dsq.worst_value as u32,
                worst_dsq_cpu,
                self.max_local_dsq_depth,
                dsq.worst_run,
                dsq.worst_at,
            ));
        }

        // Stall detection: any CPU whose rq_clock did not advance between
        // consecutive samples. Uses the sustained_samples window like
        // imbalance and DSQ checks. Exempt idle CPUs (nr_running==0 in
        // both samples): NOHZ stops the tick so rq_clock legitimately
        // does not advance.
        if self.fail_on_stall {
            let threshold = if report.preemption_threshold_ns > 0 {
                report.preemption_threshold_ns
            } else {
                vcpu_preemption_threshold_ns(None)
            };

            let num_cpus = report
                .samples
                .iter()
                .map(|s| s.cpus.len())
                .max()
                .unwrap_or(0);
            let mut stall: Vec<SustainedViolationTracker> =
                vec![SustainedViolationTracker::default(); num_cpus];

            for i in 1..report.samples.len() {
                let prev = &report.samples[i - 1];
                let curr = &report.samples[i];
                let cpu_count = prev.cpus.len().min(curr.cpus.len());
                #[allow(clippy::needless_range_loop)]
                // indexes stall[cpu], prev.cpus[cpu], curr.cpus[cpu]
                for cpu in 0..cpu_count {
                    let idle = curr.cpus[cpu].nr_running == 0 && prev.cpus[cpu].nr_running == 0;
                    let cpu_time_advanced = match (
                        curr.cpus[cpu].vcpu_cpu_time_ns,
                        prev.cpus[cpu].vcpu_cpu_time_ns,
                    ) {
                        (Some(curr_t), Some(prev_t)) => curr_t.saturating_sub(prev_t) >= threshold,
                        _ => true,
                    };
                    let is_stall = curr.cpus[cpu].rq_clock != 0
                        && curr.cpus[cpu].rq_clock == prev.cpus[cpu].rq_clock
                        && !idle
                        && cpu_time_advanced;
                    stall[cpu].record(is_stall, curr.cpus[cpu].rq_clock as f64, i);
                }
            }

            #[allow(clippy::needless_range_loop)] // cpu index used in format string
            for cpu in 0..num_cpus {
                if stall[cpu].sustained(self.sustained_samples) {
                    failed = true;
                    details.push(format!(
                        "rq_clock stall on cpu{} for {} consecutive samples (ending at sample {}, clock={})",
                        cpu,
                        stall[cpu].worst_run,
                        stall[cpu].worst_at,
                        stall[cpu].worst_value as u64,
                    ));
                }
            }
        }

        // Event counter rate checks: compute per-sample-interval rates
        // and track sustained violations like imbalance.
        let mut fallback_rate = SustainedViolationTracker::default();
        let mut keep_last_rate = SustainedViolationTracker::default();

        for i in 1..report.samples.len() {
            let prev = &report.samples[i - 1];
            let curr = &report.samples[i];
            let interval_s = curr.elapsed_ms.saturating_sub(prev.elapsed_ms) as f64 / 1000.0;
            if interval_s <= 0.0 {
                fallback_rate.record(false, 0.0, i);
                keep_last_rate.record(false, 0.0, i);
                continue;
            }

            // Fallback rate.
            if let (Some(prev_fb), Some(curr_fb)) = (
                prev.sum_event_field(|e| e.select_cpu_fallback),
                curr.sum_event_field(|e| e.select_cpu_fallback),
            ) {
                let rate = (curr_fb - prev_fb) as f64 / interval_s;
                fallback_rate.record(rate > self.max_fallback_rate, rate, i);
            } else {
                fallback_rate.record(false, 0.0, i);
            }

            // Keep-last rate.
            if let (Some(prev_kl), Some(curr_kl)) = (
                prev.sum_event_field(|e| e.dispatch_keep_last),
                curr.sum_event_field(|e| e.dispatch_keep_last),
            ) {
                let rate = (curr_kl - prev_kl) as f64 / interval_s;
                keep_last_rate.record(rate > self.max_keep_last_rate, rate, i);
            } else {
                keep_last_rate.record(false, 0.0, i);
            }
        }

        if fallback_rate.sustained(self.sustained_samples) {
            failed = true;
            details.push(format!(
                "fallback rate {:.1}/s exceeded threshold {:.1}/s for {} consecutive intervals (ending at sample {})",
                fallback_rate.worst_value,
                self.max_fallback_rate,
                fallback_rate.worst_run,
                fallback_rate.worst_at,
            ));
        }

        if keep_last_rate.sustained(self.sustained_samples) {
            failed = true;
            details.push(format!(
                "keep_last rate {:.1}/s exceeded threshold {:.1}/s for {} consecutive intervals (ending at sample {})",
                keep_last_rate.worst_value,
                self.max_keep_last_rate,
                keep_last_rate.worst_run,
                keep_last_rate.worst_at,
            ));
        }

        let summary = if failed {
            format!("monitor FAILED: {} violation(s)", details.len())
        } else {
            "monitor OK".into()
        };

        MonitorVerdict {
            passed: !failed,
            details,
            summary,
        }
    }

    /// Check whether the monitor samples contain plausible data.
    ///
    /// Returns false when the data looks like uninitialized guest memory:
    /// - All rq_clock values across every CPU in every sample are identical
    ///   (the kernel never wrote to these fields).
    /// - Any local_dsq_depth exceeds a plausibility ceiling (real kernels
    ///   never queue millions of tasks on a single CPU's local DSQ).
    fn data_looks_valid(samples: &[MonitorSample]) -> bool {
        let mut first_clock: Option<u64> = None;
        let mut all_clocks_same = true;

        for sample in samples {
            if !sample_looks_valid(sample) {
                return false;
            }
            for cpu in &sample.cpus {
                match first_clock {
                    None => first_clock = Some(cpu.rq_clock),
                    Some(fc) => {
                        if cpu.rq_clock != fc {
                            all_clocks_same = false;
                        }
                    }
                }
            }
        }

        // If we saw at least 2 clock readings and they were all identical,
        // the data is uninitialized.
        if first_clock.is_some() && all_clocks_same {
            // Check we actually had multiple readings to compare.
            let total_readings: usize = samples.iter().map(|s| s.cpus.len()).sum();
            if total_readings > 1 {
                return false;
            }
        }

        true
    }
}

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

    // -- parse_config_hz / vcpu_preemption_threshold_ns tests --

    #[test]
    fn parse_config_hz_standard() {
        let config = "# comment\nCONFIG_HZ_1000=y\nCONFIG_HZ=1000\n";
        assert_eq!(parse_config_hz(config), Some(1000));
    }

    #[test]
    fn parse_config_hz_250() {
        let config = "CONFIG_HZ=250\n";
        assert_eq!(parse_config_hz(config), Some(250));
    }

    #[test]
    fn parse_config_hz_100() {
        let config = "CONFIG_HZ=100\n";
        assert_eq!(parse_config_hz(config), Some(100));
    }

    #[test]
    fn parse_config_hz_missing() {
        let config = "CONFIG_PREEMPT=y\nCONFIG_HZ_1000=y\n";
        assert_eq!(parse_config_hz(config), None);
    }

    #[test]
    fn parse_config_hz_garbage_value() {
        let config = "CONFIG_HZ=abc\n";
        assert_eq!(parse_config_hz(config), None);
    }

    #[test]
    fn parse_config_hz_whitespace() {
        let config = "  CONFIG_HZ=1000  \n";
        assert_eq!(parse_config_hz(config), Some(1000));
    }

    #[test]
    fn vcpu_threshold_reasonable_range() {
        // With no kernel path, falls back to host config or DEFAULT_HZ=250.
        // Threshold should be between 10ms (HZ=1000) and 100ms (HZ=100).
        let t = vcpu_preemption_threshold_ns(None);
        assert!(
            (10_000_000..=100_000_000).contains(&t),
            "threshold {t} ns outside expected range 10ms-100ms"
        );
    }

    #[test]
    fn vcpu_threshold_default_hz_fallback() {
        // Nonexistent kernel path -> falls back to host config or default.
        let t = vcpu_preemption_threshold_ns(Some(std::path::Path::new("/nonexistent/bzImage")));
        assert!(
            (10_000_000..=100_000_000).contains(&t),
            "fallback threshold {t} ns outside expected range"
        );
    }

    // -- IKCONFIG extraction tests --

    /// Build a synthetic blob: padding + IKCFG_ST marker + gzip(config_text).
    fn make_ikconfig_blob(config_text: &str) -> Vec<u8> {
        use flate2::Compression;
        use flate2::write::GzEncoder;
        use std::io::Write;

        let mut blob = vec![0u8; 64]; // padding
        blob.extend_from_slice(IKCONFIG_MAGIC);
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(config_text.as_bytes()).unwrap();
        blob.extend(encoder.finish().unwrap());
        blob.extend_from_slice(b"IKCFG_ED");
        blob
    }

    #[test]
    fn ikconfig_extracts_hz_1000() {
        let blob = make_ikconfig_blob("CONFIG_HZ=1000\nCONFIG_PREEMPT=y\n");
        let dir = std::env::temp_dir().join("ktstr-ikconfig-test-1000");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("vmlinux");
        std::fs::write(&path, &blob).unwrap();
        assert_eq!(read_hz_from_ikconfig(&path), Some(1000));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ikconfig_extracts_hz_250() {
        let blob = make_ikconfig_blob("CONFIG_HZ=250\n");
        let dir = std::env::temp_dir().join("ktstr-ikconfig-test-250");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("vmlinux");
        std::fs::write(&path, &blob).unwrap();
        assert_eq!(read_hz_from_ikconfig(&path), Some(250));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ikconfig_no_marker_returns_none() {
        let dir = std::env::temp_dir().join("ktstr-ikconfig-test-none");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("vmlinux");
        std::fs::write(&path, b"no marker here").unwrap();
        assert_eq!(read_hz_from_ikconfig(&path), None);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ikconfig_missing_config_hz_returns_none() {
        let blob = make_ikconfig_blob("CONFIG_PREEMPT=y\n");
        let dir = std::env::temp_dir().join("ktstr-ikconfig-test-nohz");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("vmlinux");
        std::fs::write(&path, &blob).unwrap();
        assert_eq!(read_hz_from_ikconfig(&path), None);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn empty_samples_default_summary() {
        let summary = MonitorSummary::from_samples(&[]);
        assert_eq!(summary.total_samples, 0);
        assert_eq!(summary.max_imbalance_ratio, 0.0);
        assert_eq!(summary.max_local_dsq_depth, 0);
        assert!(!summary.stall_detected);
        assert_eq!(summary.avg_imbalance_ratio, 0.0);
        assert_eq!(summary.avg_nr_running, 0.0);
        assert_eq!(summary.avg_local_dsq_depth, 0.0);
    }

    #[test]
    fn single_sample_imbalanced_cpus() {
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    local_dsq_depth: 3,
                    rq_clock: 1000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 4,
                    local_dsq_depth: 1,
                    rq_clock: 2000,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert_eq!(summary.total_samples, 1);
        assert!((summary.max_imbalance_ratio - 4.0).abs() < f64::EPSILON);
        assert_eq!(summary.max_local_dsq_depth, 3);
        assert!(!summary.stall_detected);
        // avg fields: single sample with cpus [nr_running=1, nr_running=4]
        assert!((summary.avg_imbalance_ratio - 4.0).abs() < f64::EPSILON);
        assert!((summary.avg_nr_running - 2.5).abs() < f64::EPSILON);
        assert!((summary.avg_local_dsq_depth - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn stall_detected_when_clock_stuck() {
        let s1 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 5000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 6000,
                    ..Default::default()
                },
            ],
        };
        let s2 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 200,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 5000, // stuck
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 7000,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[s1, s2]);
        assert!(summary.stall_detected);
    }

    #[test]
    fn balanced_cpus_ratio_one() {
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 50,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 3,
                    rq_clock: 100,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 3,
                    rq_clock: 200,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert!((summary.max_imbalance_ratio - 1.0).abs() < f64::EPSILON);
        assert!(!summary.stall_detected);
        assert!((summary.avg_imbalance_ratio - 1.0).abs() < f64::EPSILON);
        assert!((summary.avg_nr_running - 3.0).abs() < f64::EPSILON);
        assert!((summary.avg_local_dsq_depth - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn single_cpu_no_division_by_zero() {
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 10,
            cpus: vec![CpuSnapshot {
                nr_running: 5,
                local_dsq_depth: 2,
                rq_clock: 1000,
                ..Default::default()
            }],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert_eq!(summary.total_samples, 1);
        // Single CPU: min == max, ratio = 1.0
        assert!((summary.max_imbalance_ratio - 1.0).abs() < f64::EPSILON);
        assert_eq!(summary.max_local_dsq_depth, 2);
        assert!(!summary.stall_detected);
    }

    #[test]
    fn all_zero_snapshots() {
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![CpuSnapshot::default(), CpuSnapshot::default()],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert_eq!(summary.total_samples, 1);
        // nr_running=0 for all CPUs: max/max(min,1) = 0/1 = 0.0, but
        // initial max_imbalance_ratio is 1.0 and 0.0 < 1.0, so stays 1.0.
        assert!((summary.max_imbalance_ratio - 1.0).abs() < f64::EPSILON);
        assert_eq!(summary.max_local_dsq_depth, 0);
        // rq_clock=0 is excluded from stall detection
        assert!(!summary.stall_detected);
        // avg: valid sample with 2 all-zero CPUs
        assert_eq!(summary.avg_imbalance_ratio, 0.0);
        assert_eq!(summary.avg_nr_running, 0.0);
        assert_eq!(summary.avg_local_dsq_depth, 0.0);
    }

    #[test]
    fn empty_cpus_in_sample() {
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 10,
            cpus: vec![],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert_eq!(summary.total_samples, 1);
        // Empty cpus slice is skipped via `continue`
        assert!((summary.max_imbalance_ratio - 1.0).abs() < f64::EPSILON);
        // avg: sample skipped (empty cpus), no valid readings
        assert_eq!(summary.avg_imbalance_ratio, 0.0);
        assert_eq!(summary.avg_nr_running, 0.0);
        assert_eq!(summary.avg_local_dsq_depth, 0.0);
    }

    #[test]
    fn min_nr_zero_division_guard() {
        // All CPUs have nr_running=0. The code uses min_nr.max(1) as
        // divisor, so ratio = 0/1 = 0.0, which is < initial 1.0.
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 10,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 0,
                    rq_clock: 100,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 0,
                    rq_clock: 200,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        // Should not panic from division by zero.
        // max_imbalance_ratio stays at initial 1.0 since 0/1=0 < 1.0.
        assert!((summary.max_imbalance_ratio - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn min_nr_zero_max_nr_nonzero() {
        // min_nr=0, max_nr=5: ratio = 5/max(0,1) = 5.0
        let sample = MonitorSample {
            prog_stats: None,
            elapsed_ms: 10,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 0,
                    rq_clock: 100,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 5,
                    rq_clock: 200,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[sample]);
        assert!((summary.max_imbalance_ratio - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn advancing_clocks_no_stall() {
        let s1 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 1000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2000,
                    ..Default::default()
                },
            ],
        };
        let s2 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 200,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 1500,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2500,
                    ..Default::default()
                },
            ],
        };
        let s3 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 300,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 3000,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[s1, s2, s3]);
        assert!(!summary.stall_detected);
        assert_eq!(summary.total_samples, 3);
    }

    #[test]
    fn different_length_cpu_vecs() {
        // First sample has 2 CPUs, second has 3. Stall detection uses
        // min(prev.len, curr.len) = 2, so only CPUs 0-1 are compared.
        let s1 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 1000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2000,
                    ..Default::default()
                },
            ],
        };
        let s2 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 200,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 1500,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2500,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 3000,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[s1, s2]);
        assert!(!summary.stall_detected);
        assert_eq!(summary.total_samples, 2);
        // max_local_dsq_depth comes from all CPUs in all samples.
        assert_eq!(summary.max_local_dsq_depth, 0);
    }

    // -- MonitorThresholds tests --

    fn balanced_sample(elapsed_ms: u64, clock_base: u64) -> MonitorSample {
        MonitorSample {
            prog_stats: None,
            elapsed_ms,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base,
                    local_dsq_depth: 3,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base + 100,
                    local_dsq_depth: 2,
                    ..Default::default()
                },
            ],
        }
    }

    #[test]
    fn thresholds_default_values() {
        let t = MonitorThresholds::default();
        assert!((t.max_imbalance_ratio - 4.0).abs() < f64::EPSILON);
        assert_eq!(t.max_local_dsq_depth, 50);
        assert!(t.fail_on_stall);
        assert_eq!(t.sustained_samples, 5);
    }

    #[test]
    fn thresholds_empty_report_passes() {
        let t = MonitorThresholds::default();
        let report = MonitorReport {
            samples: vec![],
            summary: MonitorSummary::default(),
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed);
        assert!(v.details.is_empty());
    }

    #[test]
    fn thresholds_balanced_samples_pass() {
        let t = MonitorThresholds::default();
        let samples: Vec<_> = (0..10)
            .map(|i| balanced_sample(i * 100, 1000 + i * 500))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "balanced samples should pass: {:?}", v.details);
    }

    #[test]
    fn thresholds_imbalance_below_sustained_passes() {
        let t = MonitorThresholds {
            sustained_samples: 5,
            max_imbalance_ratio: 4.0,
            ..Default::default()
        };
        // 4 consecutive imbalanced samples (below sustained_samples=5).
        let mut samples = Vec::new();
        for i in 0..4 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        // Then a balanced one to break the streak.
        samples.push(balanced_sample(400, 3000));
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "4 imbalanced < sustained_samples=5: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_imbalance_at_sustained_fails() {
        let t = MonitorThresholds {
            sustained_samples: 5,
            max_imbalance_ratio: 4.0,
            ..Default::default()
        };
        // 5 consecutive imbalanced samples (ratio=10, threshold=4).
        let mut samples = Vec::new();
        for i in 0..5u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("imbalance")));
    }

    #[test]
    fn thresholds_dsq_depth_sustained_fails() {
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_local_dsq_depth: 10,
            fail_on_stall: false,
            ..Default::default()
        };
        let mut samples = Vec::new();
        for i in 0..3u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 2,
                        local_dsq_depth: 20,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 2,
                        local_dsq_depth: 5,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("DSQ depth")));
    }

    #[test]
    fn thresholds_dsq_depth_below_sustained_passes() {
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_local_dsq_depth: 10,
            fail_on_stall: false,
            ..Default::default()
        };
        // Only 2 consecutive DSQ violations, then a clean sample.
        let mut samples = Vec::new();
        for i in 0..2u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 2,
                        local_dsq_depth: 20,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 2,
                        local_dsq_depth: 5,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        samples.push(balanced_sample(200, 2000));
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "2 DSQ violations < sustained=3: {:?}", v.details);
    }

    #[test]
    fn thresholds_stall_detected_fails() {
        // Stalls use the sustained_samples window. With sustained_samples=1,
        // a single stall pair triggers failure.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    }, // stuck
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("rq_clock stall")));
    }

    #[test]
    fn thresholds_stall_disabled_passes() {
        let t = MonitorThresholds {
            fail_on_stall: false,
            sustained_samples: 100,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 5000,
                    ..Default::default()
                }],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    }, // stuck but stall check disabled
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "stall disabled should pass: {:?}", v.details);
    }

    #[test]
    fn thresholds_imbalance_interrupted_by_balanced_resets() {
        // 3 imbalanced, 1 balanced, 3 imbalanced — never reaches sustained=5.
        let t = MonitorThresholds {
            sustained_samples: 5,
            max_imbalance_ratio: 4.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let mut samples = Vec::new();
        for i in 0..3u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        samples.push(balanced_sample(300, 2500));
        for i in 4..7u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 3000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 3100 + i * 500,
                        ..Default::default()
                    },
                ],
            });
        }
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "interrupted imbalance should pass: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_multiple_violations() {
        // Both imbalance and stall in the same report. Both need to
        // reach sustained_samples to trigger. 3 samples = 2 consecutive
        // stall pairs for cpu0 (clock stuck at 1000), 2 consecutive
        // imbalance violations (ratio=5.0 > 2.0).
        let t = MonitorThresholds {
            sustained_samples: 2,
            max_imbalance_ratio: 2.0,
            fail_on_stall: true,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 5,
                        rq_clock: 2000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000,
                        ..Default::default()
                    }, // stall + imbalance
                    CpuSnapshot {
                        nr_running: 5,
                        rq_clock: 3000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 300,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000,
                        ..Default::default()
                    }, // stall continues
                    CpuSnapshot {
                        nr_running: 5,
                        rq_clock: 4000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("imbalance")));
        assert!(v.details.iter().any(|d| d.contains("rq_clock stall")));
    }

    #[test]
    fn thresholds_empty_cpus_samples_pass() {
        let t = MonitorThresholds::default();
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed);
    }

    #[test]
    fn thresholds_uninitialized_memory_passes() {
        // Simulates what happens when monitor reads guest memory before
        // kernel initialization: all rq_clocks identical, DSQ depths garbage.
        let t = MonitorThresholds::default();
        let garbage_clock = 10314579376562252011u64;
        let samples: Vec<_> = (0..10)
            .map(|i| MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 0,
                        rq_clock: garbage_clock,
                        local_dsq_depth: 1550435906,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 0,
                        rq_clock: garbage_clock,
                        local_dsq_depth: 1550435906,
                        ..Default::default()
                    },
                ],
            })
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "uninitialized guest memory should be skipped: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_all_same_clocks_passes() {
        // All clocks identical across all CPUs and samples = uninitialized.
        let t = MonitorThresholds {
            fail_on_stall: true,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "all-same clocks should be treated as uninitialized: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_dsq_over_plausibility_ceiling_passes() {
        let t = MonitorThresholds::default();
        let samples = vec![MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 1000,
                    local_dsq_depth: 50000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 2000,
                    local_dsq_depth: 5,
                    ..Default::default()
                },
            ],
        }];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "implausible DSQ depth should skip evaluation: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_single_cpu_single_sample_valid() {
        // A single reading cannot be compared, so all_clocks_same with
        // total_readings=1 should still be treated as valid.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![CpuSnapshot {
                nr_running: 1,
                rq_clock: 5000,
                ..Default::default()
            }],
        }];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "single reading should be valid: {:?}", v.details);
    }

    // -- Event counter rate threshold tests --

    /// Build a sample with event counters. Each CPU gets the same counter
    /// values so the total across CPUs = ncpus * per_cpu_value.
    fn sample_with_events(
        elapsed_ms: u64,
        clock_base: u64,
        fallback: i64,
        keep_last: i64,
    ) -> MonitorSample {
        MonitorSample {
            prog_stats: None,
            elapsed_ms,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base,
                    event_counters: Some(ScxEventCounters {
                        select_cpu_fallback: fallback,
                        dispatch_keep_last: keep_last,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base + 100,
                    event_counters: Some(ScxEventCounters {
                        select_cpu_fallback: fallback,
                        dispatch_keep_last: keep_last,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
            ],
        }
    }

    #[test]
    fn thresholds_fallback_rate_sustained_fails() {
        // sustained_samples=3, max_fallback_rate=10.0.
        // 100ms intervals, 2 CPUs. Each CPU increments fallback by 10
        // per sample -> delta = 20 total per interval / 0.1s = 200/s > 10.
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_fallback_rate: 10.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..4)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, i as i64 * 10, 0))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("fallback rate")));
    }

    #[test]
    fn thresholds_fallback_rate_below_sustained_passes() {
        // 2 violating intervals then a clean one — below sustained=3.
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_fallback_rate: 10.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let mut samples: Vec<_> = (0..3)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, i as i64 * 10, 0))
            .collect();
        // 4th sample: same fallback as 3rd -> rate = 0.
        samples.push(sample_with_events(300, 2500, 20, 0));
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "2 violations < sustained=3: {:?}", v.details);
    }

    #[test]
    fn thresholds_keep_last_rate_sustained_fails() {
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_keep_last_rate: 10.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..4)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, 0, i as i64 * 10))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        assert!(v.details.iter().any(|d| d.contains("keep_last rate")));
    }

    #[test]
    fn thresholds_keep_last_rate_below_sustained_passes() {
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_keep_last_rate: 10.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let mut samples: Vec<_> = (0..3)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, 0, i as i64 * 10))
            .collect();
        // Reset: same keep_last as previous -> rate = 0.
        samples.push(sample_with_events(300, 2500, 0, 20));
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "2 violations < sustained=3: {:?}", v.details);
    }

    #[test]
    fn thresholds_event_rate_interrupted_resets() {
        // 2 violating intervals, 1 clean, 2 violating — never reaches sustained=3.
        let t = MonitorThresholds {
            sustained_samples: 3,
            max_fallback_rate: 10.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let mut samples = Vec::new();
        // 3 samples = 2 intervals of high fallback rate.
        for i in 0..3u64 {
            samples.push(sample_with_events(
                i * 100,
                1000 + i * 500,
                i as i64 * 10,
                0,
            ));
        }
        // Clean interval: same fallback -> rate = 0.
        samples.push(sample_with_events(300, 2500, 20, 0));
        // 3 more samples = 2 intervals of high fallback rate (not 3).
        // The fallback delta for the first interval covers sample 3->4,
        // which is (30-20)/0.1 = 100/s (violating), then 4->5 is also
        // violating. That's 2 intervals, below sustained=3.
        for i in 0..2u64 {
            samples.push(sample_with_events(
                400 + i * 100,
                3000 + i * 500,
                30 + (i + 1) as i64 * 10,
                0,
            ));
        }
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "interrupted rate violations should pass: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_no_event_counters_skips_rate_check() {
        // Samples without event counters should not trigger rate violations.
        let t = MonitorThresholds {
            sustained_samples: 1,
            max_fallback_rate: 0.0, // any rate would fail
            max_keep_last_rate: 0.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..5)
            .map(|i| balanced_sample(i * 100, 1000 + i * 500))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "no event counters should skip rate check: {:?}",
            v.details
        );
    }

    #[test]
    fn thresholds_default_event_rate_values() {
        let t = MonitorThresholds::default();
        assert!((t.max_fallback_rate - 200.0).abs() < f64::EPSILON);
        assert!((t.max_keep_last_rate - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn summary_keep_last_rate_computed() {
        // 2 CPUs, each with keep_last incrementing by 5 per sample.
        // 3 samples over 200ms -> total delta = 2*10 = 20, rate = 20/0.2 = 100.
        let samples = vec![
            sample_with_events(0, 1000, 0, 0),
            sample_with_events(100, 1500, 0, 5),
            sample_with_events(200, 2000, 0, 10),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let deltas = summary.event_deltas.unwrap();
        assert!((deltas.keep_last_rate - 100.0).abs() < f64::EPSILON);
    }

    // -- compute_event_deltas edge cases --

    #[test]
    fn event_deltas_none_without_counters() {
        let samples = vec![balanced_sample(100, 1000), balanced_sample(200, 1500)];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(summary.event_deltas.is_none());
    }

    #[test]
    fn event_deltas_single_sample() {
        // Only one sample with events -> first == last, duration=0, rates=0.
        let samples = vec![sample_with_events(100, 1000, 50, 25)];
        let summary = MonitorSummary::from_samples(&samples);
        let deltas = summary.event_deltas.unwrap();
        assert_eq!(deltas.fallback_rate, 0.0);
        assert_eq!(deltas.keep_last_rate, 0.0);
    }

    #[test]
    fn event_deltas_max_fallback_burst() {
        // 3 samples: burst between samples 1 and 2.
        let samples = vec![
            sample_with_events(0, 1000, 0, 0),
            sample_with_events(100, 1500, 5, 0),
            sample_with_events(200, 2000, 100, 0),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let deltas = summary.event_deltas.unwrap();
        // Per-CPU: burst is (100-5)*2 = 190 across 2 CPUs.
        assert!(deltas.max_fallback_burst > 0);
    }

    #[test]
    fn event_deltas_all_counters_computed() {
        let make = |elapsed_ms, fb, kl, dsq_off, exit, migdis| MonitorSample {
            prog_stats: None,
            elapsed_ms,
            cpus: vec![CpuSnapshot {
                nr_running: 1,
                rq_clock: elapsed_ms * 10,
                event_counters: Some(ScxEventCounters {
                    select_cpu_fallback: fb,
                    dispatch_local_dsq_offline: dsq_off,
                    dispatch_keep_last: kl,
                    enq_skip_exiting: exit,
                    enq_skip_migration_disabled: migdis,
                }),
                ..Default::default()
            }],
        };
        let samples = vec![
            make(100, 10, 20, 30, 40, 50),
            make(200, 110, 120, 130, 140, 150),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let d = summary.event_deltas.unwrap();
        assert_eq!(d.total_fallback, 100);
        assert_eq!(d.total_dispatch_keep_last, 100);
        assert_eq!(d.total_dispatch_offline, 100);
        assert_eq!(d.total_enq_skip_exiting, 100);
        assert_eq!(d.total_enq_skip_migration_disabled, 100);
    }

    // -- data_looks_valid tests --

    #[test]
    fn data_looks_valid_empty() {
        assert!(MonitorThresholds::data_looks_valid(&[]));
    }

    #[test]
    fn data_looks_valid_normal() {
        let samples = vec![balanced_sample(100, 1000), balanced_sample(200, 2000)];
        assert!(MonitorThresholds::data_looks_valid(&samples));
    }

    #[test]
    fn data_looks_valid_all_same_clocks() {
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        rq_clock: 5000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        rq_clock: 5000,
                        ..Default::default()
                    },
                ],
            },
        ];
        assert!(!MonitorThresholds::data_looks_valid(&samples));
    }

    #[test]
    fn data_looks_valid_dsq_over_ceiling() {
        let samples = vec![MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![CpuSnapshot {
                local_dsq_depth: 50000,
                rq_clock: 1000,
                ..Default::default()
            }],
        }];
        assert!(!MonitorThresholds::data_looks_valid(&samples));
    }

    // -- MonitorSample::imbalance_ratio tests --

    #[test]
    fn imbalance_ratio_empty_cpus() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![],
        };
        assert!((s.imbalance_ratio() - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn imbalance_ratio_single_cpu() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![CpuSnapshot {
                nr_running: 5,
                ..Default::default()
            }],
        };
        assert!((s.imbalance_ratio() - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn imbalance_ratio_balanced() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 3,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 3,
                    ..Default::default()
                },
            ],
        };
        assert!((s.imbalance_ratio() - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn imbalance_ratio_imbalanced() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 2,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 8,
                    ..Default::default()
                },
            ],
        };
        assert!((s.imbalance_ratio() - 4.0).abs() < f64::EPSILON);
    }

    #[test]
    fn imbalance_ratio_zero_min() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 0,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 5,
                    ..Default::default()
                },
            ],
        };
        // min=0, max(0,1)=1, ratio=5/1=5.0
        assert!((s.imbalance_ratio() - 5.0).abs() < f64::EPSILON);
    }

    // -- MonitorSample::sum_event_field tests --

    #[test]
    fn sum_event_field_none_when_no_counters() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![CpuSnapshot::default(), CpuSnapshot::default()],
        };
        assert!(s.sum_event_field(|e| e.select_cpu_fallback).is_none());
    }

    #[test]
    fn sum_event_field_sums_across_cpus() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![
                CpuSnapshot {
                    event_counters: Some(ScxEventCounters {
                        select_cpu_fallback: 10,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                CpuSnapshot {
                    event_counters: Some(ScxEventCounters {
                        select_cpu_fallback: 20,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
            ],
        };
        assert_eq!(s.sum_event_field(|e| e.select_cpu_fallback), Some(30));
    }

    #[test]
    fn sum_event_field_mixed_some_none() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 0,
            cpus: vec![
                CpuSnapshot {
                    event_counters: Some(ScxEventCounters {
                        dispatch_keep_last: 7,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                CpuSnapshot::default(),
            ],
        };
        assert_eq!(s.sum_event_field(|e| e.dispatch_keep_last), Some(7));
    }

    // -- sample_looks_valid tests --

    #[test]
    fn sample_looks_valid_normal() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![CpuSnapshot {
                local_dsq_depth: 5,
                ..Default::default()
            }],
        };
        assert!(sample_looks_valid(&s));
    }

    #[test]
    fn sample_looks_valid_at_ceiling() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![CpuSnapshot {
                local_dsq_depth: DSQ_PLAUSIBILITY_CEILING,
                ..Default::default()
            }],
        };
        assert!(sample_looks_valid(&s));
    }

    #[test]
    fn sample_looks_valid_over_ceiling() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![CpuSnapshot {
                local_dsq_depth: DSQ_PLAUSIBILITY_CEILING + 1,
                ..Default::default()
            }],
        };
        assert!(!sample_looks_valid(&s));
    }

    #[test]
    fn sample_looks_valid_empty_cpus() {
        let s = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![],
        };
        assert!(sample_looks_valid(&s));
    }

    // -- MonitorSummary field value assertions --

    #[test]
    fn from_samples_fields_sane_values() {
        let samples: Vec<_> = (0..5u64)
            .map(|i| MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: (i as u32 + 1),
                        scx_nr_running: i as u32,
                        local_dsq_depth: (i as u32) % 3,
                        rq_clock: 1000 + i * 500,
                        scx_flags: 0,
                        event_counters: Some(ScxEventCounters {
                            select_cpu_fallback: i as i64 * 2,
                            dispatch_keep_last: i as i64,
                            ..Default::default()
                        }),
                        schedstat: None,
                        vcpu_cpu_time_ns: None,
                        sched_domains: None,
                    },
                    CpuSnapshot {
                        nr_running: (i as u32 + 2),
                        scx_nr_running: i as u32 + 1,
                        local_dsq_depth: 0,
                        rq_clock: 1100 + i * 600,
                        scx_flags: 0,
                        event_counters: Some(ScxEventCounters {
                            select_cpu_fallback: i as i64 * 3,
                            dispatch_keep_last: i as i64 * 2,
                            ..Default::default()
                        }),
                        schedstat: None,
                        vcpu_cpu_time_ns: None,
                        sched_domains: None,
                    },
                ],
            })
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        // total_samples matches input count
        assert_eq!(summary.total_samples, 5);
        // max_imbalance_ratio: all samples have nr_running differing by 1,
        // worst case is sample 0: nr_running=[1,2] -> ratio=2.0
        assert!(
            summary.max_imbalance_ratio >= 1.0,
            "ratio must be >= 1.0: {}",
            summary.max_imbalance_ratio
        );
        assert!(
            summary.max_imbalance_ratio <= 10.0,
            "ratio must be reasonable: {}",
            summary.max_imbalance_ratio
        );
        // max_local_dsq_depth: worst is (4 % 3) = 1 on cpu0 at i=4, or (3 % 3)=0 at i=3, (2%3)=2 at i=2
        assert!(
            summary.max_local_dsq_depth <= DSQ_PLAUSIBILITY_CEILING,
            "dsq depth must be below plausibility ceiling: {}",
            summary.max_local_dsq_depth
        );
        assert!(
            summary.max_local_dsq_depth <= 10,
            "dsq depth must be small in this controlled test: {}",
            summary.max_local_dsq_depth
        );
        // stall_detected: rq_clock advances each sample, so no stall
        assert!(
            !summary.stall_detected,
            "no stall expected with advancing rq_clock"
        );
        // event_deltas: should be computed
        let deltas = summary
            .event_deltas
            .as_ref()
            .expect("event deltas must be present");
        assert!(
            deltas.total_fallback >= 0,
            "fallback count must be non-negative"
        );
        assert!(
            deltas.total_dispatch_keep_last >= 0,
            "keep_last count must be non-negative"
        );
        assert!(
            deltas.fallback_rate >= 0.0,
            "fallback rate must be non-negative"
        );
        assert!(
            deltas.keep_last_rate >= 0.0,
            "keep_last rate must be non-negative"
        );
        // avg fields: must be positive with non-zero nr_running input
        assert!(
            summary.avg_imbalance_ratio >= 1.0,
            "avg imbalance must be >= 1.0: {}",
            summary.avg_imbalance_ratio,
        );
        assert!(
            summary.avg_nr_running > 0.0,
            "avg nr_running must be positive: {}",
            summary.avg_nr_running,
        );
        assert!(
            summary.avg_local_dsq_depth >= 0.0,
            "avg dsq_depth must be non-negative: {}",
            summary.avg_local_dsq_depth,
        );
    }

    #[test]
    fn from_samples_empty_all_defaults() {
        // Verify every field of MonitorSummary defaults correctly for empty input,
        // including event_deltas which empty_samples_default_summary does not check.
        let summary = MonitorSummary::from_samples(&[]);
        assert_eq!(summary.total_samples, 0);
        assert_eq!(summary.max_imbalance_ratio, 0.0);
        assert_eq!(summary.max_local_dsq_depth, 0);
        assert!(!summary.stall_detected);
        assert_eq!(summary.avg_imbalance_ratio, 0.0);
        assert_eq!(summary.avg_nr_running, 0.0);
        assert_eq!(summary.avg_local_dsq_depth, 0.0);
        assert!(
            summary.event_deltas.is_none(),
            "empty input must not produce event deltas"
        );
    }

    // ---------------------------------------------------------------
    // Negative tests: verify monitor diagnostics catch controlled failures
    // ---------------------------------------------------------------

    #[test]
    fn neg_tight_imbalance_threshold_catches_mild_imbalance() {
        let t = MonitorThresholds {
            max_imbalance_ratio: 1.0,
            sustained_samples: 2,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..3u64)
            .map(|i| MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 2,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 3,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            })
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            summary.max_imbalance_ratio >= 1.5,
            "summary must capture ratio"
        );
        assert!(!summary.stall_detected, "no stall in this scenario");
        assert_eq!(summary.total_samples, 3);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "imbalance=1.5 must fail threshold=1.0");
        // Format: "imbalance ratio 1.5 exceeded threshold 1.0 for 2 consecutive samples (ending at sample 2)"
        let detail = v.details.iter().find(|d| d.contains("imbalance")).unwrap();
        assert!(detail.contains("ratio"), "must include 'ratio': {detail}");
        assert!(
            detail.contains("exceeded threshold"),
            "must include threshold: {detail}"
        );
        assert!(
            detail.contains("1.0"),
            "must show threshold value: {detail}"
        );
        assert!(
            detail.contains("consecutive samples"),
            "must show sustained count: {detail}"
        );
        assert!(
            detail.contains("ending at sample"),
            "must show sample index: {detail}"
        );
        assert!(
            v.summary.contains("FAILED"),
            "summary must say FAILED: {}",
            v.summary
        );
    }

    #[test]
    fn neg_tight_dsq_threshold_catches_small_depth() {
        let t = MonitorThresholds {
            max_local_dsq_depth: 1,
            sustained_samples: 2,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..3u64)
            .map(|i| MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        local_dsq_depth: 3,
                        rq_clock: 1000 + i * 500,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        local_dsq_depth: 0,
                        rq_clock: 1100 + i * 500,
                        ..Default::default()
                    },
                ],
            })
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        assert_eq!(
            summary.max_local_dsq_depth, 3,
            "summary must capture max depth"
        );
        assert!(
            summary.max_local_dsq_depth <= DSQ_PLAUSIBILITY_CEILING,
            "depth must be plausible"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "dsq_depth=3 must fail threshold=1");
        // Format: "local DSQ depth 3 on cpu0 exceeded threshold 1 for 2 consecutive samples (ending at sample 2)"
        let detail = v.details.iter().find(|d| d.contains("DSQ depth")).unwrap();
        assert!(detail.contains("3"), "must show depth value: {detail}");
        assert!(detail.contains("cpu0"), "must show CPU number: {detail}");
        assert!(
            detail.contains("threshold 1"),
            "must show threshold: {detail}"
        );
        assert!(
            detail.contains("consecutive samples"),
            "must show count: {detail}"
        );
    }

    #[test]
    fn neg_stall_detection_catches_frozen_rq_clock() {
        // Stalls use sustained_samples window. sustained_samples=1 means
        // a single stall pair triggers failure.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            summary.stall_detected,
            "summary.stall_detected must be true"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "frozen rq_clock must be detected");
        let detail = v
            .details
            .iter()
            .find(|d| d.contains("rq_clock stall"))
            .unwrap();
        assert!(detail.contains("cpu0"), "must name frozen CPU: {detail}");
        assert!(
            detail.contains("consecutive samples"),
            "must show sustained count: {detail}"
        );
        assert!(
            detail.contains("clock=5000"),
            "must include frozen clock value: {detail}"
        );
    }

    #[test]
    fn neg_combined_imbalance_and_stall_both_reported() {
        let t = MonitorThresholds {
            max_imbalance_ratio: 2.0,
            sustained_samples: 1,
            fail_on_stall: true,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 2000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 1000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 10,
                        rq_clock: 3000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(summary.stall_detected);
        assert!(summary.max_imbalance_ratio >= 10.0);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed);
        let imb = v.details.iter().find(|d| d.contains("imbalance")).unwrap();
        assert!(
            imb.contains("exceeded threshold 2.0"),
            "imbalance format: {imb}"
        );
        let stall = v
            .details
            .iter()
            .find(|d| d.contains("rq_clock stall"))
            .unwrap();
        assert!(stall.contains("cpu0"), "stall format: {stall}");
        assert!(
            v.details.len() >= 2,
            "both violations must be reported, got {}",
            v.details.len()
        );
        assert!(v.summary.contains("FAILED"), "summary: {}", v.summary);
    }

    #[test]
    fn stall_idle_cpu_exempt() {
        // nr_running==0 on both samples: idle CPU, NOHZ tick stopped.
        // rq_clock not advancing is expected, not a stall.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 0,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 0,
                        rq_clock: 5000, // stuck but idle
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            !summary.stall_detected,
            "idle CPU should not trigger stall in summary"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "idle CPU should not trigger stall: {:?}",
            v.details
        );
    }

    #[test]
    fn stall_idle_to_busy_not_exempt() {
        // nr_running transitions from 0 to 1 — the CPU woke up but
        // rq_clock didn't advance. This IS a stall (the CPU is now
        // busy but the scheduler tick hasn't fired).
        // Second CPU has advancing clock so data_looks_valid passes.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 0,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000, // stuck, but now busy
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            summary.stall_detected,
            "busy CPU with frozen clock is a stall"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            !v.passed,
            "busy CPU with frozen clock must fail: {:?}",
            v.details
        );
    }

    #[test]
    fn stall_sustained_window_filters_transient() {
        // With sustained_samples=3, a 2-sample stall doesn't trigger.
        // Second CPU has advancing clock so data_looks_valid passes.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 3,
            ..Default::default()
        };
        let mut samples = Vec::new();
        // 3 samples: 2 consecutive stall pairs for cpu0, then clock advances.
        for i in 0..3u64 {
            samples.push(MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000, // stuck for all 3
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000 + i * 500, // advancing
                        ..Default::default()
                    },
                ],
            });
        }
        // Break the streak: clock advances in 4th sample.
        samples.push(MonitorSample {
            prog_stats: None,
            elapsed_ms: 300,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 6000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 7500,
                    ..Default::default()
                },
            ],
        });
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        // 2 consecutive stall pairs < sustained_samples=3
        assert!(v.passed, "2 stall pairs < sustained=3: {:?}", v.details);
    }

    #[test]
    fn stall_sustained_window_catches_real_stall() {
        // With sustained_samples=3, 3+ consecutive stall pairs trigger.
        // Second CPU has advancing clock so data_looks_valid passes.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 3,
            ..Default::default()
        };
        // 4 samples = 3 consecutive stall pairs for cpu0. cpu1 advances.
        let samples: Vec<_> = (0..4u64)
            .map(|i| MonitorSample {
                prog_stats: None,
                elapsed_ms: i * 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000, // stuck
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000 + i * 500, // advancing
                        ..Default::default()
                    },
                ],
            })
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "3 consecutive stall pairs must fail");
        assert!(v.details.iter().any(|d| d.contains("rq_clock stall")));
    }

    #[test]
    fn from_samples_idle_cpu_no_stall() {
        // from_samples should not flag stall when both samples have
        // nr_running==0 on the stuck CPU.
        let s1 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 0,
                    rq_clock: 5000,
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 6000,
                    ..Default::default()
                },
            ],
        };
        let s2 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 200,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 0,
                    rq_clock: 5000, // stuck but idle
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 7000,
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples(&[s1, s2]);
        assert!(!summary.stall_detected);
    }

    #[test]
    fn stall_below_sustained_passes() {
        // 1 stall pair with sustained_samples=5 should pass.
        // Second CPU has advancing clock so data_looks_valid passes.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 5,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
            // Clock recovers.
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 300,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 8000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(v.passed, "1 stall < sustained=5: {:?}", v.details);
    }

    #[test]
    fn neg_fallback_rate_threshold_fires() {
        let t = MonitorThresholds {
            sustained_samples: 2,
            max_fallback_rate: 5.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..3u64)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, i as i64 * 10, 0))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            summary.event_deltas.is_some(),
            "event deltas must be computed"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "fallback rate must be caught");
        // Format: "fallback rate 200.0/s exceeded threshold 5.0/s for 2 consecutive intervals (ending at sample 2)"
        let detail = v
            .details
            .iter()
            .find(|d| d.contains("fallback rate"))
            .unwrap();
        assert!(detail.contains("/s"), "must include rate unit: {detail}");
        assert!(
            detail.contains("exceeded threshold"),
            "must state threshold: {detail}"
        );
        assert!(
            detail.contains("5.0/s"),
            "must show threshold value: {detail}"
        );
        assert!(
            detail.contains("consecutive intervals"),
            "must show sustained count: {detail}"
        );
    }

    #[test]
    fn neg_keep_last_rate_threshold_fires() {
        let t = MonitorThresholds {
            sustained_samples: 2,
            max_keep_last_rate: 5.0,
            fail_on_stall: false,
            ..Default::default()
        };
        let samples: Vec<_> = (0..3u64)
            .map(|i| sample_with_events(i * 100, 1000 + i * 500, 0, i as i64 * 10))
            .collect();
        let summary = MonitorSummary::from_samples(&samples);
        assert!(summary.event_deltas.is_some());
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "keep_last rate must be caught");
        // Format: "keep_last rate .../s exceeded threshold 5.0/s for 2 consecutive intervals ..."
        let detail = v
            .details
            .iter()
            .find(|d| d.contains("keep_last rate"))
            .unwrap();
        assert!(detail.contains("/s"), "must include rate unit: {detail}");
        assert!(
            detail.contains("exceeded threshold"),
            "must state threshold: {detail}"
        );
        assert!(
            detail.contains("5.0/s"),
            "must show threshold value: {detail}"
        );
    }

    // -- vCPU CPU time gating tests --

    #[test]
    fn evaluate_suppresses_stall_when_vcpu_preempted() {
        // vcpu_cpu_time_ns shows < threshold advancement -> vCPU was
        // preempted, stall should be suppressed. Use explicit threshold
        // (10ms) to avoid host CONFIG_HZ dependency.
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        vcpu_cpu_time_ns: Some(1_000_000_000),
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        vcpu_cpu_time_ns: Some(1_000_000_000),
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,                        // stuck
                        vcpu_cpu_time_ns: Some(1_000_500_000), // 0.5ms < 10ms threshold
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        vcpu_cpu_time_ns: Some(1_010_000_000),
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples_with_threshold(&samples, 10_000_000);
        assert!(
            !summary.stall_detected,
            "preempted vCPU should not flag stall in summary"
        );
        let report = MonitorReport {
            samples,
            summary,
            preemption_threshold_ns: 10_000_000,
        };
        let v = t.evaluate(&report);
        assert!(
            v.passed,
            "preempted vCPU should suppress stall: {:?}",
            v.details
        );
    }

    #[test]
    fn evaluate_catches_stall_when_vcpu_running() {
        // vcpu_cpu_time_ns shows advancement >= threshold -> vCPU was
        // running, stall is real. Use explicit threshold (10ms) to avoid
        // host CONFIG_HZ dependency (DEFAULT_HZ=250 gives 40ms threshold,
        // which would mask the 10ms advance).
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        vcpu_cpu_time_ns: Some(1_000_000_000),
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        vcpu_cpu_time_ns: Some(1_000_000_000),
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,                        // stuck
                        vcpu_cpu_time_ns: Some(1_010_000_000), // 10ms advance
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        vcpu_cpu_time_ns: Some(1_010_000_000),
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples_with_threshold(&samples, 10_000_000);
        assert!(
            summary.stall_detected,
            "running vCPU with stuck clock is a stall"
        );
        let report = MonitorReport {
            samples,
            summary,
            preemption_threshold_ns: 10_000_000,
        };
        let v = t.evaluate(&report);
        assert!(!v.passed, "running vCPU stall must fail: {:?}", v.details);
        assert!(v.details.iter().any(|d| d.contains("rq_clock stall")));
    }

    #[test]
    fn evaluate_stall_none_vcpu_time_falls_back_to_current_behavior() {
        // vcpu_cpu_time_ns is None -> assume vCPU was running (don't suppress).
        let t = MonitorThresholds {
            fail_on_stall: true,
            sustained_samples: 1,
            ..Default::default()
        };
        let samples = vec![
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 100,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000,
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 6000,
                        ..Default::default()
                    },
                ],
            },
            MonitorSample {
                prog_stats: None,
                elapsed_ms: 200,
                cpus: vec![
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 5000, // stuck, no vcpu_cpu_time_ns
                        ..Default::default()
                    },
                    CpuSnapshot {
                        nr_running: 1,
                        rq_clock: 7000,
                        ..Default::default()
                    },
                ],
            },
        ];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(
            summary.stall_detected,
            "None vcpu time should not suppress stall"
        );
        let report = MonitorReport {
            samples,
            summary,
            ..Default::default()
        };
        let v = t.evaluate(&report);
        assert!(
            !v.passed,
            "None vcpu time should detect stall: {:?}",
            v.details
        );
    }

    #[test]
    fn from_samples_suppresses_stall_when_vcpu_preempted() {
        // from_samples_with_threshold should respect vcpu_cpu_time_ns
        // gating. Use explicit threshold to avoid host CONFIG_HZ dependency.
        let s1 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 100,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 5000,
                    vcpu_cpu_time_ns: Some(1_000_000_000),
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 6000,
                    vcpu_cpu_time_ns: Some(1_000_000_000),
                    ..Default::default()
                },
            ],
        };
        let s2 = MonitorSample {
            prog_stats: None,
            elapsed_ms: 200,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 5000,                        // stuck
                    vcpu_cpu_time_ns: Some(1_000_100_000), // 0.1ms < 10ms threshold
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 1,
                    rq_clock: 7000,
                    vcpu_cpu_time_ns: Some(1_010_000_000),
                    ..Default::default()
                },
            ],
        };
        let summary = MonitorSummary::from_samples_with_threshold(&[s1, s2], 10_000_000);
        assert!(
            !summary.stall_detected,
            "preempted vCPU should not flag stall"
        );
    }

    // -- SchedstatDeltas tests --

    fn sample_with_schedstat(
        elapsed_ms: u64,
        clock_base: u64,
        run_delay: u64,
        pcount: u64,
        sched_count: u32,
        ttwu_count: u32,
    ) -> MonitorSample {
        MonitorSample {
            prog_stats: None,
            elapsed_ms,
            cpus: vec![
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base,
                    schedstat: Some(RqSchedstat {
                        run_delay,
                        pcount,
                        sched_count,
                        ttwu_count,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
                CpuSnapshot {
                    nr_running: 2,
                    rq_clock: clock_base + 100,
                    schedstat: Some(RqSchedstat {
                        run_delay,
                        pcount,
                        sched_count,
                        ttwu_count,
                        ..Default::default()
                    }),
                    ..Default::default()
                },
            ],
        }
    }

    #[test]
    fn schedstat_deltas_computed_from_samples() {
        // 2 CPUs, each starting at run_delay=1000, ending at 5000.
        // Total delta = 2 * (5000 - 1000) = 8000.
        let samples = vec![
            sample_with_schedstat(0, 1000, 1000, 10, 50, 30),
            sample_with_schedstat(1000, 2000, 5000, 20, 100, 60),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let d = summary.schedstat_deltas.unwrap();
        assert_eq!(d.total_run_delay, 8000);
        assert_eq!(d.total_pcount, 20);
        assert_eq!(d.total_sched_count, 100);
        assert_eq!(d.total_ttwu_count, 60);
        // Rate: 8000 ns / 1.0 s = 8000.0 ns/s.
        assert!((d.run_delay_rate - 8000.0).abs() < f64::EPSILON);
        assert!((d.sched_count_rate - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn schedstat_deltas_none_without_schedstat() {
        let samples = vec![balanced_sample(100, 1000), balanced_sample(200, 1500)];
        let summary = MonitorSummary::from_samples(&samples);
        assert!(summary.schedstat_deltas.is_none());
    }

    #[test]
    fn schedstat_deltas_single_sample() {
        // Single sample -> first == last, duration=0, rates=0.
        let samples = vec![sample_with_schedstat(100, 1000, 5000, 10, 50, 30)];
        let summary = MonitorSummary::from_samples(&samples);
        let d = summary.schedstat_deltas.unwrap();
        assert_eq!(d.run_delay_rate, 0.0);
        assert_eq!(d.sched_count_rate, 0.0);
        assert_eq!(d.total_run_delay, 0);
    }

    #[test]
    fn schedstat_deltas_rates() {
        // 1 CPU, 500ms window. run_delay increases by 2000, sched_count by 40.
        // run_delay_rate = 2000 / 0.5 = 4000.0 ns/s.
        // sched_count_rate = 40 / 0.5 = 80.0 /s.
        let samples = vec![
            sample_with_schedstat(0, 1000, 1000, 5, 10, 20),
            sample_with_schedstat(500, 2000, 3000, 15, 50, 40),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let d = summary.schedstat_deltas.unwrap();
        // 2 CPUs, each delta = 2000, total = 4000.
        assert_eq!(d.total_run_delay, 4000);
        // rate = 4000 / 0.5s = 8000.0
        assert!((d.run_delay_rate - 8000.0).abs() < f64::EPSILON);
        // 2 CPUs, each sched_count delta = 40, total = 80.
        assert_eq!(d.total_sched_count, 80);
        // rate = 80 / 0.5s = 160.0
        assert!((d.sched_count_rate - 160.0).abs() < f64::EPSILON);
    }

    #[test]
    fn schedstat_deltas_all_fields() {
        let make = |elapsed_ms, rd, pc, yc, sc, sg, tc, tl| MonitorSample {
            prog_stats: None,
            elapsed_ms,
            cpus: vec![CpuSnapshot {
                nr_running: 1,
                rq_clock: elapsed_ms * 10,
                schedstat: Some(RqSchedstat {
                    run_delay: rd,
                    pcount: pc,
                    yld_count: yc,
                    sched_count: sc,
                    sched_goidle: sg,
                    ttwu_count: tc,
                    ttwu_local: tl,
                }),
                ..Default::default()
            }],
        };
        let samples = vec![
            make(100, 100, 10, 1, 20, 5, 30, 15),
            make(200, 500, 25, 4, 50, 12, 70, 35),
        ];
        let summary = MonitorSummary::from_samples(&samples);
        let d = summary.schedstat_deltas.unwrap();
        assert_eq!(d.total_run_delay, 400);
        assert_eq!(d.total_pcount, 15);
        assert_eq!(d.total_yld_count, 3);
        assert_eq!(d.total_sched_count, 30);
        assert_eq!(d.total_sched_goidle, 7);
        assert_eq!(d.total_ttwu_count, 40);
        assert_eq!(d.total_ttwu_local, 20);
    }

    // -- SustainedViolationTracker direct tests --

    #[test]
    fn sustained_tracker_no_violations() {
        let t = SustainedViolationTracker::default();
        assert!(!t.sustained(3));
        assert_eq!(t.worst_run, 0);
    }

    #[test]
    fn sustained_tracker_single_violation_not_sustained() {
        let mut t = SustainedViolationTracker::default();
        t.record(true, 5.0, 0);
        assert!(!t.sustained(3));
        assert_eq!(t.worst_run, 1);
        assert_eq!(t.worst_at, 0);
        assert!((t.worst_value - 5.0).abs() < f64::EPSILON);
    }

    #[test]
    fn sustained_tracker_meets_threshold() {
        let mut t = SustainedViolationTracker::default();
        t.record(true, 2.0, 0);
        t.record(true, 3.0, 1);
        t.record(true, 4.0, 2);
        assert!(t.sustained(3));
        assert_eq!(t.worst_run, 3);
        assert_eq!(t.worst_at, 2);
        assert!((t.worst_value - 4.0).abs() < f64::EPSILON);
    }

    #[test]
    fn sustained_tracker_reset_on_non_violation() {
        let mut t = SustainedViolationTracker::default();
        t.record(true, 1.0, 0);
        t.record(true, 2.0, 1);
        t.record(false, 0.0, 2); // reset
        t.record(true, 3.0, 3);
        assert!(!t.sustained(3));
        assert_eq!(t.worst_run, 2); // longest consecutive run was 2
        assert_eq!(t.consecutive, 1); // current run is 1
    }

    #[test]
    fn sustained_tracker_worst_run_preserved_after_reset() {
        let mut t = SustainedViolationTracker::default();
        for i in 0..5 {
            t.record(true, i as f64, i);
        }
        t.record(false, 0.0, 5);
        t.record(true, 99.0, 6);
        t.record(true, 100.0, 7);
        // Worst run is 5 from the first sequence.
        assert_eq!(t.worst_run, 5);
        assert!(t.sustained(5));
        assert!(!t.sustained(6));
    }
}