ktstr 0.4.14

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

use super::super::bpf_map::{
    BPF_MAP_TYPE_BLOOM_FILTER, BPF_MAP_TYPE_CGROUP_STORAGE, BPF_MAP_TYPE_HASH,
    BPF_MAP_TYPE_INSN_ARRAY, BPF_MAP_TYPE_LPM_TRIE, BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE,
    BPF_MAP_TYPE_PERCPU_HASH, BPF_MAP_TYPE_QUEUE, BPF_MAP_TYPE_STACK,
};
// `MemReader` brought into scope so the stub readers below can
// call `is_arena_addr` / `read_arena` via dot notation. The FQP
// `super::super::btf_render::MemReader` resolves the trait for
// the `impl ... for StubReader` blocks, but Rust requires the
// trait to be in scope at the method-call site — the test
// bodies invoke `r.is_arena_addr(...)` and `r.read_arena(...)`,
// which fail with E0599 ("no method named `is_arena_addr` found")
// without this `use`.
use super::*;
use crate::monitor::btf_render::MemReader;
// `name_from_str` is the shared helper that packs a `&str` into the
// `(name_bytes, name_len)` representation used by
// [`super::super::bpf_map::BpfMapInfo`]. Single source of truth in
// [`crate::monitor::test_util`] — replaces the prior local
// `map_name_bytes` copy that duplicated the logic verbatim.
use crate::monitor::test_util::name_from_str;

#[test]
fn hex_dump_basic() {
    assert_eq!(hex_dump(&[]), "");
    assert_eq!(hex_dump(&[0]), "00");
    assert_eq!(hex_dump(&[0x12, 0x34, 0xab]), "12 34 ab");
}

/// Empty input renders as empty string. Single-element input
/// renders as one mid-tier glyph (constant non-zero series
/// reads as "no variation"). All-zero series renders as the
/// lowest glyph repeated.
#[test]
fn render_sparkline_edge_cases() {
    assert_eq!(render_sparkline(&[]), "");
    // Single non-zero element: constant series → mid-tier glyph.
    assert_eq!(render_sparkline(&[42]), "");
    // All-zero series: lowest glyph for every entry.
    assert_eq!(render_sparkline(&[0, 0, 0]), "▁▁▁");
    // All-equal non-zero series: mid-tier glyph for every entry.
    assert_eq!(render_sparkline(&[5, 5, 5]), "▅▅▅");
}

/// Strictly-increasing series scales linearly across the glyph
/// set: first sample at min lands at lowest glyph, last sample
/// at max lands at highest. Pin both ends so a future scaling
/// regression that broke either bound is caught.
#[test]
fn render_sparkline_monotonic_scales_to_full_range() {
    let s = render_sparkline(&[0, 1, 2, 3, 4, 5, 6, 7]);
    let chars: Vec<char> = s.chars().collect();
    assert_eq!(chars.len(), 8);
    assert_eq!(chars[0], '', "min must map to lowest glyph: {s}");
    assert_eq!(chars[7], '', "max must map to highest glyph: {s}");
}

/// i64 wrapper saturates negative values to 0, then routes
/// through u64 sparkline. Verifies a counter that briefly
/// dips negative (corrupt read) doesn't crash and produces
/// a sane sparkline.
#[test]
fn render_sparkline_i64_clamps_negatives() {
    let s = render_sparkline_i64(&[-5, 0, 5, 10]);
    // After clamp: [0, 0, 5, 10] → first two at lowest, last
    // two scale up. Just pin length and bounds; exact glyphs
    // depend on integer rounding.
    assert_eq!(s.chars().count(), 4);
}

/// Full SCX_EV_* counter timeline construction: build a
/// MonitorSample with two CPUs reporting event counters,
/// fold to EventCounterSample, verify cross-CPU sums and
/// elapsed_ms propagation.
#[test]
fn event_counter_sample_sums_across_cpus() {
    use super::super::{CpuSnapshot, MonitorSample, ScxEventCounters};
    let cpu_a = CpuSnapshot {
        event_counters: Some(ScxEventCounters {
            select_cpu_fallback: 5,
            bypass_dispatch: 100,
            ..Default::default()
        }),
        ..Default::default()
    };
    let cpu_b = CpuSnapshot {
        event_counters: Some(ScxEventCounters {
            select_cpu_fallback: 7,
            bypass_dispatch: 50,
            ..Default::default()
        }),
        ..Default::default()
    };
    let sample = MonitorSample {
        elapsed_ms: 100,
        cpus: vec![cpu_a, cpu_b],
        prog_stats: None,
    };
    let folded = EventCounterSample::from_monitor_sample(&sample)
        .expect("at least one CPU has event_counters");
    assert_eq!(folded.elapsed_ms, 100);
    assert_eq!(folded.select_cpu_fallback, 12);
    assert_eq!(folded.bypass_dispatch, 150);
}

/// MonitorSample with no CPU reporting event_counters folds
/// to None — propagating an all-zero row would mislead the
/// downstream consumer (a real "every counter at 0" tick
/// looks identical to "every CPU's offsets unresolved").
#[test]
fn event_counter_sample_returns_none_when_no_cpu_has_counters() {
    use super::super::{CpuSnapshot, MonitorSample};
    let cpu = CpuSnapshot {
        event_counters: None,
        ..Default::default()
    };
    let sample = MonitorSample {
        elapsed_ms: 200,
        cpus: vec![cpu],
        prog_stats: None,
    };
    assert!(EventCounterSample::from_monitor_sample(&sample).is_none());
}

/// EventCounterSample serde round-trips cleanly: every field
/// is `i64` (kernel-side `s64`), so a wire-format encode →
/// decode preserves bit patterns including the i64::MAX edge.
#[test]
fn event_counter_sample_serde_roundtrip() {
    let s = EventCounterSample {
        elapsed_ms: 123_456,
        select_cpu_fallback: i64::MAX,
        insert_not_owned: -1, // kernel never produces this
        // but the wire format must
        // preserve whatever the read
        // captured rather than silently
        // clamp.
        ..Default::default()
    };
    let json = serde_json::to_string(&s).unwrap();
    let loaded: EventCounterSample = serde_json::from_str(&json).unwrap();
    assert_eq!(loaded.elapsed_ms, 123_456);
    assert_eq!(loaded.select_cpu_fallback, i64::MAX);
    assert_eq!(loaded.insert_not_owned, -1);
}

#[test]
fn report_serde_roundtrip() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: vec![FailureDumpMap {
            name: "scx_demo.bss".into(),
            map_type: BPF_MAP_TYPE_ARRAY,
            value_size: 8,
            max_entries: 1,
            value: Some(RenderedValue::Uint {
                bits: 32,
                value: 42,
            }),
            entries: Vec::new(),
            percpu_entries: Vec::new(),
            percpu_hash_entries: Vec::new(),
            arena: None,
            ringbuf: None,
            stack_trace: None,
            fd_array: None,
            error: None,
        }],
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let json = serde_json::to_string(&report).unwrap();
    let parsed: FailureDumpReport = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.maps.len(), 1);
    assert_eq!(parsed.maps[0].name, "scx_demo.bss");
    assert_eq!(parsed.maps[0].max_entries, 1);
}

#[test]
fn empty_report_serde() {
    let report = FailureDumpReport::default();
    let json = serde_json::to_string(&report).unwrap();
    let parsed: FailureDumpReport = serde_json::from_str(&json).unwrap();
    assert!(parsed.maps.is_empty());
}

// ---- Display impl coverage --------------------------------------
//
// The Display impl is the human-readable form used in test
// failure output. Pin its layout against representative shapes.

fn make_simple_map() -> FailureDumpMap {
    FailureDumpMap {
        name: "scx_demo.bss".into(),
        map_type: BPF_MAP_TYPE_ARRAY,
        value_size: 8,
        max_entries: 1,
        value: Some(RenderedValue::Struct {
            type_name: Some("task_ctx".into()),
            members: vec![super::super::btf_render::RenderedMember {
                name: "weight".into(),
                value: RenderedValue::Uint {
                    bits: 32,
                    value: 1024,
                },
            }],
        }),
        entries: Vec::new(),
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    }
}

#[test]
fn report_display_empty() {
    let report = FailureDumpReport::default();
    assert_eq!(format!("{report}"), "(empty failure dump)");
}

#[test]
fn report_display_one_map_with_value() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: vec![make_simple_map()],
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    // Map header line.
    assert!(
        out.starts_with("map scx_demo.bss (type="),
        "missing header: {out}"
    );
    // Struct rendering: the inline form is `TypeName{f=v}` — no
    // `struct` keyword, no space before brace, `=` separator.
    assert!(out.contains("task_ctx{"), "missing struct: {out}");
    assert!(out.contains("weight=1024"), "missing member: {out}");
    assert!(out.ends_with('}'), "missing closing brace: {out}");
}

#[test]
fn report_display_multiple_maps_separated() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: vec![make_simple_map(), make_simple_map()],
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    // Maps separated by a blank line (\n\n).
    let blank_line_count = out.matches("\n\n").count();
    assert_eq!(
        blank_line_count, 1,
        "expected one blank-line separator between two maps: {out}"
    );
}

#[test]
fn map_display_includes_error_marker() {
    let mut m = make_simple_map();
    m.value = None;
    m.error = Some("ARRAY value region unreadable".into());
    let out = format!("{m}");
    assert!(
        out.contains("[error: ARRAY value region unreadable]"),
        "missing error marker: {out}"
    );
}

#[test]
fn entry_display_renders_key_and_value() {
    // Scalar key + value: header is `entry: key=7\n  value: 99`.
    // The `=` is the key-assignment marker; `: ` introduces the
    // value field. The renderer doesn't add type breadcrumb for
    // bare scalars.
    let entry = FailureDumpEntry {
        key: Some(RenderedValue::Uint { bits: 32, value: 7 }),
        key_hex: "07 00 00 00".into(),
        value: Some(RenderedValue::Uint {
            bits: 32,
            value: 99,
        }),
        value_hex: "63 00 00 00".into(),
        payload: None,
    };
    let out = format!("{entry}");
    assert!(out.contains("key=7"), "missing key: {out}");
    assert!(out.contains("value: 99"), "missing value: {out}");
}

#[test]
fn entry_display_falls_back_to_hex_when_no_btf() {
    // No BTF → key/value are None; Display surfaces the hex with
    // a `(raw)` marker so the operator distinguishes "no BTF
    // render" from a parsed scalar value.
    let entry = FailureDumpEntry {
        key: None,
        key_hex: "ab cd".into(),
        value: None,
        value_hex: "ef".into(),
        payload: None,
    };
    let out = format!("{entry}");
    assert!(out.contains("ab cd (raw)"), "missing key hex: {out}");
    assert!(out.contains("ef (raw)"), "missing value hex: {out}");
}

#[test]
fn percpu_entry_display_shows_each_cpu() {
    let entry = FailureDumpPercpuEntry {
        key: 0,
        per_cpu: vec![
            Some(RenderedValue::Uint { bits: 32, value: 1 }),
            None,
            Some(RenderedValue::Uint { bits: 32, value: 3 }),
        ],
    };
    let out = format!("{entry}");
    assert!(out.contains("key 0:"));
    assert!(out.contains("cpu 0: 1"));
    assert!(out.contains("cpu 1: <unmapped>"));
    assert!(out.contains("cpu 2: 3"));
}

// ---- vcpu_regs Display coverage ---------------------------------

#[test]
fn report_display_includes_vcpu_regs_section() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: vec![
            Some(VcpuRegSnapshot {
                instruction_pointer: 0x1,
                stack_pointer: 0x2,
                page_table_root: 0x3,
                user_page_table_root: None,
                tcr_el1: None,
            }),
            None,
            Some(VcpuRegSnapshot {
                instruction_pointer: 0xa,
                stack_pointer: 0xb,
                page_table_root: 0xc,
                user_page_table_root: None,
                tcr_el1: None,
            }),
        ],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    // Section header.
    assert!(out.starts_with("vcpu_regs:"), "missing header: {out}");
    // Three vCPU rows: 0 with values, 1 unavailable, 2 with values.
    assert!(out.contains("vcpu 0: ip=0x"), "missing vcpu 0: {out}");
    assert!(
        out.contains("vcpu 1: <unavailable>"),
        "missing vcpu 1 marker: {out}"
    );
    assert!(out.contains("vcpu 2: ip=0x"), "missing vcpu 2: {out}");
}

#[test]
fn report_display_pairs_maps_and_vcpu_regs_with_blank_line() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: vec![make_simple_map()],
        vcpu_regs: vec![Some(VcpuRegSnapshot {
            instruction_pointer: 0x1,
            stack_pointer: 0x2,
            page_table_root: 0x3,
            user_page_table_root: None,
            tcr_el1: None,
        })],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    // Map block, blank line, vcpu_regs section.
    assert!(out.contains("\n\nvcpu_regs:"));
}

#[test]
fn report_display_empty_with_only_vcpu_regs_does_not_say_empty_dump() {
    // An all-empty maps Vec but populated vcpu_regs must still
    // render rather than fall through to "(empty failure dump)".
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: vec![None],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    assert_eq!(out, "vcpu_regs:\n  vcpu 0: <unavailable>");
}

/// Pin the wire shape of a partial dump — the
/// "all_parked but dump prerequisites unavailable" branch in
/// `vmm::run_vm`'s freeze coordinator builds exactly this
/// shape: empty `maps`, populated `vcpu_regs`. Operators
/// reading the JSON / Display output rely on:
///   - Display NOT rendering the "(empty failure dump)"
///     fallback (which would mask the partial),
///   - Display starting with the `vcpu_regs:` section,
///   - JSON serialising `"maps":[]` (NOT skipped, since
///     `Vec::is_empty` is the skip condition only for
///     `vcpu_regs` and a few `Option`/`Vec` fields inside
///     `FailureDumpMap`, not for the top-level `maps` field).
#[test]
fn report_display_partial_with_populated_regs_and_empty_maps() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: vec![Some(VcpuRegSnapshot {
            instruction_pointer: 0xdead,
            stack_pointer: 0xbeef,
            page_table_root: 0xcafe,
            user_page_table_root: None,
            tcr_el1: None,
        })],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };

    // (a) Display: vcpu_regs section present, no fallback.
    let out = format!("{report}");
    assert!(
        out.contains("vcpu_regs:"),
        "Display must contain the vcpu_regs section: {out}"
    );
    assert!(
        out.contains("vcpu 0: ip=0x"),
        "Display must render the BSP register row: {out}"
    );
    assert!(
        !out.contains("(empty failure dump)"),
        "Display must NOT fall through to empty fallback when \
         vcpu_regs is populated: {out}"
    );

    // (b) JSON: maps key present as empty array, NOT
    // skipped — operators downstream reliably distinguish
    // "no maps captured (partial)" from "maps key absent
    // (regression / older schema)".
    let json = serde_json::to_string(&report).expect("serialize");
    assert!(
        json.contains("\"maps\":[]"),
        "JSON must carry empty `maps` array (not skip): {json}"
    );
    assert!(
        json.contains("\"vcpu_regs\""),
        "JSON must carry vcpu_regs key: {json}"
    );
}

// -- DualFailureDumpReport serde + Display tests --

/// Roundtrip a `DualFailureDumpReport` with a populated early
/// snapshot and non-zero metric/threshold fields. Pins the wire
/// format on the dual-snapshot side: the wrapper deserialises
/// back with `early` present and the jiffies fields preserved.
#[test]
fn dual_report_serde_roundtrip_with_early() {
    let early = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: vec![None],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let late = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: vec![None, None],
        sdt_allocations: Vec::new(),
        prog_runtime_stats: Vec::new(),
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(early),
        late,
        early_max_age_jiffies: 1234,
        early_threshold_jiffies: 600,
        early_skipped_reason: None,
    };
    let json = serde_json::to_string(&dual).unwrap();
    let parsed: DualFailureDumpReport = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.schema, SCHEMA_DUAL);
    assert!(parsed.early.is_some(), "early must roundtrip: {json}");
    assert_eq!(parsed.early_max_age_jiffies, 1234);
    assert_eq!(parsed.early_threshold_jiffies, 600);
    assert_eq!(parsed.late.vcpu_regs.len(), 2);
}

/// Zero `early_max_age_jiffies` / `early_threshold_jiffies`
/// must be skipped on serialize (per the
/// `skip_serializing_if = is_zero_u64` attributes). Pinning
/// this keeps the JSON tight when the early snapshot did not
/// fire — a `late`-only run yields a wrapper without the
/// trigger-metric noise.
#[test]
fn dual_report_serde_skips_zero_jiffies_fields() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let json = serde_json::to_string(&dual).unwrap();
    assert!(
        !json.contains("early_max_age_jiffies"),
        "zero early_max_age_jiffies must skip: {json}"
    );
    assert!(
        !json.contains("early_threshold_jiffies"),
        "zero early_threshold_jiffies must skip: {json}"
    );
}

/// Non-zero jiffies fields must serialize so a downstream
/// consumer can recover the trigger condition without
/// recomputing kernel arithmetic. Mirror of the
/// `skips_zero_jiffies_fields` test.
#[test]
fn dual_report_serde_emits_nonzero_jiffies_fields() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 4096,
        early_threshold_jiffies: 2048,
        early_skipped_reason: None,
    };
    let json = serde_json::to_string(&dual).unwrap();
    assert!(
        json.contains("\"early_max_age_jiffies\":4096"),
        "non-zero max_age must serialize: {json}"
    );
    assert!(
        json.contains("\"early_threshold_jiffies\":2048"),
        "non-zero threshold must serialize: {json}"
    );
}

/// The `schema` field is the wire-format discriminant.
/// `FailureDumpReport` carries `"single"`,
/// `DualFailureDumpReport` carries `"dual"`, and the two
/// values are distinguishable so a consumer can inspect a
/// single field before deciding which type to deserialize
/// into.
#[test]
fn dual_report_schema_distinguishes_from_single() {
    let single = FailureDumpReport::default();
    let single_json = serde_json::to_string(&single).unwrap();
    assert!(
        single_json.contains(&format!("\"schema\":\"{SCHEMA_SINGLE}\"")),
        "single carries schema='single': {single_json}"
    );

    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let dual_json = serde_json::to_string(&dual).unwrap();
    assert!(
        dual_json.contains(&format!("\"schema\":\"{SCHEMA_DUAL}\"")),
        "dual carries schema='dual': {dual_json}"
    );
    // The two discriminants are distinct strings — a consumer
    // checking the field can tell the variants apart without
    // attempting deserialization first.
    assert_ne!(SCHEMA_SINGLE, SCHEMA_DUAL);
}

/// Display output for the early=present branch carries the
/// summary header AND the jiffies metadata, so an operator
/// scanning a log can see at a glance whether the early
/// snapshot fired and what trigger condition produced it.
#[test]
fn dual_report_display_present_carries_jiffies() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 9001,
        early_threshold_jiffies: 4500,
        early_skipped_reason: None,
    };
    let s = format!("{dual}");
    assert!(
        s.contains("early=present"),
        "Display must say early=present: {s}"
    );
    assert!(
        s.contains("max_age=9001j"),
        "Display must surface max_age: {s}"
    );
    assert!(
        s.contains("threshold=4500j"),
        "Display must surface threshold: {s}"
    );
}

/// Display output for the early=absent branch carries the
/// summary header AND the documented absence-reason text
/// describing both possible causes (stall fired before the
/// half-way threshold; runnable_at scan setup failed) AND a
/// pointer to the RUST_LOG knob that surfaces scan-resolution
/// diagnostics — so an operator reading "early=absent" knows
/// the next debugging step rather than having to guess.
#[test]
fn dual_report_display_absent_names_both_causes() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let s = format!("{dual}");
    assert!(
        s.contains("early=absent"),
        "Display must say early=absent: {s}"
    );
    assert!(
        s.contains("stall fired before half-way threshold"),
        "Display must name the threshold-not-reached cause: {s}"
    );
    assert!(
        s.contains("runnable_at scan setup failed"),
        "Display must name the scan-setup-failure cause: {s}"
    );
    assert!(
        s.contains("RUST_LOG=ktstr=debug"),
        "Display must point at the RUST_LOG knob for diagnostics: {s}"
    );
}

// -- FailureDumpReportAny serde + Display tests --

/// `FailureDumpReportAny::from_json` picks the `Single` variant
/// for JSON whose `schema` field is `"single"`, the `Dual`
/// variant for `"dual"`, and the `Single` variant for an absent
/// `schema` field (back-compat with pre-discriminant dumps).
/// Unknown schemas return `None` rather than silently falling
/// back to single — mismatching a future richer wrapper as a
/// lossy single shape would be the wrong behaviour. Malformed
/// JSON also returns `None`.
#[test]
fn report_any_dispatch_branches() {
    // Single branch: schema="single".
    let single = FailureDumpReport::default();
    let single_json = serde_json::to_string(&single).expect("serialize single");
    match FailureDumpReportAny::from_json(&single_json) {
        Some(FailureDumpReportAny::Single(_)) => {}
        other => panic!(
            "schema=single must map to Single, got {other:?}",
            other = other.is_some()
        ),
    }

    // Dual branch: schema="dual".
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let dual_json = serde_json::to_string(&dual).expect("serialize dual");
    match FailureDumpReportAny::from_json(&dual_json) {
        Some(FailureDumpReportAny::Dual(_)) => {}
        other => panic!(
            "schema=dual must map to Dual, got {other:?}",
            other = other.is_some()
        ),
    }

    // Absent-schema branch: pre-discriminant dump.
    let absent = r#"{"maps":[],"vcpu_regs":[],"sdt_allocations":[]}"#;
    match FailureDumpReportAny::from_json(absent) {
        Some(FailureDumpReportAny::Single(_)) => {}
        other => panic!(
            "absent schema must default to Single, got {other:?}",
            other = other.is_some()
        ),
    }

    // Unknown schema → None, not a silent single fallback.
    let unknown = r#"{"schema":"triple","maps":[],"vcpu_regs":[],"sdt_allocations":[]}"#;
    assert!(
        FailureDumpReportAny::from_json(unknown).is_none(),
        "unknown schema must return None, not silent fallback"
    );

    // Malformed JSON → None.
    assert!(
        FailureDumpReportAny::from_json("not json").is_none(),
        "garbage input must return None"
    );
}

/// `prog_runtime_stats` populates and round-trips through
/// `FailureDumpReportAny::from_json`. The dispatch test above
/// covers the empty-stats path; this test pins that the field
/// survives wire encoding when populated, mirroring the
/// strict-schema concerns CgroupStats covers in assert.rs.
#[test]
fn report_any_preserves_prog_runtime_stats() {
    use super::super::bpf_prog::ProgRuntimeStats;
    let report = FailureDumpReport {
        prog_runtime_stats: vec![
            ProgRuntimeStats {
                name: "ktstr_enqueue".to_string(),
                cnt: 1_500,
                nsecs: 7_500_000,
                misses: 2,
            },
            ProgRuntimeStats {
                name: "ktstr_dispatch".to_string(),
                cnt: u64::MAX,
                nsecs: u64::MAX,
                misses: u64::MAX,
            },
        ],
        ..Default::default()
    };
    let json = serde_json::to_string(&report).expect("serialize");
    match FailureDumpReportAny::from_json(&json) {
        Some(FailureDumpReportAny::Single(loaded)) => {
            assert_eq!(loaded.prog_runtime_stats.len(), 2);
            assert_eq!(loaded.prog_runtime_stats[0].name, "ktstr_enqueue");
            assert_eq!(loaded.prog_runtime_stats[0].cnt, 1_500);
            assert_eq!(loaded.prog_runtime_stats[0].nsecs, 7_500_000);
            assert_eq!(loaded.prog_runtime_stats[0].misses, 2);
            assert_eq!(loaded.prog_runtime_stats[1].name, "ktstr_dispatch");
            assert_eq!(loaded.prog_runtime_stats[1].cnt, u64::MAX);
            assert_eq!(loaded.prog_runtime_stats[1].nsecs, u64::MAX);
            assert_eq!(loaded.prog_runtime_stats[1].misses, u64::MAX);
        }
        other => panic!(
            "populated single report must round-trip Single, got {:?}",
            other.is_some()
        ),
    }
}

/// Display roundtrip: a Single-wrapped report renders the same
/// as the underlying `FailureDumpReport`'s own Display, and a
/// Dual-wrapped report renders the same as
/// `DualFailureDumpReport`'s Display. The wrapper's Display is
/// transparent.
#[test]
fn report_any_display_matches_underlying() {
    let single = FailureDumpReport::default();
    let single_direct = format!("{single}");
    let single_via_any = format!("{}", FailureDumpReportAny::Single(Box::new(single)));
    assert_eq!(single_direct, single_via_any);

    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 42,
        early_threshold_jiffies: 21,
        early_skipped_reason: None,
    };
    let dual_direct = format!("{dual}");
    let dual_via_any = format!("{}", FailureDumpReportAny::Dual(Box::new(dual)));
    assert_eq!(dual_direct, dual_via_any);
}

// -- ProgRuntimeStats coverage in FailureDumpReport --

/// Roundtrip a populated `prog_runtime_stats` vector through
/// serde, including `u64::MAX` for every counter to lock in
/// the saturation contract documented on
/// [`super::bpf_prog::read_prog_runtime_stats`] (per-CPU sums use
/// `saturating_add`, so observing `u64::MAX` post-deserialize
/// proves the saturation path didn't silently wrap or truncate).
#[test]
fn prog_runtime_stats_serde_roundtrip_with_saturation() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: vec![
            super::super::bpf_prog::ProgRuntimeStats {
                name: "dispatch".to_string(),
                cnt: 12345,
                nsecs: 67890,
                misses: 3,
            },
            super::super::bpf_prog::ProgRuntimeStats {
                name: "saturated".to_string(),
                cnt: u64::MAX,
                nsecs: u64::MAX,
                misses: u64::MAX,
            },
        ],
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let json = serde_json::to_string(&report).expect("serialize");
    let parsed: FailureDumpReport = serde_json::from_str(&json).expect("deserialize");
    assert_eq!(parsed.prog_runtime_stats.len(), 2);
    assert_eq!(parsed.prog_runtime_stats[0].name, "dispatch");
    assert_eq!(parsed.prog_runtime_stats[0].cnt, 12345);
    assert_eq!(parsed.prog_runtime_stats[0].nsecs, 67890);
    assert_eq!(parsed.prog_runtime_stats[0].misses, 3);
    assert_eq!(parsed.prog_runtime_stats[1].cnt, u64::MAX);
    assert_eq!(parsed.prog_runtime_stats[1].nsecs, u64::MAX);
    assert_eq!(parsed.prog_runtime_stats[1].misses, u64::MAX);
}

/// Empty `prog_runtime_stats` skips serialization (the
/// `skip_serializing_if = "Vec::is_empty"` attribute) — same
/// pattern as the other optional vector fields. Pinning this
/// keeps the JSON tight for the common no-struct_ops-loaded
/// case.
#[test]
fn prog_runtime_stats_empty_skips_serialization() {
    let report = FailureDumpReport::default();
    let json = serde_json::to_string(&report).expect("serialize");
    assert!(
        !json.contains("prog_runtime_stats"),
        "empty prog_runtime_stats must be skipped: {json}"
    );
}

/// Display impl renders `prog_runtime_stats` under a labelled
/// section so an operator scanning failure-dump output sees
/// the per-program counters alongside the maps / vcpu_regs /
/// sdt_allocations sections. Pinning this prevents the
/// "rendered fields silently drop" regression that would mask
/// dump enrichment from reaching log readers.
#[test]
fn report_display_renders_prog_runtime_stats() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: vec![
            super::super::bpf_prog::ProgRuntimeStats {
                name: "dispatch".to_string(),
                cnt: 5,
                nsecs: 1234,
                misses: 0,
            },
            super::super::bpf_prog::ProgRuntimeStats {
                name: "enqueue".to_string(),
                cnt: 99,
                nsecs: 9999,
                misses: 7,
            },
        ],
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    assert!(
        out.contains("prog_runtime_stats:"),
        "Display must render the prog_runtime_stats section: {out}"
    );
    assert!(
        out.contains("dispatch: cnt=5 nsecs=1234 misses=0"),
        "Display must render first program line: {out}"
    );
    assert!(
        out.contains("enqueue: cnt=99 nsecs=9999 misses=7"),
        "Display must render second program line: {out}"
    );
}

/// An all-empty maps/vcpu_regs/sdt_allocations report with
/// only `prog_runtime_stats` populated must still render
/// rather than fall through to the "(empty failure dump)"
/// fallback — the empty-check in the Display impl gates on
/// every optional vector, including `prog_runtime_stats`.
#[test]
fn report_display_only_prog_runtime_stats_does_not_say_empty_dump() {
    let report = FailureDumpReport {
        schema: SCHEMA_SINGLE.to_string(),
        maps: Vec::new(),
        vcpu_regs: Vec::new(),
        sdt_allocations: Vec::new(),
        prog_runtime_stats: vec![super::super::bpf_prog::ProgRuntimeStats {
            name: "lone".to_string(),
            cnt: 1,
            nsecs: 2,
            misses: 0,
        }],
        prog_runtime_stats_unavailable: None,
        per_cpu_time: Vec::new(),
        per_node_numa: Vec::new(),
        per_node_numa_unavailable: None,
        task_enrichments: Vec::new(),
        task_enrichments_unavailable: None,
        event_counter_timeline: Vec::new(),
        rq_scx_states: Vec::new(),
        dsq_states: Vec::new(),
        scx_sched_state: None,
        scx_walker_unavailable: None,
        vcpu_perf_at_freeze: Vec::new(),
        dump_truncated_at_us: None,
        probe_counters: None,
    };
    let out = format!("{report}");
    assert!(
        !out.contains("(empty failure dump)"),
        "Display must NOT fall through to empty fallback when \
         prog_runtime_stats is populated: {out}"
    );
    assert!(
        out.starts_with("prog_runtime_stats:"),
        "Display must lead with prog_runtime_stats section when \
         only that field is populated: {out}"
    );
}

// ---- pin failure-dump error-message strings --------------------
//
// The six REASON_* constants emitted by `dump_state` into the
// `*_unavailable` fields are wire-format markers: an operator
// parsing `.failure-dump.json` looks for these exact strings to
// distinguish "no scheduler attached" from "no walker capture
// supplied" etc. Drift in any of them silently breaks downstream
// parsing. The constants near the top of this module are the
// single source of truth; the tests below pin each constant's
// exact value so a regression that re-words a string trips both
// at the constant declaration AND at the test assertion.
//
// The companion strict-schema and chain-limit tests for
// FailureDumpReport / is_scx_allocator_type live further down in
// this module.

#[test]
fn reason_no_struct_ops_loaded_string_pinned() {
    assert_eq!(REASON_NO_STRUCT_OPS_LOADED, "no struct_ops programs loaded");
}

#[test]
fn reason_prog_accessor_unavailable_string_pinned() {
    assert_eq!(
        REASON_PROG_ACCESSOR_UNAVAILABLE,
        "prog accessor unavailable"
    );
}

#[test]
fn reason_task_walker_zero_tasks_string_pinned() {
    assert_eq!(
        REASON_TASK_WALKER_ZERO_TASKS,
        "task walker yielded zero tasks"
    );
}

#[test]
fn reason_no_task_walker_string_pinned() {
    assert_eq!(REASON_NO_TASK_WALKER, "no task walker available");
}

#[test]
fn reason_scx_walker_no_state_string_pinned() {
    assert_eq!(REASON_SCX_WALKER_NO_STATE, "scx walker reached no state");
}

#[test]
fn reason_scx_root_null_string_pinned() {
    assert_eq!(
        REASON_SCX_ROOT_NULL,
        "scx_root is NULL (no scheduler attached)"
    );
}

#[test]
fn reason_no_scx_walker_string_pinned() {
    assert_eq!(REASON_NO_SCX_WALKER, "no scx walker capture");
}

/// Every reason constant must round-trip through the JSON wire
/// format embedded in the `*_unavailable` fields. A regression
/// that altered the field's serde encoding (renamed the field,
/// added `#[serde(rename = ...)]`, etc.) would also break the
/// operator's string-match parsing — surface that here too.
#[test]
fn reason_strings_round_trip_through_serde() {
    let report = FailureDumpReport {
        prog_runtime_stats_unavailable: Some(REASON_NO_STRUCT_OPS_LOADED.to_string()),
        task_enrichments_unavailable: Some(REASON_TASK_WALKER_ZERO_TASKS.to_string()),
        scx_walker_unavailable: Some(REASON_SCX_WALKER_NO_STATE.to_string()),
        ..Default::default()
    };
    let json = serde_json::to_string(&report).expect("serialize");
    // Each reason must appear verbatim in the JSON; a future
    // wire-format change (e.g. tagged enum) would hide them
    // behind nested objects and trip this assertion.
    assert!(
        json.contains(REASON_NO_STRUCT_OPS_LOADED),
        "JSON must contain prog reason verbatim: {json}",
    );
    assert!(
        json.contains(REASON_TASK_WALKER_ZERO_TASKS),
        "JSON must contain task reason verbatim: {json}",
    );
    assert!(
        json.contains(REASON_SCX_WALKER_NO_STATE),
        "JSON must contain scx reason verbatim: {json}",
    );

    let loaded: FailureDumpReport = serde_json::from_str(&json).expect("deserialize");
    assert_eq!(
        loaded.prog_runtime_stats_unavailable.as_deref(),
        Some(REASON_NO_STRUCT_OPS_LOADED),
    );
    assert_eq!(
        loaded.task_enrichments_unavailable.as_deref(),
        Some(REASON_TASK_WALKER_ZERO_TASKS),
    );
    assert_eq!(
        loaded.scx_walker_unavailable.as_deref(),
        Some(REASON_SCX_WALKER_NO_STATE),
    );
}

// -- Strict-schema tests for FailureDumpReport -------------------
//
// Mirrors the CgroupStats / ScenarioStats / SidecarResult tests in
// assert.rs and test_support/sidecar.rs. FailureDumpReport's
// contract is narrower than CgroupStats's because most of its
// fields are intentionally optional (capture pipelines may
// legitimately produce no entries), so the CgroupStats
// "remove every field" loop would over-assert here.
//
// Asserted contract:
//   - `maps` is the only required field on the wire.
//   - `schema` is `serde(default = default_schema_single)` —
//     omission yields `SCHEMA_SINGLE`.
//   - Every other field is `serde(default, skip_serializing_if =
//     ...)` — omission MUST succeed.
//
// A regression that softens `maps` to `serde(default)` (e.g. to
// soften a schema migration) would silently produce empty-maps
// dumps that look indistinguishable from a legitimate no-maps
// run. A regression that hardens an optional field to require it
// on the wire would break replay of older dumps. Either drift
// trips this test.

/// Removing the `maps` field MUST fail deserialize. `maps`
/// carries the BPF map enumeration that is the dump's only
/// mandatory payload — every other field is
/// capture-pipeline-optional. The deserialize error MUST name
/// `maps` so a regression produces a debuggable failure rather
/// than a silent default.
#[test]
fn failure_dump_report_strict_schema_maps_required() {
    let report = FailureDumpReport::default();
    let mut full = match serde_json::to_value(&report).unwrap() {
        serde_json::Value::Object(m) => m,
        other => panic!("expected object, got {other:?}"),
    };
    assert!(
        full.remove("maps").is_some(),
        "FailureDumpReport must emit `maps` for this test to be \
         meaningful — the field has been renamed or removed",
    );
    let json = serde_json::Value::Object(full).to_string();
    let err = serde_json::from_str::<FailureDumpReport>(&json)
        .expect_err("deserialize must reject FailureDumpReport with `maps` removed");
    let msg = format!("{err}");
    assert!(
        msg.contains("maps"),
        "missing-field error for `maps` must name the field; got: {msg}",
    );
}

/// Omitting all optional fields (`schema`, `vcpu_regs`,
/// `sdt_allocations`, every diagnostic Option, every capture
/// Vec) MUST succeed and produce a deserialized report whose
/// absent fields take their `serde(default)` value. `schema`
/// gets a positive control: omission MUST yield `SCHEMA_SINGLE`,
/// not the empty string a naive `Default for String` would
/// produce.
#[test]
fn failure_dump_report_optional_fields_round_trip_when_omitted() {
    let minimal = serde_json::json!({ "maps": [] });
    let report: FailureDumpReport = serde_json::from_value(minimal)
        .expect("deserialize must accept FailureDumpReport with only `maps`");
    assert_eq!(
        report.schema, SCHEMA_SINGLE,
        "absent `schema` field must default to SCHEMA_SINGLE \
         (default_schema_single fn); got: {:?}",
        report.schema,
    );
    assert!(report.maps.is_empty());
    assert!(report.vcpu_regs.is_empty());
    assert!(report.sdt_allocations.is_empty());
    assert!(report.prog_runtime_stats.is_empty());
    assert!(report.prog_runtime_stats_unavailable.is_none());
    assert!(report.per_cpu_time.is_empty());
    assert!(report.per_node_numa.is_empty());
    assert!(report.per_node_numa_unavailable.is_none());
    assert!(report.task_enrichments.is_empty());
    assert!(report.task_enrichments_unavailable.is_none());
    assert!(report.event_counter_timeline.is_empty());
    assert!(report.rq_scx_states.is_empty());
    assert!(report.dsq_states.is_empty());
    assert!(report.scx_sched_state.is_none());
    assert!(report.scx_walker_unavailable.is_none());
    assert!(report.vcpu_perf_at_freeze.is_empty());
}

// -- Pin failure-dump error-message strings ----------------------
//
// Pin the EXACT prose of error strings rendered into
// FailureDumpMap.error. Substring tests are permissive against
// drift; this regression suite asserts byte-for-byte equality so
// any re-wording during refactor surfaces in `cargo nextest run`
// before it ships.
//
// The strings are observable via FailureDumpMap.error contents
// and via downstream log scrapers (operators grep these in CI
// logs). Changing them silently breaks log tooling. Each pin
// doubles as documentation: this file shows exactly which prose
// is covered by drift detection.
//
// dump/render_map.rs producers covered here — five distinct
// render-time formats:
//   - BPF_MAP_TYPE_ARENA, no offsets
//   - BPF_MAP_TYPE_ARRAY, multi-entry
//   - BPF_MAP_TYPE_HASH, truncation
//   - BPF_MAP_TYPE_PERCPU_ARRAY, truncation
//   - unsupported map_type wildcard
//
// Each pin reproduces the production format string against a
// known-value placeholder and asserts byte equality with the
// expected literal. A drift in either the prose or the constant
// value (e.g. raising MAX_HASH_ENTRIES from 4096 to 8192) trips
// the test.
//
// The companion REASON_* constants for diagnostic Option fields
// (REASON_NO_STRUCT_OPS_LOADED, REASON_TASK_WALKER_ZERO_TASKS,
// REASON_SCX_WALKER_NO_STATE, ...) are already pinned by tests
// earlier in this module — see `report_unavailable_reasons_*`.

/// `arena BTF offsets unavailable (kernel lacks struct bpf_arena?)`
/// is rendered by the BPF_MAP_TYPE_ARENA arm when arena_offsets
/// is None — surfacing that the kernel lacks struct bpf_arena.
#[test]
fn pinned_error_arena_btf_offsets_unavailable() {
    // The producer has no format placeholders; reproduce the
    // exact `.into()` literal so a rephrasing in dump/render_map.rs trips.
    let rendered: String = "arena BTF offsets unavailable (kernel lacks struct bpf_arena?)".into();
    assert_eq!(
        rendered, "arena BTF offsets unavailable (kernel lacks struct bpf_arena?)",
        "arena-unavailable error string drifted from pin",
    );
}

/// `multi-entry ARRAY: only key 0 of {N} shown` is rendered by
/// the BPF_MAP_TYPE_ARRAY arm when `info.max_entries > 1`.
#[test]
fn pinned_error_multi_entry_array_truncation() {
    let n: u32 = 7;
    let rendered = format!("multi-entry ARRAY: only key 0 of {n} shown");
    assert_eq!(
        rendered, "multi-entry ARRAY: only key 0 of 7 shown",
        "multi-entry ARRAY truncation string drifted from pin",
    );
}

/// `hash map truncated at {MAX_HASH_ENTRIES} entries` is
/// rendered by the BPF_MAP_TYPE_HASH arm. Pins both the prose
/// and `MAX_HASH_ENTRIES` so either drifting trips the test.
#[test]
fn pinned_error_hash_map_truncation() {
    let rendered = format!("hash map truncated at {MAX_HASH_ENTRIES} entries");
    assert_eq!(
        rendered, "hash map truncated at 4096 entries",
        "hash map truncation string OR MAX_HASH_ENTRIES drifted from pin",
    );
}

/// `PERCPU_ARRAY truncated at {MAX_PERCPU_KEYS} keys (max_entries={N})`
/// is rendered by the BPF_MAP_TYPE_PERCPU_ARRAY arm. Pins prose,
/// constant, and placeholder ordering.
#[test]
fn pinned_error_percpu_array_truncation() {
    let max_entries: u32 = 999;
    let rendered =
        format!("PERCPU_ARRAY truncated at {MAX_PERCPU_KEYS} keys (max_entries={max_entries})",);
    assert_eq!(
        rendered, "PERCPU_ARRAY truncated at 256 keys (max_entries=999)",
        "PERCPU_ARRAY truncation string OR MAX_PERCPU_KEYS drifted from pin",
    );
}

/// `unknown map_type {N}` is rendered by the wildcard arm for any
/// map_type past the kernel-uapi enum the dump renderer was built
/// against. The dispatch now enumerates every known map_type
/// (HASH/ARRAY/PERCPU_*/LRU_*/STRUCT_OPS/RINGBUF/storage/FD-array
/// families/QUEUE/STACK/BLOOM_FILTER/LPM_TRIE/INSN_ARRAY/ARENA),
/// so the wildcard only fires for kernels newer than the
/// renderer.
#[test]
fn pinned_error_unknown_map_type() {
    let other: u32 = 42;
    let rendered = format!(
        "unknown map_type {other} (kernel newer than dump renderer; \
         update render_map dispatch)"
    );
    assert_eq!(
        rendered,
        "unknown map_type 42 (kernel newer than dump renderer; update render_map dispatch)",
        "unknown-map-type string drifted from pin",
    );
}

/// Local-storage truncation diagnostic: when a TASK / INODE / SK
/// / CGRP_STORAGE map holds more than [`MAX_HASH_ENTRIES`] selems,
/// the renderer surfaces a wire-stable error so a log scraper
/// sees the cap at the same shape as the `hash map truncated`
/// diagnostic. Pin the literal in case [`MAX_HASH_ENTRIES`] or
/// the format string drift.
#[test]
fn pinned_error_local_storage_truncation() {
    let rendered = format!("local_storage map truncated at {MAX_HASH_ENTRIES} entries");
    assert_eq!(
        rendered, "local_storage map truncated at 4096 entries",
        "local_storage truncation string OR MAX_HASH_ENTRIES drifted",
    );
}

// -- Per-node NUMA stats wire shape -------------------------------
//
// The live walker is a follow-up; this section pins the wire
// contract so the schema is stable before the producer lands.
//
// Asserted properties:
//   - PerNodeNumaStats serde-roundtrips with all fields preserved
//   - empty per_node_numa skips serialization (skip_serializing_if)
//   - REASON_NO_NUMA_WALKER string is exactly pinned (wire-stable)
//   - the dump_state path emits per_node_numa_unavailable until
//     the walker lands, so a downstream consumer sees the
//     diagnostic even on dumps that complete every other capture

#[test]
fn per_node_numa_stats_serde_roundtrip() {
    let s = PerNodeNumaStats {
        node: 1,
        numa_hit: 1_000_000,
        numa_miss: 100,
        numa_foreign: 50,
        numa_interleave_hit: 200,
        numa_local: 999_900,
        numa_other: 100,
    };
    let json = serde_json::to_string(&s).unwrap();
    let parsed: PerNodeNumaStats = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.node, 1);
    assert_eq!(parsed.numa_hit, 1_000_000);
    assert_eq!(parsed.numa_miss, 100);
    assert_eq!(parsed.numa_foreign, 50);
    assert_eq!(parsed.numa_interleave_hit, 200);
    assert_eq!(parsed.numa_local, 999_900);
    assert_eq!(parsed.numa_other, 100);
}

#[test]
fn per_node_numa_empty_skips_serialization() {
    let report = FailureDumpReport::default();
    let json = serde_json::to_string(&report).unwrap();
    assert!(
        !json.contains("per_node_numa"),
        "empty per_node_numa must be skipped: {json}",
    );
}

#[test]
fn per_node_numa_populated_lands_in_wire() {
    let mut report = FailureDumpReport::default();
    report.per_node_numa.push(PerNodeNumaStats {
        node: 0,
        numa_hit: 42,
        ..Default::default()
    });
    let json = serde_json::to_string(&report).unwrap();
    assert!(
        json.contains("\"per_node_numa\""),
        "populated per_node_numa must appear on wire: {json}",
    );
    assert!(
        json.contains("\"numa_hit\":42"),
        "field value must round-trip: {json}",
    );
}

#[test]
fn reason_no_numa_walker_string_pinned() {
    // Wire-stable diagnostic — operators string-match this in
    // failure-dump consumers. Drift would silently break that
    // tooling. The constant is the single source of truth; this
    // test pins it byte-for-byte.
    assert_eq!(
        REASON_NO_NUMA_WALKER,
        "no NUMA walker (host-side walker pending)"
    );
}

// -- FailureDumpPercpuHashEntry coverage --------------------------
//
// The PERCPU_HASH / LRU_PERCPU_HASH render path produces this
// shape: one entry per htab_elem with a rendered (or raw-hex)
// key plus one Vec<Option<RenderedValue>> slot per CPU. Mirror
// of FailureDumpPercpuEntry but keyed by hash key rather than
// an array index.

/// Display impl: with a rendered key and per-CPU values, the
/// output uses the indent-based `entry: key=` header with one
/// `cpu N:` line per slot.
#[test]
fn percpu_hash_entry_display_shows_key_and_cpus() {
    let entry = FailureDumpPercpuHashEntry {
        key: Some(RenderedValue::Uint { bits: 32, value: 7 }),
        key_hex: "07 00 00 00".into(),
        per_cpu: vec![
            Some(RenderedValue::Uint {
                bits: 32,
                value: 100,
            }),
            None,
            Some(RenderedValue::Uint {
                bits: 32,
                value: 300,
            }),
        ],
    };
    let out = format!("{entry}");
    assert!(out.starts_with("entry: key="), "entry header: {out}");
    assert!(out.contains("entry: key=7"), "rendered key: {out}");
    assert!(out.contains("cpu 0: 100"), "cpu 0 value: {out}");
    assert!(out.contains("cpu 1: <unmapped>"), "cpu 1 unmapped: {out}");
    assert!(out.contains("cpu 2: 300"), "cpu 2 value: {out}");
}

/// When BTF is unavailable the rendered key is `None`; Display
/// falls back to the raw hex representation with a `(raw)` tag,
/// mirroring FailureDumpEntry.
#[test]
fn percpu_hash_entry_display_falls_back_to_hex_when_no_btf() {
    let entry = FailureDumpPercpuHashEntry {
        key: None,
        key_hex: "ab cd ef 01".into(),
        per_cpu: vec![Some(RenderedValue::Uint { bits: 32, value: 1 })],
    };
    let out = format!("{entry}");
    assert!(
        out.contains("ab cd ef 01 (raw)"),
        "raw hex with (raw) marker: {out}",
    );
}

/// Empty per-CPU slot list — every CPU `<unmapped>`. The shape
/// stays well-formed (header + body or just unmapped markers)
/// rather than panicking.
#[test]
fn percpu_hash_entry_display_all_unmapped_cpus() {
    let entry = FailureDumpPercpuHashEntry {
        key: Some(RenderedValue::Uint { bits: 32, value: 0 }),
        key_hex: "00 00 00 00".into(),
        per_cpu: vec![None, None, None],
    };
    let out = format!("{entry}");
    assert!(out.contains("cpu 0: <unmapped>"));
    assert!(out.contains("cpu 1: <unmapped>"));
    assert!(out.contains("cpu 2: <unmapped>"));
}

/// Empty per_cpu vec — entry body has no `cpu N:` lines but the
/// `entry: key=` header is still emitted.
#[test]
fn percpu_hash_entry_display_empty_per_cpu() {
    let entry = FailureDumpPercpuHashEntry {
        key: Some(RenderedValue::Uint { bits: 32, value: 0 }),
        key_hex: "00 00 00 00".into(),
        per_cpu: vec![],
    };
    let out = format!("{entry}");
    assert!(out.starts_with("entry: key="), "header: {out}");
    assert!(!out.contains("cpu "), "no cpu lines: {out}");
}

/// Serde roundtrip: every field preserved on encode/decode.
/// Pin the wire shape so a future serde-attribute change
/// (rename, skip_serializing_if) trips the test.
#[test]
fn percpu_hash_entry_serde_roundtrip() {
    let entry = FailureDumpPercpuHashEntry {
        key: Some(RenderedValue::Uint {
            bits: 32,
            value: 42,
        }),
        key_hex: "2a 00 00 00".into(),
        per_cpu: vec![
            Some(RenderedValue::Uint {
                bits: 32,
                value: 100,
            }),
            None,
        ],
    };
    let json = serde_json::to_string(&entry).expect("serialize");
    let parsed: FailureDumpPercpuHashEntry = serde_json::from_str(&json).expect("deserialize");
    assert!(parsed.key.is_some());
    assert_eq!(parsed.key_hex, "2a 00 00 00");
    assert_eq!(parsed.per_cpu.len(), 2);
    assert!(parsed.per_cpu[0].is_some());
    assert!(parsed.per_cpu[1].is_none());
}

/// `key` is skip_serializing_if=Option::is_none — when absent on
/// the wire it must omit, then deserialize back as None.
#[test]
fn percpu_hash_entry_key_skips_when_none() {
    let entry = FailureDumpPercpuHashEntry {
        key: None,
        key_hex: "00".into(),
        per_cpu: vec![],
    };
    let json = serde_json::to_string(&entry).unwrap();
    assert!(
        !json.contains("\"key\":"),
        "None key must skip on wire: {json}",
    );
}

// -- FailureDumpMap with percpu_hash_entries Display --------------

/// A FailureDumpMap of type PERCPU_HASH renders the percpu_hash
/// entries below the header — matches the existing percpu_entries
/// pattern.
#[test]
fn map_display_percpu_hash_entries_render() {
    let m = FailureDumpMap {
        name: "percpu_hash".into(),
        map_type: BPF_MAP_TYPE_PERCPU_HASH,
        value_size: 4,
        max_entries: 100,
        value: None,
        entries: Vec::new(),
        percpu_entries: Vec::new(),
        percpu_hash_entries: vec![FailureDumpPercpuHashEntry {
            key: Some(RenderedValue::Uint { bits: 32, value: 1 }),
            key_hex: "01 00 00 00".into(),
            per_cpu: vec![
                Some(RenderedValue::Uint {
                    bits: 32,
                    value: 10,
                }),
                Some(RenderedValue::Uint {
                    bits: 32,
                    value: 20,
                }),
            ],
        }],
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    assert!(out.contains("map percpu_hash (type="), "header: {out}");
    assert!(out.contains("entry: key=1"), "key surfaces: {out}");
    assert!(out.contains("cpu 0: 10"), "cpu 0: {out}");
    assert!(out.contains("cpu 1: 20"), "cpu 1: {out}");
}

// -- New pinned error strings on render_map arms ------------------
//
// Each new arm in the render_map dispatch produces a wire-stable
// error string. Pin every one byte-for-byte so a re-wording
// refactor surfaces in cargo nextest before it reaches a log
// scraper.

#[test]
fn pinned_error_percpu_hash_truncation() {
    let rendered = format!("percpu hash map truncated at {MAX_HASH_ENTRIES} entries");
    assert_eq!(
        rendered, "percpu hash map truncated at 4096 entries",
        "percpu hash truncation string OR MAX_HASH_ENTRIES drifted",
    );
}

/// STRUCT_OPS produces TWO distinct error strings since the
/// offsets-vs-region split landed: one when struct_ops_offsets
/// are absent, one when the value region is unmapped.
#[test]
fn pinned_error_struct_ops_offsets_unresolved() {
    let expected = "STRUCT_OPS value unreadable: bpf_struct_ops_map BTF offsets unresolved \
         (kernel without struct_ops support, or vmlinux BTF stripped of \
         bpf_struct_ops_map / bpf_struct_ops_value).";
    let rendered: String = expected.into();
    assert_eq!(
        rendered, expected,
        "STRUCT_OPS offsets-unresolved error string drifted",
    );
}

#[test]
fn pinned_error_struct_ops_region_unmapped() {
    let expected = "STRUCT_OPS value unreadable: value region unmapped. Live-host \
         backend reads via BPF_MAP_LOOKUP_ELEM at key=0.";
    let rendered: String = expected.into();
    assert_eq!(
        rendered, expected,
        "STRUCT_OPS region-unmapped error string drifted",
    );
}

#[test]
fn pinned_error_cgroup_storage_deprecated() {
    let rendered: String =
        "deprecated cgroup-attached storage; use CGRP_STORAGE on newer kernels".into();
    assert_eq!(
        rendered,
        "deprecated cgroup-attached storage; use CGRP_STORAGE on newer kernels",
    );
}

#[test]
fn pinned_error_queue_stack_destructive() {
    let expected = "QUEUE/STACK are destructive (peek shows only the head; pop consumes); \
         no enumeration API";
    let rendered: String = expected.into();
    assert_eq!(rendered, expected);
}

#[test]
fn pinned_error_bloom_filter() {
    let rendered: String =
        "BLOOM_FILTER is a probabilistic set; no key enumeration is possible".into();
    assert_eq!(
        rendered,
        "BLOOM_FILTER is a probabilistic set; no key enumeration is possible",
    );
}

#[test]
fn pinned_error_lpm_trie() {
    let expected = "LPM_TRIE walker not implemented (keyed by prefixlen + data); \
         use bpf(2) BPF_MAP_GET_NEXT_KEY for live-host iteration";
    let rendered: String = expected.into();
    assert_eq!(rendered, expected);
}

#[test]
fn pinned_error_unknown_map_type_format() {
    // The wildcard arm format string carries a placeholder.
    let other: u32 = 99;
    let rendered = format!(
        "unknown map_type {other} (kernel newer than dump renderer; \
         update render_map dispatch)"
    );
    assert_eq!(
        rendered,
        "unknown map_type 99 (kernel newer than dump renderer; \
         update render_map dispatch)",
    );
}

// -- FailureDumpMap.percpu_hash_entries field round-trip ----------

/// `percpu_hash_entries` is `skip_serializing_if = Vec::is_empty`
/// — empty must be omitted; populated must round-trip.
#[test]
fn map_percpu_hash_entries_skips_when_empty() {
    let m = FailureDumpMap {
        name: "test".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 4,
        max_entries: 1,
        value: None,
        entries: Vec::new(),
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let json = serde_json::to_string(&m).unwrap();
    assert!(
        !json.contains("percpu_hash_entries"),
        "empty must skip: {json}",
    );
}

#[test]
fn map_percpu_hash_entries_round_trip_when_populated() {
    let m = FailureDumpMap {
        name: "ph".into(),
        map_type: BPF_MAP_TYPE_PERCPU_HASH,
        value_size: 4,
        max_entries: 1,
        value: None,
        entries: Vec::new(),
        percpu_entries: Vec::new(),
        percpu_hash_entries: vec![FailureDumpPercpuHashEntry {
            key: Some(RenderedValue::Uint { bits: 32, value: 1 }),
            key_hex: "01 00 00 00".into(),
            per_cpu: vec![Some(RenderedValue::Uint {
                bits: 32,
                value: 99,
            })],
        }],
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let json = serde_json::to_string(&m).expect("serialize");
    assert!(
        json.contains("percpu_hash_entries"),
        "populated must serialize: {json}",
    );
    let parsed: FailureDumpMap = serde_json::from_str(&json).expect("deserialize");
    assert_eq!(parsed.percpu_hash_entries.len(), 1);
    assert_eq!(parsed.percpu_hash_entries[0].key_hex, "01 00 00 00");
    assert_eq!(parsed.percpu_hash_entries[0].per_cpu.len(), 1);
}

// -- AccessorMemReader-shape arena pointer chasing ---------------
//
// The MemReader trait is implemented by AccessorMemReader. The
// `is_arena_addr` and `read_arena` methods don't need a guest
// kernel — they only consult the arena_snapshot field
// (specifically `snap.user_vm_start` and `snap.pages`). Test
// those paths via stand-in types that mirror production logic
// line-for-line.

/// `is_arena_addr` returns false when the snapshot is None
/// (no arena attached). Mirrors the no-arena fast path.
#[test]
fn accessor_mem_reader_no_snapshot_rejects_all_addrs() {
    struct StubReader<'a> {
        arena_snapshot: Option<&'a super::super::arena::ArenaSnapshot>,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn is_arena_addr(&self, addr: u64) -> bool {
            let Some(snap) = self.arena_snapshot else {
                return false;
            };
            if snap.user_vm_start == 0 {
                return false;
            }
            addr >= snap.user_vm_start && addr < snap.user_vm_start.wrapping_add(1 << 32)
        }
    }
    let r = StubReader {
        arena_snapshot: None,
    };
    assert!(!r.is_arena_addr(0));
    assert!(!r.is_arena_addr(0x10000));
    assert!(!r.is_arena_addr(u64::MAX));
}

/// `is_arena_addr` returns false when the snapshot is present
/// but `user_vm_start == 0` (the snapshot bailed before reading
/// the user_vm_start anchor).
#[test]
fn accessor_mem_reader_zero_user_vm_start_rejects_all() {
    use super::super::arena::ArenaSnapshot;
    let snap = ArenaSnapshot {
        user_vm_start: 0,
        ..ArenaSnapshot::default()
    };
    struct StubReader<'a> {
        arena_snapshot: Option<&'a ArenaSnapshot>,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn is_arena_addr(&self, addr: u64) -> bool {
            let Some(snap) = self.arena_snapshot else {
                return false;
            };
            if snap.user_vm_start == 0 {
                return false;
            }
            addr >= snap.user_vm_start && addr < snap.user_vm_start.wrapping_add(1 << 32)
        }
    }
    let r = StubReader {
        arena_snapshot: Some(&snap),
    };
    // Even with a snapshot present, user_vm_start=0 means no
    // arena base anchor → reject every address.
    assert!(!r.is_arena_addr(0));
    assert!(!r.is_arena_addr(0x100000));
}

/// `is_arena_addr` enforces the `[user_vm_start, user_vm_start +
/// 4 GiB)` half-open range reflecting the kernel's SZ_4G
/// enforcement in arena_map_alloc.
#[test]
fn accessor_mem_reader_arena_addr_range_via_snapshot() {
    use super::super::arena::ArenaSnapshot;
    let snap = ArenaSnapshot {
        user_vm_start: 0x10_0000_0000,
        ..ArenaSnapshot::default()
    };
    struct StubReader<'a> {
        arena_snapshot: Option<&'a ArenaSnapshot>,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn is_arena_addr(&self, addr: u64) -> bool {
            let Some(snap) = self.arena_snapshot else {
                return false;
            };
            if snap.user_vm_start == 0 {
                return false;
            }
            addr >= snap.user_vm_start && addr < snap.user_vm_start.wrapping_add(1 << 32)
        }
    }
    let r = StubReader {
        arena_snapshot: Some(&snap),
    };
    // Below start: rejected.
    assert!(!r.is_arena_addr(0));
    assert!(!r.is_arena_addr(0xf_ffff_ffff));
    // At start: accepted.
    assert!(r.is_arena_addr(0x10_0000_0000));
    // Just below upper bound: accepted.
    assert!(r.is_arena_addr(0x10_0000_0000 + (1 << 32) - 1));
    // At upper bound: rejected (exclusive).
    assert!(!r.is_arena_addr(0x10_0000_0000 + (1 << 32)));
}

/// `read_arena` returns None when no snapshot is attached.
#[test]
fn accessor_mem_reader_read_arena_none_when_no_snapshot() {
    struct StubReader<'a> {
        arena_snapshot: Option<&'a super::super::arena::ArenaSnapshot>,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn read_arena(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            self.arena_snapshot?;
            None
        }
    }
    let r = StubReader {
        arena_snapshot: None,
    };
    assert!(r.read_arena(0x1234, 8).is_none());
}

/// `read_arena` page-aligns the address and returns the matching
/// page's bytes when the full request fits in one page. Mirrors the
/// production `read_arena` logic line-for-line so a regression in
/// either trips the test. Cross-page reads (where `offset + len`
/// exceeds the page) return None per the documented MemReader
/// contract — partial bytes are not handed back.
#[test]
fn accessor_mem_reader_read_arena_page_hit() {
    use super::super::arena::{ArenaPage, ArenaSnapshot};
    let snap = ArenaSnapshot {
        pages: vec![ArenaPage {
            user_addr: 0x1000,
            bytes: (0..=0xffu8).cycle().take(4096).collect(),
        }],
        ..ArenaSnapshot::default()
    };

    struct StubReader<'a> {
        arena_snapshot: &'a ArenaSnapshot,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn read_arena(&self, addr: u64, len: usize) -> Option<Vec<u8>> {
            let page_addr = addr & !0xFFF;
            let offset = (addr & 0xFFF) as usize;
            let page = self
                .arena_snapshot
                .pages
                .iter()
                .find(|p| p.user_addr == page_addr)?;
            if offset + len > page.bytes.len() {
                // Contract: full request cannot be satisfied → None.
                return None;
            }
            Some(page.bytes[offset..offset + len].to_vec())
        }
    }
    let r = StubReader {
        arena_snapshot: &snap,
    };

    // Read at page base: byte 0..8 of (0..=0xff cycled).
    let bytes = r.read_arena(0x1000, 8).expect("page-aligned hit");
    assert_eq!(bytes, vec![0, 1, 2, 3, 4, 5, 6, 7]);

    // Read at offset 100: bytes 100..108.
    let bytes = r.read_arena(0x1000 + 100, 8).expect("offset hit");
    assert_eq!(bytes[0], 100);

    // Read past page end: contract says None. The full request
    // cannot be satisfied from one captured page, so the reader
    // declines rather than handing back a short slice.
    assert!(
        r.read_arena(0x1000 + 4090, 100).is_none(),
        "cross-page read must return None per MemReader::read_arena contract",
    );
}

/// `read_arena` returns None when the address falls outside the
/// captured pages (page miss).
#[test]
fn accessor_mem_reader_read_arena_page_miss_returns_none() {
    use super::super::arena::{ArenaPage, ArenaSnapshot};
    let snap = ArenaSnapshot {
        pages: vec![ArenaPage {
            user_addr: 0x1000,
            bytes: vec![0u8; 4096],
        }],
        ..ArenaSnapshot::default()
    };

    struct StubReader<'a> {
        arena_snapshot: &'a ArenaSnapshot,
    }
    impl super::super::btf_render::MemReader for StubReader<'_> {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
        fn read_arena(&self, addr: u64, len: usize) -> Option<Vec<u8>> {
            let page_addr = addr & !0xFFF;
            let offset = (addr & 0xFFF) as usize;
            let page = self
                .arena_snapshot
                .pages
                .iter()
                .find(|p| p.user_addr == page_addr)?;
            if offset + len > page.bytes.len() {
                // Contract: full request cannot be satisfied → None.
                return None;
            }
            Some(page.bytes[offset..offset + len].to_vec())
        }
    }
    let r = StubReader {
        arena_snapshot: &snap,
    };
    // 0x2000 is NOT in the captured pages → None.
    assert!(r.read_arena(0x2000, 8).is_none());
}

/// MemReader default impls: any reader that doesn't override
/// `is_arena_addr` and `read_arena` gets the default `false` /
/// `None` behavior.
#[test]
fn mem_reader_default_impls_skip_arena() {
    struct MinReader;
    impl super::super::btf_render::MemReader for MinReader {
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
    }
    let r = MinReader;
    assert!(!r.is_arena_addr(0));
    assert!(!r.is_arena_addr(u64::MAX));
    assert!(r.read_arena(0x1234, 8).is_none());
}

// -- ArenaSnapshot.user_vm_start serde + Display ------------------
//
// The new field is preserved across serde encode/decode and
// present even when the snapshot bailed before reading
// `kern_vm_kva` (preserves the arena anchor for is_arena_addr
// consumers).

#[test]
fn arena_snapshot_user_vm_start_round_trips() {
    use super::super::arena::ArenaSnapshot;
    let snap = ArenaSnapshot {
        user_vm_start: 0x1234_5678_0000_0000,
        ..ArenaSnapshot::default()
    };
    let json = serde_json::to_string(&snap).expect("serialize");
    assert!(
        json.contains("\"user_vm_start\":1311768464867721216"),
        "user_vm_start in JSON: {json}",
    );
    let parsed: ArenaSnapshot = serde_json::from_str(&json).expect("deserialize");
    assert_eq!(parsed.user_vm_start, 0x1234_5678_0000_0000);
}

#[test]
fn arena_snapshot_default_user_vm_start_is_zero() {
    use super::super::arena::ArenaSnapshot;
    let snap = ArenaSnapshot::default();
    assert_eq!(
        snap.user_vm_start, 0,
        "default snapshot's user_vm_start is 0 (no anchor)",
    );
}

// -- render_map refactor regression tests (task #42) --------------
//
// The refactor extracted `render_value_or_hex` and
// `render_key_optional` from 6+ duplicated match arms in
// `render_map`, and pushed wildcard explanation strings into the
// `MAP_TYPE_EXPLANATIONS` lookup table. Pin the dispatch shape of
// both helpers and the table-vs-explicit-arm coverage so a
// future refactor that drops a discriminant from the table or
// re-adds the (None, _) case to the BTF render path trips a test
// before the dump loses fidelity.

/// Empty MemReader for tests that don't need pointer-deref. The
/// helpers under test only forward the `&dyn MemReader` to
/// `render_value_with_mem`; for the (None btf) and (type_id=0)
/// paths the MemReader is never consulted.
struct EmptyReader;
impl super::super::btf_render::MemReader for EmptyReader {
    fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
        None
    }
}

/// `render_value_or_hex` falls back to `RenderedValue::Bytes`
/// when no Btf is provided. Hex output matches `hex_dump` so a
/// consumer scanning the failure dump always sees raw bytes for
/// maps whose value type id couldn't be resolved.
#[test]
fn render_value_or_hex_falls_back_to_hex_when_btf_none() {
    let bytes = [0x12u8, 0x34, 0x56];
    let reader = EmptyReader;
    let rendered = render_value_or_hex(None, 0, &bytes, &reader);
    match rendered {
        RenderedValue::Bytes { hex } => {
            assert_eq!(hex, "12 34 56", "hex must match hex_dump output");
        }
        other => panic!("expected Bytes, got {other:?}"),
    }
}

/// `render_value_or_hex` also falls back to `Bytes` when a Btf
/// IS provided but the type id is zero (the kernel libbpf
/// signal for "no BTF type recorded for this slot"). The match
/// arm guard `id != 0` enforces this.
#[test]
fn render_value_or_hex_falls_back_to_hex_when_type_id_zero() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let bytes = [0xABu8, 0xCD];
    let reader = EmptyReader;
    let rendered = render_value_or_hex(Some(&btf), 0, &bytes, &reader);
    match rendered {
        RenderedValue::Bytes { hex } => {
            assert_eq!(hex, "ab cd", "type_id=0 must surface hex even with btf");
        }
        other => panic!("expected Bytes, got {other:?}"),
    }
}

/// `render_value_or_hex` produces a typed render when both Btf
/// and a non-zero type id are available. Uses the kernel BTF's
/// `int` type, which the renderer decodes as `RenderedValue::Int`.
#[test]
fn render_value_or_hex_renders_via_btf_when_present() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let Ok(ids) = btf.resolve_ids_by_name("int") else {
        crate::report::test_skip("BTF missing 'int' type");
        return;
    };
    let Some(&id) = ids.first() else {
        crate::report::test_skip("BTF resolved 'int' to empty id list");
        return;
    };
    // Little-endian 0x42 as a 4-byte int.
    let bytes = 0x42i32.to_le_bytes();
    let reader = EmptyReader;
    let rendered = render_value_or_hex(Some(&btf), id, &bytes, &reader);
    match rendered {
        RenderedValue::Int { bits: 32, value } => {
            assert_eq!(value, 0x42, "BTF render must surface the decoded int value");
        }
        other => panic!("expected Int{{bits:32}}, got {other:?}"),
    }
}

/// `render_key_optional` returns None when no Btf is provided.
/// The hash-map key path keeps `key_hex` regardless and only
/// surfaces a typed render when both Btf and a non-zero type id
/// allow it, so the None-btf branch must NOT silently fall back
/// to `Bytes` like its value-side sibling.
#[test]
fn render_key_optional_returns_none_when_btf_none() {
    let bytes = [0x07u8, 0x00, 0x00, 0x00];
    let reader = EmptyReader;
    let rendered = render_key_optional(None, 0, &bytes, &reader);
    assert!(
        rendered.is_none(),
        "None btf must surface as None: {rendered:?}"
    );
}

/// `render_key_optional` returns None even with a Btf when the
/// type id is zero. Exercises the `id != 0` guard symmetric with
/// `render_value_or_hex_falls_back_to_hex_when_type_id_zero`.
#[test]
fn render_key_optional_returns_none_when_type_id_zero() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let bytes = [0x07u8, 0x00, 0x00, 0x00];
    let reader = EmptyReader;
    let rendered = render_key_optional(Some(&btf), 0, &bytes, &reader);
    assert!(
        rendered.is_none(),
        "type_id=0 must surface as None even with btf: {rendered:?}",
    );
}

/// `render_key_optional` returns Some(rendered) when both Btf
/// and a non-zero type id are available — the only path that
/// surfaces a typed key.
#[test]
fn render_key_optional_returns_some_via_btf() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let Ok(ids) = btf.resolve_ids_by_name("int") else {
        crate::report::test_skip("BTF missing 'int' type");
        return;
    };
    let Some(&id) = ids.first() else {
        crate::report::test_skip("BTF resolved 'int' to empty id list");
        return;
    };
    let bytes = 0x99i32.to_le_bytes();
    let reader = EmptyReader;
    let rendered = render_key_optional(Some(&btf), id, &bytes, &reader);
    match rendered {
        Some(RenderedValue::Int { bits: 32, value }) => {
            assert_eq!(value, 0x99, "must surface the decoded int value");
        }
        other => panic!("expected Some(Int{{bits:32}}), got {other:?}"),
    }
}

/// `find_sdt_data_field_offset` returns `None` for `value_type_id == 0`
/// without consulting BTF — pins the explicit early-return so a future
/// caller passing the kernel-libbpf "no BTF" sentinel doesn't trip a
/// spurious BTF probe.
#[test]
fn find_sdt_data_field_offset_zero_type_id_short_circuits() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    assert_eq!(
        super::render_map::find_sdt_data_field_offset(&btf, 0),
        None,
        "type_id=0 must short-circuit to None",
    );
}

/// `find_sdt_data_field_offset` returns `None` for a struct that has no
/// `struct sdt_data __arena *` member — vmlinux's `task_struct` is
/// guaranteed to predate scx and therefore can't carry a member with
/// that pointee. A non-None return on `task_struct` would mean the
/// helper is matching on something other than the pointee struct name.
#[test]
fn find_sdt_data_field_offset_none_for_unrelated_struct() {
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let Ok(ids) = btf.resolve_ids_by_name("task_struct") else {
        crate::report::test_skip("vmlinux BTF missing 'task_struct'");
        return;
    };
    let Some(&id) = ids.first() else {
        crate::report::test_skip("'task_struct' resolved to empty id list");
        return;
    };
    assert_eq!(
        super::render_map::find_sdt_data_field_offset(&btf, id),
        None,
        "task_struct must not match the sdt_data pointee predicate",
    );
}

/// `chase_sdt_data_payload` returns `None` whenever any of its
/// prerequisite inputs is missing: no BTF, no field offset, no
/// allocator metadata, zero `payload_btf_type_id`,
/// `elem_size <= header_size`, or `kern_vm_start == 0`. Each
/// early-return is one of the gates the surface render relies on
/// to NOT spuriously decorate non-arena entries.
#[test]
fn chase_sdt_data_payload_returns_none_on_missing_prereqs() {
    use super::super::btf_render::MemReader;
    use super::render_map::{SdtAllocMeta, chase_sdt_data_payload};
    struct StubReader;
    impl MemReader for StubReader {
        // Returns a zero buffer for every page-table-walked KVA
        // read so the gates we're testing get exercised regardless
        // of the synthetic kva. The gates this test exercises all
        // short-circuit BEFORE the read_kva call, so the contents
        // here are immaterial — the tests pin that the gates fire,
        // not the post-gate render.
        fn read_kva(&self, _: u64, len: usize) -> Option<Vec<u8>> {
            Some(vec![0u8; len])
        }
    }
    let reader = StubReader;
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    // We use any non-zero u32 as a stand-in for a payload type id —
    // the helper short-circuits BEFORE rendering when the elem_size
    // gate fails, so the type id is never dereferenced in those
    // arms.
    let placeholder_type_id: u32 = 1;
    // Every `Some` SdtAllocMeta in this test uses a non-zero
    // `kern_vm_start` so the kern_vm_start gate doesn't pre-empt
    // the gate under test; the dedicated kern_vm_start=0 case
    // appears below.
    let valid_meta = SdtAllocMeta {
        allocator_name: "scx_test_allocator".into(),
        elem_size: 32,
        header_size: 8,
        payload_btf_type_id: placeholder_type_id,
        kern_vm_start: 0xFFFF_8000_0000_0000,
    };
    // 24 bytes of value bytes: tid (8) + tptr (8) + data (8 = pointer
    // 0x100000000 in LE).
    let mut value_bytes = vec![0u8; 24];
    value_bytes[16..24].copy_from_slice(&0x1_0000_0000u64.to_le_bytes());

    // No BTF.
    assert!(
        chase_sdt_data_payload(None, Some(16), Some(&valid_meta), &value_bytes, &reader).is_none(),
        "missing btf must yield None",
    );
    // No field offset.
    assert!(
        chase_sdt_data_payload(Some(&btf), None, Some(&valid_meta), &value_bytes, &reader)
            .is_none(),
        "missing field offset must yield None",
    );
    // No allocator metadata.
    assert!(
        chase_sdt_data_payload(Some(&btf), Some(16), None, &value_bytes, &reader).is_none(),
        "missing allocator metadata must yield None",
    );
    // Zero payload_btf_type_id (allocator pre-pass returned 0 for
    // ambiguous / no-candidate paths).
    let zero_payload = SdtAllocMeta {
        payload_btf_type_id: 0,
        ..valid_meta.clone()
    };
    assert!(
        chase_sdt_data_payload(
            Some(&btf),
            Some(16),
            Some(&zero_payload),
            &value_bytes,
            &reader,
        )
        .is_none(),
        "payload_btf_type_id=0 must yield None",
    );
    // elem_size <= header_size: corrupt allocator metadata; payload
    // would slice empty.
    let small_elem = SdtAllocMeta {
        elem_size: 8,
        ..valid_meta.clone()
    };
    assert!(
        chase_sdt_data_payload(
            Some(&btf),
            Some(16),
            Some(&small_elem),
            &value_bytes,
            &reader,
        )
        .is_none(),
        "elem_size <= header_size must yield None",
    );
    // kern_vm_start == 0: arena pre-pass found no kernel-side
    // anchor — the chase has no way to compute a KVA from the
    // user-side pointer.
    let no_kern_vm = SdtAllocMeta {
        kern_vm_start: 0,
        ..valid_meta.clone()
    };
    assert!(
        chase_sdt_data_payload(
            Some(&btf),
            Some(16),
            Some(&no_kern_vm),
            &value_bytes,
            &reader,
        )
        .is_none(),
        "kern_vm_start=0 must yield None",
    );
    // Null arena pointer: scx_task_storage entry created but
    // scx_task_alloc has not populated the data slot yet.
    let mut zero_value_bytes = vec![0u8; 24];
    // explicit zero at offset 16..24 — already zero, but pin
    // intent.
    zero_value_bytes[16..24].copy_from_slice(&0u64.to_le_bytes());
    assert!(
        chase_sdt_data_payload(
            Some(&btf),
            Some(16),
            Some(&valid_meta),
            &zero_value_bytes,
            &reader,
        )
        .is_none(),
        "data_ptr=0 must yield None",
    );
    // Value bytes too short to hold a u64 at the field offset.
    let short_value_bytes = vec![0u8; 20];
    assert!(
        chase_sdt_data_payload(
            Some(&btf),
            Some(16),
            Some(&valid_meta),
            &short_value_bytes,
            &reader,
        )
        .is_none(),
        "value bytes too short for pointer read must yield None",
    );
}

/// `chase_sdt_data_payload` returns `None` when the page-table
/// walker can't resolve the composed KVA. Pages outside the
/// captured guest memory (PA past end-of-DRAM) translate to a
/// failure, matching the `read_kva_bytes_chunked` semantics
/// `mem_reader.read_kva` is built atop.
#[test]
fn chase_sdt_data_payload_yields_none_on_unmapped_kva() {
    use super::super::btf_render::MemReader;
    use super::render_map::{SdtAllocMeta, chase_sdt_data_payload};
    struct UnmappedReader;
    impl MemReader for UnmappedReader {
        // Always returns None — every read_kva fails. Mirrors a
        // page-table walker that has no PTE for the requested KVA
        // (an arena page that's been freed, or a KVA outside the
        // arena window).
        fn read_kva(&self, _: u64, _: usize) -> Option<Vec<u8>> {
            None
        }
    }
    let reader = UnmappedReader;
    let Some(path) = crate::monitor::find_test_vmlinux() else {
        return;
    };
    let Ok(btf) = crate::monitor::btf_offsets::load_btf_from_path(&path) else {
        crate::report::test_skip("could not parse vmlinux BTF");
        return;
    };
    let mut value_bytes = vec![0u8; 24];
    value_bytes[16..24].copy_from_slice(&0x1_0000_0000u64.to_le_bytes());
    let meta = SdtAllocMeta {
        allocator_name: "scx_test_allocator".into(),
        elem_size: 32,
        header_size: 8,
        payload_btf_type_id: 1,
        kern_vm_start: 0xFFFF_8000_0000_0000,
    };
    assert!(
        chase_sdt_data_payload(Some(&btf), Some(16), Some(&meta), &value_bytes, &reader,).is_none(),
        "unmapped kva must yield None even with all other prereqs satisfied",
    );
}

/// `FailureDumpEntry::payload` round-trips through serde JSON when
/// populated, and is suppressed by `skip_serializing_if` when None
/// (preserves the wire shape for entries that don't carry a typed
/// payload).
#[test]
fn failure_dump_entry_payload_serde_roundtrip() {
    let entry = FailureDumpEntry {
        key: None,
        key_hex: "00 11 22 33 44 55 66 77".into(),
        value: None,
        value_hex: "AA BB".into(),
        payload: Some(RenderedValue::Uint {
            bits: 64,
            value: 0xDEAD_BEEF,
        }),
    };
    let json = serde_json::to_string(&entry).unwrap();
    assert!(
        json.contains("\"payload\""),
        "populated payload must appear in JSON: {json}",
    );
    let parsed: FailureDumpEntry = serde_json::from_str(&json).unwrap();
    match parsed.payload {
        Some(RenderedValue::Uint { bits: 64, value }) => {
            assert_eq!(value, 0xDEAD_BEEF, "value must round-trip");
        }
        other => panic!("payload didn't round-trip cleanly: {other:?}"),
    }
}

/// Empty payload must NOT appear on the wire — the
/// `skip_serializing_if = "Option::is_none"` predicate keeps the
/// JSON shape unchanged for non-arena map entries (HASH/LRU_HASH and
/// local-storage maps without a discoverable allocator).
#[test]
fn failure_dump_entry_payload_skipped_when_none() {
    let entry = FailureDumpEntry {
        key: None,
        key_hex: "00".into(),
        value: None,
        value_hex: "00".into(),
        payload: None,
    };
    let json = serde_json::to_string(&entry).unwrap();
    assert!(
        !json.contains("\"payload\""),
        "None payload must be skipped: {json}",
    );
}

/// `FailureDumpEntry` Display surfaces the typed payload underneath
/// `value`. Pin both that the payload is rendered AND the relative
/// order — operators read top-to-bottom and the surface struct
/// (key/value) must come before the deref'd payload, matching how
/// a kernel-side debugger would inspect: chase the pointer, then
/// read the dereferenced struct. The format uses
/// `payload <rendered>` (with a space, no colon) so the value's
/// own breadcrumb completes the line.
#[test]
fn failure_dump_entry_display_renders_payload_after_value() {
    let entry = FailureDumpEntry {
        key: Some(RenderedValue::Uint { bits: 64, value: 0 }),
        key_hex: "00".into(),
        value: Some(RenderedValue::Uint {
            bits: 32,
            value: 99,
        }),
        value_hex: "63".into(),
        payload: Some(RenderedValue::Uint {
            bits: 64,
            value: 0xCAFEBABE,
        }),
    };
    let out = format!("{entry}");
    assert!(
        out.contains("\n  .data "),
        "Display must label .data: {out}"
    );
    let value_pos = out.find("value:").expect("value label present");
    let payload_pos = out.find(".data ").expect(".data label present");
    assert!(
        value_pos < payload_pos,
        "Display must order value before .data: {out}",
    );
    assert!(
        out.contains("3405691582"), // 0xCAFEBABE in decimal
        "rendered payload value must appear in Display: {out}",
    );
}

/// Display omits the payload line when payload is None — the
/// existing key/value surface stays unchanged for entries that
/// don't carry a typed payload.
#[test]
fn failure_dump_entry_display_omits_payload_when_none() {
    let entry = FailureDumpEntry {
        key: None,
        key_hex: "ab".into(),
        value: None,
        value_hex: "cd".into(),
        payload: None,
    };
    let out = format!("{entry}");
    assert!(
        !out.contains("payload"),
        "Display must not surface payload when None: {out}",
    );
}

/// `MAP_TYPE_EXPLANATIONS` must carry an entry for every
/// non-walker map type so the wildcard arm produces a precise
/// reason instead of the generic "unknown map_type N" fallback.
///
/// Walker arms (have explicit handling in `render_map`):
///   ARRAY, HASH, LRU_HASH, PERCPU_HASH, LRU_PERCPU_HASH,
///   PERCPU_ARRAY, ARENA, STRUCT_OPS, TASK_STORAGE,
///   INODE_STORAGE, SK_STORAGE, CGRP_STORAGE,
///   RINGBUF, USER_RINGBUF, STACK_TRACE, and the FD-array family
///   (PROG_ARRAY, PERF_EVENT_ARRAY, CGROUP_ARRAY, ARRAY_OF_MAPS,
///   HASH_OF_MAPS, DEVMAP, DEVMAP_HASH, SOCKMAP, SOCKHASH,
///   CPUMAP, XSKMAP, REUSEPORT_SOCKARRAY).
///
/// Non-walker types must each appear in MAP_TYPE_EXPLANATIONS:
///   LPM_TRIE (11), CGROUP_STORAGE (19),
///   PERCPU_CGROUP_STORAGE (21), QUEUE (22), STACK (23),
///   BLOOM_FILTER (30), INSN_ARRAY (34).
#[test]
fn map_type_explanations_covers_every_non_walker_type() {
    let non_walker: &[(u32, &str)] = &[
        (BPF_MAP_TYPE_LPM_TRIE, "LPM_TRIE"),
        (BPF_MAP_TYPE_CGROUP_STORAGE, "CGROUP_STORAGE"),
        (BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE, "PERCPU_CGROUP_STORAGE"),
        (BPF_MAP_TYPE_QUEUE, "QUEUE"),
        (BPF_MAP_TYPE_STACK, "STACK"),
        (BPF_MAP_TYPE_BLOOM_FILTER, "BLOOM_FILTER"),
        (BPF_MAP_TYPE_INSN_ARRAY, "INSN_ARRAY"),
    ];
    for (discriminant, name) in non_walker {
        let found = MAP_TYPE_EXPLANATIONS.iter().any(|(t, _)| t == discriminant);
        assert!(
            found,
            "MAP_TYPE_EXPLANATIONS missing entry for {name} ({discriminant}); \
             wildcard arm would surface the generic 'unknown map_type' fallback",
        );
    }
}

/// Every explanation string in MAP_TYPE_EXPLANATIONS must be a
/// non-empty, actionable reason — no placeholder strings like
/// "not yet supported" / "TODO" / "FIXME" that signal the
/// implementer left work behind. The dump must always tell the
/// operator something concrete about why the map's contents are
/// missing.
#[test]
fn map_type_explanations_strings_are_actionable() {
    for (discriminant, msg) in MAP_TYPE_EXPLANATIONS {
        assert!(
            !msg.is_empty(),
            "explanation for discriminant {discriminant} is empty",
        );
        for placeholder in ["not yet supported", "TODO", "FIXME", "unimplemented"] {
            assert!(
                !msg.contains(placeholder),
                "explanation for discriminant {discriminant} contains placeholder \
                 {placeholder:?}: {msg:?}",
            );
        }
    }
}

// -- serde roundtrip tests ----------------------------------------
//
// Every new dump section (FailureDumpRingbuf, FailureDumpStackTrace,
// FailureDumpFdArray) must round-trip through serde JSON without
// mangling field semantics. Catches drift in `#[serde(default,
// skip_serializing_if = "...")]` annotations: a renamed field, a
// removed default, or a flipped condition would silently corrupt the
// wire format.

/// FailureDumpRingbuf round-trips every field (capacity, consumer_pos,
/// producer_pos, pending_pos, pending_bytes) through JSON intact.
#[test]
fn failure_dump_ringbuf_roundtrip() {
    let original = FailureDumpRingbuf {
        capacity: 0x1_0000,
        consumer_pos: 0x100,
        producer_pos: 0x200,
        pending_pos: 0x180,
        pending_bytes: 0x100,
    };
    let json = serde_json::to_string(&original).expect("ringbuf serialize");
    let restored: FailureDumpRingbuf = serde_json::from_str(&json).expect("ringbuf deserialize");
    assert_eq!(restored.capacity, original.capacity);
    assert_eq!(restored.consumer_pos, original.consumer_pos);
    assert_eq!(restored.producer_pos, original.producer_pos);
    assert_eq!(restored.pending_pos, original.pending_pos);
    assert_eq!(restored.pending_bytes, original.pending_bytes);
}

/// FailureDumpStackTrace empty case: `truncated=false` is skipped on
/// serialize (skip_serializing_if = std::ops::Not::not) and must
/// default-deserialize back to false. `entries=[]` is serialized
/// since FailureDumpStackTrace.entries has no skip annotation.
#[test]
fn failure_dump_stack_trace_empty_roundtrip() {
    let original = FailureDumpStackTrace {
        n_buckets: 0,
        entries: Vec::new(),
        truncated: false,
    };
    let json = serde_json::to_string(&original).expect("stack_trace serialize");
    // truncated=false should NOT appear in the wire format.
    assert!(
        !json.contains("\"truncated\":true") && !json.contains("\"truncated\":false"),
        "skip_serializing_if must elide truncated when false; JSON: {json}",
    );
    let restored: FailureDumpStackTrace =
        serde_json::from_str(&json).expect("stack_trace deserialize");
    assert_eq!(restored.n_buckets, 0);
    assert!(restored.entries.is_empty());
    assert!(!restored.truncated);
}

/// FailureDumpStackTrace populated entries with truncated=true
/// preserves both the entries vector and the truncation flag.
#[test]
fn failure_dump_stack_trace_populated_roundtrip() {
    let original = FailureDumpStackTrace {
        n_buckets: 4,
        entries: vec![
            FailureDumpStackTraceEntry {
                bucket_id: 0,
                nr: 3,
                pcs: vec![
                    0xFFFF_FFFF_8100_0000,
                    0xFFFF_FFFF_8100_0010,
                    0xFFFF_FFFF_8100_0020,
                ],
                data_hex: "00 10 20".into(),
            },
            FailureDumpStackTraceEntry {
                bucket_id: 2,
                nr: 1,
                pcs: vec![0xFFFF_FFFF_8200_0000],
                data_hex: "ff".into(),
            },
        ],
        truncated: true,
    };
    let json = serde_json::to_string(&original).expect("stack_trace serialize");
    assert!(
        json.contains("\"truncated\":true"),
        "truncated=true must appear in JSON: {json}",
    );
    let restored: FailureDumpStackTrace =
        serde_json::from_str(&json).expect("stack_trace deserialize");
    assert_eq!(restored.n_buckets, 4);
    assert_eq!(restored.entries.len(), 2);
    assert_eq!(restored.entries[0].bucket_id, 0);
    assert_eq!(restored.entries[0].nr, 3);
    assert_eq!(restored.entries[0].pcs.len(), 3);
    assert_eq!(restored.entries[0].pcs[0], 0xFFFF_FFFF_8100_0000);
    assert_eq!(restored.entries[0].data_hex, "00 10 20");
    assert_eq!(restored.entries[1].bucket_id, 2);
    assert!(restored.truncated);
}

/// FailureDumpStackTraceEntry build-id mode: empty `pcs` is elided
/// from the wire format (skip_serializing_if = "Vec::is_empty"),
/// `data_hex` is always populated.
#[test]
fn failure_dump_stack_trace_entry_build_id_roundtrip() {
    let original = FailureDumpStackTraceEntry {
        bucket_id: 7,
        nr: 1,
        pcs: Vec::new(),
        data_hex: "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f \
                   10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f"
            .into(),
    };
    let json = serde_json::to_string(&original).expect("entry serialize");
    assert!(
        !json.contains("\"pcs\""),
        "empty pcs must be elided in build-id mode; JSON: {json}",
    );
    let restored: FailureDumpStackTraceEntry =
        serde_json::from_str(&json).expect("entry deserialize");
    assert_eq!(restored.bucket_id, 7);
    assert_eq!(restored.nr, 1);
    assert!(restored.pcs.is_empty());
    assert_eq!(restored.data_hex.len(), 95); // 32 bytes * 3 chars - 1 trailing
}

/// FailureDumpFdArray empty case: `truncated=false` and `indices=[]`
/// both elided. populated/scanned remain since they have no skip
/// annotation.
#[test]
fn failure_dump_fd_array_empty_roundtrip() {
    let original = FailureDumpFdArray {
        populated: 0,
        scanned: 0,
        indices: Vec::new(),
        truncated: false,
        indices_truncated: false,
    };
    let json = serde_json::to_string(&original).expect("fd_array serialize");
    assert!(
        !json.contains("\"truncated\""),
        "truncated=false must be elided; JSON: {json}",
    );
    assert!(
        !json.contains("\"indices_truncated\""),
        "indices_truncated=false must be elided; JSON: {json}",
    );
    let restored: FailureDumpFdArray = serde_json::from_str(&json).expect("fd_array deserialize");
    assert_eq!(restored.populated, 0);
    assert_eq!(restored.scanned, 0);
    assert!(restored.indices.is_empty());
    assert!(!restored.truncated);
}

/// FailureDumpFdArray populated case: indices vector and
/// truncated=true preserved. Defensive check that populated >
/// indices.len() (the truncation-asymmetry case the implementer
/// handles by capping `indices` at MAX_FD_ARRAY_INDICES while
/// continuing to count populated slots) still round-trips coherently.
#[test]
fn failure_dump_fd_array_populated_roundtrip() {
    let original = FailureDumpFdArray {
        populated: 1500,
        scanned: 4096,
        indices: (0..1024).collect(), // capped at MAX_FD_ARRAY_INDICES
        truncated: true,
        indices_truncated: true, // 1500 > 1024
    };
    let json = serde_json::to_string(&original).expect("fd_array serialize");
    assert!(
        json.contains("\"indices_truncated\":true"),
        "indices_truncated=true must be emitted; JSON: {json}",
    );
    let restored: FailureDumpFdArray = serde_json::from_str(&json).expect("fd_array deserialize");
    assert_eq!(restored.populated, 1500);
    assert_eq!(restored.scanned, 4096);
    assert_eq!(restored.indices.len(), 1024);
    assert_eq!(restored.indices[0], 0);
    assert!(
        restored.indices_truncated,
        "indices_truncated must roundtrip"
    );
    assert_eq!(restored.indices[1023], 1023);
    assert!(restored.truncated);
}

/// Defaulted-from-empty deserialization: a stripped-down JSON
/// (only required fields present) deserializes with `Default`
/// values for skipped fields. Validates the
/// `#[serde(default, skip_serializing_if = "...")]` round-trip
/// across the three new dump sections.
#[test]
fn failure_dump_minimal_deserialize_uses_defaults() {
    // Ringbuf has no skip_serializing_if (every field is required),
    // so the minimal form must include all fields.
    let json =
        r#"{"capacity":0,"consumer_pos":0,"producer_pos":0,"pending_pos":0,"pending_bytes":0}"#;
    let rb: FailureDumpRingbuf = serde_json::from_str(json).expect("ringbuf minimal deserialize");
    assert_eq!(rb.capacity, 0);

    // StackTrace minimal: only n_buckets, default-fills the rest.
    let json = r#"{"n_buckets":0,"entries":[]}"#;
    let st: FailureDumpStackTrace =
        serde_json::from_str(json).expect("stack_trace minimal deserialize");
    assert_eq!(st.n_buckets, 0);
    assert!(st.entries.is_empty());
    assert!(!st.truncated, "truncated must default to false");

    // FdArray minimal: populated/scanned required, indices and
    // truncated default.
    let json = r#"{"populated":0,"scanned":0}"#;
    let fa: FailureDumpFdArray = serde_json::from_str(json).expect("fd_array minimal deserialize");
    assert_eq!(fa.populated, 0);
    assert_eq!(fa.scanned, 0);
    assert!(fa.indices.is_empty(), "indices must default to []");
    assert!(!fa.truncated, "truncated must default to false");
}

// -- DualFailureDumpReport Display rendering ----------------------
//
// The post-pass-3 fix in display.rs distinguishes "early snapshot
// present with valid jiffies" from "early snapshot present with
// jiffies bookkeeping not captured" (both early_max_age_jiffies and
// early_threshold_jiffies are 0). Pin the wire-stable header strings
// for each branch so a reformatting regression surfaces immediately
// rather than producing operator-confusing "max_age=0j, threshold=0j"
// output.

/// Both jiffies fields are 0 with an early snapshot present:
/// renders `early=present (jiffies not captured)` instead of the
/// misleading `max_age=0j, threshold=0j`.
#[test]
fn dual_dump_display_zero_jiffies_uses_jiffies_not_captured_branch() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("early=present (jiffies not captured)"),
        "zero-jiffies branch must surface a distinct phrase; got: {rendered}",
    );
    assert!(
        !rendered.contains("max_age=0j"),
        "zero-jiffies header must NOT print max_age=0j; got: {rendered}",
    );
    assert!(
        !rendered.contains("threshold=0j"),
        "zero-jiffies header must NOT print threshold=0j; got: {rendered}",
    );
}

/// Non-zero jiffies preserves the legacy `max_age={N}j, threshold={M}j`
/// format. Pins the format-string layout so a refactor that swaps
/// the field order or drops the `j` suffix surfaces immediately.
#[test]
fn dual_dump_display_nonzero_jiffies_preserves_max_age_format() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 1234,
        early_threshold_jiffies: 5678,
        early_skipped_reason: None,
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("max_age=1234j, threshold=5678j"),
        "non-zero jiffies must preserve the max_age/threshold format; got: {rendered}",
    );
    assert!(
        !rendered.contains("jiffies not captured"),
        "non-zero jiffies must NOT use the not-captured phrase; got: {rendered}",
    );
}

/// One jiffies field zero, the other non-zero — verifies the
/// zero-jiffies branch ONLY fires when BOTH are zero. A single-zero
/// case should still use the legacy format (the bookkeeping was
/// partial but at least one number is meaningful).
#[test]
fn dual_dump_display_one_zero_one_nonzero_uses_legacy_format() {
    // max_age=0, threshold=5: legacy format with max_age=0j.
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 5,
        early_skipped_reason: None,
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("max_age=0j, threshold=5j"),
        "single-zero case must use legacy format; got: {rendered}",
    );
    assert!(
        !rendered.contains("jiffies not captured"),
        "single-zero case must NOT use the not-captured phrase; got: {rendered}",
    );

    // max_age=5, threshold=0: legacy format with threshold=0j.
    let dual2 = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: Some(FailureDumpReport::default()),
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 5,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let rendered2 = format!("{dual2}");
    assert!(
        rendered2.contains("max_age=5j, threshold=0j"),
        "single-zero case must use legacy format; got: {rendered2}",
    );
    assert!(
        !rendered2.contains("jiffies not captured"),
        "single-zero case must NOT use the not-captured phrase; got: {rendered2}",
    );
}

/// `early=absent` branch is independent of the jiffies fields:
/// when `early` is None, neither the legacy nor the
/// jiffies-not-captured phrase appears, even if the jiffies
/// fields are populated (they describe the absent snapshot's
/// trigger metric — surfacing them would be misleading).
#[test]
fn dual_dump_display_early_absent_omits_jiffies_lines() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        // Populated but unused — exercises the assertion below.
        early_max_age_jiffies: 999,
        early_threshold_jiffies: 100,
        early_skipped_reason: None,
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("early=absent"),
        "absent branch must surface 'early=absent'; got: {rendered}",
    );
    assert!(
        !rendered.contains("max_age=999j"),
        "absent branch must NOT surface jiffies values; got: {rendered}",
    );
    assert!(
        !rendered.contains("jiffies not captured"),
        "absent branch must NOT surface the not-captured phrase; got: {rendered}",
    );
}

/// `early_skipped_reason` populated → Display surfaces the structured
/// reason directly in the header AND in the absent-branch body, replacing
/// the legacy "stall fired before half-way threshold, or runnable_at scan
/// setup failed" generic text. Pins the contract for the freeze
/// coordinator's three known reasons (scan prerequisites unavailable,
/// max_age never crossed threshold, scx_tick stall) and any future
/// addition.
#[test]
fn dual_dump_display_early_absent_renders_structured_reason() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: Some("scx_tick stall — no per-task runnable_at data".to_string()),
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("scx_tick stall"),
        "structured reason must appear in absent header; got: {rendered}",
    );
    assert!(
        !rendered.contains("RUST_LOG=ktstr=debug"),
        "RUST_LOG hint must NOT appear when reason is structured; got: {rendered}",
    );
    assert!(
        !rendered.contains("stall fired before half-way threshold"),
        "legacy generic text must NOT appear when reason is structured; got: {rendered}",
    );
}

/// `early_skipped_reason` None on absent path → falls back to the
/// legacy two-cause generic text and the RUST_LOG hint. Preserves
/// rendering for older dump JSONs that predate
/// `early_skipped_reason` (the field deserialises as `None` on
/// missing-key inputs per `#[serde(default)]`).
#[test]
fn dual_dump_display_early_absent_falls_back_when_reason_absent() {
    let dual = DualFailureDumpReport {
        schema: SCHEMA_DUAL.to_string(),
        early: None,
        late: FailureDumpReport::default(),
        early_max_age_jiffies: 0,
        early_threshold_jiffies: 0,
        early_skipped_reason: None,
    };
    let rendered = format!("{dual}");
    assert!(
        rendered.contains("stall fired before half-way threshold"),
        "legacy generic text must appear when reason is absent; got: {rendered}",
    );
    assert!(
        rendered.contains("RUST_LOG=ktstr=debug"),
        "RUST_LOG hint must appear when reason is absent; got: {rendered}",
    );
}

// -- New per-section Display rendering ----------------------------
//
// Per-CPU CPU-time, per-node NUMA, and the scx_walker section each
// have wire-stable Display headers. Pin the formats so a renaming
// or a count-format swap surfaces in tests rather than as a
// mismatched log scrape.

/// `per_cpu_time` section: one-line summary of the CPU count
/// captured. Format: `per_cpu_time: {N} CPUs captured`.
#[test]
fn failure_dump_display_per_cpu_time_summary() {
    let report = FailureDumpReport {
        per_cpu_time: vec![
            super::PerCpuTimeStats {
                cpu: 0,
                ..super::PerCpuTimeStats::default()
            },
            super::PerCpuTimeStats {
                cpu: 1,
                ..super::PerCpuTimeStats::default()
            },
            super::PerCpuTimeStats {
                cpu: 2,
                ..super::PerCpuTimeStats::default()
            },
        ],
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("per_cpu_time: 3 CPUs captured"),
        "per_cpu_time section must surface CPU count; got: {rendered}",
    );
}

/// `per_cpu_time` empty + `per_node_numa` populated: the two
/// sections are independent — populated nodes render even when no
/// CPU rows were captured.
#[test]
fn failure_dump_display_per_node_numa_summary() {
    let report = FailureDumpReport {
        per_node_numa: vec![
            super::PerNodeNumaStats {
                node: 0,
                ..super::PerNodeNumaStats::default()
            },
            super::PerNodeNumaStats {
                node: 1,
                ..super::PerNodeNumaStats::default()
            },
        ],
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("per_node_numa: 2 nodes captured"),
        "per_node_numa section must surface node count; got: {rendered}",
    );
    assert!(
        !rendered.contains("per_cpu_time:"),
        "per_cpu_time must be elided when empty; got: {rendered}",
    );
}

/// `per_node_numa_unavailable` reason renders inline when the
/// walker bailed (current `"no NUMA walker"` placeholder until the
/// host-side walker lands).
#[test]
fn failure_dump_display_per_node_numa_unavailable() {
    let report = FailureDumpReport {
        per_node_numa_unavailable: Some("no NUMA walker".into()),
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("per_node_numa: <unavailable: no NUMA walker>"),
        "per_node_numa_unavailable must surface the reason inline; got: {rendered}",
    );
}

/// `scx_walker` section: one-line summary `rq_scx={N} dsq={M}
/// sched={captured|absent}`. Pinned because the format reads as a
/// log-scrapable triple a downstream tool can split on.
#[test]
fn failure_dump_display_scx_walker_all_present() {
    use crate::monitor::scx_walker::{DsqState, RqScxState, ScxSchedState};
    let report = FailureDumpReport {
        rq_scx_states: vec![RqScxState::default(); 4],
        dsq_states: vec![DsqState::default(); 2],
        scx_sched_state: Some(ScxSchedState::default()),
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("scx_walker: rq_scx=4 dsq=2 sched=captured"),
        "scx_walker present-everywhere must surface counts and 'captured'; got: {rendered}",
    );
}

/// `scx_walker` partial-output: rq_scx populated but no DSQs and no
/// scx_sched scalar. The section still renders (any non-empty
/// triggers the block) and `sched=absent` surfaces explicitly.
#[test]
fn failure_dump_display_scx_walker_partial() {
    use crate::monitor::scx_walker::RqScxState;
    let report = FailureDumpReport {
        rq_scx_states: vec![RqScxState::default()],
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("scx_walker: rq_scx=1 dsq=0 sched=absent"),
        "partial scx_walker must show 'sched=absent'; got: {rendered}",
    );
}

/// `scx_walker_unavailable` reason renders inline when the walker
/// could not run (e.g. scx_sched offsets unresolved).
#[test]
fn failure_dump_display_scx_walker_unavailable() {
    let report = FailureDumpReport {
        scx_walker_unavailable: Some("scx_sched offsets unresolved".into()),
        ..FailureDumpReport::default()
    };
    let rendered = format!("{report}");
    assert!(
        rendered.contains("scx_walker: <unavailable: scx_sched offsets unresolved>"),
        "scx_walker_unavailable must surface the reason inline; got: {rendered}",
    );
}

// -- Render-helper unit tests over synthetic guest memory --------
//
// Build a flat host-side buffer that simulates the guest direct
// mapping: every kernel KVA is `pa + page_offset`, and
// `translate_any_kva` in the production read path resolves through
// that mapping unchanged (no page-table walk needed). The synthetic
// `BpfMapOffsets` field offsets are arbitrary — they only need to be
// consistent with how the helpers read from the buffer.

/// Per-test synthetic-memory scene used by the render-helper tests.
/// Owns the guest buffer + the `BpfMapOffsets` block + the
/// `BpfRingbufOffsets` / `BpfStackmapOffsets` instances so a test
/// can borrow `&BpfMapOffsets` for a `GuestMemMapAccessor` without
/// each test re-stitching the offset substructs.
struct RenderScene {
    buf: Vec<u8>,
    page_offset: u64,
    /// `BpfMapOffsets` with `ringbuf_offsets` / `stackmap_offsets` /
    /// `array_value` populated so the synthetic helpers know where
    /// to find each field within the synthetic structs.
    offsets: crate::monitor::btf_offsets::BpfMapOffsets,
}

/// Direct-mapping KVA from a host PA: `kva = pa + page_offset`. The
/// production `translate_any_kva` reverses this with `kva - page_offset`
/// and bounds-checks against `mem.size()`.
fn pa_to_kva(pa: u64, page_offset: u64) -> u64 {
    page_offset.wrapping_add(pa)
}

/// Synthetic ringbuf offsets. The map carries `rb` at offset 0 of
/// `bpf_ringbuf_map` (the synthetic map struct is just the rb
/// pointer); the bpf_ringbuf struct lays out
/// mask/consumer_pos/producer_pos/pending_pos one per cacheline so
/// the production reader exercises the per-field translate.
fn synth_ringbuf_offsets() -> super::super::btf_offsets::BpfRingbufOffsets {
    super::super::btf_offsets::BpfRingbufOffsets {
        rbm_rb: 0,
        rb_mask: 0,
        rb_consumer_pos: 64,
        rb_producer_pos: 128,
        rb_pending_pos: 192,
    }
}

/// Build a `BpfMapOffsets` carrying only the ringbuf substruct.
/// Other walkers/render helpers do not consult these other fields,
/// so they stay zero-valued.
fn synth_ringbuf_map_offsets() -> crate::monitor::btf_offsets::BpfMapOffsets {
    let mut o = crate::monitor::btf_offsets::BpfMapOffsets::EMPTY;
    o.ringbuf_offsets = Some(synth_ringbuf_offsets());
    o
}

/// Lay out a ringbuf scene: bpf_ringbuf_map at PA 0x1000, bpf_ringbuf
/// at PA 0x10_0000. The map's `rb` pointer at offset 0 holds the
/// rb's KVA. The rb's four position fields hold the supplied values
/// at their respective offsets. Returns the scene plus the map's
/// KVA so the test can pass it as `info.map_kva`.
///
/// `rb_kva_override = Some(0)` writes a NULL rb pointer (exercises
/// the rb-NULL error path); `Some(other_kva)` writes an unmapped
/// pointer; `None` writes the rb's real KVA.
fn build_ringbuf_scene(
    mask: u64,
    consumer_pos: u64,
    producer_pos: u64,
    pending_pos: u64,
    rb_kva_override: Option<u64>,
) -> (RenderScene, u64) {
    let rb_offs = synth_ringbuf_offsets();
    let offsets = synth_ringbuf_map_offsets();
    let page_offset = crate::monitor::symbols::DEFAULT_PAGE_OFFSET;

    let map_pa: u64 = 0x1000;
    let rb_pa: u64 = 0x10_0000;
    let buf_size: usize = (rb_pa as usize) + 0x1000;

    let mut buf = vec![0u8; buf_size];

    let write_u64 = |buf: &mut Vec<u8>, pa: u64, val: u64| {
        let off = pa as usize;
        buf[off..off + 8].copy_from_slice(&val.to_ne_bytes());
    };

    // bpf_ringbuf_map.rb: pointer to bpf_ringbuf.
    let rb_kva = rb_kva_override.unwrap_or_else(|| pa_to_kva(rb_pa, page_offset));
    write_u64(&mut buf, map_pa + rb_offs.rbm_rb as u64, rb_kva);

    // bpf_ringbuf fields.
    write_u64(&mut buf, rb_pa + rb_offs.rb_mask as u64, mask);
    write_u64(
        &mut buf,
        rb_pa + rb_offs.rb_consumer_pos as u64,
        consumer_pos,
    );
    write_u64(
        &mut buf,
        rb_pa + rb_offs.rb_producer_pos as u64,
        producer_pos,
    );
    write_u64(&mut buf, rb_pa + rb_offs.rb_pending_pos as u64, pending_pos);

    let map_kva = pa_to_kva(map_pa, page_offset);
    (
        RenderScene {
            buf,
            page_offset,
            offsets,
        },
        map_kva,
    )
}

/// Build a `BpfMapInfo` for ringbuf tests with the given map_kva.
fn ringbuf_map_info(map_kva: u64) -> super::super::bpf_map::BpfMapInfo {
    let (name_bytes, name_len) = name_from_str("test_ringbuf");
    super::super::bpf_map::BpfMapInfo {
        map_pa: 0,
        map_kva,
        name_bytes,
        name_len,
        map_type: super::super::bpf_map::BPF_MAP_TYPE_RINGBUF,
        map_flags: 0,
        key_size: 0,
        value_size: 0,
        max_entries: 0,
        value_kva: None,
        btf_kva: 0,
        btf_value_type_id: 0,
        btf_vmlinux_value_type_id: 0,
        btf_key_type_id: 0,
    }
}

// -- #55 ringbuf state render tests -------------------------------

/// `render_ringbuf_state` returns the no-offsets error string when
/// `BpfMapOffsets::ringbuf_offsets` is None (kernel built without
/// ringbuf, or BTF stripped).
#[test]
fn render_ringbuf_no_offsets_returns_err() {
    let (scene, map_kva) = build_ringbuf_scene(0xFFFF, 0x100, 0x200, 0x180, None);
    let info = ringbuf_map_info(map_kva);
    // SAFETY: scene.buf is a live local Vec<u8> whose backing
    // storage outlives the GuestMem use.
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };

    let mut offsets = scene.offsets;
    offsets.ringbuf_offsets = None;
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &offsets, 0);
    let result = render_ringbuf_state(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("BTF lacks bpf_ringbuf_map")));
}

/// `render_ringbuf_state` returns the unmapped-map_kva error when
/// `info.map_kva` falls outside the synthetic memory window.
#[test]
fn render_ringbuf_unmapped_map_kva_returns_err() {
    let (scene, _map_kva) = build_ringbuf_scene(0xFFFF, 0x100, 0x200, 0x180, None);
    // Use a KVA that translates outside the buf.
    let bogus_map_kva = scene.page_offset + 0x100_0000;
    let info = ringbuf_map_info(bogus_map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_ringbuf_state(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("RINGBUF map_kva unmapped")));
}

/// `render_ringbuf_state` returns the rb-pointer-NULL error when
/// the bpf_ringbuf_map.rb field reads as 0.
#[test]
fn render_ringbuf_null_rb_returns_err() {
    let (scene, map_kva) = build_ringbuf_scene(0xFFFF, 0x100, 0x200, 0x180, Some(0));
    let info = ringbuf_map_info(map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_ringbuf_state(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("rb pointer NULL")));
}

/// `render_ringbuf_state` returns the rb-fields-unmapped error when
/// the bpf_ringbuf pointer translates outside the buffer.
#[test]
fn render_ringbuf_unmapped_rb_returns_err() {
    let (scene, map_kva) = build_ringbuf_scene(
        0xFFFF,
        0x100,
        0x200,
        0x180,
        Some(crate::monitor::symbols::DEFAULT_PAGE_OFFSET + 0x100_0000),
    );
    let info = ringbuf_map_info(map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_ringbuf_state(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("rb->mask unmapped")));
}

/// Happy path: capacity = mask + 1, pending_bytes = producer - consumer.
#[test]
fn render_ringbuf_basic_capacity_and_pending() {
    // 64 KiB ring (mask = 0xFFFF, capacity = 0x10000), consumer at
    // 0x100, producer at 0x300, pending = 0x200.
    let (scene, map_kva) = build_ringbuf_scene(0xFFFF, 0x100, 0x300, 0x180, None);
    let info = ringbuf_map_info(map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let rb = render_ringbuf_state(&accessor, &info).expect("happy-path render");
    assert_eq!(rb.capacity, 0x10000);
    assert_eq!(rb.consumer_pos, 0x100);
    assert_eq!(rb.producer_pos, 0x300);
    assert_eq!(rb.pending_pos, 0x180);
    assert_eq!(rb.pending_bytes, 0x200);
}

/// Wraparound: producer < consumer in absolute terms => unsigned
/// wraparound subtraction yields a meaningful pending count.
#[test]
fn render_ringbuf_wraparound_pending_bytes() {
    // consumer beyond producer by 100; wrap subtraction yields
    // u64::MAX - 99.
    let consumer = 200u64;
    let producer = 100u64;
    let (scene, map_kva) = build_ringbuf_scene(0xFFFF, consumer, producer, producer, None);
    let info = ringbuf_map_info(map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let rb = render_ringbuf_state(&accessor, &info).expect("wraparound render");
    assert_eq!(
        rb.pending_bytes,
        producer.wrapping_sub(consumer),
        "wraparound subtraction must match production semantics",
    );
}

/// `mask = u64::MAX` triggers the "capacity would wrap to 0" guard;
/// the helper bails with an explicit error rather than producing a
/// nonsense capacity = 0.
#[test]
fn render_ringbuf_mask_max_returns_err() {
    let (scene, map_kva) = build_ringbuf_scene(u64::MAX, 0, 0, 0, None);
    let info = ringbuf_map_info(map_kva);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_ringbuf_state(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("mask = u64::MAX")));
}

// -- #53 stack-trace render tests ---------------------------------

fn synth_stackmap_offsets() -> super::super::btf_offsets::BpfStackmapOffsets {
    super::super::btf_offsets::BpfStackmapOffsets {
        smap_n_buckets: 0,
        smap_buckets: 16,
        smb_nr: 0,
        smb_data: 16,
    }
}

fn synth_stackmap_map_offsets() -> crate::monitor::btf_offsets::BpfMapOffsets {
    let mut o = crate::monitor::btf_offsets::BpfMapOffsets::EMPTY;
    o.stackmap_offsets = Some(synth_stackmap_offsets());
    o
}

/// Build a stack-trace scene. `bucket_pc_lists[i]` carries the PCs
/// for bucket `i` (empty Vec means an empty/null bucket pointer);
/// the layout writes a `bpf_stack_map` with `n_buckets` and
/// `buckets[]` flex array, plus per-bucket `stack_map_bucket`
/// structs containing `nr` + `data[]`.
fn build_stackmap_scene(
    bucket_pc_lists: &[Vec<u64>],
    map_flags: u32,
) -> (RenderScene, super::super::bpf_map::BpfMapInfo) {
    let sm_offs = synth_stackmap_offsets();
    let offsets = synth_stackmap_map_offsets();
    let page_offset = crate::monitor::symbols::DEFAULT_PAGE_OFFSET;

    // bpf_stack_map at PA 0x1000. Layout:
    //   [0..4) n_buckets (u32)
    //   [16..16 + n*8) buckets[] (each entry is u64 pointer)
    let map_pa: u64 = 0x1000;
    let n_buckets = bucket_pc_lists.len() as u32;
    let map_struct_end = sm_offs.smap_buckets as u64 + (n_buckets as u64) * 8;

    // Each populated bucket gets a stack_map_bucket at fixed strides
    // starting 0x1_0000, each 0x1000 apart.
    let bucket_stride: u64 = 0x1000;
    let buckets_start: u64 = 0x1_0000;
    let buf_size: usize = (buckets_start + bucket_stride * (n_buckets as u64 + 1)) as usize;
    let mut buf = vec![0u8; buf_size];

    let write_u32 = |buf: &mut Vec<u8>, pa: u64, val: u32| {
        let off = pa as usize;
        buf[off..off + 4].copy_from_slice(&val.to_ne_bytes());
    };
    let write_u64 = |buf: &mut Vec<u8>, pa: u64, val: u64| {
        let off = pa as usize;
        buf[off..off + 8].copy_from_slice(&val.to_ne_bytes());
    };

    // n_buckets at smap_n_buckets (offset 0).
    write_u32(&mut buf, map_pa + sm_offs.smap_n_buckets as u64, n_buckets);

    // Per-bucket pointers and bucket data.
    let _ = map_struct_end; // silence unused
    for (i, pcs) in bucket_pc_lists.iter().enumerate() {
        let slot_pa = map_pa + sm_offs.smap_buckets as u64 + (i as u64) * 8;
        if pcs.is_empty() {
            write_u64(&mut buf, slot_pa, 0); // null bucket pointer
            continue;
        }
        let bucket_pa = buckets_start + (i as u64) * bucket_stride;
        write_u64(&mut buf, slot_pa, pa_to_kva(bucket_pa, page_offset));
        // stack_map_bucket: nr at smb_nr (0), data[] at smb_data (16).
        write_u32(
            &mut buf,
            bucket_pa + sm_offs.smb_nr as u64,
            pcs.len() as u32,
        );
        for (j, pc) in pcs.iter().enumerate() {
            write_u64(
                &mut buf,
                bucket_pa + sm_offs.smb_data as u64 + (j as u64) * 8,
                *pc,
            );
        }
    }

    let map_kva = pa_to_kva(map_pa, page_offset);
    let (name_bytes, name_len) = name_from_str("test_stack");
    let info = super::super::bpf_map::BpfMapInfo {
        map_pa: 0,
        map_kva,
        name_bytes,
        name_len,
        map_type: super::super::bpf_map::BPF_MAP_TYPE_STACK_TRACE,
        map_flags,
        key_size: 0,
        value_size: 0,
        max_entries: n_buckets,
        value_kva: None,
        btf_kva: 0,
        btf_value_type_id: 0,
        btf_vmlinux_value_type_id: 0,
        btf_key_type_id: 0,
    };

    (
        RenderScene {
            buf,
            page_offset,
            offsets,
        },
        info,
    )
}

/// `render_stack_traces` returns the BTF-lacks error when
/// stackmap_offsets is None.
#[test]
fn render_stack_traces_no_offsets_returns_err() {
    let (mut scene, info) = build_stackmap_scene(&[vec![]], 0);
    scene.offsets.stackmap_offsets = None;
    // SAFETY: scene.buf is a live local Vec<u8> whose backing
    // storage outlives the GuestMem use.
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_stack_traces(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("BTF lacks bpf_stack_map")));
}

/// `render_stack_traces` returns the unmapped-map_kva error when
/// info.map_kva translates outside the buffer.
#[test]
fn render_stack_traces_unmapped_map_kva_returns_err() {
    let (scene, _info) = build_stackmap_scene(&[vec![]], 0);
    let mut info = _info;
    info.map_kva = scene.page_offset + 0x100_0000;
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let result = render_stack_traces(&accessor, &info);
    assert!(matches!(result, Err(ref s) if s.contains("STACK_TRACE map_kva unmapped")));
}

/// All-empty buckets: walker returns Ok with `n_buckets` set, an
/// empty entries vec, and `truncated=false`.
#[test]
fn render_stack_traces_empty_returns_no_entries() {
    let (scene, info) = build_stackmap_scene(&[vec![], vec![], vec![], vec![]], 0);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let st = render_stack_traces(&accessor, &info).expect("empty render");
    assert_eq!(st.n_buckets, 4);
    assert!(st.entries.is_empty());
    assert!(!st.truncated);
}

/// Populated buckets surface their PCs in `entries[].pcs`.
#[test]
fn render_stack_traces_populated_pcs() {
    let (scene, info) = build_stackmap_scene(
        &[
            vec![],
            vec![0xFFFF_FFFF_8100_1000, 0xFFFF_FFFF_8100_2000],
            vec![],
            vec![0xFFFF_FFFF_8200_3000],
        ],
        0,
    );
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let st = render_stack_traces(&accessor, &info).expect("populated render");
    assert_eq!(st.n_buckets, 4);
    assert_eq!(st.entries.len(), 2);
    assert_eq!(st.entries[0].bucket_id, 1);
    assert_eq!(st.entries[0].nr, 2);
    assert_eq!(
        st.entries[0].pcs,
        vec![0xFFFF_FFFF_8100_1000, 0xFFFF_FFFF_8100_2000]
    );
    assert_eq!(st.entries[1].bucket_id, 3);
    assert_eq!(st.entries[1].pcs, vec![0xFFFF_FFFF_8200_3000]);
    assert!(!st.truncated);
}

/// Build-id mode: pcs vector stays empty (per-entry shape is
/// bpf_stack_build_id, not u64), data_hex carries raw bytes.
#[test]
fn render_stack_traces_build_id_mode_pcs_empty() {
    const BPF_F_STACK_BUILD_ID: u32 = 1 << 5;
    // One bucket with one "PC slot" (treated as 8 bytes of raw data
    // in build-id mode). The kernel's per-entry size is 32 bytes
    // (bpf_stack_build_id); our synthetic test only needs to verify
    // pcs stays empty regardless of data shape.
    let (scene, info) = build_stackmap_scene(&[vec![0xDEAD_BEEFu64]], BPF_F_STACK_BUILD_ID);
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let st = render_stack_traces(&accessor, &info).expect("build-id render");
    assert_eq!(st.entries.len(), 1);
    assert!(
        st.entries[0].pcs.is_empty(),
        "build-id mode must NOT populate pcs (entry shape is bpf_stack_build_id, not u64)"
    );
}

// -- #53 fd-array render tests ------------------------------------

fn synth_fd_array_offsets() -> crate::monitor::btf_offsets::BpfMapOffsets {
    let mut o = crate::monitor::btf_offsets::BpfMapOffsets::EMPTY;
    // Place ptrs[] at offset 16 within the synthetic bpf_array.
    o.array_value = 16;
    o
}

/// Build a synthetic FD-array scene. `populated_indices` lists the
/// slot indices that should be non-zero. `max_entries` controls the
/// scan upper bound.
fn build_fd_array_scene(
    map_type: u32,
    max_entries: u32,
    populated_indices: &[u32],
) -> (RenderScene, super::super::bpf_map::BpfMapInfo) {
    let offsets = synth_fd_array_offsets();
    let page_offset = crate::monitor::symbols::DEFAULT_PAGE_OFFSET;

    // bpf_array at PA 0x1000. ptrs[] starts at offset
    // `array_value` (16); each slot is 8 bytes.
    let map_pa: u64 = 0x1000;
    let scan = max_entries.min(super::render_map::MAX_FD_ARRAY_SLOTS);
    let buf_size =
        (map_pa as usize) + (offsets.array_value as usize) + (scan as usize) * 8 + 0x1000;
    let mut buf = vec![0u8; buf_size];
    let write_u64 = |buf: &mut Vec<u8>, pa: u64, val: u64| {
        let off = pa as usize;
        buf[off..off + 8].copy_from_slice(&val.to_ne_bytes());
    };

    for &idx in populated_indices {
        if idx >= scan {
            continue;
        }
        let slot_pa = map_pa + offsets.array_value as u64 + (idx as u64) * 8;
        // Any non-zero pointer suffices; use the slot index + 1
        // shifted into a recognizable kernel-pointer range.
        write_u64(&mut buf, slot_pa, 0xFFFF_8000_0000_0000 + (idx as u64));
    }

    let map_kva = pa_to_kva(map_pa, page_offset);
    let (name_bytes, name_len) = name_from_str("test_fd_array");
    let info = super::super::bpf_map::BpfMapInfo {
        map_pa: 0,
        map_kva,
        name_bytes,
        name_len,
        map_type,
        map_flags: 0,
        key_size: 0,
        value_size: 0,
        max_entries,
        value_kva: None,
        btf_kva: 0,
        btf_value_type_id: 0,
        btf_vmlinux_value_type_id: 0,
        btf_key_type_id: 0,
    };
    (
        RenderScene {
            buf,
            page_offset,
            offsets,
        },
        info,
    )
}

/// PROG_ARRAY with three populated slots: walker reports
/// populated=3, indices=[indexes].
#[test]
fn render_fd_array_populated_indices() {
    let (scene, info) = build_fd_array_scene(
        super::super::bpf_map::BPF_MAP_TYPE_PROG_ARRAY,
        16,
        &[0, 5, 10],
    );
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let fa = render_fd_array_slots(&accessor, &info);
    assert_eq!(fa.populated, 3);
    assert_eq!(fa.scanned, 16);
    assert_eq!(fa.indices, vec![0, 5, 10]);
    assert!(!fa.truncated);
    assert!(
        !fa.indices_truncated,
        "populated == indices.len() must NOT set indices_truncated",
    );
}

/// HASH-shaped FD families (SOCKHASH / DEVMAP_HASH / HASH_OF_MAPS)
/// short-circuit to populated=0/scanned=0/empty.
#[test]
fn render_fd_array_hash_shaped_returns_empty() {
    let (scene, info) = build_fd_array_scene(
        super::super::bpf_map::BPF_MAP_TYPE_SOCKHASH,
        16,
        &[0, 5, 10],
    );
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let fa = render_fd_array_slots(&accessor, &info);
    assert_eq!(fa.populated, 0);
    assert_eq!(fa.scanned, 0);
    assert!(fa.indices.is_empty());
    assert!(!fa.truncated);
    assert!(
        !fa.indices_truncated,
        "hash-shaped early exit must NOT set indices_truncated",
    );
}

/// `max_entries > MAX_FD_ARRAY_SLOTS` triggers the truncation flag.
/// Walker still reports populated/indices for the slots it scanned.
#[test]
fn render_fd_array_max_entries_truncation() {
    // max_entries one above the cap. Skip populating slots — the
    // truncation flag fires regardless of population state. Build a
    // scene with the cap as effective scan size.
    let (scene, mut info) = build_fd_array_scene(
        super::super::bpf_map::BPF_MAP_TYPE_PROG_ARRAY,
        super::render_map::MAX_FD_ARRAY_SLOTS,
        &[],
    );
    info.max_entries = super::render_map::MAX_FD_ARRAY_SLOTS + 1;
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let fa = render_fd_array_slots(&accessor, &info);
    assert!(
        fa.truncated,
        "max_entries above MAX_FD_ARRAY_SLOTS must set truncated"
    );
    assert_eq!(fa.scanned, super::render_map::MAX_FD_ARRAY_SLOTS);
    // No populated slots in this scene → indices.len() == 0 == populated,
    // so indices_truncated stays false even though scan-size truncation
    // fires. Pin the orthogonality of the two flags.
    assert!(
        !fa.indices_truncated,
        "scan-size truncation must NOT set indices_truncated when populated == indices.len()",
    );
    let _ = scene; // silence unused
}

// -- #52 STRUCT_OPS render error paths ----------------------------

/// `render_map` STRUCT_OPS arm with `struct_ops_offsets = None`
/// surfaces the BTF-offsets-unresolved diagnostic — the renderer
/// must NOT silently read with `data_off = 0` against a wrapper-
/// inclusive `value_size`.
#[test]
fn render_map_struct_ops_no_offsets_returns_error() {
    let mut offsets = crate::monitor::btf_offsets::BpfMapOffsets::EMPTY;
    // No struct_ops_offsets resolution.
    offsets.struct_ops_offsets = None;
    // Provide buf with map at PA 0x1000 — won't actually be read.
    let buf = vec![0u8; 0x4000];
    let page_offset = crate::monitor::symbols::DEFAULT_PAGE_OFFSET;
    // SAFETY: buf is a live local Vec<u8>.
    let mem =
        unsafe { super::super::reader::GuestMem::new(buf.as_ptr() as *mut u8, buf.len() as u64) };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &offsets, 0);
    let (name_bytes, name_len) = name_from_str("test_struct_ops");
    let info = super::super::bpf_map::BpfMapInfo {
        map_pa: 0,
        map_kva: pa_to_kva(0x1000, page_offset),
        name_bytes,
        name_len,
        map_type: super::super::bpf_map::BPF_MAP_TYPE_STRUCT_OPS,
        map_flags: 0,
        key_size: 0,
        value_size: 256,
        max_entries: 1,
        value_kva: None,
        btf_kva: 0,
        btf_value_type_id: 0,
        btf_vmlinux_value_type_id: 0,
        btf_key_type_id: 0,
    };
    let arena_page_index = super::render_map::ArenaPageIndex::new();
    let sdt_alloc_metas: Vec<super::render_map::SdtAllocMeta> = Vec::new();
    let ctx = super::render_map::RenderMapCtx {
        accessor: &accessor,
        btf: None,
        num_cpus: 1,
        arena_offsets: None,
        shared_arena: None,
        arena_page_index: &arena_page_index,
        sdt_alloc_metas: &sdt_alloc_metas,
    };
    let rendered = super::render_map::render_map(&ctx, &info);
    let err = rendered
        .error
        .expect("STRUCT_OPS no-offsets must surface error");
    assert!(
        err.contains("STRUCT_OPS value unreadable") && err.contains("BTF offsets unresolved"),
        "STRUCT_OPS no-offsets error must explain the resolution failure; got: {err}",
    );
}

/// `render_map` STRUCT_OPS arm with valid struct_ops_offsets but
/// `value_kva` translating outside the buffer surfaces the
/// "value region unmapped" diagnostic.
#[test]
fn render_map_struct_ops_unmapped_value_returns_error() {
    let mut offsets = crate::monitor::btf_offsets::BpfMapOffsets::EMPTY;
    offsets.struct_ops_offsets = Some(super::super::btf_offsets::StructOpsOffsets {
        kvalue: 64,
        value_data: 8,
    });
    let buf = vec![0u8; 0x4000];
    let page_offset = crate::monitor::symbols::DEFAULT_PAGE_OFFSET;
    let mem =
        unsafe { super::super::reader::GuestMem::new(buf.as_ptr() as *mut u8, buf.len() as u64) };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &offsets, 0);
    // value_kva points outside the buffer (page_offset + far) so
    // the read_value translate fails.
    let (name_bytes, name_len) = name_from_str("test_struct_ops");
    let info = super::super::bpf_map::BpfMapInfo {
        map_pa: 0,
        map_kva: pa_to_kva(0x1000, page_offset),
        name_bytes,
        name_len,
        map_type: super::super::bpf_map::BPF_MAP_TYPE_STRUCT_OPS,
        map_flags: 0,
        key_size: 0,
        value_size: 256,
        max_entries: 1,
        value_kva: Some(page_offset + 0x100_0000), // far past buffer
        btf_kva: 0,
        btf_value_type_id: 0,
        btf_vmlinux_value_type_id: 0,
        btf_key_type_id: 0,
    };
    let arena_page_index = super::render_map::ArenaPageIndex::new();
    let sdt_alloc_metas: Vec<super::render_map::SdtAllocMeta> = Vec::new();
    let ctx = super::render_map::RenderMapCtx {
        accessor: &accessor,
        btf: None,
        num_cpus: 1,
        arena_offsets: None,
        shared_arena: None,
        arena_page_index: &arena_page_index,
        sdt_alloc_metas: &sdt_alloc_metas,
    };
    let rendered = super::render_map::render_map(&ctx, &info);
    let err = rendered
        .error
        .expect("STRUCT_OPS unmapped-value must surface error");
    assert!(
        err.contains("STRUCT_OPS value unreadable") && err.contains("value region unmapped"),
        "STRUCT_OPS unmapped-value error must mention the unmapped region; got: {err}",
    );
}

/// `find_all_bpf_maps` populates `value_kva = kvalue + data_off` for
/// STRUCT_OPS maps when `struct_ops_offsets` is resolved. This test
/// covers the static math without the page-walk to confirm the
/// kvalue + data_off chain matches the spec from
/// `bpf_struct_ops_map_alloc`.
#[test]
fn struct_ops_value_kva_math_kvalue_plus_data() {
    let so = super::super::btf_offsets::StructOpsOffsets {
        kvalue: 0x40,
        value_data: 0x10,
    };
    let map_kva = 0xFFFF_8888_0000_0000u64;
    // Production calculation: map_kva + kvalue + value_data.
    let value_kva = map_kva
        .wrapping_add(so.kvalue as u64)
        .wrapping_add(so.value_data as u64);
    assert_eq!(value_kva, 0xFFFF_8888_0000_0050);
}

/// `populated > MAX_FD_ARRAY_INDICES`: indices vector caps at the
/// limit; populated continues to count beyond. The renderer flags
/// the divergence on `indices_truncated` so a downstream consumer
/// can see at a glance that the indices list is partial.
#[test]
fn render_fd_array_indices_capped_at_max_indices() {
    let cap = super::render_map::MAX_FD_ARRAY_INDICES as u32;
    // Populate cap + 5 slots; expect populated=cap+5, indices=cap.
    let pop: Vec<u32> = (0..cap + 5).collect();
    let (scene, info) = build_fd_array_scene(
        super::super::bpf_map::BPF_MAP_TYPE_PROG_ARRAY,
        cap + 5,
        &pop,
    );
    let mem = unsafe {
        super::super::reader::GuestMem::new(scene.buf.as_ptr() as *mut u8, scene.buf.len() as u64)
    };
    let mem_ref: &super::super::reader::GuestMem = unsafe { &*(&mem as *const _) };
    let kernel = super::super::guest::GuestKernel::new_for_test(
        mem_ref,
        std::collections::HashMap::new(),
        scene.page_offset,
        0,
        false,
    );
    let kernel_ref = unsafe { &*(&kernel as *const _) };
    let accessor =
        super::super::bpf_map::GuestMemMapAccessor::new_for_test(kernel_ref, &scene.offsets, 0);
    let fa = render_fd_array_slots(&accessor, &info);
    assert_eq!(
        fa.populated,
        cap + 5,
        "populated counts every non-zero slot"
    );
    assert_eq!(
        fa.indices.len() as u32,
        cap,
        "indices vector caps at MAX_FD_ARRAY_INDICES",
    );
    assert!(
        fa.indices_truncated,
        "populated > indices.len() must set indices_truncated",
    );
}

/// `dump_truncated_at_us` defaults to None and roundtrips through
/// serde with `skip_serializing_if`. The field is absent on the
/// wire when None (every healthy dump) and surfaces a u64 us-offset
/// when the soft deadline fires.
#[test]
fn report_dump_truncated_at_us_serde() {
    // None: field absent in JSON.
    let r = FailureDumpReport::default();
    let json = serde_json::to_string(&r).unwrap();
    assert!(
        !json.contains("dump_truncated_at_us"),
        "None must skip-serialize: {json}"
    );
    let parsed: FailureDumpReport = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.dump_truncated_at_us, None);

    // Some(us): field present and roundtrips.
    let r = FailureDumpReport {
        dump_truncated_at_us: Some(15_000),
        ..FailureDumpReport::default()
    };
    let json = serde_json::to_string(&r).unwrap();
    assert!(
        json.contains("\"dump_truncated_at_us\":15000"),
        "Some must serialize: {json}"
    );
    let parsed: FailureDumpReport = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.dump_truncated_at_us, Some(15_000));
}

/// `MAX_ENRICHED_TASKS` constant is non-zero and large enough to
/// cover any healthy SCX runnable_list depth (bounded by the
/// kernel's stall watchdog, well under 4096 in practice).
#[test]
fn max_enriched_tasks_constant_is_reasonable() {
    // Pin the constant so a future tightening / loosening is a
    // deliberate test edit, not a silent drift.
    assert_eq!(super::MAX_ENRICHED_TASKS, 4096);
}

// ---- Inline small struct rendering for FailureDumpEntry --------
//
// When a key or value is a struct with ≤ 3 non-zero non-fmt-string
// inline-scalar fields, Display collapses it into the
// `{field: value, ...}` form. When BOTH sides qualify, the entry
// renders on a single line. When only one qualifies, that side
// inlines and the other keeps its block form. Payload (when
// present) always renders as a block below the entry.

fn make_small_struct(type_name: &str, fields: &[(&str, u64)]) -> RenderedValue {
    RenderedValue::Struct {
        type_name: Some(type_name.into()),
        members: fields
            .iter()
            .map(|(n, v)| super::super::btf_render::RenderedMember {
                name: (*n).into(),
                value: RenderedValue::Uint {
                    bits: 64,
                    value: *v,
                },
            })
            .collect(),
    }
}

#[test]
fn entry_display_renders_inline_struct_key_and_value() {
    // With the consolidated indent-based format, each entry renders
    // as:
    //   `entry: key=<key>\n  value: <value>`
    // Small structs collapse onto their own line via the btf_render
    // inline form `Type{f=v, f=v}`.
    let entry = FailureDumpEntry {
        key: Some(make_small_struct(
            "cgroup_llc_id",
            &[("cgrp_id", 1), ("llc_id", 5)],
        )),
        key_hex: "01 05".into(),
        value: Some(make_small_struct(
            "cbw_llc_entry",
            &[("llcx", 17_592_186_046_336)],
        )),
        value_hex: "00".into(),
        payload: None,
    };
    let out = format!("{entry}");
    // Header line: `entry: key=cgroup_llc_id{cgrp_id=1, llc_id=5}`
    assert!(
        out.starts_with("entry: key="),
        "missing entry header: {out}",
    );
    assert!(out.contains("cgroup_llc_id{"), "key inline form: {out}");
    assert!(out.contains("cgrp_id=1"), "key field cgrp_id: {out}");
    assert!(out.contains("llc_id=5"), "key field llc_id: {out}");
    // Value line: indented `  value: cbw_llc_entry{...}`.
    assert!(
        out.contains("\n  value: "),
        "missing indented value line: {out}",
    );
    assert!(out.contains("cbw_llc_entry{"), "value inline form: {out}");
    assert!(out.contains("llcx=17592186046336"), "value field: {out}");
    // No `struct` keyword in inline form (it's been dropped from
    // the renderer entirely).
    assert!(
        !out.contains("struct cgroup_llc_id"),
        "inline form must drop `struct` prefix: {out}",
    );
    assert!(
        !out.contains("struct cbw_llc_entry"),
        "inline form must drop `struct` prefix: {out}",
    );
}

#[test]
fn entry_display_inline_zero_fields_dropped_silently() {
    // Zero fields are suppressed silently — no `(N fields zero)`
    // summary appears in the inline braces or anywhere else. The
    // operator infers from the rendered fields that the rest are
    // zero.
    let entry = FailureDumpEntry {
        key: Some(make_small_struct(
            "k",
            &[("real", 7), ("zero1", 0), ("zero2", 0)],
        )),
        key_hex: "07".into(),
        value: Some(make_small_struct("v", &[("real", 3)])),
        value_hex: "03".into(),
        payload: None,
    };
    let out = format!("{entry}");
    assert!(out.contains("real=7"), "non-zero key field present: {out}");
    assert!(
        out.contains("real=3"),
        "non-zero value field present: {out}"
    );
    assert!(!out.contains("zero1"), "zero fields are suppressed: {out}",);
    assert!(
        !out.contains("fields zero"),
        "no zero-count summary anywhere: {out}",
    );
}

#[test]
fn entry_display_value_falls_to_multi_line_when_too_wide() {
    // Value is a struct that's small enough by field count (5) but
    // its rendered inline form may exceed the inline width budget
    // — actually 5 small u64 fields fit comfortably. The btf_render
    // inline path handles arbitrary field counts so long as the
    // rendered length fits 120 chars; this test pins a value that
    // intentionally exceeds the budget to exercise the multi-line
    // breadcrumb fallback.
    let big_value = RenderedValue::Struct {
        type_name: Some("v".into()),
        members: (0..15)
            .map(|i| super::super::btf_render::RenderedMember {
                name: format!("very_long_field_name_{i}"),
                value: RenderedValue::Uint {
                    bits: 64,
                    value: 0x1234_5678_9abc_def0u64.wrapping_add(i as u64),
                },
            })
            .collect(),
    };
    let entry = FailureDumpEntry {
        key: Some(make_small_struct("k", &[("only", 1)])),
        key_hex: "01".into(),
        value: Some(big_value),
        value_hex: "01".into(),
        payload: None,
    };
    let out = format!("{entry}");
    // Multi-line breadcrumb: `value: v:` then indented field rows.
    // Block form has at least one extra newline beyond the header
    // and value lines.
    assert!(
        out.contains("\n  value: v:"),
        "multi-line value uses breadcrumb form: {out}",
    );
    // Key still inlines.
    assert!(out.contains("k{only=1}"), "key inline form: {out}");
}

#[test]
fn entry_display_payload_renders_below_value() {
    // Payload value renders below the entry on its own indented
    // line. The Display impl uses `\n  payload <rendered>` (with
    // a space, no colon) so the value's own breadcrumb completes
    // the line as `payload TypeName:` for multi-line structs or
    // just `payload <scalar>` for scalars.
    let entry = FailureDumpEntry {
        key: Some(make_small_struct("k", &[("a", 1)])),
        key_hex: "01".into(),
        value: Some(make_small_struct("v", &[("b", 2)])),
        value_hex: "02".into(),
        payload: Some(RenderedValue::Uint {
            bits: 64,
            value: 0xDEAD_BEEF,
        }),
    };
    let out = format!("{entry}");
    assert!(out.starts_with("entry: key="), "entry header: {out}");
    assert!(out.contains("\n  value: v{b=2}"), "value inline: {out}");
    // Payload on a separate line. Scalars don't have a breadcrumb,
    // so the rendered form is just the decimal number.
    assert!(out.contains("\n  .data "), ".data label must appear: {out}",);
    assert!(
        out.contains("3735928559"), // 0xDEADBEEF in decimal
        "rendered payload value must appear: {out}",
    );
}

// ---- Table rendering for FailureDumpMap -------------------------
//
// Homogeneous entries (every entry has key+value as same-shape
// inline-scalar struct, no payload) render as a compact table.
// Heterogeneous or non-qualifying batches fall back to the
// per-entry block form.

#[test]
fn map_display_table_for_homogeneous_entries() {
    let m = FailureDumpMap {
        name: "cbw".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 8,
        max_entries: 64,
        value: None,
        entries: vec![
            FailureDumpEntry {
                key: Some(make_small_struct(
                    "cgroup_llc_id",
                    &[("cgrp_id", 1), ("llc_id", 5)],
                )),
                key_hex: "01 05".into(),
                value: Some(make_small_struct(
                    "cbw_llc_entry",
                    &[("llcx", 17_592_186_046_336)],
                )),
                value_hex: "00".into(),
                payload: None,
            },
            FailureDumpEntry {
                key: Some(make_small_struct(
                    "cgroup_llc_id",
                    &[("cgrp_id", 61), ("llc_id", 3)],
                )),
                key_hex: "3d 03".into(),
                value: Some(make_small_struct(
                    "cbw_llc_entry",
                    &[("llcx", 17_592_186_047_616)],
                )),
                value_hex: "00".into(),
                payload: None,
            },
            FailureDumpEntry {
                key: Some(make_small_struct(
                    "cgroup_llc_id",
                    &[("cgrp_id", 41), ("llc_id", 1)],
                )),
                key_hex: "29 01".into(),
                value: Some(make_small_struct(
                    "cbw_llc_entry",
                    &[("llcx", 17_592_186_047_040)],
                )),
                value_hex: "00".into(),
                payload: None,
            },
        ],
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    // Header row carries column names with `|` separating key
    // from value columns.
    assert!(out.contains("cgrp_id"), "key column header missing: {out}",);
    assert!(out.contains("llc_id"), "key column header missing: {out}");
    assert!(out.contains("llcx"), "value column header missing: {out}");
    assert!(out.contains(" | "), "key/value separator missing: {out}");
    // Data rows carry the per-entry values.
    assert!(out.contains("17592186046336"), "row 0 value: {out}");
    assert!(out.contains("17592186047616"), "row 1 value: {out}");
    assert!(out.contains("17592186047040"), "row 2 value: {out}");
    // Per-entry block form should NOT appear (table replaced it).
    assert!(
        !out.contains("entry {"),
        "table form must replace per-entry blocks: {out}",
    );
}

#[test]
fn map_display_skips_table_for_single_entry() {
    // Single-entry maps fall through to per-entry rendering — the
    // table header overhead exceeds the savings.
    let m = FailureDumpMap {
        name: "single".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 8,
        max_entries: 64,
        value: None,
        entries: vec![FailureDumpEntry {
            key: Some(make_small_struct("k", &[("a", 1)])),
            key_hex: "01".into(),
            value: Some(make_small_struct("v", &[("b", 2)])),
            value_hex: "02".into(),
            payload: None,
        }],
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    // Per-entry rendering uses the indent-based format, with each
    // entry starting on its own line as `entry: key=...`. The
    // table form would have started with column headers like
    // `cgrp_id  llc_id |` — verify the per-entry path took over.
    assert!(
        out.contains("entry: key="),
        "single entry must keep per-entry rendering: {out}",
    );
    assert!(
        !out.contains(" | "),
        "single entry must not use table form: {out}",
    );
}

#[test]
fn map_display_skips_table_when_payload_present() {
    // Any entry with a payload disqualifies the whole batch — the
    // table can't carry the per-entry typed payload below each row.
    let m = FailureDumpMap {
        name: "with_payload".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 8,
        max_entries: 64,
        value: None,
        entries: vec![
            FailureDumpEntry {
                key: Some(make_small_struct("k", &[("a", 1)])),
                key_hex: "01".into(),
                value: Some(make_small_struct("v", &[("b", 2)])),
                value_hex: "02".into(),
                payload: Some(RenderedValue::Uint {
                    bits: 64,
                    value: 99,
                }),
            },
            FailureDumpEntry {
                key: Some(make_small_struct("k", &[("a", 3)])),
                key_hex: "03".into(),
                value: Some(make_small_struct("v", &[("b", 4)])),
                value_hex: "04".into(),
                payload: None,
            },
        ],
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    // Per-entry rendering used (each entry has `entry {` opener).
    assert!(
        out.contains("entry: key="),
        "payload-bearing batch must use per-entry form: {out}",
    );
    assert!(out.contains("\n  .data "), ".data still surfaces: {out}",);
}

#[test]
fn map_display_skips_table_for_heterogeneous_types() {
    // Different key type names → not homogeneous → no table.
    let m = FailureDumpMap {
        name: "het".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 8,
        max_entries: 64,
        value: None,
        entries: vec![
            FailureDumpEntry {
                key: Some(make_small_struct("k1", &[("a", 1)])),
                key_hex: "01".into(),
                value: Some(make_small_struct("v", &[("b", 2)])),
                value_hex: "02".into(),
                payload: None,
            },
            FailureDumpEntry {
                key: Some(make_small_struct("k2", &[("a", 3)])),
                key_hex: "03".into(),
                value: Some(make_small_struct("v", &[("b", 4)])),
                value_hex: "04".into(),
                payload: None,
            },
        ],
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    // Per-entry rendering, NOT a table.
    assert!(
        out.contains("entry: key="),
        "heterogeneous types must use per-entry form: {out}",
    );
}

#[test]
fn map_display_skips_table_when_entry_has_no_btf_render() {
    // Any entry with a None key or value (hex-only fallback)
    // disqualifies the table.
    let m = FailureDumpMap {
        name: "no_btf".into(),
        map_type: BPF_MAP_TYPE_HASH,
        value_size: 8,
        max_entries: 64,
        value: None,
        entries: vec![
            FailureDumpEntry {
                key: None,
                key_hex: "ab".into(),
                value: None,
                value_hex: "cd".into(),
                payload: None,
            },
            FailureDumpEntry {
                key: Some(make_small_struct("k", &[("a", 1)])),
                key_hex: "01".into(),
                value: Some(make_small_struct("v", &[("b", 2)])),
                value_hex: "02".into(),
                payload: None,
            },
        ],
        percpu_entries: Vec::new(),
        percpu_hash_entries: Vec::new(),
        arena: None,
        ringbuf: None,
        stack_trace: None,
        fd_array: None,
        error: None,
    };
    let out = format!("{m}");
    assert!(
        out.contains("entry: key="),
        "missing BTF render disqualifies table: {out}",
    );
    assert!(
        out.contains("ab (raw)"),
        "hex fallback must still surface: {out}",
    );
}