tak-cli 0.0.17

Pre-v1 command-line benchmarking and performance tracking
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
//! Measurement backends.
//!
//! Two tiers, deliberately separated:
//!
//! - **Deterministic** (`instructions`) — reproducible to ~0.02% run-to-run and
//!   ~0.035% across wildly different machine load. This is the only tier that may
//!   gate CI.
//! - **Timing** (`wall_*`) — recorded and charted, never gated. On a quiet 32-core
//!   host wall clock still shows 4–20% coefficient of variation; under contention
//!   the median moves ~150%.
//!
//! Syscall counts and peak RSS sit awkwardly between the two: better than wall
//! clock (~1%) but not deterministic, because they move with thread scheduling.
//! They are recorded, and may be flagged, but must not gate at a tight threshold.
//!
//! Heap allocations (`alloc_*`, from DHAT) are counted rather than timed. Their
//! totals have repeated exactly for every hermetic subject measured so far, but
//! that is five programs, not a demonstrated property, so they are recorded
//! and reported and do not gate. Their peak moves with thread scheduling.

use crate::config::{AutoRuns, DEFAULT_OK_EXIT_CODES, MetricSource, Runs, SELF_TOOL, Subject};
use crate::settings::Settings;
use anyhow::{Context, Result, bail};
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::time::Instant;

#[derive(Debug, Clone)]
pub struct Plan {
    pub cmd: Vec<String>,
    pub warmup: u32,
    pub runs: u32,
    /// Directory to run in. Declared benchmarks resolve relative commands
    /// against `tak.toml`'s directory, not the caller's — otherwise the same
    /// benchmark measures different things depending on where you stood.
    pub dir: Option<std::path::PathBuf>,
    /// Resolved settings. Carried on the plan rather than read from a global so
    /// a test can measure under a different configuration without touching the
    /// environment of the whole test binary.
    pub settings: Settings,
}

/// A command for running a benchmark subject, with the scrubbed variables
/// removed.
///
/// Every subject spawn goes through here. Under cachegrind the removal is
/// applied to valgrind itself, which the subject inherits from.
///
/// What gets removed is [`Settings::scrubbed_env`] — `env_deny` less
/// `env_allow`, both declared on the `Settings` registry. The default is the
/// forge tokens because a CLI that finds one often does more with it than
/// without, so a measurement would move depending on whether CI happened to
/// export one.
///
/// This controls direct inheritance, not hostile-code isolation. A subject can
/// still inspect accessible same-user processes and files, so `backfill` must
/// run without credentials when its release binaries are not trusted.
///
/// tak's own network calls are unaffected — `backfill` authenticates with
/// `curl` directly rather than through this path.
fn subject(bin: &str, settings: &Settings) -> Command {
    let mut c = Command::new(bin);
    for key in settings.scrubbed_env() {
        c.env_remove(key);
    }
    c
}

/// Where a command runs and what it sees, beyond its argv.
#[derive(Debug, Clone, Copy)]
struct Site<'a> {
    dir: Option<&'a Path>,
    env: &'a BTreeMap<String, String>,
    settings: &'a Settings,
}

/// Build a spawn of `argv` at `site`.
///
/// Declared variables are applied after the scrub. A variable written into
/// `tak.toml` for a subject is an explicit choice, not something inherited by
/// accident, which is the only thing the scrub exists to stop.
fn command(argv: &[String], site: &Site) -> Result<Command> {
    let (bin, args) = argv.split_first().context("empty command")?;
    let mut c = subject(bin, site.settings);
    c.args(args).envs(site.env);
    if let Some(d) = site.dir {
        c.current_dir(d);
    }
    #[cfg(unix)]
    if tracked::OWN_GROUPS.load(std::sync::atomic::Ordering::SeqCst) {
        std::os::unix::process::CommandExt::process_group(&mut c, 0);
    }
    Ok(c)
}

/// Spawn `c`, wait for it, and keep its process group known to
/// [`stop_running`] meanwhile. `Command::status` split in two: the same
/// stdio defaults, and only an uncontended lock between the spawn and the wait.
fn run_tracked(c: &mut Command) -> std::io::Result<std::process::ExitStatus> {
    let mut child = c.spawn()?;
    tracked::started(child.id());
    let status = child.wait();
    tracked::finished();
    status
}

/// Put every measured command in a process group of its own, so that
/// [`stop_running`] can stop it and whatever it started, and nothing else.
///
/// For `tak backfill --commits`, whose interrupt handler has to stop the
/// command before deleting the checkout it runs in. A SIGTERM sent to tak
/// alone, as when CI cancels a job, never reaches a command in tak's own
/// group, and signalling that group instead would also stop whatever shares
/// it with tak, such as `tee` at the other end of a pipeline. `tak run`
/// leaves commands in its group, where a terminal's Ctrl-C reaches them.
///
/// The group is set in the child before it runs the program, so it is inside
/// the timed window, as one `setpgid` against a fork and exec that already
/// cost hundreds of microseconds; and the program's own instructions, which
/// cachegrind counts from exec, do not include it. Wall time is not gated.
#[cfg(unix)]
pub fn use_own_groups() {
    tracked::OWN_GROUPS.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// Kill the measured command running now, any started after this, and
/// whatever earlier ones left running, each with its whole process group.
/// Only effective after [`use_own_groups`]: a command in tak's own group is
/// left alone.
#[cfg(unix)]
pub fn stop_running() {
    use std::sync::atomic::Ordering::SeqCst;
    tracked::STOPPED.store(true, SeqCst);
    tracked::kill_all();
}

/// The one measured command running at a time — samples, setup, prepare,
/// check and valgrind all run one after another — as its process group.
mod tracked {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};

    pub(super) static OWN_GROUPS: AtomicBool = AtomicBool::new(false);
    pub(super) static STOPPED: AtomicBool = AtomicBool::new(false);

    /// Every group an interrupt must kill, behind one lock.
    ///
    /// One lock for both, so that moving a group from running to left
    /// behind is a single step. With the running group in an atomic and the
    /// others in a list, `finished` cleared the one before adding to the
    /// other, and an interrupt landing between the two found the group in
    /// neither: its leftover process then outlived the checkout it ran in.
    static GROUPS: Mutex<Groups> = Mutex::new(Groups::new());

    /// The state behind [`GROUPS`], with the transitions as plain methods so
    /// they can be tested without real processes.
    #[derive(Debug, Default, PartialEq)]
    pub(super) struct Groups {
        /// The group of the command running now, or 0.
        running: i32,
        /// Groups whose leader has exited but where something it started is
        /// still running: a server a `setup` started on purpose, a daemon a
        /// tool leaves behind. Left alone while the backfill runs, as `tak
        /// run` leaves them, and killed with the running command on
        /// interrupt, since the checkout they run in is about to be deleted.
        left: Vec<i32>,
    }

    impl Groups {
        pub(super) const fn new() -> Groups {
            Groups {
                running: 0,
                left: Vec::new(),
            }
        }

        pub(super) fn start(&mut self, pgid: i32) {
            self.running = pgid;
        }

        /// The running command has been reaped. Its group moves to `left`
        /// while it still has members, and groups that have emptied are
        /// dropped: a group id is only kept while it cannot be reused. A
        /// group that empties between this and an interrupt leaves a window
        /// in which its id could be reused, which would take the kernel
        /// handing out that exact pid again first.
        pub(super) fn finish(&mut self, alive: impl Fn(i32) -> bool) {
            self.left.retain(|g| alive(*g));
            if self.running > 0 && alive(self.running) {
                self.left.push(self.running);
            }
            self.running = 0;
        }

        /// Every group an interrupt kills now.
        pub(super) fn targets(&self) -> Vec<i32> {
            std::iter::once(self.running)
                .filter(|g| *g > 0)
                .chain(self.left.iter().copied())
                .collect()
        }
    }

    fn groups() -> std::sync::MutexGuard<'static, Groups> {
        // A poisoned lock still holds the groups; an interrupt must not
        // skip them.
        GROUPS.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// `pid` leads its own group. If [`super::stop_running`] already ran it
    /// may have looked before this was stored, so the group is killed here:
    /// each side stores before it loads, all `SeqCst`, so one of them acts.
    /// The uncontended lock this takes is inside the timed window, and costs
    /// tens of nanoseconds against a fork and exec.
    pub(super) fn started(pid: u32) {
        if !OWN_GROUPS.load(SeqCst) {
            return;
        }
        groups().start(pid as i32);
        if STOPPED.load(SeqCst) {
            kill(pid as i32);
        }
    }

    /// The running command has been reaped; see [`Groups::finish`]. Called
    /// after the clock stops, since checking the groups costs a syscall each.
    pub(super) fn finished() {
        if OWN_GROUPS.load(SeqCst) {
            groups().finish(alive);
        }
    }

    /// Kill the running command's group and every group left behind, under
    /// the same lock `finished` moves them with.
    pub(super) fn kill_all() {
        for g in groups().targets() {
            kill(g);
        }
    }

    #[cfg(unix)]
    fn alive(pgid: i32) -> bool {
        // SAFETY: signal 0 only checks that the group exists.
        unsafe { libc::killpg(pgid, 0) == 0 }
    }

    #[cfg(not(unix))]
    fn alive(_pgid: i32) -> bool {
        false
    }

    #[cfg(unix)]
    pub(super) fn kill(pgid: i32) {
        if pgid > 0 {
            // SAFETY: killpg has no memory-safety preconditions.
            unsafe {
                libc::killpg(pgid, libc::SIGKILL);
            }
        }
    }

    #[cfg(not(unix))]
    pub(super) fn kill(_pgid: i32) {}

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

        /// A group is always somewhere an interrupt looks: running while its
        /// command runs, left behind once it exits with a member still there,
        /// and forgotten only when it is empty.
        #[test]
        fn a_group_is_never_untracked_while_it_has_members() {
            let mut g = Groups::new();
            assert!(g.targets().is_empty());
            g.start(10);
            assert_eq!(g.targets(), [10]);

            // Exits, with a helper still in its group.
            g.finish(|p| p == 10);
            assert_eq!(g.targets(), [10]);
            g.start(20);
            assert_eq!(g.targets(), [20, 10]);

            // 20 exits empty; 10's helper is still there.
            g.finish(|p| p == 10);
            assert_eq!(g.targets(), [10]);

            // 10's helper exits too, and is forgotten at the next finish.
            g.start(30);
            g.finish(|_| false);
            assert!(g.targets().is_empty());
            assert_eq!(g, Groups::new());
        }
    }
}

/// One successful run of a subject's timed command.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sample {
    /// Elapsed wall time in milliseconds.
    pub ms: f64,
    /// What the command exited with: one of its `ok_exit_codes`, kept so the
    /// export shows what actually happened rather than assuming 0.
    pub exit_code: i32,
}

/// The exit code of a sample that counts, or the error that drops its
/// subject.
///
/// A death by signal has no exit code and always fails: a subject that
/// crashed or was killed did not do the work being measured, whatever its
/// `ok_exit_codes` allow.
fn accepted(bin: &str, status: std::process::ExitStatus, ok: &[i32], via: &str) -> Result<i32> {
    match status.code() {
        Some(code) if ok.contains(&code) => Ok(code),
        // Name the accepted codes only when they are not the default, where
        // "exited with 1" alone would leave the reader wondering why that
        // was a failure.
        _ if ok == DEFAULT_OK_EXIT_CODES => {
            bail!("benchmark subject `{bin}` exited with {status}{via}")
        }
        _ => bail!(
            "benchmark subject `{bin}` exited with {status}{via}, and ok_exit_codes is {}",
            ok.iter().map(i32::to_string).collect::<Vec<_>>().join(", ")
        ),
    }
}

/// Run once, discarding output, returning elapsed wall time and exit code.
///
/// No shell. Spawning a shell adds its own startup cost and variance to every
/// sample, which for commands in the 10ms range is a large fraction of the
/// measurement — the same reasoning behind poop's refusal to support one.
fn time_once(cmd: &[String], site: &Site, ok: &[i32]) -> Result<Sample> {
    let mut c = command(cmd, site)?;
    c.stdout(Stdio::null()).stderr(Stdio::null());
    let bin = &cmd[0];
    let start = Instant::now();
    let mut child = c
        .spawn()
        .with_context(|| format!("failed to spawn `{bin}`"))?;
    // An uncontended lock inside the timed window; see `tracked::started`.
    tracked::started(child.id());
    let status = child.wait();
    let ms = start.elapsed().as_secs_f64() * 1000.0;
    tracked::finished();
    let status = status.with_context(|| format!("failed to wait for `{bin}`"))?;
    let exit_code = accepted(bin, status, ok, "")?;
    Ok(Sample { ms, exit_code })
}

/// How much of a failing prepare, setup or check step's stderr to keep for
/// the message. Enough for the last few lines; a verbose reset command's full
/// output would otherwise sit in memory before every sample.
const UNTIMED_STDERR_TAIL: usize = 4096;

/// Run a subject's prepare step. Untimed, so reading its stderr for the error
/// message costs the measurement nothing.
fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
    required("prepare", cmd, site)
}

/// Run an untimed step that must succeed: `prepare` or `setup`.
fn required(what: &str, cmd: &[String], site: &Site) -> Result<()> {
    match untimed(what, cmd, site)? {
        None => Ok(()),
        Some(failure) => bail!("{failure}"),
    }
}

/// Run a subject's check step after a timed sample. `Ok(None)` is a pass and
/// `Ok(Some(why))` a failed sample. Only a check that cannot be started at
/// all is an error: that is a mistake in `tak.toml`, not a finding about the
/// subject, and would otherwise read as every sample having failed.
fn check_once(cmd: &[String], site: &Site) -> Result<Option<String>> {
    untimed("check", cmd, site)
}

/// Run an untimed step — `prepare`, `setup` or `check`, named by `step` in
/// messages. `Ok(Some(why))` when it exits non-zero, naming the step and the
/// last line of its stderr.
///
/// Its output is not passed through: on a terminal it would tear up the
/// progress bar, and in a log a setup that clones a fixture could bury the
/// results. The tail of stderr is kept for the message.
///
/// Always judged by exit 0, whatever the subject's `ok_exit_codes` say: those
/// describe the program being measured. A setup or reset that failed leaves
/// every later sample starting from the wrong state, and a check passes only
/// by exiting 0.
///
/// stderr goes to an anonymous temporary file, not a pipe, and the step is
/// done when its process exits. With a pipe, a step that starts something in
/// the background — a fixture server, a daemon, a build server, `sleep 600 &`
/// — leaves that process holding the write end: waiting for EOF hung the
/// whole run, and closing the read end instead would kill the process with
/// SIGPIPE the next time it logged. A file has neither problem. tak neither
/// waits for nor kills such processes, since a server started by `setup` may
/// be exactly the point; one still running while samples are timed competes
/// with them, and the timings show it.
///
/// The cost is disk: whatever a leftover process writes to stderr lands in
/// the file, in the temp directory, for as long as it runs. The file has no
/// name on Unix and is deleted when its last handle closes on Windows, so the
/// space comes back once tak has dropped its handle and the process exits. A
/// step whose background process logs heavily should redirect that output.
///
/// There is deliberately no overall deadline: a setup that builds or clones a
/// fixture can legitimately take minutes.
fn untimed(step: &str, cmd: &[String], site: &Site) -> Result<Option<String>> {
    let mut c = command(cmd, site)?;
    let bin = &cmd[0];
    let err = tempfile::tempfile()
        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
    let reader = err
        .try_clone()
        .with_context(|| format!("failed to create a file for {step} `{bin}`'s stderr"))?;
    c.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::from(err));
    let status = run_tracked(&mut c).with_context(|| format!("failed to spawn {step} `{bin}`"))?;
    if status.success() {
        return Ok(None);
    }
    // A check like `git diff --quiet` says nothing on failure by design, so
    // silence is reported as the status alone. An unreadable file is treated
    // the same way: the status is the finding, the stderr only decoration.
    let tail = stderr_tail(&reader).unwrap_or_default();
    let stderr = String::from_utf8_lossy(&tail);
    Ok(Some(match stderr.lines().rfind(|l| !l.trim().is_empty()) {
        Some(last) => format!("{step} `{bin}` exited with {status}: {}", last.trim()),
        None => format!("{step} `{bin}` exited with {status}"),
    }))
}

/// The most a metric command may print. One number and a newline is a few
/// dozen bytes; anything near this is a log or a report, not a value, and
/// guessing which part of it was meant would record the wrong thing.
const METRIC_OUTPUT_MAX: usize = 1024;

/// A subject's custom metric: a file's size in bytes, or the one number a
/// command prints.
///
/// Taken once, after the subject's samples and instruction counts, and not
/// part of either. After, because `setup` or the samples themselves may be
/// what produces the file or the output being measured.
///
/// A file is `stat`ed, following symlinks, and must be a regular file: a
/// directory's size is filesystem bookkeeping, not the size of what is in it.
///
/// A command runs in the subject's `dir` and `env`, with the same variables
/// removed, no shell, and no deadline, like `setup` or `check`. It must exit 0
/// and print exactly one number; see [`parse_metric_value`]. Its output is
/// captured the way `version_cmd`'s is, through [`capture`]: bounded while it
/// is read, so a script that dumps a report is stopped at
/// [`METRIC_OUTPUT_MAX`] instead of filling memory or a disk, and not waited
/// on past its exit, so one that leaves something running in the background
/// holding the pipe open does not hang the run.
pub fn custom_metric(source: &MetricSource, s: &Subject, settings: &Settings) -> Result<f64> {
    match source {
        MetricSource::File(path) => {
            let meta = std::fs::metadata(path)
                .with_context(|| format!("could not read the size of {}", path.display()))?;
            if !meta.is_file() {
                bail!("{} is not a regular file", path.display());
            }
            Ok(meta.len() as f64)
        }
        MetricSource::Cmd(argv) => {
            let site = Site {
                dir: s.dir.as_deref(),
                env: &s.env,
                settings,
            };
            metric_cmd_once(argv, &site)
        }
    }
}

fn metric_cmd_once(argv: &[String], site: &Site) -> Result<f64> {
    let bin = &argv[0];
    let out = capture(argv, site, None, METRIC_OUTPUT_MAX, true)?;
    // Either way the metric is lost, and whatever the command started is
    // stopped, unlike after a `version_cmd`: a metric is taken between
    // benchmarks, and a leftover would compete with the next one's samples.
    // `capture` stops the group only while the command itself runs, so a
    // background writer that crosses the cap after it exited, or that still
    // holds stdout, is stopped here. Harmless when nothing is left.
    if out.overflowed || out.stdout_open {
        stop_leftovers(out.pgid);
    }
    // Before the status: a command stopped for printing too much died of
    // tak's signal, and saying so would hide why it was stopped.
    if out.overflowed {
        bail!(
            "`{bin}` and what it started printed more than {METRIC_OUTPUT_MAX} bytes, so they were \
             stopped; a metric command prints one number and nothing else"
        );
    }
    // Something the command left running still holds its stdout and may
    // print more, so what arrived so far is not known to be the whole answer.
    if out.stdout_open {
        bail!(
            "`{bin}` exited but left a process holding its stdout open, so that was stopped; \
             a metric command must finish its output before it exits"
        );
    }
    if !out.status.success() {
        bail!(
            "`{bin}` exited with {}: {}",
            out.status,
            last_line(&out.stderr_tail)
        );
    }
    let text = std::str::from_utf8(&out.stdout)
        .map_err(|_| anyhow::anyhow!("`{bin}` printed something that is not UTF-8"))?;
    parse_metric_value(text).with_context(|| format!("`{bin}`"))
}

/// Read a metric command's stdout as one number.
///
/// Deliberately strict. Surrounding whitespace, a trailing newline included,
/// is ignored; what is left must be a single non-negative decimal: digits,
/// optionally a fraction, optionally an exponent — `1234`, `12.5`, `1.2e6`.
/// No sign, no `inf` or `nan`, no hex, no thousands separators, no unit, and
/// nothing else on the line or on another one. A script that prints
/// `bundle: 42 kB` or two numbers has a bug worth hearing about, and pulling
/// the first number out of it would record whichever one happened to come
/// first. Negative values are refused because `compare` reports a change as a
/// percentage of the base, which is meaningless against a negative one, and
/// nothing a size or a count measures goes below zero.
pub fn parse_metric_value(text: &str) -> Result<f64> {
    let t = text.trim_matches(|c: char| c.is_ascii_whitespace());
    if t.is_empty() {
        bail!("printed nothing; a metric command prints one number");
    }
    let bytes = t.as_bytes();
    let digits = |i: &mut usize| {
        let start = *i;
        while *i < bytes.len() && bytes[*i].is_ascii_digit() {
            *i += 1;
        }
        *i > start
    };
    let mut i = 0;
    let mut ok = digits(&mut i);
    if ok && i < bytes.len() && bytes[i] == b'.' {
        i += 1;
        ok = digits(&mut i);
    }
    if ok && i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') {
        i += 1;
        if i < bytes.len() && (bytes[i] == b'+' || bytes[i] == b'-') {
            i += 1;
        }
        ok = digits(&mut i);
    }
    if !ok || i != bytes.len() {
        bail!(
            "printed {t:?}, not one number; a metric command prints a single non-negative \
             number such as `1234` or `12.5`, and nothing else"
        );
    }
    let v: f64 = t
        .parse()
        .with_context(|| format!("printed {t:?}, which is not a number"))?;
    if !v.is_finite() {
        bail!("printed {t:?}, which is too large to record");
    }
    Ok(v)
}

/// The last [`UNTIMED_STDERR_TAIL`] bytes of a step's stderr file.
///
/// Read by position, not through the file cursor: the handle is a duplicate
/// of the one a leftover process may still be writing through, and on Unix
/// they share the cursor, so seeking would move where that process writes.
/// Windows has no positional read that leaves the cursor alone; there a
/// leftover writer may overwrite part of a file nobody reads again.
fn stderr_tail(f: &std::fs::File) -> std::io::Result<Vec<u8>> {
    let len = f.metadata()?.len();
    let start = len.saturating_sub(UNTIMED_STDERR_TAIL as u64);
    let mut buf = vec![0u8; (len - start) as usize];
    let mut filled = 0;
    while filled < buf.len() {
        let n = read_at(f, &mut buf[filled..], start + filled as u64)?;
        if n == 0 {
            break;
        }
        filled += n;
    }
    buf.truncate(filled);
    Ok(buf)
}

#[cfg(unix)]
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
    std::os::unix::fs::FileExt::read_at(f, buf, offset)
}

#[cfg(windows)]
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<usize> {
    std::os::windows::fs::FileExt::seek_read(f, buf, offset)
}

/// One entry in a run's sample order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Slot {
    /// Index into the subjects being measured.
    pub subject: usize,
    /// Whether this sample is kept. Warmup samples run through the same
    /// prepare-then-run path and are discarded.
    pub timed: bool,
}

/// The order in which to take samples: every warmup round, then every timed
/// round, each round a fresh shuffle of the subjects due in it.
///
/// Measuring one subject to completion before starting the next puts any
/// drift over the run — contention on a shared host, thermal throttling, a
/// cache filling up — entirely on whichever subjects ran while it happened,
/// where it reads as a difference between them. One sample of each per round
/// spreads that drift across all of them, and shuffling each round stops any
/// subject from systematically running first (cold) or right after a
/// particular other one (whose leftovers it inherits).
///
/// A subject with fewer samples than there are rounds sits out evenly spaced
/// rounds rather than dropping out at the end, which would leave the late
/// part of the run — and its drift — to the others.
///
/// `counts` is `(warmup, runs)` per subject. The same seed gives the same
/// order for the same subjects.
pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
    let mut rng = fastrand::Rng::with_seed(seed);
    let warmups: Vec<u64> = counts.iter().map(|&(w, _)| u64::from(w)).collect();
    let runs: Vec<u64> = counts.iter().map(|&(_, r)| u64::from(r)).collect();
    let mut out = rounds(&warmups, false, &mut rng);
    out.extend(rounds(&runs, true, &mut rng));
    out
}

/// Shuffled rounds taking `count[i]` samples of subject `i`.
fn rounds(count: &[u64], timed: bool, rng: &mut fastrand::Rng) -> Vec<Slot> {
    let total = count.iter().copied().max().unwrap_or(0);
    let mut out = Vec::new();
    for round in 0..total {
        // Subject i is due in the rounds where floor(r * k / R) steps up:
        // exactly k of the R rounds, as evenly spaced as integers allow.
        let mut due: Vec<usize> = (0..count.len())
            .filter(|&i| (round + 1) * count[i] / total > round * count[i] / total)
            .collect();
        rng.shuffle(&mut due);
        out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
    }
    out
}

/// Derive a benchmark's seed from the run's, so `--bench x --seed n` takes
/// the same order for `x` as the full run with `--seed n` did.
pub fn seed_for(seed: u64, bench: &str) -> u64 {
    // FNV-1a: a fixed function, unlike std's randomly keyed hasher.
    bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
    })
}

/// Told about a run as it happens, to report progress.
pub trait Observer {
    /// Samples still to take per subject, warmups included. Called before the
    /// first sample and again once `runs = "auto"` has settled its counts.
    fn planned(&mut self, _remaining: &[u64]) {}
    /// `subject`'s setup step is starting. Untimed and not a sample, so it
    /// counts toward neither the samples taken nor their average.
    fn setting_up(&mut self, _subject: usize) {}
    /// Every setup has run, and `subject`'s succeeded; nothing of it has run
    /// yet, not its version, not a warmup. Asked after *all* setups rather
    /// than after its own, since a later subject's setup can change the
    /// paths an earlier one runs in. An error drops the subject as a failed
    /// setup would. `tak backfill --commits` checks here that the old tree's
    /// code has not left a path leading out of the checkout.
    fn set_up(&mut self, _subject: usize) -> Result<()> {
        Ok(())
    }
    /// A step of `subject` that runs from its paths is about to start: its
    /// setup, the prepare before a sample, the sample itself (after that
    /// prepare), or the check after it. Asked before each of them, warmups
    /// included, since any earlier step, of this subject or another, can
    /// change the paths the next one runs with. Never inside the timed
    /// window. An error drops the subject.
    fn before_run(&mut self, _subject: usize) -> Result<()> {
        Ok(())
    }
    /// A sample of `subject` is starting.
    fn started(&mut self, _subject: usize) {}
    /// A sample of `subject` finished; `elapsed` covers its prepare step too.
    fn finished(&mut self, _subject: usize, _elapsed: Duration) {}
    /// `subject` failed and takes no more samples.
    fn dropped(&mut self, _subject: usize) {}
}

/// An observer that reports nothing.
pub struct Quiet;
impl Observer for Quiet {}

/// What one subject's run produced.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Samples {
    /// Timed samples in milliseconds, in the order taken.
    pub times: Vec<f64>,
    /// Whether the subject's `check` passed after each timed sample, aligned
    /// with `times`. Empty when the subject has no check.
    pub checks: Vec<bool>,
    /// What each timed sample exited with, aligned with `times`: always one
    /// of the subject's `ok_exit_codes`.
    pub exit_codes: Vec<i32>,
    /// Why the first failing check failed, for the warning that reports it.
    pub first_failure: Option<String>,
}

impl Samples {
    /// Checks that passed.
    pub fn passed(&self) -> usize {
        self.checks.iter().filter(|&&ok| ok).count()
    }
}

/// Measure several subjects against each other, interleaved.
///
/// Returns each subject's timed samples in the order they were taken, with
/// the outcome of its check after each one, or the error that stopped it. A failing subject is dropped from the remaining
/// rounds and the others carry on: one competitor breaking should not throw
/// away a long run's worth of everyone else's samples. Subject directories
/// are used as given, so the caller resolves them first.
///
/// Every subject's `setup` runs first, once, in the order given: before
/// any warmup, so a subject's first sample never shares the machine with
/// another's setup and none of it is counted toward an auto run count. A
/// subject whose setup fails is dropped like one whose prepare does.
///
/// Sampling then runs in two phases. The warmups come first, plus one kept
/// sample of every `runs = "auto"` subject that has no warmups, so each auto
/// subject has been timed at least once. Its run count is then fixed from the
/// fastest of those samples, and every remaining timed sample is taken in
/// shuffled rounds.
///
/// A subject's `check` runs after each of its timed samples, pilots included,
/// and never after a warmup: a warmup is discarded, so whether it did the
/// right work says nothing about any result. A failing check is recorded
/// against its sample and the subject carries on — how often it fails is the
/// finding — so only a check that cannot be started drops the subject.
pub fn interleaved(
    subjects: &[Subject],
    seed: u64,
    settings: &Settings,
    observer: &mut dyn Observer,
) -> Vec<Result<Samples>> {
    interleaved_with_versions(subjects, seed, settings, observer).0
}

/// A subject's `version_cmd` result: `None` when it declares none or never
/// got that far, otherwise what it printed or why it could not tell.
pub type Version = Option<Result<String>>;

/// [`interleaved`], also returning each subject's version.
///
/// Versions are asked for after every `setup` and before any warmup: setup
/// may be what installs or builds the subject, so asking earlier would name
/// the wrong program or none, and a tool that warms a cache or checks for
/// updates on `--version` does so before the first sample rather than
/// between samples. A subject whose setup failed is not asked.
pub fn interleaved_with_versions(
    subjects: &[Subject],
    seed: u64,
    settings: &Settings,
    observer: &mut dyn Observer,
) -> (Vec<Result<Samples>>, Vec<Version>) {
    let mut rng = fastrand::Rng::with_seed(seed);
    let mut results: Vec<Result<Samples>> = subjects
        .iter()
        .map(|s| {
            // Zero runs would leave nothing to report on.
            if s.runs == Runs::Fixed(0) {
                bail!("runs must be at least 1");
            }
            Ok(Samples::default())
        })
        .collect();
    // The fastest whole sample of each subject so far, prepare included —
    // what an auto count is sized from. The fastest, because a warmup is
    // often a cold outlier and would shrink the count for no reason.
    let mut fastest: Vec<Option<Duration>> = vec![None; subjects.len()];

    let warmups: Vec<u64> = subjects.iter().map(|s| u64::from(s.warmup)).collect();
    let pilots: Vec<u64> = subjects
        .iter()
        .map(|s| u64::from(s.runs == Runs::Auto && s.warmup == 0))
        .collect();
    // Until the auto counts are known, plan on each one's floor.
    let provisional: Vec<u64> = subjects
        .iter()
        .zip(&warmups)
        .map(|(s, w)| {
            w + u64::from(match s.runs {
                Runs::Fixed(n) => n,
                Runs::Auto => s.auto.min,
            })
        })
        .collect();
    observer.planned(&provisional);

    for (i, s) in subjects.iter().enumerate() {
        let (Some(setup), Ok(_)) = (&s.setup, &results[i]) else {
            continue;
        };
        observer.setting_up(i);
        let site = Site {
            dir: s.setup_dir.as_deref(),
            env: &s.env,
            settings,
        };
        // Before as well as after: an earlier subject's setup may have
        // changed the paths this one runs with.
        if let Err(e) = observer
            .before_run(i)
            .and_then(|()| required("setup", setup, &site))
        {
            results[i] = Err(e);
            observer.dropped(i);
        }
    }
    for (i, result) in results.iter_mut().enumerate() {
        if result.is_ok()
            && let Err(e) = observer.set_up(i)
        {
            *result = Err(e);
            observer.dropped(i);
        }
    }

    let versions: Vec<Version> = subjects
        .iter()
        .zip(&results)
        .map(|(s, r)| r.as_ref().ok().and_then(|_| subject_version(s, settings)))
        .collect();

    let mut first = rounds(&warmups, false, &mut rng);
    first.extend(rounds(&pilots, true, &mut rng));
    run_slots(
        &first,
        subjects,
        settings,
        &mut results,
        &mut fastest,
        observer,
    );

    let remaining: Vec<u64> = subjects
        .iter()
        .enumerate()
        .map(|(i, s)| match (&results[i], s.runs) {
            (Err(_), _) => 0,
            (Ok(_), Runs::Fixed(n)) => u64::from(n),
            (Ok(taken), Runs::Auto) => {
                let n = auto_runs(&s.auto, fastest[i]);
                u64::from(n).saturating_sub(taken.times.len() as u64)
            }
        })
        .collect();
    observer.planned(&remaining);
    let second = rounds(&remaining, true, &mut rng);
    run_slots(
        &second,
        subjects,
        settings,
        &mut results,
        &mut fastest,
        observer,
    );
    (results, versions)
}

/// An auto subject's run count. One that was never timed — its every sample
/// failed, so it is being dropped anyway — gets the floor.
fn auto_runs(auto: &AutoRuns, fastest: Option<Duration>) -> u32 {
    fastest.map_or(auto.min, |d| auto.runs_for(d))
}

/// Take the given samples, recording timed ones and the fastest slot seen.
///
/// `fastest` covers prepare and the command but not the check, so an auto
/// count is sized from the same kind of sample whether it was a warmup (which
/// runs no check) or a pilot. The observer is told the whole slot, check
/// included, because that is what its time estimate has to cover.
fn run_slots(
    slots: &[Slot],
    subjects: &[Subject],
    settings: &Settings,
    results: &mut [Result<Samples>],
    fastest: &mut [Option<Duration>],
    observer: &mut dyn Observer,
) {
    for slot in slots {
        let Ok(samples) = &mut results[slot.subject] else {
            continue;
        };
        let s = &subjects[slot.subject];
        let site = Site {
            dir: s.dir.as_deref(),
            env: &s.env,
            settings,
        };
        observer.started(slot.subject);
        // Before the prepare as well as after it, and outside `began`, which
        // sizes auto runs: the previous sample, of any subject, may have
        // changed the paths this prepare runs with.
        let vetted = if s.prepare.is_some() {
            observer.before_run(slot.subject)
        } else {
            Ok(())
        };
        let began = Instant::now();
        let taken = vetted
            .and_then(|()| {
                s.prepare
                    .as_deref()
                    .map_or(Ok(()), |p| prepare_once(p, &site))
            })
            .and_then(|()| observer.before_run(slot.subject))
            .and_then(|()| time_once(&s.cmd, &site, &s.ok_exit_codes));
        let elapsed = began.elapsed();
        // Only after the clock has stopped: the check is outside the
        // measurement, however long it takes.
        let checked = match (&taken, &s.check) {
            // Asked again first: the sample just run can have changed the
            // paths the check runs with.
            (Ok(_), Some(check)) if slot.timed => observer
                .before_run(slot.subject)
                .and_then(|()| check_once(check, &site))
                .map(Some),
            _ => Ok(None),
        };
        match taken.and_then(|sample| checked.map(|c| (sample, c))) {
            Ok((sample, check)) => {
                if slot.timed {
                    samples.times.push(sample.ms);
                    samples.exit_codes.push(sample.exit_code);
                }
                if let Some(failure) = check {
                    samples.checks.push(failure.is_none());
                    if samples.first_failure.is_none() {
                        samples.first_failure = failure;
                    }
                }
                let f = &mut fastest[slot.subject];
                *f = Some(f.map_or(elapsed, |f| f.min(elapsed)));
                observer.finished(slot.subject, began.elapsed());
            }
            Err(e) => {
                results[slot.subject] = Err(e);
                observer.dropped(slot.subject);
            }
        }
    }
}

/// Wall-clock statistics over a set of samples, in milliseconds.
///
/// Reports `min` alongside the mean because contention is one-sided — a busy
/// machine can only make a run slower, never faster — so the minimum is a far
/// more robust estimator than the mean on shared CI hardware. The standard
/// deviation is there to show how noisy the run was, not to be compared.
pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
    let mut sorted = samples.to_vec();
    sorted.sort_by(f64::total_cmp);
    let n = sorted.len();
    let mean = sorted.iter().sum::<f64>() / n as f64;
    // Sample (n - 1) deviation, as hyperfine reports; a single sample has none.
    let stddev = if n > 1 {
        (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
    } else {
        0.0
    };
    BTreeMap::from([
        ("wall_min_ms".to_string(), sorted[0]),
        ("wall_p50_ms".to_string(), sorted[n / 2]),
        ("wall_mean_ms".to_string(), mean),
        ("wall_max_ms".to_string(), sorted[n - 1]),
        ("wall_stddev_ms".to_string(), stddev),
        ("wall_n".to_string(), n as f64),
    ])
}

/// Signs a subject's samples should not be taken at face value, as
/// sentences for stderr. `samples` must be in the order they were taken.
///
/// Two, both from hyperfine's experience of what goes wrong:
///
/// - **Outliers**, by modified z-score (0.6745 x distance from the median /
///   median absolute deviation) above 3.5, the usual cut-off. Something else
///   on the machine ran, or the command's own work varies from run to run.
/// - **A slow first sample**, over twice the median of the rest: a cache the
///   warmup did not fill. The first timed sample should look like the others.
///
/// Nothing is dropped or corrected; the point is to say when a comparison
/// deserves a second run. Slow outliers leave the minimum alone, but a fast
/// one may be the minimum, so the two are reported apart.
pub fn warnings(samples: &[f64]) -> Vec<String> {
    let mut out = Vec::new();
    let n = samples.len();
    if n < 5 {
        return out;
    }
    let median = |v: &mut Vec<f64>| {
        v.sort_by(f64::total_cmp);
        let m = v.len();
        if m.is_multiple_of(2) {
            (v[m / 2 - 1] + v[m / 2]) / 2.0
        } else {
            v[m / 2]
        }
    };
    let med = median(&mut samples.to_vec());
    let mad = median(&mut samples.iter().map(|x| (x - med).abs()).collect());
    // The modified z-score needs a spread to divide by. When over half the
    // samples equal the median the median deviation is zero, and any
    // stand-in computed from all the samples would be inflated by the very
    // spikes it should catch. With a flat majority there is no noise to
    // measure against, so anything over a quarter away from the median
    // counts. Identical samples still raise nothing.
    let outlier = |x: f64| {
        if mad > 0.0 {
            0.6745 * (x - med).abs() / mad > 3.5
        } else {
            med > 0.0 && (x - med).abs() > 0.25 * med
        }
    };
    {
        let (fast, slow) = samples
            .iter()
            .filter(|&&x| outlier(x))
            .fold(
                (0, 0),
                |(f, s), &x| if x < med { (f + 1, s) } else { (f, s + 1) },
            );
        if slow > 0 {
            out.push(format!(
                "{slow} of {n} samples are slow outliers; something else was running, or the \
                 command's work varies. Consider a quieter machine or more runs."
            ));
        }
        // A fast outlier is not harmless the way a slow one is: it is the
        // minimum tak reports, so the headline number may rest on it.
        if fast > 0 {
            out.push(format!(
                "{fast} of {n} samples are fast outliers, and the reported minimum may be one of \
                 them; check the command did the same work every time."
            ));
        }
    }
    let rest = median(&mut samples[1..].to_vec());
    if rest > 0.0 && samples[0] > 2.0 * rest {
        out.push(format!(
            "the first sample took {:.1}x the median of the rest; the warmup did not fill some \
             cache. Consider more warmup runs.",
            samples[0] / rest
        ));
    }
    out
}

/// Wall-clock statistics over `plan.runs` samples of one command.
pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
    let subject = Subject {
        name: SELF_TOOL.to_string(),
        cmd: plan.cmd.clone(),
        prepare: None,
        setup: None,
        setup_dir: None,
        check: None,
        dir: plan.dir.clone(),
        version_cmd: None,
        env: BTreeMap::new(),
        vars: BTreeMap::new(),
        when: None,
        runs: Runs::Fixed(plan.runs),
        auto: AutoRuns {
            budget: crate::config::DEFAULT_BUDGET,
            min: crate::config::DEFAULT_MIN_RUNS,
            max: crate::config::DEFAULT_MAX_RUNS,
        },
        warmup: plan.warmup,
        counters: false,
        allocations: false,
        ok_exit_codes: DEFAULT_OK_EXIT_CODES.to_vec(),
        metrics: BTreeMap::new(),
    };
    // One subject has one possible order, so the seed is irrelevant.
    let samples = interleaved(
        std::slice::from_ref(&subject),
        0,
        &plan.settings,
        &mut Quiet,
    )
    .pop()
    .expect("one result per subject")?;
    Ok(stats(&samples.times))
}

/// Is cachegrind usable on this machine?
///
/// Exposed so callers can tell "no counters because valgrind is missing" from
/// "no counters because the measurement failed" — two problems with entirely
/// different fixes.
pub fn valgrind_available() -> bool {
    Command::new("valgrind")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Repeats of the cachegrind run. Three is enough to catch a bimodal subject
/// without tripling the cost of a measurement that is already ~50x slowed.
const COUNTER_RUNS: u32 = 3;

/// A subject varying by more than this is doing environment-dependent work, and
/// its instruction count is not a usable gate. Well above the ~0.005% observed
/// for a genuinely hermetic command, far below the 16% seen from one that
/// touches the network.
const SPREAD_WARN_PCT: f64 = 0.5;

/// Instruction counts from repeated cachegrind runs.
#[derive(Debug, Clone, Copy)]
pub struct Counted {
    pub min: u64,
    pub max: u64,
    pub runs: u32,
}

impl Counted {
    /// Relative spread across runs, as a percentage of the minimum.
    pub fn spread_pct(&self) -> f64 {
        if self.min == 0 {
            return 0.0;
        }
        (self.max - self.min) as f64 / self.min as f64 * 100.0
    }

    /// Whether this subject looks non-hermetic.
    ///
    /// The metric is deterministic; the program being measured need not be. A
    /// CLI that checks for updates, reads a cache it may have just created, or
    /// resolves DNS retires a different number of instructions depending on
    /// conditions that have nothing to do with the code under test.
    pub fn is_suspect(&self) -> bool {
        self.spread_pct() > SPREAD_WARN_PCT
    }
}

/// Instruction count via `valgrind --tool=cachegrind`, repeated.
///
/// Reports the **minimum**, for the same reason wall clock does: the extra work
/// a subject sometimes performs is one-sided. A run that consults the network or
/// populates a cache can only retire *more* instructions than the quiet path,
/// never fewer, so the floor is the stable estimator.
///
/// Returns `Ok(None)` when valgrind is unavailable rather than failing: this is
/// the expected state on macOS (no usable Apple Silicon support) and Windows.
/// Those platforms record timing only, and the CI gate lives on the Linux job.
/// Locally, a container gets you counters on any host.
pub fn instructions(
    cmd: &[String],
    dir: Option<&std::path::Path>,
    settings: &Settings,
) -> Result<Option<Counted>> {
    count(
        cmd,
        None,
        &Site {
            dir,
            env: &BTreeMap::new(),
            settings,
        },
        &DEFAULT_OK_EXIT_CODES,
        false,
        &|| Ok(()),
    )
    .map(|c| c.map(|(c, _)| c))
}

/// [`instructions`] for a declared subject: its environment, its
/// `ok_exit_codes`, and its prepare step before every cachegrind run, since
/// each run has to start from the same state the timed samples did.
pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
    subject_count(s, settings, false, &|| Ok(())).map(|c| c.map(|(c, _)| c))
}

/// [`subject_instructions`], asking `vet` before each counted run, after its
/// `prepare`, as [`Observer::before_run`] is asked before each sample.
pub fn subject_instructions_vetted(
    s: &Subject,
    settings: &Settings,
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Counted>> {
    subject_count(s, settings, false, vet).map(|c| c.map(|(c, _)| c))
}

/// [`subject_instructions`], also returning the cachegrind profile of the run
/// whose count is reported. That is the minimum, so the profile's total is
/// the number recorded, and attributing a change to its functions explains
/// exactly the change the gate saw.
///
/// The profile is a separate result: failing to keep it must not cost the
/// count, which is the one metric that gates.
pub fn subject_profile(s: &Subject, settings: &Settings) -> Result<Option<(Counted, Profiled)>> {
    subject_profile_vetted(s, settings, &|| Ok(()))
}

/// [`subject_profile`], asking `vet` as [`subject_instructions_vetted`] does.
pub fn subject_profile_vetted(
    s: &Subject,
    settings: &Settings,
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Profiled)>> {
    Ok(subject_count(s, settings, true, vet)?
        .map(|(c, p)| (c, p.expect("a profile was asked for"))))
}

/// The raw cachegrind profile behind a count, or why it could not be kept.
pub type Profiled = Result<Vec<u8>>;

fn subject_count(
    s: &Subject,
    settings: &Settings,
    profile: bool,
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Option<Profiled>)>> {
    count(
        &s.cmd,
        s.prepare.as_deref(),
        &Site {
            dir: s.dir.as_deref(),
            env: &s.env,
            settings,
        },
        &s.ok_exit_codes,
        profile,
        vet,
    )
}

/// Run a subject's `version_cmd` once and return the version it reports, or
/// `None` when the subject declares none.
///
/// It runs where the subject does — its directory, its environment, the same
/// scrub — because that decides which binary a bare name resolves to, and the
/// point is to name the program that was measured. The result is the first
/// non-empty line of stdout, or of stderr when stdout has none: `java
/// -version` and some older tools print only there. Only one line, because a
/// version is a label on a results page, and several tools follow it with a
/// licence or build banner.
pub fn subject_version(s: &Subject, settings: &Settings) -> Option<Result<String>> {
    let argv = s.version_cmd.as_ref()?;
    let site = Site {
        dir: s.dir.as_deref(),
        env: &s.env,
        settings,
    };
    Some(version_once(argv, &site, VERSION_TIMEOUT))
}

/// How much of each stream a `version_cmd` keeps. A version is its first
/// non-empty line; a tool that follows it with a banner, or a help dump,
/// must not be held in memory for the rest.
const VERSION_OUTPUT_CAP: usize = 8192;

/// How long a `version_cmd` may take. Asking a tool its version should be
/// instant; one that stalls on a network or licence check must cost a
/// warning, not hang the run before its first sample with nothing on
/// screen. Fixed rather than a setting until a real tool needs longer.
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);

/// After the command exits, how long to wait for its output to finish
/// arriving. Anything it wrote is already in the pipe by then, so this only
/// ends up mattering when a process it started in the background still
/// holds the pipe open — and that must not hold up the run.
const VERSION_OUTPUT_GRACE: Duration = Duration::from_millis(500);

/// Read `r` to the end, keeping the first `cap` bytes in `kept` and
/// discarding the rest. Draining it all means the writer never blocks on a
/// full pipe, so the command can finish and report its real exit status.
/// `overflow` is set once anything past `cap` arrives, for a caller that
/// treats more output than that as a failure and stops the command.
///
/// With `tail`, the last [`UNTIMED_STDERR_TAIL`] bytes are kept there too:
/// an error message is at the end of a log, and a long one pushes it past
/// any prefix.
fn keep_prefix(
    mut r: impl std::io::Read,
    cap: usize,
    kept: &Mutex<Vec<u8>>,
    overflow: &std::sync::atomic::AtomicBool,
    tail: Option<&Mutex<Vec<u8>>>,
) {
    let mut buf = [0u8; 8192];
    loop {
        match r.read(&mut buf) {
            Ok(0) => return,
            Ok(n) => {
                let Ok(mut k) = kept.lock() else { return };
                let room = cap.saturating_sub(k.len());
                if n > room {
                    overflow.store(true, std::sync::atomic::Ordering::SeqCst);
                }
                k.extend_from_slice(&buf[..n.min(room)]);
                if let Some(Ok(mut t)) = tail.map(Mutex::lock) {
                    t.extend_from_slice(&buf[..n]);
                    let excess = t.len().saturating_sub(UNTIMED_STDERR_TAIL);
                    t.drain(..excess);
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => return,
        }
    }
}

/// Passing a fatal signal on to a running `version_cmd`'s process group.
///
/// The group is what lets a timeout stop everything the command started,
/// but it also takes the command out of the terminal's foreground group, so
/// a Ctrl-C — or a SIGTERM from CI cancelling the job — would stop tak and
/// leave the command running, however long it would otherwise have hung.
/// While a guard is alive, SIGINT, SIGTERM and SIGHUP kill that group and
/// then stop tak exactly as they would have without the handler. The
/// previous handlers come back when the guard drops, so the rest of a run
/// behaves as before: the measured commands share tak's group and get the
/// terminal's signals directly.
#[cfg(unix)]
mod forward_signals {
    use std::sync::atomic::{AtomicBool, AtomicI32, Ordering::SeqCst};

    const SIGNALS: [libc::c_int; 3] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP];

    /// What the handler knows, as atomics alone: nothing else is safe to
    /// touch from a signal handler.
    ///
    /// A handler can run on any thread and be preempted anywhere, so every
    /// path that records a signal in `pending` must end with someone acting
    /// on it. All accesses are `SeqCst`, which puts them in one order:
    ///
    /// - The handler writes `pending`, then reads `done` and `pgid`.
    ///   [`State::spawned`] writes `pgid` and then takes `pending`;
    ///   [`State::end`] writes `done` and then takes `pending`. Either a take
    ///   comes after the handler's write, and the spawning thread acts on the
    ///   signal, or every take that could have collected it came before, and
    ///   so did the store preceding it, which the handler's later read sees,
    ///   so the handler acts on the signal itself.
    /// - The handler reads `spawning` before `pgid`, and `spawned` writes
    ///   them in the opposite order, so a handler that sees `spawning`
    ///   cleared also sees the group.
    ///
    /// A handler that starts after [`State::end`] sees `spawning` cleared and
    /// never writes `pending`; one that started earlier and was preempted
    /// sees `done` and stops tak itself, without killing a group whose id may
    /// have been reused by then.
    pub(super) struct State {
        /// Between installing the handlers and recording the group: a
        /// command may exist whose group the handler cannot know yet.
        spawning: AtomicBool,
        /// The group to kill, or 0 when there is none.
        pgid: AtomicI32,
        /// A signal that arrived while `spawning`, for the spawning thread
        /// to act on once the group is known.
        pending: AtomicI32,
        /// The version step is over and nothing will look at `pending`
        /// again, so a late handler must act on its signal itself.
        done: AtomicBool,
    }

    /// What the handler should do with a signal.
    #[derive(Debug, PartialEq, Eq)]
    pub(super) enum Act {
        /// Leave it for [`State::spawned`] or [`State::end`].
        Defer,
        /// Kill this group (0 for none) and stop tak.
        Die { pgid: i32 },
    }

    impl State {
        pub(super) const fn new() -> State {
            State {
                spawning: AtomicBool::new(false),
                pgid: AtomicI32::new(0),
                pending: AtomicI32::new(0),
                done: AtomicBool::new(true),
            }
        }

        pub(super) fn begin(&self) {
            self.pending.store(0, SeqCst);
            self.pgid.store(0, SeqCst);
            self.done.store(false, SeqCst);
            self.spawning.store(true, SeqCst);
        }

        /// The handler's decision.
        pub(super) fn on_signal(&self, sig: libc::c_int) -> Act {
            if self.wants_to_defer() {
                self.defer(sig)
            } else {
                Act::Die {
                    pgid: self.pgid.load(SeqCst),
                }
            }
        }

        /// First half of [`State::on_signal`]: still spawning, group not yet
        /// known. Separate so a test can pause a handler between the halves.
        fn wants_to_defer(&self) -> bool {
            let spawning = self.spawning.load(SeqCst);
            spawning && self.pgid.load(SeqCst) == 0
        }

        /// Second half: record the signal, then check whether whoever would
        /// have collected it already has.
        fn defer(&self, sig: libc::c_int) -> Act {
            self.pending.store(sig, SeqCst);
            if self.done.load(SeqCst) {
                return Act::Die { pgid: 0 };
            }
            match self.pgid.load(SeqCst) {
                0 => Act::Defer,
                pgid => Act::Die { pgid },
            }
        }

        /// Record the group once the spawn returns (`None` if it failed),
        /// and hand back any signal that arrived meanwhile with the group
        /// to kill for it.
        pub(super) fn spawned(&self, pid: Option<u32>) -> Option<(libc::c_int, i32)> {
            let pgid = pid.map_or(0, |p| p as i32);
            self.pgid.store(pgid, SeqCst);
            self.spawning.store(false, SeqCst);
            let sig = self.pending.swap(0, SeqCst);
            (sig != 0).then_some((sig, pgid))
        }

        /// The step is over. Returns a signal a late handler deferred, which
        /// the caller must still act on; its group is not killed, since the
        /// command has been reaped and the id may be reused.
        pub(super) fn end(&self) -> Option<libc::c_int> {
            self.spawning.store(false, SeqCst);
            self.done.store(true, SeqCst);
            self.pgid.store(0, SeqCst);
            let sig = self.pending.swap(0, SeqCst);
            (sig != 0).then_some(sig)
        }
    }

    static STATE: State = State::new();

    /// Kill the group, then stop tak the way `sig` would have. The signal is
    /// blocked while a handler runs, so from there the raise takes effect —
    /// with the default action — as soon as the handler returns.
    fn die(sig: libc::c_int, pgid: i32) {
        // SAFETY: killpg, signal and raise are async-signal-safe.
        unsafe {
            if pgid > 0 {
                libc::killpg(pgid, libc::SIGKILL);
            }
            libc::signal(sig, libc::SIG_DFL);
            libc::raise(sig);
        }
    }

    extern "C" fn forward(sig: libc::c_int) {
        if let Act::Die { pgid } = STATE.on_signal(sig) {
            die(sig, pgid);
        }
    }

    pub struct Guard {
        previous: Vec<(libc::c_int, libc::sigaction)>,
    }

    impl Guard {
        /// Install the handlers, before spawning: a signal between here and
        /// [`Guard::spawned`] is held until the group is known.
        pub fn install() -> Guard {
            STATE.begin();
            let mut previous = Vec::new();
            for sig in SIGNALS {
                // SAFETY: plain-data structs, filled in before use; the
                // handler is an `extern "C" fn(c_int)`, as sa_sigaction
                // expects without SA_SIGINFO.
                unsafe {
                    let mut new: libc::sigaction = std::mem::zeroed();
                    new.sa_sigaction = forward as extern "C" fn(libc::c_int) as libc::sighandler_t;
                    libc::sigemptyset(&mut new.sa_mask);
                    let mut old: libc::sigaction = std::mem::zeroed();
                    if libc::sigaction(sig, &new, &mut old) == 0 {
                        previous.push((sig, old));
                    }
                }
            }
            Guard { previous }
        }

        /// The spawn returned: `pid` leads the new group, or `None` if the
        /// spawn failed. A signal that arrived during it is acted on now.
        pub fn spawned(pid: Option<u32>) {
            if let Some((sig, pgid)) = STATE.spawned(pid) {
                die(sig, pgid);
            }
        }
    }

    impl Drop for Guard {
        fn drop(&mut self) {
            // Before the previous handlers come back, so a signal one of ours
            // deferred late is still acted on.
            if let Some(sig) = STATE.end() {
                die(sig, 0);
            }
            for (sig, old) in &self.previous {
                // SAFETY: restores the action saved by `install`.
                unsafe {
                    libc::sigaction(*sig, old, std::ptr::null_mut());
                }
            }
        }
    }

    /// Driven on a private `State`, so no real signal is sent and the
    /// handler's own state is untouched: every way a handler and the version
    /// step can interleave ends with the signal acted on.
    #[cfg(test)]
    mod tests {
        use super::{Act, SeqCst, State};

        #[test]
        fn a_signal_during_the_spawn_is_held_until_the_group_is_known() {
            let s = State::new();
            s.begin();
            assert_eq!(s.on_signal(libc::SIGTERM), Act::Defer, "no group yet");
            assert_eq!(s.spawned(Some(42)), Some((libc::SIGTERM, 42)));
            assert_eq!(s.on_signal(libc::SIGINT), Act::Die { pgid: 42 });
            assert_eq!(s.end(), None);

            s.begin();
            assert_eq!(s.spawned(Some(7)), None, "nothing arrived");
            assert_eq!(s.end(), None);

            s.begin();
            assert_eq!(s.on_signal(libc::SIGINT), Act::Defer);
            assert_eq!(
                s.spawned(None),
                Some((libc::SIGINT, 0)),
                "a failed spawn still stops tak"
            );
            assert_eq!(s.end(), None);

            assert_eq!(
                s.on_signal(libc::SIGHUP),
                Act::Die { pgid: 0 },
                "after the step"
            );
            assert!(!s.wants_to_defer(), "and it never defers there");
        }

        /// A handler that decided to defer, then was preempted: whenever it
        /// resumes, its signal is acted on.
        #[test]
        fn a_handler_preempted_past_the_step_still_acts() {
            let s = State::new();

            // Until after the step ended: it sees `done` and stops tak,
            // without killing a group whose id may be reused.
            s.begin();
            assert!(s.wants_to_defer());
            assert_eq!(s.spawned(Some(42)), None);
            assert_eq!(s.end(), None);
            assert_eq!(s.defer(libc::SIGTERM), Act::Die { pgid: 0 });

            // Until after the spawn: it sees the group. Its write is also
            // left for `end`; acting twice on a signal is harmless.
            s.begin();
            assert!(s.wants_to_defer());
            assert_eq!(s.spawned(Some(42)), None);
            assert_eq!(s.defer(libc::SIGINT), Act::Die { pgid: 42 });
            assert_eq!(s.end(), Some(libc::SIGINT));

            // Its write landed before `end` took `pending` (and it read the
            // group before `spawned` stored it): `end` acts on it.
            s.begin();
            assert_eq!(s.spawned(Some(42)), None);
            s.pending.store(libc::SIGHUP, SeqCst);
            assert_eq!(s.end(), Some(libc::SIGHUP), "acted on at teardown");
        }
    }
}

/// Stop a command run by [`capture`] and everything it started, then reap it:
/// a `version_cmd` past its deadline, or a metric command past its output cap.
///
/// On Unix that is its whole process group, so a helper it spawned cannot go
/// on using CPU through the samples that follow, or hold the output pipes
/// open. Elsewhere only the command itself is stopped.
///
/// Only then: a command that exits on its own may have started a
/// daemon on purpose — a version check that launches a language server or
/// build daemon — and that is the tool's business, not tak's to kill.
fn stop_group(child: &mut std::process::Child) {
    #[cfg(unix)]
    {
        // The child leads its own group (`process_group(0)`), so its pid is
        // the group id. SAFETY: killpg only sends a signal.
        let pgid = child.id() as libc::pid_t;
        if unsafe { libc::killpg(pgid, libc::SIGKILL) } != 0 {
            let _ = child.kill();
        }
    }
    #[cfg(not(unix))]
    let _ = child.kill();
    let _ = child.wait();
}

fn version_once(argv: &[String], site: &Site, timeout: Duration) -> Result<String> {
    let bin = argv
        .first()
        .map(String::as_str)
        .unwrap_or("(empty command)");
    let Captured {
        status,
        stdout,
        stderr,
        stderr_tail,
        ..
    } = capture(argv, site, Some(timeout), VERSION_OUTPUT_CAP, false)?;

    // A failing command's output is an error message or a usage dump, not a
    // version, however much of it there is.
    if !status.success() {
        bail!("`{bin}` exited with {status}: {}", last_line(&stderr_tail));
    }
    let first = |bytes: &[u8]| {
        String::from_utf8_lossy(bytes)
            .lines()
            .map(str::trim)
            .find(|l| !l.is_empty())
            .map(str::to_string)
    };
    first(&stdout)
        .or_else(|| first(&stderr))
        .with_context(|| format!("`{bin}` printed nothing"))
}

/// The last non-empty line of a captured stream, for an error message.
fn last_line(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes)
        .lines()
        .map(str::trim)
        .rfind(|l| !l.is_empty())
        .unwrap_or("(no output)")
        .to_string()
}

/// What [`capture`] got from a command that finished.
struct Captured {
    status: std::process::ExitStatus,
    /// At most the cap passed to [`capture`].
    stdout: Vec<u8>,
    /// The first [`VERSION_OUTPUT_CAP`] bytes, where a version is.
    stderr: Vec<u8>,
    /// The last [`UNTIMED_STDERR_TAIL`] bytes, where an error is.
    stderr_tail: Vec<u8>,
    /// stdout went past the cap. With `stop_past_cap`, the command was
    /// stopped as soon as that was seen, and `status` is how it died.
    overflowed: bool,
    /// stdout was still open when the grace period after the command's exit
    /// ran out: something it left running holds it and may yet write to it.
    stdout_open: bool,
    /// The command's process group on Unix, which is also its pid, for a
    /// caller that has to stop what it left behind.
    pgid: u32,
}

/// Stop whatever is left of a finished command's process group: a caller's
/// decision, since leaving a daemon running can be the point; see
/// [`stop_group`]. The command itself has been reaped, but its group id
/// cannot be handed to a new process while any member of the group lives,
/// so this reaches only what the command started. Elsewhere there is no
/// group to reach. When nothing is left, `killpg` fails with ESRCH, which
/// is expected and ignored. It is called only when the output was rejected,
/// which is when something may be left.
fn stop_leftovers(pgid: u32) {
    #[cfg(unix)]
    // SAFETY: killpg only sends a signal.
    unsafe {
        libc::killpg(pgid as libc::pid_t, libc::SIGKILL);
    }
    #[cfg(not(unix))]
    let _ = pgid;
}

/// Run `argv` at `site` with both streams piped, keeping the first
/// `stdout_cap` bytes of stdout and [`VERSION_OUTPUT_CAP`] of stderr, and
/// reading and discarding the rest so the command never blocks on a full
/// pipe. Memory and disk stay bounded however much it prints.
///
/// It runs in its own process group, so a `timeout` or `stop_past_cap` can
/// stop everything it started. With `stop_past_cap`, output beyond the cap
/// is a failure the caller will report anyway, so the command is stopped the
/// moment it arrives rather than left to print for as long as it likes.
/// `timeout: None` waits as long as the command takes, as `setup` does.
///
/// Once the command exits, its output is waited for only briefly: a process
/// it left in the background may hold a pipe open indefinitely.
fn capture(
    argv: &[String],
    site: &Site,
    timeout: Option<Duration>,
    stdout_cap: usize,
    stop_past_cap: bool,
) -> Result<Captured> {
    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
    let bin = argv
        .first()
        .map(String::as_str)
        .unwrap_or("(empty command)");
    let mut cmd = command(argv, site)?;
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    // Its own process group, so a timeout can stop everything it started:
    // a helper left running would compete with the samples that follow.
    #[cfg(unix)]
    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
    // Being in its own group, it no longer gets the terminal's Ctrl-C; this
    // passes a fatal signal on to it until the guard drops.
    #[cfg(unix)]
    let _forward = forward_signals::Guard::install();
    let spawned = cmd.spawn();
    // Also when the spawn failed, so a signal held during it still stops tak.
    #[cfg(unix)]
    forward_signals::Guard::spawned(spawned.as_ref().ok().map(std::process::Child::id));
    let mut child = spawned.with_context(|| format!("failed to spawn `{bin}`"))?;
    // Known to `stop_running` like every other command tak runs, so a
    // backfill's interrupt stops it, and anything it leaves behind, before
    // deleting the checkout it ran in. Finished on every way out, early
    // returns included.
    tracked::started(child.id());
    struct Finished;
    impl Drop for Finished {
        fn drop(&mut self) {
            tracked::finished();
        }
    }
    let _finished = Finished;

    // One thread per stream, so neither pipe can fill while the other is
    // read. They are never joined: a background process the command started
    // may hold a pipe open long after it exits, and the run must not wait on
    // that. Each thread ends when its pipe finally closes.
    let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
    let overflow = Arc::new(AtomicBool::new(false));
    // stderr's overflow is never acted on: it only feeds an error message.
    let ignored = Arc::new(AtomicBool::new(false));
    let stdout_done = Arc::new(AtomicBool::new(false));
    let unused = Arc::new(AtomicBool::new(false));
    let spawn_reader = |r: Option<Box<dyn std::io::Read + Send>>,
                        cap: usize,
                        flag: &Arc<AtomicBool>,
                        done: &Arc<AtomicBool>,
                        tail: Option<&Arc<Mutex<Vec<u8>>>>| {
        let kept = Arc::new(Mutex::new(Vec::new()));
        if let Some(r) = r {
            let (kept, tx, flag, done) = (
                Arc::clone(&kept),
                done_tx.clone(),
                Arc::clone(flag),
                Arc::clone(done),
            );
            let tail = tail.map(Arc::clone);
            std::thread::spawn(move || {
                keep_prefix(r, cap, &kept, &flag, tail.as_deref());
                done.store(true, SeqCst);
                let _ = tx.send(());
            });
        } else {
            done.store(true, SeqCst);
            let _ = done_tx.send(());
        }
        kept
    };
    let stdout = spawn_reader(
        child.stdout.take().map(|o| Box::new(o) as _),
        stdout_cap,
        &overflow,
        &stdout_done,
        None,
    );
    let stderr_tail = Arc::new(Mutex::new(Vec::new()));
    let stderr = spawn_reader(
        child.stderr.take().map(|e| Box::new(e) as _),
        VERSION_OUTPUT_CAP,
        &ignored,
        &unused,
        Some(&stderr_tail),
    );

    let deadline = timeout.map(|t| Instant::now() + t);
    let status = loop {
        if stop_past_cap && overflow.load(SeqCst) {
            stop_group(&mut child);
            // Reaped by `stop_group`; this only reads the status it left.
            break child
                .wait()
                .with_context(|| format!("failed to wait for `{bin}`"))?;
        }
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if deadline.is_none_or(|d| Instant::now() < d) => {
                std::thread::sleep(Duration::from_millis(5));
            }
            Ok(None) => {
                stop_group(&mut child);
                bail!(
                    "`{bin}` did not finish within {}, so it was stopped",
                    crate::progress::fmt(timeout.unwrap_or_default())
                );
            }
            Err(e) => {
                stop_group(&mut child);
                return Err(e).with_context(|| format!("failed to wait for `{bin}`"));
            }
        }
    };
    let grace = Instant::now() + VERSION_OUTPUT_GRACE;
    for _ in 0..2 {
        let left = grace.saturating_duration_since(Instant::now());
        if done_rx.recv_timeout(left).is_err() {
            break;
        }
    }
    let take = |kept: &Mutex<Vec<u8>>| kept.lock().map(|k| k.clone()).unwrap_or_default();
    Ok(Captured {
        status,
        stdout: take(&stdout),
        stderr: take(&stderr),
        stderr_tail: take(&stderr_tail),
        overflowed: overflow.load(SeqCst),
        stdout_open: !stdout_done.load(SeqCst),
        pgid: child.id(),
    })
}

/// How much of valgrind's log to read. Only valgrind writes it, so it holds
/// a banner and a summary and is a few kilobytes; the cap is there so a
/// tool that turned verbose could not make tak read without limit.
const VALGRIND_LOG_CAP: u64 = 1 << 20;

/// Run `cmd` under valgrind with `tool` options to completion, returning its
/// exit status and the lines of valgrind's log that belong to the subject's
/// own process, where the tool's summary is.
///
/// valgrind writes its messages to a file of its own (`--log-fd`), and the
/// subject's stdout and stderr go to `/dev/null`, as they do for timed
/// samples. Mixing the two on one stream, as valgrind does by default,
/// caused every problem a subject's background process could cause: reading
/// the stream to EOF waited for that process and hung the run; a file for
/// it grew for as long as the process logged; a bounded tail of it could
/// have the summary pushed out by the process's output; and the subject
/// could print a line that read as the summary. With the log apart, nothing
/// the subject leaves behind can reach it, and the run is over when the
/// process spawned here exits.
///
/// The log is an anonymous temporary file — unlinked from the start, so a
/// subject that clears its temporary directory, as `rm -rf "$TMPDIR"/*`
/// does, cannot take the log with it. It reaches valgrind by descriptor:
/// close-on-exec is cleared for it in the child alone, and valgrind moves it
/// out of the client's sight and marks it close-on-exec again, so programs
/// the subject runs never hold it. A process the subject forks without exec
/// stays under valgrind and writes to the same file, under its own
/// `==PID==` prefix, which is why only the subject's pid's lines are
/// returned: valgrind replaces itself with the tool rather than forking, so
/// that is the pid spawned here.
///
/// Creating the file can fail — a full or read-only temporary directory —
/// and that is an error naming it, which the caller reports as a failed
/// measurement, never as valgrind being absent.
#[cfg(unix)]
fn under_valgrind(
    tool: &[&str],
    cmd: &[String],
    site: &Site,
) -> Result<(std::process::ExitStatus, String)> {
    use std::io::{Read, Seek};
    use std::os::fd::AsRawFd;
    use std::os::unix::process::CommandExt;
    let mut log = tempfile::tempfile().context("failed to create a file for valgrind's log")?;
    let fd = log.as_raw_fd();
    let mut argv: Vec<String> = std::iter::once("valgrind")
        .chain(tool.iter().copied())
        .map(String::from)
        .collect();
    argv.push(format!("--log-fd={fd}"));
    argv.extend_from_slice(cmd);
    let mut c = command(&argv, site)?;
    c.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    // SAFETY: runs in the child between fork and exec, and only calls fcntl,
    // which is async-signal-safe, on a descriptor this function owns.
    unsafe {
        c.pre_exec(move || {
            if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    // Spawned and waited for as `run_tracked` does, so under `tak backfill
    // --commits` the run is in its own process group (set by `command`) and
    // an interrupt stops it with everything it started. The group is set by
    // std, not by the hook above, which is the only `pre_exec` here.
    let mut child = c.spawn().context("failed to run valgrind")?;
    let pid = child.id();
    tracked::started(pid);
    let status = child.wait();
    tracked::finished();
    let status = status.context("failed to run valgrind")?;
    // An empty log is what a valgrind that could not start the subject
    // leaves: its launcher reports that on stderr, before the log is used.
    // The caller's "no summary" error says so rather than this one guessing.
    let mut raw = Vec::new();
    log.rewind().context("failed to read valgrind's log")?;
    log.take(VALGRIND_LOG_CAP)
        .read_to_end(&mut raw)
        .context("failed to read valgrind's log")?;
    let prefix = format!("=={pid}==");
    let own: String = String::from_utf8_lossy(&raw)
        .lines()
        .filter(|l| l.starts_with(&prefix))
        .flat_map(|l| [l, "\n"])
        .collect();
    Ok((status, own))
}

/// There is no valgrind to run on other platforms, and [`valgrind_available`]
/// says so before this is reached.
#[cfg(not(unix))]
fn under_valgrind(
    _tool: &[&str],
    _cmd: &[String],
    _site: &Site,
) -> Result<(std::process::ExitStatus, String)> {
    bail!("valgrind runs only on Unix")
}

/// The last line of valgrind's log with something on it past the `==PID==`
/// prefix, for an error that has no summary to show. valgrind ends its
/// output with a bare `==PID==` line, which says nothing.
fn last_log_line(log: &str) -> &str {
    log.lines()
        .map(|l| valgrind_line(l).unwrap_or(l).trim())
        .rfind(|l| !l.is_empty())
        .unwrap_or("(valgrind wrote no log; it may not have been able to start the command)")
}

/// `ok` applies to the subject under valgrind: cachegrind exits with its
/// client's code, and re-raises the signal a client died of.
///
/// With `profile`, each run writes its per-function profile to a scratch
/// file, and the one from the run at the minimum is returned. Without it the
/// profile goes to `/dev/null` as it always has. cachegrind writes it after
/// the client exits, so keeping it cannot move the count.
///
/// Anything that stops the profile being kept is returned in its place
/// rather than failing the count: an instruction count is still the gate
/// with or without the profile that explains it.
fn count(
    cmd: &[String],
    prepare: Option<&[String]>,
    site: &Site,
    ok: &[i32],
    profile: bool,
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<(Counted, Option<Profiled>)>> {
    if !valgrind_available() {
        return Ok(None);
    }

    // An absolute path, since the subject may run in its own `dir`; removed
    // with the directory on every exit path. When it cannot be created the
    // runs go to `/dev/null` as they would without `profile`.
    let (scratch, unkept) = match profile.then(tempfile::tempdir) {
        Some(Ok(d)) => (Some(d), None),
        Some(Err(e)) => (
            None,
            Some(
                anyhow::Error::new(e)
                    .context("could not create a directory for cachegrind profiles"),
            ),
        ),
        None => (None, None),
    };
    let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
    for run in 0..COUNTER_RUNS {
        // Before each step that runs from the subject's paths, as for a
        // timed sample: the previous run may have changed them.
        if let Some(p) = prepare {
            vet()?;
            prepare_once(p, site)?;
        }
        vet()?;
        let out_file = match &scratch {
            // valgrind expands `%p` and `%q{VAR}` in this path and reads `%%`
            // as a literal one. A temporary directory seldom holds a `%`, but
            // TMPDIR is the user's to set.
            Some(d) => d
                .path()
                .join(format!("run-{run}"))
                .to_string_lossy()
                .replace('%', "%%"),
            None => "/dev/null".to_string(),
        };
        let out_arg = format!("--cachegrind-out-file={out_file}");
        let (status, log) = under_valgrind(
            &[
                "--tool=cachegrind",
                "--cache-sim=no",
                "--branch-sim=no",
                &out_arg,
            ],
            cmd,
            site,
        )?;

        // cachegrind writes its summary to its log as e.g. "I refs:  48,349,132".
        let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
        accepted(bin, status, ok, " under valgrind")?;
        match parse_irefs(&log) {
            // cachegrind that cannot open its output file still exits with
            // the client's code, and reports `I refs: 0` — a count that would
            // record as the largest improvement ever measured. Seen with
            // valgrind 3.24 when the subject removed the directory the profile
            // was going to. Decided on the count, not on the message, which
            // only names the cause: no process retires zero instructions, so
            // zero is never a measurement.
            Some(0) => {
                let unwritable =
                    valgrind_lines(&log).any(|l| l.contains("can't open output data file"));
                if unwritable {
                    bail!(
                        "cachegrind could not write its profile to {out_file}, and counts nothing when that happens"
                    );
                }
                bail!("cachegrind counted no instructions");
            }
            Some(n) => samples.push(n),
            // Valgrind is installed but produced no summary — a real failure,
            // not the same thing as valgrind being absent. Reporting it as
            // absent sends people off installing something they already have.
            None => bail!(
                "valgrind ran but emitted no `I refs` summary: {}",
                last_log_line(&log)
            ),
        }
    }

    let counted = Counted {
        min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
        max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
        runs: COUNTER_RUNS,
    };
    // The first run at the minimum. A hermetic subject's runs are identical,
    // and for one that is not, the minimum is the quiet path the recorded
    // count describes.
    let best = samples
        .iter()
        .position(|n| *n == counted.min)
        .expect("the minimum is one of the samples");
    let kept = match (scratch, unkept) {
        (Some(d), _) => {
            let path = d.path().join(format!("run-{best}"));
            Some(
                std::fs::read(&path)
                    .with_context(|| format!("cachegrind wrote no profile to {}", path.display()))
                    .and_then(|raw| {
                        if raw.is_empty() {
                            bail!("cachegrind wrote an empty profile to {}", path.display());
                        }
                        Ok(raw)
                    }),
            )
        }
        (None, Some(e)) => Some(Err(e)),
        (None, None) => None,
    };
    Ok(Some((counted, kept)))
}

/// Extract the `I refs:` count from cachegrind's summary in its log.
///
/// Only valgrind's own `==PID==` lines are read, and the last summary among
/// them. [`under_valgrind`] keeps the subject's output out of the log
/// altogether; the prefix check is what would still hold if that ever
/// changed, since a subject printing `I refs:` must not supply its own count.
fn parse_irefs(log: &str) -> Option<u64> {
    let line = valgrind_lines(log)
        .filter(|l| l.contains("I refs:"))
        .last()?;
    let digits: String = line
        .rsplit(':')
        .next()?
        .chars()
        .filter(|c| c.is_ascii_digit())
        .collect();
    digits.parse().ok()
}

/// What DHAT reports about one run's heap use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Heap {
    /// Blocks allocated over the whole run, freed or not.
    pub blocks: u64,
    /// Bytes allocated over the whole run, freed or not.
    pub bytes: u64,
    /// Bytes live at the global peak (DHAT's `t-gmax`).
    pub peak_bytes: u64,
}

impl Heap {
    /// As recorded metrics. The `alloc_` prefix keeps them together in the
    /// sorted metrics map and apart from the gated `instructions`.
    pub fn metrics(&self) -> [(&'static str, u64); 3] {
        [
            ("alloc_blocks", self.blocks),
            ("alloc_bytes", self.bytes),
            ("alloc_peak_bytes", self.peak_bytes),
        ]
    }
}

/// Heap allocations from repeated DHAT runs: each metric's floor and ceiling,
/// taken independently, as [`Counted`] does for instructions.
#[derive(Debug, Clone, Copy)]
pub struct Allocated {
    pub min: Heap,
    pub max: Heap,
    pub runs: u32,
}

/// Relative spread of one metric across runs, as a percentage of its
/// minimum. A minimum of zero under a maximum that is not has no percentage,
/// and counts as infinitely spread: something allocated on one run and not on
/// another.
fn spread(lo: u64, hi: u64) -> f64 {
    match (lo, hi) {
        (0, 0) => 0.0,
        (0, _) => f64::INFINITY,
        (lo, hi) => (hi - lo) as f64 / lo as f64 * 100.0,
    }
}

impl Allocated {
    /// The wider spread of the two totals, blocks and bytes.
    pub fn totals_spread_pct(&self) -> f64 {
        spread(self.min.blocks, self.max.blocks).max(spread(self.min.bytes, self.max.bytes))
    }

    /// The spread of the peak.
    pub fn peak_spread_pct(&self) -> f64 {
        spread(self.min.peak_bytes, self.max.peak_bytes)
    }

    /// Whether the totals moved between runs, which says the program's work
    /// did. Same threshold as instructions. The totals of every hermetic
    /// subject measured, threaded ones included, repeated exactly; the one
    /// that moved was `git status` refreshing its index on the first run.
    pub fn is_suspect(&self) -> bool {
        self.totals_spread_pct() > SPREAD_WARN_PCT
    }

    /// Whether the peak moved while the totals did not. That is how a
    /// threaded subject looks: every thread does the same work, but how much
    /// of it is live at once depends on how valgrind interleaves them, which
    /// moved an 8-thread subject's peak by up to 2.5%.
    pub fn peak_is_unsteady(&self) -> bool {
        self.peak_spread_pct() > SPREAD_WARN_PCT
    }

    /// Whether DHAT saw no heap allocation at all. Nearly always blindness
    /// rather than a finding: DHAT counts only calls it can intercept, so a
    /// statically linked binary, or one with its own allocator compiled in
    /// (jemalloc, mimalloc), reports zero however much it allocates.
    pub fn saw_nothing(&self) -> bool {
        self.max.blocks == 0
    }
}

/// Heap allocations via `valgrind --tool=dhat`, repeated [`COUNTER_RUNS`]
/// times, with the subject's prepare step before each run as for
/// [`subject_instructions`].
///
/// Reported, never gated — not yet. In the measurements on the methodology
/// page the totals repeated exactly for every hermetic subject, threaded ones
/// and a 32-way CPU contention run included. The peak did not: valgrind runs
/// one thread at a time and switches by its own schedule, so how much a
/// threaded program has live at once moves with it, in both directions. Its
/// minimum drifted 0.7% under contention, so for the peak the floor is not
/// the one-sided estimator it is for everything else.
///
/// `Ok(None)` when valgrind is unavailable, like [`instructions`].
pub fn subject_allocations(s: &Subject, settings: &Settings) -> Result<Option<Allocated>> {
    subject_allocations_vetted(s, settings, &|| Ok(()))
}

/// [`subject_allocations`], asking `vet` before each DHAT run, after its
/// `prepare`, as [`subject_instructions_vetted`] does before each counted
/// run.
pub fn subject_allocations_vetted(
    s: &Subject,
    settings: &Settings,
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Allocated>> {
    let site = Site {
        dir: s.dir.as_deref(),
        env: &s.env,
        settings,
    };
    allocations(&s.cmd, s.prepare.as_deref(), &site, &s.ok_exit_codes, vet)
}

/// `ok` applies to the subject under valgrind: DHAT, like cachegrind, exits
/// with its client's code.
fn allocations(
    cmd: &[String],
    prepare: Option<&[String]>,
    site: &Site,
    ok: &[i32],
    vet: &dyn Fn() -> Result<()>,
) -> Result<Option<Allocated>> {
    if !valgrind_available() {
        return Ok(None);
    }
    let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
    let mut runs: Vec<Heap> = Vec::with_capacity(COUNTER_RUNS as usize);
    for _ in 0..COUNTER_RUNS {
        // Before each step that runs from the subject's paths, as for a
        // counted cachegrind run: the previous run may have changed them,
        // and the prepare may change them again.
        if let Some(p) = prepare {
            vet()?;
            prepare_once(p, site)?;
        }
        vet()?;
        // The profile DHAT would write is for its viewer, and tak reads only
        // the summary; without this every run leaves a `dhat.out.PID` in the
        // subject's directory.
        let (status, log) =
            under_valgrind(&["--tool=dhat", "--dhat-out-file=/dev/null"], cmd, site)?;
        accepted(bin, status, ok, " under valgrind")?;
        match parse_dhat(&log) {
            Some(h) => runs.push(h),
            None => bail!(
                "valgrind ran but emitted no DHAT summary: {}",
                last_log_line(&log)
            ),
        }
    }
    let fold = |f: fn(u64, u64) -> u64| {
        runs.iter()
            .copied()
            .reduce(|a, b| Heap {
                blocks: f(a.blocks, b.blocks),
                bytes: f(a.bytes, b.bytes),
                peak_bytes: f(a.peak_bytes, b.peak_bytes),
            })
            .expect("COUNTER_RUNS > 0")
    };
    Ok(Some(Allocated {
        min: fold(u64::min),
        max: fold(u64::max),
        runs: COUNTER_RUNS,
    }))
}

/// Extract DHAT's summary from valgrind's log, e.g.
///
/// ```text
/// ==8== Total:     4,140 bytes in 3 blocks
/// ==8== At t-gmax: 4,140 bytes in 3 blocks
/// ```
///
/// Only lines with valgrind's `==PID==` prefix count. The log holds nothing
/// else when it is written by [`under_valgrind`], but the summary's own
/// words are too ordinary — "Total: 5 bytes in 1 blocks" could be any
/// progress line — to match wherever they appear. The format is the one
/// valgrind 3.15 introduced with `--tool=dhat`; before that it was
/// `exp-dhat`, which no longer exists.
fn parse_dhat(log: &str) -> Option<Heap> {
    let field = |name: &str| {
        let rest = valgrind_lines(log).find_map(|l| l.trim_start().strip_prefix(name))?;
        let (bytes, rest) = rest.trim().split_once(" bytes in ")?;
        let blocks = rest.split_whitespace().next()?;
        Some((dhat_number(bytes)?, dhat_number(blocks)?))
    };
    let (bytes, blocks) = field("Total:")?;
    let (peak_bytes, _) = field("At t-gmax:")?;
    Some(Heap {
        blocks,
        bytes,
        peak_bytes,
    })
}

/// A line of valgrind's own output, without its `==PID==` prefix.
fn valgrind_line(line: &str) -> Option<&str> {
    let rest = line.strip_prefix("==")?;
    let (pid, rest) = rest.split_once("==")?;
    (!pid.is_empty() && pid.chars().all(|c| c.is_ascii_digit())).then_some(rest)
}

/// A count as valgrind prints it, with commas every three digits.
fn dhat_number(s: &str) -> Option<u64> {
    let digits: String = s.trim().chars().filter(|&c| c != ',').collect();
    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }
    digits.parse().ok()
}

/// valgrind's own lines in its log, with their `==<pid>==` prefix removed.
fn valgrind_lines(log: &str) -> impl Iterator<Item = &str> {
    log.lines().filter_map(valgrind_line)
}

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

    /// Captured from valgrind 3.22.0 (Ubuntu 24.04) running `git --version`.
    /// 3.24.0 (Debian trixie) prints the same summary lines.
    const DHAT_3_22: &str = "\
==9== DHAT, a dynamic heap analysis tool
==9== Copyright (C) 2010-2018, and GNU GPL'd, by Mozilla Foundation
==9== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==9== Command: git --version
==9==
git version 2.43.0
==9==
==9== Total:     7,119 bytes in 31 blocks
==9== At t-gmax: 6,847 bytes in 25 blocks
==9== At t-end:  2,379 bytes in 15 blocks
==9== Reads:     1,067 bytes
==9== Writes:    1,546 bytes
==9==
==9== To view the resulting profile, open
==9==   file:///usr/libexec/valgrind/dh_view.html
==9== in a web browser, click on \"Load...\", and then select the file
==9==   /dev/null
==9== The text at the bottom explains the abbreviations used in the output.
";

    #[test]
    fn parses_a_dhat_summary() {
        assert_eq!(
            parse_dhat(DHAT_3_22),
            Some(Heap {
                blocks: 31,
                bytes: 7_119,
                peak_bytes: 6_847,
            })
        );
    }

    /// Captured from valgrind 3.24.0 running a threaded Python script: the
    /// separators matter once counts pass a million.
    #[test]
    fn parses_counts_past_a_million() {
        let s = "==21== Total:     2,626,313 bytes in 2,833 blocks\n\
                 ==21== At t-gmax: 1,185,686 bytes in 1,661 blocks\n";
        assert_eq!(
            parse_dhat(s),
            Some(Heap {
                blocks: 2_833,
                bytes: 2_626_313,
                peak_bytes: 1_185_686,
            })
        );
    }

    /// Only valgrind's own lines are read: a line without its `==PID==`
    /// prefix is never the measurement, however much it looks like one.
    #[test]
    fn only_valgrinds_own_lines_are_read() {
        let s = "Total: 5 bytes in 1 blocks\n\
                 ==12== \n\
                 ==12== Total:     8,748 bytes in 17 blocks\n\
                 ==12== At t-gmax: 8,748 bytes in 17 blocks\n";
        assert_eq!(parse_dhat(s).unwrap().blocks, 17);
        assert_eq!(
            parse_dhat("Total: 5 bytes in 1 blocks\nAt t-gmax: 5 bytes in 1 blocks\n"),
            None
        );
        assert_eq!(valgrind_line("==x== Total:"), None);
        assert_eq!(valgrind_line("==== Total:"), None);
    }

    #[test]
    fn a_missing_or_truncated_dhat_summary_is_none() {
        assert_eq!(parse_dhat(""), None);
        // A run that died before the summary's second line.
        assert_eq!(parse_dhat("==3== Total:     1 bytes in 1 blocks\n"), None);
        assert_eq!(
            parse_dhat(
                "==3== Total:     lots bytes in 1 blocks\n==3== At t-gmax: 1 bytes in 1 blocks\n"
            ),
            None
        );
    }

    /// Totals and peak are judged apart: moving totals mean the work
    /// changed, a moving peak alone means threads interleaved differently.
    #[test]
    fn totals_and_peak_spread_are_judged_apart() {
        let h = |blocks, bytes, peak_bytes| Heap {
            blocks,
            bytes,
            peak_bytes,
        };
        let a = |min, max| Allocated { min, max, runs: 3 };
        let steady = a(h(10, 1000, 500), h(10, 1000, 500));
        assert_eq!(steady.totals_spread_pct(), 0.0);
        assert!(!steady.is_suspect() && !steady.peak_is_unsteady());

        let threaded = a(h(10, 1000, 500), h(10, 1000, 510));
        assert!((threaded.peak_spread_pct() - 2.0).abs() < 1e-9);
        assert!(threaded.peak_is_unsteady() && !threaded.is_suspect());

        // The first run refreshed a cache: 1140 blocks, then 496.
        let first_run = a(h(496, 2_077_237, 1_790_738), h(1140, 2_227_102, 1_888_914));
        assert!(first_run.is_suspect());
        assert!((first_run.totals_spread_pct() - 129.84).abs() < 0.01);

        // Nothing on one run and something on another has no percentage.
        assert!(a(h(0, 0, 0), h(1, 8, 8)).totals_spread_pct().is_infinite());
        assert!(a(h(0, 0, 0), h(0, 0, 0)).saw_nothing());
        assert!(!steady.saw_nothing());
    }

    /// The subject's stderr is interleaved with valgrind's; only valgrind's
    /// prefixed lines are its summary.
    #[test]
    fn a_count_printed_by_the_subject_is_not_the_count() {
        let s = "I refs: 5\n==7== error: can't open output data file\n==7== I refs:      1,234\nI refs: 9\n";
        assert_eq!(parse_irefs(s), Some(1_234));
        assert_eq!(parse_irefs("I refs: 5\n"), None);
        assert_eq!(
            valgrind_lines("==x== no\n== 1== no\n==12== yes\n").collect::<Vec<_>>(),
            [" yes"]
        );
    }

    #[test]
    fn parses_cachegrind_summary() {
        let s = "==12== I refs:      48,349,132\n";
        assert_eq!(parse_irefs(s), Some(48_349_132));
    }

    #[test]
    fn missing_summary_is_none_not_panic() {
        assert_eq!(parse_irefs("valgrind: command not found"), None);
    }

    /// What `subject` removes, as configured.
    fn removals(settings: &Settings) -> Vec<String> {
        subject("true", settings)
            .get_envs()
            .filter(|(_, v)| v.is_none())
            .map(|(k, _)| k.to_string_lossy().into_owned())
            .collect()
    }

    /// Construction-level check. The end-to-end proof that a subject cannot see
    /// the token lives in `tests/subject_env.rs`, which runs the real binary.
    #[test]
    fn subject_commands_remove_the_default_denied_variables() {
        let removed = removals(&Settings::default());
        for key in Settings::default().scrubbed_env() {
            assert!(removed.contains(&key.to_string()), "{key} not removed");
        }
    }

    /// The removal follows the setting rather than a compiled-in list, which is
    /// the whole point of routing it through `Settings`.
    #[test]
    fn the_removal_follows_the_settings() {
        let removed = removals(&Settings {
            env_deny: vec!["CUSTOM_SECRET".into()],
            env_allow: Vec::new(),
            ..Settings::default()
        });
        assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
    }

    /// An allowed variable is not removed, so a subject that genuinely needs
    /// one can still be measured.
    #[test]
    fn an_allowed_variable_survives() {
        let removed = removals(&Settings {
            env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
            env_allow: vec!["GITHUB_TOKEN".into()],
            ..Settings::default()
        });
        assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
        assert!(removed.contains(&"GH_TOKEN".to_string()));
    }

    #[test]
    fn zero_runs_is_rejected_not_a_panic() {
        let plan = Plan {
            cmd: vec!["true".into()],
            warmup: 0,
            runs: 0,
            dir: None,
            settings: Settings::default(),
        };
        assert!(wall(&plan).is_err());
    }

    #[test]
    fn a_failed_subject_is_not_recorded_as_a_fast_run() {
        #[cfg(unix)]
        let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
        #[cfg(windows)]
        let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];

        let err = wall(&Plan {
            cmd,
            warmup: 0,
            runs: 1,
            dir: None,
            settings: Settings::default(),
        })
        .unwrap_err();

        assert!(format!("{err:#}").contains("exited with"), "{err:#}");
    }

    #[test]
    fn wall_reports_min_le_p50_le_max() {
        let plan = Plan {
            cmd: vec!["true".into()],
            warmup: 1,
            runs: 5,
            dir: None,
            settings: Settings::default(),
        };
        let m = wall(&plan).unwrap();
        assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
        assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
        assert_eq!(m["wall_n"], 5.0);
    }

    /// Every subject gets exactly its warmups and runs, warmups first.
    #[test]
    fn the_schedule_gives_each_subject_its_counts() {
        let counts = [(2, 10), (1, 5), (0, 3)];
        let order = schedule(&counts, 7);
        for (i, &(warmup, runs)) in counts.iter().enumerate() {
            let of = |timed| {
                order
                    .iter()
                    .filter(|s| s.subject == i && s.timed == timed)
                    .count()
            };
            assert_eq!(of(false), warmup as usize, "subject {i} warmups");
            assert_eq!(of(true), runs as usize, "subject {i} runs");
        }
        let first_timed = order.iter().position(|s| s.timed).unwrap();
        assert!(order[first_timed..].iter().all(|s| s.timed));
    }

    #[test]
    fn the_same_seed_gives_the_same_order() {
        let counts = [(1, 8), (1, 8), (1, 8)];
        assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
        assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
    }

    /// Interleaving is the point: with equal counts, every round holds each
    /// subject once, and the order is not the same in every round.
    #[test]
    fn each_round_runs_every_subject_once_in_a_varying_order() {
        let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
        let rounds: Vec<Vec<usize>> = order
            .chunks(3)
            .map(|r| r.iter().map(|s| s.subject).collect())
            .collect();
        assert_eq!(rounds.len(), 20);
        for r in &rounds {
            let mut sorted = r.clone();
            sorted.sort();
            assert_eq!(sorted, [0, 1, 2], "round {r:?}");
        }
        assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
    }

    /// A subject with half the runs takes part in alternate rounds, not only
    /// the first half — otherwise drift late in the run lands on the others.
    #[test]
    fn a_subject_with_fewer_runs_is_spread_across_the_run() {
        let order = schedule(&[(0, 10), (0, 5)], 3);
        let fewer: Vec<usize> = order
            .iter()
            .enumerate()
            .filter(|(_, s)| s.subject == 1)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(fewer.len(), 5);
        assert!(
            *fewer.last().unwrap() >= order.len() - 3,
            "last sample of the smaller subject is near the end: {fewer:?} of {}",
            order.len()
        );
    }

    #[test]
    fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
        assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
        assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
        assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
    }

    #[test]
    fn stats_report_the_sample_standard_deviation() {
        let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
        assert_eq!(m["wall_min_ms"], 2.0);
        assert_eq!(m["wall_max_ms"], 9.0);
        assert_eq!(m["wall_mean_ms"], 5.0);
        // sqrt(32 / 7)
        assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
        assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
    }

    /// A failing subject is dropped; the others still get every sample.
    #[cfg(unix)]
    #[test]
    fn a_failing_subject_does_not_stop_the_others() {
        let mk = |name: &str, cmd: &[&str]| Subject {
            name: name.into(),
            cmd: cmd.iter().map(|s| s.to_string()).collect(),
            prepare: None,
            setup: None,
            setup_dir: None,
            check: None,
            dir: None,
            version_cmd: None,
            env: BTreeMap::new(),
            vars: BTreeMap::new(),
            when: None,
            runs: Runs::Fixed(4),
            auto: AutoRuns {
                budget: Duration::from_secs(30),
                min: 5,
                max: 50,
            },
            warmup: 1,
            counters: false,
            allocations: false,
            ok_exit_codes: vec![0],
            metrics: BTreeMap::new(),
        };
        let res = interleaved(
            &[mk("ok", &["true"]), mk("bad", &["false"])],
            5,
            &Settings::default(),
            &mut Quiet,
        );
        assert_eq!(res[0].as_ref().unwrap().times.len(), 4);
        assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
    }

    /// One number and nothing else; anything a script might print around it
    /// is refused rather than picked apart.
    #[test]
    fn a_metric_value_is_exactly_one_non_negative_number() {
        for (text, want) in [
            ("1234", 1234.0),
            ("1234\n", 1234.0),
            ("  \t12.5\r\n", 12.5),
            ("0", 0.0),
            ("1.5e3", 1500.0),
            ("2E-2", 0.02),
            ("007", 7.0),
        ] {
            assert_eq!(parse_metric_value(text).unwrap(), want, "{text:?}");
        }
        for bad in [
            "", "\n", "-1", "+1", ".5", "5.", "1e", "1e+", "nan", "inf", "0x10", "1,234", "12 kB",
            "1 2", "1\n2", "size: 3", "1e999",
        ] {
            assert!(parse_metric_value(bad).is_err(), "accepted {bad:?}");
        }
    }

    fn with_metrics(dir: &Path, env: &[(&str, &str)]) -> Subject {
        Subject {
            name: "s".into(),
            cmd: vec!["true".into()],
            prepare: None,
            setup: None,
            setup_dir: None,
            check: None,
            dir: Some(dir.to_path_buf()),
            version_cmd: None,
            env: env
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            vars: BTreeMap::new(),
            when: None,
            runs: Runs::Fixed(1),
            auto: AutoRuns {
                budget: Duration::from_secs(30),
                min: 5,
                max: 50,
            },
            warmup: 0,
            counters: false,
            allocations: false,
            ok_exit_codes: vec![0],
            metrics: BTreeMap::new(),
        }
    }

    /// A file's size is its length in bytes; a directory has none worth
    /// recording, and a missing file is an error that names it.
    #[test]
    fn a_file_metric_is_its_size_in_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("bin");
        std::fs::write(&file, vec![0u8; 4321]).unwrap();
        let s = with_metrics(dir.path(), &[]);
        let settings = Settings::default();
        assert_eq!(
            custom_metric(&MetricSource::File(file), &s, &settings).unwrap(),
            4321.0
        );
        let err = custom_metric(&MetricSource::File(dir.path().into()), &s, &settings).unwrap_err();
        assert!(format!("{err:#}").contains("not a regular file"), "{err:#}");
        let missing = dir.path().join("missing");
        let err = custom_metric(&MetricSource::File(missing), &s, &settings).unwrap_err();
        assert!(format!("{err:#}").contains("missing"), "{err:#}");
    }

    /// A metric command runs where the subject does, with its env, and must
    /// exit 0 and print one number. The scrub is checked end to end in
    /// `tests/subjects.rs`, which can set a token for tak without touching
    /// this test binary's environment.
    #[cfg(unix)]
    #[test]
    fn a_cmd_metric_runs_in_the_subjects_dir_and_env() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("here"), "").unwrap();
        let s = with_metrics(dir.path(), &[("N", "42")]);
        let settings = Settings::default();
        let sh = |script: &str| {
            custom_metric(
                &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
                &s,
                &settings,
            )
        };
        assert_eq!(sh("test -e here && echo $N").unwrap(), 42.0);
        let err = format!("{:#}", sh("echo 5; echo broke >&2; exit 3").unwrap_err());
        assert!(
            err.contains("exit status: 3") && err.contains("broke"),
            "{err}"
        );
        let err = format!("{:#}", sh("echo 'bundle: 12 kB'").unwrap_err());
        assert!(err.contains("not one number"), "{err}");
        let err = format!("{:#}", sh("yes 1 | head -c 4096").unwrap_err());
        assert!(err.contains("more than 1024 bytes"), "{err}");
        // Exactly at the cap is still judged as output, not as too much.
        let err = format!("{:#}", sh("yes 1 | head -c 1024").unwrap_err());
        assert!(err.contains("not one number"), "{err}");
        // A command that never stops printing is stopped at the cap, not
        // left to fill memory or a disk; `exec` so it is the command itself.
        let start = Instant::now();
        let err = format!("{:#}", sh("exec yes 1").unwrap_err());
        assert!(err.contains("so they were stopped"), "{err}");
        assert!(start.elapsed() < Duration::from_secs(4));
        // The error at the end of a long log is the one reported, not a line
        // from its start.
        let err = format!(
            "{:#}",
            sh("yes 'noise line' | head -c 20000 >&2; echo 'the real error' >&2; exit 2")
                .unwrap_err()
        );
        assert!(err.ends_with("the real error"), "{err}");
        assert!(!err.contains("noise"), "{err}");
    }

    /// A metric command that exits while something it started still holds
    /// its stdout has not finished its answer: that is an error rather than
    /// whatever number arrived first, it does not hold up the run, and the
    /// leftover is stopped rather than left running into the next samples.
    #[cfg(unix)]
    #[test]
    fn a_metric_cmd_leaving_stdout_open_fails_and_is_stopped() {
        let err = leftover_metric("sleep 30 & echo $! > pid; echo 7");
        assert!(err.contains("stdout open"), "{err}");
    }

    /// A background writer that goes past the cap only after the command has
    /// exited — too late for `capture` to stop the command itself — is still
    /// stopped, and the error says what happened.
    #[cfg(unix)]
    #[test]
    fn a_leftover_that_floods_stdout_after_exit_is_stopped() {
        let err = leftover_metric("(sleep 0.1; exec yes 1) & echo $! > pid; echo 7");
        assert!(
            err.contains("more than 1024 bytes") && err.contains("what it started"),
            "{err}"
        );
    }

    /// Runs `script` as a metric command whose background process writes its
    /// pid to `pid`, and checks that the metric fails promptly and the
    /// background process does not outlive it. Returns the error.
    #[cfg(unix)]
    fn leftover_metric(script: &str) -> String {
        let dir = tempfile::tempdir().unwrap();
        let s = with_metrics(dir.path(), &[]);
        let start = Instant::now();
        let err = custom_metric(
            &MetricSource::Cmd(vec!["sh".into(), "-c".into(), script.into()]),
            &s,
            &Settings::default(),
        )
        .unwrap_err();
        assert!(start.elapsed() < Duration::from_secs(4));
        let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
        let pid = pid.trim();
        // SIGKILL is delivered asynchronously; give it a moment to land.
        // `running`, not `kill -0`: the orphan may linger as a zombie.
        let until = Instant::now() + Duration::from_secs(2);
        while running(pid) && Instant::now() < until {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(
            !running(pid),
            "the background process {pid} was left running"
        );
        format!("{err:#}")
    }

    /// Runs `sh -c script` as a `version_cmd` with the given deadline.
    #[cfg(unix)]
    fn version_sh(script: &str, env: &[(&str, &str)], timeout: Duration) -> Result<String> {
        let settings = Settings::default();
        let env: BTreeMap<String, String> = env
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let site = Site {
            dir: None,
            env: &env,
            settings: &settings,
        };
        version_once(&["sh".into(), "-c".into(), script.into()], &site, timeout)
    }

    /// The first non-empty line, from stdout or else stderr; a failure is an
    /// error naming the command, which the caller turns into a warning.
    #[cfg(unix)]
    #[test]
    fn a_version_is_the_first_line_printed() {
        let sh = |script: &str| version_sh(script, &[("V", "9.9")], VERSION_TIMEOUT);
        assert_eq!(
            sh("printf '\\n  tool %s  \\nbuilt today\\n' \"$V\"").unwrap(),
            "tool 9.9",
            "first non-empty line, trimmed, in the subject's env"
        );
        assert_eq!(sh("echo 'java 21' >&2").unwrap(), "java 21");
        let err = format!("{:#}", sh("echo nope >&2; exit 2").unwrap_err());
        assert!(err.contains("`sh`") && err.contains("nope"), "{err}");
        assert!(sh("true").is_err(), "no output is no version");
    }

    /// Output past the cap is read and dropped, so a command that prints a
    /// lot still finishes, and its first line is what counts.
    #[cfg(unix)]
    #[test]
    fn a_version_is_read_from_a_capped_prefix() {
        let sh = |script: &str| version_sh(script, &[], VERSION_TIMEOUT);
        assert_eq!(sh("yes 'tool 1.0' | head -c 10000000").unwrap(), "tool 1.0");
        assert_eq!(
            sh("yes 'java 21' | head -c 10000000 >&2").unwrap(),
            "java 21",
            "a flood on stderr"
        );
        let kept = Mutex::new(Vec::new());
        let mut src = std::io::Cursor::new(vec![7u8; 100]);
        let overflow = std::sync::atomic::AtomicBool::new(false);
        keep_prefix(&mut src, 10, &kept, &overflow, None);
        assert_eq!(kept.lock().unwrap().len(), 10, "only the cap is kept");
        assert_eq!(
            src.position(),
            100,
            "the rest is read, not left in the pipe"
        );
        assert!(overflow.into_inner(), "and going past the cap is noticed");

        let (kept, overflow) = (
            Mutex::new(Vec::new()),
            std::sync::atomic::AtomicBool::new(false),
        );
        keep_prefix(
            std::io::Cursor::new(vec![7u8; 10]),
            10,
            &kept,
            &overflow,
            None,
        );
        assert!(!overflow.into_inner(), "exactly the cap is not past it");
    }

    /// A failing command that prints a lot — a usage dump after an unknown
    /// flag — is a failure, not a version, however long its output.
    #[cfg(unix)]
    #[test]
    fn a_failing_version_cmd_is_an_error_even_past_the_cap() {
        let err = version_sh(
            "yes 'usage: tool [flags]' | head -c 100000; echo 'unknown flag' >&2; exit 1",
            &[],
            VERSION_TIMEOUT,
        )
        .unwrap_err();
        let err = format!("{err:#}");
        assert!(
            err.contains("exited with") && err.contains("unknown flag"),
            "{err}"
        );
    }

    /// One that never finishes, even one that only floods stderr, is stopped
    /// at the deadline and says so.
    #[cfg(unix)]
    #[test]
    fn a_version_cmd_that_never_finishes_is_stopped() {
        let t = Duration::from_millis(300);
        let began = Instant::now();
        // `exec`, so the process stopped at the deadline is the flood itself.
        for script in ["exec yes 'tool 2.0' >&2", "exec sleep 30"] {
            let err = format!("{:#}", version_sh(script, &[], t).unwrap_err());
            assert!(err.contains("did not finish"), "{script}: {err}");
        }
        assert!(
            began.elapsed() < Duration::from_secs(5),
            "{:?}",
            began.elapsed()
        );
    }

    /// A timeout stops what the command started too, not just the command:
    /// a helper left running would compete with the samples that follow.
    #[cfg(unix)]
    #[test]
    fn a_timeout_stops_the_whole_process_group() {
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("pid");
        let script = format!("sleep 30 & echo $! > '{}'; wait", pidfile.display());
        let err = version_sh(&script, &[], Duration::from_millis(300)).unwrap_err();
        assert!(format!("{err:#}").contains("did not finish"), "{err:#}");
        let pid = std::fs::read_to_string(&pidfile).unwrap();
        let pid = pid.trim();
        let until = Instant::now() + Duration::from_secs(2);
        while running(pid) && Instant::now() < until {
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(
            !running(pid),
            "the background sleep {pid} outlived the timeout"
        );
    }

    /// Whether `pid` is still running. A zombie is not: once the shell that
    /// started the process is killed with it, only PID 1 can reap it, and in
    /// a container whose PID 1 does not reap orphans it stays a zombie —
    /// which `kill -0` still reports as present.
    #[cfg(unix)]
    fn running(pid: &str) -> bool {
        #[cfg(target_os = "linux")]
        {
            // The state follows the `)` closing the command name, which may
            // itself contain spaces or parentheses, so look for the last one.
            let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
                return false;
            };
            let state = stat
                .rfind(')')
                .and_then(|i| stat[i + 1..].trim_start().chars().next());
            !matches!(state, None | Some('Z' | 'X' | 'x'))
        }
        #[cfg(not(target_os = "linux"))]
        {
            let Ok(out) = Command::new("ps")
                .args(["-o", "stat=", "-p", pid])
                .stderr(Stdio::null())
                .output()
            else {
                return false;
            };
            let stat = String::from_utf8_lossy(&out.stdout);
            let stat = stat.trim();
            out.status.success() && !stat.is_empty() && !stat.starts_with('Z')
        }
    }

    /// A background process that inherits the pipes keeps them open after
    /// the command exits; the version it printed still comes back promptly.
    #[cfg(unix)]
    #[test]
    fn a_background_process_holding_the_pipe_does_not_hold_up_the_version() {
        let began = Instant::now();
        let v = version_sh("sleep 5 & echo 'tool 3.0'", &[], VERSION_TIMEOUT).unwrap();
        assert_eq!(v, "tool 3.0");
        assert!(
            began.elapsed() < Duration::from_secs(3),
            "{:?}",
            began.elapsed()
        );
    }

    /// A prepare step that fails stops its subject, and says it was prepare.
    #[cfg(unix)]
    #[test]
    fn a_failing_prepare_is_reported_as_prepare() {
        let res = interleaved(
            &[Subject {
                name: "x".into(),
                cmd: vec!["true".into()],
                prepare: Some(vec![
                    "/bin/sh".into(),
                    "-c".into(),
                    "echo nope >&2; exit 3".into(),
                ]),
                setup: None,
                setup_dir: None,
                check: None,
                dir: None,
                version_cmd: None,
                env: BTreeMap::new(),
                vars: BTreeMap::new(),
                when: None,
                runs: Runs::Fixed(1),
                auto: AutoRuns {
                    budget: Duration::from_secs(30),
                    min: 5,
                    max: 50,
                },
                warmup: 0,
                counters: false,
                allocations: false,
                ok_exit_codes: vec![0],
                metrics: BTreeMap::new(),
            }],
            0,
            &Settings::default(),
            &mut Quiet,
        );
        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
        assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
    }

    /// A subject whose command bumps a counter file and whose check fails on
    /// every even-numbered run, warmups included in the count.
    #[cfg(unix)]
    fn alternating(dir: &Path, warmup: u32, runs: u32) -> Subject {
        Subject {
            name: "alt".into(),
            cmd: vec![
                "/bin/sh".into(),
                "-c".into(),
                "echo x >> n".into(),
            ],
            prepare: None,
            setup: None,
            setup_dir: None,
            check: Some(vec![
                "/bin/sh".into(),
                "-c".into(),
                // Arithmetic strips the padding macOS `wc -l` puts before the count.
                "echo check >> checked; runs=$(( $(wc -l < n) )); test $(( runs % 2 )) = 1 || { echo \"run $runs is even\" >&2; exit 1; }".into(),
            ]),
            version_cmd: None,
            dir: Some(dir.to_path_buf()),
            env: BTreeMap::new(),
            vars: BTreeMap::new(),
            when: None,
            runs: Runs::Fixed(runs),
            auto: AutoRuns {
                budget: Duration::from_secs(30),
                min: 5,
                max: 50,
            },
            warmup,
            counters: false,
            allocations: false,
            ok_exit_codes: vec![0],
            metrics: BTreeMap::new(),
        }
    }

    /// A failing check marks its sample and the subject keeps every one;
    /// warmups are never checked.
    #[cfg(unix)]
    #[test]
    fn a_failing_check_marks_the_sample_without_dropping_the_subject() {
        let dir = tempfile::tempdir().unwrap();
        let res = interleaved(
            &[alternating(dir.path(), 1, 6)],
            0,
            &Settings::default(),
            &mut Quiet,
        );
        let s = res[0].as_ref().unwrap();
        assert_eq!(s.times.len(), 6);
        // Run 1 is the warmup; timed runs 2..=7 fail on the even ones.
        assert_eq!(s.checks, [false, true, false, true, false, true]);
        assert_eq!(s.passed(), 3);
        assert!(
            s.first_failure
                .as_deref()
                .unwrap()
                .contains("run 2 is even"),
            "{s:?}"
        );
        let checked = std::fs::read_to_string(dir.path().join("checked")).unwrap();
        assert_eq!(checked.lines().count(), 6, "no check after the warmup");
    }

    /// `ok_exit_codes` belong to the command, not its check: a command that
    /// exits 1 under `[0, 1]` is kept with its code, and a check that exits 1
    /// is still a failed check.
    #[cfg(unix)]
    #[test]
    fn ok_exit_codes_do_not_pass_a_check_that_exits_1() {
        let dir = tempfile::tempdir().unwrap();
        let mut s = alternating(dir.path(), 0, 2);
        s.cmd = vec!["/bin/sh".into(), "-c".into(), "exit 1".into()];
        s.check = Some(vec!["/bin/sh".into(), "-c".into(), "exit 1".into()]);
        s.ok_exit_codes = vec![0, 1];
        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
        let s = res[0].as_ref().unwrap();
        assert_eq!(s.exit_codes, [1, 1]);
        assert_eq!(s.checks, [false, false]);
        assert_eq!(s.passed(), 0);
    }

    /// A check that cannot be started is a configuration mistake, not six
    /// failed samples.
    #[cfg(unix)]
    #[test]
    fn a_check_that_cannot_start_drops_the_subject() {
        let dir = tempfile::tempdir().unwrap();
        let mut s = alternating(dir.path(), 0, 2);
        s.check = Some(vec!["/nonexistent/tak-check".into()]);
        let res = interleaved(&[s], 0, &Settings::default(), &mut Quiet);
        let msg = format!("{:#}", res[0].as_ref().unwrap_err());
        assert!(msg.contains("failed to spawn check"), "{msg}");
    }

    /// A passing step that leaves a process writing to stderr returns at
    /// once, and that process is left alone: a fixture server started by
    /// `setup` must survive logging after the step is done, so its later
    /// write to stderr must succeed rather than die of SIGPIPE (exit 141).
    #[cfg(unix)]
    #[test]
    fn a_process_left_by_a_passing_step_can_still_write_to_stderr() {
        let dir = tempfile::tempdir().unwrap();
        let env = BTreeMap::new();
        let settings = Settings::default();
        let site = Site {
            dir: Some(dir.path()),
            env: &env,
            settings: &settings,
        };
        const N: usize = 10;
        let start = Instant::now();
        for i in 0..N {
            let script = format!(
                "{{ sh -c 'sleep 1; echo late >&2'; echo $? > s{i}.tmp && mv s{i}.tmp s{i}; }} & exit 0"
            );
            let step = ["/bin/sh".to_string(), "-c".into(), script];
            assert_eq!(untimed("setup", &step, &site).unwrap(), None);
        }
        let took = start.elapsed();
        assert!(took < Duration::from_secs(2), "{N} passes took {took:?}");

        let deadline = Instant::now() + Duration::from_secs(20);
        let statuses: Vec<String> = (0..N)
            .map(|i| {
                loop {
                    if let Ok(s) = std::fs::read_to_string(dir.path().join(format!("s{i}"))) {
                        break s.trim().to_string();
                    }
                    assert!(Instant::now() < deadline, "leftover {i} never finished");
                    std::thread::sleep(Duration::from_millis(50));
                }
            })
            .collect();
        assert!(statuses.iter().all(|s| s == "0"), "{statuses:?}");
    }

    /// An observer that records what it was told.
    #[derive(Default)]
    struct Log {
        plans: Vec<Vec<u64>>,
        finished: Vec<usize>,
        /// Every event in order, as `setup:N`, `start:N` and `drop:N`.
        events: Vec<String>,
    }
    impl Observer for Log {
        fn planned(&mut self, remaining: &[u64]) {
            self.plans.push(remaining.to_vec());
        }
        fn setting_up(&mut self, subject: usize) {
            self.events.push(format!("setup:{subject}"));
        }
        fn started(&mut self, subject: usize) {
            self.events.push(format!("start:{subject}"));
        }
        fn dropped(&mut self, subject: usize) {
            self.events.push(format!("drop:{subject}"));
        }
        fn finished(&mut self, subject: usize, _: Duration) {
            self.finished.push(subject);
        }
    }

    /// Every setup runs once, before any sample; a failing one drops its
    /// subject before it takes a sample, and says it was setup.
    #[cfg(unix)]
    #[test]
    fn setups_run_once_first_and_a_failing_one_drops_its_subject() {
        let sh = |script: &str| Some(["/bin/sh", "-c", script].map(String::from).to_vec());
        let mk = |name: &str, setup: Option<Vec<String>>| Subject {
            name: name.into(),
            cmd: vec!["true".into()],
            prepare: None,
            setup,
            setup_dir: None,
            check: None,
            version_cmd: None,
            dir: None,
            env: BTreeMap::new(),
            vars: BTreeMap::new(),
            when: None,
            runs: Runs::Auto,
            auto: AutoRuns {
                budget: Duration::from_secs(30),
                min: 2,
                max: 2,
            },
            warmup: 1,
            counters: false,
            allocations: false,
            ok_exit_codes: vec![0],
            metrics: BTreeMap::new(),
        };
        let mut log = Log::default();
        let res = interleaved(
            &[
                mk("ok", sh("true")),
                mk("bad", sh("echo no fixture >&2; exit 2")),
                mk("none", None),
            ],
            3,
            &Settings::default(),
            &mut log,
        );
        assert_eq!(log.events[..3], ["setup:0", "setup:1", "drop:1"]);
        assert!(!log.events[3..].iter().any(|e| e.starts_with("setup:")));
        assert!(!log.events.contains(&"start:1".to_string()));
        assert_eq!(res[0].as_ref().unwrap().times.len(), 2);
        assert_eq!(res[2].as_ref().unwrap().times.len(), 2);
        let msg = format!("{:#}", res[1].as_ref().unwrap_err());
        assert!(msg.contains("setup") && msg.contains("no fixture"), "{msg}");
        // Setup is not a sample: only warmups and runs finish.
        assert_eq!(log.finished.len(), 2 * (1 + 2));
    }

    /// `runs = "auto"` sizes each subject from its own speed: a subject too
    /// slow for the budget gets the floor, a faster one gets more. Uses real
    /// sleeps, so the fast count is only bounded, not exact. The fast subject
    /// needs a sample under budget/3 to beat the floor, so the margin is 20x:
    /// at 6.5x a loaded macOS runner pushed it to the floor of 2 and failed CI.
    #[cfg(unix)]
    #[test]
    fn auto_runs_give_a_slow_subject_the_floor_and_a_fast_one_more() {
        let mk = |name: &str, secs: &str, warmup: u32| Subject {
            name: name.into(),
            cmd: vec!["sleep".into(), secs.into()],
            prepare: None,
            setup: None,
            setup_dir: None,
            check: None,
            dir: None,
            version_cmd: None,
            env: BTreeMap::new(),
            vars: BTreeMap::new(),
            when: None,
            runs: Runs::Auto,
            auto: AutoRuns {
                budget: Duration::from_millis(600),
                min: 2,
                max: 6,
            },
            warmup,
            counters: false,
            allocations: false,
            ok_exit_codes: vec![0],
            metrics: BTreeMap::new(),
        };
        let mut log = Log::default();
        // The slow one has no warmup, so its first kept sample sizes it.
        let res = interleaved(
            &[mk("fast", "0.01", 1), mk("slow", "0.5", 0)],
            9,
            &Settings::default(),
            &mut log,
        );
        let fast = res[0].as_ref().unwrap().times.len();
        let slow = res[1].as_ref().unwrap().times.len();
        assert_eq!(slow, 2, "0.6s budget / 0.5s sample is below the floor");
        assert!(fast > slow && fast <= 6, "fast got {fast}");
        // Planned on the floors first, then on the settled counts.
        assert_eq!(log.plans[0], [1 + 2, 2]);
        assert_eq!(log.plans.len(), 2);
        assert_eq!(log.finished.len(), 1 + fast + slow);
    }

    #[test]
    fn steady_samples_raise_no_warning() {
        assert!(warnings(&[10.0, 10.2, 9.9, 10.1, 10.0, 10.3]).is_empty());
        assert!(warnings(&[10.0, 50.0]).is_empty(), "too few to judge");
    }

    #[test]
    fn a_spike_is_an_outlier() {
        let w = warnings(&[10.0, 10.2, 9.9, 10.1, 40.0, 10.0, 10.1]);
        assert_eq!(w.len(), 1, "{w:?}");
        assert!(
            w[0].starts_with("1 of 7 samples are slow outliers"),
            "{w:?}"
        );
    }

    #[test]
    fn a_slow_first_sample_is_called_out() {
        let w = warnings(&[35.0, 10.0, 10.2, 9.9, 10.1, 10.0]);
        assert!(
            w.iter().any(|m| m.contains("first sample took 3.5x")),
            "{w:?}"
        );
    }

    /// With most samples identical the median deviation is zero; a spike
    /// must still be reported.
    #[test]
    fn a_spike_among_identical_samples_is_still_an_outlier() {
        let w = warnings(&[10.0, 10.0, 10.0, 100.0, 10.0]);
        assert!(w.iter().any(|m| m.contains("slow outliers")), "{w:?}");
        assert!(
            warnings(&[10.0; 6]).is_empty(),
            "identical samples are fine"
        );
    }

    /// A fast outlier is the minimum, so it is reported as such rather than
    /// reassured away.
    #[test]
    fn a_fast_outlier_is_flagged_as_possibly_the_minimum() {
        let w = warnings(&[100.0, 101.0, 99.0, 102.0, 10.0, 100.0]);
        assert!(
            w.iter()
                .any(|m| m.contains("fast outliers") && m.contains("minimum")),
            "{w:?}"
        );
    }

    /// Several identical spikes over a flat majority are all caught, not
    /// hidden by a spread they themselves inflate.
    #[test]
    fn several_spikes_over_a_flat_majority_are_caught() {
        let w = warnings(&[10.0, 10.0, 10.0, 10.0, 40.0, 45.0]);
        assert!(
            w.iter()
                .any(|m| m.starts_with("2 of 6 samples are slow outliers")),
            "{w:?}"
        );
        assert!(
            warnings(&[10.0, 10.0, 10.0, 11.0, 10.0]).is_empty(),
            "10% is not a spike"
        );
    }
}