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
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
//! tak — benchmark command-line programs and track their performance over time.
//!
//! Pre-v1: interfaces and behavior are not finalized and may change between releases.

use anyhow::{Context, Result, bail};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use usage_rs::{Args, Cli, Subcommands};

use tak_cli::accept::{self, Acceptances};
use tak_cli::backfill;
use tak_cli::baseline::{self, Baseline, Store};
use tak_cli::compare;
use tak_cli::config::{
    self, AutoRuns, Config, DEFAULT_BUDGET, DEFAULT_MAX_RUNS, DEFAULT_MIN_RUNS, DEFAULT_RUNS,
    DEFAULT_WARMUP, Runs, SELF_TOOL, Subject,
};
use tak_cli::detect;
use tak_cli::export::{self, ExportResult};
use tak_cli::measure::{self, Plan};
use tak_cli::notes;
use tak_cli::record::{self, Record, SCHEMA_VERSION};
use tak_cli::settings::{CliLayer, EnvLayer, Settings, TakConfigLayer, config_source};

#[derive(Cli)]
#[usage(completion = true)]
#[usage(
    name = "tak",
    bin = "tak",
    version,
    about = "CLI performance, tracked",
    unknown_flags = "error",
    config = tak_cli::settings::Settings
)]
struct Cli {
    #[usage(subcommand)]
    cmd: Cmd,

    // Global so a setting is spelled the same wherever it applies, rather than
    // being repeated per subcommand and drifting. `setting = "..."` is the
    // executable binding: what these flags are given lands in the settings
    // layer the parser hands back, and a test holds the bindings against the
    // registry so neither can drift from the other.
    /// Remove a variable from the environment of measured commands. Repeatable.
    /// Replaces the default list rather than adding to it.
    #[usage(long, global, value_name = "VAR", setting = "env_deny")]
    env_deny: Vec<String>,
    /// Keep a variable that --env-deny would remove. Repeatable.
    #[usage(long, global, value_name = "VAR", setting = "env_allow")]
    env_allow: Vec<String>,
    /// Percentage an instruction count may rise before `compare` fails.
    #[usage(long, global, value_name = "PCT", setting = "gate_pct")]
    gate_pct: Option<f64>,
    /// Instructions a count may rise by before `compare` fails, whatever the percentage.
    #[usage(long, global, value_name = "N", setting = "gate_min_delta")]
    gate_min_delta: Option<u64>,
    /// Pass, with a warning, when nothing was compared, instead of failing. For
    /// `compare`, `detect` and `run --baseline --gate`. A regression still fails.
    // A plain `bool`: given, it contributes `true`; left off, nothing, so
    // `[gate] allow_empty` and `TAK_ALLOW_EMPTY` still apply. It was a flag on
    // `compare` and `detect` before it was a setting, and is global now for the
    // reason above — one spelling wherever the setting applies.
    #[usage(long, global, setting = "allow_empty")]
    allow_empty: bool,
    /// Leave the line naming tak off the end of generated reports.
    // `SetFalse`: the long spelling is the negation of the setting, so `--no-credit`
    // contributes `false` to the settings layer and its absence contributes nothing.
    #[usage(long = "no-credit", action = usage_rs::ArgAction::SetFalse, global = true)]
    #[usage(default = "true", setting = "credit")]
    credit: bool,
    /// Machine class to record under. Overrides the derived name.
    #[usage(long, global, value_name = "CLASS", setting = "runner_class")]
    runner: Option<String>,
}

#[derive(Subcommands)]
enum Cmd {
    /// Generate a self-contained shell completion script
    Completion {
        /// Shell to generate completions for
        #[usage(
            arg,
            choices("bash", "elvish", "zsh", "fish", "nu", "nushell", "powershell", "pwsh")
        )]
        shell: String,
    },
    /// Benchmark a command, or everything declared in tak.toml.
    Run {
        /// Name to record this measurement under. With no command, selects a
        /// single benchmark from tak.toml instead of running all of them.
        #[usage(long)]
        bench: Option<String>,
        /// Timed runs, or `auto` to size each subject from how long its
        /// samples take. Overrides tak.toml when both are given.
        #[usage(long, value_name = "N|auto")]
        runs: Option<String>,
        /// Untimed warmup runs. Overrides tak.toml when both are given.
        #[usage(long)]
        warmup: Option<u32>,
        /// Skip instruction counting even where valgrind is available.
        #[usage(long)]
        no_counters: bool,
        /// Also count heap allocations under valgrind's DHAT, for every
        /// subject measured. Recorded and reported, never gated.
        #[usage(long)]
        allocations: bool,
        /// Append the result to refs/notes/tak for the current commit.
        #[usage(long)]
        record: bool,
        /// Do not report progress on stderr.
        #[usage(long)]
        no_progress: bool,
        /// Run only the benchmarks that name this `[group.NAME]` in tak.toml.
        /// Repeatable. Cannot be combined with --bench.
        #[usage(long, value_name = "NAME")]
        group: Vec<String>,
        /// Measure only this subject of each multi-subject benchmark.
        /// Repeatable. Benchmarks with none of the named subjects are skipped.
        #[usage(long, value_name = "NAME")]
        subject: Vec<String>,
        /// Seed for the order subjects are sampled in. Every multi-subject
        /// run prints the seed it used, so an order can be repeated.
        #[usage(long, value_name = "N")]
        seed: Option<u64>,
        /// Read this file instead of searching for tak.toml.
        #[usage(long, value_name = "PATH")]
        config: Option<std::path::PathBuf>,
        /// Print what would run — every subject's command, setup, prepare,
        /// check, directory, environment and run count, templates rendered —
        /// without running any of it.
        #[usage(long)]
        dry_run: bool,
        /// Write every sample and summary to PATH as hyperfine-compatible JSON.
        #[usage(long, value_name = "PATH")]
        export_json: Option<std::path::PathBuf>,
        /// Keep the cachegrind profile behind each instruction count, as
        /// `DIR/<bench>/<subject>.cachegrind.out`, for `tak explain`.
        #[usage(long, value_name = "DIR")]
        profile_dir: Option<std::path::PathBuf>,
        /// Save the results as a named local baseline, kept in the git
        /// directory rather than in refs/notes/tak. Replaces what NAME held
        /// for the benchmarks measured and keeps the rest.
        #[usage(long, value_name = "NAME")]
        save_baseline: Option<String>,
        /// Compare the results against a saved local baseline and print the
        /// report `tak compare` prints. Reports only; add --gate to fail on a
        /// regression.
        #[usage(long, value_name = "NAME")]
        baseline: Option<String>,
        /// With --baseline, fail when an instruction count rose beyond its
        /// gate — the one `tak compare` would apply — or when a gated benchmark
        /// could not be compared. `allow_empty` (`--allow-empty`) passes, with a
        /// warning, a run where nothing was compared at all.
        #[usage(long)]
        gate: bool,
        /// Command to benchmark, after `--`. Omit to run what tak.toml declares.
        #[usage(arg, double_dash = "required")]
        cmd: Vec<String>,
    },
    /// Show recorded history for a commit.
    History {
        /// Revision to read. Defaults to HEAD.
        #[usage(arg, default = "HEAD")]
        rev: String,
        /// Remote to refresh notes from.
        #[usage(long, default = "origin")]
        remote: String,
    },
    /// Show each benchmark's measurements over first-parent history.
    ///
    /// One table per benchmark and runner class, newest commit first, with the
    /// change in instruction count from the previous measurement. Commits with
    /// nothing recorded are skipped. `--html` writes the same history as a
    /// self-contained page of charts instead.
    Log {
        /// Revision to walk back from. Defaults to HEAD.
        #[usage(arg, default = "HEAD")]
        rev: String,
        /// Most recent recorded commits to show.
        #[usage(short = 'n', long, default = "30")]
        limit: usize,
        /// Show only this benchmark. Repeatable.
        #[usage(long, value_name = "NAME")]
        bench: Vec<String>,
        /// Write a self-contained HTML report to PATH instead of printing.
        #[usage(long, value_name = "PATH")]
        html: Option<std::path::PathBuf>,
        /// Remote to refresh notes from.
        #[usage(long, default = "origin")]
        remote: String,
    },
    /// Push recorded measurements to the remote.
    Push(RemoteArgs),
    /// Move measurements between a read-only job and a trusted publisher.
    Artifact(Box<ArtifactArgs>),
    /// Teach plain `git fetch` about the notes ref.
    Init(RemoteArgs),
    /// Benchmark published release binaries, or build and benchmark past
    /// commits, to bootstrap history.
    ///
    /// By default, downloads the release binaries a project already published
    /// and measures one command against each. With `--commits`, checks out
    /// each first-parent commit in a range, runs tak.toml's `[build]` there,
    /// and measures the benchmarks tak.toml declares.
    Backfill {
        /// Build and measure the first-parent commits in RANGE, such as
        /// `main~20..main`, instead of downloading releases.
        #[usage(long, value_name = "RANGE")]
        commits: Option<String>,
        /// With --commits, measure every subject again even where this runner
        /// class already has a record, and retry commits whose build or
        /// measurement failed in an earlier run.
        #[usage(long)]
        force: bool,
        /// Repository to pull releases from, as "owner/name". Defaults to the
        /// `origin` remote of the current repository.
        #[usage(long)]
        repo: Option<String>,
        /// Executable name to look for inside each release archive. Defaults to
        /// the repository name.
        #[usage(long)]
        bin: Option<String>,
        /// Arguments passed to the downloaded binary, after `--`.
        /// Defaults to `--version`, which every CLI answers cheaply.
        #[usage(arg, double_dash = "required")]
        args: Vec<String>,
        /// Name to record release measurements under; `release` if omitted.
        /// With --commits, the one benchmark from tak.toml to measure.
        #[usage(long)]
        bench: Option<String>,
        /// Most recent releases to measure. With --commits, most commits to
        /// build, newest first, among those not already recorded.
        #[usage(long, default = "20")]
        limit: usize,
        /// Timed runs per release; 10 if omitted. With --commits, overrides
        /// tak.toml's `runs` for every benchmark.
        #[usage(long)]
        runs: Option<u32>,
        /// Measure releases but do not write to refs/notes/tak. With
        /// --commits, list what would be built, and build nothing.
        #[usage(long)]
        dry_run: bool,
    },
    /// Compare this commit's measurements against another's.
    ///
    /// Fails when an instruction count has risen by more than `gate_pct` and
    /// `gate_min_delta`, or by more than a benchmark's own `gate`, or when no
    /// series was measured on both sides, unless `allow_empty` (`--allow-empty`)
    /// is on, which passes that case with a warning. The gate comes from BASE's
    /// tak.toml, not the working tree's, so a change cannot loosen its own;
    /// flags and environment variables still override it. Wall clock is
    /// reported and never gated. A regression in a benchmark named by
    /// `--accept` is reported as accepted and does not fail. So is one named by a `Tak-Accept:` trailer on a commit in
    /// BASE..REV, but only when the `accept_trailers` setting is on.
    Compare {
        /// Revision to compare against.
        #[usage(arg, default = "origin/main")]
        base: String,
        /// Revision to compare. Defaults to HEAD.
        #[usage(long, default = "HEAD")]
        rev: String,
        /// Remote to refresh notes from.
        #[usage(long, default = "origin")]
        remote: String,
        /// Report without failing, whatever the numbers say. Takes precedence
        /// over `allow_empty`: an empty comparison passes too. Errors, such as
        /// an invalid `tak.toml`, still fail.
        #[usage(long)]
        no_gate: bool,
        /// Accept a regression in this benchmark: report it, but do not fail
        /// on it. Repeatable; each value is one exact benchmark name. Honoured
        /// whatever `accept_trailers` says.
        #[usage(long, value_name = "BENCH")]
        accept: Vec<String>,
    },
    /// Show which functions an instruction-count change came from.
    ///
    /// Reads two sets of profiles written by `tak run --profile-dir`, pairs
    /// them by benchmark and subject, and prints the functions whose counts
    /// changed most as markdown. Reports only; it never fails on the numbers.
    Explain {
        /// Base profiles: a directory written by `tak run --profile-dir`, or
        /// one profile file.
        #[usage(arg)]
        base: std::path::PathBuf,
        /// Head profiles, in the same form as the base.
        #[usage(arg)]
        head: std::path::PathBuf,
        /// Functions to list for each benchmark.
        #[usage(long, default = "10", value_name = "N")]
        top: usize,
    },
    /// Find instruction-count steps that already landed on a branch.
    ///
    /// Meant for the main-branch workflow, after recording. Walks REV's
    /// first-parent history and compares each series' consecutive recorded
    /// points. Fails when the step onto REV itself is beyond that series' gate
    /// (the same per-benchmark gates as `compare`), so a regression fails the
    /// run for the commit that introduced it rather than every run after, and
    /// when nothing could be compared: REV has no instruction counts, or none
    /// of its series has an earlier point in the window. `allow_empty`
    /// (`--allow-empty`) passes that case with a warning, for a first
    /// recording or the first on a new runner class. Older steps and slow
    /// drift are reported without failing. Wall clock is shown and never gated. A step in a
    /// benchmark named by `--accept` is reported as accepted and does not fail.
    /// So is one named by a `Tak-Accept:` trailer on a first-parent commit in
    /// the step's range, but only when the `accept_trailers` setting is on.
    Detect {
        /// Newest commit to examine. Defaults to HEAD.
        #[usage(arg, default = "HEAD")]
        rev: String,
        /// Recorded commits to examine, counting REV when it is recorded.
        #[usage(long, default = "20", value_name = "N")]
        window: usize,
        /// Remote to refresh notes from.
        #[usage(long, default = "origin")]
        remote: String,
        /// Report without failing on the result: neither a step nor an empty
        /// comparison fails the command. Errors, such as an invalid `tak.toml`,
        /// still fail.
        #[usage(long)]
        no_gate: bool,
        /// Accept a step onto REV in this benchmark: report it, but do not fail
        /// on it. Repeatable; each value is one exact benchmark name. Honoured
        /// whatever `accept_trailers` says.
        #[usage(long, value_name = "BENCH")]
        accept: Vec<String>,
    },
    /// Diagnose the git-notes plumbing.
    Doctor,
    /// Show every setting, its resolved value, and where that value came from.
    Settings {
        /// Include the full description of each setting.
        #[usage(long)]
        docs: bool,
    },
    /// Generate the CLI specification used to build the documentation.
    #[usage(hide)]
    Usage,
}

#[derive(Args)]
struct ArtifactArgs {
    #[usage(subcommand)]
    cmd: ArtifactCmd,
}

#[derive(Subcommands)]
enum ArtifactCmd {
    /// Export locally recorded measurements as one portable file.
    Export {
        /// Artifact file to write.
        #[usage(long, value_name = "PATH")]
        output: std::path::PathBuf,
        /// Revision whose local measurements should be exported.
        #[usage(long, default = "HEAD")]
        rev: String,
    },
    /// Validate, import, and publish a measurement artifact.
    Publish {
        /// Artifact file produced by `tak artifact export`.
        #[usage(arg)]
        path: std::path::PathBuf,
        /// Trusted revision the artifact must target.
        #[usage(long, value_name = "REV")]
        expect: String,
        /// Remote to synchronize with.
        #[usage(long, default = "origin")]
        remote: String,
    },
}

#[derive(Args)]
struct RemoteArgs {
    /// Remote to use for git-notes synchronization.
    #[usage(long, default = "origin")]
    remote: String,
}

/// Identify the machine class. Series must be partitioned on this — moving
/// between runner types shifts absolute numbers enough to look like a regression,
/// which is a documented failure mode of every threshold-based CI benchmark.
///
/// An explicit `runner_class` wins. It is how a project partitions on something
/// the derived name cannot see: a compiler or image upgrade changes the numbers
/// without changing the machine, and tak has no way to detect that on its own.
fn runner_class(settings: &Settings) -> String {
    if !settings.runner_class.trim().is_empty() {
        return settings.runner_class.clone();
    }
    if std::env::var("GITHUB_ACTIONS").is_ok() {
        let os = std::env::var("RUNNER_OS").unwrap_or_else(|_| "unknown".into());
        let arch = std::env::var("RUNNER_ARCH").unwrap_or_else(|_| "unknown".into());
        return format!("gha-{}-{}", os.to_lowercase(), arch.to_lowercase());
    }
    format!("local-{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}

/// RFC 3339 to second resolution, without pulling in a date crate for a skeleton.
fn now_rfc3339() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    rfc3339(i64::try_from(secs).unwrap_or(i64::MAX))
}

/// `secs` since the epoch as RFC 3339 in UTC, the one shape `ts` is written in.
///
/// Signed, because a commit can be dated before 1970 (`git commit --date`),
/// and flooring division keeps such a time on the right day.
fn rfc3339(secs: i64) -> String {
    let days = secs.div_euclid(86_400);
    let rem = secs.rem_euclid(86_400);
    // Civil-from-days (Howard Hinnant's algorithm), epoch shifted to 0000-03-01.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        rem / 3600,
        (rem % 3600) / 60,
        rem % 60
    )
}

/// `tak run`'s options, gathered so they travel as one value.
struct RunOpts {
    bench: Option<String>,
    runs: Option<Runs>,
    warmup: Option<u32>,
    no_counters: bool,
    allocations: bool,
    record: bool,
    no_progress: bool,
    groups: Vec<String>,
    subjects: Vec<String>,
    seed: Option<u64>,
    export_json: Option<std::path::PathBuf>,
    /// Absolute, so a subject's own `dir` cannot move where profiles land.
    profile_dir: Option<std::path::PathBuf>,
    config: Option<std::path::PathBuf>,
    dry_run: bool,
    save_baseline: Option<String>,
    baseline: Option<String>,
    gate: bool,
}

/// What `--baseline` and `--save-baseline` resolved to, decided before
/// anything is measured: a mistyped name or a missing repository should fail
/// in a second, not after the whole run.
#[derive(Default)]
struct Local {
    /// Present whenever either flag was given.
    store: Option<Store>,
    against: Option<Baseline>,
    /// Each series' gate, with `--baseline`: the same lookup `tak compare`
    /// makes, so a report-only benchmark or a `min_delta` floor means the same
    /// thing against a baseline as against a commit.
    gates: Option<compare::Gates>,
}

/// The gates a `--baseline` report and `--gate` use.
///
/// A declared run loads and validates `tak.toml` to run at all, so reading
/// its per-benchmark gates adds no way to fail. An ad-hoc `tak run -- CMD`
/// has never depended on the declared benchmarks — settings read only the
/// `[gate]` and other registry keys — and a broken `[bench.x]` must not stop
/// a report either. So an ad-hoc run without `--gate` holds everything to
/// `[gate]` and never reads the benchmarks.
///
/// With `--gate` the verdict needs the real thresholds: a benchmark of the
/// same name may be report-only or have its own `pct` or floor. A file that
/// will not load is then an error, before anything is measured. Falling back
/// to `[gate]` would gate silently harder or softer than the project asked,
/// and a wrong verdict that exits 0 is worse than a loud failure.
fn baseline_gates(opts: &RunOpts, settings: &Settings, adhoc: bool) -> Result<compare::Gates> {
    if adhoc && !opts.gate {
        return Ok(compare::Gates::uniform(global_gate(settings)?));
    }
    compare_gates(settings, opts.config.as_deref()).with_context(|| {
        if adhoc {
            "--gate needs a valid tak.toml to find per-benchmark gates; run without --gate \
             to report only"
        } else {
            "could not read the gates in tak.toml"
        }
    })
}

fn open_local(opts: &RunOpts, settings: &Settings, adhoc: bool) -> Result<Local> {
    if opts.gate && opts.baseline.is_none() {
        bail!(
            "--gate applies to --baseline; to gate against another commit's recorded \
             measurements, use `tak compare`"
        );
    }
    for name in [&opts.baseline, &opts.save_baseline].into_iter().flatten() {
        baseline::validate_name(name)?;
    }
    if opts.baseline.is_none() && opts.save_baseline.is_none() {
        return Ok(Local::default());
    }
    let store = Store::locate()?;
    if let Some(name) = &opts.save_baseline {
        store.check_saveable(name)?;
    }
    let against = opts
        .baseline
        .as_deref()
        .map(|name| store.load(name))
        .transpose()?;
    // Read with the baseline, before measuring, so a bad `[gate]` fails in a
    // second. From `--config` when it is given: that is the file whose
    // benchmarks this run measures.
    let gates = against
        .is_some()
        .then(|| baseline_gates(opts, settings, adhoc))
        .transpose()?;
    Ok(Local {
        store: Some(store),
        against,
        gates,
    })
}

/// One subject's successful measurement.
struct Measured {
    bench: String,
    subject: Subject,
    /// What `version_cmd` printed: `None` when the subject has none,
    /// `Some(None)` when it failed.
    version: Option<Option<String>>,
    samples: measure::Samples,
    /// Each declared custom metric's value, `None` when it could not be
    /// taken. Also in `record.metrics` when it could.
    custom: BTreeMap<String, Option<f64>>,
    record: Record,
    /// Counting was asked for, valgrind was there, and no count came back.
    /// Kept apart from counters being off: the record looks the same either
    /// way, and only one of them is a benchmark `--gate` meant to check.
    count_failed: bool,
    /// The cachegrind profile behind the instruction count, when
    /// `--profile-dir` asked for one and the count succeeded.
    profile: Option<Vec<u8>>,
}

/// Check every profile path before measuring anything, so a benchmark name
/// that cannot be a file name fails now rather than after an hour of
/// benchmarks before it.
fn check_profile_paths<'a>(
    opts: &RunOpts,
    plans: impl IntoIterator<Item = (&'a str, bool, &'a [Subject])>,
) -> Result<()> {
    let Some(dir) = &opts.profile_dir else {
        return Ok(());
    };
    if opts.no_counters {
        bail!(
            "--profile-dir keeps the profiles of instruction counts, and --no-counters turns them off"
        );
    }
    for (bench, multi, subjects) in plans {
        for s in subjects {
            tak_cli::profile::path_for(dir, bench, &record_tool(multi, s))?;
        }
    }
    Ok(())
}

/// Reject the recorded names that come from outside `tak.toml` — the runner
/// class and `--bench` — before anything is measured, for the reason
/// `record::check_name` gives. `tak.toml`'s own names are checked when it
/// loads, and `TAK_TOOL` by [`check_tak_tool`] where it is used.
fn check_recorded_names(settings: &Settings, bench: Option<&str>) -> Result<()> {
    record::check_name("runner class", &runner_class(settings))?;
    if let Some(bench) = bench {
        record::check_name("benchmark", bench)?;
    }
    Ok(())
}

/// Reject a `TAK_TOOL` that would be recorded with a control character in it.
///
/// Only called where it would be recorded: it names the series of a
/// single-command benchmark or an ad-hoc `tak run -- CMD`, and nothing else.
/// A multi-subject run records each subject's own name and backfill records
/// the release binary's, so checking it there let a stray inherited value
/// block work that would never have used it.
fn check_tak_tool() -> Result<()> {
    if let Ok(tool) = std::env::var("TAK_TOOL") {
        record::check_name("TAK_TOOL", &tool)?;
    }
    Ok(())
}

fn cmd_run(opts: RunOpts, cmd: Vec<String>, settings: &Settings) -> Result<()> {
    global_gate(settings)?;
    check_recorded_names(settings, opts.bench.as_deref())?;
    let local = open_local(&opts, settings, !cmd.is_empty())?;
    // An explicit command always wins; tak.toml is only consulted when none is
    // given, so ad-hoc measurement never depends on repository state.
    if cmd.is_empty() {
        return run_declared(opts, settings, &local);
    }
    check_tak_tool()?;
    if !opts.subjects.is_empty() {
        bail!(
            "--subject selects subjects declared in tak.toml; it cannot be used with a command after `--`"
        );
    }
    if !opts.groups.is_empty() {
        bail!(
            "--group selects benchmarks declared in tak.toml; it cannot be used with a command after `--`"
        );
    }
    let bench = opts.bench.clone().unwrap_or_else(|| "default".to_string());
    let subject = Subject {
        name: SELF_TOOL.to_string(),
        cmd,
        prepare: None,
        setup: None,
        setup_dir: None,
        check: None,
        dir: None,
        version_cmd: None,
        env: BTreeMap::new(),
        vars: BTreeMap::new(),
        when: None,
        runs: opts.runs.unwrap_or(Runs::Fixed(DEFAULT_RUNS)),
        auto: AutoRuns {
            budget: DEFAULT_BUDGET,
            min: DEFAULT_MIN_RUNS,
            max: DEFAULT_MAX_RUNS,
        },
        warmup: opts.warmup.unwrap_or(DEFAULT_WARMUP),
        counters: true,
        allocations: opts.allocations,
        ok_exit_codes: config::DEFAULT_OK_EXIT_CODES.to_vec(),
        metrics: BTreeMap::new(),
    };
    check_profile_paths(
        &opts,
        [(bench.as_str(), false, std::slice::from_ref(&subject))],
    )?;
    let seed = opts.seed.unwrap_or_else(random_seed);
    if opts.dry_run {
        print_plan(
            &bench,
            false,
            std::slice::from_ref(&subject),
            opts.no_counters,
        );
        return Ok(());
    }
    let (measured, _) = measure_bench(&bench, &[subject], false, seed, &opts, settings)?;
    finish(measured, Vec::new(), &opts, seed, settings, &local)
}

/// Run the benchmarks declared in `tak.toml`.
fn run_declared(opts: RunOpts, settings: &Settings, local: &Local) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let found = match &opts.config {
        // Absolute, so the directory commands are anchored to is too: a
        // relative one would be re-resolved from each subject's own `dir`,
        // and a bare `tak.toml` would have no parent at all.
        Some(path) => {
            let path = std::path::absolute(path)
                .with_context(|| format!("could not resolve {}", path.display()))?;
            let cfg = Config::load(&path)?;
            Some((path, cfg))
        }
        None => Config::find(&cwd)?,
    };
    let Some((path, cfg)) = found else {
        bail!(
            "no command given and no {} found in {} or any parent.\n\
             Pass a command after `--`, or declare one:\n\n\
             \x20   [bench.startup]\n\
             \x20   cmd = [\"./mycli\", \"--version\"]",
            config::FILE_NAME,
            cwd.display()
        );
    };

    let Planned { mut plans, skipped } = plan_declared(&cfg, &path, &opts)?;
    print_skipped(&skipped);

    // Commands are relative to tak.toml, not to wherever this was invoked.
    let root = path.parent().map(Path::to_path_buf).unwrap_or_default();
    for (_, _, subjects) in &mut plans {
        for s in subjects {
            s.anchor(&root);
        }
    }

    if plans.is_empty() {
        // A gate that measured nothing has checked nothing, and exiting 0
        // would mark the revision good: `git bisect run` would carry on past
        // it. Same exemption as below: a dry run gates nothing either way.
        if opts.gate && !opts.dry_run {
            bail!(
                "nothing to gate against baseline `{}`: {}",
                opts.baseline.as_deref().unwrap_or_default(),
                if skipped.is_empty() {
                    format!("{} declares no benchmarks", path.display())
                } else {
                    "every selected benchmark or subject has a false `when`".to_string()
                }
            );
        }
        if skipped.is_empty() {
            println!("{} declares no benchmarks", path.display());
            return Ok(());
        }
        // Asked to leave a result behind and producing none is a failure: a
        // CI job recording or exporting must not look like it measured
        // something when every benchmark was switched off.
        // A dry run writes neither, so there is nothing for it to fail over.
        if !opts.dry_run
            && (opts.record || opts.export_json.is_some() || opts.save_baseline.is_some())
        {
            bail!(
                "nothing to {}: every selected benchmark or subject has a false `when`",
                if opts.record {
                    "record"
                } else if opts.save_baseline.is_some() {
                    "save"
                } else {
                    "export"
                }
            );
        }
        println!("nothing to run: every selected benchmark or subject has a false `when`");
        return Ok(());
    }

    check_profile_paths(
        &opts,
        plans
            .iter()
            .map(|(name, multi, subjects)| (name.as_str(), *multi, subjects.as_slice())),
    )?;
    if opts.dry_run {
        println!("{}", path.display());
        for (name, multi, subjects) in &plans {
            print_plan(name, *multi, subjects, opts.no_counters);
        }
        return Ok(());
    }

    let seed = opts.seed.unwrap_or_else(random_seed);
    let mut measured = Vec::new();
    let mut failed = Vec::new();
    for (name, multi, subjects) in &plans {
        let (m, f) = measure_bench(name, subjects, *multi, seed, &opts, settings)?;
        measured.extend(m);
        failed.extend(f);
    }
    finish(measured, failed, &opts, seed, settings, local)
}

/// One benchmark ready to measure: its name, whether it compares several
/// subjects, and those subjects.
type BenchPlan = (String, bool, Vec<Subject>);

/// What `tak.toml` asks to measure, with every layer applied and every
/// template rendered, but not yet anchored to a directory: `tak run` anchors
/// it at the directory holding `tak.toml`, `tak backfill --commits` at the
/// same place in each commit's checkout.
struct Planned {
    plans: Vec<BenchPlan>,
    /// Benchmarks, or subjects of one, that a false `when` switched off.
    skipped: Vec<(String, Option<String>, String)>,
}

/// Resolve the benchmarks `opts` selects from `cfg`, found at `path`.
/// Keep the benchmarks in one of `--group`'s groups, or all of them when it
/// names none. A group tak.toml does not declare fails the run before any
/// benchmark is measured.
fn select_groups<'a>(
    cfg: &Config,
    path: &Path,
    opts: &RunOpts,
    selected: Vec<(String, &'a tak_cli::config::Bench)>,
) -> Result<Vec<(String, &'a tak_cli::config::Bench)>> {
    if opts.groups.is_empty() {
        return Ok(selected);
    }
    if opts.bench.is_some() {
        bail!("--bench and --group cannot be combined; --bench already names one benchmark");
    }
    for g in &opts.groups {
        if !cfg.has_group(g) {
            let found: Vec<_> = cfg.group_names().collect();
            bail!(
                "no group `{g}` in {} (found: {})",
                path.display(),
                if found.is_empty() {
                    "none".to_string()
                } else {
                    found.join(", ")
                }
            );
        }
    }
    // A group no benchmark names would select nothing, and a run that selects
    // nothing exits 0 without writing what --record, --export-json or
    // --save-baseline asked for. Like an unknown --subject, it is a mistake.
    for g in &opts.groups {
        if !selected.iter().any(|(_, b)| b.group() == Some(g.as_str())) {
            bail!("no benchmark in {} names group `{g}`", path.display());
        }
    }
    Ok(selected
        .into_iter()
        .filter(|(_, b)| {
            b.group()
                .is_some_and(|g| opts.groups.iter().any(|o| o == g))
        })
        .collect())
}

fn plan_declared(cfg: &Config, path: &Path, opts: &RunOpts) -> Result<Planned> {
    let selected: Vec<_> = match &opts.bench {
        Some(name) => {
            let b = cfg.bench.get(name).with_context(|| {
                format!(
                    "no benchmark `{name}` in {} (found: {})",
                    path.display(),
                    if cfg.bench.is_empty() {
                        "none".to_string()
                    } else {
                        cfg.bench.keys().cloned().collect::<Vec<_>>().join(", ")
                    }
                )
            })?;
            vec![(name.clone(), b)]
        }
        None => cfg.bench.iter().map(|(k, v)| (k.clone(), v)).collect(),
    };
    let selected = select_groups(cfg, path, opts, selected)?;

    // Resolve and filter everything before measuring anything, so a mistyped
    // --subject fails now rather than after the benchmarks before it ran.
    let mut plans = Vec::new();
    let mut seen = std::collections::BTreeSet::new();
    let env = tak_cli::template::env();
    let mut skipped = Vec::new();
    // Subjects a `when` switched off — their own, or their benchmark's — so
    // a --subject naming one is told why it will not run, rather than that
    // it does not exist.
    let mut hidden: std::collections::BTreeMap<String, (String, String)> = Default::default();
    for (name, b) in selected {
        let subjects = cfg.subjects(&name)?;
        seen.extend(subjects.iter().map(|s| s.name.clone()));
        // A benchmark with none of the requested subjects is not being run:
        // nothing about it, its own `when` included, is decided or reported.
        if !opts.subjects.is_empty() && !subjects.iter().any(|s| opts.subjects.contains(&s.name)) {
            continue;
        }
        // `when` is decided before anything is rendered, so a skipped
        // benchmark or subject never needs the variables it would have used.
        if let Some(when) = b.when()
            && !tak_cli::condition::eval(when, &env, &name, None)
                .with_context(|| format!("benchmark `{name}`"))?
        {
            for s in subjects {
                hidden
                    .entry(s.name)
                    .or_insert_with(|| (name.clone(), when.to_string()));
            }
            skipped.push((name.clone(), None, when.to_string()));
            continue;
        }
        let mut kept = Vec::with_capacity(subjects.len());
        for s in subjects {
            // Only the subjects being run are decided on: one --subject left
            // out cannot fail the run, whatever its condition evaluates to.
            if !opts.subjects.is_empty() && !opts.subjects.contains(&s.name) {
                continue;
            }
            match &s.when {
                Some(when)
                    if !tak_cli::condition::eval(when, &env, &name, Some(&s.name))
                        .with_context(|| format!("benchmark `{name}`, subject `{}`", s.name))? =>
                {
                    // Remembered rather than fatal: another benchmark may
                    // still measure a subject this one switches off. Only a
                    // requested subject no benchmark runs is an error, below.
                    hidden
                        .entry(s.name.clone())
                        .or_insert_with(|| (name.clone(), when.clone()));
                    skipped.push((name.clone(), Some(s.name.clone()), when.clone()));
                }
                _ => kept.push(s),
            }
        }
        let mut subjects = kept;
        if subjects.is_empty() {
            continue;
        }
        // Filter before rendering: a subject that is not being measured must
        // not fail the run over a variable only it needs.
        if !opts.subjects.is_empty() {
            subjects.retain(|s| opts.subjects.contains(&s.name));
            if subjects.is_empty() {
                continue;
            }
        }
        let mut subjects = subjects
            .into_iter()
            .map(|s| {
                let subject = s.name.clone();
                tak_cli::template::render(s, &name, &env)
                    .with_context(|| format!("benchmark `{name}`, subject `{subject}`"))
            })
            .collect::<Result<Vec<_>>>()?;
        for s in &mut subjects {
            // Only for what runs, after `when`, --bench and --subject, and
            // before anything is set up or sampled: a portable tak.toml may
            // hold a Windows-only subject, or list Windows codes next to Unix
            // ones. A list with no possible code at all fails the run here,
            // dry run included, rather than dropping the subject at its
            // first sample.
            let impossible = config::check_platform_exit_codes(&s.ok_exit_codes, cfg!(unix))
                .with_context(|| format!("benchmark `{name}`, subject `{}`", s.name))?;
            if !impossible.is_empty() {
                let range = config::exit_code_range(cfg!(unix)).expect("narrowed");
                eprintln!(
                    "  warning: {name} ({}): ok_exit_codes {} can never match here: exit codes on this platform are {} to {}",
                    s.name,
                    config::join_codes(&impossible),
                    range.start(),
                    range.end()
                );
            }
            // An explicit flag beats the file; the file beats the default.
            s.runs = opts.runs.unwrap_or(s.runs);
            s.warmup = opts.warmup.unwrap_or(s.warmup);
            // Adds to the file rather than overriding it: there is no
            // `--no-allocations`, since leaving the flag off already means
            // whatever tak.toml says.
            s.allocations |= opts.allocations;
        }
        plans.push((name, b.is_multi(), subjects));
    }
    // A requested subject that no benchmark will measure: say why.
    let planned: std::collections::BTreeSet<&str> = plans
        .iter()
        .flat_map(|(_, _, subjects)| subjects.iter().map(|s| s.name.as_str()))
        .collect();
    if let Some(off) = opts
        .subjects
        .iter()
        .find(|s| !planned.contains(s.as_str()) && hidden.contains_key(*s))
    {
        let (bench, when) = &hidden[off];
        bail!(
            "subject `{off}` was asked for, but `when` is false for it in benchmark `{bench}`: {when}"
        );
    }
    if let Some(missing) = opts.subjects.iter().find(|s| !seen.contains(*s)) {
        bail!(
            "no subject `{missing}` in the selected benchmarks (found: {})",
            seen.into_iter().collect::<Vec<_>>().join(", ")
        );
    }
    // Before measuring anything, and only when a benchmark that will run
    // records under TAK_TOOL: one without subjects.
    if plans.iter().any(|(_, multi, _)| !multi) {
        check_tak_tool()?;
    }

    Ok(Planned { plans, skipped })
}

fn print_skipped(skipped: &[(String, Option<String>, String)]) {
    for (bench, subject, when) in skipped {
        let what = subject
            .as_ref()
            .map_or(bench.to_string(), |s| format!("{bench} ({s})"));
        eprintln!("  skipping {what}: `when` is false: {when}");
    }
}

/// A random seed below 2^53, so it survives any JSON reader — JavaScript and
/// jq hold numbers as doubles — and is shorter to copy into `--seed`.
fn random_seed() -> u64 {
    fastrand::u64(..1 << 53)
}

/// Print a benchmark's subjects as they would run, for `tak run --dry-run`:
/// every layer applied, templates rendered, paths anchored and command-line
/// overrides taken into account.
fn print_plan(bench: &str, multi: bool, subjects: &[Subject], no_counters: bool) {
    println!(
        "\n  {bench}{}",
        if multi { "" } else { "  (single command)" }
    );
    for s in subjects {
        if multi {
            println!("    {}", s.name);
        }
        let pad = if multi { "      " } else { "    " };
        println!("{pad}cmd      {}", shell_words(&s.cmd));
        if let Some(p) = &s.setup {
            // Where it runs, since unlike everything else it is not `dir`.
            match &s.setup_dir {
                Some(d) => println!("{pad}setup    {}  (in {})", shell_words(p), d.display()),
                None => println!("{pad}setup    {}", shell_words(p)),
            }
        }
        if let Some(v) = &s.version_cmd {
            println!("{pad}version  {}", shell_words(v));
        }
        if let Some(p) = &s.prepare {
            println!("{pad}prepare  {}", shell_words(p));
        }
        if let Some(c) = &s.check {
            println!("{pad}check    {}", shell_words(c));
        }
        if let Some(d) = &s.dir {
            println!("{pad}dir      {}", d.display());
        }
        for (k, v) in &s.env {
            println!("{pad}env      {k}={}", shell_words(std::slice::from_ref(v)));
        }
        let runs = match s.runs {
            Runs::Fixed(n) => n.to_string(),
            Runs::Auto => format!(
                "auto ({} budget, {}..={})",
                tak_cli::progress::fmt(s.auto.budget),
                s.auto.min,
                s.auto.max
            ),
        };
        println!("{pad}runs     {runs}, warmup {}", s.warmup);
        // Only when it differs from the default, which every subject has.
        if s.ok_exit_codes != config::DEFAULT_OK_EXIT_CODES {
            let codes: Vec<String> = s.ok_exit_codes.iter().map(i32::to_string).collect();
            println!("{pad}ok exit  {}", codes.join(", "));
        }
        // As the run would do it: --no-counters overrides the file.
        if s.counters && !no_counters {
            println!("{pad}counters on");
        }
        if s.allocations {
            println!("{pad}allocations on");
        }
        for (name, source) in &s.metrics {
            match source {
                config::MetricSource::File(p) => {
                    println!("{pad}metric   {name}  file {}", p.display())
                }
                config::MetricSource::Cmd(c) => {
                    println!("{pad}metric   {name}  cmd {}", shell_words(c))
                }
            }
        }
    }
}

/// Arguments joined for reading, quoting any that a shell would split. For
/// display only: tak itself never passes a command through a shell.
fn shell_words(argv: &[String]) -> String {
    argv.iter()
        .map(|a| {
            if !a.is_empty()
                && a.chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_./=:,@%+".contains(c))
            {
                a.clone()
            } else {
                format!("'{}'", a.replace('\'', r"'\''"))
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Export and record what was measured, then report any failures.
fn finish(
    measured: Vec<Measured>,
    failed: Vec<String>,
    opts: &RunOpts,
    seed: u64,
    settings: &Settings,
    local: &Local,
) -> Result<()> {
    // The export is written even when a subject failed: it is this run's
    // results, the failed subject is simply absent, and a consumer comparing
    // subjects has to handle a missing one anyway.
    if let Some(path) = &opts.export_json {
        let results = measured
            .iter()
            .map(|m| {
                let command = if m.subject.name == SELF_TOOL {
                    &m.bench
                } else {
                    &m.subject.name
                };
                let mut r = ExportResult::new(&m.bench, &m.subject.name, command, &m.samples.times)
                    .with_exit_codes(&m.samples.exit_codes);
                r.version = m.version.clone();
                r.allocations = export::Allocations::from_metrics(&m.record.metrics);
                r.metrics = m.custom.clone();
                if m.subject.check.is_some() {
                    r.with_checks(&m.samples.checks)
                } else {
                    r
                }
            })
            .collect();
        let meta = export::Meta {
            tak_version: env!("CARGO_PKG_VERSION").to_string(),
            seed,
            runner: runner_class(settings),
            time: now_rfc3339(),
            // Read after measuring, so describing the machine is never part
            // of what was measured.
            machine: tak_cli::machine::detect(),
        };
        export::write(path, meta, results)?;
        println!(
            "\n  exported {} result(s) to {}",
            measured.len(),
            path.display()
        );
    }
    // Written when the export is and for the same reason: they describe this
    // run, and a subject that failed simply has none, which `tak explain`
    // reports as a profile on one side only.
    if let Some(dir) = &opts.profile_dir {
        let runner = runner_class(settings);
        // What `--record` would attach the counts to, so `tak explain` can
        // find them. Outside a repository there is nothing to check against.
        let commit = notes::rev_parse("HEAD").ok();
        let mut written = 0usize;
        for m in &measured {
            if let Some(raw) = &m.profile {
                // Named, like the origin inside it, by the series the record
                // uses — what the notes are looked up by, and for a single
                // command that may be TAK_TOOL rather than `self`.
                let dest = tak_cli::profile::path_for(dir, &m.bench, &m.record.tool)?;
                let origin = tak_cli::profile::Origin {
                    runner: runner.clone(),
                    commit: commit.clone(),
                    bench: m.bench.clone(),
                    subject: m.record.tool.clone(),
                };
                tak_cli::profile::write(&dest, raw, &origin)?;
                written += 1;
            }
        }
        println!("\n  wrote {written} profile(s) to {}", dir.display());
    }
    let failing = failing_checks(&measured);
    // Reported before a failed subject stops the run: the question this
    // answers is whether an edit helped, and the subjects that did measure
    // answer it.
    let compared = match (&local.against, &local.gates) {
        (Some(b), Some(gates)) => Some(report_against(
            b,
            &measured,
            &failing,
            gates,
            opts.gate && settings.allow_empty,
        )),
        _ => None,
    };
    // What a failure below keeps from being written, named so the message
    // says which store was left untouched.
    let storing = match (opts.record, &opts.save_baseline) {
        (true, Some(name)) => Some(format!("recording or saving baseline `{name}`")),
        (true, None) => Some("recording".to_string()),
        (false, Some(name)) => Some(format!("saving baseline `{name}`")),
        (false, None) => None,
    };
    if !failed.is_empty() {
        // Everything is measured before anything is written, and that holds
        // here too: a run missing a subject is stored whole or not at all,
        // because a partial set left in history looks like a complete one.
        if let Some(storing) = &storing {
            eprintln!("\n  not {storing}: a run with a failed subject would be stored incomplete");
        }
        bail!("{} subject(s) failed: {}", failed.len(), failed.join(", "));
    }
    // A declared metric that could not be taken fails the run, recording or
    // not. Unlike a failed check it is not a finding about the subject — a
    // missing file or a broken script is a broken benchmark — and storing the
    // rest, in git notes or as a baseline, would leave the metric silently
    // absent, which reads as it having been dropped rather than having failed.
    let broken = failed_metrics(&measured);
    if !broken.is_empty() {
        if let Some(storing) = &storing {
            eprintln!(
                "\n  not {storing}: a run missing a declared metric would be stored incomplete"
            );
        }
        bail!("{} metric(s) failed: {}", broken.len(), broken.join(", "));
    }
    // Decided before anything is stored, reported after: a regression is
    // exactly the measurement a `--record` run exists to keep, and failing
    // before storing would throw it away. The one exception is a baseline
    // saved over the one it was gated against. Replacing `good` with the run
    // that just failed against it would make a retry — or the next `git
    // bisect run` step — compare the regression with itself and pass.
    let verdict = match (&local.against, &compared, &local.gates) {
        (Some(against), Some(compared), Some(gates)) if opts.gate => {
            gate_against(against, compared, &failing, gates)
        }
        _ => Ok(()),
    };
    let kept = match &opts.save_baseline {
        Some(name) if verdict.is_err() && opts.baseline.as_ref() == Some(name) => Some(name),
        _ => None,
    };
    if let Some(storing) = &storing {
        // Git notes keep the timings but not the check verdicts, which do not
        // fit how recorded metrics are read: `compare` keeps each metric's
        // minimum and treats lower as better. So a failed check has to stop
        // the recording, or history would hold a fast time from a sample
        // that did the work wrong with nothing marking it. Only this run's
        // verdicts can vouch for this run's timings, so there is no way to
        // clear it but a run whose checks all pass. The export above is still
        // written: it carries the verdicts. A baseline holds the same records
        // and is read by the same `compare`, so the same rule applies to it.
        if !failing.is_empty() {
            eprintln!(
                "
  not {storing}: stored measurements keep timings without check verdicts, so a \
                 run with a failed check would be stored as if it had passed"
            );
            bail!("check failed: {}", labels(&failing));
        }
        let records: Vec<Record> = measured.into_iter().map(|m| m.record).collect();
        // The baseline first. Saving it replaces this run's series, so doing
        // it twice leaves the same file, while appending to the notes twice
        // leaves two records. With that order, a failed second write is
        // fixed by re-running the same command; the other order would
        // double-record every retry of a failed baseline save.
        if let (Some(name), Some(store)) = (&opts.save_baseline, &local.store)
            && kept.is_none()
        {
            save_baseline(store, name, &records)?;
        }
        if opts.record {
            record_all(&records).with_context(|| match &opts.save_baseline {
                Some(name) if kept.is_none() => format!(
                    "baseline `{name}` was saved, but nothing was recorded to {}; \
                     re-running the same command saves the baseline again and records",
                    notes::NOTES_REF
                ),
                _ => format!("nothing was recorded to {}", notes::NOTES_REF),
            })?;
        }
    }
    match kept {
        Some(name) => verdict
            .with_context(|| format!("baseline `{name}` was not replaced because the gate failed")),
        None => verdict,
    }
}

/// A subject whose check failed on at least one sample.
struct FailedCheck {
    bench: String,
    /// As recorded, so its gate can be looked up the way the comparison's is.
    tool: String,
    /// `bench (subject) failed N of M`, for messages.
    label: String,
}

/// Each subject whose check failed on any sample.
fn failing_checks(measured: &[Measured]) -> Vec<FailedCheck> {
    measured
        .iter()
        .filter(|m| m.samples.passed() < m.samples.checks.len())
        .map(|m| {
            let label = if m.subject.name == SELF_TOOL {
                m.bench.clone()
            } else {
                format!("{} ({})", m.bench, m.subject.name)
            };
            FailedCheck {
                bench: m.bench.clone(),
                tool: m.record.tool.clone(),
                label: format!(
                    "{label} failed {} of {}",
                    m.samples.checks.len() - m.samples.passed(),
                    m.samples.checks.len()
                ),
            }
        })
        .collect()
}

fn labels<'a>(failing: impl IntoIterator<Item = &'a FailedCheck>) -> String {
    failing
        .into_iter()
        .map(|f| f.label.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// What a baseline comparison found, kept for `--gate`.
struct Against {
    comparison: compare::Comparison,
    /// Series this run measured that cannot be gated; see [`baseline::gaps`].
    gaps: Vec<(compare::Key, baseline::Gap)>,
    /// Every series this run measured, compared or not.
    measured: BTreeSet<compare::Key>,
}

/// Print how this run compares with a saved baseline, and return the
/// comparison for `--gate`.
///
/// The same [`compare::compare`] and [`compare::markdown`] as `tak compare`,
/// so a local report and a pull request's read the same way and are kept
/// correct in one place.
///
/// `allow_empty` is the setting under `--gate`, and false without it: only a
/// gate has anything to waive, and a report-only run should not claim to have
/// passed with a warning.
fn report_against(
    against: &Baseline,
    measured: &[Measured],
    failing: &[FailedCheck],
    gates: &compare::Gates,
    allow_empty: bool,
) -> Against {
    let current: Vec<Record> = measured.iter().map(|m| m.record.clone()).collect();
    let base = baseline::relevant(&against.records, &current);
    let mut comparison = compare::compare(&base, &current);
    // A report-only series is never a reason to fail, so it cannot leave a
    // gap in what the gate checked either.
    let count_failed: BTreeSet<compare::Key> = measured
        .iter()
        .filter(|m| m.count_failed)
        .map(|m| {
            (
                m.record.bench.clone(),
                m.record.tool.clone(),
                m.record.runner.clone(),
            )
        })
        .collect();
    let gaps: Vec<_> = baseline::gaps(&against.records, &current, &count_failed)
        .into_iter()
        .filter(|(k, _)| gates.get(&k.0, &k.1).enabled)
        .collect();
    let keys: BTreeSet<compare::Key> = current
        .iter()
        .map(|r| (r.bench.clone(), r.tool.clone(), r.runner.clone()))
        .collect();
    // Decided here, before the report is printed, so the report and
    // `gate_against` read the same answer. Only an empty comparison, as in
    // `tak compare`: nothing measured both here and in the baseline. Not a
    // count that failed or a check that failed, which are this run's own
    // measurement going wrong rather than history that is missing, and not a
    // run of report-only benchmarks, which passes on that ground and says so.
    let enabled = |bench: &str, tool: &str| gates.get(bench, tool).enabled;
    comparison.allowed_empty = allow_empty
        && comparison.is_empty()
        && keys.iter().any(|k| enabled(&k.0, &k.1))
        && !failing.iter().any(|f| enabled(&f.bench, &f.tool))
        && !gaps
            .iter()
            .any(|(_, gap)| matches!(gap, baseline::Gap::CountFailed));

    // Series the baseline holds only for other runner classes. The table
    // leaves them out, as it should, so this says why they are absent: a
    // baseline saved with another `--runner`, or on the other side of a CI
    // boundary, is the usual cause. Nothing is said when this run's class is
    // in the baseline too; the other classes are simply not this run's.
    let mut stranded: BTreeMap<Vec<String>, Vec<String>> = BTreeMap::new();
    for k in &keys {
        if base.iter().any(|r| r.bench == k.0 && r.tool == k.1) {
            continue;
        }
        let elsewhere = baseline::other_runners(&against.records, k);
        if !elsewhere.is_empty() {
            stranded
                .entry(elsewhere)
                .or_default()
                .push(describe_series(k));
        }
    }
    for (runners, series) in &stranded {
        let runners: BTreeSet<&str> = runners.iter().map(String::as_str).collect();
        eprintln!(
            "  warning: baseline `{}` holds {} only for runner class {}. Runner classes are \
             never compared with each other.",
            against.name,
            series.join(", "),
            quoted(&runners)
        );
    }

    println!(
        "\n  compared against baseline `{}` ({})\n",
        against.name,
        against.path.display()
    );
    // No trend: a baseline is one point, not a history. No credit line
    // either: it says the numbers live in git notes, which these do not, and
    // a terminal report is not headed for a stranger's pull request.
    print!(
        "{}",
        compare::markdown(&comparison, &compare::Trend::new(), gates, false)
    );
    // In the report itself, not only in the warning above it: the table has
    // no way to mark a row whose samples did the wrong work, and a check
    // that fails fast is exactly what reads as a large improvement.
    if !failing.is_empty() {
        println!(
            "\n**Check failed, so this comparison is not evidence of an improvement:** {}. \
             Those numbers come from samples that did the wrong work.",
            labels(failing)
        );
    }
    if !gaps.is_empty() {
        println!("\nNot gated: {}", describe_gaps(&gaps));
    }
    Against {
        comparison,
        gaps,
        measured: keys,
    }
}

fn describe_gaps(gaps: &[(compare::Key, baseline::Gap)]) -> String {
    gaps.iter()
        .map(|(k, why)| format!("{} ({why})", describe_series(k)))
        .collect::<Vec<_>>()
        .join(", ")
}

fn quoted(names: &BTreeSet<&str>) -> String {
    names
        .iter()
        .map(|n| format!("`{}`", compare::escape_control(n)))
        .collect::<Vec<_>>()
        .join(", ")
}

/// A series for a message, spelled — and escaped — as the comparison report
/// spells one.
fn describe_series(key: &compare::Key) -> String {
    compare::describe(key)
}

/// Fail on a regression against a baseline, for `--gate`.
///
/// Comparing nothing fails, as it does in `tak compare`: the baseline was
/// named and loaded, so nothing to compare means a runner or tool mismatch,
/// or a run without valgrind, and a gate that passed then would pass every
/// edit: `git bisect run` would blame the wrong commit. `allow_empty` waives
/// that case alone, with a warning, exactly as it does for `tak compare`.
///
/// Stricter than `tak compare` about any one series: a gate that checked only
/// some of what this run counted has not passed, `allow_empty` or not. And a
/// failed check fails the gate, since a subject that stopped doing its work
/// retires fewer instructions, which is the one direction the gate lets
/// through.
///
/// Each series is held to its own gate, as `tak compare` holds it: the same
/// [`compare::Gates`], so a `min_delta` floor applies and a report-only
/// benchmark never fails this — not by regressing, not by a gap, and not by a
/// failed check, which the report still flags.
fn gate_against(
    against: &Baseline,
    compared: &Against,
    failing: &[FailedCheck],
    gates: &compare::Gates,
) -> Result<()> {
    let failing: Vec<&FailedCheck> = failing
        .iter()
        .filter(|f| gates.get(&f.bench, &f.tool).enabled)
        .collect();
    if !failing.is_empty() {
        bail!(
            "check failed, so nothing is gated against baseline `{}`: {}",
            against.name,
            labels(failing)
        );
    }
    let comparison = &compared.comparison;
    let enabled = |bench: &str, tool: &str| gates.get(bench, tool).enabled;
    // Report-only never fails, so a run of nothing else passes, counted or
    // not. It says so on stderr as well as in the table: an exit status of 0
    // from `--gate` otherwise reads, to a script, as "checked and fine".
    // Asked ahead of the gaps, which only ever hold gated series, so this was
    // already the outcome whenever it applied; asking first keeps the
    // `allow_empty` waiver below from claiming a pass it did not grant.
    let nothing_gated = |why: &str| {
        eprintln!(
            "  note: nothing was gated against baseline `{}`: {why}",
            against.name
        );
        Ok(())
    };
    if !compared.measured.iter().any(|k| enabled(&k.0, &k.1)) {
        return nothing_gated("every benchmark measured is report-only");
    }
    // Decided in `report_against`, which has already said so in the report.
    // Before the gaps: an empty comparison is one gap per gated series, and
    // failing on those would leave the setting nothing to waive.
    if comparison.allowed_empty {
        warn_allowed_empty(&format!(
            "nothing was compared against baseline `{}`",
            against.name
        ));
        return Ok(());
    }
    if !compared.gaps.is_empty() {
        // Each series carries its own reason, because the remedy differs:
        // install valgrind or turn counters back on for one, save the
        // baseline on this runner class for another.
        bail!(
            "cannot gate against baseline `{}`: {}",
            against.name,
            describe_gaps(&compared.gaps)
        );
    }
    if !comparison
        .changes
        .iter()
        .any(|c| c.metric == compare::GATED_METRIC)
    {
        bail!(
            "nothing to gate: no instruction count was measured both in this run and in \
             baseline `{}`",
            against.name
        );
    }
    if !comparison
        .changes
        .iter()
        .any(|c| c.metric == compare::GATED_METRIC && enabled(&c.bench, &c.tool))
    {
        return nothing_gated("every benchmark compared by instruction count is report-only");
    }
    let regressions = comparison.regressions(gates);
    if regressions.is_empty() {
        return Ok(());
    }
    // Worded as `tak compare` words it, so one grep matches both.
    if comparison.gated_uniformly(gates) {
        let floor = match gates.global.min_delta {
            0 => String::new(),
            n => format!(" and {n} instructions"),
        };
        bail!(
            "{} benchmark(s) regressed by more than {}%{floor} against baseline `{}`",
            regressions.len(),
            gates.global.pct,
            against.name
        );
    }
    bail!(
        "{} benchmark(s) regressed beyond their gate against baseline `{}`",
        regressions.len(),
        against.name
    )
}

/// Save records as a local baseline and say where they went.
fn save_baseline(store: &Store, name: &str, records: &[Record]) -> Result<()> {
    if records.is_empty() {
        return Ok(());
    }
    let path = store.save(name, records)?;
    println!(
        "\n  saved {} measurement(s) to baseline `{name}` ({})",
        records.len(),
        path.display()
    );
    println!("  compare against it with: tak run --baseline {name}");
    Ok(())
}

/// Each declared metric that could not be taken, as `bench (subject)
/// \`name\``. One list for every path that stores a run, `tak run` and
/// `tak backfill --commits` alike, so that none of them keeps a run with a
/// declared metric silently missing.
fn failed_metrics(measured: &[Measured]) -> Vec<String> {
    measured
        .iter()
        .flat_map(|m| {
            m.custom
                .iter()
                .filter(|(_, v)| v.is_none())
                .map(|(name, _)| format!("{} `{name}`", label(m)))
        })
        .collect()
}

/// How a measured subject is named in messages: the benchmark, plus the
/// subject when it is one of several.
fn label(m: &Measured) -> String {
    if m.subject.name == SELF_TOOL {
        m.bench.clone()
    } else {
        format!("{} ({})", m.bench, m.subject.name)
    }
}

/// A metric value for the summary: whole numbers without a fraction, since
/// most custom metrics are sizes and counts, and anything else as written.
/// Never negative: `parse_metric_value` refuses a sign and a size has none.
/// Past 1e15 the fraction test says nothing, so large values print as-is.
fn metric_value(v: f64) -> String {
    if v.fract() == 0.0 && v < 1e15 {
        format!("{v:.0}")
    } else {
        v.to_string()
    }
}

/// Append every record in one write, so a run is stored whole or not at all.
fn record_all(records: &[Record]) -> Result<()> {
    if records.is_empty() {
        return Ok(());
    }
    let sha = notes::rev_parse("HEAD").context("not in a git repository")?;
    notes::append(&sha, records)?;
    println!(
        "\n  recorded {} measurement(s) to {} for {}",
        records.len(),
        notes::NOTES_REF,
        &sha[..12]
    );
    println!("  push with: tak push");
    Ok(())
}

/// Measure one benchmark's subjects, interleaved, and print them.
///
/// A single-command benchmark fails as a whole, as it always has. In a
/// multi-subject one a failing subject is reported and dropped, and its name
/// is returned alongside the subjects that succeeded.
fn measure_bench(
    bench: &str,
    subjects: &[Subject],
    multi: bool,
    seed: u64,
    opts: &RunOpts,
    settings: &Settings,
) -> Result<(Vec<Measured>, Vec<String>)> {
    measure_bench_vetted(bench, subjects, multi, seed, opts, settings, &|_| Ok(()))
}

/// [`measure_bench`], with `vet` asked about each subject once its setup has
/// succeeded; see [`measure::Observer::set_up`].
fn measure_bench_vetted(
    bench: &str,
    subjects: &[Subject],
    multi: bool,
    seed: u64,
    opts: &RunOpts,
    settings: &Settings,
    vet: &dyn Fn(&Subject) -> Result<()>,
) -> Result<(Vec<Measured>, Vec<String>)> {
    if multi {
        println!(
            "  {bench}: {} subjects, interleaved (--seed {seed})",
            subjects.len()
        );
    }
    let bench_seed = measure::seed_for(seed, bench);
    // Each subject's version is asked for inside the run, after its setup
    // and before any warmup; see `measure::interleaved_with_versions`.
    let (results, versions) = if opts.no_progress {
        let mut quiet = measure::Quiet;
        let mut obs = Vetted {
            inner: &mut quiet,
            subjects,
            vet,
        };
        measure::interleaved_with_versions(subjects, bench_seed, settings, &mut obs)
    } else {
        let names = subjects.iter().map(|s| s.name.clone()).collect();
        let mut bar = tak_cli::progress::Bar::new(bench, names);
        let mut obs = Vetted {
            inner: &mut bar,
            subjects,
            vet,
        };
        let r = measure::interleaved_with_versions(subjects, bench_seed, settings, &mut obs);
        bar.finish();
        r
    };
    // A failed version costs only the label: warned about once the progress
    // bar is out of the way, and exported as null.
    let versions: Vec<Option<Option<String>>> = subjects
        .iter()
        .zip(versions)
        .map(|(s, v)| {
            v.map(|r| match r {
                Ok(v) => Some(v),
                Err(e) => {
                    let label = if multi {
                        format!("{bench} ({})", s.name)
                    } else {
                        bench.to_string()
                    };
                    eprintln!("  warning: {label}: version_cmd failed, version unknown: {e:#}");
                    None
                }
            })
        })
        .collect();
    let mut measured = Vec::new();
    let mut failed = Vec::new();
    for ((s, result), version) in subjects.iter().zip(results).zip(versions) {
        let samples = match result {
            Ok(samples) => samples,
            Err(e) if !multi => return Err(e),
            Err(e) => {
                eprintln!("  error: {bench} ({}) dropped: {e:#}", s.name);
                failed.push(format!("{bench} ({})", s.name));
                continue;
            }
        };
        let mut metrics = measure::stats(&samples.times);
        let label = if multi {
            format!("{bench} ({})", s.name)
        } else {
            bench.to_string()
        };
        for w in measure::warnings(&samples.times) {
            eprintln!("  warning: {label}: {w}");
        }
        // A failed check is reported, not fatal: how often a subject gets
        // the work wrong is exactly what the check is there to find out.
        let checks = s
            .check
            .as_ref()
            .map(|_| (samples.passed(), samples.checks.len()));
        if let Some((passed, total)) = checks
            && passed < total
        {
            // Which samples, so a failure can be matched to its time in the
            // export; the first few are enough when nearly all of them fail.
            const LISTED: usize = 8;
            let failed: Vec<usize> = samples
                .checks
                .iter()
                .enumerate()
                .filter(|(_, ok)| !**ok)
                .map(|(i, _)| i + 1)
                .collect();
            let mut which = failed
                .iter()
                .take(LISTED)
                .map(usize::to_string)
                .collect::<Vec<_>>()
                .join(", ");
            if failed.len() > LISTED {
                which.push_str(", …");
            }
            eprintln!(
                "  warning: {label}: check failed after {} of {total} samples (sample {which}); first: {}",
                failed.len(),
                samples.first_failure.as_deref().unwrap_or("(no detail)")
            );
        }
        let (count_failed, profile) = if s.counters && !opts.no_counters {
            let (counted, profile) = count_into(
                &mut metrics,
                s,
                settings,
                opts.profile_dir.is_some(),
                &|| vet(s),
            );
            (!counted, profile)
        } else {
            (false, None)
        };
        // Independent of --no-counters, which is about instruction counting.
        // A subject that asked for allocations gets them, or a note saying
        // why not. Never part of `count_failed`: allocations do not gate, so
        // failing to count them leaves no gate unchecked, and the rest of
        // the measurement is recorded without them. Only `vet` refusing a
        // DHAT run is fatal, as it is before any sample: the subject no
        // longer runs from where it may.
        if s.allocations
            && let Err(e) = allocations_into(&mut metrics, &label, s, settings, &|| vet(s))
        {
            if !multi {
                return Err(e);
            }
            eprintln!("  error: {label} dropped: {e:#}");
            failed.push(label.clone());
            continue;
        }
        // Last, once the subject is done running: setup or the samples may
        // be what produced the file or output being measured. A failure is
        // reported here and fails the run in `finish`, after every other
        // benchmark has been measured, so one broken script does not throw
        // away the rest of a long run.
        let mut custom = BTreeMap::new();
        for (name, source) in &s.metrics {
            // Vetted again right before, as each sample is: the samples
            // just run can have changed what the metric's path resolves to.
            let value = match vet(s).and_then(|()| measure::custom_metric(source, s, settings)) {
                Ok(v) => {
                    metrics.insert(name.clone(), v);
                    Some(v)
                }
                Err(e) => {
                    eprintln!("  error: {label}: metric `{name}` failed: {e:#}");
                    None
                }
            };
            custom.insert(name.clone(), value);
        }

        if multi {
            // One line per subject, in the order of a quick read: the floor
            // first, since that is the robust estimator, then the spread.
            // The command is in tak.toml; repeating it here buried the numbers.
            // Instruction counts, when a subject opted in, stay on its line.
            let mut count = metrics
                .get("instructions")
                .map_or(String::new(), |i| format!("  instructions {i:.0}"));
            if let (Some(blocks), Some(bytes)) =
                (metrics.get("alloc_blocks"), metrics.get("alloc_bytes"))
            {
                count.push_str(&format!("  allocs {blocks:.0} ({bytes:.0} bytes)"));
            }
            let checked = checks.map_or(String::new(), |(p, t)| format!("  checks {p}/{t}"));
            let extra: String = custom
                .iter()
                .filter_map(|(k, v)| v.map(|v| format!("  {k} {}", metric_value(v))))
                .collect();
            println!(
                "    {:<width$}  min {:>9.2}  p50 {:>9.2}  mean {:>9.2} ± {:<8.2} max {:>9.2} ms  n={}{checked}{count}{extra}",
                s.name,
                metrics["wall_min_ms"],
                metrics["wall_p50_ms"],
                metrics["wall_mean_ms"],
                metrics["wall_stddev_ms"],
                metrics["wall_max_ms"],
                samples.times.len(),
                width = subjects.iter().map(|s| s.name.len()).max().unwrap_or(0),
            );
        } else {
            println!("  {bench}  {}", s.cmd.join(" "));
        }
        for (k, v) in metrics.iter().filter(|_| !multi) {
            if k == "wall_n" {
                continue;
            }
            // Counts, not measurements: a fraction would be noise.
            if k == "instructions" || k.starts_with("alloc_") {
                println!("  {k:<16} {v:>14.0}");
            } else if s.metrics.contains_key(k) {
                println!("  {k:<16} {:>14}", metric_value(*v));
            } else {
                println!("  {k:<16} {v:>14.2}");
            }
        }
        if let Some((passed, total)) = checks.filter(|_| !multi) {
            println!("  {:<16} {:>14}", "checks", format!("{passed}/{total}"));
        }

        let tool = record_tool(multi, s);
        measured.push(Measured {
            bench: bench.to_string(),
            subject: s.clone(),
            version: version.clone(),
            samples,
            custom,
            count_failed,
            profile,
            record: Record {
                v: SCHEMA_VERSION,
                bench: bench.to_string(),
                tool,
                // The field backfill fills from a release tag, and meant for
                // competitors: which of their releases a point measured.
                version: version.flatten(),
                runner: runner_class(settings),
                ts: now_rfc3339(),
                metrics,
            },
        });
    }
    Ok((measured, failed))
}

/// An observer that passes everything on, and asks `vet` about a subject
/// once every setup has run and again before each of its samples.
struct Vetted<'a> {
    inner: &'a mut dyn measure::Observer,
    subjects: &'a [Subject],
    vet: &'a dyn Fn(&Subject) -> Result<()>,
}

impl measure::Observer for Vetted<'_> {
    fn planned(&mut self, remaining: &[u64]) {
        self.inner.planned(remaining);
    }
    fn setting_up(&mut self, subject: usize) {
        self.inner.setting_up(subject);
    }
    fn set_up(&mut self, subject: usize) -> Result<()> {
        self.inner.set_up(subject)?;
        (self.vet)(&self.subjects[subject])
    }
    fn before_run(&mut self, subject: usize) -> Result<()> {
        self.inner.before_run(subject)?;
        (self.vet)(&self.subjects[subject])
    }
    fn started(&mut self, subject: usize) {
        self.inner.started(subject);
    }
    fn finished(&mut self, subject: usize, elapsed: std::time::Duration) {
        self.inner.finished(subject, elapsed);
    }
    fn dropped(&mut self, subject: usize) {
        self.inner.dropped(subject);
    }
}

/// The `tool` a subject's records are stored under.
///
/// TAK_TOOL only ever renames the single-command series. Keyed on the
/// benchmark's shape rather than the subject's name, so a declared subject
/// can never be recorded as anything but itself. Profiles are named by it
/// too, so two `TAK_TOOL`s measured into one `--profile-dir` are two files,
/// not one overwriting the other under `self`.
fn record_tool(multi: bool, s: &Subject) -> String {
    if multi {
        s.name.clone()
    } else {
        std::env::var("TAK_TOOL").unwrap_or_else(|_| SELF_TOOL.into())
    }
}

/// Add a subject's instruction count to its metrics, warning rather than
/// failing when it cannot be had: the timing already collected is still good.
///
/// False only when valgrind was there and the count still failed. A missing
/// valgrind is not a failure: nothing on this host could be counted, and
/// `--gate` already has nothing to check then.
///
/// With `profile`, also returns the cachegrind profile behind the count.
/// `vet` is asked before each counted run; see
/// [`measure::subject_instructions_vetted`].
fn count_into(
    metrics: &mut BTreeMap<String, f64>,
    s: &Subject,
    settings: &Settings,
    profile: bool,
    vet: &dyn Fn() -> Result<()>,
) -> (bool, Option<Vec<u8>>) {
    let counted = if profile {
        measure::subject_profile_vetted(s, settings, vet).map(|c| c.map(|(c, p)| (c, Some(p))))
    } else {
        measure::subject_instructions_vetted(s, settings, vet).map(|c| c.map(|c| (c, None)))
    };
    match counted {
        Ok(Some((c, profile))) => {
            // The count stands without its profile; only the explanation is
            // lost, and saying so beats a missing file nobody notices.
            let profile = match profile {
                Some(Ok(raw)) => Some(raw),
                Some(Err(e)) => {
                    eprintln!(
                        "warning: {}: instruction count kept, but its profile was not: {e:#}",
                        s.name
                    );
                    None
                }
                None => None,
            };
            metrics.insert("instructions".into(), c.min as f64);
            if c.is_suspect() {
                eprintln!(
                    "warning: instruction count varied {:.2}% across {} runs. \
                     The metric is deterministic, so this means the command \
                     itself does environment-dependent work (an update check, \
                     a cache it populates on first run, DNS). Its counts are \
                     not a usable gate until that is removed.",
                    c.spread_pct(),
                    c.runs
                );
            }
            (true, profile)
        }
        Ok(None) => {
            eprintln!(
                "note: valgrind not found — recording timing only. \
                 Instruction counts are the only gate-able metric; on macOS/Windows \
                 run tak in a Linux container to get them."
            );
            (true, None)
        }
        // Valgrind exists but the measurement failed. Say so rather than
        // blaming a missing install, and keep the timing we did collect.
        Err(e) => {
            eprintln!("warning: instruction counting failed: {e}");
            (false, None)
        }
    }
}

/// Add a subject's heap allocations to its metrics, warning rather than
/// failing when they cannot be had, as [`count_into`] does.
///
/// The one error returned is `vet` refusing a run, which is not a failed
/// measurement but a subject that must not run at all. Told apart by
/// remembering the refusal, since the measurement reports both the same way.
fn allocations_into(
    metrics: &mut BTreeMap<String, f64>,
    label: &str,
    s: &Subject,
    settings: &Settings,
    vet: &dyn Fn() -> Result<()>,
) -> Result<()> {
    let refused = std::cell::RefCell::new(None);
    let checked = || {
        vet().inspect_err(|e| {
            refused.replace(Some(format!("{e:#}")));
        })
    };
    let result = measure::subject_allocations_vetted(s, settings, &checked);
    if let Some(why) = refused.take() {
        bail!("{why}");
    }
    match result {
        Ok(Some(a)) => {
            for (k, v) in a.min.metrics() {
                metrics.insert(k.into(), v as f64);
            }
            // Recorded anyway: it is what DHAT reported, and nothing gates
            // on it. The warning is what keeps a zero from being believed.
            if a.saw_nothing() {
                eprintln!(
                    "  warning: {label}: DHAT saw no heap allocations. It counts only \
                     calls it can intercept, so a statically linked binary or one with \
                     its own allocator (jemalloc, mimalloc) reports zero however much \
                     it allocates."
                );
            } else if a.is_suspect() {
                eprintln!(
                    "  warning: {label}: heap allocation totals varied {:.2}% across {} runs. \
                     A hermetic command repeats them exactly, so this one does \
                     environment-dependent work (a cache it fills on first run, an \
                     update check, DNS).",
                    a.totals_spread_pct(),
                    a.runs
                );
            } else if a.peak_is_unsteady() {
                eprintln!(
                    "  note: {label}: peak heap varied {:.2}% across {} runs while the \
                     totals did not. Threads that allocate at once reach a different peak \
                     depending on how valgrind interleaves them; the minimum is recorded.",
                    a.peak_spread_pct(),
                    a.runs
                );
            }
        }
        Ok(None) => {
            eprintln!("  note: {label}: valgrind not found, so heap allocations were not measured.")
        }
        Err(e) => eprintln!("  warning: {label}: allocation counting failed: {e:#}"),
    }
    Ok(())
}

fn cmd_history(rev: String, remote: String) -> Result<()> {
    let sha = notes::rev_parse(&rev).context("not in a git repository")?;
    let recs = notes::read(Some(&remote), &sha)?;
    if recs.is_empty() {
        println!("no measurements recorded for {}", &sha[..12]);
        return Ok(());
    }
    println!("{} measurement(s) for {}\n", recs.len(), &sha[..12]);
    for r in recs {
        let ins = r
            .metrics
            .get("instructions")
            .map(|v| format!("{v:.0}"))
            .unwrap_or_else(|| "-".into());
        let wall = r
            .metrics
            .get("wall_min_ms")
            .map(|v| format!("{v:.2}ms"))
            .unwrap_or_else(|| "-".into());
        // Escaped: the main-branch workflow reads this output line by line to
        // prove a commit's counts were recorded, and a name holding a newline
        // could forge a line of its own.
        println!(
            "  {:<16} {:<10} {:<22} instructions={:<14} wall_min={}",
            compare::escape_control(&r.bench),
            compare::escape_control(&r.tool),
            compare::escape_control(&r.runner),
            ins,
            wall
        );
    }
    Ok(())
}

/// `tak log`'s options, gathered so they travel as one value.
struct LogOpts {
    rev: String,
    limit: usize,
    bench: Vec<String>,
    html: Option<std::path::PathBuf>,
    remote: String,
}

/// Print, or write as a page, the series along `rev`'s first-parent history.
fn cmd_log(opts: LogOpts, settings: &Settings) -> Result<()> {
    if opts.limit == 0 {
        bail!("-n must be at least 1");
    }
    // Resolved first so a bad revision names itself, rather than surfacing as
    // whatever `git log` makes of it after a network round trip.
    notes::rev_parse(&opts.rev).with_context(|| format!("cannot resolve {}", opts.rev))?;
    // Never fatal, as in `notes::read`: offline, or a remote with no notes
    // yet, falls back to the local ref.
    let _ = notes::fetch(&opts.remote);
    let mut enough = tak_cli::report::Enough::new(opts.limit, &opts.bench);
    let walked = notes::log_until(&opts.rev, |c| enough.after(c))?;
    // Whether the walk stopped at a graft, not whether anything in the clone
    // is shallow: the notes fetch above is shallow by design.
    let shallow = walked
        .last()
        .is_some_and(|oldest| notes::is_shallow_boundary(&oldest.sha));
    let history = tak_cli::report::build(walked, opts.limit, &opts.bench, shallow)?;

    let Some(path) = opts.html else {
        print!(
            "{}",
            tak_cli::report::markdown(&history, &opts.rev, settings.credit)
        );
        return Ok(());
    };
    let page = tak_cli::report::html(
        &history,
        &opts.rev,
        repo_from_origin().as_deref(),
        settings.credit,
    );
    std::fs::write(&path, page).with_context(|| format!("could not write {}", path.display()))?;
    println!(
        "wrote {}: {} series over {} recorded commit(s)",
        path.display(),
        history.series.len(),
        history.commits.len()
    );
    Ok(())
}

/// How many commits of trunk history the sparkline covers.
///
/// A constant rather than a setting: it changes how a picture looks, not what
/// the gate decides, and the registry should hold things worth a project
/// arguing about. Twenty is enough to see a step change and short enough that
/// the column stays narrow in a comment.
const TREND_COMMITS: usize = 20;

/// Recent values for each series along `base`'s first-parent history, oldest
/// first, with `head`'s own value appended.
///
/// Reading the trunk and then the pull request in one line is the point: a
/// number that has drifted for weeks and a number this branch just moved look
/// nothing alike, and the base-versus-head columns alone cannot tell them apart.
fn gather_trend(base: &str, head_sha: &str, head_records: &[Record]) -> Result<compare::Trend> {
    let commits = notes::rev_list(base, TREND_COMMITS)?;
    // rev-list is newest first; a trend reads oldest to newest.
    let mut walked = Vec::with_capacity(commits.len());
    for sha in commits.iter().rev() {
        walked.push((sha.clone(), notes::read(None, sha)?));
    }
    Ok(compare::build_trend(&walked, head_sha, head_records))
}

/// The floor, for the one-line error `compare` and `detect` fail with when
/// every series is at the global gate: ` and N instructions`, or nothing.
///
/// Shared so the two commands word the same gate the same way; a script that
/// learns one error learns the other.
fn floor_suffix(gate: &compare::Gate) -> String {
    match gate.min_delta {
        0 => String::new(),
        n => format!(" and {n} instructions"),
    }
}

/// Say that a comparison of nothing passed because `allow_empty` let it.
///
/// Shared by `compare`, `detect` and `run --baseline --gate`, so the three word
/// it alike and a log search for one finds them all. The report already says
/// so, but a report is usually redirected to a file or a comment, and a pass
/// that examined nothing should be visible where the job's own output is read.
///
/// Stderr, never stdout: workflows redirect stdout to the report whose first
/// line scripts classify a run by. Under GitHub Actions the one line is a
/// `::warning::` workflow command instead of plain text. That is still an
/// `eprintln!` rather than a logging layer: the runner reads workflow commands
/// from both of a step's streams, so the same line shows in the log as a
/// warning and as an annotation on the run's summary page, where a green check
/// that compared nothing gets seen by people who never open the log. Not both
/// forms: in the log the annotation already reads as a warning, and printing
/// the plain line too would say it twice.
fn warn_allowed_empty(what: &str) {
    let message = format!("{what}; passing because `allow_empty` is on");
    if std::env::var_os("GITHUB_ACTIONS").is_some() {
        eprintln!("::warning::tak: {}", workflow_escape(&message));
    } else {
        eprintln!("warning: {message}");
    }
}

/// Escape a workflow command's message as `@actions/core` does. A revision or
/// baseline name is interpolated, and a raw `%` or line break in one would be
/// decoded as an escape or end the command early.
fn workflow_escape(text: &str) -> String {
    text.replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

/// Compare `rev` against `base`, print the report, and gate on it.
///
/// `cli` beside `settings`: the base's gate is resolved afresh under the same
/// flags, so they have to arrive unresolved as well.
#[allow(clippy::too_many_arguments)]
fn cmd_compare(
    base: String,
    rev: String,
    remote: String,
    no_gate: bool,
    accept_flags: Vec<String>,
    cli: &CliLayer,
    settings: &Settings,
) -> Result<()> {
    // The working tree's policy is loaded first, and still has to be valid:
    // it is what this change will gate with once merged, and a bad gate should
    // fail here, on its own pull request, before anything is fetched.
    let proposed = Policy {
        gates: compare_gates(settings, None)?,
        accept_trailers: settings.accept_trailers,
        allow_empty: settings.allow_empty,
    };
    // The commit itself is needed, not only its notes: the gate is read out of
    // its tree. A workflow that found the merge base has already fetched it.
    let base_sha = notes::rev_parse(&base).with_context(|| {
        format!("cannot resolve {base}; tak compare needs the base commit locally, so fetch it")
    })?;
    let head_sha = notes::rev_parse(&rev).with_context(|| format!("cannot resolve {rev}"))?;
    let (policy, from) = base_policy(&base_sha, cli)?;
    let gates = &policy.gates;

    let mut accepted = Acceptances::default();
    for name in &accept_flags {
        accepted.add_name(name, accept::Source::Flag)?;
    }
    // Read either way; only honoured when the setting says so. The commits
    // under comparison are the change being gated, so by default their own
    // trailers must not be able to waive the gate — but an author whose
    // trailer was ignored should be told, not left guessing.
    let log = notes::trailers(&base_sha, &head_sha, accept::TRAILER, false);
    let mut ignored = Acceptances::default();
    if policy.accept_trailers {
        // Fatal when honoured, unlike the trend below. Carrying on would still
        // fail closed, but on a regression the author accepted, with a report
        // that says nothing about why the acceptance was not seen.
        let log = log.with_context(|| {
            format!(
                "cannot read {} trailers from {base}..{rev}",
                accept::TRAILER
            )
        })?;
        accepted.add_trailer_log(&log);
    } else if let Ok(log) = log {
        // Not fatal: nothing the gate decides depends on it.
        ignored.add_trailer_log(&log);
    }

    // One fetch, not two: `read` refreshes from the remote, and doing it twice
    // doubles the round trip for the same ref.
    let base_records = notes::read(Some(&remote), &base_sha)?;
    let head_records = notes::read(None, &head_sha)?;

    let mut comparison = compare::compare(&base_records, &head_records)
        .with_accepted(accepted)
        .with_ignored_trailers(ignored);
    // Never fatal: a shallow checkout has no history to walk, and a missing
    // sparkline is a smaller loss than a failed gate.
    let trend = gather_trend(&base_sha, &head_sha, &head_records).unwrap_or_default();
    // Beside the verdict, where a pull request that edits a gate on purpose
    // looks when the gate it wrote did not apply.
    let at = detect::short(&base_sha);
    let measured = base_records
        .iter()
        .chain(&head_records)
        .map(|r| (r.bench.clone(), r.tool.clone()))
        .collect();
    let changed = proposed.changes_from(&policy, &measured);
    comparison.gate_source = compare::gate_source(from.as_deref(), at, &changed);
    // The base's, never the working tree's: a pull request that could turn this
    // on for itself could pass a comparison that never ran. `--no-gate` wins,
    // as it says it does, and then there is no waiver to name.
    comparison.allowed_empty = comparison.is_empty() && policy.allow_empty && !no_gate;
    print!(
        "{}",
        compare::markdown(&comparison, &trend, gates, settings.credit)
    );

    if no_gate {
        return Ok(());
    }
    // An empty comparison has no regressions, so the check below would pass
    // it — and a gate that passed because it never ran reads exactly like one
    // that ran clean. Opting out is a setting, not the default, because the
    // usual causes are a broken workflow rather than a state worth accepting.
    // Opted out, it still says so: a pass that compared nothing must not look
    // like one that compared everything, to a person or to a log search.
    if comparison.is_empty() {
        if !policy.allow_empty {
            bail!(
                "nothing was compared: no series was measured on both {base} and {rev}. \
                 Either one side has no measurements recorded (the base predates \
                 adopting tak, or its notes were never pushed or fetched), or the two \
                 were measured on different runner classes, which are deliberately \
                 not comparable. Pass --allow-empty, or set `[gate] allow_empty = true` \
                 in the base's tak.toml, to accept this, as on the first pull request \
                 after adopting tak or across a runner-class migration"
            )
        }
        warn_allowed_empty(&format!(
            "nothing was compared: no series was measured on both {base} and {rev}"
        ));
        return Ok(());
    }
    // Accepted regressions are reported above and do not count here.
    let regressions = comparison.failures(gates);
    if regressions.is_empty() {
        return Ok(());
    }
    // A non-zero exit is the gate. The table above already says which and by
    // how much, so this only has to be unambiguous about why the job failed.
    if comparison.gated_uniformly(gates) {
        let floor = floor_suffix(&gates.global);
        bail!(
            "{} benchmark(s) regressed by more than {}%{floor}",
            regressions.len(),
            gates.global.pct
        )
    }
    bail!(
        "{} benchmark(s) regressed beyond their gate",
        regressions.len()
    )
}

/// Print which functions account for the instruction-count changes between
/// two sets of profiles.
///
/// Settings are not read: nothing here measures or gates, and the credit line
/// is left to `tak compare`, whose report this is meant to sit under.
fn cmd_explain(base: &Path, head: &Path, top: usize) -> Result<()> {
    if top == 0 {
        bail!("--top must be at least 1");
    }
    let (pairs, unpaired) = tak_cli::profile::load(base, head)?;
    // Local notes only, no fetch: the check is a warning, and a report that
    // waits on the network, or fails without one, costs more than it adds.
    let recorded = |o: &tak_cli::profile::Origin| {
        let records = notes::read(None, o.commit.as_deref()?).ok()?;
        records
            .iter()
            .filter(|r| r.bench == o.bench && r.tool == o.subject && r.runner == o.runner)
            .filter_map(|r| r.metrics.get(compare::GATED_METRIC))
            .map(|v| *v as u64)
            .min()
    };
    print!(
        "{}",
        tak_cli::profile::markdown(&pairs, &unpaired, top, &recorded)
    );
    Ok(())
}

/// Walk `rev`'s recorded history, print the steps, and gate on the newest.
fn cmd_detect(
    rev: String,
    window: usize,
    remote: String,
    no_gate: bool,
    accept_flags: Vec<String>,
    settings: &Settings,
) -> Result<()> {
    // Up front, before any git work: one recorded commit has no step to find,
    // and a run that quietly compared nothing would read as a pass.
    if window < 2 {
        bail!("--window must be at least 2: a step needs two recorded commits");
    }
    // The same per-series gates as `tak compare`, loaded before any git work
    // for the same reason: a bad gate should fail before anything is fetched.
    let gates = compare_gates(settings, None)?;
    // Checked before any git work too: an empty `--accept` is an unset CI
    // variable, and finding out after the walk wastes it.
    let mut flags = Acceptances::default();
    for name in &accept_flags {
        flags.add_name(name, accept::Source::Flag)?;
    }
    let head = notes::rev_parse(&rev).with_context(|| format!("cannot resolve {rev}"))?;
    // Never fatal, as for every read path: offline, or no notes pushed yet,
    // falls back to what is recorded locally.
    let _ = notes::fetch(&remote);

    let (walked, cutoff) = detect::gather(&head, window)?;
    let mut found = detect::analyze(&walked, &gates);
    found.cutoff = cutoff;
    found.allow_empty = settings.allow_empty;
    found.no_gate = no_gate;

    // Trailers from each step's own range, `from..head` along the first
    // parent: the commits that landed on this branch between the step's two
    // points. Read either way, honoured only when the setting says so — the
    // same rule as `tak compare`, so an ignored trailer is reported rather
    // than silently doing nothing.
    let froms: BTreeSet<&str> = found.latest.iter().map(|s| s.from.as_str()).collect();
    let mut logs = BTreeMap::new();
    let mut ignored = Acceptances::default();
    for from in froms {
        let log = notes::trailers(from, &head, accept::TRAILER, true);
        if settings.accept_trailers {
            // Fatal when honoured, as in compare: carrying on would fail a
            // step its trailer accepted, with nothing saying why.
            let log = log.with_context(|| {
                format!(
                    "cannot read {} trailers from {}..{}",
                    accept::TRAILER,
                    detect::short(from),
                    detect::short(&head)
                )
            })?;
            logs.insert(from.to_string(), log);
        } else if let Ok(log) = log {
            ignored.add_trailer_log(&log);
        }
    }
    found.accept(&flags, &logs);
    found.ignored_trailers = ignored;
    print!("{}", detect::markdown(&found, settings.credit));

    // Passing here would claim a check that never ran, so it takes an explicit
    // waiver: `allow_empty` for this case alone, or --no-gate for everything.
    if found.empty_fails() {
        bail!(
            "nothing was compared at {}; pass --allow-empty, or set `[gate] allow_empty = \
             true` in tak.toml, if that is expected",
            detect::short(&head)
        );
    }
    // Waived, but said out loud, as in compare. `--no-gate` asked for a report
    // that never fails and gets no warning for doing what it was told.
    if found.nothing_compared() && found.allow_empty && !no_gate {
        warn_allowed_empty(&format!("nothing was compared at {}", detect::short(&head)));
    }
    let failures = found.failures();
    if failures.is_empty() || no_gate {
        return Ok(());
    }
    // As with compare: the report already names which and by how much, so this
    // only has to be unambiguous about why the job failed — and reads as it did
    // before per-benchmark gates when every series is at the global one.
    if found.uniform() {
        let floor = floor_suffix(&gates.global);
        bail!(
            "{} benchmark(s) stepped up by more than {}%{floor} at {}",
            failures.len(),
            gates.global.pct,
            detect::short(&head)
        )
    }
    bail!(
        "{} benchmark(s) stepped beyond their gate at {}",
        failures.len(),
        detect::short(&head)
    )
}

/// The gate for every series: `[gate]` and its flags, overridden per benchmark
/// by the `tak.toml` in the working tree.
///
/// The working tree's file is right for `tak detect`, which runs on the merged
/// branch, and for `tak run --baseline`, which is local. `tak compare`
/// enforces [`base_policy`] instead and uses this only to tell a pull request
/// that its own file would gate differently.
///
/// Loaded before any notes are read, so a bad gate fails the command before it
/// has fetched anything. No `tak.toml` is fine — every series gets the global
/// gate, as before per-benchmark gates existed — but one that does not parse
/// is an error rather than a quiet fallback to a gate the file did not ask for.
///
/// `config` is `tak run --config`, for `tak run --baseline`: the file that run
/// measures from is the one whose gates apply to it.
fn compare_gates(settings: &Settings, config: Option<&Path>) -> Result<compare::Gates> {
    let global = global_gate(settings)?;
    let found = match config {
        Some(path) => Some((path.to_path_buf(), Config::load(path)?)),
        None => Config::find(&std::env::current_dir()?)?,
    };
    Ok(match found {
        Some((_, cfg)) => cfg.gates(global),
        None => compare::Gates::uniform(global),
    })
}

/// Everything a `tak.toml` can say about whether `tak compare` fails.
struct Policy {
    gates: compare::Gates,
    accept_trailers: bool,
    /// Policy, not presentation: it decides whether comparing nothing fails,
    /// and a change able to set it for itself could merge with no comparison.
    allow_empty: bool,
}

impl Policy {
    /// What this policy would enforce differently from `base`, named for the
    /// report; empty when it would gate every series the same way.
    ///
    /// Both sides are resolved under the same flags and environment, so a
    /// difference an override masks is not reported: with the workflow
    /// unchanged, merging it changes nothing either.
    fn changes_from(&self, base: &Policy, measured: &BTreeSet<(String, String)>) -> Vec<String> {
        let mut out = self.gates.changes_from(&base.gates, measured);
        if self.accept_trailers != base.accept_trailers {
            out.push("`accept_trailers`".to_string());
        }
        if self.allow_empty != base.allow_empty {
            out.push("`allow_empty`".to_string());
        }
        out
    }
}

/// The gate policy `tak compare` enforces, read from `tak.toml` in the base
/// revision's tree, and the path it was found at.
///
/// Not the working tree's. In CI that is the change under review, and a gate
/// the change can edit is a gate it can waive: raise `pct`, mark the benchmark
/// it regressed `enabled = false`, or turn on `accept_trailers` and add a
/// trailer. The base is already reviewed and merged. The cost is that a gate
/// change takes effect one merge late, which the report says when it applies.
///
/// Only the gate moves. `[report] credit` is cosmetic, and nothing else in
/// the file bears on a comparison, which measures nothing: the benchmarks the
/// working tree declares are what `tak run` measured on this side. Flags and
/// environment variables still override the base's file, because the workflow
/// sets them, not the change.
///
/// Found by searching upward from the current directory, as `tak run` finds
/// its file, but through the base's tree rather than the disk. A path taken
/// from the working tree would let a change pick which file gates it: delete
/// or move `tak.toml`, or add one nearer the working directory, and the base
/// would have nothing there. For the same reason a base with no `tak.toml`
/// falls back to the defaults, never to the working tree's file.
///
/// A base file that does not parse is an error, not a fallback: the base is
/// the trusted side, and whatever it failed to say would otherwise be replaced
/// by defaults nobody chose. Missing objects are an error too, rather than
/// being read as a missing file.
fn base_policy(base_sha: &str, cli: &CliLayer) -> Result<(Policy, Option<String>)> {
    let at = detect::short(base_sha);
    let found = find_at(base_sha).with_context(|| {
        format!(
            "cannot read the gate policy from the base, {at}: tak compare reads {} out \
             of the base commit's tree, so its objects must be in this clone",
            config::FILE_NAME
        )
    })?;
    let (layer, config, path) = match found {
        None => (TakConfigLayer::empty(), None, None),
        Some((path, text)) => {
            let origin = format!("{at}:{path}");
            let context = || {
                format!(
                    "in {path} at the base, {at}, which sets the gate for this comparison; \
                     fix it there"
                )
            };
            let layer = TakConfigLayer::parse(&origin, &text).with_context(context)?;
            let config = Config::parse(&text).with_context(context)?;
            (layer, Some(config), Some(path))
        }
    };
    let settings = Settings::resolve(cli, &EnvLayer::from_process(), &layer)
        .with_context(|| format!("could not read settings from the base, {at}"))?;
    let global = global_gate(&settings)?;
    let gates = match config {
        Some(cfg) => cfg.gates(global),
        None => compare::Gates::uniform(global),
    };
    let policy = Policy {
        gates,
        accept_trailers: settings.accept_trailers,
        allow_empty: settings.allow_empty,
    };
    Ok((policy, path))
}

/// The nearest `tak.toml` in `commit`'s tree, searching from the current
/// directory up to the repository root: its path from the root, and its text.
fn find_at(commit: &str) -> Result<Option<(String, String)>> {
    let prefix = notes::prefix()?;
    let mut dir = prefix.trim_end_matches('/');
    loop {
        let path = match dir {
            "" => config::FILE_NAME.to_string(),
            _ => format!("{dir}/{}", config::FILE_NAME),
        };
        if let Some(text) = notes::file_at(commit, &path)? {
            return Ok(Some((path, text)));
        }
        if dir.is_empty() {
            return Ok(None);
        }
        dir = dir.rsplit_once('/').map_or("", |(parent, _)| parent);
    }
}

/// The `[gate]` settings, checked, from whichever source set them.
///
/// Checked by `tak run` as well as `tak compare`. A `TAK_GATE_PCT=-1` exported
/// in CI would otherwise let a run spend minutes measuring and fail only at
/// the comparison afterwards, which is the late failure `tak.toml` validation
/// exists to prevent.
fn global_gate(settings: &Settings) -> Result<compare::Gate> {
    compare::Gate::new(settings.gate_pct, settings.gate_min_delta).context("gate_pct")
}

/// Diagnose the plumbing.
///
/// Takes settings by value so a `tak.toml` that will not parse cannot stop the
/// command whose job is to tell you about it — main resolves them tolerantly
/// and falls back to the defaults.
fn cmd_doctor(settings: &Settings) -> Result<()> {
    println!("tak doctor\n");

    match notes::rev_parse("HEAD") {
        Ok(sha) => println!("  ✓ git repository        HEAD {}", &sha[..12]),
        Err(_) => {
            println!("  ✗ git repository        not in one — nothing can be recorded");
            return Ok(());
        }
    }

    match std::process::Command::new("valgrind")
        .arg("--version")
        .output()
    {
        Ok(o) if o.status.success() => println!(
            "  ✓ valgrind              {}",
            String::from_utf8_lossy(&o.stdout).trim()
        ),
        _ => println!(
            "  ! valgrind              not found — timing only, no gate-able metric\n\
             \x20                         (expected on macOS/Windows; use a Linux container)"
        ),
    }

    match notes::fetch("origin") {
        Ok(true) => println!(
            "  ✓ notes fetch           refreshed {} from origin",
            notes::NOTES_REF
        ),
        Ok(false) => println!(
            "  ! notes fetch           could not fetch {} (no remote, offline, or no data yet)",
            notes::NOTES_REF
        ),
        Err(e) => println!("  ! notes fetch           {e}"),
    }

    println!("  · runner class          {}", runner_class(settings));
    Ok(())
}

/// Infer "owner/name" from the `origin` remote.
fn repo_from_origin() -> Option<String> {
    let out = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
    // Match the host exactly. Splitting on the substring "github.com" would
    // accept `git@mygithub.com:o/r` and then query the wrong repository.
    let rest = [
        "https://github.com/",
        "http://github.com/",
        "git@github.com:",
        "ssh://git@github.com/",
    ]
    .iter()
    .find_map(|p| url.strip_prefix(p))?;
    let slug = rest.trim_end_matches('/').trim_end_matches(".git");
    (slug.matches('/').count() == 1 && !slug.is_empty()).then(|| slug.to_string())
}

fn backfill_workdir() -> Result<tempfile::TempDir> {
    let mut builder = tempfile::Builder::new();
    builder.prefix("tak-backfill-");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        builder.permissions(std::fs::Permissions::from_mode(0o700));
    }
    builder
        .tempdir()
        .context("could not create a backfill directory")
}

#[allow(clippy::too_many_arguments)]
fn cmd_backfill(
    repo: Option<String>,
    bin: Option<String>,
    args: Vec<String>,
    bench: String,
    limit: usize,
    runs: u32,
    dry_run: bool,
    settings: &Settings,
) -> Result<()> {
    check_recorded_names(settings, Some(&bench))?;
    let repo = repo
        .or_else(repo_from_origin)
        .context("could not infer the repository — pass --repo owner/name")?;
    let bin = bin.unwrap_or_else(|| repo.rsplit('/').next().unwrap_or(&repo).to_string());
    let args = if args.is_empty() {
        vec!["--version".to_string()]
    } else {
        args
    };

    // Fail before spending minutes downloading and measuring, and so that a
    // missing tag later means exactly that rather than "not in a repository".
    if !dry_run && !backfill::in_git_repo() {
        bail!(
            "not inside a git repository — measurements are recorded against tagged \
             commits. Run from a clone of {repo}, or pass --dry-run."
        );
    }

    let releases = backfill::list_releases(&repo, limit)?;
    if releases.is_empty() {
        println!("no releases with downloadable assets found for {repo}");
        return Ok(());
    }
    println!("{} release(s) from {repo}\n", releases.len());

    // The parent has to be atomically created and, on Unix, owner-only. A
    // predictable `/tmp/tak-backfill-<pid>` let another local user pre-create
    // that path and replace a downloaded executable before tak spawned it.
    // TempDir also removes downloads on every exit path, including `?`.
    let workdir = backfill_workdir()?;
    let mut recorded = 0usize;
    let mut skipped = 0usize;

    for (i, rel) in releases.iter().enumerate() {
        let Some(asset) = backfill::pick_asset(&rel.assets) else {
            println!("  {:<14} skipped — no asset for this platform", rel.tag);
            skipped += 1;
            continue;
        };

        let dir = workdir.path().join(backfill::release_dir_name(i, &rel.tag));
        let path = match backfill::fetch_binary(asset, &bin, &dir) {
            Ok(p) => p,
            Err(e) => {
                println!("  {:<14} skipped — {e}", rel.tag);
                skipped += 1;
                continue;
            }
        };

        let mut cmd = vec![path.to_string_lossy().to_string()];
        cmd.extend(args.iter().cloned());

        let plan = Plan {
            cmd: cmd.clone(),
            warmup: 2,
            runs,
            // Release binaries are extracted to absolute paths.
            dir: None,
            settings: settings.clone(),
        };
        let mut metrics = match measure::wall(&plan) {
            Ok(m) => m,
            Err(e) => {
                println!("  {:<14} skipped — {e}", rel.tag);
                skipped += 1;
                continue;
            }
        };
        let mut suspect = None;
        if let Ok(Some(c)) = measure::instructions(&cmd, None, settings) {
            metrics.insert("instructions".into(), c.min as f64);
            if c.is_suspect() {
                suspect = Some(c.spread_pct());
            }
        }

        let ins = metrics
            .get("instructions")
            .map(|v| format!("{v:>14.0}"))
            .unwrap_or_else(|| format!("{:>14}", "-"));
        println!(
            "  {:<14} wall_min {:>8.2}ms   instructions {ins}{}",
            rel.tag,
            metrics["wall_min_ms"],
            suspect
                .map(|p| format!("   ⚠ varied {p:.1}%"))
                .unwrap_or_default()
        );

        if dry_run {
            continue;
        }

        // Attach to the tagged commit so the series lands on the real timeline.
        // A shallow clone has no tags, which is a skip rather than an error.
        let Some(sha) = backfill::tag_commit(&rel.tag) else {
            println!(
                "                 not recorded — tag {} not present locally (try `git fetch --tags`)",
                rel.tag
            );
            skipped += 1;
            continue;
        };

        let rec = Record {
            v: SCHEMA_VERSION,
            bench: bench.clone(),
            tool: bin.clone(),
            version: Some(backfill::version_of(&rel.tag).to_string()),
            runner: runner_class(settings),
            // The release's own date, not now: this is when the code existed.
            ts: rel.published_at.clone().unwrap_or_else(now_rfc3339),
            metrics,
        };
        notes::append(&sha, &[rec])?;
        recorded += 1;
    }

    if dry_run {
        println!("\n  dry run — nothing written");
    } else {
        println!(
            "\n  recorded {recorded}, skipped {skipped} → {}",
            notes::NOTES_REF
        );
        println!("  push with: tak push");
    }
    Ok(())
}

/// `tak backfill --commits`'s options, gathered so they travel as one value.
struct CommitBackfill {
    range: String,
    bench: Option<String>,
    limit: usize,
    runs: Option<u32>,
    force: bool,
    dry_run: bool,
}

/// A commit in the range, and what it still needs.
struct Pending {
    sha: String,
    subject: String,
    /// Benchmark to the names of its subjects with no record for this runner
    /// class yet, or every selected one under `--force`. Empty means nothing
    /// to do.
    needs: BTreeMap<String, Vec<String>>,
    /// Its build failed in an earlier run, under the same keys; see
    /// [`tak_cli::worktree::FailedCommits`]. Always false under `--force`.
    build_failed_before: bool,
    /// Benchmarks it still needs whose measurement failed here in an earlier
    /// run, and which `needs` therefore leaves out. Empty under `--force`.
    measure_failed_before: Vec<String>,
}

impl Pending {
    fn wanted(&self) -> bool {
        !self.needs.is_empty() && !self.build_failed_before
    }

    /// Nothing is still needed, and it is not because it was all recorded.
    fn passed_over(&self) -> bool {
        (self.build_failed_before && !self.needs.is_empty())
            || (self.needs.is_empty() && !self.measure_failed_before.is_empty())
    }
}

/// What a commit still needs, given the `(bench, tool)` pairs it already has
/// records for: per benchmark, the subjects that have none.
///
/// Keyed on the subject and not only the benchmark, so a subject added to a
/// benchmark after some commits were recorded is still backfilled on them,
/// without measuring again the subjects that already have a point there.
fn needs_for(
    plans: &[BenchPlan],
    have: &std::collections::BTreeSet<(String, String)>,
    force: bool,
) -> BTreeMap<String, Vec<String>> {
    let mut needs = BTreeMap::new();
    for (bench, multi, subjects) in plans {
        let missing: Vec<String> = subjects
            .iter()
            .filter(|s| force || !have.contains(&(bench.clone(), record_tool(*multi, s))))
            .map(|s| s.name.clone())
            .collect();
        if !missing.is_empty() {
            needs.insert(bench.clone(), missing);
        }
    }
    needs
}

/// `needs` for a dry run: benchmarks whole where every subject is missing,
/// otherwise with the subjects that are.
fn describe_needs(needs: &BTreeMap<String, Vec<String>>, plans: &[BenchPlan]) -> String {
    needs
        .iter()
        .map(|(bench, subjects)| {
            let all = plans
                .iter()
                .find(|(b, _, _)| b == bench)
                .is_some_and(|(_, _, s)| s.len() == subjects.len());
            if all {
                bench.clone()
            } else {
                format!("{bench} ({})", subjects.join(", "))
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// How far one commit got.
enum Outcome {
    Recorded(usize),
    /// The build failed, or its tree could not be used. Remembered.
    BuildFailed,
    /// It built, and measuring this benchmark failed. Remembered too, for
    /// that benchmark: at a fixed commit it almost always fails the same way
    /// again.
    MeasureFailed(String),
    /// It could not be checked out, which says nothing about the commit.
    /// Not remembered.
    NotRecorded,
}

/// Build and measure past commits, recording each to its own note.
///
/// The benchmarks are the *current* tak.toml's, run inside each old checkout.
/// Using each commit's own tak.toml instead would change what a series
/// measures whenever someone edited a benchmark, and the step that edit
/// produced would read as a change in the code. The cost is that an old tree
/// may lack a fixture or path the current file names; that commit is then
/// reported and left unrecorded rather than measured against the wrong thing.
fn cmd_backfill_commits(o: CommitBackfill, settings: &Settings) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let Some((path, cfg)) = Config::find(&cwd)? else {
        bail!(
            "no {} found in {} or any parent — --commits measures the benchmarks it declares",
            config::FILE_NAME,
            cwd.display()
        );
    };
    let Some(build) = cfg.build()? else {
        bail!(
            "{} has no [build]. --commits checks each commit out fresh, so it has \
             to be built before it can be measured:\n\n\
             \x20   [build]\n\
             \x20   cmd = [\"cargo\", \"build\", \"--release\"]\n\n\
             A project with nothing to build can declare cmd = [\"true\"].",
            path.display()
        );
    };
    let opts = RunOpts {
        bench: o.bench.clone(),
        runs: o.runs.map(Runs::Fixed),
        warmup: None,
        no_counters: false,
        // What tak.toml says; backfilling past commits has no flag for it.
        allocations: false,
        record: true,
        no_progress: false,
        groups: Vec::new(),
        subjects: Vec::new(),
        seed: None,
        export_json: None,
        profile_dir: None,
        config: None,
        dry_run: o.dry_run,
        // Backfill records to each commit's note; local baselines belong to
        // `tak run` on the working tree.
        save_baseline: None,
        baseline: None,
        gate: false,
    };
    // Everything resolved and rendered before the first checkout, so a
    // mistake in tak.toml fails in a second rather than after a build.
    let Planned { plans, skipped } = plan_declared(&cfg, &path, &opts)?;
    print_skipped(&skipped);
    if plans.is_empty() {
        bail!(
            "nothing to backfill: {}",
            if skipped.is_empty() {
                "tak.toml declares no benchmarks"
            } else {
                "every selected benchmark or subject has a false `when`"
            }
        );
    }

    // Where tak.toml sits within the repository, so the same place can be
    // found in each checkout: relative programs, `dir` and the build are all
    // anchored there, exactly as `tak run` anchors them in this one.
    let config_dir = path.parent().context("tak.toml has no parent directory")?;
    let top = tak_cli::worktree::toplevel(config_dir)?;
    let rel = config_dir
        .canonicalize()?
        .strip_prefix(top.canonicalize()?)
        .map(Path::to_path_buf)
        .with_context(|| {
            format!(
                "{} is outside the repository at {}",
                path.display(),
                top.display()
            )
        })?;

    // `notes::log` passes the range after `--end-of-options`, so a leading
    // `-` could not become an option anyway; this only gives it a clearer
    // error than git's.
    if o.range.starts_with('-') || o.range.trim().is_empty() {
        bail!("not a commit range: {:?} (try `main~20..main`)", o.range);
    }
    // So what CI already pushed counts as recorded. Without it a backfill
    // re-measures the commits the main-branch workflow did, and those get a
    // second point each. Offline or without a remote, the local ref decides.
    let _ = notes::fetch("origin");
    // One first-parent walk with every note inlined, the same one `tak log`
    // reads, rather than a subprocess or two per commit. Unbounded: the
    // range bounds it, and `--limit` counts builds among the commits still
    // needing one, which a cap on the walk would cut short.
    let commits = notes::log(&o.range, None)
        .with_context(|| format!("could not list the commits in {}", o.range))?;
    if commits.is_empty() {
        println!("no commits in {}", o.range);
        return Ok(());
    }

    let runner = runner_class(settings);
    // A stable one-line description of the build and where it ran, so a
    // remembered failure is forgotten as soon as `[build]` changes, and does
    // not follow the clone onto a new runner class: a toolchain upgrade is
    // exactly what a new class marks, and may be what makes an old commit
    // build again. JSON escapes tabs and newlines.
    let build_key = serde_json::to_string(&(
        &runner,
        &build.cmd,
        build.dir.as_ref().map(|d| d.to_string_lossy()),
        &build.env,
    ))?;
    // A measurement failure also depends on the benchmarks, and editing
    // tak.toml is how one gets fixed: the file's contents are part of its
    // key, so any edit tries those commits again. Coarser than the
    // benchmarks alone, and erring towards a retry.
    let text =
        std::fs::read(&path).with_context(|| format!("could not read {}", path.display()))?;
    let measure_key = format!("{build_key} {}", tak_cli::worktree::fingerprint(&text));
    let mut failures = tak_cli::worktree::FailedCommits::load(build_key, measure_key)?;

    let mut pending = Vec::with_capacity(commits.len());
    for c in commits {
        let have: std::collections::BTreeSet<(String, String)> = c
            .records
            .into_iter()
            .filter(|r| r.runner == runner)
            .map(|r| (r.bench, r.tool))
            .collect();
        let mut needs = needs_for(&plans, &have, o.force);
        // Only the benchmarks that failed here are passed over: another
        // benchmark of the same commit, or one a later `--bench` selects,
        // has not failed and is still measured.
        let mut measure_failed_before = Vec::new();
        if !o.force {
            needs.retain(|bench, _| {
                let failed = failures.measure_failed(&c.sha, bench);
                if failed {
                    measure_failed_before.push(bench.clone());
                }
                !failed
            });
        }
        pending.push(Pending {
            build_failed_before: !o.force && failures.build_failed(&c.sha),
            measure_failed_before,
            needs,
            sha: c.sha,
            subject: c.subject,
        });
    }
    let recorded_before = pending
        .iter()
        .filter(|p| p.needs.is_empty() && p.measure_failed_before.is_empty())
        .count();
    let build_failed_before = pending
        .iter()
        .filter(|p| p.passed_over() && p.build_failed_before)
        .count();
    let measure_failed_before = pending
        .iter()
        .filter(|p| p.passed_over() && !p.build_failed_before)
        .count();
    // Newest first, and `--limit` counts builds rather than commits. A
    // commit that failed is remembered and passed over next time, so the
    // same command run again carries on from where the last one stopped
    // instead of retrying the same broken commit at the top of every run.
    let (todo, beyond): (Vec<&Pending>, Vec<&Pending>) = {
        let needed: Vec<&Pending> = pending.iter().filter(|p| p.wanted()).collect();
        let split = needed.len().min(o.limit);
        (needed[..split].to_vec(), needed[split..].to_vec())
    };

    println!(
        "{} commit(s) in {}, first parent only, runner {runner}",
        pending.len(),
        o.range
    );
    println!("build: {}", shell_words(&build.cmd));

    if o.dry_run {
        println!();
        let everything = needs_for(&plans, &Default::default(), true);
        for p in &pending {
            let status = if p.build_failed_before && p.passed_over() {
                "build failed before".to_string()
            } else if p.passed_over() {
                "measure failed before".to_string()
            } else if p.needs.is_empty() {
                "recorded".to_string()
            } else if beyond.iter().any(|b| b.sha == p.sha) {
                "beyond --limit".to_string()
            } else if p.needs == everything {
                "would build".to_string()
            } else if p.measure_failed_before.is_empty() {
                format!("would build ({})", describe_needs(&p.needs, &plans))
            } else {
                format!(
                    "would build ({}; {} failed before)",
                    describe_needs(&p.needs, &plans),
                    p.measure_failed_before.join(", ")
                )
            };
            println!("  {}  {status:<21}  {}", &p.sha[..12], p.subject);
        }
        println!("\n  dry run — nothing built or written");
        return Ok(());
    }

    // Owner-only for the reason release backfill's is: the build writes
    // executables here that tak then runs. Every checkout lives inside it.
    let scratch = backfill_workdir()?;
    let hooks = scratch.path().join("hooks");
    std::fs::create_dir(&hooks).context("could not create an empty hooks directory")?;
    tak_cli::worktree::prune();
    tak_cli::worktree::clean_up_on_interrupt(scratch.path())?;

    let seed = random_seed();
    let mut recorded = 0usize;
    let (mut build_failed, mut measure_failed, mut not_recorded) =
        (Vec::new(), Vec::new(), Vec::new());
    for p in &todo {
        let short = &p.sha[..12];
        println!("\n{short}  {}", p.subject);
        let outcome = backfill_commit(
            p,
            &build,
            &plans,
            &rel,
            scratch.path(),
            &hooks,
            seed,
            &opts,
            settings,
        );
        // A build or measurement the interrupt handler killed comes back as
        // a failure; the handler exits the process, with the signal's
        // status, and nothing here may write or return first.
        tak_cli::worktree::wait_if_interrupted();
        match outcome? {
            Outcome::Recorded(n) => {
                println!("  recorded {n} measurement(s)");
                recorded += 1;
                let benches: Vec<String> = p.needs.keys().cloned().collect();
                failures.recorded(&p.sha, &benches)?;
            }
            // Never an interrupted one: a failure the handler caused by
            // killing the build or the measured command says nothing about
            // the commit, and `wait_if_interrupted` above stops here before
            // one could be remembered and leave a cancelled job's commit out
            // of every later run.
            Outcome::BuildFailed => {
                build_failed.push(short);
                failures.add(&p.sha, tak_cli::worktree::Failure::Build)?;
            }
            Outcome::MeasureFailed(bench) => {
                measure_failed.push(short);
                // It built, so a build failure remembered from before — which
                // `--force` retried — no longer holds. Kept, it would pass
                // over every other benchmark of the commit from now on.
                failures.recorded(&p.sha, &[])?;
                failures.add(&p.sha, tak_cli::worktree::Failure::Measure(bench))?;
            }
            Outcome::NotRecorded => not_recorded.push(short),
        }
    }
    // A signal after the last commit still ends with its own status, and no
    // summary that reads as if the run had finished.
    tak_cli::worktree::wait_if_interrupted();

    println!(
        "\n  recorded {recorded} commit(s) → {}; {recorded_before} already recorded",
        notes::NOTES_REF
    );
    if !build_failed.is_empty() {
        println!("  build failed: {}", build_failed.join(", "));
    }
    if !measure_failed.is_empty() {
        println!("  measurement failed: {}", measure_failed.join(", "));
    }
    if !not_recorded.is_empty() {
        println!("  not checked out: {}", not_recorded.join(", "));
    }
    let failed_before = build_failed_before + measure_failed_before;
    if failed_before > 0 {
        println!(
            "  {failed_before} commit(s) passed over: they failed in an earlier run \
             ({build_failed_before} build, {measure_failed_before} measurement; \
             --force retries them)"
        );
    }
    if !beyond.is_empty() {
        println!(
            "  {} more commit(s) beyond --limit {}; run again to continue",
            beyond.len(),
            o.limit
        );
    }
    if recorded > 0 {
        println!("  push with: tak push");
    }
    // A range where some old commits no longer build is normal and still a
    // success, and so is a second run that only retries those. One that has
    // no record at all to show for the range is not: a CI job seeding
    // history must not pass having seeded none.
    let failed = !(build_failed.is_empty() && measure_failed.is_empty() && not_recorded.is_empty())
        || failed_before > 0;
    if recorded == 0 && recorded_before == 0 && failed {
        bail!("no commit in {} was recorded", o.range);
    }
    Ok(())
}

/// Check out, build and measure one commit, and record it whole or not at
/// all. `Err` only for what would fail every later commit too, such as
/// being unable to write the note.
#[allow(clippy::too_many_arguments)]
fn backfill_commit(
    p: &Pending,
    build: &config::Build,
    plans: &[BenchPlan],
    rel: &Path,
    scratch: &Path,
    hooks: &Path,
    seed: u64,
    opts: &RunOpts,
    settings: &Settings,
) -> Result<Outcome> {
    let wt = match tak_cli::worktree::Worktree::add(&scratch.join(&p.sha[..12]), &p.sha, hooks) {
        Ok(wt) => wt,
        Err(e) => {
            println!("  not recorded — {e:#}");
            return Ok(Outcome::NotRecorded);
        }
    };
    let root = wt.path().join(rel);
    // The commit's own date, as release backfill uses the release's: this is
    // when the code existed, which is what a series is plotted against. It
    // is also the same every time the commit is measured, so its points keep
    // one place on the timeline, and nothing in a record depends on when the
    // backfill ran except the metrics themselves: a record written twice
    // stays byte-identical, which is all cat_sort_uniq dedupes on. A commit
    // object with no readable committer date would be malformed; it still
    // costs only its own date, with a warning, rather than failing.
    let ts = match tak_cli::worktree::commit_time(&p.sha) {
        Ok(t) => rfc3339(t),
        Err(e) => {
            eprintln!("  warning: {e:#}; recording the measurement time instead");
            now_rfc3339()
        }
    };

    let mut build = build.clone();
    build.anchor(&root);
    // The checked path has no `..`, but the old tree may put a symlink where
    // the current tak.toml expects a directory.
    // Counted as a failed build: which paths a commit's tree holds never
    // changes, so this would fail the same way next time, and retrying it
    // first on every run would stop `--limit` from reaching older commits.
    // The build's own program too, when it is one of the tree's files.
    let contained = [Some(&root), build.dir.as_ref()]
        .into_iter()
        .flatten()
        .try_for_each(|dir| wt.check_contains(dir))
        .and_then(|()| check_program(&build.cmd, &wt));
    if let Err(e) = contained {
        println!("  build failed — skipped: {e:#}");
        return Ok(Outcome::BuildFailed);
    }
    match backfill::run_build(&build, &scratch.join("build.log")) {
        Ok(took) => println!("  built in {:.1}s", took.as_secs_f64()),
        Err(e) => {
            println!("  build failed — skipped");
            for line in format!("{e:#}").lines() {
                println!("    {line}");
            }
            return Ok(Outcome::BuildFailed);
        }
    }

    let mut records = Vec::new();
    for (name, multi, subjects) in plans {
        let Some(wanted) = p.needs.get(name) else {
            continue;
        };
        // Only the subjects with no point on this commit yet: measuring the
        // rest again would give them a second one.
        let mut subjects: Vec<Subject> = subjects
            .iter()
            .filter(|s| wanted.contains(&s.name))
            .cloned()
            .collect();
        for s in &mut subjects {
            s.anchor(&root);
        }
        // A subject with a `setup` is checked again once that has run: the
        // setup is the old tree's own code, and can leave a symlink leading
        // out of the checkout where `dir` or the program is, just as the
        // tree itself can. Checked before anything else of it runs.
        let vet = |s: &Subject| check_contained(s, &wt);
        let problem = match check_inputs(&subjects, &wt) {
            Some(missing) => Some(missing),
            None => match measure_bench_vetted(name, &subjects, *multi, seed, opts, settings, &vet)
            {
                Err(e) => Some(format!("{e:#}")),
                // The same rules `tak run --record` applies: a missing
                // subject or a failed check would leave a set in history
                // that looks complete and is not.
                Ok((_, failed)) if !failed.is_empty() => {
                    Some(format!("subject(s) failed: {}", failed.join(", ")))
                }
                Ok((measured, _)) => {
                    let failing = failing_checks(&measured);
                    // A count that was asked for and failed leaves a
                    // timing-only record that looks like counters were off,
                    // and a gate would pass over it without a word: the same
                    // gap `tak run --baseline --gate` refuses.
                    let uncounted: Vec<String> = measured
                        .iter()
                        .filter(|m| m.count_failed)
                        .map(|m| {
                            if *multi {
                                format!("{name} ({})", m.subject.name)
                            } else {
                                name.clone()
                            }
                        })
                        .collect();
                    // And a declared metric that could not be taken — its
                    // file missing at this commit, say — as `tak run
                    // --record` refuses it: the commit would count as
                    // measured with the metric absent.
                    let broken = failed_metrics(&measured);
                    if !failing.is_empty() {
                        Some(format!("check failed: {}", labels(&failing)))
                    } else if !broken.is_empty() {
                        Some(format!(
                            "{} metric(s) failed: {}",
                            broken.len(),
                            broken.join(", ")
                        ))
                    } else if !uncounted.is_empty() {
                        Some(format!(
                            "instruction counting failed: {}",
                            uncounted.join(", ")
                        ))
                    } else {
                        records.extend(measured.into_iter().map(|m| m.record));
                        None
                    }
                }
            },
        };
        if let Some(problem) = problem {
            // Nothing from this run of the commit is written, including
            // benchmarks that did measure: a run that stopped partway would
            // leave a set nobody chose. Only this benchmark is remembered as
            // failed, so the next run measures the others without it. That
            // commit then lacks this benchmark by a decision the failure
            // file records, rather than because a run broke off.
            println!("  not recorded — {name}: {problem}");
            return Ok(Outcome::MeasureFailed(name.clone()));
        }
    }
    for r in &mut records {
        r.ts = ts.clone();
    }
    notes::append(&p.sha, &records)?;
    Ok(Outcome::Recorded(records.len()))
}

/// A `dir` or program path the current tak.toml names that this checkout
/// does not have, described for the user.
///
/// Only for subjects without a `setup`, which may be what creates them.
/// Without this, the failure surfaces as a spawn error that says nothing
/// about the file having been read from a newer commit than the tree.
///
/// A `dir` or program inside the checkout must also stay inside it once
/// symlinks are resolved, for the reason
/// [`tak_cli::worktree::Worktree::check_contains`] gives: a committed
/// symlink at the program's path would otherwise run a binary from outside
/// the commit being measured. One named outside the checkout, such as an
/// absolute path from a template, is the user's choice and is left alone.
fn check_inputs(subjects: &[Subject], wt: &tak_cli::worktree::Worktree) -> Option<String> {
    let shown = |p: &Path| p.strip_prefix(wt.path()).unwrap_or(p).display().to_string();
    for s in subjects {
        if let Err(e) = check_contained(s, wt) {
            return Some(format!("{e:#}"));
        }
        let program = Path::new(&s.cmd[0]);
        if s.setup.is_some() {
            continue;
        }
        if let Some(d) = &s.dir
            && !d.is_dir()
        {
            return Some(format!(
                "`dir` {} does not exist at this commit (tak.toml is read from the current checkout)",
                shown(d)
            ));
        }
        if program.is_absolute()
            && program.starts_with(wt.path())
            && spawned_path(program).is_none()
        {
            return Some(format!(
                "{} does not exist at this commit after the build",
                shown(program)
            ));
        }
    }
    None
}

/// Whether a subject's `dir` and program, where they are inside the checkout
/// and exist, still resolve inside it with symlinks followed.
///
/// Every program tak runs for the subject counts, not only `cmd`: `setup`,
/// `prepare`, `check`, `version_cmd` and metric commands are the old tree's
/// code as much as the subject is, and a committed symlink at one of their
/// paths would run something from outside the commit just the same. So is a
/// metric's file, which is read rather than run.
fn check_contained(s: &Subject, wt: &tak_cli::worktree::Worktree) -> Result<()> {
    if let Some(d) = &s.dir
        && d.starts_with(wt.path())
        && d.exists()
    {
        wt.check_contains(d)?;
    }
    let programs = [
        Some(&s.cmd),
        s.setup.as_ref(),
        s.prepare.as_ref(),
        s.check.as_ref(),
        s.version_cmd.as_ref(),
    ];
    for argv in programs.into_iter().flatten() {
        check_program(argv, wt)?;
    }
    // A custom metric's command is a program like the rest, and its file is
    // read from the checkout: a committed symlink to the live tree would
    // record the live binary's size at every commit. A file missing here is
    // left for the metric itself to fail on, which names it.
    for source in s.metrics.values() {
        match source {
            config::MetricSource::Cmd(argv) => check_program(argv, wt)?,
            config::MetricSource::File(p) => {
                if p.starts_with(wt.path()) && p.exists() {
                    wt.check_contains(p)?;
                }
            }
        }
    }
    Ok(())
}

/// A program path inside the checkout that exists must resolve inside it.
/// One on PATH, or named outside the checkout, is left alone.
fn check_program(argv: &[String], wt: &tak_cli::worktree::Worktree) -> Result<()> {
    let program = Path::new(&argv[0]);
    if program.is_absolute()
        && program.starts_with(wt.path())
        && let Some(found) = spawned_path(program)
    {
        wt.check_contains(&found)?;
    }
    Ok(())
}

/// The file spawning `program` would run, if there is one. On Windows that
/// includes the executable suffix: `./target/release/mycli` runs `mycli.exe`,
/// and a check for the bare name would call every Windows build missing.
fn spawned_path(program: &Path) -> Option<std::path::PathBuf> {
    if program.exists() {
        return Some(program.to_path_buf());
    }
    let suffix = std::env::consts::EXE_SUFFIX;
    if suffix.is_empty() || program.extension().is_some() {
        return None;
    }
    let mut with = program.as_os_str().to_owned();
    with.push(suffix);
    let with = std::path::PathBuf::from(with);
    with.exists().then_some(with)
}

/// Resolve settings from the CLI layer, the environment, and `tak.toml`.
///
/// Called only by the commands that measure something or report settings.
/// `push`, `init`, `history` and `doctor` do not consult `tak.toml` at all, so a
/// broken one cannot stop you from pushing measurements you already took.
///
/// Reads only the dotted keys the registry binds to `tak.toml`, so an invalid
/// `[bench.x]` does not abort `tak run -- somecmd` — an explicit command has
/// never depended on the declared benchmarks and still does not.
///
/// A *missing* `tak.toml` is fine. A *syntax-broken* one is an error even here:
/// it may carry `[env]` settings that change what gets scrubbed from a
/// subject's environment, and silently applying a weaker filter than the
/// project asked for is not a good failure.
/// Settings for a command that must still run when tak.toml cannot be read,
/// with a warning naming what it is doing without it.
///
/// Only the file is dropped. Falling all the way back to the defaults threw
/// away the flags and the environment too, so doctor once reported a derived
/// runner class while a recording would have used the one the user asked for.
fn tolerant_settings(cli: &CliLayer, doing: &str) -> Settings {
    resolve_settings(cli).unwrap_or_else(|_| {
        eprintln!("warning: could not read tak.toml; {doing} without it");
        Settings::resolve(cli, &EnvLayer::from_process(), &TakConfigLayer::empty())
            .unwrap_or_default()
    })
}

fn resolve_settings(cli: &CliLayer) -> Result<Settings> {
    Settings::from_process(cli)
}

/// A declared default, written the way `tak.toml` would spell it.
fn render_default(value: &usage_rs::config::Const) -> String {
    use usage_rs::config::{Const, Value};
    match value {
        Const::Str(s) => format!("{s:?}"),
        Const::Bool(b) => b.to_string(),
        Const::Int(i) => i.to_string(),
        Const::Float(f) => Value::Float(*f).display(),
        Const::List(items) => format!(
            "[{}]",
            items
                .iter()
                .map(render_default)
                .collect::<Vec<_>>()
                .join(", ")
        ),
        other => other.to_value().display(),
    }
}

/// Print the settings registry with resolved values.
fn cmd_settings(resolved: &Settings, docs: bool) -> Result<()> {
    let scrubbed: Vec<&str> = resolved.scrubbed_env().collect();
    for meta in Settings::SETTINGS_PROPS {
        // `display_value` rather than a match here: a test asserts it answers
        // for every registry entry, so a new setting cannot reach this display
        // without a value behind it.
        let Some(value) = resolved.display_value(meta.key) else {
            println!(
                "{}  (no accessor — wire it into Settings::display_value)",
                meta.key
            );
            continue;
        };
        println!("{}  {}", meta.key, meta.ty.name());
        println!("  value    {value}");
        if let Some(default) = &meta.default {
            println!("  default  {}", render_default(default));
        }
        if !meta.cli.is_empty() {
            println!("  cli      {}", meta.cli.join(", "));
        }
        if !meta.envs.is_empty() {
            println!("  env      {}", meta.envs.join(", "));
        }
        let config_keys: Vec<&str> = meta
            .bindings
            .iter()
            .filter(|(kind, _)| *kind == config_source().name())
            .map(|(_, key)| *key)
            .collect();
        if !config_keys.is_empty() {
            println!("  tak.toml {}", config_keys.join(", "));
        }
        if let Some(since) = meta.since {
            println!("  since    {since}");
        }
        if docs {
            println!();
            if let Some(text) = meta.long_help.or(meta.help) {
                for line in text.trim().lines() {
                    println!("  {line}");
                }
            }
            for example in meta.examples {
                println!("  $ {example}");
            }
        }
        println!();
    }
    println!("removed from measured commands: {scrubbed:?}");
    Ok(())
}

fn main() -> Result<()> {
    // The settings layer beside the parsed struct: what was given on the
    // command line contributes, and what was left off does not.
    let (cli, overrides) = Cli::parse_with_settings();
    match cli.cmd {
        Cmd::Completion { shell } => {
            let shell = usage_rs::complete::Shell::from_name(&shell)
                .ok_or_else(|| anyhow::anyhow!("unsupported shell: {shell}"))?;
            print!("{}", Cli::completion_script(shell));
            Ok(())
        }
        Cmd::Run {
            bench,
            runs,
            warmup,
            no_counters,
            allocations,
            record,
            no_progress,
            group,
            subject,
            seed,
            export_json,
            profile_dir,
            config,
            dry_run,
            save_baseline,
            baseline,
            gate,
            cmd,
        } => {
            let settings = Settings::from_process_at(&overrides, config.as_deref())?;
            let profile_dir = profile_dir
                .map(|d| {
                    std::path::absolute(&d)
                        .with_context(|| format!("could not resolve {}", d.display()))
                })
                .transpose()?;
            cmd_run(
                RunOpts {
                    bench,
                    runs: runs.as_deref().map(str::parse).transpose()?,
                    warmup,
                    no_counters,
                    allocations,
                    record,
                    no_progress,
                    groups: group,
                    subjects: subject,
                    seed,
                    export_json,
                    profile_dir,
                    config,
                    dry_run,
                    save_baseline,
                    baseline,
                    gate,
                },
                cmd,
                &settings,
            )
        }
        Cmd::History { rev, remote } => cmd_history(rev, remote),
        Cmd::Log {
            rev,
            limit,
            bench,
            html,
            remote,
        } => cmd_log(
            LogOpts {
                rev,
                limit,
                bench,
                html,
                remote,
            },
            // Tolerant, like doctor: reading what was recorded needs nothing
            // from tak.toml but the credit line, and a config broken on this
            // commit must not hide the history of every commit before it.
            &tolerant_settings(&overrides, "reading history"),
        ),
        Cmd::Push(RemoteArgs { remote }) => {
            notes::push(&remote)?;
            println!("pushed {} to {}", notes::NOTES_REF, remote);
            Ok(())
        }
        Cmd::Artifact(args) => match args.cmd {
            ArtifactCmd::Export { output, rev } => {
                let (sha, records) = tak_cli::artifact::export(&output, &rev)?;
                println!(
                    "exported {records} measurement(s) for {} to {}",
                    &sha[..12],
                    output.display()
                );
                Ok(())
            }
            ArtifactCmd::Publish {
                path,
                expect,
                remote,
            } => {
                let (sha, records) = tak_cli::artifact::publish(&path, &expect, &remote)?;
                println!(
                    "published {records} measurement(s) for {} to {remote}",
                    &sha[..12]
                );
                Ok(())
            }
        },
        Cmd::Init(RemoteArgs { remote }) => {
            notes::install_refspec(&remote)?;
            println!(
                "added {} to remote.{}.fetch — plain `git fetch` now picks up measurements",
                notes::NOTES_REF,
                remote
            );
            Ok(())
        }
        Cmd::Backfill {
            commits,
            force,
            repo,
            bin,
            args,
            bench,
            limit,
            runs,
            dry_run,
        } => {
            let settings = resolve_settings(&overrides)?;
            match commits {
                Some(range) => {
                    // Refused rather than ignored: each names something a
                    // release backfill downloads, and a commit backfill
                    // silently measuring tak.toml's benchmarks instead would
                    // record a different series from the one asked for.
                    if repo.is_some() || bin.is_some() || !args.is_empty() {
                        bail!(
                            "--repo, --bin and arguments after `--` select release binaries; \
                             --commits measures the benchmarks tak.toml declares"
                        );
                    }
                    cmd_backfill_commits(
                        CommitBackfill {
                            range,
                            bench,
                            limit,
                            runs,
                            force,
                            dry_run,
                        },
                        &settings,
                    )
                }
                None => {
                    if force {
                        bail!("--force only applies with --commits");
                    }
                    cmd_backfill(
                        repo,
                        bin,
                        args,
                        bench.unwrap_or_else(|| "release".to_string()),
                        limit,
                        runs.unwrap_or(10),
                        dry_run,
                        &settings,
                    )
                }
            }
        }
        Cmd::Compare {
            base,
            rev,
            remote,
            no_gate,
            accept,
        } => cmd_compare(
            base,
            rev,
            remote,
            no_gate,
            accept,
            &overrides,
            &resolve_settings(&overrides)?,
        ),
        Cmd::Explain { base, head, top } => cmd_explain(&base, &head, top),
        Cmd::Detect {
            rev,
            window,
            remote,
            no_gate,
            accept,
        } => cmd_detect(
            rev,
            window,
            remote,
            no_gate,
            accept,
            &resolve_settings(&overrides)?,
        ),
        // Tolerant on purpose: doctor diagnoses a broken setup, so a tak.toml
        // it cannot read must not stop it from running.
        Cmd::Doctor => cmd_doctor(&tolerant_settings(&overrides, "showing settings")),
        Cmd::Settings { docs } => cmd_settings(&resolve_settings(&overrides)?, docs),
        Cmd::Usage => {
            // The command tree, then the config block: the settings are part
            // of the spec, so docs and completions read the same declaration
            // the resolver does.
            print!("{}", Cli::spec().view().omit_version().to_kdl());
            print!("{}", Settings::spec_kdl());
            Ok(())
        }
    }
}

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

    /// The drift guard. The registry lists the flags each setting declares and
    /// the parser lists the flags it binds to settings; both are generated, and
    /// this holds them against each other — a flag documented and read by
    /// nothing, or read and documented by nothing, fails here.
    ///
    #[test]
    fn the_flags_this_cli_reads_are_the_flags_its_settings_declare() {
        assert_eq!(
            Settings::SETTINGS_REGISTRY.drift(Cli::SETTINGS_BINDINGS),
            Vec::<String>::new()
        );
    }

    #[test]
    fn timestamp_is_rfc3339_shaped() {
        let ts = now_rfc3339();
        assert_eq!(ts.len(), 20, "{ts}");
        assert!(ts.ends_with('Z'));
        assert_eq!(&ts[4..5], "-");
        assert_eq!(&ts[10..11], "T");
    }

    /// A backfilled commit can be dated before 1970, and must land on the
    /// right day rather than failing the backfill.
    #[test]
    fn timestamps_before_the_epoch_are_formatted() {
        assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
        assert_eq!(rfc3339(-1), "1969-12-31T23:59:59Z");
        assert_eq!(rfc3339(-86_400 * 365), "1969-01-01T00:00:00Z");
        assert_eq!(rfc3339(1_700_000_000), "2023-11-14T22:13:20Z");
    }

    #[cfg(unix)]
    #[test]
    fn the_backfill_workdir_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let workdir = backfill_workdir().unwrap();
        let mode = workdir.path().metadata().unwrap().permissions().mode();
        assert_eq!(mode & 0o077, 0, "workdir mode was {:o}", mode & 0o777);
    }

    /// A program is found as spawning would find it, which on Windows
    /// includes the `.exe` a bare `./target/release/mycli` resolves to.
    #[test]
    fn a_built_program_is_found_with_the_platform_suffix() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("mycli");
        assert_eq!(spawned_path(&bin), None);
        let file = format!("{}{}", bin.display(), std::env::consts::EXE_SUFFIX);
        std::fs::write(&file, b"").unwrap();
        assert_eq!(spawned_path(&bin), Some(std::path::PathBuf::from(file)));
    }

    /// An explicit class wins over the derived one. This is how a project
    /// partitions its series across a toolchain bump, which tak cannot detect.
    #[test]
    fn an_explicit_runner_class_wins() {
        let s = Settings {
            runner_class: "gha-linux-x64-rust1.85".into(),
            ..Settings::default()
        };
        assert_eq!(runner_class(&s), "gha-linux-x64-rust1.85");
    }

    /// Empty means derive, and whitespace is empty. Recording under a blank
    /// class would silently merge every machine into one series.
    #[test]
    fn a_blank_class_falls_back_to_the_derived_name() {
        for blank in ["", "   "] {
            let s = Settings {
                runner_class: blank.into(),
                ..Settings::default()
            };
            let got = runner_class(&s);
            assert!(!got.trim().is_empty(), "{blank:?} produced {got:?}");
            assert!(got.contains('-'), "expected a derived name, got {got:?}");
        }
    }
}