exatok 0.1.1

Exact GPU-resident BPE tokenizer whose token ids match tiktoken byte for byte
Documentation
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
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
//! Benchmark harness support. OWNER: Bench.
//!
//! Absolute-throughput measurement against host baselines on one machine.
//! Ratios alone are prohibited: published GPU tokenizer speedups do not
//! survive division precisely because they were reported as ratios over an
//! unstated and mismeasured baseline.
//!
//! Acceptance: one command emits absolute MB/s per tokenizer with thread and
//! core counts recorded, reproducible across runs.
//!
//! # What this module is
//!
//! Every number that leaves this harness is absolute: bytes per second, and
//! bytes per second divided by the thread count that produced it. A ratio may
//! be computed by a reader from two absolute rows; the harness never reports
//! one on its own, because a ratio hides which baseline was used and how it
//! was measured.
//!
//! # The defect this harness exists to avoid
//!
//! Both BlockBPE and GPUTOK report speedups against a tiktoken baseline of
//! roughly 0.94 MB/s. On this machine the same library, same vocabulary,
//! reaches tens of MB/s on a single thread. The gap is not hardware: it is
//! per-call Python wrapper overhead measured as if it were tokenizer work.
//! [`assess_plausibility`] encodes that boundary so a regressed harness fails
//! loudly instead of quietly publishing a 40x measurement error.
//!
//! # Layering
//!
//! Pure measurement algebra, machine probing, corpus construction, and report
//! rendering live here and are unit tested. The host baselines themselves are
//! third-party Python libraries, so a driver subprocess does the encoding and
//! reports records on stdout; this module owns the protocol, the statistics,
//! and the table.

use std::collections::BTreeMap;
use std::fs;
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::ExatokError;

/// Bytes in one megabyte, SI. The literature quotes MB/s decimally, so the
/// harness does too, and says so rather than leaving the reader to guess.
pub const BYTES_PER_MB: f64 = 1_000_000.0;

/// Bytes in one gigabyte, SI.
pub const BYTES_PER_GB: f64 = 1_000_000_000.0;

/// Per-physical-core MB/s below which a compiled byte-level BPE measurement
/// warrants an explanation before it is published.
///
/// Calibration: correctly measured tiktoken on one core of this class of core
/// runs in the tens of MB/s, and the published 0.94 MB/s baseline sits a
/// factor of forty below that.
///
/// Per *core*, not per thread. An earlier version divided by the thread count,
/// which flagged every SMT-oversubscribed cell: putting 32 threads on 16
/// physical cores must roughly halve per-thread throughput, and that is
/// arithmetic, not a defect. Dividing by `min(threads, physical_cores)`
/// measures the hardware actually doing the work.
///
/// Falling under this floor is a question, not a verdict. A library can be
/// legitimately this slow; see [`KNOWN_SLOW_BASELINES`]. The conditions that
/// are unambiguously harness bugs are
/// [`Plausibility::ShortTimedRegion`] and
/// [`Plausibility::ThreadsNotHonoured`].
pub const PLAUSIBLE_FLOOR_MB_S_PER_CORE: f64 = 5.0;

/// Shortest timed region whose throughput is trustworthy.
///
/// A 16-thread rayon pool costs a few hundred microseconds to spin up and the
/// batch is not evenly divided until every worker has started. Timing a 20 ms
/// region across 16 threads therefore charges pool startup to the tokenizer:
/// the first sweep on this machine timed 33.5 MB batches that completed in
/// 19 ms and recorded gigatoken at 4.04x achieved parallelism on 16 pinned
/// cores, which is a startup artifact rather than a scaling limit.
pub const MIN_TRUSTWORTHY_TIMED_SECS: f64 = 0.25;

/// Fraction of the requested thread count that must actually be achieved.
///
/// Checked only when the request fits in physical cores, since an SMT-
/// oversubscribed request cannot achieve its nominal count by definition.
/// This is the check that distinguishes a real 16-thread run from a
/// 16-thread run that quietly ran on one thread.
pub const MIN_PARALLEL_EFFICIENCY: f64 = 0.5;

/// Parallelism a single-threaded pinned cell must achieve.
///
/// A 1-thread run pinned to one CPU consumes one CPU-second per wall second
/// unless the kernel descheduled it. If another process competes for that CPU,
/// wall time inflates while CPU time does not, so the ratio falls below 1.
///
/// This is load-bearing for honesty, not tidiness: a contended run UNDERSTATES
/// the host baseline, and understating the CPU state of the art is exactly how
/// a GPU tokenizer flatters itself. The published 0.94 MB/s figures are the
/// cautionary case. Tight, because 0.9 already allows a tenth of the core to
/// be stolen.
pub const MIN_SINGLE_THREAD_EFFICIENCY: f64 = 0.9;

/// Foreign CPU load, as a fraction of one core, that voids a cell.
///
/// Mirrors `MAX_FOREIGN_LOAD_RATIO` in `benches/baselines/host_baselines.py`
/// and must stay equal to it: the driver names the cell and this side decides
/// its fate, so a divergence either prints a note nobody acts on or refuses a
/// cell with no note explaining why.
///
/// This gate exists because [`MIN_SINGLE_THREAD_EFFICIENCY`] cannot see foreign
/// load at all. That ratio asks whether this process kept its pinned CPU, not
/// whether the machine was busy, so an SMT sibling or a memory-bandwidth hog
/// leaves it at 1.0 while throughput falls. The driver measured the answer per
/// cell and emitted it, and this side dropped the field, which left the
/// exclusivity requirement resting on an `#[ignore]` attribute string asking a
/// human for an idle machine. An advisory is not an interlock.
pub const MAX_FOREIGN_LOAD_RATIO: f64 = 0.05;

/// Baselines measured below [`PLAUSIBLE_FLOOR_MB_S_PER_CORE`] for reasons
/// established by direct experiment rather than assumed.
///
/// An entry here suppresses nothing: the cell is still reported with its
/// measured number and this reason printed beside it. The entry exists so a
/// known-slow library does not mask a genuine harness regression in the same
/// run, which a blanket threshold relaxation would.
///
/// PROVENANCE, single-sourced. Every number in the entry below came from a
/// one-off interactive measurement, not from a sweep of this harness, so it is
/// reproducible only by someone repeating that measurement by hand. It is
/// recorded here rather than in a message so the caveat travels with the
/// figure. Do not cite these four numbers, and do not tighten the floor on the
/// strength of them, until a committed sweep re-derives them. What the entry is
/// load-bearing for is narrower than what it states: the gate needs only the
/// claim that hf-tokenizers is legitimately sub-floor on this vocabulary, and
/// that claim is re-established on every run by the cell's own measured number.
pub const KNOWN_SLOW_BASELINES: &[(&str, &str)] = &[(
    "hf-tokenizers",
    "single-sourced, from an interactive run rather than this harness, pending \
     re-derivation: 8.1 MB/s/core at 60 KB falling to 4.6 MB/s/core at 1 MB \
     with encode_batch_fast, which returns ids only. The library is genuinely \
     in this range on this vocabulary and degrades with document length; the \
     offset-building encode() path is a further 1.4x to 2.0x slower and is not \
     used for timing.",
)];

/// The recorded reason a baseline is legitimately below the floor, if any.
#[must_use]
pub fn known_slow_reason(tokenizer: &str) -> Option<&'static str> {
    KNOWN_SLOW_BASELINES.iter().find(|(n, _)| *n == tokenizer).map(|(_, r)| *r)
}

/// Document size at or above which per-call dispatch overhead is amortized.
///
/// Below this, a low MB/s figure is a real property of the small-input regime
/// and not a defect, so the floor above must not be applied.
pub const AMORTIZED_DOC_BYTES: usize = 4096;

/// Relative change in whole-machine mean clock across a sweep that is worth
/// printing.
///
/// NOT a thermal drift threshold, despite the name's history. Both samples are
/// means over EVERY logical CPU, taken between cells while the machine is
/// otherwise idle, so the figure tracks how many cores happened to be busy at
/// each boundary at least as strongly as boost state. A +45.53% reading from
/// this comparison was published from this harness as thermal drift and was
/// occupancy: the sweep's first and last cells had different thread counts.
/// Treat a flagged value as "investigate the probe", never as evidence that
/// late rows are biased.
pub const SIGNIFICANT_CLOCK_DRIFT: f64 = 0.05;

/// Relative standard deviation at or above which a cell is called noisy.
pub const NOISY_REL_STDDEV: f64 = 0.05;

/// Relative standard deviation above which a cell's headline figure depends on
/// which repetition you pick, so it must not be published.
///
/// Deliberately looser than [`NOISY_REL_STDDEV`], which stays an advisory that
/// prints. The two answer different questions: a 5% spread is worth showing a
/// reader, while this gate fires only once [`RunStats::best`] and the mean have
/// diverged far enough that the published number is a property of the estimator
/// rather than of the tokenizer.
///
/// This gate exists because the report publishes the FASTEST repetition, which
/// systematically selects the least contended one. Bursty load therefore
/// improves the headline figure while leaving every CPU-side gate clean: the
/// quiet repetition kept its core, saw no foreign load, and delivered its
/// threads. Dispersion across repetitions is the only signal that survives
/// taking the best, and it was measured and printed as prose while nothing
/// acted on it. An advisory is not an interlock.
pub const MAX_PUBLISHABLE_REL_STDDEV: f64 = 0.20;

/// Fraction of the wall window a device cell's own kernels must occupy.
///
/// Applied only to cells carrying a device timeline, so host baselines are
/// untouched. Every other gate here is CPU-side: foreign load, both
/// parallelism ratios and the per-core floor all read CPU counters, and a
/// device cell contended by another process's kernels has an IDLE CPU. Such a
/// cell waits in the device queue, so wall time inflates while its own
/// `device_secs` does not, and it reaches the table as
/// [`Plausibility::Plausible`] with every CPU gate satisfied.
///
/// Deliberately loose. Host-to-device copies, launch overhead and
/// synchronisation are legitimate parts of wall time, so this is not an
/// efficiency target and must not be tightened into one. It is an interlock
/// against the gross case: below this, most of the window had the device idle,
/// so the figure measures queueing or host stalls rather than device
/// throughput.
pub const MIN_DEVICE_UTILIZATION: f64 = 0.25;

/// Stable 64-bit change detector over corpus bytes.
///
/// Two FNV-1a passes under different seeds, reusing [`crate::fnv1a32`] so the
/// harness carries no hash of its own. This detects a corpus that changed
/// between runs; it is not a cryptographic digest and is not claimed as one.
#[must_use]
pub fn corpus_digest(bytes: &[u8]) -> u64 {
    let lo = crate::fnv1a32(crate::FNV1A32_OFFSET_BASIS, bytes);
    let hi = crate::fnv1a32(crate::FNV1A32_PRIME, bytes);
    (u64::from(hi) << 32) | u64::from(lo)
}

fn artifact_err(artifact: &str, location: &str, detail: &str, fix: &str) -> ExatokError {
    ExatokError::Artifact {
        artifact: artifact.to_owned(),
        location: location.to_owned(),
        detail: detail.to_owned(),
        fix: fix.to_owned(),
    }
}

// ---------------------------------------------------------------------------
// Machine
// ---------------------------------------------------------------------------

/// The GPU the device-resident tokenizer will target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GpuInfo {
    /// Marketing name, for example `NVIDIA GeForce RTX 5090`.
    pub name: String,
    /// Total device memory in MiB, as `nvidia-smi` reports it.
    pub memory_mib: String,
    /// Driver version string.
    pub driver_version: String,
    /// CUDA compute capability.
    pub compute_capability: String,
}

/// The machine a measurement was taken on.
///
/// Recorded in full on every report. A throughput figure without a core count
/// is not comparable, which is the root of the published-baseline problem:
/// a 24.53 GB/s figure on 144 cores and a 4 GB/s figure on 16 cores describe
/// nearly the same per-core rate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Machine {
    /// CPU model string from `/proc/cpuinfo`.
    pub cpu_model: String,
    /// Distinct physical cores.
    pub physical_cores: usize,
    /// Logical CPUs, including SMT siblings.
    pub logical_cores: usize,
    /// One logical CPU per physical core, ascending. The pinning set.
    pub physical_core_cpus: Vec<usize>,
    /// cpufreq governor of cpu0, when cpufreq is present.
    pub governor: Option<String>,
    /// `MemTotal` in KiB.
    pub total_memory_kib: u64,
    /// GPU, when `nvidia-smi` answers.
    pub gpu: Option<GpuInfo>,
}

impl Machine {
    /// Probe the running machine.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when `/proc/cpuinfo` is unreadable
    /// or names no logical CPU, since no measurement is comparable without a
    /// core count. Optional facts (governor, GPU, SMT topology) degrade to a
    /// conservative default instead of failing.
    pub fn probe() -> Result<Self, ExatokError> {
        let cpuinfo = fs::read_to_string("/proc/cpuinfo").map_err(|e| {
            artifact_err(
                "/proc/cpuinfo",
                "open",
                &e.to_string(),
                "run the sweep on Linux, or supply a Machine literal",
            )
        })?;
        Self::from_probe_inputs(&cpuinfo, Self::probe_sibling_lists(), Self::probe_governor(), Self::probe_meminfo(), Self::probe_gpu())
    }

    /// Assemble a [`Machine`] from already-read probe inputs.
    ///
    /// Split out from [`Machine::probe`] so topology parsing is testable
    /// without a `/sys` mount.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when `cpuinfo` names no logical CPU.
    pub fn from_probe_inputs(
        cpuinfo: &str,
        sibling_lists: Vec<String>,
        governor: Option<String>,
        total_memory_kib: u64,
        gpu: Option<GpuInfo>,
    ) -> Result<Self, ExatokError> {
        let cpu_model = cpuinfo
            .lines()
            .find_map(|l| l.strip_prefix("model name").and_then(|r| r.split_once(':')))
            .map_or_else(|| "unknown".to_owned(), |(_, v)| v.trim().to_owned());
        let logical_cores = cpuinfo
            .lines()
            .filter(|l| l.starts_with("processor") && l.contains(':'))
            .count();
        if logical_cores == 0 {
            return Err(artifact_err(
                "/proc/cpuinfo",
                "processor lines",
                "no logical CPU found",
                "a throughput figure without a core count is not comparable; fix the probe",
            ));
        }
        let (physical_cores, physical_core_cpus) =
            Self::physical_from_siblings(&sibling_lists, logical_cores);
        Ok(Self {
            cpu_model,
            physical_cores,
            logical_cores,
            physical_core_cpus,
            governor,
            total_memory_kib,
            gpu,
        })
    }

    /// Reduce SMT sibling lists to a physical core count and a pinning set.
    ///
    /// Each entry is one CPU's `thread_siblings_list`, in ascending CPU order.
    /// The representative of a sibling group is its lowest CPU, so pinning to
    /// the returned set puts one thread on each physical core rather than two
    /// threads on one core's shared execution resources.
    #[must_use]
    pub fn physical_from_siblings(
        sibling_lists: &[String],
        logical_cores: usize,
    ) -> (usize, Vec<usize>) {
        if sibling_lists.len() != logical_cores {
            // Topology unavailable: assume no SMT rather than inventing a map.
            return (logical_cores, (0..logical_cores).collect());
        }
        let mut groups: BTreeMap<String, usize> = BTreeMap::new();
        for (cpu, list) in sibling_lists.iter().enumerate() {
            let key = list.trim().to_owned();
            groups.entry(key).and_modify(|rep| *rep = (*rep).min(cpu)).or_insert(cpu);
        }
        let mut reps: Vec<usize> = groups.values().copied().collect();
        reps.sort_unstable();
        (reps.len(), reps)
    }

    /// SMT siblings per physical core, at least 1.
    #[must_use]
    pub fn smt_siblings_per_core(&self) -> usize {
        if self.physical_cores == 0 { 1 } else { self.logical_cores / self.physical_cores }
    }

    fn probe_sibling_lists() -> Vec<String> {
        let mut out = Vec::new();
        for cpu in 0.. {
            let p = format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list");
            match fs::read_to_string(&p) {
                Ok(s) => out.push(s.trim().to_owned()),
                Err(_) => break,
            }
        }
        out
    }

    fn probe_governor() -> Option<String> {
        fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")
            .ok()
            .map(|s| s.trim().to_owned())
    }

    fn probe_meminfo() -> u64 {
        fs::read_to_string("/proc/meminfo")
            .ok()
            .and_then(|s| {
                s.lines()
                    .find_map(|l| l.strip_prefix("MemTotal:"))
                    .and_then(|r| r.split_whitespace().next().map(str::to_owned))
            })
            .and_then(|n| n.parse().ok())
            .unwrap_or(0)
    }

    fn probe_gpu() -> Option<GpuInfo> {
        let out = Command::new("nvidia-smi")
            .args([
                "--query-gpu=name,memory.total,driver_version,compute_cap",
                "--format=csv,noheader",
            ])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let text = String::from_utf8_lossy(&out.stdout);
        let line = text.lines().next()?;
        let mut f = line.split(',').map(str::trim);
        Some(GpuInfo {
            name: f.next()?.to_owned(),
            memory_mib: f.next()?.to_owned(),
            driver_version: f.next()?.to_owned(),
            compute_capability: f.next()?.to_owned(),
        })
    }
}

// ---------------------------------------------------------------------------
// Clock drift
// ---------------------------------------------------------------------------

/// A snapshot of per-CPU clocks, for detecting boost loss across a sweep.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClockSample {
    /// Mean reported MHz across logical CPUs.
    pub mean_mhz: f64,
    /// Lowest reported MHz.
    pub min_mhz: f64,
    /// Highest reported MHz.
    pub max_mhz: f64,
}

impl ClockSample {
    /// Parse a clock sample out of `/proc/cpuinfo` text.
    ///
    /// Returns `None` when the kernel reports no `cpu MHz` lines, which is the
    /// case on some virtualized hosts; the report then omits drift rather than
    /// asserting a stability it did not observe.
    #[must_use]
    pub fn parse(cpuinfo: &str) -> Option<Self> {
        let mhz: Vec<f64> = cpuinfo
            .lines()
            .filter_map(|l| l.strip_prefix("cpu MHz"))
            .filter_map(|r| r.split_once(':'))
            .filter_map(|(_, v)| v.trim().parse::<f64>().ok())
            .filter(|v| v.is_finite() && *v > 0.0)
            .collect();
        if mhz.is_empty() {
            return None;
        }
        let sum: f64 = mhz.iter().sum();
        let mut min = f64::INFINITY;
        let mut max = f64::NEG_INFINITY;
        for v in &mhz {
            min = min.min(*v);
            max = max.max(*v);
        }
        #[allow(clippy::cast_precision_loss)]
        let n = mhz.len() as f64;
        Some(Self { mean_mhz: sum / n, min_mhz: min, max_mhz: max })
    }

    /// Probe the running machine's clocks.
    #[must_use]
    pub fn probe() -> Option<Self> {
        Self::parse(&fs::read_to_string("/proc/cpuinfo").ok()?)
    }
}

/// Clock behaviour observed across a whole sweep.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClockDrift {
    /// Sample taken before the first measurement.
    pub first: ClockSample,
    /// Sample taken after the last measurement.
    pub last: ClockSample,
}

impl ClockDrift {
    /// Signed relative change in mean clock from start to end of the sweep.
    ///
    /// Negative means the whole-machine mean fell. This does NOT establish that
    /// late rows are pessimistic: see [`SIGNIFICANT_CLOCK_DRIFT`] for why the
    /// two samples are not comparable unless both boundaries had equal
    /// occupancy.
    #[must_use]
    pub fn drift_ratio(&self) -> f64 {
        if self.first.mean_mhz <= 0.0 {
            return 0.0;
        }
        (self.last.mean_mhz - self.first.mean_mhz) / self.first.mean_mhz
    }

    /// True when the two boundary samples differ enough to warrant checking the
    /// probe. Not a statement that any row is biased.
    #[must_use]
    pub fn is_significant(&self) -> bool {
        self.drift_ratio().abs() >= SIGNIFICANT_CLOCK_DRIFT
    }
}

/// Busy-weighted CPU clock bracketing one cell's own timed region.
///
/// Distinct from [`ClockDrift`], which brackets the whole sweep with a
/// whole-machine mean and therefore cannot separate a boost-state change from a
/// change in how many cores were occupied: that confusion once produced a
/// published +45.53% "drift" that was occupancy. This averages only the CPUs
/// that ran the cell's work, weighted by how long each was non-idle, so a
/// difference between its endpoints is attributable to clock.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RegionClock {
    /// Weighted MHz at the start of the timed region.
    pub start_mhz: f64,
    /// Weighted MHz at the end, under the same weights.
    pub end_mhz: f64,
    /// Logical CPUs non-idle for at least a tenth of the region.
    pub busy_cpus: u32,
}

impl RegionClock {
    /// Fractional clock change across the region, positive when it rose.
    ///
    /// Zero when the start reading is unusable, which reads as "no claim"
    /// rather than as a clock that did not move.
    #[must_use]
    pub fn drift_ratio(&self) -> f64 {
        if self.start_mhz <= 0.0 {
            return 0.0;
        }
        (self.end_mhz - self.start_mhz) / self.start_mhz
    }

    /// True when this cell's own clock moved enough to bias its throughput.
    #[must_use]
    pub fn is_significant(&self) -> bool {
        self.drift_ratio().abs() >= SIGNIFICANT_CLOCK_DRIFT
    }
}

// ---------------------------------------------------------------------------
// Corpus
// ---------------------------------------------------------------------------

/// Directory names never walked when building a corpus.
const CORPUS_SKIP_DIRS: &[&str] =
    &["target", ".git", "node_modules", ".venv", "bench-venv", "_archive", ".cargo-target"];

/// File extensions admitted into a corpus, in preference order.
const CORPUS_EXTENSIONS: &[&str] = &["md", "rs", "toml", "txt", "py"];

/// What the corpus actually was, recorded so a rerun is checkable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorpusFacts {
    /// Where the bytes came from, as a human description.
    pub origin: String,
    /// Byte length of the assembled corpus.
    pub bytes: usize,
    /// Number of source files concatenated.
    pub files: usize,
    /// Change detector over the exact bytes measured.
    pub digest: u64,
}

/// A corpus of real text, assembled deterministically.
#[derive(Debug, Clone)]
pub struct Corpus {
    /// The text handed to every tokenizer, identical across libraries.
    pub text: String,
    /// Provenance and digest.
    pub facts: CorpusFacts,
}

impl Corpus {
    /// Assemble a corpus of at most `target_bytes` from a source tree.
    ///
    /// Traversal is sorted at every level, files before subdirectories, so
    /// the same tree yields the same bytes on every run. Real text matters:
    /// naively repeated synthetic text compresses far better under BPE and
    /// inflates MB/s, so the report always carries bytes-per-token alongside
    /// throughput.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when `root` yields no admissible
    /// text, rather than silently measuring an empty corpus.
    pub fn from_tree(root: &Path, target_bytes: usize) -> Result<Self, ExatokError> {
        let mut text = String::with_capacity(target_bytes.min(1 << 26));
        let mut files = 0usize;
        Self::walk(root, target_bytes, &mut text, &mut files);
        if text.is_empty() {
            return Err(artifact_err(
                "benchmark corpus",
                &root.display().to_string(),
                "no admissible text files found under the corpus root",
                "pass an explicit corpus file, or point the root at a tree containing .md or .rs files",
            ));
        }
        let bytes = text.len();
        let digest = corpus_digest(text.as_bytes());
        Ok(Self {
            text,
            facts: CorpusFacts {
                origin: format!("deterministic sorted walk of {}", root.display()),
                bytes,
                files,
                digest,
            },
        })
    }

    /// Load a corpus from one explicit file, truncated to `target_bytes`.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when the file cannot be read as
    /// UTF-8 text or is empty.
    pub fn from_file(path: &Path, target_bytes: usize) -> Result<Self, ExatokError> {
        let raw = fs::read_to_string(path).map_err(|e| {
            artifact_err(
                "benchmark corpus",
                &path.display().to_string(),
                &e.to_string(),
                "supply a readable UTF-8 text file",
            )
        })?;
        let text = truncate_at_char_boundary(&raw, target_bytes).to_owned();
        if text.is_empty() {
            return Err(artifact_err(
                "benchmark corpus",
                &path.display().to_string(),
                "corpus file is empty after truncation",
                "supply a non-empty corpus, or raise the byte budget",
            ));
        }
        let bytes = text.len();
        let digest = corpus_digest(text.as_bytes());
        Ok(Self {
            text,
            facts: CorpusFacts {
                origin: format!("explicit file {}", path.display()),
                bytes,
                files: 1,
                digest,
            },
        })
    }

    fn walk(dir: &Path, target: usize, out: &mut String, files: &mut usize) {
        if out.len() >= target {
            return;
        }
        let Ok(entries) = fs::read_dir(dir) else { return };
        let mut dirs: Vec<PathBuf> = Vec::new();
        let mut texts: Vec<PathBuf> = Vec::new();
        for e in entries.flatten() {
            let path = e.path();
            let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue };
            if e.file_type().is_ok_and(|t| t.is_dir()) {
                if !CORPUS_SKIP_DIRS.contains(&name) && !name.starts_with('.') {
                    dirs.push(path);
                }
            } else if path
                .extension()
                .and_then(|x| x.to_str())
                .is_some_and(|x| CORPUS_EXTENSIONS.contains(&x))
            {
                texts.push(path);
            }
        }
        texts.sort();
        dirs.sort();
        for f in texts {
            if out.len() >= target {
                return;
            }
            if let Ok(s) = fs::read_to_string(&f) {
                let room = target - out.len();
                out.push_str(truncate_at_char_boundary(&s, room));
                *files += 1;
            }
        }
        for d in dirs {
            Self::walk(&d, target, out, files);
        }
    }
}

/// Longest prefix of `s` that is at most `max` bytes and ends on a character
/// boundary.
///
/// Slicing a UTF-8 corpus to an exact byte budget otherwise panics mid
/// character, and a corpus that differs by a partial character between runs
/// changes the digest and the token count.
#[must_use]
pub fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

// ---------------------------------------------------------------------------
// Sweep plan
// ---------------------------------------------------------------------------

/// Token counts swept, small to large.
///
/// The crossover regime is the entire argument for a device-resident
/// tokenizer, so the sweep has to straddle it: 256 tokens is smaller than any
/// plausible kernel launch amortization, and 4M tokens is deep into the
/// streaming regime where the host libraries reach steady state.
pub const DEFAULT_TARGET_TOKENS: &[usize] =
    &[256, 1_024, 4_096, 16_384, 65_536, 262_144, 1_048_576, 4_194_304];

/// Documents in one batch cell: enough to fill the byte budget.
///
/// Every batch cell therefore encodes about the same total bytes, so timer
/// resolution and cache footprint are uniform across the sweep and only the
/// document size varies. Mirrored by `batch_documents` in the driver script.
#[must_use]
pub const fn batch_docs(doc_bytes: usize, budget_bytes: usize) -> usize {
    if doc_bytes == 0 {
        return 1;
    }
    let n = budget_bytes.div_ceil(doc_bytes);
    if n == 0 { 1 } else { n }
}

/// Whether a document size leaves at least one document per thread.
///
/// With fewer documents than threads a library cannot use the threads it was
/// given, and the row would claim a width that never ran. Such sizes are
/// reported in the single-document regime instead of being silently mislabeled.
#[must_use]
pub const fn batch_admits(doc_bytes: usize, budget_bytes: usize, threads: usize) -> bool {
    batch_docs(doc_bytes, budget_bytes) >= threads
}

/// How a measurement was driven.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Regime {
    /// One document of the target size, encoded by one thread.
    ///
    /// The latency-bound regime. A single small document cannot be split
    /// across cores by any of these libraries, so this is the honest number
    /// for interactive, one-prompt-at-a-time use.
    SingleDocument,
    /// Many documents of the target size, filling a fixed byte budget.
    ///
    /// The throughput-bound regime, and the only one where thread count means
    /// anything.
    Batch,
}

impl Regime {
    /// Protocol and table spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SingleDocument => "single",
            Self::Batch => "batch",
        }
    }

    /// Parse the protocol spelling.
    #[must_use]
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "single" => Some(Self::SingleDocument),
            "batch" => Some(Self::Batch),
            _ => None,
        }
    }
}

/// One driver invocation: a thread count and the CPUs it may run on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadPlan {
    /// Threads the library is told to use.
    pub threads: usize,
    /// CPUs the process is confined to, or empty for no confinement.
    pub cpus: Vec<usize>,
    /// True when `cpus` holds one CPU per physical core, so no two threads
    /// share a core's execution resources.
    pub pinned_to_physical: bool,
    /// Whether this invocation also runs the single-document regime.
    pub include_single_doc: bool,
}

impl ThreadPlan {
    /// The standard three invocations for a machine.
    ///
    /// One thread pinned to one physical core is the per-core number.
    /// `physical_cores` threads pinned one-per-core is the honest scaling
    /// number. `logical_cores` threads unconfined shows what SMT adds, which
    /// for tokenization is usually far less than the logical count suggests.
    #[must_use]
    pub fn standard(machine: &Machine) -> Vec<Self> {
        let phys = &machine.physical_core_cpus;
        let mut plans = vec![Self {
            threads: 1,
            cpus: phys.first().copied().map(|c| vec![c]).unwrap_or_default(),
            pinned_to_physical: !phys.is_empty(),
            include_single_doc: true,
        }];
        if machine.physical_cores > 1 {
            plans.push(Self {
                threads: machine.physical_cores,
                cpus: phys.clone(),
                pinned_to_physical: true,
                include_single_doc: false,
            });
        }
        if machine.logical_cores > machine.physical_cores {
            plans.push(Self {
                threads: machine.logical_cores,
                cpus: Vec::new(),
                pinned_to_physical: false,
                include_single_doc: false,
            });
        }
        plans
    }

    /// `taskset -c` argument for this plan, or `None` when unconfined.
    #[must_use]
    pub fn cpu_list(&self) -> Option<String> {
        if self.cpus.is_empty() {
            return None;
        }
        let mut s = String::new();
        for (i, c) in self.cpus.iter().enumerate() {
            if i > 0 {
                s.push(',');
            }
            s.push_str(&c.to_string());
        }
        Some(s)
    }
}

// ---------------------------------------------------------------------------
// Statistics
// ---------------------------------------------------------------------------

/// Wall-clock samples for one measured cell.
#[derive(Debug, Clone, PartialEq)]
pub struct RunStats {
    samples: Vec<f64>,
}

impl RunStats {
    /// Build from per-repetition wall times in seconds.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when the sample set is empty or
    /// holds a non-positive or non-finite time. A zero time would divide into
    /// an infinite throughput, which is how a broken timer becomes a
    /// published speedup.
    pub fn new(samples: Vec<f64>) -> Result<Self, ExatokError> {
        if samples.is_empty() {
            return Err(artifact_err(
                "measurement samples",
                "count",
                "no wall-clock samples",
                "raise --reps to at least 1",
            ));
        }
        if let Some(bad) = samples.iter().find(|s| !s.is_finite() || **s <= 0.0) {
            return Err(artifact_err(
                "measurement samples",
                "value",
                &format!("non-positive or non-finite wall time {bad}"),
                "a zero wall time divides into infinite throughput; use a monotonic clock and a larger input",
            ));
        }
        Ok(Self { samples })
    }

    /// Number of repetitions.
    #[must_use]
    pub fn reps(&self) -> usize {
        self.samples.len()
    }

    /// Fastest observed time, the reported figure.
    ///
    /// Minimum rather than mean: every perturbation on a loaded machine adds
    /// time, so the minimum is the closest estimate of the tokenizer's own
    /// cost. The relative spread is reported next to it so a reader can see
    /// how noisy the cell was.
    #[must_use]
    pub fn best(&self) -> f64 {
        self.samples.iter().copied().fold(f64::INFINITY, f64::min)
    }

    /// Arithmetic mean of the samples.
    #[must_use]
    pub fn mean(&self) -> f64 {
        #[allow(clippy::cast_precision_loss)]
        let n = self.samples.len() as f64;
        self.samples.iter().sum::<f64>() / n
    }

    /// Median sample, upper of the two middles for an even count.
    #[must_use]
    pub fn median(&self) -> f64 {
        let mut v = self.samples.clone();
        v.sort_by(f64::total_cmp);
        v[v.len() / 2]
    }

    /// Sample standard deviation divided by the mean, or 0 for one sample.
    #[must_use]
    pub fn rel_stddev(&self) -> f64 {
        if self.samples.len() < 2 {
            return 0.0;
        }
        let mean = self.mean();
        if mean <= 0.0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let n1 = (self.samples.len() - 1) as f64;
        let var = self.samples.iter().map(|s| (s - mean) * (s - mean)).sum::<f64>() / n1;
        var.sqrt() / mean
    }

    /// The raw samples, for the JSON record.
    #[must_use]
    pub fn samples(&self) -> &[f64] {
        &self.samples
    }
}

// ---------------------------------------------------------------------------
// Measurement
// ---------------------------------------------------------------------------

/// Machine facts stamped onto each measurement by the harness, not the driver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MachineContext {
    /// Physical cores on the host.
    pub physical_cores: usize,
    /// Logical CPUs on the host.
    pub logical_cores: usize,
    /// Whether this invocation was confined one thread per physical core.
    pub pinned_to_physical: bool,
}

/// Execution time attributable to the tokenizer, separate from wall time.
///
/// vyre's benchmark doctrine requires active backend execution to be recorded
/// separately from wall time, and device time to be used when the backend
/// exposes one. A host CPU baseline has no device timeline, so `device_secs`
/// is `None` there and the honest active measure is CPU-seconds summed across
/// threads: dividing it by wall time recovers the parallelism the run actually
/// achieved, which is the only way to tell a real 32-thread run from a
/// 32-thread run that ran on one thread.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ActiveTime {
    /// CPU-seconds across every thread during the timed region.
    pub cpu_secs: f64,
    /// Backend-reported device execution seconds, when the backend exposes a
    /// device timeline. `None` for host CPU baselines, which have none.
    pub device_secs: Option<f64>,
}

/// One measured cell: a tokenizer, an input size, a regime, a thread count.
#[derive(Debug, Clone, PartialEq)]
pub struct Measurement {
    /// Library name, for example `tiktoken`.
    pub tokenizer: String,
    /// Exact version of the library under test.
    pub version: String,
    /// Vocabulary identity, so rows are only compared within one vocabulary.
    pub vocab: String,
    /// How the measurement was driven.
    pub regime: Regime,
    /// Requested token count per document.
    pub target_tokens: usize,
    /// Actual bytes per document.
    pub doc_bytes: usize,
    /// Documents encoded per repetition.
    pub docs: usize,
    /// Total input bytes per repetition.
    pub input_bytes: u64,
    /// Total tokens produced per repetition.
    pub tokens: u64,
    /// Wall-clock samples.
    pub stats: RunStats,
    /// Untimed warmup repetitions run before sampling.
    pub warmups: u32,
    /// Threads the library was told to use.
    pub threads: usize,
    /// Machine facts.
    pub machine: MachineContext,
    /// Mean CPU MHz observed while this cell ran.
    pub mean_mhz: f64,
    /// Busy-weighted clock across this cell's own timed region, when the driver
    /// could sample it. `None` means the per-CPU probes were unavailable, which
    /// is not the same as a clock that held steady.
    pub region_clock: Option<RegionClock>,
    /// Whether this library's ids matched the reference implementation's on a
    /// fixed corpus sample.
    ///
    /// Throughput across libraries that disagree on ids is not a comparison,
    /// it is two different computations. Recorded per row so the table can say
    /// so instead of leaving the reader to assume vocabulary equivalence.
    pub matches_reference: bool,
    /// Active execution time for the timed region, separate from wall time.
    pub active: ActiveTime,
    /// CPU-seconds everything else on the machine consumed during this cell's
    /// timed region.
    ///
    /// Sampled from `/proc/stat` around the region with this process's own CPU
    /// time subtracted. Required rather than optional: a cell that cannot say
    /// what else was running cannot claim it measured an idle machine.
    pub foreign_cpu_secs: f64,
    /// Times the unit was repeated inside one timed region.
    ///
    /// A 1 KB document encodes in tens of microseconds, close enough to timer
    /// noise that a bare measurement is mostly clock overhead. The unit is
    /// therefore repeated until the timed region clears a floor, and the count
    /// is recorded rather than folded into `input_bytes`: keeping them separate
    /// means `input_bytes` stays the reproducible size of the actual input
    /// while the timed region may legitimately differ between machines.
    pub inner_reps: u32,
}

impl Measurement {
    /// Bytes encoded inside one timed region: the unit input times the
    /// repetition count folded into it.
    #[must_use]
    pub fn timed_bytes(&self) -> u64 {
        self.input_bytes.saturating_mul(u64::from(self.inner_reps))
    }

    /// Tokens produced inside one timed region.
    #[must_use]
    pub fn timed_tokens(&self) -> u64 {
        self.tokens.saturating_mul(u64::from(self.inner_reps))
    }

    /// Absolute bytes per second.
    #[must_use]
    pub fn bytes_per_second(&self) -> f64 {
        let t = self.stats.best();
        if t <= 0.0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let b = self.timed_bytes() as f64;
        b / t
    }

    /// Absolute MB/s, SI megabytes.
    #[must_use]
    pub fn mb_per_second(&self) -> f64 {
        self.bytes_per_second() / BYTES_PER_MB
    }

    /// Absolute GB/s, SI gigabytes.
    #[must_use]
    pub fn gb_per_second(&self) -> f64 {
        self.bytes_per_second() / BYTES_PER_GB
    }

    /// MB/s divided by the thread count that produced it.
    ///
    /// Reported beside the absolute figure on every row. Without it, a
    /// 144-core result and a 16-core result look like different algorithms
    /// when they are the same algorithm on different machines.
    #[must_use]
    pub fn mb_per_second_per_thread(&self) -> f64 {
        if self.threads == 0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let t = self.threads as f64;
        self.mb_per_second() / t
    }

    /// MB/s divided by the physical cores that could have done the work.
    ///
    /// `min(threads, physical_cores)`, so an SMT-oversubscribed cell is
    /// credited to the 16 cores that exist rather than the 32 threads
    /// requested. Dividing by threads instead makes correct SMT scaling look
    /// like a halving of efficiency, which is the arithmetic of
    /// oversubscription and not a property of the tokenizer.
    #[must_use]
    pub fn mb_per_second_per_core(&self) -> f64 {
        let cores = self.threads.min(self.machine.physical_cores);
        if cores == 0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let c = cores as f64;
        self.mb_per_second() / c
    }

    /// Tokens emitted per second.
    #[must_use]
    pub fn tokens_per_second(&self) -> f64 {
        let t = self.stats.best();
        if t <= 0.0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let n = self.timed_tokens() as f64;
        n / t
    }

    /// Nanoseconds of wall time per token produced.
    #[must_use]
    pub fn ns_per_token(&self) -> f64 {
        let tps = self.tokens_per_second();
        if tps <= 0.0 {
            return 0.0;
        }
        1e9 / tps
    }

    /// Input bytes per token, the corpus compression control.
    ///
    /// MB/s scales directly with this, so two runs at different
    /// bytes-per-token are not comparable even on identical hardware. A
    /// naively repeated synthetic corpus reaches well over 5 where real prose
    /// sits near 3.9, which alone inflates MB/s by about a third.
    #[must_use]
    pub fn bytes_per_token(&self) -> f64 {
        if self.tokens == 0 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let (b, t) = (self.input_bytes as f64, self.tokens as f64);
        b / t
    }

    /// Active execution seconds: device time when the backend exposes one,
    /// otherwise CPU-seconds summed across threads.
    ///
    /// Reported next to wall time rather than instead of it. A device kernel
    /// that runs in 2 ms inside a 40 ms wall window is a transfer-bound
    /// pipeline, and only the pair of numbers says so.
    #[must_use]
    pub fn active_secs(&self) -> f64 {
        self.active.device_secs.unwrap_or(self.active.cpu_secs)
    }

    /// CPU-seconds divided by wall seconds: the parallelism actually achieved.
    ///
    /// A row claiming 32 threads that returns 1.0 here ran on one thread. This
    /// is the check that a pinned thread count was honoured by the library
    /// rather than merely requested of it.
    #[must_use]
    pub fn achieved_parallelism(&self) -> f64 {
        let wall = self.stats.best();
        if wall <= 0.0 {
            return 0.0;
        }
        self.active.cpu_secs / wall
    }

    /// Foreign CPU-seconds per wall second: competing load as a fraction of
    /// one core.
    ///
    /// Independent of [`Self::achieved_parallelism`], which only sees load that
    /// displaced this process from its own CPU. Contention that runs beside it
    /// rather than on top of it leaves that ratio at 1.0 and appears only here.
    #[must_use]
    pub fn foreign_load_ratio(&self) -> f64 {
        let wall = self.stats.best();
        if wall <= 0.0 {
            return 0.0;
        }
        self.foreign_cpu_secs / wall
    }

    /// Fraction of wall time the backend's device timeline was busy, when the
    /// backend exposes one.
    #[must_use]
    pub fn device_utilization(&self) -> Option<f64> {
        let wall = self.stats.best();
        if wall <= 0.0 {
            return None;
        }
        self.active.device_secs.map(|d| d / wall)
    }
}

/// Whether a baseline produced a number, and if not, exactly why.
///
/// A baseline that could not run is recorded with its reason. It is never
/// estimated, extrapolated, or carried over from a paper, because a
/// fabricated row is indistinguishable from a measured one once it is in a
/// table.
#[derive(Debug, Clone, PartialEq)]
pub enum Availability {
    /// The baseline ran and produced this cell.
    Measured(Measurement),
    /// The baseline did not run.
    Unavailable {
        /// Library name.
        tokenizer: String,
        /// Specific, actionable reason.
        reason: String,
    },
}

// ---------------------------------------------------------------------------
// Plausibility
// ---------------------------------------------------------------------------

/// Verdict on whether a measurement measured tokenization.
///
/// Ordered by severity of what it says about the harness. Four variants mean
/// the harness measured the wrong thing: [`Self::ShortTimedRegion`],
/// [`Self::ThreadsNotHonoured`], [`Self::Contended`] and
/// [`Self::ForeignLoad`]. A run containing any of them has not measured what
/// it claims and must not be published.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Plausibility {
    /// Above the floor, timed long enough, threads delivered.
    Plausible,
    /// Input too small for dispatch overhead to amortize, so the floor does
    /// not apply and the low figure is a real property of the regime.
    PerCallBound,
    /// The timed region was too short for its throughput to mean anything.
    ///
    /// A harness bug, not a result: the fix is more inner repetitions or a
    /// larger byte budget, never a relaxed threshold.
    ShortTimedRegion {
        /// Fastest repetition's wall seconds.
        timed_secs: f64,
        /// The minimum it needed to clear.
        minimum_secs: f64,
    },
    /// Fewer threads did the work than the cell requested.
    ///
    /// A harness bug: the thread count in the table is a claim about how the
    /// work ran, and this says the claim is false.
    ThreadsNotHonoured {
        /// Threads the cell asked for.
        requested: usize,
        /// CPU-seconds divided by wall seconds, so the count actually used.
        achieved_parallelism: f64,
    },
    /// A single-threaded pinned cell that did not get its core to itself.
    ///
    /// A harness bug in the run conditions rather than the code: the number is
    /// depressed by whatever else was on that CPU. Fixing it means measuring on
    /// an idle machine, never accepting the low figure.
    Contended {
        /// CPU-seconds divided by wall seconds. Below 1.0 means descheduled.
        achieved_parallelism: f64,
        /// The efficiency a pinned single-threaded cell must reach.
        minimum_efficiency: f64,
    },
    /// Another process was consuming CPU somewhere on the machine while this
    /// cell ran.
    ///
    /// Not a slow run, a non-run: the figure is depressed by load this harness
    /// did not control, so publishing it understates the baseline. Distinct
    /// from [`Self::Contended`], which only fires when the competing work
    /// landed on this cell's own pinned CPU.
    ForeignLoad {
        /// Foreign CPU-seconds per wall second, as a fraction of one core.
        foreign_load_ratio: f64,
        /// The most this gate tolerates.
        maximum_ratio: f64,
    },
    /// Repetitions of the same cell disagreed enough that the published figure
    /// depends on which one was chosen.
    ///
    /// Not a slow run and not a fast one, an unrepeatable one. Distinct from
    /// both contention gates, which read CPU counters and stay clean when
    /// bursty load merely widens the spread.
    EstimatorDependent {
        /// Relative standard deviation across this cell's repetitions.
        rel_stddev: f64,
        /// The most this gate tolerates.
        maximum_rel_stddev: f64,
    },
    /// A cell with a device timeline whose device sat idle for most of the
    /// wall window.
    ///
    /// The device-side counterpart to [`Self::ForeignLoad`], and it fires
    /// exactly where every CPU gate is blind: another process's kernels
    /// inflate this cell's wall time while its own device time is unchanged.
    DeviceStarved {
        /// Device-busy seconds per wall second.
        device_utilization: f64,
        /// The least this gate accepts.
        minimum_utilization: f64,
    },
    /// Below the floor for a reason established by experiment and recorded in
    /// [`KNOWN_SLOW_BASELINES`]. Reported with its number and its reason.
    KnownSlowLibrary {
        /// What was observed, per physical core.
        observed_mb_s_per_core: f64,
        /// Why this library is legitimately this slow.
        reason: &'static str,
    },
    /// Below the floor with no recorded explanation. Investigate before
    /// publishing: either the harness mismeasured or the library belongs in
    /// [`KNOWN_SLOW_BASELINES`] with evidence.
    SuspectedMeasurementDefect {
        /// What was observed, per physical core.
        observed_mb_s_per_core: f64,
        /// The floor it fell under.
        floor_mb_s_per_core: f64,
    },
}

impl Plausibility {
    /// Whether this verdict means the harness measured the wrong thing.
    ///
    /// True only for the variants that are unambiguously harness bugs. A floor
    /// trip is deliberately excluded: a slow library is a result, and
    /// conflating the two is what made the first version of this guard fire on
    /// 25 cells that included correct SMT scaling.
    #[must_use]
    pub const fn is_harness_defect(self) -> bool {
        matches!(
            self,
            Self::ShortTimedRegion { .. }
                | Self::ThreadsNotHonoured { .. }
                | Self::Contended { .. }
                | Self::ForeignLoad { .. }
                | Self::EstimatorDependent { .. }
                | Self::DeviceStarved { .. }
        )
    }

    /// Whether the cell is fit to publish as a throughput number.
    #[must_use]
    pub const fn is_publishable(self) -> bool {
        !self.is_harness_defect()
    }

    /// Marker appended to this cell's row in the rendered table.
    ///
    /// One of the only two exhaustive matches on this enum, deliberately. This
    /// variant set broke the build four times in one wave because the renderer
    /// and the notes each matched it and a new variant had to be chased across
    /// both. Adding a variant now produces exactly one compile error, here,
    /// which is a guarantee rather than something to remember.
    #[must_use]
    pub const fn table_flag(self) -> &'static str {
        match self {
            Self::ShortTimedRegion { .. } => " <-- HARNESS: TIMED REGION TOO SHORT",
            Self::ThreadsNotHonoured { .. } => " <-- HARNESS: THREADS NOT DELIVERED",
            Self::Contended { .. } => " <-- HARNESS: CORE NOT EXCLUSIVE",
            Self::ForeignLoad { .. } => " <-- HARNESS: MACHINE NOT EXCLUSIVE",
            Self::EstimatorDependent { .. } => " <-- HARNESS: REPETITIONS DISAGREE",
            Self::DeviceStarved { .. } => " <-- HARNESS: DEVICE NOT EXCLUSIVE",
            Self::SuspectedMeasurementDefect { .. } => " <-- UNEXPLAINED, UNDER FLOOR",
            Self::KnownSlowLibrary { .. } => " <-- known slow, see note",
            Self::PerCallBound | Self::Plausible => "",
        }
    }

    /// Why this cell is flagged, with the numbers that flagged it.
    ///
    /// The second and last exhaustive match. Returns `None` for verdicts that
    /// need no explanation. Never a wildcard arm: a wildcard is what let the
    /// contended case render as "unclassified" instead of failing to compile.
    #[must_use]
    pub fn diagnosis(self) -> Option<String> {
        match self {
            Self::ShortTimedRegion { timed_secs, minimum_secs } => Some(format!(
                "timed region {timed_secs:.4} s is under the {minimum_secs:.2} s minimum; \
                 raise inner repetitions or the byte budget"
            )),
            Self::ThreadsNotHonoured { requested, achieved_parallelism } => Some(format!(
                "requested {requested} threads but achieved {achieved_parallelism:.2}x \
                 parallelism; the thread request was not delivered"
            )),
            Self::Contended { achieved_parallelism, minimum_efficiency } => Some(format!(
                "pinned single-threaded cell achieved only {achieved_parallelism:.3}x of one \
                 core against a {minimum_efficiency:.2} minimum; another process was on that \
                 CPU, so this figure understates the baseline"
            )),
            Self::ForeignLoad { foreign_load_ratio, maximum_ratio } => Some(format!(
                "{foreign_load_ratio:.3}x of one core was consumed elsewhere on the machine \
                 against a {maximum_ratio:.2} maximum; this cell measured a contended machine \
                 and understates the baseline"
            )),
            Self::EstimatorDependent { rel_stddev, maximum_rel_stddev } => Some(format!(
                "repetitions spread {:.1}% against a {:.0}% maximum; the headline figure is \
                 whichever repetition was picked rather than a property of the tokenizer",
                rel_stddev * 100.0,
                maximum_rel_stddev * 100.0
            )),
            Self::DeviceStarved { device_utilization, minimum_utilization } => Some(format!(
                "the device was busy for only {:.1}% of the wall window against a {:.0}% \
                 minimum; this cell measured queueing or host stalls rather than device \
                 throughput",
                device_utilization * 100.0,
                minimum_utilization * 100.0
            )),
            Self::SuspectedMeasurementDefect { observed_mb_s_per_core, floor_mb_s_per_core } => {
                Some(format!(
                    "{observed_mb_s_per_core:.3} MB/s/core is under the \
                     {floor_mb_s_per_core:.1} MB/s/core floor with no recorded explanation"
                ))
            }
            Self::KnownSlowLibrary { observed_mb_s_per_core, reason } => Some(format!(
                "{observed_mb_s_per_core:.3} MB/s/core, legitimately: {reason}"
            )),
            Self::PerCallBound | Self::Plausible => None,
        }
    }
}

/// Classify a measurement.
///
/// Checks run most-invalidating first. A region too short to time makes every
/// other number derived from it meaningless, including the parallelism ratio,
/// so it is checked before anything else.
#[must_use]
pub fn assess_plausibility(m: &Measurement) -> Plausibility {
    let timed = m.stats.best();
    if timed < MIN_TRUSTWORTHY_TIMED_SECS {
        return Plausibility::ShortTimedRegion {
            timed_secs: timed,
            minimum_secs: MIN_TRUSTWORTHY_TIMED_SECS,
        };
    }
    // Before the thread gates, deliberately. Foreign load also depresses
    // achieved parallelism, so checking threads first reports a starved cell as
    // a thread-delivery bug. Eight 16-thread cells were published with exactly
    // that wrong cause, and a wrong cause is worse than an open one.
    let foreign = m.foreign_load_ratio();
    if foreign > MAX_FOREIGN_LOAD_RATIO {
        return Plausibility::ForeignLoad {
            foreign_load_ratio: foreign,
            maximum_ratio: MAX_FOREIGN_LOAD_RATIO,
        };
    }
    // Device-side exclusivity, checked here because every gate below is
    // CPU-side and a contended device cell has an idle CPU. Foreign load is
    // checked first only because it is the cheaper and more common cause.
    if let Some(utilization) = m.device_utilization() {
        if utilization < MIN_DEVICE_UTILIZATION {
            return Plausibility::DeviceStarved {
                device_utilization: utilization,
                minimum_utilization: MIN_DEVICE_UTILIZATION,
            };
        }
    }
    // Only checkable when the request fits in physical cores: 32 threads on 16
    // cores cannot reach 32x and is not expected to.
    if m.threads > 1 && m.threads <= m.machine.physical_cores {
        let achieved = m.achieved_parallelism();
        #[allow(clippy::cast_precision_loss)]
        let floor = m.threads as f64 * MIN_PARALLEL_EFFICIENCY;
        if achieved < floor {
            return Plausibility::ThreadsNotHonoured {
                requested: m.threads,
                achieved_parallelism: achieved,
            };
        }
    }
    // A pinned single-threaded cell must get its whole core. Checked separately
    // from the multi-thread case because the tolerable loss is far smaller:
    // half of 16 threads can be a real scaling limit, half of one pinned core
    // is always another process.
    if m.threads == 1 {
        let achieved = m.achieved_parallelism();
        if achieved < MIN_SINGLE_THREAD_EFFICIENCY {
            return Plausibility::Contended {
                achieved_parallelism: achieved,
                minimum_efficiency: MIN_SINGLE_THREAD_EFFICIENCY,
            };
        }
    }
    // Before the per-call-bound return, deliberately: a small-document cell is
    // exempt from the throughput floor but not from having to be repeatable.
    let spread = m.stats.rel_stddev();
    if spread > MAX_PUBLISHABLE_REL_STDDEV {
        return Plausibility::EstimatorDependent {
            rel_stddev: spread,
            maximum_rel_stddev: MAX_PUBLISHABLE_REL_STDDEV,
        };
    }
    if m.doc_bytes < AMORTIZED_DOC_BYTES {
        return Plausibility::PerCallBound;
    }
    let per_core = m.mb_per_second_per_core();
    if per_core < PLAUSIBLE_FLOOR_MB_S_PER_CORE {
        return match known_slow_reason(&m.tokenizer) {
            Some(reason) => {
                Plausibility::KnownSlowLibrary { observed_mb_s_per_core: per_core, reason }
            }
            None => Plausibility::SuspectedMeasurementDefect {
                observed_mb_s_per_core: per_core,
                floor_mb_s_per_core: PLAUSIBLE_FLOOR_MB_S_PER_CORE,
            },
        };
    }
    Plausibility::Plausible
}

// ---------------------------------------------------------------------------
// Driver protocol
// ---------------------------------------------------------------------------

/// One line of driver output.
#[derive(Debug, Clone, PartialEq)]
pub enum DriverEvent {
    /// A completed measurement.
    Record(Measurement),
    /// A baseline that could not run, with its reason.
    Unavailable {
        /// Library name.
        tokenizer: String,
        /// Specific reason.
        reason: String,
    },
    /// Measured bytes per token for the corpus under one vocabulary, used to
    /// size documents so a "256 token" cell really holds about 256 tokens.
    Calibration {
        /// Vocabulary identity.
        vocab: String,
        /// Corpus bytes per token.
        bytes_per_token: f64,
    },
}

fn field<'a>(
    fields: &BTreeMap<&'a str, &'a str>,
    key: &str,
    location: &str,
) -> Result<&'a str, ExatokError> {
    fields.get(key).copied().ok_or_else(|| {
        artifact_err(
            "driver record stream",
            location,
            &format!("missing field `{key}`"),
            "the driver and bench_support disagree on the record protocol; update both together",
        )
    })
}

fn num<T: std::str::FromStr>(
    fields: &BTreeMap<&str, &str>,
    key: &str,
    location: &str,
) -> Result<T, ExatokError> {
    let raw = field(fields, key, location)?;
    raw.parse().map_err(|_| {
        artifact_err(
            "driver record stream",
            location,
            &format!("field `{key}` is not a number: {raw:?}"),
            "emit plain decimal values with no thousands separators or units",
        )
    })
}

/// Parse one tab-separated driver line.
///
/// Format is a leading kind token then `key=value` fields, tab separated.
/// Lines that are blank or do not start with a known kind yield `None` so the
/// driver may print human notes on stdout without breaking the protocol.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] when a known kind is missing a required
/// field or carries an unparseable number. A silently dropped malformed
/// record would show up as a missing table row, which reads as "did not run"
/// rather than "harness bug".
pub fn parse_driver_line(
    line: &str,
    machine: MachineContext,
    line_no: usize,
) -> Result<Option<DriverEvent>, ExatokError> {
    let line = line.trim_end_matches(['\r', '\n']);
    let mut parts = line.split('\t');
    let Some(kind) = parts.next() else { return Ok(None) };
    if !matches!(kind, "record" | "unavailable" | "calibration") {
        return Ok(None);
    }
    let location = format!("line {line_no}");
    let mut fields: BTreeMap<&str, &str> = BTreeMap::new();
    for p in parts {
        if let Some((k, v)) = p.split_once('=') {
            fields.insert(k, v);
        }
    }
    match kind {
        "unavailable" => Ok(Some(DriverEvent::Unavailable {
            tokenizer: field(&fields, "tokenizer", &location)?.to_owned(),
            reason: field(&fields, "reason", &location)?.to_owned(),
        })),
        "calibration" => Ok(Some(DriverEvent::Calibration {
            vocab: field(&fields, "vocab", &location)?.to_owned(),
            bytes_per_token: num(&fields, "bytes_per_token", &location)?,
        })),
        _ => {
            let regime_raw = field(&fields, "regime", &location)?;
            let regime = Regime::from_str_opt(regime_raw).ok_or_else(|| {
                artifact_err(
                    "driver record stream",
                    &location,
                    &format!("unknown regime {regime_raw:?}"),
                    "regime must be `single` or `batch`",
                )
            })?;
            let samples_raw = field(&fields, "samples", &location)?;
            let mut samples = Vec::new();
            for s in samples_raw.split(',').filter(|s| !s.is_empty()) {
                samples.push(s.parse::<f64>().map_err(|_| {
                    artifact_err(
                        "driver record stream",
                        &location,
                        &format!("sample {s:?} is not a number"),
                        "emit comma-separated decimal seconds",
                    )
                })?);
            }
            Ok(Some(DriverEvent::Record(Measurement {
                tokenizer: field(&fields, "tokenizer", &location)?.to_owned(),
                version: field(&fields, "version", &location)?.to_owned(),
                vocab: field(&fields, "vocab", &location)?.to_owned(),
                regime,
                target_tokens: num(&fields, "target_tokens", &location)?,
                doc_bytes: num(&fields, "doc_bytes", &location)?,
                docs: num(&fields, "docs", &location)?,
                input_bytes: num(&fields, "input_bytes", &location)?,
                tokens: num(&fields, "tokens", &location)?,
                stats: RunStats::new(samples)?,
                warmups: num(&fields, "warmups", &location)?,
                threads: num(&fields, "threads", &location)?,
                machine,
                mean_mhz: num(&fields, "mean_mhz", &location)?,
                region_clock: match (
                    fields.get("busy_mhz_start"),
                    fields.get("busy_mhz_end"),
                    fields.get("busy_cpus"),
                ) {
                    (Some(_), Some(_), Some(_)) => Some(RegionClock {
                        start_mhz: num(&fields, "busy_mhz_start", &location)?,
                        end_mhz: num(&fields, "busy_mhz_end", &location)?,
                        busy_cpus: num(&fields, "busy_cpus", &location)?,
                    }),
                    _ => None,
                },
                matches_reference: field(&fields, "matches_ref", &location)? != "0",
                active: ActiveTime {
                    cpu_secs: num(&fields, "cpu_secs", &location)?,
                    device_secs: match fields.get("device_secs") {
                        Some(_) => Some(num(&fields, "device_secs", &location)?),
                        None => None,
                    },
                },
                foreign_cpu_secs: num(&fields, "foreign_cpu_secs", &location)?,
                inner_reps: num(&fields, "inner_reps", &location)?,
            })))
        }
    }
}

// ---------------------------------------------------------------------------
// Report
// ---------------------------------------------------------------------------

/// How a reported figure was obtained.
///
/// Tonight this project shipped five numbers that read as measured and were
/// not: a test pinning 174,080, a doc comment asserting occupancy intent for a
/// heuristic with no occupancy term, a synthetic device profile named after this
/// GPU whose fields overstate it by a third, an unqualified test count of 272,
/// and a per-crate API gate reporting byte-stable for a crate it does not
/// inspect. Every one was a figure whose ORIGIN was lost, not a figure that was
/// wrong when taken. Recording the origin next to the value is the only fix that
/// survives the value being copied somewhere else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Provenance {
    /// Observed on this machine, this run, by measurement or by reading a
    /// kernel interface. The only kind that may be quoted as a measurement.
    Probed,
    /// Computed from probed values. Honest, but no better than its inputs, and
    /// it moves when they do.
    Derived,
    /// A hand-written constant: a test fixture, a synthetic device profile, or a
    /// documented reference figure from someone else's paper. NEVER a
    /// measurement of this machine, however plausible the magnitude.
    Fixture,
}

impl Provenance {
    /// Lowercase tag used in reports and JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Probed => "probed",
            Self::Derived => "derived",
            Self::Fixture => "fixture",
        }
    }

    /// Whether a figure with this origin may be quoted as measured.
    #[must_use]
    pub const fn is_quotable_as_measured(self) -> bool {
        matches!(self, Self::Probed)
    }
}

/// Cargo features compiled into THIS binary.
///
/// A test count or a throughput figure without its feature set is not a
/// measurement: `cargo test -p exatok --lib` reports 255 on default features
/// and 286 with `confluence`, because 31 unit tests live behind that flag. The
/// two figures are both correct and are not comparable, and the 272 that circled
/// this project for an hour was a third feature set nobody recorded. Probed from
/// `cfg!`, so it cannot drift from the binary that produced the numbers.
#[must_use]
pub fn compiled_features() -> Vec<&'static str> {
    let mut out = Vec::new();
    if cfg!(feature = "confluence") {
        out.push("confluence");
    }
    if cfg!(feature = "cuda") {
        out.push("cuda");
    }
    if cfg!(feature = "gpu-pretokenize") {
        out.push("gpu-pretokenize");
    }
    if cfg!(feature = "multi-merge") {
        out.push("multi-merge");
    }
    out
}

/// A test count that cannot be written down without its feature set.
///
/// Exists because the bare number is the whole defect: 255, 272 and 286 were all
/// true of this crate within one hour, and comparing any two of them as though
/// they described the same build read a benign packaging change as a 17-test
/// regression and cost an agent real time chasing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestCount {
    /// Tests that passed.
    pub passed: u32,
    /// Tests skipped with `#[ignore]`.
    pub ignored: u32,
    /// Features the counted binary was built with, empty meaning default.
    pub features: Vec<String>,
}

impl TestCount {
    /// Count for the current binary, features probed from `cfg!`.
    #[must_use]
    pub fn here(passed: u32, ignored: u32) -> Self {
        Self {
            passed,
            ignored,
            features: compiled_features().into_iter().map(str::to_owned).collect(),
        }
    }

    /// The count with its feature set attached, never the bare number.
    #[must_use]
    pub fn render(&self) -> String {
        let features =
            if self.features.is_empty() { "default".to_owned() } else { self.features.join(",") };
        format!("{} passed / {} ignored (features: {features})", self.passed, self.ignored, )
    }

    /// Whether two counts describe the same build and may be compared.
    ///
    /// Feature sets differing means the counts are not comparable, whatever the
    /// numbers say. This is the check whose absence produced the 272 confusion.
    #[must_use]
    pub fn comparable_to(&self, other: &Self) -> bool {
        self.features == other.features
    }
}

/// A complete sweep result.
#[derive(Debug, Clone)]
pub struct Report {
    /// Machine the sweep ran on.
    pub machine: Machine,
    /// Corpus provenance and digest.
    pub corpus: CorpusFacts,
    /// Vocabulary all rows share.
    pub vocab: String,
    /// Measured cells and unavailable baselines.
    pub rows: Vec<Availability>,
    /// Clock behaviour across the sweep, when the kernel reported clocks.
    pub clock: Option<ClockDrift>,
    /// Measured corpus bytes per token, per vocabulary.
    pub bytes_per_token: Option<f64>,
    /// Where [`Report::persist`] wrote this report, when it was persisted.
    /// Reported so a caller can name the evidence file it just produced.
    pub report_path: Option<PathBuf>,
}

impl Report {
    /// Measured cells only.
    #[must_use]
    pub fn measured(&self) -> impl Iterator<Item = &Measurement> {
        self.rows.iter().filter_map(|r| match r {
            Availability::Measured(m) => Some(m),
            Availability::Unavailable { .. } => None,
        })
    }

    /// Every cell whose figure the plausibility floor rejects.
    #[must_use]
    pub fn suspected_defects(&self) -> Vec<&Measurement> {
        self.measured()
            .filter(|m| {
                matches!(assess_plausibility(m), Plausibility::SuspectedMeasurementDefect { .. })
            })
            .collect()
    }

    /// Every cell the harness itself measured wrongly.
    ///
    /// Distinct from [`Self::suspected_defects`]: these are cells whose timed
    /// region was too short or whose thread request was not delivered, so the
    /// number is invalid regardless of which library produced it. A run with
    /// any of these has not measured what the table claims.
    #[must_use]
    pub fn harness_defects(&self) -> Vec<&Measurement> {
        self.measured().filter(|m| assess_plausibility(m).is_harness_defect()).collect()
    }

    /// Cells below the floor for a reason recorded in
    /// [`KNOWN_SLOW_BASELINES`], reported with that reason.
    #[must_use]
    pub fn known_slow(&self) -> Vec<&Measurement> {
        self.measured()
            .filter(|m| matches!(assess_plausibility(m), Plausibility::KnownSlowLibrary { .. }))
            .collect()
    }

    /// Measured cells whose library disagreed with the reference on ids.
    ///
    /// A throughput comparison across libraries that emit different ids is not
    /// a comparison. These rows are still reported, because hiding them would
    /// be worse, but they are called out rather than read as equivalent.
    #[must_use]
    pub fn disagreeing(&self) -> Vec<&Measurement> {
        self.measured().filter(|m| !m.matches_reference).collect()
    }

    /// Fastest measured cell for one tokenizer, by absolute MB/s.
    #[must_use]
    pub fn peak_for(&self, tokenizer: &str) -> Option<&Measurement> {
        self.measured()
            .filter(|m| m.tokenizer == tokenizer)
            .max_by(|a, b| a.mb_per_second().total_cmp(&b.mb_per_second()))
    }

    /// Human table with absolute figures. No ratios.
    #[must_use]
    pub fn render_table(&self) -> String {
        let mut out = String::new();
        out.push_str(&self.render_header());
        out.push_str(
            "\n== absolute throughput (no ratios; divide two rows yourself if you want one) ==\n\n",
        );
        out.push_str(&format!(
            "{:<13} {:<7} {:>4} {:>10} {:>7} {:>9} {:>7} {:>10} {:>6} {:>11} {:>8} {:>10} {:>12} {:>8} {:>7} {:>5} {:>6}\n",
            "tokenizer",
            "regime",
            "thr",
            "doc_bytes",
            "docs",
            "unit_MB",
            "xreps",
            "tokens",
            "B/tok",
            "MB/s",
            "GB/s",
            "MB/s/core",
            "MB/s/thread",
            "ns/tok",
            "relsd%",
            "exact",
            "par",
        ));
        out.push_str(&"-".repeat(162));
        out.push('\n');
        let mut rows: Vec<&Measurement> = self.measured().collect();
        rows.sort_by(|a, b| {
            a.tokenizer
                .cmp(&b.tokenizer)
                .then(a.regime.as_str().cmp(b.regime.as_str()))
                .then(a.threads.cmp(&b.threads))
                .then(a.target_tokens.cmp(&b.target_tokens))
        });
        for m in rows {
            #[allow(clippy::cast_precision_loss)]
            let unit_mb = m.input_bytes as f64 / BYTES_PER_MB;
            let flag = assess_plausibility(m).table_flag();
            out.push_str(&format!(
                "{:<13} {:<7} {:>4} {:>10} {:>7} {:>9.4} {:>7} {:>10} {:>6.3} {:>11.2} {:>8.3} {:>10.2} {:>12.2} {:>8.1} {:>7.2} {:>5} {:>6.2}{}\n",
                m.tokenizer,
                m.regime.as_str(),
                m.threads,
                m.doc_bytes,
                m.docs,
                unit_mb,
                m.inner_reps,
                m.tokens,
                m.bytes_per_token(),
                m.mb_per_second(),
                m.gb_per_second(),
                m.mb_per_second_per_core(),
                m.mb_per_second_per_thread(),
                m.ns_per_token(),
                m.stats.rel_stddev() * 100.0,
                if m.matches_reference { "yes" } else { "NO" },
                m.achieved_parallelism(),
                flag,
            ));
        }
        out.push_str(&self.render_versions());
        out.push_str(&self.render_unavailable());
        out.push_str(&self.render_notes());
        out
    }

    fn render_header(&self) -> String {
        let mut s = String::from("== machine ==\n");
        let features = compiled_features();
        s.push_str(&format!(
            "features          : {}\n",
            if features.is_empty() { "default".to_owned() } else { features.join(",") }
        ));
        s.push_str(&format!("cpu               : {}\n", self.machine.cpu_model));
        s.push_str(&format!(
            "cores             : {} physical / {} logical ({} SMT siblings per core)\n",
            self.machine.physical_cores,
            self.machine.logical_cores,
            self.machine.smt_siblings_per_core(),
        ));
        s.push_str(&format!(
            "governor          : {}\n",
            self.machine.governor.as_deref().unwrap_or("unknown (no cpufreq)"),
        ));
        s.push_str(&format!(
            "memory            : {} KiB\n",
            self.machine.total_memory_kib
        ));
        match &self.machine.gpu {
            Some(g) => s.push_str(&format!(
                "gpu               : {} ({} MiB, driver {}, compute {})\n",
                g.name, g.memory_mib, g.driver_version, g.compute_capability,
            )),
            None => s.push_str("gpu               : none detected (nvidia-smi absent or failed)\n"),
        }
        s.push_str(&format!("vocabulary        : {}\n", self.vocab));
        s.push_str(&format!(
            "corpus            : {} bytes from {} files, digest {:#018x}\n",
            self.corpus.bytes, self.corpus.files, self.corpus.digest,
        ));
        s.push_str(&format!("corpus origin     : {}\n", self.corpus.origin));
        match self.bytes_per_token {
            Some(b) => s.push_str(&format!(
                "corpus bytes/token: {b:.4} (MB/s scales with this; rows at different \
                 bytes/token are not comparable)\n"
            )),
            None => s.push_str("corpus bytes/token: not calibrated\n"),
        }
        if let Some(c) = self.clock {
            s.push_str(&format!(
                "clock             : {:.0} MHz mean at start, {:.0} MHz at end, drift {:+.2}%{}\n",
                c.first.mean_mhz,
                c.last.mean_mhz,
                c.drift_ratio() * 100.0,
                if c.is_significant() {
                    "  <-- boundary samples differ; occupancy-confounded, not proof of bias"
                } else {
                    ""
                },
            ));
        } else {
            s.push_str("clock             : kernel reported no per-CPU MHz; drift unknown\n");
        }
        s
    }

    fn render_versions(&self) -> String {
        let mut seen: BTreeMap<&str, (&str, &str)> = BTreeMap::new();
        for m in self.measured() {
            seen.insert(&m.tokenizer, (&m.version, &m.vocab));
        }
        let mut s = String::from("\n== versions under test ==\n\n");
        for (name, (ver, vocab)) in seen {
            s.push_str(&format!("{name:<12} {ver:<16} vocab {vocab}\n"));
        }
        s
    }

    fn render_unavailable(&self) -> String {
        let missing: Vec<(&str, &str)> = self
            .rows
            .iter()
            .filter_map(|r| match r {
                Availability::Unavailable { tokenizer, reason } => {
                    Some((tokenizer.as_str(), reason.as_str()))
                }
                Availability::Measured(_) => None,
            })
            .collect();
        if missing.is_empty() {
            return String::from("\n== unavailable baselines ==\n\nnone; every baseline ran\n");
        }
        let mut s = String::from(
            "\n== unavailable baselines (recorded, never estimated) ==\n\n",
        );
        let mut seen: BTreeMap<&str, &str> = BTreeMap::new();
        for (t, r) in missing {
            seen.entry(t).or_insert(r);
        }
        for (t, r) in seen {
            s.push_str(&format!("{t:<12} {r}\n"));
        }
        s
    }

    fn render_notes(&self) -> String {
        let harness = self.harness_defects();
        let defects = self.suspected_defects();
        let slow = self.known_slow();
        let mut s = String::new();
        if harness.is_empty() {
            s.push_str(&format!(
                "\nharness: every cell timed at least {MIN_TRUSTWORTHY_TIMED_SECS:.2} s, \
                 delivered at least {:.0}% of its requested threads, and ran with under \
                 {:.0}% of one core consumed elsewhere on the machine\n",
                MIN_PARALLEL_EFFICIENCY * 100.0,
                MAX_FOREIGN_LOAD_RATIO * 100.0,
            ));
        } else {
            s.push_str(&format!(
                "\nHARNESS DEFECT: {} cell(s) did not measure what the table claims. \
                 These are bugs in this harness, not results.\n",
                harness.len(),
            ));
            for d in harness {
                let why = assess_plausibility(d)
                    .diagnosis()
                    .unwrap_or_else(|| "unclassified".to_owned());
                s.push_str(&format!(
                    "  {} {} thr={} doc_bytes={} -> {why}\n",
                    d.tokenizer,
                    d.regime.as_str(),
                    d.threads,
                    d.doc_bytes,
                ));
            }
        }
        if defects.is_empty() {
            s.push_str(&format!(
                "plausibility: every large-input cell clears the \
                 {PLAUSIBLE_FLOOR_MB_S_PER_CORE:.1} MB/s per-core floor, or is recorded below as \
                 legitimately slower\n"
            ));
        } else {
            s.push_str(&format!(
                "plausibility: {} cell(s) fall under the {:.1} MB/s per-core floor with no \
                 recorded explanation. Investigate before publishing: either the harness \
                 mismeasured or the library needs an evidenced KNOWN_SLOW_BASELINES entry.\n",
                defects.len(),
                PLAUSIBLE_FLOOR_MB_S_PER_CORE,
            ));
            for d in defects {
                s.push_str(&format!(
                    "  {} {} thr={} doc_bytes={} -> {:.3} MB/s/core\n",
                    d.tokenizer,
                    d.regime.as_str(),
                    d.threads,
                    d.doc_bytes,
                    d.mb_per_second_per_core(),
                ));
            }
        }
        if !slow.is_empty() {
            let mut names: Vec<&str> = slow.iter().map(|m| m.tokenizer.as_str()).collect();
            names.sort_unstable();
            names.dedup();
            s.push_str(&format!(
                "known-slow: {} cell(s) across {} librar(y/ies) are below the floor for recorded \
                 reasons; the number stands, the reason is printed with it\n",
                slow.len(),
                names.len(),
            ));
            for n in names {
                if let Some(reason) = known_slow_reason(n) {
                    s.push_str(&format!("  {n}: {reason}\n"));
                }
            }
        }
        let noisy = self
            .measured()
            .filter(|m| m.stats.rel_stddev() >= NOISY_REL_STDDEV)
            .count();
        s.push_str(&format!(
            "variance: {} of {} cells exceeded {:.0}% relative standard deviation across reps\n",
            noisy,
            self.measured().count(),
            NOISY_REL_STDDEV * 100.0,
        ));
        let disagreeing = self.disagreeing();
        if disagreeing.is_empty() {
            s.push_str(
                "exactness: every measured library produced ids identical to the reference on the \
                 agreement sample, so the rows are vocabulary-comparable\n",
            );
        } else {
            let mut names: Vec<&str> = disagreeing.iter().map(|m| m.tokenizer.as_str()).collect();
            names.sort_unstable();
            names.dedup();
            s.push_str(&format!(
                "exactness: {} produced ids DIFFERENT from the reference; those rows measure a \
                 different computation and are not vocabulary-comparable\n",
                names.join(", "),
            ));
        }
        s
    }

    /// Machine-readable form, hand-emitted so the crate takes no serde
    /// dependency for a benchmark artifact.
    #[must_use]
    pub fn to_json(&self) -> String {
        let mut s = String::from("{\n");
        // Probed from `cfg!` rather than stored on the struct, so there is no
        // way to persist a feature set that disagrees with the binary that
        // produced the numbers. A throughput figure or a test count without its
        // feature set is not a measurement.
        let features: Vec<String> =
            compiled_features().iter().map(|f| json_str(f)).collect();
        s.push_str(&format!("  \"feature_set\": [{}],\n", features.join(", ")));
        s.push_str(&format!(
            "  \"provenance\": {},\n",
            json_str(Provenance::Probed.as_str())
        ));
        s.push_str(&format!("  \"cpu_model\": {},\n", json_str(&self.machine.cpu_model)));
        s.push_str(&format!("  \"physical_cores\": {},\n", self.machine.physical_cores));
        s.push_str(&format!("  \"logical_cores\": {},\n", self.machine.logical_cores));
        s.push_str(&format!(
            "  \"governor\": {},\n",
            self.machine.governor.as_deref().map_or_else(|| "null".to_owned(), json_str)
        ));
        s.push_str(&format!("  \"total_memory_kib\": {},\n", self.machine.total_memory_kib));
        match &self.machine.gpu {
            Some(g) => s.push_str(&format!(
                "  \"gpu\": {{\"name\": {}, \"memory_mib\": {}, \"driver_version\": {}, \"compute_capability\": {}}},\n",
                json_str(&g.name),
                json_str(&g.memory_mib),
                json_str(&g.driver_version),
                json_str(&g.compute_capability),
            )),
            None => s.push_str("  \"gpu\": null,\n"),
        }
        s.push_str(&format!("  \"vocab\": {},\n", json_str(&self.vocab)));
        s.push_str(&format!(
            "  \"corpus\": {{\"origin\": {}, \"bytes\": {}, \"files\": {}, \"digest\": \"{:#018x}\"}},\n",
            json_str(&self.corpus.origin),
            self.corpus.bytes,
            self.corpus.files,
            self.corpus.digest,
        ));
        s.push_str(&format!(
            "  \"bytes_per_token\": {},\n",
            self.bytes_per_token.map_or_else(|| "null".to_owned(), |b| format!("{b:.6}"))
        ));
        match self.clock {
            Some(c) => s.push_str(&format!(
                "  \"clock\": {{\"start_mean_mhz\": {:.1}, \"end_mean_mhz\": {:.1}, \"drift_ratio\": {:.6}, \"significant\": {}}},\n",
                c.first.mean_mhz,
                c.last.mean_mhz,
                c.drift_ratio(),
                c.is_significant(),
            )),
            None => s.push_str("  \"clock\": null,\n"),
        }
        s.push_str("  \"rows\": [\n");
        for (i, row) in self.rows.iter().enumerate() {
            if i > 0 {
                s.push_str(",\n");
            }
            match row {
                Availability::Unavailable { tokenizer, reason } => s.push_str(&format!(
                    "    {{\"status\": \"unavailable\", \"tokenizer\": {}, \"reason\": {}}}",
                    json_str(tokenizer),
                    json_str(reason)
                )),
                Availability::Measured(m) => {
                    let samples: Vec<String> =
                        m.stats.samples().iter().map(|v| format!("{v:.9}")).collect();
                    // Rendered ahead of the row so the whole object is one
                    // placeholder, matching how `device_secs` handles absence.
                    let region = m.region_clock.map_or_else(
                        || "null".to_owned(),
                        |c| {
                            format!(
                                "{{\"start_mhz\": {:.1}, \"end_mhz\": {:.1}, \
                                 \"drift_ratio\": {:.6}, \"busy_cpus\": {}, \"significant\": {}}}",
                                c.start_mhz,
                                c.end_mhz,
                                c.drift_ratio(),
                                c.busy_cpus,
                                c.is_significant(),
                            )
                        },
                    );
                    s.push_str(&format!(
                        "    {{\"status\": \"measured\", \"tokenizer\": {}, \"version\": {}, \"vocab\": {}, \
                         \"regime\": {}, \"target_tokens\": {}, \"doc_bytes\": {}, \"docs\": {}, \
                         \"input_bytes\": {}, \"tokens\": {}, \"threads\": {}, \"physical_cores\": {}, \
                         \"logical_cores\": {}, \"pinned_to_physical\": {}, \"warmups\": {}, \
                         \"matches_reference\": {}, \"cpu_secs\": {:.9}, \"device_secs\": {}, \
                         \"foreign_cpu_secs\": {:.9}, \"foreign_load_ratio\": {:.4}, \
                         \"achieved_parallelism\": {:.4}, \"inner_reps\": {}, \
                         \"timed_bytes\": {}, \"timed_tokens\": {}, \
                         \"mean_mhz\": {:.1}, \"region_clock\": {}, \
                         \"best_secs\": {:.9}, \"rel_stddev\": {:.6}, \
                         \"mb_per_s\": {:.4}, \"gb_per_s\": {:.6}, \"mb_per_s_per_thread\": {:.4}, \
                         \"tokens_per_s\": {:.1}, \"ns_per_token\": {:.3}, \"bytes_per_token\": {:.4}, \
                         \"samples_secs\": [{}]}}",
                        json_str(&m.tokenizer),
                        json_str(&m.version),
                        json_str(&m.vocab),
                        json_str(m.regime.as_str()),
                        m.target_tokens,
                        m.doc_bytes,
                        m.docs,
                        m.input_bytes,
                        m.tokens,
                        m.threads,
                        m.machine.physical_cores,
                        m.machine.logical_cores,
                        m.machine.pinned_to_physical,
                        m.warmups,
                        m.matches_reference,
                        m.active.cpu_secs,
                        m.active
                            .device_secs
                            .map_or_else(|| "null".to_owned(), |d| format!("{d:.9}")),
                        m.foreign_cpu_secs,
                        m.foreign_load_ratio(),
                        m.achieved_parallelism(),
                        m.inner_reps,
                        m.timed_bytes(),
                        m.timed_tokens(),
                        m.mean_mhz,
                        region,
                        m.stats.best(),
                        m.stats.rel_stddev(),
                        m.mb_per_second(),
                        m.gb_per_second(),
                        m.mb_per_second_per_thread(),
                        m.tokens_per_second(),
                        m.ns_per_token(),
                        m.bytes_per_token(),
                        samples.join(", "),
                    ));
                }
            }
        }
        s.push_str("\n  ]\n}\n");
        s
    }

    /// Write this report into `dir` under a UTC-timestamped name, returning the
    /// path written.
    ///
    /// Called for every sweep, passing or failing, because the failing sweep is
    /// the one whose per-cell numbers someone will need.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when the directory cannot be created
    /// or the file cannot be written.
    pub fn persist(&self, dir: &Path) -> Result<PathBuf, ExatokError> {
        let fix = "point SweepConfig::report_dir somewhere writable, or set it to None";
        fs::create_dir_all(dir).map_err(|e| {
            artifact_err("report directory", &dir.display().to_string(), &e.to_string(), fix)
        })?;
        let path =
            dir.join(format!("host-baseline-{}.json", utc_stamp(std::time::SystemTime::now())));
        fs::write(&path, self.to_json()).map_err(|e| {
            artifact_err("report file", &path.display().to_string(), &e.to_string(), fix)
        })?;
        Ok(path)
    }
}

/// `YYYYMMDDTHHMMSSZ` for an instant, in UTC.
///
/// Hand-written because this crate carries no date dependency, and a report
/// filename has to sort chronologically as plain text so the newest run is
/// findable without stat-ing every file. Valid for any instant at or after the
/// unix epoch; earlier instants clamp to the epoch rather than wrapping.
#[must_use]
pub fn utc_stamp(at: std::time::SystemTime) -> String {
    let secs = at.duration_since(std::time::SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs());
    let (days, rem) = (secs / 86_400, secs % 86_400);
    let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
    // Hinnant's civil_from_days with the era anchored at 0000-03-01, so leap
    // years need no special case. Unsigned throughout: the epoch floor above
    // means `days` is never negative.
    let z = days + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + u64::from(month <= 2);
    format!("{year:04}{month:02}{day:02}T{hh:02}{mm:02}{ss:02}Z")
}

/// JSON string literal with the six escapes JSON requires.
#[must_use]
pub fn json_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

// ---------------------------------------------------------------------------
// Sweep execution
// ---------------------------------------------------------------------------

/// Durable location of the baseline virtualenv, relative to `HOME`.
///
/// Deliberately NOT under the cargo target directory. A comparison baseline
/// kept in build output evaporates the first time anything cleans it, and that
/// is not hypothetical here: the venv was wiped between two sweeps, which left
/// a published gigatoken figure unreproducible and turned a broken install into
/// six `unavailable` rows that read like data.
pub const BENCH_VENV_REL: &str = ".cache/exatok-bench-venv";

/// Durable directory for timestamped sweep reports, relative to `HOME`.
///
/// Every sweep writes one whether it passes or fails. A gate that refuses to
/// certify a table but keeps no record of which cells failed forces a full
/// rerun to answer "which ones", which is the gap this closes.
pub const BENCH_REPORT_REL: &str = ".cache/exatok-bench/reports";

/// Baseline libraries the sweep expects the configured interpreter to import.
pub const BASELINE_MODULES: &[&str] = &["tiktoken", "tokenizers", "gigatoken", "fastokens"];

/// `HOME`, or `/root` when the environment does not name one.
///
/// One definition so the config, the preflight and the spawn failure message
/// cannot disagree about where the durable venv is.
#[must_use]
pub fn home_dir() -> PathBuf {
    std::env::var_os("HOME").map_or_else(|| PathBuf::from("/root"), PathBuf::from)
}

/// Everything the sweep needs to run.
#[derive(Debug, Clone)]
pub struct SweepConfig {
    /// Python interpreter that has the baseline libraries importable.
    pub python: PathBuf,
    /// The measurement driver script.
    pub driver: PathBuf,
    /// Vocabulary name, for the report.
    pub vocab: String,
    /// `.tiktoken` rank file for tiktoken and gigatoken.
    pub tiktoken_ranks: PathBuf,
    /// Hub id whose `tokenizer.json` gives the same vocabulary to the
    /// `tokenizer.json` based libraries.
    pub hf_repo: String,
    /// Corpus root walked when no explicit corpus file is given.
    pub corpus_root: PathBuf,
    /// Explicit corpus file, overriding the walk.
    pub corpus_file: Option<PathBuf>,
    /// Where the exact corpus bytes are written for the driver to read.
    pub corpus_scratch: PathBuf,
    /// Total bytes each batch-regime cell encodes per repetition.
    pub batch_budget_bytes: usize,
    /// Token counts swept.
    pub target_tokens: Vec<usize>,
    /// Timed repetitions per cell.
    pub reps: u32,
    /// Untimed warmups per cell.
    pub warmups: u32,
    /// Directory holding the durable tiktoken rank cache.
    pub tiktoken_cache_dir: Option<PathBuf>,
    /// Directory receiving a timestamped report for every sweep, pass or fail.
    /// `None` disables the write.
    pub report_dir: Option<PathBuf>,
    /// Treat a missing interpreter or an unimportable baseline as a hard error
    /// rather than letting the driver record it as an `unavailable` row.
    pub require_baselines: bool,
}

impl SweepConfig {
    /// Defaults for this repository: the durable off-tree bench venv, the
    /// durable named vocabulary cache, and `cl100k_base` across all four
    /// libraries.
    ///
    /// The interpreter is NOT probed here and there is no fallback to system
    /// `python3`. A silent fallback is how a wiped venv came to look like four
    /// unavailable libraries instead of one missing directory, so the path is
    /// stated unconditionally and checked by [`preflight_baselines`], which can
    /// name it.
    #[must_use]
    pub fn defaults(crate_dir: &Path, repo_root: &Path) -> Self {
        let scratch = scratch_root();
        let home = home_dir();
        Self {
            python: home.join(BENCH_VENV_REL).join("bin/python"),
            driver: crate_dir.join("benches/baselines/host_baselines.py"),
            vocab: "cl100k_base".to_owned(),
            tiktoken_ranks: home.join(".cache/exatok-vocab/cl100k_base.tiktoken"),
            hf_repo: "Xenova/gpt-4".to_owned(),
            corpus_root: repo_root.to_path_buf(),
            corpus_file: None,
            corpus_scratch: scratch.join("bench-corpus.txt"),
            batch_budget_bytes: 32 * 1024 * 1024,
            target_tokens: DEFAULT_TARGET_TOKENS.to_vec(),
            reps: 3,
            warmups: 1,
            tiktoken_cache_dir: Some(home.join(".cache/tiktoken")),
            report_dir: Some(home.join(BENCH_REPORT_REL)),
            require_baselines: true,
        }
    }
}

/// Fail loudly when the configured interpreter cannot import the baselines.
///
/// The alternative, which this replaces, is the driver reporting one
/// `ModuleNotFoundError` per library and the sweep publishing a table whose
/// missing rows are indistinguishable from libraries that genuinely do not
/// exist on the platform. Naming the expected venv path and the command that
/// rebuilds it turns that into a one-line fix.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] when the interpreter is absent or when
/// any module in [`BASELINE_MODULES`] cannot be imported.
pub fn preflight_baselines(cfg: &SweepConfig) -> Result<(), ExatokError> {
    let venv = home_dir().join(BENCH_VENV_REL);
    let fix = format!(
        "python3 -m venv --system-site-packages {} && {}/bin/pip install {}",
        venv.display(),
        venv.display(),
        BASELINE_MODULES.join(" ")
    );
    if !cfg.python.is_file() {
        return Err(artifact_err(
            "baseline interpreter",
            &cfg.python.display().to_string(),
            "no such file",
            &fix,
        ));
    }
    let script = format!(
        "import importlib\nbad=[]\nfor m in {BASELINE_MODULES:?}:\n    \
         try:\n        importlib.import_module(m)\n    \
         except Exception as e:\n        bad.append(f'{{m}}: {{type(e).__name__}}')\n\
         print(';'.join(bad))\n"
    );
    let out = Command::new(&cfg.python).arg("-c").arg(&script).output().map_err(|e| {
        artifact_err("baseline interpreter", &cfg.python.display().to_string(), &e.to_string(), &fix)
    })?;
    let missing = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    if !out.status.success() {
        return Err(artifact_err(
            "baseline import probe",
            &cfg.python.display().to_string(),
            &describe_stderr(&out.stderr),
            &fix,
        ));
    }
    if missing.is_empty() {
        Ok(())
    } else {
        Err(artifact_err("baseline libraries", &missing, "not importable", &fix))
    }
}

/// Build the corpus, run every thread plan, and assemble the report.
///
/// The corpus is written once and every library reads the same bytes, so a
/// row difference is a library difference and not an input difference.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] when the corpus cannot be built or
/// written, when the driver emits a malformed record, or when the measured
/// baselines do not tokenize the corpus identically, because a ratio against
/// a mistokenizing baseline is unfalsifiable and the sweep fails closed (see
/// `refuse_noncomparable_cells`), and [`ExatokError::Backend`] when a driver
/// invocation cannot be spawned or exits non-zero.
pub fn run_sweep(cfg: &SweepConfig, machine: &Machine) -> Result<Report, ExatokError> {
    // Refuse to measure before spending minutes on a corpus when the thing that
    // does the measuring cannot be imported.
    if cfg.require_baselines {
        preflight_baselines(cfg)?;
    }
    // The corpus must cover one whole batch cell plus the largest single
    // document, so no cell has to wrap around and re-read bytes it already
    // touched. Eight bytes per token is a deliberate overestimate of any
    // real bytes-per-token, so the largest document always fits.
    let corpus_bytes = cfg.batch_budget_bytes.saturating_add(
        cfg.target_tokens.iter().copied().max().unwrap_or(0).saturating_mul(8),
    );
    let corpus = match &cfg.corpus_file {
        Some(p) => Corpus::from_file(p, corpus_bytes)?,
        None => Corpus::from_tree(&cfg.corpus_root, corpus_bytes)?,
    };
    if let Some(parent) = cfg.corpus_scratch.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            artifact_err(
                "corpus scratch directory",
                &parent.display().to_string(),
                &e.to_string(),
                "ensure the crate target directory is writable",
            )
        })?;
    }
    fs::write(&cfg.corpus_scratch, corpus.text.as_bytes()).map_err(|e| {
        artifact_err(
            "corpus scratch file",
            &cfg.corpus_scratch.display().to_string(),
            &e.to_string(),
            "ensure the crate target directory is writable",
        )
    })?;

    let clock_first = ClockSample::probe();
    let mut rows = Vec::new();
    let mut bytes_per_token = None;
    for plan in ThreadPlan::standard(machine) {
        let ctx = MachineContext {
            physical_cores: machine.physical_cores,
            logical_cores: machine.logical_cores,
            pinned_to_physical: plan.pinned_to_physical,
        };
        let stdout = spawn_driver(cfg, &plan)?;
        for (i, line) in stdout.lines().enumerate() {
            match parse_driver_line(line, ctx, i + 1)? {
                Some(DriverEvent::Record(m)) => rows.push(Availability::Measured(m)),
                Some(DriverEvent::Unavailable { tokenizer, reason }) => {
                    rows.push(Availability::Unavailable { tokenizer, reason });
                }
                Some(DriverEvent::Calibration { bytes_per_token: b, .. }) => {
                    bytes_per_token = Some(b);
                }
                None => {}
            }
        }
    }
    // Fail closed before the report exists: a corpus the measured baselines do
    // not tokenize identically voids every ratio computed from these rows, so
    // the sweep refuses it rather than publishing an unfalsifiable table.
    refuse_noncomparable_cells(&rows, &corpus.facts)?;
    let clock_last = ClockSample::probe();
    let clock = match (clock_first, clock_last) {
        (Some(first), Some(last)) => Some(ClockDrift { first, last }),
        _ => None,
    };
    let mut report = Report {
        machine: machine.clone(),
        corpus: corpus.facts,
        vocab: cfg.vocab.clone(),
        rows,
        clock,
        bytes_per_token,
        report_path: None,
    };
    // Persist before returning, so a sweep whose table is later rejected still
    // left the per-cell evidence behind. Recovering "which cells failed and
    // why" previously meant a full rerun, because only an explicit `--json`
    // wrote anything.
    if let Some(dir) = &cfg.report_dir {
        report.report_path = Some(report.persist(dir)?);
    }
    Ok(report)
}

/// Fail closed on a corpus the measured baselines do not tokenize
/// identically.
///
/// Every library reads the same bytes, so two rows of one cell that disagree
/// on token count are timed on work that is not the work being compared, and a
/// ratio computed against either is unfalsifiable: that is the precise defect
/// that made the published speedups this harness exists to re-measure
/// uncheckable. The hazard is real, not hypothetical. A 1 MiB corpus walked
/// from this crate's own tree carries README.md prose quoting the literal
/// strings `<|endoftext|>` and `<|endofprompt|>`; hf-tokenizers matches them
/// through its added-token table and emits one id where tiktoken's ordinary
/// encoding, which exatok reproduces exactly, emits seven, so the two
/// libraries reported token counts 19 apart on the same bytes
/// (FINDING-hf-tokenizers-diverges-from-tiktoken-on-crate-tree-corpus).
///
/// Unequal `input_bytes` inside one cell refuses too: it means the libraries
/// were not even fed the same input, which voids the cell before tokenization
/// is ever reached.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] naming the cell, both tokenizers and both
/// counts when any measured cell disagrees, so the refusal identifies the
/// corpus rather than reading as a driver failure.
fn refuse_noncomparable_cells(
    rows: &[Availability],
    corpus: &CorpusFacts,
) -> Result<(), ExatokError> {
    let mut cells: BTreeMap<(&str, &str, usize), Vec<(&str, u64, u64)>> = BTreeMap::new();
    for m in rows.iter().filter_map(|r| match r {
        Availability::Measured(m) => Some(m),
        Availability::Unavailable { .. } => None,
    }) {
        cells
            .entry((m.vocab.as_str(), m.regime.as_str(), m.target_tokens))
            .or_default()
            .push((m.tokenizer.as_str(), m.input_bytes, m.tokens));
    }
    for ((vocab, regime, target), entries) in &cells {
        let &(first_tok, first_bytes, first_tokens) = &entries[0];
        for &(tok, bytes, tokens) in &entries[1..] {
            if bytes != first_bytes || tokens != first_tokens {
                return Err(artifact_err(
                    "baseline sweep corpus",
                    &format!("{vocab} {regime} target_tokens={target}"),
                    &format!(
                        "{tok} emitted {tokens} tokens from {bytes} bytes but {first_tok} emitted \
                         {first_tokens} from {first_bytes} bytes of the same corpus ({} bytes, \
                         digest {})",
                        corpus.bytes, corpus.digest
                    ),
                    "the baselines do not tokenize this corpus identically, so no ratio between \
                     them is falsifiable; remove the diverging text from the corpus tree or point \
                     corpus_file at text every baseline encodes to the same ids",
                ));
            }
        }
    }
    Ok(())
}

fn spawn_driver(cfg: &SweepConfig, plan: &ThreadPlan) -> Result<String, ExatokError> {
    let cpu_list = plan.cpu_list();
    let mut cmd = match &cpu_list {
        Some(list) => {
            let mut c = Command::new("taskset");
            c.arg("-c").arg(list).arg(&cfg.python);
            c
        }
        None => Command::new(&cfg.python),
    };
    cmd.arg(&cfg.driver)
        .arg("--corpus")
        .arg(&cfg.corpus_scratch)
        .arg("--vocab")
        .arg(&cfg.vocab)
        .arg("--ranks")
        .arg(&cfg.tiktoken_ranks)
        .arg("--hf-repo")
        .arg(&cfg.hf_repo)
        .arg("--threads")
        .arg(plan.threads.to_string())
        .arg("--batch-budget")
        .arg(cfg.batch_budget_bytes.to_string())
        .arg("--reps")
        .arg(cfg.reps.to_string())
        .arg("--warmups")
        .arg(cfg.warmups.to_string())
        .arg("--target-tokens")
        .arg(
            cfg.target_tokens
                .iter()
                .map(usize::to_string)
                .collect::<Vec<_>>()
                .join(","),
        );
    if plan.include_single_doc {
        cmd.arg("--include-single-doc");
    }
    // Every thread-count knob these libraries read, set explicitly. Letting a
    // library pick its own width makes a row's thread count a guess.
    cmd.env("RAYON_NUM_THREADS", plan.threads.to_string())
        .env("TOKENIZERS_PARALLELISM", if plan.threads > 1 { "true" } else { "false" })
        .env("OMP_NUM_THREADS", "1")
        .env("MKL_NUM_THREADS", "1")
        .env("PYTHONHASHSEED", "0");
    if let Some(dir) = &cfg.tiktoken_cache_dir {
        cmd.env("TIKTOKEN_CACHE_DIR", dir);
    }
    let out = cmd.output().map_err(|e| {
        ExatokError::Backend(format!(
            "cannot spawn baseline driver {} via {}: {e}. Fix: create the bench venv \
             off-tree with `python3 -m venv --system-site-packages {}` and install \
             {} into it",
            cfg.driver.display(),
            cfg.python.display(),
            home_dir().join(BENCH_VENV_REL).display(),
            BASELINE_MODULES.join(" "),
        ))
    })?;
    if !out.status.success() {
        return Err(ExatokError::Backend(format!(
            "baseline driver failed with {} for threads={}. stderr: {}{}",
            describe_termination(&out.status),
            plan.threads,
            describe_stderr(&out.stderr),
            kill_hint(&out.status),
        )));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// Guidance for a signalled driver, naming the reapers that cause it here.
///
/// Signal 9 is never the driver's own doing: it has no handler and leaves no
/// stderr, so the only way to attribute it is to know what reaps processes on
/// this fleet. A cron CPU watchdog kills anything non-allowlisted that holds
/// >95% CPU for five minutes, which a legitimate multi-minute sweep does by
/// construction, and it logs the kill. Pointing at that log turns a silent
/// several-minute failure into a one-line diagnosis.
fn kill_hint(status: &std::process::ExitStatus) -> &'static str {
    match status.signal() {
        Some(9) => {
            " A sweep is long and CPU-bound, so signal 9 is usually an external \
             reaper rather than a fault in the driver. Check /tmp/cpu-watchdog.log \
             and /tmp/watchdog.log for a kill naming this pid, and check dmesg for \
             an OOM kill. If a watchdog reaped it, allowlist the driver rather than \
             shortening the measurement."
        }
        Some(7) => " Signal 7 means the corpus changed under a mapped read; keep it off-tree.",
        _ => "",
    }
}

/// Name how a process ended, including the signal when it was killed.
///
/// A signalled process has no exit code, so `status.code()` is `None` and the
/// obvious `{:?}` rendering prints `None`. Paired with the empty stderr a killed
/// process leaves behind, that reads like the driver failed silently and cleanly,
/// which sent an earlier investigation looking for a bug in the driver instead of
/// for whatever killed it. The signal number is the whole diagnosis: 9 is an
/// external kill such as a CPU or memory watchdog, 7 is the corpus vanishing
/// under a mapped read, 11 is a crash inside the tokenizer.
fn describe_termination(status: &std::process::ExitStatus) -> String {
    if let Some(code) = status.code() {
        return format!("exit code {code}");
    }
    match status.signal() {
        Some(signal) => format!("no exit code, killed by signal {signal}"),
        None => "neither an exit code nor a signal".to_owned(),
    }
}

/// Render captured stderr, marking emptiness rather than printing nothing.
///
/// An empty stderr is itself evidence: it distinguishes a process killed from
/// outside from one that reported a fault. Printing the empty string makes the
/// message trail off after `stderr:` and loses that distinction.
fn describe_stderr(stderr: &[u8]) -> String {
    let text = String::from_utf8_lossy(stderr);
    let trimmed = text.trim();
    if trimmed.is_empty() {
        "<empty, which means the driver reported nothing before it ended>".to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// Directory for the multi-megabyte scratch corpus the driver reads.
///
/// This fleet configures the cargo target directory off-tree, and repository
/// hygiene deletes any `target/` that appears inside the source tree. Writing
/// the corpus to `<crate>/target` therefore created a directory that a cleanup
/// is entitled to remove *while the driver is reading it*, which is how a sweep
/// loses its input mid-measurement. Derive the real target directory from the
/// running test binary, whose path is `<target>/<profile>/deps/<bin>`, so the
/// corpus lands beside the artifacts cargo already writes.
#[must_use]
pub fn scratch_root() -> PathBuf {
    if let Ok(exe) = std::env::current_exe() {
        for dir in exe.ancestors() {
            let profile = dir.file_name().and_then(|n| n.to_str());
            if matches!(profile, Some("debug" | "release")) {
                if let Some(target) = dir.parent() {
                    return target.to_path_buf();
                }
            }
        }
    }
    std::env::temp_dir()
}

/// Walk up from `start` to the OUTERMOST ancestor holding a `.git` entry.
///
/// The corpus root has to be stable regardless of where cargo was invoked
/// from, otherwise the corpus digest changes with the caller's directory. It
/// also has to survive the crate gaining its own nested `.git`: exatok is both
/// a standalone repository and a directory inside a larger checkout, and the
/// benchmark corpus is the larger tree. First-ancestor lookup would silently
/// move the corpus from the outer checkout to the crate tree the day the
/// nested repository was created, which is exactly the change detector problem
/// the corpus digest exists to catch, so the walk keeps going to the top.
#[must_use]
pub fn find_repo_root(start: &Path) -> Option<PathBuf> {
    let mut outer = None;
    let mut cur = Some(start);
    while let Some(dir) = cur {
        if dir.join(".git").exists() {
            outer = Some(dir.to_path_buf());
        }
        cur = dir.parent();
    }
    outer
}

// ---------------------------------------------------------------------------
// In-process cell measurement
// ---------------------------------------------------------------------------

/// Seconds a timed region is calibrated to reach.
///
/// Twice [`MIN_TRUSTWORTHY_TIMED_SECS`] deliberately. Calibrating to exactly
/// the gate floor leaves a cell one unlucky repetition away from being voided
/// for a harness reason rather than a real one.
pub const CALIBRATION_TARGET_SECS: f64 = 0.5;

/// Growth attempts allowed while calibrating a timed region.
const CALIBRATION_ATTEMPTS: u32 = 12;

/// Headroom applied when growing the inner repetition count.
const CALIBRATION_HEADROOM: f64 = 1.2;

/// `/proc` reports CPU time in USER_HZ, which is 100 on every Linux ABI
/// regardless of the kernel's `CONFIG_HZ`. Hardcoded because reading it needs
/// `sysconf` and this crate carries no libc dependency.
const USER_HZ: f64 = 100.0;

/// Fraction of a region a CPU must be non-idle for to count as participating.
const BUSY_CPU_MIN_OCCUPANCY: f64 = 0.10;

/// Rounds a paired comparison needs before its spread means anything.
///
/// Eight rather than three because the contaminant on a shared card is bursty:
/// a sibling landing inside one arm of one round biases that round, and with
/// few rounds it biases the median too.
pub const MIN_PAIRED_ROUNDS: u32 = 8;

/// Foreign device residency growth tolerated within a round, in MiB.
///
/// A steady resident process reads identically sample to sample, so this only
/// absorbs accounting jitter. A sibling landing adds hundreds of MiB.
pub const DEVICE_RESIDENCY_TOLERANCE_MIB: u64 = 64;

/// Relative spread of per-round host load a paired comparison tolerates.
///
/// A paired ratio survives contention only where the contaminant is STATIONARY:
/// present in both arms of every round, so it largely cancels. This gates that
/// premise instead of assuming it. The level is deliberately NOT gated, because
/// a heavily but evenly loaded box still yields a valid ratio, whereas load that
/// moves between rounds does not cancel and biases whichever arm it lands on.
///
/// Set from the failure that motivated it. Two captures each passing every gate
/// disagreed on which arm wins cjk: its within-run speedup spread was 0.0397
/// while its BETWEEN-run device-arm drift was 0.31, roughly eight times larger,
/// because concurrent cargo builds started and finished across the window. At
/// 0.25 that window is refused rather than published.
pub const MAX_PAIRED_HOST_LOAD_DRIFT: f64 = 0.25;

/// Times a contaminated round is retried before the comparison refuses.
pub const MAX_VOIDED_ROUND_RETRIES: u32 = 3;

/// Seconds to wait for the device measurement lock before refusing.
pub const DEVICE_LOCK_TIMEOUT_SECS: u64 = 900;

/// Advisory lock file for device measurement, relative to `HOME`.
pub const BENCH_LOCK_REL: &str = ".cache/exatok-bench/device.lock";

/// What one unit of timed work processed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WorkUnit {
    /// Input bytes the unit consumed.
    pub bytes: u64,
    /// Tokens the unit produced.
    pub tokens: u64,
}

/// One arm of a paired comparison.
pub struct Arm<'a> {
    /// Name carried into the result.
    pub label: &'a str,
    /// Runs one unit of work and reports what it processed.
    pub work: &'a mut dyn FnMut() -> Result<WorkUnit, ExatokError>,
}

/// Non-idle CPU-seconds summed over every CPU.
fn machine_busy_secs() -> Option<f64> {
    let stat = fs::read_to_string("/proc/stat").ok()?;
    let aggregate = stat.lines().next()?;
    let ticks: Vec<f64> =
        aggregate.split_whitespace().skip(1).filter_map(|t| t.parse::<f64>().ok()).collect();
    if ticks.len() < 4 {
        return None;
    }
    let idle = ticks[3] + ticks.get(4).copied().unwrap_or(0.0);
    Some((ticks.iter().sum::<f64>() - idle) / USER_HZ)
}

/// This process's own CPU-seconds, user plus system.
fn process_cpu_secs() -> Option<f64> {
    let stat = fs::read_to_string("/proc/self/stat").ok()?;
    // The comm field can contain spaces and parentheses, so fields are counted
    // from the LAST closing parenthesis rather than by splitting the whole line.
    // Splitting naively misparses any process whose name contains a space.
    let after_comm = stat.rsplit_once(')')?.1;
    let fields: Vec<&str> = after_comm.split_whitespace().collect();
    // `state` is field 3, so index i here is field i + 3: utime is field 14 and
    // stime is field 15.
    let utime = fields.get(11)?.parse::<f64>().ok()?;
    let stime = fields.get(12)?.parse::<f64>().ok()?;
    Some((utime + stime) / USER_HZ)
}

/// Non-idle CPU-seconds per logical CPU, indexed by CPU number.
///
/// The whole-machine figure cannot say WHICH cores were busy, and that is the
/// missing input for a defensible clock reading.
fn per_cpu_busy_secs() -> Vec<f64> {
    let Ok(stat) = fs::read_to_string("/proc/stat") else {
        return Vec::new();
    };
    stat.lines()
        .filter_map(|line| {
            let (head, rest) = line.split_once(char::is_whitespace)?;
            // Per-CPU rows only: the bare `cpu` aggregate has an empty index and
            // the intr/ctxt/btime tail does not start with `cpu`.
            let index = head.strip_prefix("cpu")?;
            if index.is_empty() || !index.bytes().all(|b| b.is_ascii_digit()) {
                return None;
            }
            let ticks: Vec<f64> =
                rest.split_whitespace().filter_map(|t| t.parse::<f64>().ok()).collect();
            if ticks.len() < 4 {
                return None;
            }
            let idle = ticks[3] + ticks.get(4).copied().unwrap_or(0.0);
            Some((ticks.iter().sum::<f64>() - idle) / USER_HZ)
        })
        .collect()
}

/// Reported MHz per logical CPU, in `processor` index order.
fn per_cpu_mhz() -> Vec<f64> {
    let Ok(info) = fs::read_to_string("/proc/cpuinfo") else {
        return Vec::new();
    };
    info.lines()
        .filter_map(|l| l.strip_prefix("cpu MHz"))
        .filter_map(|r| r.split_once(':'))
        .filter_map(|(_, v)| v.trim().parse::<f64>().ok())
        .collect()
}

/// Mean MHz over only the CPUs that did work, weighted by how much.
///
/// The probe [`ClockSample`] cannot be: a whole-machine mean averages idle
/// cores in, so it tracks occupancy rather than boost state. Returns 0.0 when
/// nothing was busy, which reads as "no claim" rather than as a clock.
#[must_use]
pub fn busy_weighted_mhz(mhz: &[f64], weights: &[f64]) -> f64 {
    let n = mhz.len().min(weights.len());
    if n == 0 {
        return 0.0;
    }
    let total: f64 = weights[..n].iter().sum();
    if total <= 0.0 {
        return 0.0;
    }
    mhz[..n].iter().zip(&weights[..n]).map(|(m, w)| m * w).sum::<f64>() / total
}

/// Per-process device load, attributing nothing to this process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeviceLoad {
    /// Device memory held by compute processes other than this one.
    pub foreign_resident_mib: u64,
    /// Summed SM utilization percent attributed to those processes.
    ///
    /// Sampled at roughly 1 Hz, so a blank column means "no kernel in this
    /// window" and NOT a measured zero. Reported as evidence, never gated on.
    pub foreign_sm_percent: u32,
    /// Compute processes on the device other than this one.
    pub foreign_processes: u32,
    /// Device memory held by THIS process.
    ///
    /// Zero means this process has no compute context on the card, so the cell
    /// is host-only and foreign device residency cannot affect its timing. That
    /// is what scopes the device-contention gate automatically, instead of
    /// asking every caller to declare whether its work touches the GPU.
    pub own_resident_mib: u64,
}

/// Sample per-process device load via `nvidia-smi pmon`.
///
/// Deliberately NOT `--query-compute-apps`: that interface showed an 87.5%
/// false-absence rate against the process table during live CUDA runs and was
/// retired as an all-clear observable. `pmon -s um` reports per-PID `sm%` and
/// resident `fb` MB from NVML's per-process sampling, and five consecutive
/// samples caught a known resident process in every one.
///
/// Resident `fb` is memory accounting and therefore reliable. `sm%` is sampled
/// and can legitimately be blank, so gating on it would produce false clean
/// verdicts, the same class of error as the compute-apps false absence.
///
/// Returns `None` when `nvidia-smi` is absent or emits nothing parseable, which
/// reads as "not observed" rather than as an idle device.
#[must_use]
pub fn sample_device_load() -> Option<DeviceLoad> {
    let out = Command::new("nvidia-smi").args(["pmon", "-c", "1", "-s", "um"]).output().ok()?;
    if !out.status.success() {
        return None;
    }
    parse_pmon(&String::from_utf8_lossy(&out.stdout), std::process::id())
}

/// Attribute one `pmon -s um` capture to self and to foreign processes.
///
/// Split out from [`sample_device_load`] so attribution is testable against a
/// fixture. Testing it live cannot work: whether THIS process holds device
/// memory depends on the feature set (a `cuda` test binary creates a context on
/// a sibling thread) and on what a concurrent agent is doing, so a live
/// assertion is either vacuous or flaky. Attribution is the property that
/// matters, since inverting it would silently move a foreign process's residency
/// into `own_resident_mib` and void host-only cells that nothing contaminated.
fn parse_pmon(text: &str, own_pid: u32) -> Option<DeviceLoad> {
    let mut load = DeviceLoad {
        foreign_resident_mib: 0,
        foreign_sm_percent: 0,
        foreign_processes: 0,
        own_resident_mib: 0,
    };
    let mut saw_row = false;
    for line in text.lines() {
        if line.starts_with('#') {
            continue;
        }
        // gpu pid type sm mem enc dec jpg ofa fb ccpm command
        let f: Vec<&str> = line.split_whitespace().collect();
        if f.len() < 11 {
            continue;
        }
        let Ok(pid) = f[1].parse::<u32>() else {
            continue;
        };
        saw_row = true;
        // Only compute contexts contend for SM time with our kernels; graphics
        // contexts are the desktop and are not what a device benchmark races.
        if f[2] != "C" {
            continue;
        }
        let resident = f[9].parse::<u64>().unwrap_or(0);
        if pid == own_pid {
            load.own_resident_mib += resident;
            continue;
        }
        load.foreign_processes += 1;
        load.foreign_resident_mib += resident;
        load.foreign_sm_percent += f[3].parse::<u32>().unwrap_or(0);
    }
    saw_row.then_some(load)
}

/// Exclusive advisory lock held across a timed region.
///
/// Mutual exclusion by construction rather than by convention: six agents
/// sharing one card cannot each be relied on to remember a booking order, and
/// one forgotten turn contaminates someone else's numbers rather than their own.
///
/// Held across the TIMED REGION ONLY. Holding it across setup or correctness
/// suites would trade measurement noise for serialized wall time.
///
/// Implemented as an exclusive-create lock file carrying the holder's pid,
/// because this crate has no libc dependency and therefore no `flock`. A holder
/// that died without cleaning up is detected by checking whether its pid still
/// exists, so a crash cannot wedge the card permanently.
#[derive(Debug)]
pub struct DeviceLock {
    path: PathBuf,
}

impl DeviceLock {
    /// Acquire the lock, waiting up to `timeout`.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError::Artifact`] when the lock directory is unusable,
    /// or when the lock is still held at the deadline, naming the holder when
    /// its pid is still readable.
    pub fn acquire(timeout: std::time::Duration) -> Result<Self, ExatokError> {
        Self::acquire_at(home_dir().join(BENCH_LOCK_REL), timeout)
    }

    /// Acquire a lock at an explicit path.
    ///
    /// Separated so tests can exercise the protocol without contending for the
    /// well-known path against a real measurement, which would make the suite
    /// depend on whether a sibling agent happened to be timing something.
    ///
    /// # Errors
    ///
    /// As [`DeviceLock::acquire`].
    pub fn acquire_at(path: PathBuf, timeout: std::time::Duration) -> Result<Self, ExatokError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                artifact_err(
                    "device lock directory",
                    &parent.display().to_string(),
                    &e.to_string(),
                    "ensure $HOME/.cache is writable",
                )
            })?;
        }
        let deadline = std::time::Instant::now() + timeout;
        loop {
            match fs::OpenOptions::new().write(true).create_new(true).open(&path) {
                Ok(mut file) => {
                    // Best effort: the lock is the file's existence, so a failed
                    // write costs only the holder's name in a later refusal.
                    use std::io::Write;
                    let _ = write!(file, "{}", std::process::id());
                    return Ok(Self { path });
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                    if Self::clear_if_stale(&path) {
                        continue;
                    }
                    if std::time::Instant::now() >= deadline {
                        return Err(artifact_err(
                            "device measurement lock",
                            &path.display().to_string(),
                            &format!(
                                "still held by {} after {} s",
                                Self::describe_holder(&path),
                                timeout.as_secs()
                            ),
                            "wait for the running measurement to finish, or delete the lock \
                             file if its holder is gone",
                        ));
                    }
                    std::thread::sleep(std::time::Duration::from_millis(200));
                }
                Err(e) => {
                    return Err(artifact_err(
                        "device measurement lock",
                        &path.display().to_string(),
                        &e.to_string(),
                        "ensure $HOME/.cache is writable",
                    ));
                }
            }
        }
    }

    /// Remove the lock when its recorded holder no longer exists.
    fn clear_if_stale(path: &Path) -> bool {
        let Ok(text) = fs::read_to_string(path) else {
            return false;
        };
        let Ok(pid) = text.trim().parse::<u32>() else {
            // An unreadable pid cannot be checked, so the lock is left alone
            // rather than stolen from a holder that may be alive.
            return false;
        };
        if Path::new(&format!("/proc/{pid}")).exists() {
            return false;
        }
        fs::remove_file(path).is_ok()
    }

    /// Describe the current holder for a refusal message.
    fn describe_holder(path: &Path) -> String {
        let Ok(text) = fs::read_to_string(path) else {
            return "an unreadable lock file".to_owned();
        };
        let pid = text.trim();
        match fs::read_to_string(format!("/proc/{pid}/comm")) {
            Ok(comm) => format!("pid {pid} ({})", comm.trim()),
            Err(_) => format!("pid {pid}"),
        }
    }
}

impl Drop for DeviceLock {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

/// One timed region and everything observed around it.
struct RegionSample {
    secs: f64,
    unit: WorkUnit,
    cpu_secs: f64,
    foreign_cpu_secs: f64,
    mean_mhz: f64,
    region_clock: Option<RegionClock>,
    /// Highest foreign residency seen at either end of the region.
    foreign_resident_mib: u64,
    /// Highest foreign SM percent seen at either end.
    foreign_sm_percent: u32,
    /// Highest residency THIS process held at either end. Zero means the region
    /// never touched the device, so foreign device load cannot have biased it.
    own_resident_mib: u64,
}

/// Grow an inner repetition count until the region clears the target.
///
/// Calibrates AFTER a warm pass. The cold call pays first-touch faults, cache
/// fill and lazy setup, so it overestimates steady-state cost and therefore
/// UNDERESTIMATES the repetitions needed; calibrating on it produced regions
/// under half the target that the gate then correctly rejected.
///
/// `target_secs` is [`CALIBRATION_TARGET_SECS`] on every measurement path. It
/// is a parameter so tests of the paired-comparison estimator can run the same
/// algebra over short regions: the estimator's contract (per-unit ratios,
/// interleaving, the work pin) does not depend on region length, and the full
/// half-second floor exists for publishable absolute figures, which no test
/// asserts.
fn calibrate(
    work: &mut dyn FnMut() -> Result<WorkUnit, ExatokError>,
    target_secs: f64,
) -> Result<(u32, WorkUnit), ExatokError> {
    let start = std::time::Instant::now();
    let unit = work()?;
    let cold = start.elapsed().as_secs_f64();
    work()?;
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let mut inner = ((target_secs / cold.max(1e-9)).ceil() as u32).max(1);
    for _ in 0..CALIBRATION_ATTEMPTS {
        let probe = std::time::Instant::now();
        for _ in 0..inner {
            work()?;
        }
        let observed = probe.elapsed().as_secs_f64();
        if observed >= target_secs {
            break;
        }
        let grow = target_secs / observed.max(1e-9) * CALIBRATION_HEADROOM;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let grown = (f64::from(inner) * grow).ceil() as u32;
        // Always by at least one, so this terminates even when `observed` sits
        // at timer resolution and the ratio is enormous or degenerate.
        inner = grown.max(inner.saturating_add(1));
    }
    Ok((inner, unit))
}

/// Time one region of `inner` units under the device lock, with probes.
fn time_region(
    work: &mut dyn FnMut() -> Result<WorkUnit, ExatokError>,
    inner: u32,
) -> Result<RegionSample, ExatokError> {
    let lock = DeviceLock::acquire(std::time::Duration::from_secs(DEVICE_LOCK_TIMEOUT_SECS))?;
    // Sampled inside the lock so the reading describes a serialized moment, but
    // outside the timed region so the subprocess cost is not charged to the work.
    let device_before = sample_device_load();
    let per_cpu_before = per_cpu_busy_secs();
    let mhz_before = per_cpu_mhz();
    let busy_before = machine_busy_secs();
    let cpu_before = process_cpu_secs();

    let start = std::time::Instant::now();
    let mut unit = WorkUnit { bytes: 0, tokens: 0 };
    for _ in 0..inner {
        unit = work()?;
    }
    let secs = start.elapsed().as_secs_f64();

    let mhz_after = per_cpu_mhz();
    let per_cpu_after = per_cpu_busy_secs();
    let cpu_after = process_cpu_secs();
    let busy_after = machine_busy_secs();
    let device_after = sample_device_load();
    drop(lock);

    let cpu_secs = match (cpu_before, cpu_after) {
        (Some(a), Some(b)) => (b - a).max(0.0),
        _ => 0.0,
    };
    let machine_busy = match (busy_before, busy_after) {
        (Some(a), Some(b)) => (b - a).max(0.0),
        _ => 0.0,
    };
    // CPU-seconds burned by everything that is not this process. A cpu/wall
    // ratio alone cannot see an SMT sibling or a memory bandwidth hog: both
    // leave this process at full CPU-seconds while its throughput falls.
    let foreign_cpu_secs = (machine_busy - cpu_secs).max(0.0);

    let width = per_cpu_before.len().min(per_cpu_after.len());
    let weights: Vec<f64> =
        (0..width).map(|i| (per_cpu_after[i] - per_cpu_before[i]).max(0.0)).collect();
    let region_clock = if weights.is_empty() {
        None
    } else {
        let floor = secs * BUSY_CPU_MIN_OCCUPANCY;
        #[allow(clippy::cast_possible_truncation)]
        let busy_cpus = weights.iter().filter(|w| **w >= floor).count() as u32;
        Some(RegionClock {
            start_mhz: busy_weighted_mhz(&mhz_before, &weights),
            end_mhz: busy_weighted_mhz(&mhz_after, &weights),
            busy_cpus,
        })
    };
    let mean_mhz = if mhz_after.is_empty() {
        0.0
    } else {
        #[allow(clippy::cast_precision_loss)]
        let n = mhz_after.len() as f64;
        mhz_after.iter().sum::<f64>() / n
    };
    // The worse of the two ends: a sibling that landed and left within the
    // region still contaminated it, so the maximum is the honest figure.
    let foreign_resident_mib = device_before
        .map_or(0, |d| d.foreign_resident_mib)
        .max(device_after.map_or(0, |d| d.foreign_resident_mib));
    let foreign_sm_percent = device_before
        .map_or(0, |d| d.foreign_sm_percent)
        .max(device_after.map_or(0, |d| d.foreign_sm_percent));
    Ok(RegionSample {
        secs,
        unit,
        cpu_secs,
        foreign_cpu_secs,
        mean_mhz,
        region_clock,
        foreign_resident_mib,
        own_resident_mib: device_before
            .map_or(0, |d| d.own_resident_mib)
            .max(device_after.map_or(0, |d| d.own_resident_mib)),
        foreign_sm_percent,
    })
}

/// Measure one cell of in-process work.
///
/// Owns the whole protocol so a caller supplies only the work: an inner
/// repetition count calibrated until the timed region clears
/// [`CALIBRATION_TARGET_SECS`], one warm pass before calibrating, the device
/// lock across each timed region, and the per-CPU and per-process device probes
/// around it. The returned [`Measurement`] carries everything
/// [`assess_plausibility`] needs, so the caller never decides whether its own
/// number is trustworthy.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] when the machine cannot be probed, when a
/// timed region produced no samples, or when foreign device residency ROSE
/// during measurement, which means a sibling process landed on the card and the
/// number would be contaminated. Propagates whatever `work` returns.
pub fn measure_cell(
    label: &str,
    threads: usize,
    work: &mut dyn FnMut() -> Result<WorkUnit, ExatokError>,
) -> Result<Measurement, ExatokError> {
    let machine = Machine::probe()?;
    let (inner, _) = calibrate(work, CALIBRATION_TARGET_SECS)?;
    let baseline = sample_device_load().map_or(0, |d| d.foreign_resident_mib);
    let mut samples = Vec::new();
    let mut last: Option<RegionSample> = None;
    for _ in 0..MIN_PAIRED_ROUNDS {
        let region = time_region(work, inner)?;
        // Scoped to cells that actually used the card. A host-only region shares
        // no SMs and no device memory bandwidth with a resident foreign process,
        // so voiding it on that process's residency would refuse a measurement
        // nothing had contaminated.
        if region.own_resident_mib > 0
            && region.foreign_resident_mib > baseline + DEVICE_RESIDENCY_TOLERANCE_MIB
        {
            return Err(artifact_err(
                "device exclusivity during measurement",
                &format!("{} MiB foreign resident", region.foreign_resident_mib),
                &format!(
                    "rose above the {baseline} MiB baseline by more than \
                     {DEVICE_RESIDENCY_TOLERANCE_MIB} MiB, so another process landed on the \
                     card mid-measurement"
                ),
                "wait for sibling device work to finish and re-run; absolute device throughput \
                 is not certifiable while another process holds the card",
            ));
        }
        samples.push(region.secs);
        last = Some(region);
    }
    let Some(region) = last else {
        return Err(artifact_err(
            "measured cell",
            label,
            "no timed region completed",
            "check that MIN_PAIRED_ROUNDS is above zero",
        ));
    };
    let regime = if threads > 1 { Regime::Batch } else { Regime::SingleDocument };
    #[allow(clippy::cast_possible_truncation)]
    let doc_bytes = region.unit.bytes as usize;
    Ok(Measurement {
        tokenizer: label.to_owned(),
        version: env!("CARGO_PKG_VERSION").to_owned(),
        vocab: "in-process".to_owned(),
        regime,
        target_tokens: 0,
        doc_bytes,
        docs: 1,
        input_bytes: region.unit.bytes.saturating_mul(u64::from(inner)),
        tokens: region.unit.tokens.saturating_mul(u64::from(inner)),
        stats: RunStats::new(samples)?,
        warmups: 1,
        threads,
        machine: MachineContext {
            physical_cores: machine.physical_cores,
            logical_cores: machine.logical_cores,
            pinned_to_physical: false,
        },
        mean_mhz: region.mean_mhz,
        region_clock: region.region_clock,
        // In-process work is measured against itself, so there is no second
        // implementation to agree with here. Exactness is proved by the parity
        // suites, not by a throughput cell.
        matches_reference: true,
        active: ActiveTime { cpu_secs: region.cpu_secs, device_secs: None },
        foreign_cpu_secs: region.foreign_cpu_secs,
        inner_reps: inner,
    })
}

/// A paired interleaved comparison of two implementations.
#[derive(Debug, Clone, PartialEq)]
pub struct Paired {
    /// First arm's label.
    pub label_a: String,
    /// Second arm's label.
    pub label_b: String,
    /// Per-round seconds per unit of work for arm A, in round order.
    pub a_unit_secs: Vec<f64>,
    /// Per-round seconds per unit of work for arm B, in round order.
    pub b_unit_secs: Vec<f64>,
    /// Per-round A over B. Above 1.0 means B is faster.
    pub speedups: Vec<f64>,
    /// Rounds discarded because foreign device residency rose while they ran.
    pub voided_rounds: u32,
    /// Foreign device residency established before the rounds began.
    pub foreign_resident_baseline_mib: u64,
    /// Highest foreign SM percent observed. Evidence, not a gate.
    pub foreign_sm_percent_max: u32,
    /// Per-round foreign CPU load, in cores' worth of other work, worst arm of
    /// the round. Empty means NOT RECORDED, which is only the case for a pairing
    /// assembled from separate processes by [`Self::from_unit_secs`].
    ///
    /// Recorded because its absence caused a wrong published sign. Two captures
    /// of the same four shapes disagreed on which arm wins cjk, and the cause was
    /// concurrent cargo builds: the device arm is 89 to 97 percent host
    /// orchestration over thousands of small latency-bound driver calls and
    /// degrades under CPU preemption, while the host arm is a throughput-bound
    /// loop that merely needs a core. `time_region` measured this all along and
    /// the paired path discarded it, so a box saturated with rustc was invisible
    /// to an instrument that appeared to be checking for interference.
    pub host_foreign_load: Vec<f64>,
    /// Per-round foreign CPU load for each arm separately, `(a, b)`, in cores'
    /// worth of other work. Empty exactly when [`Self::host_foreign_load`] is.
    ///
    /// Kept beside the max rather than replacing it: the max stays the gated
    /// statistic, but a drift computed over a max of two draws cannot be told
    /// apart from an estimator artifact once the individual readings are gone,
    /// and the reduction at the call site used to discard them.
    pub host_foreign_load_arms: Vec<(f64, f64)>,
    /// One unit's work for each arm, `(a, b)`. `None` only for a cross-process
    /// pairing, which never ran the work itself.
    ///
    /// Pinned because a duration alone cannot tell a genuine speedup from a cell
    /// that quietly stopped doing the work: both read as fast. A count beside
    /// every duration makes a vacuous cell arithmetically impossible instead of
    /// merely unlikely.
    pub unit_work: Option<(WorkUnit, WorkUnit)>,
}

impl Paired {
    /// Median per-round speedup.
    ///
    /// The median, NOT the best, and the distinction is deliberate. An absolute
    /// cell quotes its minimum because contention is strictly additive to
    /// elapsed time, so the fastest observation is the closest estimate of the
    /// uncontended cost. A paired ratio has already cancelled most of a
    /// stationary contaminant, so what is wanted is the typical ratio, and
    /// taking the best ratio would just select the luckiest round.
    #[must_use]
    pub fn median_speedup(&self) -> f64 {
        if self.speedups.is_empty() {
            return 0.0;
        }
        let mut sorted = self.speedups.clone();
        sorted.sort_by(f64::total_cmp);
        let mid = sorted.len() / 2;
        if sorted.len() % 2 == 0 { (sorted[mid - 1] + sorted[mid]) / 2.0 } else { sorted[mid] }
    }

    /// Lowest and highest per-round speedup.
    #[must_use]
    pub fn speedup_range(&self) -> (f64, f64) {
        let mut lo = f64::INFINITY;
        let mut hi = f64::NEG_INFINITY;
        for s in &self.speedups {
            lo = lo.min(*s);
            hi = hi.max(*s);
        }
        if self.speedups.is_empty() { (0.0, 0.0) } else { (lo, hi) }
    }

    /// Relative standard deviation of the per-round speedups.
    #[must_use]
    pub fn speedup_rel_stddev(&self) -> f64 {
        if self.speedups.len() < 2 {
            return 0.0;
        }
        #[allow(clippy::cast_precision_loss)]
        let n = self.speedups.len() as f64;
        let mean = self.speedups.iter().sum::<f64>() / n;
        if mean <= 0.0 {
            return 0.0;
        }
        let variance = self.speedups.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / (n - 1.0);
        variance.sqrt() / mean
    }

    /// Median per-round host load, in cores' worth of foreign work.
    ///
    /// `None` when host load was not recorded, which is the cross-process case.
    /// Reported as EVIDENCE and never gated on the level: an evenly loaded box
    /// still yields a valid ratio because the contaminant sits in both arms.
    #[must_use]
    pub fn median_host_load(&self) -> Option<f64> {
        if self.host_foreign_load.is_empty() {
            return None;
        }
        let mut sorted = self.host_foreign_load.clone();
        sorted.sort_by(f64::total_cmp);
        let mid = sorted.len() / 2;
        Some(if sorted.len() % 2 == 0 {
            (sorted[mid - 1] + sorted[mid]) / 2.0
        } else {
            sorted[mid]
        })
    }

    /// Relative spread of per-round host load, the stationarity statistic.
    ///
    /// This is the gated quantity, not the level, because a paired ratio only
    /// cancels a contaminant that is present in both arms of every round.
    /// `None` when host load was not recorded.
    #[must_use]
    pub fn host_load_rel_stddev(&self) -> Option<f64> {
        if self.host_foreign_load.len() < 2 {
            return None;
        }
        #[allow(clippy::cast_precision_loss)]
        let n = self.host_foreign_load.len() as f64;
        let mean = self.host_foreign_load.iter().sum::<f64>() / n;
        // A genuinely idle box reads a mean at or near zero, where a relative
        // spread is meaningless rather than infinite. Idle is maximally
        // stationary, so report no drift instead of dividing.
        if mean <= 1e-6 {
            return Some(0.0);
        }
        let variance =
            self.host_foreign_load.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / (n - 1.0);
        Some(variance.sqrt() / mean)
    }

    /// Whether the paired delta is tight enough to publish.
    ///
    /// Gated on the SPREAD of the per-round deltas, exactly as an absolute cell
    /// is gated on [`MAX_PUBLISHABLE_REL_STDDEV`]. A wide delta spread is not a
    /// small effect, it is an uncontrolled one, and reporting it as a small win
    /// would be the worst available outcome.
    ///
    /// Also gated on host-load STATIONARITY, because the spread gate above is
    /// blind to it. A paired ratio cancels a contaminant present in both arms of
    /// every round; load that arrives or leaves mid-comparison does not cancel
    /// and biases whichever arm it landed on. Two captures that each passed the
    /// spread gate disagreed on which arm wins cjk for exactly this reason. The
    /// LEVEL is deliberately not gated: an evenly loaded box still yields a valid
    /// ratio, so refusing on level would refuse work this estimator exists to do.
    #[must_use]
    pub fn is_publishable(&self) -> bool {
        #[allow(clippy::cast_possible_truncation)]
        let rounds = self.speedups.len() as u32;
        // An unrecorded host load cannot clear a gate it was never measured for,
        // so it does not block publication here; `render` discloses it instead.
        let stationary = self
            .host_load_rel_stddev()
            .is_none_or(|drift| drift <= MAX_PAIRED_HOST_LOAD_DRIFT);
        rounds >= MIN_PAIRED_ROUNDS
            && self.speedup_rel_stddev() <= MAX_PUBLISHABLE_REL_STDDEV
            && stationary
    }

    /// Pair per-unit seconds measured in SEPARATE processes.
    ///
    /// Some arms cannot coexist in one address space: when the change lives
    /// inside a production code path, the "before" arm only exists in a binary
    /// compiled before the edit, and making both reachable at runtime would mean
    /// leaving a switch through that path as scaffolding. Alternating whole runs
    /// A,B,A,B is then the honest option, and this constructor exists so that
    /// case reuses the same estimator and the same publication gate as the
    /// in-process path instead of hand-rolling the statistics a second time.
    ///
    /// Feed it the per-unit seconds each build reported from its own
    /// [`measure_cell`], in alternation order, so index `i` of each slice is the
    /// same round. Pairing adjacent rounds is what cancels slow drift; comparing
    /// two independently averaged cells does not.
    ///
    /// # Errors
    ///
    /// Refuses unequal or short slices, and any non-finite or non-positive
    /// timing, rather than producing a ratio from a value that cannot be one.
    pub fn from_unit_secs(
        label_a: &str,
        label_b: &str,
        a_unit_secs: &[f64],
        b_unit_secs: &[f64],
        foreign_resident_baseline_mib: u64,
        foreign_sm_percent_max: u32,
    ) -> Result<Self, ExatokError> {
        if a_unit_secs.len() != b_unit_secs.len() {
            return Err(artifact_err(
                "paired rounds",
                &format!("{} A rounds against {} B rounds", a_unit_secs.len(), b_unit_secs.len()),
                "the arms must alternate, so round i of each is the same round",
                "emit one timing per arm per round and pass them in alternation order",
            ));
        }
        #[allow(clippy::cast_possible_truncation)]
        let rounds = a_unit_secs.len() as u32;
        if rounds < MIN_PAIRED_ROUNDS {
            return Err(artifact_err(
                "paired comparison rounds",
                &format!("{rounds} rounds"),
                "too few rounds to establish a delta spread against a bursty contaminant",
                &format!("run at least {MIN_PAIRED_ROUNDS} alternating rounds per arm"),
            ));
        }
        for (i, secs) in a_unit_secs.iter().chain(b_unit_secs).enumerate() {
            if !secs.is_finite() || *secs <= 0.0 {
                return Err(artifact_err(
                    "paired round timing",
                    &format!("value {i} is {secs}"),
                    "a per-unit time must be finite and positive to form a ratio",
                    "check that the emitting build divided its region by the inner \
                     iteration count and reported a real unit count",
                ));
            }
        }
        let speedups = a_unit_secs
            .iter()
            .zip(b_unit_secs)
            .map(|(a, b)| a / b)
            .collect();
        Ok(Self {
            label_a: label_a.to_owned(),
            label_b: label_b.to_owned(),
            a_unit_secs: a_unit_secs.to_vec(),
            b_unit_secs: b_unit_secs.to_vec(),
            speedups,
            voided_rounds: 0,
            foreign_resident_baseline_mib,
            foreign_sm_percent_max,
            // Separate processes, so no region probe exists to copy. Left empty
            // deliberately, and rendered as NOT RECORDED rather than as zero: a
            // missing contaminant reading must never read as a quiet machine.
            host_foreign_load: Vec::new(),
            host_foreign_load_arms: Vec::new(),
            // No work ran in this process, so there is no count to pin.
            unit_work: None,
        })
    }

    /// Human-readable summary, absolute figures first and never a bare ratio.
    #[must_use]
    pub fn render(&self) -> String {
        let (lo, hi) = self.speedup_range();
        let mut s = String::new();
        s.push_str(&format!("paired: {} against {}\n", self.label_a, self.label_b));
        s.push_str(&format!(
            "rounds            : {} interleaved, {} voided for device contention\n",
            self.speedups.len(),
            self.voided_rounds
        ));
        let a_best = self.a_unit_secs.iter().copied().fold(f64::INFINITY, f64::min);
        let b_best = self.b_unit_secs.iter().copied().fold(f64::INFINITY, f64::min);
        s.push_str(&format!(
            "best per unit     : {a_best:.9} s ({}), {b_best:.9} s ({})\n",
            self.label_a, self.label_b
        ));
        match self.unit_work {
            Some((ua, ub)) => s.push_str(&format!(
                "work per unit     : {} B, {} tokens ({}); {} B, {} tokens ({})\n",
                ua.bytes, ua.tokens, self.label_a, ub.bytes, ub.tokens, self.label_b
            )),
            None => s.push_str(
                "work per unit     : NOT RECORDED (a cross-process pairing ran no work here)\n",
            ),
        }
        s.push_str(&format!(
            "median speedup    : {:.4}x  (range {lo:.4}x to {hi:.4}x, rel stddev {:.4})\n",
            self.median_speedup(),
            self.speedup_rel_stddev()
        ));
        // A bare ratio is the single most invertible number this harness prints, so name the
        // faster arm outright. speedups are a_unit/b_unit, so above 1.0 arm B is the quicker one.
        let ratio = self.median_speedup();
        let (faster, factor) = if ratio >= 1.0 {
            (&self.label_b, ratio)
        } else {
            (&self.label_a, 1.0 / ratio)
        };
        s.push_str(&format!(
            "faster arm        : {faster} by {factor:.4}x  (ratio is {}_secs/{}_secs)\n",
            self.label_a, self.label_b
        ));
        s.push_str(&format!(
            "foreign device    : {} MiB resident baseline, peak {}% SM (evidence, not gated)\n",
            self.foreign_resident_baseline_mib, self.foreign_sm_percent_max
        ));
        match (self.median_host_load(), self.host_load_rel_stddev()) {
            (Some(level), Some(drift)) => s.push_str(&format!(
                "host load         : {level:.2} cores foreign (median), drift {drift:.4} \
                 (gated at {MAX_PAIRED_HOST_LOAD_DRIFT:.2})\n"
            )),
            _ => s.push_str(
                "host load         : NOT RECORDED (cross-process pairing; absence is not a \
                 quiet machine)\n",
            ),
        }
        if self.is_publishable() {
            s.push_str("verdict           : publishable\n");
        } else {
            let drift = self
                .host_load_rel_stddev()
                .map_or_else(|| "n/a".to_owned(), |d| format!("{d:.4}"));
            s.push_str(&format!(
                "verdict           : NOT publishable; needs {MIN_PAIRED_ROUNDS} rounds, delta \
                 spread at or under {MAX_PUBLISHABLE_REL_STDDEV:.2} (got {:.4}) and host-load \
                 drift at or under {MAX_PAIRED_HOST_LOAD_DRIFT:.2} (got {drift})\n",
                self.speedup_rel_stddev()
            ));
        }
        s
    }
}

/// Compare two implementations with interleaved paired rounds.
///
/// Runs A, B, A, B rather than all of A then all of B. Interleaving is the
/// whole point on a contended machine: a slow drift or a steady foreign load
/// affects adjacent arms nearly equally and largely cancels in the ratio,
/// whereas sequential blocks attribute the drift to the change under test.
///
/// Each arm is calibrated independently and compared per UNIT of work, so a
/// faster arm does not silently undershoot the timed-region floor.
///
/// A round whose foreign device residency rose above the established baseline is
/// VOIDED and retried up to [`MAX_VOIDED_ROUND_RETRIES`] times, because a
/// sibling landing inside one arm biases that round and does not cancel.
///
/// # Errors
///
/// Returns [`ExatokError::Artifact`] when `rounds` is below
/// [`MIN_PAIRED_ROUNDS`], or when a round could not be completed cleanly within
/// the retry budget, reporting the observed foreign residency rather than
/// emitting a contaminated number. Propagates whatever either arm returns.
pub fn compare_cells(a: Arm<'_>, b: Arm<'_>, rounds: u32) -> Result<Paired, ExatokError> {
    compare_cells_at(a, b, rounds, CALIBRATION_TARGET_SECS)
}

/// [`compare_cells`] with an explicit calibration target.
///
/// Separated so the estimator's own tests can run the identical protocol over
/// much shorter regions: a test asserting that self-comparison reads 1.0x or
/// that a real two-fold difference is detected is testing the estimator, not a
/// publishable figure, and the half-second region floor exists only for the
/// latter. Private because a caller measuring for publication must not get to
/// shorten the region its number will be read against.
fn compare_cells_at(
    a: Arm<'_>,
    b: Arm<'_>,
    rounds: u32,
    target_secs: f64,
) -> Result<Paired, ExatokError> {
    if rounds < MIN_PAIRED_ROUNDS {
        return Err(artifact_err(
            "paired comparison rounds",
            &rounds.to_string(),
            &format!("below the {MIN_PAIRED_ROUNDS} needed for the spread to mean anything"),
            "raise rounds to at least MIN_PAIRED_ROUNDS",
        ));
    }
    let label_a = a.label.to_owned();
    let label_b = b.label.to_owned();
    let work_a = a.work;
    let work_b = b.work;
    let (inner_a, _) = calibrate(work_a, target_secs)?;
    let (inner_b, _) = calibrate(work_b, target_secs)?;
    let baseline = sample_device_load().map_or(0, |d| d.foreign_resident_mib);
    let ceiling = baseline + DEVICE_RESIDENCY_TOLERANCE_MIB;

    let mut out = Paired {
        label_a,
        label_b,
        a_unit_secs: Vec::new(),
        b_unit_secs: Vec::new(),
        speedups: Vec::new(),
        voided_rounds: 0,
        foreign_resident_baseline_mib: baseline,
        foreign_sm_percent_max: 0,
        host_foreign_load: Vec::new(),
        host_foreign_load_arms: Vec::new(),
        unit_work: None,
    };
    for round in 0..rounds {
        let mut attempt = 0;
        loop {
            let ra = time_region(work_a, inner_a)?;
            let rb = time_region(work_b, inner_b)?;
            let on_device = ra.own_resident_mib > 0 || rb.own_resident_mib > 0;
            let worst = ra.foreign_resident_mib.max(rb.foreign_resident_mib);
            out.foreign_sm_percent_max =
                out.foreign_sm_percent_max.max(ra.foreign_sm_percent).max(rb.foreign_sm_percent);
            if !on_device || worst <= ceiling {
                let a_unit = ra.secs / f64::from(inner_a);
                let b_unit = rb.secs / f64::from(inner_b);
                out.a_unit_secs.push(a_unit);
                out.b_unit_secs.push(b_unit);
                // Worst arm of the round. The arms are unequally sensitive to CPU
                // preemption, so the quieter reading would understate what biased
                // the ratio.
                let load_a = ra.foreign_cpu_secs / ra.secs.max(1e-9);
                let load_b = rb.foreign_cpu_secs / rb.secs.max(1e-9);
                let host_load = load_a.max(load_b);
                out.host_foreign_load.push(host_load);
                out.host_foreign_load_arms.push((load_a, load_b));
                // Pinned so no duration stands in a report without the count that
                // produced it, and refused on disagreement: a unit count that moves
                // between rounds means the arms stopped doing identical work, which
                // a single ratio cannot express.
                match out.unit_work {
                    None => {
                        if ra.unit.bytes == 0 || rb.unit.bytes == 0 {
                            return Err(artifact_err(
                                "paired unit work",
                                &format!("{} B against {} B", ra.unit.bytes, rb.unit.bytes),
                                "an arm consumed no input, so its duration measures nothing",
                                "give both arms real input before comparing them",
                            ));
                        }
                        out.unit_work = Some((ra.unit, rb.unit));
                    }
                    Some((pin_a, pin_b)) => {
                        if pin_a != ra.unit || pin_b != rb.unit {
                            return Err(artifact_err(
                                "paired unit work",
                                &format!(
                                    "round {round} did {} B/{} tok against {} B/{} tok, pinned at \
                                     {} B/{} tok against {} B/{} tok",
                                    ra.unit.bytes,
                                    ra.unit.tokens,
                                    rb.unit.bytes,
                                    rb.unit.tokens,
                                    pin_a.bytes,
                                    pin_a.tokens,
                                    pin_b.bytes,
                                    pin_b.tokens
                                ),
                                "the work changed between rounds, so the ratio compares two \
                                 different quantities",
                                "make both arms process the same input every round",
                            ));
                        }
                    }
                }
                out.speedups.push(if b_unit > 0.0 { a_unit / b_unit } else { 0.0 });
                break;
            }
            out.voided_rounds += 1;
            attempt += 1;
            if attempt > MAX_VOIDED_ROUND_RETRIES {
                return Err(artifact_err(
                    "clean paired round",
                    &format!("round {} of {rounds}", round + 1),
                    &format!(
                        "foreign device residency reached {worst} MiB against a {baseline} MiB \
                         baseline across {} attempts, so every attempt was contaminated",
                        MAX_VOIDED_ROUND_RETRIES + 1
                    ),
                    "wait for sibling device work to finish; a paired delta measured through \
                     another process's residency is not publishable",
                ));
            }
        }
    }
    Ok(out)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    /// Calibration target for the paired-estimator tests.
    ///
    /// The estimator's contract (per-unit ratios, interleaving, the work pin,
    /// the per-arm load series) is independent of region length, and the full
    /// [`CALIBRATION_TARGET_SECS`] floor exists so a PUBLISHED figure clears
    /// [`MIN_TRUSTWORTHY_TIMED_SECS`], which no estimator test asserts. A
    /// tenth of a second keeps each test at a few seconds of device-lock time
    /// while staying long enough that a scheduler preemption landing inside
    /// one region moves that round's ratio by a few percent rather than
    /// doubling it: at twenty milliseconds a single preemption outlasts the
    /// whole region and the median of eight rounds visibly drifted under a
    /// loaded machine.
    const TEST_REGION_SECS: f64 = 0.1;

    fn measurement(mb_s: f64, threads: usize, doc_bytes: usize) -> Measurement {
        // Choose input_bytes and wall time so mb_per_second is exactly mb_s.
        let secs = 0.5_f64;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let input_bytes = (mb_s * BYTES_PER_MB * secs) as u64;
        Measurement {
            tokenizer: "probe".to_owned(),
            version: "0".to_owned(),
            vocab: "cl100k_base".to_owned(),
            regime: Regime::Batch,
            target_tokens: 1024,
            doc_bytes,
            docs: 1,
            input_bytes,
            tokens: input_bytes / 4,
            stats: RunStats::new(vec![secs]).unwrap(),
            warmups: 1,
            threads,
            machine: MachineContext {
                physical_cores: 16,
                logical_cores: 32,
                pinned_to_physical: true,
            },
            mean_mhz: 5000.0,
            // A steady region clock: the default cell is not clock-biased, so a
            // test that wants drift sets it explicitly.
            region_clock: Some(RegionClock { start_mhz: 5000.0, end_mhz: 5000.0, busy_cpus: 16 }),
            matches_reference: true,
            // A fully-honoured parallel run: every requested thread busy for
            // the whole wall window, so achieved_parallelism equals `threads`
            // and the parallelism check passes. Tests that want an unhonoured
            // request build it explicitly rather than inheriting it here.
            #[allow(clippy::cast_precision_loss)]
            active: ActiveTime { cpu_secs: secs * threads as f64, device_secs: None },
            // An exclusive machine: nothing else consumed CPU while this cell
            // ran. Tests that want contention set it explicitly.
            foreign_cpu_secs: 0.0,
            inner_reps: 1,
        }
    }

    /// Locks the published-baseline defect out of our own harness: a 0.94 MB/s
    /// single-thread figure on a large document is the exact number BlockBPE
    /// and GPUTOK compared against, and it is a measurement artifact, not a
    /// tokenizer speed. If this stops flagging, the harness can silently
    /// publish a 40x measurement error as a speedup.
    #[test]
    fn published_094_mb_s_baseline_is_flagged_as_a_defect() {
        let m = measurement(0.94, 1, 65_536);
        match assess_plausibility(&m) {
            Plausibility::SuspectedMeasurementDefect {
                observed_mb_s_per_core,
                floor_mb_s_per_core,
            } => {
                assert!((observed_mb_s_per_core - 0.94).abs() < 1e-6);
                assert!((floor_mb_s_per_core - 5.0).abs() < 1e-12);
            }
            other => panic!("0.94 MB/s on a 64 KiB document must be a defect, got {other:?}"),
        }
    }

    /// Real correctly measured tiktoken on one core of this machine is about
    /// 37 MB/s. If the floor ever rises above real single-core throughput the
    /// harness would reject every honest measurement, which is worse than the
    /// defect it guards against.
    #[test]
    fn real_single_core_tiktoken_throughput_is_plausible() {
        assert_eq!(assess_plausibility(&measurement(36.9, 1, 65_536)), Plausibility::Plausible);
    }

    /// Small documents are genuinely dispatch-bound: 2-byte inputs measure
    /// about 4.4 MB/s on real tiktoken because per-call cost dominates. That
    /// is a real property of the regime, so the floor must not apply and the
    /// row must not be branded a defect.
    #[test]
    fn small_documents_are_per_call_bound_not_defects() {
        assert_eq!(assess_plausibility(&measurement(4.4, 1, 2)), Plausibility::PerCallBound);
        assert_eq!(
            assess_plausibility(&measurement(4.4, 1, AMORTIZED_DOC_BYTES - 1)),
            Plausibility::PerCallBound
        );
    }

    /// The floor is per physical core, not absolute and not per thread.
    ///
    /// A 16-thread run at 60 MB/s is 3.75 MB/s per core and is broken even
    /// though 60 looks healthy; gigatoken's real 2339 MB/s on 16 threads is 146
    /// per core and is fine. Without the division a wide-but-broken run passes.
    #[test]
    fn floor_is_applied_per_core_not_absolute() {
        assert!(matches!(
            assess_plausibility(&measurement(60.0, 16, 65_536)),
            Plausibility::SuspectedMeasurementDefect { .. }
        ));
        assert_eq!(
            assess_plausibility(&measurement(2339.0, 16, 65_536)),
            Plausibility::Plausible
        );
    }

    /// The divisor saturates at physical cores, so correct SMT scaling is not
    /// reported as a defect.
    ///
    /// This is the regression that made the first full sweep unusable: 32
    /// threads on 16 physical cores divided by 32 flagged 25 cells, most of
    /// which were correct. A cell running 32 threads at 120 MB/s is 7.5 MB/s
    /// per core (above the floor) but 3.75 per thread (below it). Dividing by
    /// threads would call the hardware's own topology a measurement error.
    #[test]
    fn smt_oversubscription_divides_by_cores_not_threads() {
        let m = measurement(120.0, 32, 65_536);
        assert_eq!(m.machine.physical_cores, 16);
        assert!((m.mb_per_second_per_core() - 7.5).abs() < 1e-9);
        assert!((m.mb_per_second_per_thread() - 3.75).abs() < 1e-9);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// A timed region shorter than the minimum is a harness bug, and it is
    /// caught before the floor so its throughput is never trusted.
    ///
    /// The real defect: batch cells completing in 19 ms recorded gigatoken at
    /// 4.04x parallelism on 16 pinned cores, which is rayon pool startup
    /// charged to the tokenizer. Reporting that as a scaling limit would have
    /// understated the CPU baseline we must beat, flattering exatok.
    #[test]
    fn a_timed_region_too_short_to_trust_is_a_harness_defect() {
        let mut m = measurement(800.0, 16, 65_536);
        m.stats = RunStats::new(vec![0.019]).unwrap();
        match assess_plausibility(&m) {
            Plausibility::ShortTimedRegion { timed_secs, minimum_secs } => {
                assert!((timed_secs - 0.019).abs() < 1e-12);
                assert!((minimum_secs - MIN_TRUSTWORTHY_TIMED_SECS).abs() < 1e-12);
            }
            other => panic!("a 19 ms timed region must be a harness defect, got {other:?}"),
        }
        assert!(assess_plausibility(&m).is_harness_defect());
        assert!(!assess_plausibility(&m).is_publishable());
        // Exactly at the minimum is trusted: the comparison is inclusive.
        m.stats = RunStats::new(vec![MIN_TRUSTWORTHY_TIMED_SECS]).unwrap();
        assert!(!assess_plausibility(&m).is_harness_defect());
    }

    /// A thread count in the table is a claim about how the work ran. A
    /// 16-thread cell that consumed one thread's worth of CPU time did not run
    /// the way the row says, and its per-core figure is meaningless.
    #[test]
    fn a_thread_request_that_was_not_delivered_is_a_harness_defect() {
        let mut m = measurement(400.0, 16, 65_536);
        // 0.5 s wall, 0.5 CPU-seconds: one thread did all the work.
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: None };
        match assess_plausibility(&m) {
            Plausibility::ThreadsNotHonoured { requested, achieved_parallelism } => {
                assert_eq!(requested, 16);
                assert!((achieved_parallelism - 1.0).abs() < 1e-9);
            }
            other => panic!("16 threads at 1x parallelism must be a defect, got {other:?}"),
        }
        // Half the requested threads is the accepted boundary.
        m.active = ActiveTime { cpu_secs: 0.5 * 8.0, device_secs: None };
        assert!(!assess_plausibility(&m).is_harness_defect());
        m.active = ActiveTime { cpu_secs: 0.5 * 7.9, device_secs: None };
        assert!(assess_plausibility(&m).is_harness_defect());
    }

    /// An oversubscribed request is exempt from the parallelism check, because
    /// 32 threads on 16 cores cannot reach 32x. Without the exemption every
    /// SMT cell would be labelled a harness bug.
    #[test]
    fn oversubscribed_requests_are_exempt_from_the_parallelism_check() {
        let mut m = measurement(120.0, 32, 65_536);
        // 17.4x on 16 physical cores is what SMT actually delivers here.
        m.active = ActiveTime { cpu_secs: 0.5 * 17.4, device_secs: None };
        assert!(!assess_plausibility(&m).is_harness_defect());
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// A pinned single-threaded cell that lost part of its core is a
    /// mismeasurement, not a slow tokenizer.
    ///
    /// This is the one that protects the comparison's honesty. A contended
    /// baseline run reports the CPU competitor as slower than it is, and a GPU
    /// number divided by an understated baseline is the exact defect this whole
    /// harness exists to avoid reproducing. Several agents were running test
    /// suites on this machine while the sweep ran, so the condition is real
    /// here rather than hypothetical.
    #[test]
    fn a_contended_single_thread_cell_is_a_harness_defect_not_a_slow_library() {
        let mut m = measurement(19.0, 1, 65_536);
        // 0.5 s wall but only 0.35 CPU-seconds: 30% of the core went elsewhere.
        m.active = ActiveTime { cpu_secs: 0.35, device_secs: None };
        match assess_plausibility(&m) {
            Plausibility::Contended { achieved_parallelism, minimum_efficiency } => {
                assert!((achieved_parallelism - 0.7).abs() < 1e-9);
                assert!((minimum_efficiency - MIN_SINGLE_THREAD_EFFICIENCY).abs() < 1e-12);
            }
            other => panic!("0.7x of one pinned core must be contention, got {other:?}"),
        }
        assert!(assess_plausibility(&m).is_harness_defect());
        // An exclusive core passes, and the boundary is inclusive at 0.9.
        m.active = ActiveTime { cpu_secs: 0.5 * MIN_SINGLE_THREAD_EFFICIENCY, device_secs: None };
        assert!(!assess_plausibility(&m).is_harness_defect());
        m.active = ActiveTime { cpu_secs: 0.5 * 0.89, device_secs: None };
        assert!(assess_plausibility(&m).is_harness_defect());
        // Full exclusivity is the normal case and must not be flagged.
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: None };
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// Locks out the defect that made the exclusivity claim unenforceable: the
    /// driver measured foreign CPU per cell and this side dropped the field, so
    /// a cell starved by an SMT sibling or a bandwidth hog was published as a
    /// slow tokenizer. The pinned-core ratio cannot see it, which this test
    /// pins by asserting that ratio is a clean 1.0 on a voided cell.
    #[test]
    fn foreign_cpu_load_voids_a_cell_that_kept_its_own_core() {
        let mut m = measurement(36.9, 1, 65_536);
        // 0.10 CPU-seconds elsewhere during a 0.5 s region: 0.2x of one core.
        m.foreign_cpu_secs = 0.5 * 0.20;
        // The old gate sees nothing wrong: this cell held its whole pinned CPU.
        assert!((m.achieved_parallelism() - 1.0).abs() < 1e-12);
        assert!((m.foreign_load_ratio() - 0.20).abs() < 1e-12);
        match assess_plausibility(&m) {
            Plausibility::ForeignLoad { foreign_load_ratio, maximum_ratio } => {
                assert!((foreign_load_ratio - 0.20).abs() < 1e-12);
                assert!((maximum_ratio - MAX_FOREIGN_LOAD_RATIO).abs() < 1e-12);
            }
            other => panic!("0.2x of a core stolen elsewhere must void the cell, got {other:?}"),
        }
        assert!(assess_plausibility(&m).is_harness_defect());
        assert!(!assess_plausibility(&m).is_publishable());
    }

    /// The negative twin of the gate above. Without this, a gate that voided
    /// every cell regardless of load would pass its positive test and silently
    /// refuse an honest sweep, which is the same unpublishable outcome by the
    /// opposite route.
    #[test]
    fn an_idle_machine_publishes_the_same_cell_the_foreign_gate_voids() {
        let mut m = measurement(36.9, 1, 65_536);
        m.foreign_cpu_secs = 0.0;
        assert!((m.foreign_load_ratio() - 0.0).abs() < 1e-12);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
        // A machine is never perfectly quiet: load under the threshold still
        // publishes, or no real sweep could ever report a number.
        m.foreign_cpu_secs = 0.5 * 0.04;
        assert!((m.foreign_load_ratio() - 0.04).abs() < 1e-12);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// The threshold is inclusive: exactly [`MAX_FOREIGN_LOAD_RATIO`] passes
    /// and anything above it fails. Locks out an off-by-one comparison that
    /// would either void every cell on a normally-noisy box or let a cell one
    /// increment over the documented limit through.
    #[test]
    fn the_foreign_load_gate_boundary_is_exact_and_inclusive() {
        let mut m = measurement(36.9, 1, 65_536);
        // Dividing by 0.5 is exact in binary, so this ratio is exactly the
        // constant rather than approximately it.
        m.foreign_cpu_secs = 0.5 * MAX_FOREIGN_LOAD_RATIO;
        assert!((m.foreign_load_ratio() - MAX_FOREIGN_LOAD_RATIO).abs() < 1e-15);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
        m.foreign_cpu_secs = 0.5 * 0.06;
        match assess_plausibility(&m) {
            Plausibility::ForeignLoad { foreign_load_ratio, maximum_ratio } => {
                assert!((foreign_load_ratio - 0.06).abs() < 1e-12);
                assert!((maximum_ratio - MAX_FOREIGN_LOAD_RATIO).abs() < 1e-12);
            }
            other => panic!("0.06x is over the {MAX_FOREIGN_LOAD_RATIO} limit, got {other:?}"),
        }
    }

    /// A voided cell must be refused rather than published with a footnote.
    /// Locks out the shape this defect actually shipped in: the contention
    /// evidence existed per cell, in a note the record parser is documented to
    /// ignore, so the table printed the depressed number and its clean bill of
    /// health side by side.
    #[test]
    fn a_cell_voided_for_foreign_load_cannot_reach_a_published_table() {
        let mut m = measurement(36.9, 1, 65_536);
        m.foreign_cpu_secs = 0.5 * 0.30;
        let r = report_with(vec![Availability::Measured(m)]);
        assert_eq!(r.harness_defects().len(), 1);
        let text = r.render_table();
        assert!(text.contains("MACHINE NOT EXCLUSIVE"), "{text}");
        assert!(text.contains("HARNESS DEFECT"), "{text}");
        // The diagnosis has to carry the number that voided the cell.
        assert!(text.contains("0.300x of one core"), "{text}");
        // And the all-clear must not appear beside it.
        assert!(!text.contains("harness: every cell timed at least"), "{text}");
    }

    /// Locks out a published misdiagnosis, not just a missing gate. Eight
    /// 16-thread cells were refused for failing the parallel-efficiency gate
    /// and reported as a `taskset`/`RAYON_NUM_THREADS` bug, when the cause was
    /// foreign load: contention depresses achieved parallelism too, so the
    /// thread gate fires on a starved cell and names the wrong culprit. The
    /// foreign check must therefore be reached first.
    #[test]
    fn foreign_load_outranks_the_thread_gate_on_a_starved_parallel_cell() {
        let mut m = measurement(60.0, 16, 65_536);
        // 16 threads delivering only 4x, which the thread gate rejects.
        m.active = ActiveTime { cpu_secs: 0.5 * 4.0, device_secs: None };
        assert!((m.achieved_parallelism() - 4.0).abs() < 1e-12);
        // With no foreign load recorded, that is genuinely a thread-delivery
        // bug and must still be reported as one.
        match assess_plausibility(&m) {
            Plausibility::ThreadsNotHonoured { requested, achieved_parallelism } => {
                assert_eq!(requested, 16);
                assert!((achieved_parallelism - 4.0).abs() < 1e-12);
            }
            other => panic!("an idle machine delivering 4 of 16 threads is a thread bug: {other:?}"),
        }
        // The same numbers with 3x of a core burned elsewhere are a contended
        // machine, and attributing them to thread delivery is the defect.
        m.foreign_cpu_secs = 0.5 * 3.0;
        match assess_plausibility(&m) {
            Plausibility::ForeignLoad { foreign_load_ratio, maximum_ratio } => {
                assert!((foreign_load_ratio - 3.0).abs() < 1e-12);
                assert!((maximum_ratio - MAX_FOREIGN_LOAD_RATIO).abs() < 1e-12);
            }
            other => panic!("a starved parallel cell must not be filed as a thread bug: {other:?}"),
        }
    }

    /// Every flagged verdict must carry a diagnosis, and every clean verdict
    /// must carry none.
    ///
    /// Locks out the wildcard match arm this replaced, which rendered any
    /// unhandled variant as the literal string "unclassified". A flag with no
    /// explanation is worse than no flag: it tells a reader something is wrong
    /// without telling them what, so it gets ignored.
    #[test]
    fn every_flagged_verdict_explains_itself_and_clean_ones_stay_silent() {
        let flagged = [
            Plausibility::ShortTimedRegion { timed_secs: 0.019, minimum_secs: 0.25 },
            Plausibility::ThreadsNotHonoured { requested: 16, achieved_parallelism: 1.0 },
            Plausibility::Contended { achieved_parallelism: 0.7, minimum_efficiency: 0.9 },
            Plausibility::ForeignLoad { foreign_load_ratio: 0.3, maximum_ratio: 0.05 },
            Plausibility::SuspectedMeasurementDefect {
                observed_mb_s_per_core: 3.183,
                floor_mb_s_per_core: 5.0,
            },
            Plausibility::KnownSlowLibrary { observed_mb_s_per_core: 4.6, reason: "measured" },
            Plausibility::EstimatorDependent { rel_stddev: 0.31, maximum_rel_stddev: 0.20 },
            Plausibility::DeviceStarved { device_utilization: 0.08, minimum_utilization: 0.25 },
        ];
        for v in flagged {
            let d = v.diagnosis().unwrap_or_else(|| panic!("{v:?} must explain itself"));
            assert!(!d.is_empty(), "{v:?}");
            assert!(!d.contains("unclassified"), "{v:?} fell through to a wildcard: {d}");
            assert!(!v.table_flag().is_empty(), "{v:?} must be marked in the table");
        }
        for v in [Plausibility::Plausible, Plausibility::PerCallBound] {
            assert_eq!(v.diagnosis(), None, "{v:?}");
            assert_eq!(v.table_flag(), "", "{v:?}");
        }
    }

    /// The table flag must distinguish a harness bug from a library result, in
    /// the rendered text and not only in the type.
    ///
    /// A reader scanning the table decides what to trust from this marker. If
    /// contention and a genuinely slow library rendered the same way, the
    /// contended row would be read as a real measurement.
    #[test]
    fn table_flags_separate_harness_bugs_from_library_results() {
        for v in [
            Plausibility::ShortTimedRegion { timed_secs: 0.019, minimum_secs: 0.25 },
            Plausibility::ThreadsNotHonoured { requested: 16, achieved_parallelism: 1.0 },
            Plausibility::Contended { achieved_parallelism: 0.7, minimum_efficiency: 0.9 },
            Plausibility::ForeignLoad { foreign_load_ratio: 0.3, maximum_ratio: 0.05 },
            Plausibility::EstimatorDependent { rel_stddev: 0.31, maximum_rel_stddev: 0.20 },
            Plausibility::DeviceStarved { device_utilization: 0.08, minimum_utilization: 0.25 },
        ] {
            assert!(v.table_flag().contains("HARNESS"), "{v:?} -> {}", v.table_flag());
            assert!(v.is_harness_defect(), "{v:?}");
            assert!(!v.is_publishable(), "{v:?}");
        }
        for v in [
            Plausibility::SuspectedMeasurementDefect {
                observed_mb_s_per_core: 3.0,
                floor_mb_s_per_core: 5.0,
            },
            Plausibility::KnownSlowLibrary { observed_mb_s_per_core: 4.6, reason: "measured" },
        ] {
            assert!(!v.table_flag().contains("HARNESS"), "{v:?} -> {}", v.table_flag());
            assert!(!v.is_harness_defect(), "{v:?}");
            assert!(v.is_publishable(), "{v:?}");
        }
    }

    /// A device cell contended by another process's kernels must not publish,
    /// even though every CPU-side gate reads perfectly clean on it.
    ///
    /// This is the gap the CPU gates cannot see. Foreign load, both
    /// parallelism ratios and the per-core floor all read CPU counters, and a
    /// cell queued behind a foreign kernel has an IDLE CPU: it keeps its core,
    /// consumes no foreign CPU time, and delivers its threads. Only wall time
    /// inflates. Without this gate such a cell reaches the table as
    /// `Plausible`, which is how a contended device number gets published as a
    /// measurement.
    #[test]
    fn a_contended_device_cell_cannot_publish_though_every_cpu_gate_is_clean() {
        let mut m = measurement(36.9, 1, 65_536);
        // 0.5 s wall, the device busy for 0.0625 s of it: 12.5% utilization.
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: Some(0.0625) };
        m.foreign_cpu_secs = 0.0;
        // Every CPU-side signal is spotless, which is the point of the test.
        assert!((m.achieved_parallelism() - 1.0).abs() < 1e-15);
        assert!((m.foreign_load_ratio() - 0.0).abs() < 1e-15);
        assert!((m.device_utilization().unwrap_or(0.0) - 0.125).abs() < 1e-15);
        match assess_plausibility(&m) {
            Plausibility::DeviceStarved { device_utilization, minimum_utilization } => {
                assert!((device_utilization - 0.125).abs() < 1e-15);
                assert!((minimum_utilization - MIN_DEVICE_UTILIZATION).abs() < 1e-15);
            }
            other => panic!("a device idle for 87.5% of the window must void the cell: {other:?}"),
        }
    }

    /// An exclusive device cell publishes the same shape the starvation gate
    /// voids, so the gate discriminates instead of rejecting every device row.
    ///
    /// Without this, a gate that voided unconditionally would look correct in
    /// the test above while making device throughput unmeasurable.
    #[test]
    fn an_exclusive_device_cell_publishes_the_shape_the_starved_gate_voids() {
        let mut m = measurement(36.9, 1, 65_536);
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: Some(0.4375) };
        assert!((m.device_utilization().unwrap_or(0.0) - 0.875).abs() < 1e-15);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// The device gate boundary is exact and inclusive: exactly
    /// [`MIN_DEVICE_UTILIZATION`] publishes and anything under it voids.
    ///
    /// Locks out an inverted or off-by-one comparison, which would either void
    /// every device cell on a machine that does any host work at all, or let a
    /// cell one increment under the documented limit through. Both operands are
    /// dyadic, so these ratios are exact in binary rather than approximate.
    #[test]
    fn the_device_utilization_gate_boundary_is_exact_and_inclusive() {
        let mut m = measurement(36.9, 1, 65_536);
        // 0.125 / 0.5 is exactly MIN_DEVICE_UTILIZATION.
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: Some(0.125) };
        assert!((m.device_utilization().unwrap_or(0.0) - MIN_DEVICE_UTILIZATION).abs() < 1e-15);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
        // One dyadic step under the limit must void.
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: Some(0.09375) };
        match assess_plausibility(&m) {
            Plausibility::DeviceStarved { device_utilization, .. } => {
                assert!((device_utilization - 0.1875).abs() < 1e-15);
            }
            other => panic!("0.1875 is under the {MIN_DEVICE_UTILIZATION} limit: {other:?}"),
        }
    }

    /// A host baseline has no device timeline and must never be judged against
    /// the device gate.
    ///
    /// `device_secs` is `None` for every CPU baseline, so a gate that treated
    /// absence as zero utilization would void tiktoken, gigatoken and
    /// hf-tokenizers on every run. This is the regression that would make the
    /// whole host sweep unpublishable.
    #[test]
    fn a_host_baseline_without_a_device_timeline_is_never_device_starved() {
        let mut m = measurement(36.9, 1, 65_536);
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: None };
        assert_eq!(m.device_utilization(), None);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
    }

    /// Repetitions that disagree cannot publish a best-of-N figure.
    ///
    /// The report publishes the FASTEST repetition, which systematically picks
    /// the least contended one, so bursty load raises the headline number while
    /// leaving every CPU gate clean. Dispersion is the only signal that
    /// survives taking the best, and it was measured and printed as prose while
    /// nothing acted on it.
    #[test]
    fn repetitions_that_disagree_cannot_publish_a_best_of_n_figure() {
        let mut m = measurement(36.9, 1, 65_536);
        // Dyadic samples: stddev 0.125, mean 0.5, so exactly 0.25 relative.
        m.stats = RunStats::new(vec![0.375, 0.5, 0.625]).unwrap();
        m.active = ActiveTime { cpu_secs: m.stats.best(), device_secs: None };
        assert!((m.stats.rel_stddev() - 0.25).abs() < 1e-15);
        match assess_plausibility(&m) {
            Plausibility::EstimatorDependent { rel_stddev, maximum_rel_stddev } => {
                assert!((rel_stddev - 0.25).abs() < 1e-15);
                assert!((maximum_rel_stddev - MAX_PUBLISHABLE_REL_STDDEV).abs() < 1e-15);
            }
            other => panic!("a 25% spread across reps must void the cell: {other:?}"),
        }
    }

    /// The variance interlock and the noisy advisory are two thresholds, and
    /// collapsing them would void every mildly noisy cell.
    ///
    /// A cell at 18.75% spread is well above [`NOISY_REL_STDDEV`] and must
    /// still publish with its advisory printed, while 21.875% must void. This
    /// locks out the tempting simplification of gating on `NOISY_REL_STDDEV`
    /// itself, which would refuse most real cells on a normally busy box.
    #[test]
    fn the_variance_interlock_is_looser_than_the_noisy_advisory() {
        let mut m = measurement(36.9, 1, 65_536);
        // 0.09375 / 0.5 is exactly 0.1875: noisy, publishable.
        m.stats = RunStats::new(vec![0.40625, 0.5, 0.59375]).unwrap();
        m.active = ActiveTime { cpu_secs: m.stats.best(), device_secs: None };
        assert!((m.stats.rel_stddev() - 0.1875).abs() < 1e-15);
        assert!(m.stats.rel_stddev() > NOISY_REL_STDDEV);
        assert_eq!(assess_plausibility(&m), Plausibility::Plausible);
        // 0.109375 / 0.5 is exactly 0.21875: over the interlock.
        m.stats = RunStats::new(vec![0.390625, 0.5, 0.609375]).unwrap();
        m.active = ActiveTime { cpu_secs: m.stats.best(), device_secs: None };
        assert!((m.stats.rel_stddev() - 0.21875).abs() < 1e-15);
        assert!(assess_plausibility(&m).is_harness_defect());
    }

    /// A small-document cell is exempt from the throughput floor but not from
    /// having to be repeatable.
    ///
    /// [`Plausibility::PerCallBound`] returns early and is publishable, so a
    /// variance check placed after it would silently exempt every small-input
    /// cell from the interlock. Ordering, not thresholds, is what this locks.
    #[test]
    fn a_per_call_bound_cell_is_still_held_to_repeatability() {
        let mut m = measurement(4.4, 1, AMORTIZED_DOC_BYTES - 1);
        m.stats = RunStats::new(vec![0.375, 0.5, 0.625]).unwrap();
        m.active = ActiveTime { cpu_secs: m.stats.best(), device_secs: None };
        // Small enough to be per-call bound, and it must NOT be reported so.
        assert!(m.doc_bytes < AMORTIZED_DOC_BYTES);
        match assess_plausibility(&m) {
            Plausibility::EstimatorDependent { rel_stddev, .. } => {
                assert!((rel_stddev - 0.25).abs() < 1e-15);
            }
            other => panic!("an unrepeatable small-input cell is not merely per-call: {other:?}"),
        }
    }

    /// A starved device cell that is also under the per-core floor is reported
    /// as starved, because that is the cause.
    ///
    /// Eight 16-thread cells were once published as thread-delivery bugs when
    /// the real cause was foreign load. This is the same defect one gate over:
    /// a contended device cell is slow BECAUSE it was contended, and filing it
    /// as an unexplained sub-floor measurement sends the reader to look for a
    /// performance bug that does not exist.
    #[test]
    fn device_starvation_outranks_the_per_core_floor_as_a_cause() {
        let mut m = measurement(1.0, 1, 65_536);
        m.active = ActiveTime { cpu_secs: 0.5, device_secs: Some(0.0625) };
        assert!(m.mb_per_second_per_core() < PLAUSIBLE_FLOOR_MB_S_PER_CORE);
        match assess_plausibility(&m) {
            Plausibility::DeviceStarved { device_utilization, .. } => {
                assert!((device_utilization - 0.125).abs() < 1e-15);
            }
            other => panic!("a contended device cell must not be filed sub-floor: {other:?}"),
        }
    }

    /// A library legitimately below the floor is reported with its number and
    /// an evidenced reason, not silently passed and not called a harness bug.
    ///
    /// The distinction matters: suppressing the check for hf-tokenizers by
    /// lowering the floor would also hide a genuine regression in tiktoken or
    /// gigatoken measured in the same run.
    #[test]
    fn a_known_slow_library_is_recorded_with_its_reason_not_suppressed() {
        let mut m = measurement(4.6, 1, 65_536);
        m.tokenizer = "hf-tokenizers".to_owned();
        match assess_plausibility(&m) {
            Plausibility::KnownSlowLibrary { observed_mb_s_per_core, reason } => {
                assert!((observed_mb_s_per_core - 4.6).abs() < 1e-6);
                assert!(reason.contains("encode_batch_fast"));
            }
            other => panic!("hf-tokenizers under the floor must be known-slow, got {other:?}"),
        }
        // Not a harness defect, so it does not fail a run.
        assert!(!assess_plausibility(&m).is_harness_defect());
        // The same number from a library with no recorded reason still is one.
        m.tokenizer = "tiktoken".to_owned();
        assert!(matches!(
            assess_plausibility(&m),
            Plausibility::SuspectedMeasurementDefect { .. }
        ));
        assert_eq!(known_slow_reason("tiktoken"), None);
        assert_eq!(known_slow_reason("gigatoken"), None);
    }

    /// Boundary: exactly at the floor passes, a hair under fails. An
    /// off-by-one comparison here either rejects good data or admits the
    /// defect it exists to catch.
    ///
    /// Note for anyone auditing this with the operand-independence smell test:
    /// the first case's operands ARE value-derived, since the input is built
    /// from the same constant `assess_plausibility` compares against. That is
    /// the mechanism, not a defect. Constructing the input exactly at the
    /// boundary cancels the value so the only thing left observable is the
    /// comparison DIRECTION, which is what this pins. Verified by perturbing
    /// the operator rather than the value: `<` to `<=` at the floor check makes
    /// this test fail with left `SuspectedMeasurementDefect { observed: 5.0,
    /// floor: 5.0 }` against right `Plausible`. Its failure space and its
    /// stated guard space are therefore the same set.
    #[test]
    fn plausibility_boundary_is_inclusive_at_the_floor() {
        assert_eq!(
            assess_plausibility(&measurement(PLAUSIBLE_FLOOR_MB_S_PER_CORE, 1, AMORTIZED_DOC_BYTES)),
            Plausibility::Plausible
        );
        assert!(matches!(
            assess_plausibility(&measurement(4.999, 1, AMORTIZED_DOC_BYTES)),
            Plausibility::SuspectedMeasurementDefect { .. }
        ));
    }

    /// A zero or negative wall time divides into infinite throughput, which is
    /// precisely how a broken timer becomes a published speedup. Rejecting it
    /// at construction means no such row can ever reach a table.
    #[test]
    fn zero_and_negative_wall_times_are_rejected() {
        assert!(RunStats::new(vec![]).is_err());
        assert!(RunStats::new(vec![0.0]).is_err());
        assert!(RunStats::new(vec![-1e-9]).is_err());
        assert!(RunStats::new(vec![f64::NAN]).is_err());
        assert!(RunStats::new(vec![f64::INFINITY]).is_err());
        assert!(RunStats::new(vec![1e-9]).is_ok());
    }

    /// Statistics must be exact, not approximately right. Minimum is the
    /// reported figure because every perturbation adds time; the spread is
    /// reported beside it so a noisy cell is visible rather than averaged
    /// into looking clean.
    #[test]
    fn run_stats_computes_exact_min_mean_median_and_spread() {
        let s = RunStats::new(vec![0.20, 0.10, 0.30]).unwrap();
        assert_eq!(s.reps(), 3);
        assert!((s.best() - 0.10).abs() < 1e-12);
        assert!((s.mean() - 0.20).abs() < 1e-12);
        assert!((s.median() - 0.20).abs() < 1e-12);
        // sample stddev of {0.1,0.2,0.3} is 0.1, mean 0.2, so 0.5 exactly.
        assert!((s.rel_stddev() - 0.5).abs() < 1e-12);
        // One sample has no spread, and must not be NaN from a 0/0.
        let one = RunStats::new(vec![0.25]).unwrap();
        assert!((one.rel_stddev() - 0.0).abs() < 1e-12);
        assert!((one.best() - 0.25).abs() < 1e-12);
    }

    /// Throughput algebra with exact expected values. 8 MB in 0.5 s is
    /// 16 MB/s, 0.016 GB/s, and on 16 threads 1.0 MB/s per thread. Getting
    /// the SI base wrong by using 2^20 would report 15.26 and every published
    /// comparison would be off by 4.9%.
    #[test]
    fn throughput_derivations_are_exact_and_si_based() {
        let mut m = measurement(16.0, 16, 65_536);
        m.input_bytes = 8_000_000;
        m.tokens = 2_000_000;
        m.stats = RunStats::new(vec![0.5]).unwrap();
        assert!((m.bytes_per_second() - 16_000_000.0).abs() < 1e-6);
        assert!((m.mb_per_second() - 16.0).abs() < 1e-12);
        assert!((m.gb_per_second() - 0.016).abs() < 1e-12);
        assert!((m.mb_per_second_per_thread() - 1.0).abs() < 1e-12);
        assert!((m.tokens_per_second() - 4_000_000.0).abs() < 1e-6);
        assert!((m.ns_per_token() - 250.0).abs() < 1e-9);
        assert!((m.bytes_per_token() - 4.0).abs() < 1e-12);
    }

    /// Divide-by-zero guards. A zero thread count, zero tokens, or an
    /// unreachable zero wall time must yield 0.0 rather than NaN or inf,
    /// because NaN formats into a table as a plausible-looking blank.
    #[test]
    fn derived_rates_never_produce_nan_or_infinity() {
        let mut m = measurement(16.0, 0, 65_536);
        m.tokens = 0;
        assert!((m.mb_per_second_per_thread() - 0.0).abs() < 1e-12);
        assert!((m.tokens_per_second() - 0.0).abs() < 1e-12);
        assert!((m.ns_per_token() - 0.0).abs() < 1e-12);
        assert!((m.bytes_per_token() - 0.0).abs() < 1e-12);
    }

    /// SMT reduction: on a 9950X, cpu0 and cpu16 share physical core 0, so
    /// the pinning set must be 0..15 and never include a sibling. Pinning two
    /// threads onto one core's shared execution resources would understate
    /// per-core throughput by nearly half.
    #[test]
    fn smt_siblings_reduce_to_one_cpu_per_physical_core() {
        let lists: Vec<String> = (0..32).map(|c| format!("{},{}", c % 16, (c % 16) + 16)).collect();
        let (cores, reps) = Machine::physical_from_siblings(&lists, 32);
        assert_eq!(cores, 16);
        assert_eq!(reps, (0..16).collect::<Vec<usize>>());
    }

    /// Missing topology must degrade to "assume no SMT" rather than invent a
    /// map. A wrong sibling map silently halves or doubles the per-core
    /// figure, which is exactly the class of error this harness exists to
    /// eliminate.
    #[test]
    fn absent_topology_assumes_no_smt_rather_than_guessing() {
        let (cores, reps) = Machine::physical_from_siblings(&[], 8);
        assert_eq!(cores, 8);
        assert_eq!(reps, (0..8).collect::<Vec<usize>>());
        // A partial map is also untrustworthy and must not be used.
        let partial = vec!["0,4".to_owned(), "1,5".to_owned()];
        let (cores, reps) = Machine::physical_from_siblings(&partial, 8);
        assert_eq!(cores, 8);
        assert_eq!(reps.len(), 8);
    }

    /// A logical CPU count of zero means the probe failed, and a throughput
    /// figure with no core count is not comparable. Erroring beats defaulting
    /// to 1 and publishing a per-core number that is really a 32-thread one.
    #[test]
    fn cpuinfo_without_processors_is_an_error() {
        let err = Machine::from_probe_inputs("model name : Nothing\n", vec![], None, 0, None);
        assert!(err.is_err());
        let ok = Machine::from_probe_inputs(
            "processor : 0\nmodel name : AMD Ryzen 9 9950X 16-Core Processor\nprocessor : 1\n",
            vec![],
            Some("performance".to_owned()),
            96_399_728,
            None,
        )
        .unwrap();
        assert_eq!(ok.logical_cores, 2);
        assert_eq!(ok.cpu_model, "AMD Ryzen 9 9950X 16-Core Processor");
        assert_eq!(ok.governor.as_deref(), Some("performance"));
        assert_eq!(ok.total_memory_kib, 96_399_728);
        assert_eq!(ok.smt_siblings_per_core(), 1);
    }

    /// Clock drift sign and magnitude. A sweep that loses 8% of its clock
    /// biases late rows against early ones, so the direction has to be
    /// reported, not just the magnitude.
    #[test]
    fn clock_drift_reports_signed_ratio_and_flags_significance() {
        let d = ClockDrift {
            first: ClockSample { mean_mhz: 5000.0, min_mhz: 4900.0, max_mhz: 5100.0 },
            last: ClockSample { mean_mhz: 4600.0, min_mhz: 4500.0, max_mhz: 4700.0 },
        };
        assert!((d.drift_ratio() - -0.08).abs() < 1e-12);
        assert!(d.is_significant());
        let steady = ClockDrift {
            first: ClockSample { mean_mhz: 5000.0, min_mhz: 5000.0, max_mhz: 5000.0 },
            last: ClockSample { mean_mhz: 4950.0, min_mhz: 4950.0, max_mhz: 4950.0 },
        };
        assert!((steady.drift_ratio() - -0.01).abs() < 1e-12);
        assert!(!steady.is_significant());
        // Exactly at the threshold counts as significant.
        let edge = ClockDrift {
            first: ClockSample { mean_mhz: 100.0, min_mhz: 100.0, max_mhz: 100.0 },
            last: ClockSample { mean_mhz: 95.0, min_mhz: 95.0, max_mhz: 95.0 },
        };
        assert!(edge.is_significant());
    }

    /// A kernel that reports no `cpu MHz` must yield None so the report says
    /// "drift unknown" instead of asserting a stability it never observed.
    #[test]
    fn clock_sample_parses_mhz_and_returns_none_when_absent() {
        let s = ClockSample::parse("cpu MHz : 4000.0\ncpu MHz : 5000.0\ncpu MHz : 4500.0\n")
            .expect("three MHz lines parse");
        assert!((s.mean_mhz - 4500.0).abs() < 1e-12);
        assert!((s.min_mhz - 4000.0).abs() < 1e-12);
        assert!((s.max_mhz - 5000.0).abs() < 1e-12);
        assert!(ClockSample::parse("processor : 0\nmodel name : x\n").is_none());
        // Garbage values are dropped, not parsed as zero.
        assert!(ClockSample::parse("cpu MHz : unknown\n").is_none());
    }

    /// Byte-budget truncation must land on a character boundary. Slicing a
    /// UTF-8 corpus at an arbitrary byte panics mid character, and a corpus
    /// that differs by a partial character between runs changes both the
    /// digest and the token count.
    #[test]
    fn corpus_truncation_respects_utf8_boundaries() {
        // "héllo" is 6 bytes: h, 0xc3, 0xa9, l, l, o.
        let s = "héllo";
        assert_eq!(s.len(), 6);
        assert_eq!(truncate_at_char_boundary(s, 6), "héllo");
        assert_eq!(truncate_at_char_boundary(s, 2), "h");
        assert_eq!(truncate_at_char_boundary(s, 3), "hé");
        assert_eq!(truncate_at_char_boundary(s, 0), "");
        assert_eq!(truncate_at_char_boundary(s, 99), "héllo");
        // A 4-byte scalar must not be split either.
        let emoji = "a\u{1F600}b";
        assert_eq!(emoji.len(), 6);
        assert_eq!(truncate_at_char_boundary(emoji, 4), "a");
        assert_eq!(truncate_at_char_boundary(emoji, 5), "a\u{1F600}");
    }

    /// The corpus digest must change when a single byte changes, and be
    /// stable for identical bytes. Without it, a rerun against a mutated tree
    /// looks like a throughput regression.
    #[test]
    fn corpus_digest_detects_single_byte_change() {
        let a = corpus_digest(b"the quick brown fox");
        let b = corpus_digest(b"the quick brown fox");
        let c = corpus_digest(b"the quick brown fbx");
        assert_eq!(a, b);
        assert_ne!(a, c);
        // Both halves must participate, so a length-preserving swap moves it.
        assert_ne!(corpus_digest(b"ab"), corpus_digest(b"ba"));
        assert_ne!(corpus_digest(b""), corpus_digest(b"\0"));
    }

    /// Thread plans must pin one thread per physical core, and must not claim
    /// physical pinning for the SMT-wide run. "Did you pin?" is unanswerable
    /// after the fact, so the plan records it.
    #[test]
    fn standard_thread_plans_pin_one_thread_per_physical_core() {
        let machine = Machine {
            cpu_model: "AMD Ryzen 9 9950X 16-Core Processor".to_owned(),
            physical_cores: 16,
            logical_cores: 32,
            physical_core_cpus: (0..16).collect(),
            governor: Some("performance".to_owned()),
            total_memory_kib: 96_399_728,
            gpu: None,
        };
        let plans = ThreadPlan::standard(&machine);
        assert_eq!(plans.len(), 3);
        assert_eq!(plans[0].threads, 1);
        assert_eq!(plans[0].cpus, vec![0]);
        assert!(plans[0].pinned_to_physical);
        assert!(plans[0].include_single_doc);
        assert_eq!(plans[0].cpu_list().as_deref(), Some("0"));
        assert_eq!(plans[1].threads, 16);
        assert_eq!(plans[1].cpus, (0..16).collect::<Vec<usize>>());
        assert!(plans[1].pinned_to_physical);
        assert!(!plans[1].include_single_doc);
        assert_eq!(
            plans[1].cpu_list().as_deref(),
            Some("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15")
        );
        assert_eq!(plans[2].threads, 32);
        assert!(plans[2].cpus.is_empty());
        assert!(!plans[2].pinned_to_physical);
        assert_eq!(plans[2].cpu_list(), None);
    }

    /// A machine without SMT must not get a duplicate 32-thread plan, and a
    /// single-core machine must not get a redundant multi-core plan. A
    /// duplicated plan double-counts rows in the table.
    #[test]
    fn thread_plans_omit_redundant_invocations() {
        let no_smt = Machine {
            cpu_model: "x".to_owned(),
            physical_cores: 4,
            logical_cores: 4,
            physical_core_cpus: (0..4).collect(),
            governor: None,
            total_memory_kib: 0,
            gpu: None,
        };
        let plans = ThreadPlan::standard(&no_smt);
        assert_eq!(plans.len(), 2);
        assert_eq!(plans[1].threads, 4);
        let single = Machine { physical_cores: 1, logical_cores: 1, physical_core_cpus: vec![0], ..no_smt };
        let plans = ThreadPlan::standard(&single);
        assert_eq!(plans.len(), 1);
        assert_eq!(plans[0].threads, 1);
    }

    /// The record protocol must round-trip every field the report needs. A
    /// dropped field would surface as a missing table row, which reads as
    /// "baseline did not run" rather than "harness bug".
    #[test]
    fn driver_record_parses_every_field_exactly() {
        let ctx = MachineContext { physical_cores: 16, logical_cores: 32, pinned_to_physical: true };
        let line = "record\ttokenizer=tiktoken\tversion=0.12.0\tvocab=cl100k_base\tregime=batch\t\
                    target_tokens=65536\tdoc_bytes=262144\tdocs=32\tinput_bytes=8388608\t\
                    tokens=2097152\tsamples=0.25,0.26,0.30\twarmups=1\tthreads=16\t\
                    mean_mhz=5100.5\tmatches_ref=1\tcpu_secs=3.90\tinner_reps=4\t\
                    foreign_cpu_secs=0.012";
        let ev = parse_driver_line(line, ctx, 7).unwrap().expect("a record");
        let DriverEvent::Record(m) = ev else { panic!("expected a record event") };
        assert_eq!(m.tokenizer, "tiktoken");
        assert_eq!(m.version, "0.12.0");
        assert_eq!(m.vocab, "cl100k_base");
        assert_eq!(m.regime, Regime::Batch);
        assert_eq!(m.target_tokens, 65_536);
        assert_eq!(m.doc_bytes, 262_144);
        assert_eq!(m.docs, 32);
        assert_eq!(m.input_bytes, 8_388_608);
        assert_eq!(m.tokens, 2_097_152);
        assert_eq!(m.threads, 16);
        assert_eq!(m.warmups, 1);
        assert_eq!(m.machine, ctx);
        assert!((m.mean_mhz - 5100.5).abs() < 1e-9);
        assert_eq!(m.stats.reps(), 3);
        assert!((m.stats.best() - 0.25).abs() < 1e-12);
        assert_eq!(m.inner_reps, 4);
        assert_eq!(m.active.device_secs, None);
        // `input_bytes` is the reproducible size of one unit; the timed region
        // held four of them. Folding the repetition count into `input_bytes`
        // instead would make the recorded input size machine dependent, which
        // is the bug this separation fixes.
        assert_eq!(m.timed_bytes(), 33_554_432);
        assert_eq!(m.timed_tokens(), 8_388_608);
        // 4 x 8388608 bytes in 0.25 s is 134.217728 MB/s, 8.388608 per thread.
        assert!((m.mb_per_second() - 134.217_728).abs() < 1e-9);
        assert!((m.mb_per_second_per_thread() - 8.388_608).abs() < 1e-9);
        // 3.90 CPU-seconds inside a 0.25 s wall window is 15.6x parallelism.
        assert!((m.achieved_parallelism() - 15.6).abs() < 1e-9);
    }

    /// A malformed record must be an error, never silently skipped. Silence
    /// turns a harness bug into an apparently missing baseline.
    #[test]
    fn malformed_records_are_errors_not_silent_skips() {
        let ctx = MachineContext { physical_cores: 1, logical_cores: 1, pinned_to_physical: false };
        // Missing `tokens`.
        let missing = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                       doc_bytes=1\tdocs=1\tinput_bytes=1\tsamples=0.1\twarmups=0\tthreads=1\t\
                       mean_mhz=1\tmatches_ref=1\tcpu_secs=0.1\tinner_reps=1\t\
                       foreign_cpu_secs=0.0";
        assert!(parse_driver_line(missing, ctx, 1).is_err());
        // Unknown regime.
        let bad_regime = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=streaming\t\
                          target_tokens=1\tdoc_bytes=1\tdocs=1\tinput_bytes=1\ttokens=1\t\
                          samples=0.1\twarmups=0\tthreads=1\tmean_mhz=1\tmatches_ref=1\t\
                          cpu_secs=0.1\tinner_reps=1\tforeign_cpu_secs=0.0";
        assert!(parse_driver_line(bad_regime, ctx, 2).is_err());
        // Non-numeric sample.
        let bad_sample = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                          doc_bytes=1\tdocs=1\tinput_bytes=1\ttokens=1\tsamples=fast\twarmups=0\t\
                          threads=1\tmean_mhz=1\tmatches_ref=1\tcpu_secs=0.1\tinner_reps=1\t\
                          foreign_cpu_secs=0.0";
        assert!(parse_driver_line(bad_sample, ctx, 3).is_err());
        // Zero wall time, which would divide into infinite throughput.
        let zero = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                    doc_bytes=1\tdocs=1\tinput_bytes=1\ttokens=1\tsamples=0.0\twarmups=0\t\
                    threads=1\tmean_mhz=1\tmatches_ref=1\tcpu_secs=0.1\tinner_reps=1\t\
                    foreign_cpu_secs=0.0";
        assert!(parse_driver_line(zero, ctx, 4).is_err());
        // Missing `inner_reps`, without which the timed region size is
        // unknown and the throughput cannot be computed at all.
        let no_inner = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                        doc_bytes=1\tdocs=1\tinput_bytes=1\ttokens=1\tsamples=0.1\twarmups=0\t\
                        threads=1\tmean_mhz=1\tmatches_ref=1\tcpu_secs=0.1\t\
                        foreign_cpu_secs=0.0";
        assert!(parse_driver_line(no_inner, ctx, 5).is_err());
    }

    /// The agreement flag must round-trip, and a missing flag must be an
    /// error rather than defaulting to "matched". Defaulting to true would
    /// silently assert vocabulary equivalence the harness never checked,
    /// which is the assumption this field exists to remove.
    #[test]
    fn id_agreement_flag_round_trips_and_is_required() {
        let ctx = MachineContext { physical_cores: 1, logical_cores: 1, pinned_to_physical: false };
        let base = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                    doc_bytes=1\tdocs=1\tinput_bytes=1\ttokens=1\tsamples=0.1\twarmups=0\t\
                    threads=1\tmean_mhz=1\tcpu_secs=0.1\tinner_reps=1\tforeign_cpu_secs=0.0";
        assert!(
            parse_driver_line(base, ctx, 1).is_err(),
            "a record without matches_ref must be rejected, not assumed equivalent"
        );
        let yes = parse_driver_line(&format!("{base}\tmatches_ref=1"), ctx, 2).unwrap();
        let Some(DriverEvent::Record(m)) = yes else { panic!("expected a record") };
        assert!(m.matches_reference);
        let no = parse_driver_line(&format!("{base}\tmatches_ref=0"), ctx, 3).unwrap();
        let Some(DriverEvent::Record(m)) = no else { panic!("expected a record") };
        assert!(!m.matches_reference);
    }

    /// Active execution must be recorded separately from wall time, per
    /// vyre's benchmark doctrine. `device_secs` is absent for host CPU
    /// baselines and must stay `None` rather than defaulting to the wall time,
    /// which would claim a device timeline that does not exist.
    #[test]
    fn active_time_is_recorded_separately_and_device_time_is_optional() {
        let ctx = MachineContext { physical_cores: 16, logical_cores: 32, pinned_to_physical: true };
        let base = "record\ttokenizer=t\tversion=1\tvocab=v\tregime=batch\ttarget_tokens=1\t\
                    doc_bytes=8192\tdocs=1\tinput_bytes=33554432\ttokens=8388608\tsamples=0.25\t\
                    warmups=1\tthreads=16\tmean_mhz=5000\tmatches_ref=1\tinner_reps=1\t\
                    foreign_cpu_secs=0.0";
        // A record with no cpu_secs is rejected: active time is not optional.
        assert!(parse_driver_line(base, ctx, 1).is_err());
        let host = parse_driver_line(&format!("{base}\tcpu_secs=3.75"), ctx, 2).unwrap();
        let Some(DriverEvent::Record(m)) = host else { panic!("expected a record") };
        assert!((m.active.cpu_secs - 3.75).abs() < 1e-12);
        assert_eq!(m.active.device_secs, None);
        assert_eq!(m.device_utilization(), None);
        // 3.75 CPU-seconds inside a 0.25 s wall window is 15x parallelism.
        assert!((m.achieved_parallelism() - 15.0).abs() < 1e-12);
        // With no device timeline the active figure falls back to CPU time.
        assert!((m.active_secs() - 3.75).abs() < 1e-12);
        let dev =
            parse_driver_line(&format!("{base}\tcpu_secs=0.30\tdevice_secs=0.05"), ctx, 3).unwrap();
        let Some(DriverEvent::Record(m)) = dev else { panic!("expected a record") };
        assert_eq!(m.active.device_secs, Some(0.05));
        // Device time, when present, is the active figure and 20% of wall.
        assert!((m.active_secs() - 0.05).abs() < 1e-12);
        assert!((m.device_utilization().unwrap_or(0.0) - 0.2).abs() < 1e-12);
    }

    /// A row claiming N threads that achieved 1x parallelism ran on one
    /// thread. Without this the harness would publish a per-thread figure N
    /// times too pessimistic and nobody could tell from the table.
    #[test]
    fn achieved_parallelism_exposes_a_thread_count_that_never_ran() {
        let mut honest = measurement(4115.0, 16, 65_536);
        honest.active = ActiveTime { cpu_secs: honest.stats.best() * 15.6, device_secs: None };
        assert!((honest.achieved_parallelism() - 15.6).abs() < 1e-9);
        let mut lying = measurement(60.0, 16, 65_536);
        lying.active = ActiveTime { cpu_secs: lying.stats.best(), device_secs: None };
        assert!((lying.achieved_parallelism() - 1.0).abs() < 1e-12);
        // The table has to show it, not just expose it on the struct.
        let text = report_with(vec![Availability::Measured(lying)]).render_table();
        assert!(text.contains("par"), "{text}");
        assert!(text.contains("  1.00"), "{text}");
    }

    /// A library that disagrees on ids must be named in the table, because a
    /// throughput row from a different computation read as comparable is
    /// exactly the error this whole harness exists to prevent.
    #[test]
    fn disagreeing_libraries_are_named_and_flagged_in_the_table() {
        let mut good = measurement(36.9, 1, 65_536);
        good.tokenizer = "tiktoken".to_owned();
        let mut bad = measurement(90.0, 1, 65_536);
        bad.tokenizer = "hf-tokenizers".to_owned();
        bad.matches_reference = false;
        let r = report_with(vec![Availability::Measured(good), Availability::Measured(bad)]);
        assert_eq!(r.disagreeing().len(), 1);
        assert_eq!(r.disagreeing()[0].tokenizer, "hf-tokenizers");
        let text = r.render_table();
        assert!(text.contains("ids DIFFERENT from the reference"), "{text}");
        assert!(text.contains("hf-tokenizers"), "{text}");
        // The per-row column must carry it too, not only the summary line.
        assert!(text.contains("   NO"), "{text}");
        // And a fully-agreeing report must say so positively.
        let clean = report_with(vec![Availability::Measured(measurement(36.9, 1, 65_536))]);
        assert!(clean.disagreeing().is_empty());
        assert!(clean.render_table().contains("ids identical to the reference"));
    }

    /// Locks out the crate-tree divergence from
    /// FINDING-hf-tokenizers-diverges-from-tiktoken-on-crate-tree-corpus ever
    /// reaching a published table: hf-tokenizers emitted 254124 tokens where
    /// tiktoken emitted 254143 from the same 1 MiB of crate-tree text, 19
    /// apart, because its added-token table matches the literal
    /// `<|endoftext|>` and `<|endofprompt|>` strings in README.md prose that
    /// tiktoken's ordinary encoding splits into seven ids each. A ratio
    /// against either row is unfalsifiable, so the sweep refuses the corpus.
    ///
    /// The pin is the exact pair of counts from the finding, carried on
    /// synthetic rows so the unit test does not need the bench venv; the live
    /// reproduction is the integration test in `tests/bench_support.rs`.
    #[test]
    fn the_sweep_refuses_a_corpus_the_baselines_tokenize_differently() {
        let corpus = CorpusFacts {
            origin: "deterministic sorted walk of /crate".to_owned(),
            bytes: 1_048_576,
            files: 24,
            digest: 6_380_138_651_704_881_638,
        };
        let mut tiktoken = measurement(36.9, 1, 65_536);
        tiktoken.tokenizer = "tiktoken".to_owned();
        tiktoken.input_bytes = 1_048_576;
        tiktoken.tokens = 254_143;
        let mut hf = tiktoken.clone();
        hf.tokenizer = "hf-tokenizers".to_owned();
        hf.tokens = 254_124;
        let rows = vec![Availability::Measured(tiktoken), Availability::Measured(hf)];
        let err = refuse_noncomparable_cells(&rows, &corpus)
            .expect_err("a 19-token disagreement on identical bytes must refuse the sweep");
        let text = err.to_string();
        // The refusal must name the cell and BOTH sides with their counts: an
        // operator has to be able to tell which libraries disagreed and by how
        // much without a several-minute rerun.
        assert!(text.contains("cl100k_base batch target_tokens=1024"), "{text}");
        assert!(text.contains("hf-tokenizers"), "{text}");
        assert!(text.contains("tiktoken"), "{text}");
        assert!(text.contains("254124"), "{text}");
        assert!(text.contains("254143"), "{text}");
        assert!(text.contains("1048576"), "{text}");
        // The corpus digest travels with the refusal so the void corpus is
        // identifiable after the fact.
        assert!(text.contains("6380138651704881638"), "{text}");
    }

    /// The negative control for the refusal above: cells whose libraries agree
    /// exactly, and reports too thin to compare at all, must pass. Without
    /// this a guard that refused EVERY report would look identical to the
    /// correct one, which is the same class of vacuous guard this file has
    /// shipped before.
    #[test]
    fn the_sweep_publishes_a_corpus_the_baselines_tokenize_identically() {
        let corpus = CorpusFacts {
            origin: "test".to_owned(),
            bytes: 1_048_576,
            files: 24,
            digest: 7,
        };
        let mut tiktoken = measurement(36.9, 1, 65_536);
        tiktoken.tokenizer = "tiktoken".to_owned();
        tiktoken.input_bytes = 1_048_576;
        tiktoken.tokens = 254_143;
        // Same cell, same bytes, same count: agreement.
        let mut hf = tiktoken.clone();
        hf.tokenizer = "hf-tokenizers".to_owned();
        // A different cell entirely: its count is its own business.
        let mut other_cell = tiktoken.clone();
        other_cell.tokenizer = "hf-tokenizers".to_owned();
        other_cell.regime = Regime::SingleDocument;
        other_cell.input_bytes = 262_144;
        other_cell.tokens = 65_536;
        let rows = vec![
            Availability::Measured(tiktoken),
            Availability::Measured(hf),
            Availability::Measured(other_cell),
            // An unavailable row carries no counts and must never refuse.
            Availability::Unavailable {
                tokenizer: "gigatoken".to_owned(),
                reason: "not installed".to_owned(),
            },
        ];
        refuse_noncomparable_cells(&rows, &corpus)
            .expect("agreeing cells, distinct cells and unavailable rows all pass");
        // A one-library report compares nothing and passes.
        let single = vec![Availability::Measured(measurement(36.9, 1, 65_536))];
        refuse_noncomparable_cells(&single, &corpus).expect("nothing to disagree with");
    }

    /// Equal token counts over UNEQUAL byte counts is not agreement: the
    /// libraries were fed different inputs, so the cell was never a
    /// comparison. The count check alone would wave this through.
    #[test]
    fn the_sweep_refuses_a_cell_whose_libraries_read_different_bytes() {
        let corpus = CorpusFacts {
            origin: "test".to_owned(),
            bytes: 1_048_576,
            files: 24,
            digest: 7,
        };
        let mut a = measurement(36.9, 1, 65_536);
        a.tokenizer = "tiktoken".to_owned();
        a.input_bytes = 1_048_576;
        a.tokens = 254_143;
        let mut b = a.clone();
        b.tokenizer = "hf-tokenizers".to_owned();
        b.input_bytes = 1_048_320;
        let rows = vec![Availability::Measured(a), Availability::Measured(b)];
        let err = refuse_noncomparable_cells(&rows, &corpus)
            .expect_err("different inputs void the cell before tokenization is reached");
        let text = err.to_string();
        assert!(text.contains("1048320"), "{text}");
        assert!(text.contains("1048576"), "{text}");
    }

    /// Batch cells must hold a whole number of documents that covers the
    /// budget, so every cell encodes about the same total bytes. An off-by-one
    /// here changes the input size per cell and makes sizes incomparable.
    #[test]
    fn batch_doc_count_covers_the_budget_exactly() {
        // 16 MiB budget, 1 KiB documents.
        assert_eq!(batch_docs(1024, 16 * 1024 * 1024), 16_384);
        // Non-divisible sizes round up so the budget is always covered.
        assert_eq!(batch_docs(1000, 16 * 1024 * 1024), 16_778);
        assert_eq!(batch_docs(3, 10), 4);
        assert_eq!(batch_docs(10, 10), 1);
        // A document larger than the budget is still one document, never zero.
        assert_eq!(batch_docs(1 << 24, 1 << 20), 1);
        // Degenerate inputs must not divide by zero.
        assert_eq!(batch_docs(0, 1 << 20), 1);
        assert_eq!(batch_docs(1024, 0), 1);
    }

    /// A size with fewer documents than threads must be refused by the batch
    /// regime. Admitting it would publish a 32-thread row that a library ran
    /// on one thread, overstating per-thread cost by up to 32x.
    #[test]
    fn batch_regime_refuses_sizes_that_starve_threads() {
        let budget = 16 * 1024 * 1024;
        // 512 KiB documents give exactly 32 documents: enough for 32 threads.
        assert_eq!(batch_docs(512 * 1024, budget), 32);
        assert!(batch_admits(512 * 1024, budget, 32));
        assert!(batch_admits(512 * 1024, budget, 16));
        // 1 MiB documents give 16: fine for 16 threads, starves 32.
        assert_eq!(batch_docs(1024 * 1024, budget), 16);
        assert!(batch_admits(1024 * 1024, budget, 16));
        assert!(!batch_admits(1024 * 1024, budget, 32));
        // A 16 MiB document is a single document and admits only one thread.
        assert!(batch_admits(16 * 1024 * 1024, budget, 1));
        assert!(!batch_admits(16 * 1024 * 1024, budget, 2));
    }

    /// Human notes on stdout must not break the protocol, and unavailability
    /// must carry its reason through verbatim, including an `=` inside the
    /// reason text.
    #[test]
    fn notes_are_ignored_and_unavailable_reasons_survive_verbatim() {
        let ctx = MachineContext { physical_cores: 1, logical_cores: 1, pinned_to_physical: false };
        assert_eq!(parse_driver_line("", ctx, 1).unwrap(), None);
        assert_eq!(parse_driver_line("loading vocabulary...", ctx, 2).unwrap(), None);
        assert_eq!(parse_driver_line("# a comment", ctx, 3).unwrap(), None);
        let ev = parse_driver_line(
            "unavailable\ttokenizer=fastokens\treason=import failed: no module named x=y",
            ctx,
            4,
        )
        .unwrap()
        .expect("an unavailable event");
        assert_eq!(
            ev,
            DriverEvent::Unavailable {
                tokenizer: "fastokens".to_owned(),
                reason: "import failed: no module named x=y".to_owned(),
            }
        );
    }

    /// Calibration carries the corpus bytes-per-token used to size documents.
    /// If it were dropped, a "256 token" cell could hold any number of tokens
    /// and the sweep would not straddle the crossover it claims to.
    #[test]
    fn calibration_event_carries_bytes_per_token() {
        let ctx = MachineContext { physical_cores: 1, logical_cores: 1, pinned_to_physical: false };
        let ev = parse_driver_line(
            "calibration\tvocab=cl100k_base\tbytes_per_token=3.9041",
            ctx,
            1,
        )
        .unwrap()
        .expect("a calibration event");
        match ev {
            DriverEvent::Calibration { vocab, bytes_per_token } => {
                assert_eq!(vocab, "cl100k_base");
                assert!((bytes_per_token - 3.9041).abs() < 1e-9);
            }
            other => panic!("expected calibration, got {other:?}"),
        }
    }

    /// JSON escaping must handle every character that would otherwise produce
    /// invalid JSON. A corpus origin containing a Windows path or a reason
    /// containing a quote would break every downstream consumer.
    #[test]
    fn json_strings_escape_quotes_backslashes_and_controls() {
        assert_eq!(json_str("plain"), "\"plain\"");
        assert_eq!(json_str("a\"b"), "\"a\\\"b\"");
        assert_eq!(json_str("C:\\path"), "\"C:\\\\path\"");
        assert_eq!(json_str("a\nb\tc\rd"), "\"a\\nb\\tc\\rd\"");
        assert_eq!(json_str("\u{1}"), "\"\\u0001\"");
    }

    fn report_with(rows: Vec<Availability>) -> Report {
        Report {
            machine: Machine {
                cpu_model: "AMD Ryzen 9 9950X 16-Core Processor".to_owned(),
                physical_cores: 16,
                logical_cores: 32,
                physical_core_cpus: (0..16).collect(),
                governor: Some("performance".to_owned()),
                total_memory_kib: 96_399_728,
                gpu: Some(GpuInfo {
                    name: "NVIDIA GeForce RTX 5090".to_owned(),
                    memory_mib: "32607 MiB".to_owned(),
                    driver_version: "570.211.01".to_owned(),
                    compute_capability: "12.0".to_owned(),
                }),
            },
            corpus: CorpusFacts {
                origin: "test".to_owned(),
                bytes: 1024,
                files: 2,
                digest: 0x1234_5678_9abc_def0,
            },
            vocab: "cl100k_base".to_owned(),
            rows,
            clock: None,
            bytes_per_token: Some(3.9041),
            report_path: None,
        }
    }

    /// The table must print the core counts inline. A GB/s figure without a
    /// core count beside it is the exact ambiguity that lets a 144-core
    /// published number be compared against a 16-core one.
    #[test]
    fn table_states_core_counts_and_per_thread_throughput_inline() {
        let mut m = measurement(4115.0, 16, 1_048_576);
        m.tokenizer = "gigatoken".to_owned();
        let text = report_with(vec![Availability::Measured(m)]).render_table();
        assert!(text.contains("16 physical / 32 logical"), "{text}");
        assert!(text.contains("2 SMT siblings per core"), "{text}");
        assert!(text.contains("MB/s/core"), "{text}");
        assert!(text.contains("MB/s/thread"), "{text}");
        assert!(text.contains("NVIDIA GeForce RTX 5090"), "{text}");
        assert!(text.contains("cl100k_base"), "{text}");
        assert!(text.contains("3.9041"), "{text}");
        // 4115 MB/s on 16 threads is 257.19 per thread.
        assert!(text.contains("257.19"), "{text}");
        assert!(text.contains("gigatoken"), "{text}");
    }

    /// An unavailable baseline must appear with its reason and must never be
    /// filled in with an estimate. A fabricated row is indistinguishable from
    /// a measured one once it is in a table.
    #[test]
    fn unavailable_baselines_are_listed_with_reasons_and_no_number() {
        let text = report_with(vec![Availability::Unavailable {
            tokenizer: "fastokens".to_owned(),
            reason: "wheel has no cp312 build for this platform".to_owned(),
        }])
        .render_table();
        assert!(text.contains("fastokens"), "{text}");
        assert!(text.contains("wheel has no cp312 build for this platform"), "{text}");
        assert!(text.contains("never estimated"), "{text}");
        let r = report_with(vec![Availability::Unavailable {
            tokenizer: "x".to_owned(),
            reason: "y".to_owned(),
        }]);
        assert_eq!(r.measured().count(), 0);
        assert_eq!(r.peak_for("x"), None);
    }

    /// A defect cell must be flagged in the rendered table, not just in a
    /// return value nobody reads. The whole point is that a bad number cannot
    /// leave this harness looking clean.
    ///
    /// The fixture is a real cell from the first full sweep on this machine:
    /// tiktoken batch, 16 threads, 60477-byte documents, 50.92 MB/s absolute.
    /// It is a genuine negative control rather than a value tuned to trip the
    /// check, because it clears both harness gates (0.66 s timed region, 12.44x
    /// achieved parallelism) and is still only 3.18 MB/s per core against the
    /// same library's 19 MB/s per core on one thread. Something is wrong in
    /// that cell and the guard must keep saying so.
    #[test]
    fn rendered_table_flags_suspected_defect_rows() {
        let mut bad = measurement(50.92, 16, 60_477);
        bad.tokenizer = "tiktoken".to_owned();
        assert!((bad.mb_per_second_per_core() - 3.1825).abs() < 1e-4);
        // Implausible per core, so it is caught under the new divisor and not
        // only under the old per-thread one.
        assert!(bad.mb_per_second_per_core() < PLAUSIBLE_FLOOR_MB_S_PER_CORE);
        let r = report_with(vec![Availability::Measured(bad)]);
        assert_eq!(r.suspected_defects().len(), 1);
        assert_eq!(r.harness_defects().len(), 0);
        assert_eq!(r.known_slow().len(), 0);
        let text = r.render_table();
        assert!(text.contains("UNEXPLAINED, UNDER FLOOR"), "{text}");
        assert!(text.contains("5.0 MB/s per-core floor with no"), "{text}");
        assert!(text.contains("3.183 MB/s/core"), "{text}");
        // The absolute figure stays visible beside the per-core one, so a
        // reader can see both without recomputing either.
        assert!(text.contains("50.92"), "{text}");
    }

    /// A clean sweep must say so explicitly, so "no defect flag" is a
    /// positive statement rather than the absence of output. Both gates report
    /// affirmatively: the harness gate and the plausibility floor.
    #[test]
    fn clean_sweep_states_the_floor_was_cleared() {
        let r = report_with(vec![Availability::Measured(measurement(36.9, 1, 65_536))]);
        assert!(r.suspected_defects().is_empty());
        assert!(r.harness_defects().is_empty());
        let text = r.render_table();
        assert!(text.contains("clears the 5.0 MB/s per-core floor"), "{text}");
        assert!(text.contains("timed at least 0.25 s"), "{text}");
        assert!(text.contains("delivered at least 50% of its requested threads"), "{text}");
        assert!(!text.contains("UNEXPLAINED"), "{text}");
        assert!(!text.contains("HARNESS DEFECT"), "{text}");
    }

    /// Peak selection must pick the highest absolute MB/s for that tokenizer
    /// and ignore other libraries' rows, otherwise the summary line credits
    /// one library with another's number.
    #[test]
    fn peak_selects_the_fastest_row_for_that_tokenizer_only() {
        let mut slow = measurement(40.0, 1, 65_536);
        slow.tokenizer = "tiktoken".to_owned();
        let mut fast = measurement(130.0, 16, 65_536);
        fast.tokenizer = "tiktoken".to_owned();
        let mut other = measurement(4115.0, 16, 65_536);
        other.tokenizer = "gigatoken".to_owned();
        let r = report_with(vec![
            Availability::Measured(slow),
            Availability::Measured(fast),
            Availability::Measured(other),
        ]);
        let peak = r.peak_for("tiktoken").expect("tiktoken rows exist");
        assert!((peak.mb_per_second() - 130.0).abs() < 1e-9);
        assert_eq!(peak.threads, 16);
        let g = r.peak_for("gigatoken").expect("gigatoken row exists");
        assert!((g.mb_per_second() - 4115.0).abs() < 1e-9);
        assert_eq!(r.peak_for("absent"), None);
    }

    /// JSON must carry the absolute figures and the core counts, and must
    /// parse. Downstream comparison scripts read this, so a row without
    /// thread and core counts is unusable for an honest comparison.
    #[test]
    fn json_carries_absolute_figures_and_core_counts() {
        let mut m = measurement(36.9, 1, 65_536);
        m.tokenizer = "tiktoken".to_owned();
        let json = report_with(vec![
            Availability::Measured(m),
            Availability::Unavailable {
                tokenizer: "fastokens".to_owned(),
                reason: "not installed".to_owned(),
            },
        ])
        .to_json();
        for needle in [
            "\"physical_cores\": 16",
            "\"logical_cores\": 32",
            "\"threads\": 1",
            "\"pinned_to_physical\": true",
            "\"mb_per_s\": 36.9",
            "\"mb_per_s_per_thread\": 36.9",
            "\"status\": \"unavailable\"",
            "\"reason\": \"not installed\"",
            "\"digest\": \"0x123456789abcdef0\"",
            "\"bytes_per_token\": 3.904100",
        ] {
            assert!(json.contains(needle), "missing {needle} in {json}");
        }
        // Balanced braces and brackets, a cheap structural check.
        assert_eq!(json.matches('{').count(), json.matches('}').count());
        assert_eq!(json.matches('[').count(), json.matches(']').count());
    }

    /// Regime spelling must round-trip, and an unknown spelling must be
    /// rejected rather than silently becoming `batch`. Mislabelling a
    /// single-document latency row as a batch row would make a 1-thread
    /// figure look like a throughput result.
    #[test]
    fn regime_round_trips_and_rejects_unknown_spellings() {
        assert_eq!(Regime::SingleDocument.as_str(), "single");
        assert_eq!(Regime::Batch.as_str(), "batch");
        assert_eq!(Regime::from_str_opt("single"), Some(Regime::SingleDocument));
        assert_eq!(Regime::from_str_opt("batch"), Some(Regime::Batch));
        assert_eq!(Regime::from_str_opt("Batch"), None);
        assert_eq!(Regime::from_str_opt(""), None);
        assert_eq!(Regime::from_str_opt("stream"), None);
    }

    /// The sweep must straddle the crossover: small enough that a kernel
    /// launch cannot amortize, large enough that host libraries reach steady
    /// state. Shrinking either end removes the regime the argument rests on.
    #[test]
    fn default_sweep_straddles_the_crossover_regime() {
        assert_eq!(DEFAULT_TARGET_TOKENS.first(), Some(&256));
        assert!(
            DEFAULT_TARGET_TOKENS.last().copied().unwrap_or(0) >= 131_072,
            "sweep must reach 128K+ tokens"
        );
        // Strictly increasing, so table ordering is meaningful.
        for w in DEFAULT_TARGET_TOKENS.windows(2) {
            assert!(w[1] > w[0], "sweep must be ascending: {w:?}");
        }
        // Every step is a power of two, so sizes are reproducible by hand.
        for t in DEFAULT_TARGET_TOKENS {
            assert!(t.is_power_of_two(), "{t} is not a power of two");
        }
    }

    /// A corpus built from a real tree must be non-empty, respect the byte
    /// budget, and be byte-identical across two builds. A corpus that differs
    /// between runs makes every rerun look like a regression.
    #[test]
    fn corpus_from_tree_is_deterministic_and_respects_the_budget() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let a = Corpus::from_tree(root, 4096).expect("crate tree has .rs and .toml text");
        let b = Corpus::from_tree(root, 4096).expect("second build");
        assert_eq!(a.text, b.text);
        assert_eq!(a.facts.digest, b.facts.digest);
        assert_eq!(a.facts.bytes, a.text.len());
        assert!(a.facts.bytes <= 4096, "budget exceeded: {}", a.facts.bytes);
        assert!(a.facts.bytes > 0);
        assert!(a.facts.files >= 1);
        // A larger budget must yield strictly more text from this tree, and
        // must extend the same prefix rather than reshuffle it.
        let big = Corpus::from_tree(root, 65_536).expect("larger budget");
        assert!(big.facts.bytes > a.facts.bytes);
        assert!(big.text.starts_with(&a.text));
    }

    /// An empty or missing corpus root must error rather than measure zero
    /// bytes, which would divide into an infinite throughput.
    #[test]
    fn corpus_rejects_empty_sources() {
        assert!(Corpus::from_tree(Path::new("/nonexistent-exatok-corpus-root"), 4096).is_err());
        assert!(Corpus::from_file(Path::new("/nonexistent-exatok-corpus-file"), 4096).is_err());
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        assert!(Corpus::from_tree(root, 0).is_err(), "a zero-byte budget is not a corpus");
    }

    /// Repo-root discovery must find the OUTERMOST checkout containing this crate,
    /// so the corpus root does not depend on the caller's directory and does not move
    /// when the crate gains its own nested `.git`. This test locks out the regression
    /// where first-ancestor lookup moved the benchmark corpus from the outer checkout
    /// to the crate tree the day the nested repository was created: the corpus digest
    /// changed, and with it every token count a baseline comparison is built on.
    /// Idempotence is the portable form of outermost: re-querying from the answer must
    /// return the answer, which only holds when the walk cannot stop early.
    #[test]
    fn repo_root_is_found_by_walking_up_to_the_git_directory() {
        let here = Path::new(env!("CARGO_MANIFEST_DIR"));
        let root = find_repo_root(here).expect("crate lives inside a git checkout");
        assert!(root.join(".git").exists());
        assert!(here.starts_with(&root));
        assert_eq!(
            find_repo_root(&root).as_deref(),
            Some(root.as_path()),
            "the walk must be outermost-idempotent: re-querying from {} moved the root",
            root.display()
        );
        assert_eq!(find_repo_root(Path::new("/")), None);
    }

    /// Config defaults must point at the driver and the durable vocabulary
    /// cache, and must prefer the bench venv when it exists. A default that
    /// silently picks the system python measures whatever happens to be
    /// installed there, which is not reproducible.
    #[test]
    fn sweep_config_defaults_point_at_driver_and_durable_vocab() {
        let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let root = find_repo_root(crate_dir).expect("git checkout");
        let cfg = SweepConfig::defaults(crate_dir, &root);
        assert!(cfg.driver.ends_with("benches/baselines/host_baselines.py"));
        assert_eq!(cfg.vocab, "cl100k_base");
        assert!(cfg.tiktoken_ranks.ends_with(".cache/exatok-vocab/cl100k_base.tiktoken"));
        assert_eq!(cfg.hf_repo, "Xenova/gpt-4");
        assert_eq!(cfg.batch_budget_bytes, 32 * 1024 * 1024);
        assert_eq!(cfg.target_tokens, DEFAULT_TARGET_TOKENS.to_vec());
        assert!(cfg.reps >= 3, "fewer than three reps cannot yield a spread");
        assert!(cfg.warmups >= 1, "an unwarmed first call measures page faults");
        assert_eq!(
            cfg.corpus_scratch.file_name().and_then(|n| n.to_str()),
            Some("bench-corpus.txt")
        );
        assert!(
            !cfg.corpus_scratch.starts_with(crate_dir),
            "the corpus must not land inside the source tree, but it is at {}",
            cfg.corpus_scratch.display()
        );
        // Unconditional: a conditional assertion here asserted nothing on the
        // machine where the venv had been deleted, which is exactly the machine
        // whose config needed checking.
        assert_eq!(
            cfg.python,
            home_dir().join(BENCH_VENV_REL).join("bin/python"),
            "the interpreter must be the durable off-tree venv, with no system fallback"
        );
        assert!(
            !cfg.python.starts_with(scratch_root()),
            "a baseline venv under the cargo target directory gets cleaned away, but it is at {}",
            cfg.python.display()
        );
        assert_eq!(
            cfg.report_dir,
            Some(home_dir().join(BENCH_REPORT_REL)),
            "every sweep must persist a report by default"
        );
        assert!(cfg.require_baselines, "a wiped venv must fail loudly, not yield empty rows");
    }

    /// The scratch corpus must never be written inside the source tree.
    ///
    /// A sweep once wrote its 64 MiB corpus to `<crate>/target/bench-corpus.txt`.
    /// That path is an in-tree `target/`, which this repository's hygiene rule
    /// deletes on sight, so a cleanup was entitled to remove the file while the
    /// baseline driver was reading it. Keeping the corpus off-tree is what makes a
    /// long sweep safe from routine housekeeping.
    #[test]
    fn the_scratch_corpus_never_lands_inside_the_source_tree() {
        let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let root = scratch_root();
        assert!(
            !root.starts_with(crate_dir),
            "scratch_root resolved into the crate at {}",
            root.display()
        );
        assert!(root.is_absolute(), "scratch root {} is not absolute", root.display());
    }

    /// `scratch_root` must find the cargo target directory, not guess a sibling.
    ///
    /// It walks up from the test binary at `<target>/<profile>/deps/<bin>`, so the
    /// answer has to be the directory two levels above the profile directory. If
    /// the walk ever silently falls through to the temp-dir fallback the corpus
    /// still works but stops sharing the artifact directory's lifetime, so pin the
    /// derivation rather than merely checking that some path came back.
    #[test]
    fn scratch_root_resolves_to_the_cargo_target_directory() {
        let exe = std::env::current_exe().expect("test binary path");
        let profile = exe
            .ancestors()
            .find(|d| matches!(d.file_name().and_then(|n| n.to_str()), Some("debug" | "release")))
            .expect("test binary must sit under a profile directory");
        assert_eq!(scratch_root(), profile.parent().expect("target dir"));
    }

    /// A signalled driver must be reported by signal, never as `None`.
    ///
    /// The sweep's diagnostic used to print `status.code()`, which is `None` for a
    /// killed process. Combined with the empty stderr a kill leaves behind, the
    /// message `exited with None ... stderr:` reads as a silent clean failure and
    /// hid an external kill (`rc=137`, SIGKILL) behind what looked like a driver
    /// bug. Every signal must be named so the reader knows to look outside the
    /// driver.
    #[test]
    fn a_driver_killed_by_a_signal_is_reported_by_its_signal_number() {
        for signal in [9_i32, 7, 11, 15] {
            let status = std::process::ExitStatus::from_raw(signal);
            let text = describe_termination(&status);
            assert_eq!(
                text,
                format!("no exit code, killed by signal {signal}"),
                "signal {signal} was not named"
            );
            assert!(!text.contains("None"), "signal {signal} rendered as None: {text}");
        }
    }

    /// An ordinary non-zero exit must still be reported as an exit code.
    ///
    /// The signal branch must not swallow the common case. A driver that raised a
    /// Python exception exits 1, and reporting that as a signal would send the
    /// reader hunting for a kill that never happened.
    #[test]
    fn a_driver_that_exits_non_zero_is_reported_by_its_exit_code() {
        for code in [1_i32, 2, 101] {
            let status = std::process::ExitStatus::from_raw(code << 8);
            assert_eq!(describe_termination(&status), format!("exit code {code}"));
        }
    }

    /// Empty stderr must be labelled, because its emptiness is the evidence.
    ///
    /// A killed process writes nothing. If the message simply interpolates the
    /// empty string it trails off after `stderr:` and the reader cannot tell an
    /// absent report from a lost one.
    #[test]
    fn empty_stderr_is_labelled_rather_than_printed_as_nothing() {
        let described = describe_stderr(b"");
        assert!(described.contains("<empty"), "empty stderr rendered as {described:?}");
        assert!(described.contains("reported nothing"));
        assert_eq!(describe_stderr(b"   \n  \t "), described, "whitespace is not a report");
        assert_eq!(describe_stderr(b"  boom: bad rank  "), "boom: bad rank");
    }

    /// A SIGKILLed driver must point at the reaper logs, not at the driver.
    ///
    /// Signal 9 has no handler and leaves no stderr, so an investigation with only
    /// the signal number in hand still has to guess. On this fleet a cron CPU
    /// watchdog reaps any non-allowlisted process holding >95% CPU for five
    /// minutes, which is exactly what an honest multi-minute sweep does, and it
    /// records the kill. Three real sweeps died that way before the message named
    /// the log, so the hint must survive.
    #[test]
    fn a_sigkilled_driver_points_at_the_watchdog_logs() {
        let hint = kill_hint(&std::process::ExitStatus::from_raw(9));
        assert!(hint.contains("/tmp/cpu-watchdog.log"), "hint lost the log path: {hint}");
        assert!(hint.contains("external reaper"), "hint does not name a reaper: {hint}");
        assert!(hint.contains("allowlist"), "hint does not say how to fix it: {hint}");
    }

    /// Signal 7 must blame the corpus, and a clean exit must add no advice.
    ///
    /// SIGBUS on this harness means the corpus was truncated or deleted under a
    /// mapped read, which is a different fix from a reaper, so the two must not
    /// share advice. An ordinary non-zero exit already carries the driver's own
    /// stderr, and appending speculation about reapers there would mislead.
    #[test]
    fn only_the_relevant_signal_earns_advice() {
        let bus = kill_hint(&std::process::ExitStatus::from_raw(7));
        assert!(bus.contains("off-tree"), "SIGBUS hint lost the corpus advice: {bus}");
        assert!(!bus.contains("cpu-watchdog"), "SIGBUS must not blame the reaper: {bus}");
        for code in [1_i32, 101] {
            let status = std::process::ExitStatus::from_raw(code << 8);
            assert_eq!(kill_hint(&status), "", "exit code {code} must earn no signal advice");
        }
        assert_eq!(kill_hint(&std::process::ExitStatus::from_raw(11)), "");
    }

    /// Locks out a miscomputed calendar in the report filename.
    ///
    /// `utc_stamp` hand-rolls civil-from-days because the crate carries no date
    /// dependency. The two ways that goes wrong are the leap-year rule and the
    /// century exception, and both are silent: a wrong month or day still
    /// produces a plausible-looking filename, so two runs can collide on one
    /// name or sort into the wrong order, which is exactly the evidence trail
    /// this filename exists to keep. 2100 is the load-bearing case, being
    /// divisible by 100 but not 400 and therefore NOT a leap year.
    #[test]
    fn utc_stamp_matches_the_calendar_at_epoch_and_leap_boundaries() {
        let at = |secs: u64| {
            utc_stamp(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs))
        };
        assert_eq!(at(0), "19700101T000000Z");
        assert_eq!(at(1), "19700101T000001Z");
        assert_eq!(at(59), "19700101T000059Z");
        assert_eq!(at(60), "19700101T000100Z");
        assert_eq!(at(86_399), "19700101T235959Z");
        assert_eq!(at(86_400), "19700102T000000Z");
        // 2000 is divisible by 400, so 29 February exists.
        assert_eq!(at(951_782_400), "20000229T000000Z");
        assert_eq!(at(1_709_164_800), "20240229T000000Z");
        assert_eq!(at(1_751_328_000), "20250701T000000Z");
        // 2100 is divisible by 100 and not 400: 28 February is followed by
        // 1 March, and an algorithm that grants it a 29th lands a day early on
        // every subsequent date.
        assert_eq!(at(4_107_456_000), "21000228T000000Z");
        assert_eq!(at(4_107_542_400), "21000301T000000Z");
        assert_eq!(at(253_402_300_799), "99991231T235959Z");
    }

    /// Locks out a filename that does not sort chronologically as text.
    ///
    /// The stamp is fixed-width and big-endian precisely so `ls` order is time
    /// order. A zero-padding regression would break that silently, and finding
    /// the newest report would then need a stat of every file.
    #[test]
    fn utc_stamp_is_fixed_width_and_sorts_as_text_in_time_order() {
        let at = |secs: u64| {
            utc_stamp(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs))
        };
        let early = at(951_782_400);
        let late = at(1_751_328_000);
        assert_eq!(early.len(), 16, "stamp {early} is not the fixed 16 characters");
        assert_eq!(late.len(), 16);
        assert!(early < late, "{early} must sort before {late}");
        // A single-digit month and day must still occupy two characters.
        assert_eq!(at(0), "19700101T000000Z");
    }

    /// Locks out a region clock that cannot distinguish a throttle from a boost,
    /// and one that reads an unavailable probe as a 100% collapse.
    ///
    /// `busy_weighted_mhz` returns 0.0 to mean "no reading". If `drift_ratio`
    /// divided by that it would report -1.0, a catastrophic throttle, on every
    /// machine whose per-CPU probes are simply absent.
    #[test]
    fn region_clock_drift_is_signed_and_reads_zero_as_no_claim() {
        let fell = RegionClock { start_mhz: 5000.0, end_mhz: 4600.0, busy_cpus: 16 };
        assert!((fell.drift_ratio() - -0.08).abs() < 1e-12);
        assert!(fell.is_significant());
        let rose = RegionClock { start_mhz: 4600.0, end_mhz: 5000.0, busy_cpus: 16 };
        assert!((rose.drift_ratio() - 0.086_956_521_739_130_43).abs() < 1e-12);
        assert!(rose.is_significant(), "a boost mid-region biases throughput too");
        let steady = RegionClock { start_mhz: 5000.0, end_mhz: 4990.0, busy_cpus: 32 };
        assert!((steady.drift_ratio() - -0.002).abs() < 1e-12);
        assert!(!steady.is_significant());
        // No reading at all: exactly zero, not -1.0.
        let absent = RegionClock { start_mhz: 0.0, end_mhz: 0.0, busy_cpus: 0 };
        assert!((absent.drift_ratio() - 0.0).abs() < f64::EPSILON);
        assert!(!absent.is_significant());
    }

    /// Locks out making the busy-clock fields mandatory in the record format.
    ///
    /// Several negative parse tests feed records that omit one required field to
    /// prove it is required. If the busy-clock fields became required too, those
    /// records would be rejected for the missing clock instead of the field
    /// under test, and every one of those tests would pass while asserting
    /// nothing about its own subject.
    #[test]
    fn a_record_without_busy_clock_fields_parses_as_no_reading() {
        let ctx =
            MachineContext { physical_cores: 16, logical_cores: 32, pinned_to_physical: true };
        let line = "record\ttokenizer=tiktoken\tversion=0.12.0\tvocab=cl100k_base\t\
                    regime=single\ttarget_tokens=1024\tdoc_bytes=4096\tdocs=1\t\
                    input_bytes=4096\ttokens=1024\tsamples=0.25\twarmups=1\tthreads=1\t\
                    mean_mhz=5100.5\tmatches_ref=1\tcpu_secs=0.25\tinner_reps=1\t\
                    foreign_cpu_secs=0.0";
        let ev = parse_driver_line(line, ctx, 1).unwrap().expect("a record");
        let DriverEvent::Record(m) = ev else { panic!("expected a record event") };
        assert_eq!(m.region_clock, None, "an absent probe must read as None, not as 0 MHz");
        // The rest of the record must still parse, so the absence is inert.
        assert!((m.mean_mhz - 5100.5).abs() < 1e-9);
        assert_eq!(m.tokens, 1024);
    }

    /// Locks out dropping or transposing the busy-clock values during parsing.
    ///
    /// Start and end are the same type and adjacent in the record, so a swap is
    /// easy and would invert every drift sign in the report.
    #[test]
    fn a_record_with_busy_clock_fields_parses_the_exact_values() {
        let ctx =
            MachineContext { physical_cores: 16, logical_cores: 32, pinned_to_physical: true };
        let line = "record\ttokenizer=tiktoken\tversion=0.12.0\tvocab=cl100k_base\t\
                    regime=single\ttarget_tokens=1024\tdoc_bytes=4096\tdocs=1\t\
                    input_bytes=4096\ttokens=1024\tsamples=0.25\twarmups=1\tthreads=1\t\
                    mean_mhz=3274.4\tbusy_mhz_start=4618.6\tbusy_mhz_end=4568.0\tbusy_cpus=22\t\
                    matches_ref=1\tcpu_secs=0.25\tinner_reps=1\tforeign_cpu_secs=0.0";
        let ev = parse_driver_line(line, ctx, 1).unwrap().expect("a record");
        let DriverEvent::Record(m) = ev else { panic!("expected a record event") };
        let clock = m.region_clock.expect("the record carried all three fields");
        assert!((clock.start_mhz - 4618.6).abs() < 1e-9, "start was {}", clock.start_mhz);
        assert!((clock.end_mhz - 4568.0).abs() < 1e-9, "end was {}", clock.end_mhz);
        assert_eq!(clock.busy_cpus, 22);
        // Fell slightly, so the sign must be negative and the magnitude small.
        assert!(clock.drift_ratio() < 0.0, "a fall must read negative");
        assert!((clock.drift_ratio() - -0.010_955_700_861_733_07).abs() < 1e-12);
        assert!(!clock.is_significant());
        // The whole-machine mean is kept alongside and must NOT be overwritten
        // by the weighted figure: the gap between them is the point.
        assert!((m.mean_mhz - 3274.4).abs() < 1e-9);
    }

    /// Locks out silently defaulting a corrupt clock field to zero.
    ///
    /// A driver that emitted a garbled number would otherwise produce a cell
    /// claiming no clock reading, which is indistinguishable from a machine
    /// without per-CPU probes and hides a real driver bug.
    #[test]
    fn a_record_with_a_malformed_busy_clock_is_rejected() {
        let ctx =
            MachineContext { physical_cores: 16, logical_cores: 32, pinned_to_physical: true };
        let base = "record\ttokenizer=tiktoken\tversion=0.12.0\tvocab=cl100k_base\t\
                    regime=single\ttarget_tokens=1024\tdoc_bytes=4096\tdocs=1\t\
                    input_bytes=4096\ttokens=1024\tsamples=0.25\twarmups=1\tthreads=1\t\
                    mean_mhz=5000\tmatches_ref=1\tcpu_secs=0.25\tinner_reps=1\t\
                    foreign_cpu_secs=0.0";
        for bad in [
            "\tbusy_mhz_start=fast\tbusy_mhz_end=4568.0\tbusy_cpus=22",
            "\tbusy_mhz_start=4618.6\tbusy_mhz_end=slow\tbusy_cpus=22",
            "\tbusy_mhz_start=4618.6\tbusy_mhz_end=4568.0\tbusy_cpus=lots",
        ] {
            let line = format!("{base}{bad}");
            assert!(
                parse_driver_line(&line, ctx, 1).is_err(),
                "a malformed busy clock must be rejected, but this parsed: {bad}"
            );
        }
    }

    /// Locks out the regression that made a published figure unreproducible.
    ///
    /// The baseline venv was stored under the cargo target directory and got
    /// cleaned away. The sweep then reported one `ModuleNotFoundError` per
    /// library, which reads as libraries that do not exist on this platform
    /// rather than one missing directory, and a gigatoken throughput figure
    /// published from an earlier run became unverifiable. The refusal must name
    /// the path and the command that rebuilds it.
    #[test]
    fn preflight_names_the_expected_venv_and_the_command_that_rebuilds_it() {
        let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let root = find_repo_root(crate_dir).expect("git checkout");
        let mut cfg = SweepConfig::defaults(crate_dir, &root);
        cfg.python = PathBuf::from("/nonexistent/exatok-bench-venv/bin/python");
        let err = preflight_baselines(&cfg).expect_err("a missing interpreter must refuse");
        let text = err.to_string();
        assert!(
            text.contains("/nonexistent/exatok-bench-venv/bin/python"),
            "the refusal must name the interpreter it looked for, but said: {text}"
        );
        assert!(
            text.contains(BENCH_VENV_REL),
            "the refusal must name the durable venv location, but said: {text}"
        );
        assert!(
            text.contains("python3 -m venv"),
            "the refusal must carry the command that rebuilds it, but said: {text}"
        );
        for module in BASELINE_MODULES {
            assert!(
                text.contains(module),
                "the rebuild command must install {module}, but said: {text}"
            );
        }
    }

    /// Locks out a durable path that is really a build-output path.
    ///
    /// The whole lesson of the wiped venv is that anything under the cargo
    /// target directory is deletable without warning. A future edit that points
    /// either constant back there would reintroduce exactly that failure.
    #[test]
    fn the_durable_bench_paths_are_not_under_build_output() {
        for rel in [BENCH_VENV_REL, BENCH_REPORT_REL] {
            let path = home_dir().join(rel);
            assert!(
                !path.starts_with(scratch_root()),
                "{} is under the cargo target directory and will be cleaned away",
                path.display()
            );
            assert!(!rel.contains("target"), "{rel} names a build-output directory");
            assert!(path.is_absolute(), "{} must be absolute", path.display());
        }
        assert_ne!(BENCH_VENV_REL, BENCH_REPORT_REL);
    }

    /// Locks out a sweep that refuses to certify a table but keeps no evidence.
    ///
    /// Recovering which cells failed and why previously required a full rerun,
    /// because only an explicit `--json` wrote anything. The written file must
    /// be complete enough to answer that question offline, so it has to carry
    /// the per-cell foreign load, achieved parallelism, best-case seconds and
    /// clock, and it must record its own path so a caller can name it.
    #[test]
    fn persist_writes_a_timestamped_report_carrying_the_diagnostic_fields() {
        let report = report_with(vec![Availability::Measured(measurement(20.0, 1, 4096))]);
        let dir = std::env::temp_dir().join(format!(
            "exatok-persist-{}-{}",
            std::process::id(),
            utc_stamp(std::time::SystemTime::now())
        ));
        let path = report.persist(&dir).expect("a writable temp directory");
        let name = path.file_name().and_then(|n| n.to_str()).expect("a filename");
        assert!(name.starts_with("host-baseline-"), "unexpected report name {name}");
        assert!(name.ends_with("Z.json"), "report name {name} is not UTC-stamped");
        assert_eq!(name.len(), "host-baseline-".len() + 16 + ".json".len());
        let text = std::fs::read_to_string(&path).expect("the report we just wrote");
        // The four fields that turned "8 cells failed" into a diagnosis.
        for key in [
            "\"foreign_load_ratio\"",
            "\"achieved_parallelism\"",
            "\"best_secs\"",
            "\"region_clock\"",
        ] {
            assert!(text.contains(key), "the report must carry {key}, but it did not");
        }
        assert!(text.contains("\"status\": \"measured\""));
        assert!(text.trim_end().ends_with('}'), "the report must be closed JSON");
        std::fs::remove_file(&path).expect("cleanup");
        std::fs::remove_dir(&dir).expect("cleanup");
    }

    /// Locks out a report that renders an absent clock as a real reading.
    ///
    /// `None` means the per-CPU probes were unavailable. Rendering that as
    /// `0 MHz` would let a consumer compute a -100% drift, and rendering it as
    /// a steady clock would assert something never measured.
    #[test]
    fn an_absent_region_clock_serializes_as_null_not_as_zero() {
        let mut m = measurement(20.0, 1, 4096);
        m.region_clock = None;
        let json = report_with(vec![Availability::Measured(m)]).to_json();
        assert!(
            json.contains("\"region_clock\": null"),
            "an unmeasured clock must serialize as null, but the report said: {json}"
        );
        let present =
            report_with(vec![Availability::Measured(measurement(20.0, 1, 4096))]).to_json();
        assert!(
            present.contains("\"busy_cpus\": 16"),
            "a measured clock must serialize its busy CPU count, but said: {present}"
        );
        assert!(present.contains("\"significant\": false"));
    }

    fn paired_with(speedups: Vec<f64>) -> Paired {
        Paired {
            label_a: "old".to_owned(),
            label_b: "new".to_owned(),
            a_unit_secs: speedups.iter().map(|_| 1.0).collect(),
            b_unit_secs: speedups.iter().map(|s| 1.0 / s).collect(),
            speedups,
            voided_rounds: 0,
            foreign_resident_baseline_mib: 24_204,
            foreign_sm_percent_max: 41,
            // A synthetic fixture probes no region, so NOT RECORDED is the
            // truthful value and the accessors return None on it. Tests that
            // exercise the stationarity gate push explicit readings instead of
            // inheriting a fabricated quiet machine from this helper.
            host_foreign_load: Vec::new(),
            host_foreign_load_arms: Vec::new(),
            unit_work: None,
        }
    }

    /// Locks out a paired comparison published through non-stationary host load.
    ///
    /// THE DEFECT THIS LOCKS OUT. Two full captures of the same four shapes, each
    /// passing every gate this harness had, disagreed on which arm wins cjk. The
    /// cause was concurrent cargo builds: the device arm is 89 to 97 percent host
    /// orchestration over small latency-bound driver calls and is preempted by
    /// competing rustc, while the host arm is a throughput-bound loop that shrugs.
    /// `time_region` measured `foreign_cpu_secs` the whole time and the paired
    /// path discarded it, so the gate was green because it never looked. If this
    /// regresses, a comparison taken across a load transient publishes a sign that
    /// belongs to the contaminant rather than to the code under test.
    #[test]
    fn a_paired_comparison_refuses_host_load_that_moved_while_it_ran() {
        // Tight deltas, so the OLD gate passes and only stationarity can refuse.
        let mut drifting = paired_with(vec![1.20; MIN_PAIRED_ROUNDS as usize]);
        assert!((drifting.speedup_rel_stddev() - 0.0).abs() < 1e-12);
        // Load ramps 0.1 -> 8.0 cores across the rounds: a build starting mid-run.
        drifting.host_foreign_load = vec![0.1, 0.2, 0.4, 1.0, 2.0, 4.0, 6.0, 8.0];
        let drift = drifting.host_load_rel_stddev().expect("eight readings have a spread");
        assert!(
            drift > MAX_PAIRED_HOST_LOAD_DRIFT,
            "a 0.1 to 8.0 core ramp must exceed the {MAX_PAIRED_HOST_LOAD_DRIFT} drift gate, \
             got {drift}"
        );
        assert!(
            !drifting.is_publishable(),
            "zero delta spread must NOT publish when the contaminant moved: that is the \
             precise combination that published a wrong cjk sign"
        );
        let text = drifting.render();
        assert!(text.contains("NOT publishable"), "{text}");
        assert!(text.contains("host-load"), "the refusal must name host load as the cause: {text}");

        // Heavily but EVENLY loaded: the level is high and it still publishes,
        // because a stationary contaminant sits in both arms and cancels.
        let mut loaded = paired_with(vec![1.20; MIN_PAIRED_ROUNDS as usize]);
        loaded.host_foreign_load = vec![9.8; MIN_PAIRED_ROUNDS as usize];
        assert!(
            (loaded.host_load_rel_stddev().expect("eight readings") - 0.0).abs() < 1e-12,
            "identical readings are perfectly stationary"
        );
        assert!(
            (loaded.median_host_load().expect("eight readings") - 9.8).abs() < 1e-12,
            "the level must be reported even though it is not gated"
        );
        assert!(
            loaded.is_publishable(),
            "9.8 cores of EVEN foreign load still yields a valid ratio; gating on level \
             would refuse the work this estimator exists to do"
        );
        assert!(loaded.render().contains("9.80 cores foreign"), "{}", loaded.render());
    }

    /// Locks out an unrecorded host load reading as a quiet machine.
    ///
    /// `from_unit_secs` pairs separate processes and has no region probe to copy,
    /// so its vector is permanently empty. If empty ever renders as 0.00 cores or
    /// satisfies the drift gate by looking stationary, a cross-process comparison
    /// would claim a contention check that never happened, which is the exact
    /// inversion the field was added to prevent.
    #[test]
    fn an_unrecorded_host_load_renders_as_absent_not_as_idle() {
        let eight = vec![1.0; MIN_PAIRED_ROUNDS as usize];
        let half = vec![0.5; MIN_PAIRED_ROUNDS as usize];
        let cross = Paired::from_unit_secs("old", "new", &eight, &half, 0, 0)
            .expect("eight clean rounds per arm");
        assert!(cross.host_foreign_load.is_empty(), "a cross-process pairing probes no region");
        assert_eq!(cross.median_host_load(), None, "absent must not read as a level");
        assert_eq!(cross.host_load_rel_stddev(), None, "absent must not read as stationary");
        let text = cross.render();
        assert!(text.contains("NOT RECORDED"), "absence must be disclosed: {text}");
        assert!(
            !text.contains("0.00 cores foreign"),
            "an unmeasured machine must never render as an idle one: {text}"
        );
        // Absence does not BLOCK publication either: the delta is still sound.
        assert!(cross.is_publishable(), "a valid cross-process delta stays publishable");

        // An idle in-process cell is a THIRD state: recorded, and genuinely zero.
        let mut idle = paired_with(vec![1.20; MIN_PAIRED_ROUNDS as usize]);
        idle.host_foreign_load = vec![0.0; MIN_PAIRED_ROUNDS as usize];
        assert_eq!(idle.median_host_load(), Some(0.0), "idle is measured, not absent");
        assert_eq!(
            idle.host_load_rel_stddev(),
            Some(0.0),
            "a near-zero mean makes relative spread undefined, not infinite, and idle is \
             maximally stationary"
        );
        assert!(idle.render().contains("0.00 cores foreign"), "{}", idle.render());
    }

    /// Locks the two host-load series to a single absence state.
    ///
    /// A cross-process pairing has no region probe, so the max series is empty and
    /// renders as NOT RECORDED. If a later edit populates the per-arm series there
    /// while leaving the max empty, the cell reports no contaminant reading while
    /// carrying fabricated per-arm loads, which is the same "a missing reading must
    /// never read as a quiet machine" defect one level down and invisible to the
    /// renderer. Deterministic, so it runs by default: the loop-level max
    /// consistency needs real timed regions and is checked in an ignored test.
    #[test]
    fn the_two_host_load_series_are_absent_together() {
        let eight = vec![1.0; MIN_PAIRED_ROUNDS as usize];
        let half = vec![0.5; MIN_PAIRED_ROUNDS as usize];
        let cross = Paired::from_unit_secs("old", "new", &eight, &half, 0, 0)
            .expect("eight clean rounds per arm");
        assert!(cross.host_foreign_load.is_empty(), "no region probe, so no gated reading");
        assert_eq!(
            cross.host_foreign_load_arms.len(),
            cross.host_foreign_load.len(),
            "the per-arm series must be absent exactly when the gated one is, got {} against {}",
            cross.host_foreign_load_arms.len(),
            cross.host_foreign_load.len()
        );
        assert_eq!(cross.median_host_load(), None, "absent must not read as a level");
    }

    /// Locks out quoting the luckiest round as the paired result.
    ///
    /// An absolute cell quotes its MINIMUM, because contention only ever adds
    /// elapsed time. A paired ratio must NOT: the contaminant has already
    /// largely cancelled, so taking the best ratio just selects the round where
    /// the noise happened to favour the new code. That substitution would turn
    /// noise into a reported win, which is the worst available outcome.
    #[test]
    fn the_paired_median_is_the_middle_round_not_the_luckiest() {
        let odd = paired_with(vec![1.10, 0.95, 3.00]);
        assert!((odd.median_speedup() - 1.10).abs() < 1e-12);
        assert!(
            odd.median_speedup() < 3.00,
            "the median must not be the best round, which was 3.00x"
        );
        // Even round counts average the two middle values.
        let even = paired_with(vec![1.0, 2.0, 3.0, 4.0]);
        assert!((even.median_speedup() - 2.5).abs() < 1e-12);
        let (lo, hi) = even.speedup_range();
        assert!((lo - 1.0).abs() < 1e-12);
        assert!((hi - 4.0).abs() < 1e-12);
        // An empty comparison claims nothing rather than dividing by zero.
        assert!((paired_with(Vec::new()).median_speedup() - 0.0).abs() < f64::EPSILON);
        assert_eq!(paired_with(Vec::new()).speedup_range(), (0.0, 0.0));
    }

    /// Locks out publishing a wide paired delta as a small effect.
    ///
    /// A wide spread across rounds is not a small win, it is an uncontrolled
    /// measurement, and on a card shared with six agents plus an external
    /// server it is the expected failure. Both halves of the gate matter: too
    /// few rounds cannot establish a spread at all, and a wide spread must fail
    /// even when the round count is satisfied.
    #[test]
    fn the_paired_spread_gates_publication_like_an_absolute_cell() {
        // Eight identical rounds: zero spread, publishable.
        let tight = paired_with(vec![1.20; 8]);
        assert!((tight.speedup_rel_stddev() - 0.0).abs() < 1e-12);
        assert!(tight.is_publishable());
        // One round short, however tight.
        let short = paired_with(vec![1.20; 7]);
        assert_eq!(short.speedups.len(), MIN_PAIRED_ROUNDS as usize - 1);
        assert!(!short.is_publishable(), "seven rounds cannot establish a spread");
        // Enough rounds, but one round is wildly out: mean 1.25, rel stddev
        // 0.5657, which is over the 0.20 interlock.
        let mut wide = vec![1.0; 7];
        wide.push(3.0);
        let wide = paired_with(wide);
        assert!((wide.speedup_rel_stddev() - 0.565_685_424_949_238).abs() < 1e-12);
        assert!(wide.speedup_rel_stddev() > MAX_PUBLISHABLE_REL_STDDEV);
        assert!(!wide.is_publishable(), "a 0.57 delta spread is uncontrolled, not a small win");
        // A single round has no spread to speak of and must not read as tight.
        assert!((paired_with(vec![1.2]).speedup_rel_stddev() - 0.0).abs() < f64::EPSILON);
        assert!(!paired_with(vec![1.2]).is_publishable());
    }

    /// Locks out a comparison that quotes a ratio with no absolute figures.
    ///
    /// The whole objection to the published GPU BPE baselines is a ratio whose
    /// inputs are not printed. The render must carry both arms' absolute
    /// per-unit seconds, the spread, and the foreign device load present.
    #[test]
    fn the_paired_render_carries_absolutes_and_the_contaminant() {
        let text = paired_with(vec![1.20; 8]).render();
        assert!(text.contains("best per unit"), "no absolute figures in: {text}");
        assert!(text.contains("rel stddev"), "no spread in: {text}");
        assert!(text.contains("24204 MiB"), "no foreign residency in: {text}");
        assert!(text.contains("41% SM"), "no foreign SM evidence in: {text}");
        assert!(text.contains("evidence, not gated"), "sm% must be labelled ungated: {text}");
        assert!(text.contains("publishable"));
        let bad = paired_with(vec![1.0, 3.0]).render();
        assert!(bad.contains("NOT publishable"), "a two-round comparison must refuse: {bad}");
    }

    /// Locks out the inverted speedup direction that shipped in the paired report.
    ///
    /// `render` printed only a bare ratio, and the device bench captioned it
    /// "above 1.0 means the HOST is faster". That is backwards: speedups are
    /// `a_unit/b_unit`, so above 1.0 arm A spends MORE time and arm B is the
    /// quicker one. The first real capture read 2.2260x on prose with the host
    /// at 0.014983 s and the device at 0.006621 s per unit, a device win, and
    /// the caption called it a host win. A reader acting on that would have
    /// concluded the device path was not worth taking when it was 2.23x ahead.
    /// If this regresses, every paired cell in the report reverses meaning while
    /// its numbers stay correct, which is the hardest kind of wrong to notice.
    #[test]
    fn the_paired_render_names_the_faster_arm_and_never_inverts_it() {
        // Arm B is twice as quick, so the ratio is 2.0 and B must be named.
        let quick_b = Paired::from_unit_secs("host", "device", &[1.0; 8], &[0.5; 8], 0, 0)
            .expect("eight clean rounds");
        assert!((quick_b.median_speedup() - 2.0).abs() < 1e-12);
        let text = quick_b.render();
        assert!(
            text.contains("faster arm        : device by 2.0000x"),
            "arm B is quicker at 0.5 s against 1.0 s, so it must be named: {text}"
        );
        assert!(
            text.contains("(ratio is host_secs/device_secs)"),
            "the ratio's orientation must be stated so it cannot be read backwards: {text}"
        );
        assert!(!text.contains("faster arm        : host"), "naming the slow arm is the bug: {text}");

        // Mirror it: arm A quicker must name A and report the reciprocal, not 0.5x.
        let quick_a = Paired::from_unit_secs("host", "device", &[0.25; 8], &[1.0; 8], 0, 0)
            .expect("eight clean rounds");
        assert!((quick_a.median_speedup() - 0.25).abs() < 1e-12);
        let mirrored = quick_a.render();
        assert!(
            mirrored.contains("faster arm        : host by 4.0000x"),
            "0.25x means the HOST is 4x quicker, stated as 4x not 0.25x: {mirrored}"
        );
        assert!(!mirrored.contains("faster arm        : device"), "inverted: {mirrored}");

        // The real short_pretokens cell: device slower, so the host is named.
        let short = Paired::from_unit_secs(
            "host",
            "device",
            &[0.003_239_845; 8],
            &[0.008_483_396; 8],
            24_204,
            0,
        )
        .expect("eight clean rounds");
        assert!(
            short.render().contains("faster arm        : host by 2.6185x"),
            "the observed short_pretokens cell is a host win: {}",
            short.render()
        );

        // Exact parity is not a win for either arm, and must not read as inverted.
        let tie = Paired::from_unit_secs("host", "device", &[1.0; 8], &[1.0; 8], 0, 0)
            .expect("eight clean rounds");
        assert!(
            tie.render().contains("faster arm        : device by 1.0000x"),
            "a 1.0000x tie must report unit factor, never a reciprocal blowup: {}",
            tie.render()
        );
    }

    /// Locks out a device lock that does not actually exclude.
    ///
    /// Six agents sharing one card cannot be relied on to observe a booking
    /// order, so exclusion has to be structural. If a second acquire succeeded
    /// while the first was held, two agents would time overlapping regions and
    /// both would silently measure the other.
    #[test]
    fn the_device_lock_excludes_a_second_holder_and_releases_on_drop() {
        let path = std::env::temp_dir().join(format!("exatok-lock-{}.lock", std::process::id()));
        let _ = fs::remove_file(&path);
        let held = DeviceLock::acquire_at(path.clone(), std::time::Duration::from_secs(5))
            .expect("an uncontended lock");
        assert!(path.is_file(), "the lock file must exist while held");
        let refused = DeviceLock::acquire_at(path.clone(), std::time::Duration::from_millis(0))
            .expect_err("a second holder must be refused");
        let text = refused.to_string();
        assert!(
            text.contains(&std::process::id().to_string()),
            "the refusal must name the holding pid, but said: {text}"
        );
        drop(held);
        assert!(!path.exists(), "the lock must be released on drop, not leaked");
        // Reacquirable immediately afterwards.
        let again = DeviceLock::acquire_at(path.clone(), std::time::Duration::from_secs(5))
            .expect("the lock is free again");
        drop(again);
        assert!(!path.exists());
    }

    /// Locks out a crashed holder wedging the card permanently.
    ///
    /// The lock is a file rather than an flock, because this crate carries no
    /// libc. That buys one hazard: a process killed before its `Drop` runs
    /// leaves the file behind. Without staleness detection the next agent waits
    /// the full timeout and then refuses, and every later one does too, so one
    /// SIGKILL would take device measurement down until a human noticed.
    #[test]
    fn a_dead_holders_lock_is_reclaimed_rather_than_wedging_the_card() {
        let path = std::env::temp_dir().join(format!("exatok-stale-{}.lock", std::process::id()));
        // A pid that cannot exist: the kernel's maximum is well under this.
        fs::write(&path, "4294967000").expect("write a stale lock");
        let taken = DeviceLock::acquire_at(path.clone(), std::time::Duration::from_millis(0))
            .expect("a stale lock must be reclaimed immediately, not waited out");
        assert_eq!(
            fs::read_to_string(&path).expect("the reclaimed lock").trim(),
            std::process::id().to_string(),
            "the reclaiming process must record itself as the new holder"
        );
        drop(taken);
        // A LIVE holder's lock is never stolen, even though we cannot open it.
        fs::write(&path, std::process::id().to_string()).expect("write a live lock");
        assert!(
            DeviceLock::acquire_at(path.clone(), std::time::Duration::from_millis(0)).is_err(),
            "a live holder's lock must not be reclaimed"
        );
        // An unparseable holder is left alone rather than stolen on a guess.
        fs::write(&path, "not-a-pid").expect("write a corrupt lock");
        assert!(
            DeviceLock::acquire_at(path.clone(), std::time::Duration::from_millis(0)).is_err(),
            "an unreadable holder must not be assumed dead"
        );
        let _ = fs::remove_file(&path);
    }

    /// Locks out `/proc` parsing that silently reports nothing.
    ///
    /// Every gate downstream divides by these numbers. A parse that returned
    /// zero CPU-seconds would make foreign load read as zero and quietly
    /// certify a contended cell, which is precisely the failure the foreign-load
    /// gate exists to prevent.
    #[test]
    fn the_proc_probes_report_this_machine_not_zero() {
        let machine = Machine::probe().expect("a Linux machine");
        // Burn a little CPU so our own process time is unambiguously nonzero.
        let mut acc = 0u64;
        for i in 0..2_000_000u64 {
            acc = acc.wrapping_add(i).wrapping_mul(31);
        }
        assert_ne!(acc, 0);
        let own = process_cpu_secs().expect("/proc/self/stat is readable");
        assert!(own > 0.0, "this process has burned CPU, but the probe read {own}");
        let busy = machine_busy_secs().expect("/proc/stat is readable");
        assert!(
            busy >= own,
            "machine-wide busy {busy} cannot be below this process's own {own}"
        );
        let per_cpu = per_cpu_busy_secs();
        assert_eq!(
            per_cpu.len(),
            machine.logical_cores,
            "one /proc/stat row per logical CPU is required for the weighted clock"
        );
        let mhz = per_cpu_mhz();
        assert_eq!(mhz.len(), machine.logical_cores, "one MHz reading per logical CPU");
        assert!(mhz.iter().all(|m| *m > 0.0), "a zero clock reading is a parse failure");
        // The aggregate row must not be counted as a CPU.
        assert!(per_cpu.iter().sum::<f64>() > 0.0);
    }

    /// Locks out a weighted clock that silently averages idle cores back in.
    ///
    /// Weighting by occupancy is the entire difference between this probe and
    /// the whole-machine mean it replaces. If the weights were ignored the
    /// result would collapse back to the unweighted mean, reintroducing the
    /// occupancy confound that produced a published +45.53% "drift".
    #[test]
    fn the_weighted_clock_ignores_cores_that_did_no_work() {
        // One busy core at 5000 MHz, three idle at 1000 MHz.
        let mhz = [5000.0, 1000.0, 1000.0, 1000.0];
        let weights = [1.0, 0.0, 0.0, 0.0];
        assert!((busy_weighted_mhz(&mhz, &weights) - 5000.0).abs() < 1e-12);
        // The unweighted mean of the same instant is 2000 MHz, which is the
        // number this probe exists to avoid reporting.
        assert!((mhz.iter().sum::<f64>() / 4.0 - 2000.0).abs() < 1e-12);
        // Proportional weighting: two cores, one busy twice as long.
        let two = busy_weighted_mhz(&[3000.0, 6000.0], &[2.0, 1.0]);
        assert!((two - 4000.0).abs() < 1e-12, "expected 4000 MHz, got {two}");
        // No claim when nothing was busy, or when the probes disagree entirely.
        assert!((busy_weighted_mhz(&mhz, &[0.0; 4]) - 0.0).abs() < f64::EPSILON);
        assert!((busy_weighted_mhz(&[], &[]) - 0.0).abs() < f64::EPSILON);
        // Mismatched lengths use the overlap rather than reading out of bounds.
        assert!((busy_weighted_mhz(&[5000.0, 1000.0], &[1.0]) - 5000.0).abs() < 1e-12);
    }

    /// Locks out a paired comparison that accepts too few rounds to mean
    /// anything.
    ///
    /// Three rounds against a bursty contaminant is how a sibling's GPU burst
    /// becomes a reported speedup, so the refusal has to be in the entry point
    /// rather than in a caller's discipline.
    #[test]
    fn compare_cells_refuses_fewer_rounds_than_the_spread_needs() {
        let mut a = || Ok(WorkUnit { bytes: 1, tokens: 1 });
        let mut b = || Ok(WorkUnit { bytes: 1, tokens: 1 });
        let err = compare_cells(
            Arm { label: "a", work: &mut a },
            Arm { label: "b", work: &mut b },
            MIN_PAIRED_ROUNDS - 1,
        )
        .expect_err("seven rounds must be refused before any work runs");
        let text = err.to_string();
        assert!(text.contains(&(MIN_PAIRED_ROUNDS - 1).to_string()), "{text}");
        assert!(text.contains(&MIN_PAIRED_ROUNDS.to_string()), "{text}");
    }

    /// Locks out a paired cell that times an arm consuming no input.
    ///
    /// A duration alone cannot tell a real speedup from an arm that quietly
    /// stopped doing the work: both read as fast, and the faster arm would be the
    /// broken one. This burns real time while reporting zero bytes, so a pass
    /// would mean the refusal came from the clock rather than from the count.
    /// Not ignored: it refuses at round 0, so it holds the device lock about a
    /// second rather than the tens of seconds its siblings need.
    #[test]
    fn compare_cells_refuses_an_arm_that_consumed_no_input() {
        fn burn(rounds: u64) -> u64 {
            let mut acc = 1u64;
            for i in 0..rounds {
                acc = acc.wrapping_mul(31).wrapping_add(i);
            }
            acc
        }
        let mut real = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let mut vacuous = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 0, tokens: v % 7 + 1 })
        };
        let err = compare_cells_at(
            Arm { label: "real", work: &mut real },
            Arm { label: "vacuous", work: &mut vacuous },
            MIN_PAIRED_ROUNDS,
            TEST_REGION_SECS,
        )
        .expect_err("an arm that consumed no input must be refused, not timed");
        let text = err.to_string();
        assert!(text.contains("consumed no input"), "{text}");
        assert!(text.contains("200000 B against 0 B"), "{text}");
    }

    /// Locks out a ratio whose arms did different work from round to round.
    ///
    /// The pin is taken at round 0 and every later round must match it. Without
    /// that check a cell whose work drifts mid-run still prints one ratio, and
    /// that ratio divides one quantity by a different one while looking ordinary.
    /// Token count rises on every call here, so the mismatch is guaranteed at
    /// round 1 whatever the calibrated repetition count turns out to be.
    #[test]
    fn compare_cells_refuses_work_that_changes_between_rounds() {
        fn burn(rounds: u64) -> u64 {
            let mut acc = 1u64;
            for i in 0..rounds {
                acc = acc.wrapping_mul(31).wrapping_add(i);
            }
            acc
        }
        let mut calls = 0u64;
        let mut drifting = move || {
            calls += 1;
            std::hint::black_box(burn(200_000));
            Ok(WorkUnit { bytes: 200_000, tokens: calls })
        };
        let mut steady = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let err = compare_cells_at(
            Arm { label: "drifting", work: &mut drifting },
            Arm { label: "steady", work: &mut steady },
            MIN_PAIRED_ROUNDS,
            TEST_REGION_SECS,
        )
        .expect_err("work that changes between rounds must be refused");
        let text = err.to_string();
        assert!(text.contains("the work changed between rounds"), "{text}");
        assert!(text.contains("pinned at"), "{text}");
    }

    /// End-to-end: comparing an implementation against ITSELF must read as no
    /// change, and against a half-cost variant as roughly twice as fast.
    ///
    /// This is the property that catches a harness bug no synthetic test can: if
    /// calibration, per-unit normalization or the interleaving were wrong, a
    /// self-comparison would drift away from 1.0. It ran ignored for a long
    /// stretch because the full [`CALIBRATION_TARGET_SECS`] region floor cost
    /// tens of seconds and held the device measurement lock across it; the
    /// estimator's algebra does not depend on region length, so it now runs the
    /// identical protocol calibrated to a short test region and stays in the
    /// suite.
    #[test]
    fn compare_cells_reads_identical_work_as_no_change() {
        fn burn(rounds: u64) -> u64 {
            let mut acc = 1u64;
            for i in 0..rounds {
                acc = acc.wrapping_mul(31).wrapping_add(i);
            }
            acc
        }
        let mut a = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let mut b = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let paired = compare_cells_at(
            Arm { label: "self-a", work: &mut a },
            Arm { label: "self-b", work: &mut b },
            MIN_PAIRED_ROUNDS,
            TEST_REGION_SECS,
        )
        .expect("a paired comparison of identical work");
        assert_eq!(paired.speedups.len(), MIN_PAIRED_ROUNDS as usize);
        assert_eq!(paired.a_unit_secs.len(), MIN_PAIRED_ROUNDS as usize);
        assert_eq!(paired.b_unit_secs.len(), MIN_PAIRED_ROUNDS as usize);
        assert!(paired.a_unit_secs.iter().all(|s| *s > 0.0 && s.is_finite()));
        let median = paired.median_speedup();
        assert!(
            (median - 1.0).abs() < 0.25,
            "identical work must read near 1.0x, got {median}x; calibration or per-unit \
             normalization is wrong"
        );
    }

    /// The negative control for the test above: a real difference must be
    /// DETECTED, at roughly its true size.
    ///
    /// Without this, a harness that ignored its arms entirely and returned 1.0
    /// would pass the self-comparison test and look correct. Arm B does half the
    /// work of arm A, so the paired ratio must land near 2.0x, and the spread
    /// must stay tight enough to publish. Runs the same short-region protocol as
    /// the self-comparison above; the ratio it must detect is a property of the
    /// work, not of the region length.
    #[test]
    fn compare_cells_detects_a_real_two_fold_difference() {
        fn burn(rounds: u64) -> u64 {
            let mut acc = 1u64;
            for i in 0..rounds {
                acc = acc.wrapping_mul(31).wrapping_add(i);
            }
            acc
        }
        let mut slow = || {
            let v = burn(400_000);
            Ok(WorkUnit { bytes: 400_000, tokens: v % 7 + 1 })
        };
        let mut fast = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let paired = compare_cells_at(
            Arm { label: "slow", work: &mut slow },
            Arm { label: "fast", work: &mut fast },
            MIN_PAIRED_ROUNDS,
            TEST_REGION_SECS,
        )
        .expect("a paired comparison of unequal work");
        let median = paired.median_speedup();
        assert!(
            (median - 2.0).abs() < 0.4,
            "half the work must read near 2.0x, got {median}x; the harness is not \
             distinguishing its arms"
        );
        // Arm A really is the slower one per unit of work.
        let a_best = paired.a_unit_secs.iter().copied().fold(f64::INFINITY, f64::min);
        let b_best = paired.b_unit_secs.iter().copied().fold(f64::INFINITY, f64::min);
        assert!(a_best > b_best, "arm A does twice the work, so {a_best} must exceed {b_best}");
        println!("{}", paired.render());
    }

    /// Locks the per-arm host-load series to the gated max it was reduced from.
    ///
    /// The paired loop computes each arm's foreign CPU load and used to keep only
    /// the max. With both readings discarded, a drift computed over that max could
    /// not be told apart from an estimator artifact: a max of two draws is upward
    /// biased in proportion to their variance, so a refusal could belong to the
    /// statistic rather than to the machine. Three of four host-versus-device cells
    /// in a real capture refused, and the output carries only the median and the
    /// drift, so if this regresses that question is unanswerable after the run.
    /// The gated reading is the exact max of the two per-arm readings, which is
    /// arithmetic on recorded values and holds at any region length, so this
    /// runs the same short-region protocol as the other estimator tests.
    #[test]
    fn the_paired_loop_keeps_both_arms_behind_the_gated_max() {
        fn burn(rounds: u64) -> u64 {
            let mut acc = 1u64;
            for i in 0..rounds {
                acc = acc.wrapping_mul(31).wrapping_add(i);
            }
            acc
        }
        let mut a = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let mut b = || {
            let v = burn(200_000);
            Ok(WorkUnit { bytes: 200_000, tokens: v % 7 + 1 })
        };
        let paired = compare_cells_at(
            Arm { label: "arm-a", work: &mut a },
            Arm { label: "arm-b", work: &mut b },
            MIN_PAIRED_ROUNDS,
            TEST_REGION_SECS,
        )
        .expect("a paired comparison of equal work");
        assert_eq!(
            paired.host_foreign_load.len(),
            MIN_PAIRED_ROUNDS as usize,
            "one gated reading per round"
        );
        assert_eq!(
            paired.host_foreign_load_arms.len(),
            paired.host_foreign_load.len(),
            "the per-arm series must not fall behind the series it explains"
        );
        for (round, ((load_a, load_b), gated)) in
            paired.host_foreign_load_arms.iter().zip(&paired.host_foreign_load).enumerate()
        {
            assert!(
                (load_a.max(*load_b) - gated).abs() < 1e-12,
                "round {round}: gated {gated} must be the max of {load_a} and {load_b}"
            );
            assert!(
                *load_a >= 0.0 && *load_b >= 0.0,
                "round {round}: a foreign load is never negative, got {load_a} and {load_b}"
            );
        }
    }
}

#[cfg(test)]
mod provenance_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::{
        MIN_PAIRED_ROUNDS, Paired, Provenance, TestCount, compiled_features,
    };

    /// Locks out comparing two test counts taken under different feature sets.
    ///
    /// This is the defect that cost an agent real time tonight: 255 (default),
    /// 272 (an unrecorded set) and 286 (`confluence`) were all true of this crate
    /// within one hour. Comparing 255 against 272 read a benign packaging change,
    /// 31 unit tests moving behind a default-off feature, as a 17-test
    /// regression. The count was never wrong; its qualifier was missing.
    #[test]
    fn a_test_count_is_not_comparable_across_feature_sets() {
        let default = TestCount { passed: 255, ignored: 2, features: Vec::new() };
        let confluence =
            TestCount { passed: 286, ignored: 2, features: vec!["confluence".to_owned()] };
        assert!(
            !default.comparable_to(&confluence),
            "255 default and 286 confluence describe different builds and must never compare"
        );
        assert!(default.comparable_to(&TestCount {
            passed: 261,
            ignored: 2,
            features: Vec::new()
        }));
        // The rendered form can never be the bare number.
        assert_eq!(default.render(), "255 passed / 2 ignored (features: default)");
        assert_eq!(confluence.render(), "286 passed / 2 ignored (features: confluence)");
        let both = TestCount {
            passed: 1,
            ignored: 0,
            features: vec!["confluence".to_owned(), "cuda".to_owned()],
        };
        assert_eq!(both.render(), "1 passed / 0 ignored (features: confluence,cuda)");
        assert!(
            !both.comparable_to(&confluence),
            "a superset of features is still a different build"
        );
    }

    /// Locks out a fixture or a derived value being quoted as measured.
    ///
    /// Only `Probed` may be quoted. Tonight a synthetic device profile named
    /// after this GPU overstated its threads per SM by a third (2048 against a
    /// measured 1536) and was read as hardware fact; a `Fixture` tag is what
    /// makes that impossible to mistake.
    #[test]
    fn only_a_probed_figure_may_be_quoted_as_measured() {
        assert!(Provenance::Probed.is_quotable_as_measured());
        assert!(!Provenance::Derived.is_quotable_as_measured());
        assert!(!Provenance::Fixture.is_quotable_as_measured());
        assert_eq!(Provenance::Probed.as_str(), "probed");
        assert_eq!(Provenance::Derived.as_str(), "derived");
        assert_eq!(Provenance::Fixture.as_str(), "fixture");
    }

    /// Locks out a feature set that disagrees with the binary reporting it.
    ///
    /// Probed from `cfg!`, so a default build must claim nothing and a
    /// feature-enabled build must claim exactly that feature. If this ever read
    /// a stored field instead, a report could carry a feature set from a
    /// different build, which is the whole failure being prevented.
    #[test]
    fn the_feature_set_is_probed_from_this_binary() {
        let features = compiled_features();
        assert_eq!(features.contains(&"confluence"), cfg!(feature = "confluence"));
        assert_eq!(features.contains(&"cuda"), cfg!(feature = "cuda"));
        assert_eq!(features.contains(&"gpu-pretokenize"), cfg!(feature = "gpu-pretokenize"));
        assert_eq!(features.contains(&"multi-merge"), cfg!(feature = "multi-merge"));
        // Sorted and duplicate-free, so two runs of the same build render identically.
        let mut sorted = features.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted, features, "the feature list must be stable and duplicate-free");
        assert_eq!(TestCount::here(1, 0).features.len(), features.len());
    }

    /// Locks out cross-process pairing that silently accepts junk.
    ///
    /// Some arms only exist in separate builds, so their timings arrive as two
    /// vectors rather than two closures. That path must refuse exactly what the
    /// in-process path refuses, or "measured in two builds" becomes a way to
    /// bypass the round count and the spread gate.
    #[test]
    fn cross_process_pairing_enforces_the_same_gates_as_the_in_process_path() {
        let eight = vec![1.0; MIN_PAIRED_ROUNDS as usize];
        let half = vec![0.5; MIN_PAIRED_ROUNDS as usize];
        let ok = Paired::from_unit_secs("old", "new", &eight, &half, 24_204, 41)
            .expect("eight clean rounds per arm");
        // Arm B takes half the time, so exactly 2.0x, and it is publishable.
        assert!((ok.median_speedup() - 2.0).abs() < 1e-12);
        assert!(ok.is_publishable());
        assert_eq!(ok.foreign_resident_baseline_mib, 24_204);
        assert_eq!(ok.foreign_sm_percent_max, 41);
        assert!(ok.render().contains("24204 MiB"));
        // Too few rounds, the same refusal as `compare_cells`.
        let short = vec![1.0; MIN_PAIRED_ROUNDS as usize - 1];
        let err = Paired::from_unit_secs("old", "new", &short, &short, 0, 0)
            .expect_err("seven rounds must be refused");
        assert!(err.to_string().contains(&MIN_PAIRED_ROUNDS.to_string()));
        // Ragged arms cannot be paired at all: index i would not be round i.
        assert!(
            Paired::from_unit_secs("old", "new", &eight, &short, 0, 0).is_err(),
            "8 A rounds against 7 B rounds is not a pairing"
        );
        // A zero or non-finite timing would divide, so it is refused up front.
        let mut zeroed = eight.clone();
        zeroed[3] = 0.0;
        assert!(Paired::from_unit_secs("old", "new", &eight, &zeroed, 0, 0).is_err());
        let mut nan = eight.clone();
        nan[0] = f64::NAN;
        assert!(Paired::from_unit_secs("old", "new", &nan, &eight, 0, 0).is_err());
        let mut negative = eight.clone();
        negative[7] = -1.0;
        assert!(Paired::from_unit_secs("old", "new", &negative, &eight, 0, 0).is_err());
        let mut inf = eight.clone();
        inf[2] = f64::INFINITY;
        assert!(Paired::from_unit_secs("old", "new", &inf, &eight, 0, 0).is_err());
        // A wide spread across builds is refused exactly as in-process.
        let mut wide = vec![1.0; MIN_PAIRED_ROUNDS as usize];
        wide[0] = 3.0;
        let loose = Paired::from_unit_secs("old", "new", &wide, &eight, 0, 0)
            .expect("valid timings, wide spread");
        assert!(!loose.is_publishable(), "a wide cross-build spread is uncontrolled too");
    }
}

#[cfg(test)]
mod device_scope_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::{parse_pmon, sample_device_load};

    /// A `pmon -s um` capture: this process at 12 MiB, an inference server at
    /// 24204 MiB, one desktop graphics context, and one more compute process.
    const CAPTURE: &str = "\
# gpu        pid  type    sm   mem   enc   dec   jpg   ofa    fb  ccpm  command
# Idx          #   C/G     %     %     %     %     %     %    MB    MB  name
    0     999001     C     0     0     -     -     -     -    12     0  exatok-test
    0     123456     C    41    12     -     -     -     -  24204     0  llama-server
    0     555000     G     3     1     -     -     -     -   512     0  Xorg
    0     777000     C     7     2     -     -     -     -   670     0  device_determ
";

    /// Locks out inverting own and foreign device residency.
    ///
    /// This is the guard on the mechanism that decides which cells are valid, so
    /// a fault here does not produce a wrong number, it produces a number nobody
    /// can audit. Inversion would move an external inference server's 24 GB into
    /// `own_resident_mib`, which makes every host-only cell look like a device
    /// cell and voids measurements nothing contaminated; the mirror fault would
    /// hide our own allocation in `foreign_resident_mib` and void every device
    /// cell against itself.
    ///
    /// Tested against a fixture rather than live, because the live premise is
    /// false: a `--features cuda` test binary creates a CUDA context on a sibling
    /// thread, so this process legitimately holds about 12 MiB and an assertion
    /// of zero fails for a correct parse. That is precisely the bug this test
    /// replaces.
    #[test]
    fn own_and_foreign_device_residency_are_never_swapped() {
        let load = parse_pmon(CAPTURE, 999_001).expect("four parseable rows");
        assert_eq!(load.own_resident_mib, 12, "our own row is 12 MiB, not the server's 24204");
        assert_eq!(
            load.foreign_resident_mib,
            24_204 + 670,
            "foreign residency is the sum of the OTHER compute rows"
        );
        assert_eq!(load.foreign_processes, 2, "two foreign compute processes, excluding ourselves");
        assert_eq!(load.foreign_sm_percent, 41 + 7, "foreign SM percent excludes our own row");
        // Seen from another process's perspective the same capture attributes our
        // 12 MiB as foreign, which is the inversion this test would catch.
        let other = parse_pmon(CAPTURE, 123_456).expect("same capture, different self");
        assert_eq!(other.own_resident_mib, 24_204);
        assert_eq!(other.foreign_resident_mib, 12 + 670);
        assert_eq!(other.foreign_processes, 2);
        // A process on none of the rows owns nothing and sees everything.
        let stranger = parse_pmon(CAPTURE, 1).expect("same capture, uninvolved self");
        assert_eq!(stranger.own_resident_mib, 0);
        assert_eq!(stranger.foreign_resident_mib, 12 + 24_204 + 670);
        assert_eq!(stranger.foreign_processes, 3);
    }

    /// Locks out counting the desktop as a benchmark competitor, and out
    /// treating an unreadable capture as an idle card.
    ///
    /// A graphics context is the display server, which does not contend for SM
    /// time with a compute kernel, so folding it in would void cells over a
    /// moving mouse cursor. And an absent or unparseable `nvidia-smi` must read
    /// as "not observed" rather than as a clean device, since a false all-clear
    /// is how the retired `--query-compute-apps` probe certified contended runs.
    #[test]
    fn graphics_contexts_are_excluded_and_an_unreadable_capture_is_not_an_idle_card() {
        // The `G` row at 512 MiB appears in neither total above.
        let load = parse_pmon(CAPTURE, 999_001).expect("parseable");
        assert_eq!(load.own_resident_mib + load.foreign_resident_mib, 12 + 24_204 + 670);
        assert!(
            !format!("{load:?}").contains("512"),
            "the desktop's 512 MiB must not appear in any total"
        );
        // Headers only: nothing observed, so None rather than a zeroed load.
        let headers = CAPTURE.lines().take(2).collect::<Vec<_>>().join("\n");
        assert!(parse_pmon(&headers, 1).is_none(), "headers alone are not an observation");
        assert!(parse_pmon("", 1).is_none(), "empty output is not an idle card");
        assert!(parse_pmon("garbage\nmore garbage\n", 1).is_none());
        // A card with no compute work at all IS an observation: rows parsed, all
        // graphics, so zero foreign compute load is a real measurement.
        let idle = "    0     555000     G     3     1     -     -     -     -   512     0  Xorg\n";
        let idle = parse_pmon(idle, 1).expect("a parsed graphics row is an observation");
        assert_eq!(idle.foreign_processes, 0);
        assert_eq!(idle.foreign_resident_mib, 0);
        assert_eq!(idle.own_resident_mib, 0);
    }

    /// Locks out a truncated or dash-filled row corrupting a total.
    ///
    /// `pmon` prints `-` for a column it did not sample, and truncates rows on
    /// some driver versions. A `-` parsed as anything but "no data" would either
    /// panic or, worse, land as a plausible small number in a residency total
    /// that gates publication.
    #[test]
    fn unsampled_and_short_rows_do_not_corrupt_a_residency_total() {
        let ragged = "\
    0     123456     C     -     -     -     -     -     -     -     0  llama-server
    0     123457     C
    0     notapid    C    10     5     -     -     -     -   100     0  weird
    0     123458     C    10     5     -     -     -     -   256     0  real
";
        let load = parse_pmon(ragged, 999_001).expect("at least one parseable row");
        // The dash row counts as a process at zero bytes and zero sampled SM,
        // the short row and the non-numeric pid are skipped, and only the real
        // row contributes bytes.
        assert_eq!(load.foreign_resident_mib, 256, "only the one sampled row has bytes");
        assert_eq!(load.foreign_sm_percent, 10, "the unsampled `-` contributes no SM percent");
        assert_eq!(load.foreign_processes, 2, "the dash row and the real row, not the malformed");
        assert_eq!(load.own_resident_mib, 0);
    }

    /// Locks out a live capture that attributes a foreign multi-gigabyte process
    /// to this process.
    ///
    /// The fixture tests above pin attribution exactly; this one checks the live
    /// probe on this machine without assuming whether we hold a context, since
    /// that varies by feature set. A test binary holding gigabytes would itself
    /// be a defect, so the bound catches an inversion (which would land the
    /// external server's ~24 GB in `own_resident_mib`) while staying true under
    /// both a host-only and a `cuda` build.
    #[test]
    fn a_live_capture_never_attributes_gigabytes_to_this_test_process() {
        let Some(load) = sample_device_load() else {
            // No NVIDIA device or no pmon here: every sample is None, the
            // baseline stays 0, and the gate cannot fire at all.
            return;
        };
        assert!(
            load.own_resident_mib < 4096,
            "this test process holds {} MiB of device memory; a test binary holding gigabytes \
             means a foreign process was attributed to self, which voids host-only cells",
            load.own_resident_mib
        );
        if load.foreign_processes > 0 {
            assert!(
                load.foreign_resident_mib > 0,
                "{} foreign compute processes were counted, so their residency cannot be 0",
                load.foreign_processes
            );
        }
    }
}