stokehold 0.4.8

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

use std::collections::VecDeque;

use crate::job::{Capacity, Job, Live, State, Usage, Weights};

/// A backfilling job may pass the head only while the head has waited less than this.
pub const BACKFILL_WINDOW_MS: i64 = 60_000;
/// Memory target: jobs start while measured use plus holds stays within this % of RAM, and memory used at this % blocks.
const MEM_PCT: u64 = 95;
/// VRAM reservations stay within this % of capacity.
const VRAM_PCT: u64 = 90;
/// The CPU target: jobs start while the machine's CPU plus one core stays within this % of every core (2026-11-21: Todd
/// wants the Mac about 95% hot; it was 90%).
const CPU_PCT: u64 = 95;
/// macOS memory pressure level 2 ("warn") blocks only while memory used is at least this %. Level 2 is common and sticky:
/// on 2026-11-21 it held for hours at 49-58% used with 1.8 of 3 GB swap, and vetoed every start (40+ minutes with
/// nothing running at 27% CPU). Level 4 ("critical") always blocks.
const WARN_MEM_PCT: u64 = 85;
/// A tiny job (at most the backfill share of cores and this fraction, 1/32, of RAM) may pass a head that is blocked by
/// memory, VRAM or a guard (for up to `TINY_BYPASS_MS` of its wait), or a ramp hold it does not prolong.
const TINY_MEM: (u64, u64) = (1, 32);
/// Tiny jobs pass a head blocked by memory, VRAM or a guard only while it has waited under this long: a stream of them
/// (up to 1/32 of RAM each) could otherwise hold its memory away until its timeout.
pub const TINY_BYPASS_MS: i64 = 5 * 60_000;
/// How far back the shared CPU readings count towards the sustained CPU.
pub const BUSY_WINDOW_MS: i64 = 20_000;
/// The CPU counts as pinned at or over this % busy: nothing new starts, whatever the holds and the load say (0.4.8).
/// The 6 hours to 2026-11-21 21:50 UTC on 0.4.7: the Mac read over 95% CPU or 3 x cores of load in 80% of samples, and
/// 190 of 272 starts came while it read at least 95% busy or load1 over 48. Bursty jobs (`make lint test-changed`, 25
/// minutes at about 1 core with spikes to 10-11) swung the CPU between 35% and 99% within seconds, and starts landed in
/// the dips.
pub const CPU_PINNED_PCT: u64 = 98;
/// How far back a pinned CPU reading blocks starts (`CPU_PINNED_PCT`): a start in a dip between two spikes still waits.
pub const PINNED_WINDOW_MS: i64 = 10_000;
/// Load at or over this many times the core count blocks only while the CPU is also this busy.
const LOAD_SOFT: f64 = 2.0;
const LOAD_BUSY_CPU_PCT: u64 = 90;
/// A rising load at or over `LOAD_SOFT` x cores blocks only while the CPU is at least this busy; below it the load is
/// threads waiting on I/O, not CPU work (and blocking there would leave the CPU under the 75% that counts as underused).
const LOAD_RISING_CPU_PCT: u64 = 75;
/// Load at or over this many times the core count blocks unless Linux PSI shows it is not CPU work: without a PSI
/// reading (macOS) it always blocks; with one, it blocks once the CPU is at least `LOAD_HARD_CPU_PCT` busy or tasks
/// stalled waiting for a CPU (PSI cpu `some avg10`) reach `CPU_PSI_PCT`.
/// 0.4.8: before, it blocked whatever the CPU said; on the rig a load of 35 on 16 cores read 8-15% CPU with PSI cpu
/// `some` under 1 (threads in I/O wait, mostly Postgres and WSL), which is no CPU overload. The 2026-11-19 Mac load
/// of 120 on 16 cores came with the CPU pinned, so it still blocks.
const LOAD_HARD: f64 = 4.0;
/// The CPU % that confirms a load of `LOAD_HARD` x cores.
const LOAD_HARD_CPU_PCT: u64 = 50;
/// Load at or over this many times the core count blocks whatever the CPU says: a 6 x cores storm is never safe to add
/// to, confirmed or not (the 2026-11-19 load of 120 on 16 cores was 7.5 x).
const LOAD_EXTREME: f64 = 6.0;
/// Linux PSI cpu `some avg10` (% of the last 10 s some task waited for a CPU) at or over this confirms any load of
/// `LOAD_SOFT` x cores or more: tasks really queue for the CPU.
const CPU_PSI_PCT: u64 = 25;
/// A job admitted this recently has not ramped its CPU yet.
pub const RAMP_MS: i64 = 10_000;
/// A learned or declared CPU size with no known time to peak is held this long, unless its peak shows sooner.
pub const CPU_FALLBACK_HOLD_MS: i64 = 30_000;
/// A learned CPU peak is never held longer than this, whatever history says: a run that never reaches its learned peak
/// (an incremental build) must not keep the machine reserved.
pub const CPU_MAX_HOLD_MS: i64 = 120_000;
/// A held CPU peak has shown up once the job's live use reaches this fraction (3/4) of it.
const CPU_SHOWN: (u64, u64) = (3, 4);
/// For this long after admission a ramping job holds its full peak, whatever the machine reads: the stagger floor.
pub const RAMP_FULL_MS: i64 = 3_000;
/// A learned peak of at least this fraction (3/4) of the machine keeps the full `RAMP_MS` hold, like a whole-machine hold: two
/// such jobs together would overload it, and an idle reading right after the floor proves nothing yet.
const FULL_HOLD_FRACTION: (u64, u64) = (3, 4);
/// A learned memory size with no known time to peak is held this long after admission.
pub const MEM_FALLBACK_HOLD_MS: i64 = 60_000;
/// After its hold, a learned size's unused part shrinks linearly to nothing over this long.
pub const MEM_DECAY_MS: i64 = 60_000;
/// The learned unused parts together may take at most this fraction (3/4) of the memory still free (ceiling minus
/// machine use), so a burst cannot all peak at once while measured use still admits jobs.
const MEM_HELD_CAP: (u64, u64) = (3, 4);
/// After `RAMP_FULL_MS`, a machine measured under this CPU % has room the ramping job is not using: its hold is released.
const RAMP_IDLE_CPU_PCT: u64 = 50;
/// Granularity of the search for the moment a ramp-blocked waiter will fit.
const RAMP_STEP_MS: i64 = 250;
const CPU_ASK: u64 = 100;
/// The least CPU (2 cores) a held peak leaves free in the band for small waiters (`backfill`).
const BACKFILL_CPU: u64 = 200;
/// How many recent non-heavy samples the smoother averages (waiters re-sample every 10 s).
pub const SMOOTH_WINDOW: usize = 3;
/// A running job's CPU has plateaued once it has not risen for this long (`cpu_plateaued`).
pub const PLATEAU_MS: u64 = 10_000;
/// A rise of at most this much (1 core, or 1/8 of the level reached if more) still counts as flat.
const PLATEAU_SLACK_CPU: u64 = 100;
/// A big waiter's own learned peak, projected: this fraction (1/2) of it must fit on top of the projected CPU (measured
/// use plus the unrealized holds of the jobs still ramping) within every core. Learned peaks are the highest 500 ms tree
/// sample, well above what a build sustains, so the whole peak would keep big jobs off a half-busy machine.
/// 0.4.5: 2/5, from 1/2. Measured over 575 runs peaking at 6+ cores for 20 s+, average cores / peak cores is p50 0.18,
/// p75 0.32, p90 0.51, so half sat above p90. 1/3 or 1/4 overran the machine 43-47% of the time in
/// `bursty_big_jobs_start_one_at_a_time_without_pinning_the_machine` (bursts at p90); 2/5 keeps it at 0%.
const PROJECTED_PEAK: (u64, u64) = (2, 5);
/// Past `BACKFILL_WINDOW_MS`, a waiter of at most the backfill share of cores may still pass a head blocked on CPU room
/// (or a ramp hold) while the machine reads under this CPU % and the head has waited under `TINY_BYPASS_MS`. Before
/// 0.4.6 the queue was strict FIFO there: an 11-16 core head waiting for 4-5 free cores kept 1-2 core jobs queued for
/// up to 30 minutes while the Mac swung between 30% and 100% (2026-11-21). The 5-minute bound keeps a stream of small
/// jobs from starving the head. (Shrinking the head's projected peak after the window instead overran the machine 52%
/// of the time in `bursty_big_jobs_start_one_at_a_time_without_pinning_the_machine`.)
///
/// 0.4.8: any waiter no bigger than the head (cores, memory and VRAM) may backfill there, not only 1-2 core ones. With
/// 0.4.7 the 1-2 core jobs waited p50 42 s, but 3-8 core ones (`cargo clippy`, `cargo test` at 6 cores) waited p50
/// 21 min behind 11-core `make lint` heads, on a Mac idle 23% of the time while jobs waited. Past `TINY_BYPASS_MS` the
/// head holds the queue (no backfill at all), so only the jobs already running stand between it and its start. Aging
/// its projected peak away instead (tried for 0.4.8) overran the machine 16% of the time in
/// `bursty_big_jobs_start_one_at_a_time_without_pinning_the_machine`.
const UNDERUSED_CPU_PCT: u64 = 75;
/// A running job with a learned sustained level (`Job::cpu_sustained`) holds its full learned peak at least this long
/// after its start, and until its learned time to peak plus margin (`Job::cpu_hold_ms`) has passed, then at most that
/// sustained level (0.4.8): learned peaks are the highest 500 ms sample, and `make lint test-changed` learned 10 cores
/// while it averaged 1.2. A job that sits on 1 core for 60 s and then spikes to 16 keeps its peak reserved until past
/// its learned peak time, so two or three of them are never let in together to spike at once.
pub const SUSTAINED_FULL_MS: i64 = RAMP_MS;
/// A backfiller bigger than tiny may pass a blocked head only when its learned p90 run time (`Job::run_p90_ms`) ends by
/// the head's `TINY_BYPASS_MS` plus this (0.4.8): otherwise a 12-core, 70-minute job arriving at 4:59 of the head's wait
/// would hold the head's room for an hour.
pub const BACKFILL_OVERRUN_MS: i64 = 30_000;
/// The window (ms) of the sustained level: the highest mean of the process tree's CPU over any window this long.
pub const SUSTAINED_WINDOW_MS: u64 = 10_000;
/// Fast lane (0.4.7): a command whose recent runs all finished within this long (and at least
/// `history::FAST_MIN_RUNS` of them, of this very command) is short.
pub const FAST_RUN_MS: u64 = 10_000;
/// A fast-lane job reserves at most this many cores (and a tiny share of RAM, `TINY_MEM`, and no VRAM).
pub const FAST_MAX_CPU: u32 = 2;
/// At most this many fast-lane jobs run at once, so the lane adds at most `FAST_MAX_JOBS` x `FAST_MAX_CPU` cores to a
/// busy machine. A fast-lane job that runs long keeps its slot until it ends (it is never forgotten), and its long run
/// takes the command out of the lane from then on.
pub const FAST_MAX_JOBS: usize = 2;

/// Which check blocked a waiter (recorded in the history; a disk that is too full fails instead of waiting).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum Block {
    Cpu,
    Mem,
    Vram,
    Load1,
    /// No longer a block of its own (the 5-minute load only tells rising from falling); kept so older history parses.
    Load5,
    Queue,
    Ramp,
}

impl Block {
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::Mem => "mem",
            Self::Vram => "vram",
            Self::Load1 => "load1",
            Self::Load5 => "load5",
            Self::Queue => "queue",
            Self::Ramp => "ramp",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    Start,
    /// The job can never run here (the disk is too full even with nothing else running): exit at once.
    Fail(String),
    /// `live` is true when live data is the blocker, so waiting re-samples on a timer; otherwise a job
    /// finishing (a file event) is what unblocks it.
    /// `block` is the check that blocked. `ramp_end_ms` is set when a ramp hold is the blocker: the moment the
    /// earliest ramp ends, so the waiter sleeps exactly until then.
    Wait {
        reason: String,
        live: bool,
        block: Block,
        ramp_end_ms: Option<i64>,
    },
}

struct Blocked {
    reason: String,
    live: bool,
    block: Block,
    ramp_end_ms: Option<i64>,
}

fn blocked(reason: impl Into<String>, live: bool, block: Block) -> Blocked {
    Blocked {
        reason: reason.into(),
        live,
        block,
        ramp_end_ms: None,
    }
}

fn wait(reason: impl Into<String>, block: Block) -> Decision {
    Decision::Wait {
        reason: reason.into(),
        live: false,
        block,
        ramp_end_ms: None,
    }
}

/// max(latest sample, mean of the last few): fast to block when usage jumps (a fresh waiter has one sample only, and a
/// mean alone would take about 20 s to follow a jump), slow to release after a spike or a dip.
#[derive(Debug, Default)]
pub struct Smoother {
    window: VecDeque<Usage>,
}

impl Smoother {
    pub fn push(&mut self, sample: Usage) -> Usage {
        self.window.push_back(sample);
        while self.window.len() > SMOOTH_WINDOW {
            self.window.pop_front();
        }
        let n = u64::try_from(self.window.len().max(1)).unwrap_or(1);
        let sum = self.window.iter().fold(Usage::default(), |a, b| Usage {
            cpu: a.cpu + b.cpu,
            mem: a.mem + b.mem,
            vram: a.vram + b.vram,
        });
        Usage {
            cpu: (sum.cpu / n).max(sample.cpu),
            mem: (sum.mem / n).max(sample.mem),
            vram: (sum.vram / n).max(sample.vram),
        }
    }
}

/// Non-heavy usage: what the machine uses minus what heavy's own process trees use.
#[must_use]
pub fn non_heavy(machine: Usage, heavy_trees: Usage) -> Usage {
    machine.saturating_sub(heavy_trees)
}

fn centi(cores: u32) -> u64 {
    u64::from(cores) * 100
}

/// Centi-cores as `1.25`.
fn cores(centi: u64) -> String {
    format!("{}.{:02}", centi / 100, centi % 100)
}

/// A job small enough to pass a head blocked by anything but CPU room (`TINY_MEM`).
fn tiny(w: Weights, cap: &Capacity) -> bool {
    centi(w.cpu) <= backfill(cap) && w.mem <= cap.mem / TINY_MEM.1 * TINY_MEM.0
}

fn ceiling(cap: &Capacity) -> Usage {
    Usage {
        cpu: centi(cap.cpu) * CPU_PCT / 100,
        mem: cap.mem / 100 * MEM_PCT,
        vram: cap.vram / 100 * VRAM_PCT,
    }
}

/// The CPU (centi-cores) kept out of the hold reservation for small waiters: 2 cores, or 1/8 of the machine if more.
fn backfill(cap: &Capacity) -> u64 {
    (centi(cap.cpu) / 8).max(BACKFILL_CPU)
}

fn request(w: Weights) -> Usage {
    Usage {
        cpu: if w.cpu > 0 { CPU_ASK } else { 0 },
        mem: w.mem,
        vram: w.vram,
    }
}

fn fits(ask: Usage, room: Usage) -> bool {
    ask.cpu <= room.cpu && ask.mem <= room.mem && ask.vram <= room.vram
}

/// VRAM reservations only: running sums plus the request within 90% of capacity. Memory and CPU are live.
#[must_use]
pub fn fits_reservations(req: Weights, running: &[&Job], cap: &Capacity) -> bool {
    let used: u64 = running.iter().map(|j| j.weights.vram).sum();
    req.vram <= ceiling(cap).vram.saturating_sub(used)
}

/// The part of a reservation a job `elapsed_ms` after admission has not yet used. A `declared` size is held for the
/// whole run. A learned one is held until `peak_at_ms` (at least `RAMP_MS`; `MEM_FALLBACK_HOLD_MS` when unknown), then
/// shrinks linearly to nothing over `MEM_DECAY_MS`.
#[must_use]
pub fn mem_unmet(
    reserved: u64,
    live: u64,
    elapsed_ms: i64,
    declared: bool,
    peak_at_ms: Option<i64>,
) -> u64 {
    let (full, tail) = mem_unmet_split(reserved, live, elapsed_ms, declared, peak_at_ms);
    full + tail
}

/// `mem_unmet` split into `(full, tail)`: `full` is held in full (a declared size, or a learned one before its
/// time-to-peak); `tail` is the decaying part after the peak time.
#[must_use]
pub fn mem_unmet_split(
    reserved: u64,
    live: u64,
    elapsed_ms: i64,
    declared: bool,
    peak_at_ms: Option<i64>,
) -> (u64, u64) {
    let unmet = reserved.saturating_sub(live);
    if declared {
        return (unmet, 0);
    }
    let hold = peak_at_ms.unwrap_or(MEM_FALLBACK_HOLD_MS).max(RAMP_MS);
    if elapsed_ms <= hold {
        (unmet, 0)
    } else if elapsed_ms >= hold + MEM_DECAY_MS {
        (0, 0)
    } else {
        (
            0,
            unmet * u64::try_from(hold + MEM_DECAY_MS - elapsed_ms).unwrap_or(0)
                / u64::try_from(MEM_DECAY_MS).unwrap_or(1),
        )
    }
}

/// The CPU a job `elapsed_ms` into its ramp still holds beyond its live use (`peak` already clamped to `machine`). A
/// hold of Docker/VM work (`vm`), a cold whole-machine hold or a peak of `FULL_HOLD_FRACTION` of the machine is full for
/// all of `RAMP_MS`. A smaller learned peak is full for `RAMP_FULL_MS`, then nothing if the machine is measured under `RAMP_IDLE_CPU_PCT` busy, else it shrinks linearly to 0
/// at `RAMP_MS`.
#[must_use]
pub fn ramp_hold(peak: u64, machine: u64, elapsed_ms: i64, cpu_pct: u64, vm: bool) -> u64 {
    if elapsed_ms >= RAMP_MS {
        return 0;
    }
    if elapsed_ms < RAMP_FULL_MS
        || vm
        || peak * FULL_HOLD_FRACTION.1 >= machine * FULL_HOLD_FRACTION.0
    {
        return peak;
    }
    if cpu_pct < RAMP_IDLE_CPU_PCT {
        return 0;
    }
    let left = u64::try_from(RAMP_MS - elapsed_ms).unwrap_or(0);
    let span = u64::try_from(RAMP_MS - RAMP_FULL_MS).unwrap_or(1);
    peak * left / span
}

/// How long a learned or declared CPU peak is held, from history's slowest recent time to peak (`None`: unknown) plus
/// a 25% margin: at least `RAMP_MS`, at most `CPU_MAX_HOLD_MS`, and `CPU_FALLBACK_HOLD_MS` when unknown.
#[must_use]
pub fn cpu_hold_ms(peak_at_ms: Option<u64>) -> i64 {
    peak_at_ms
        .and_then(|ms| i64::try_from(ms.saturating_add(ms / 4)).ok())
        .unwrap_or(CPU_FALLBACK_HOLD_MS)
        .clamp(RAMP_MS, CPU_MAX_HOLD_MS)
}

/// The CPU a running job holds beyond its live use. A job with a learned or declared size (`hold_ms`) holds its whole
/// peak until the peak shows in its live use (3/4 of it), its CPU plateaus past its slowest time to peak (`settled`, see
/// `cpu_plateaued`) or `hold_ms` has passed, like a learned memory size, never
/// less than the `RAMP_FULL_MS` floor: a cargo build spends its first 10-30 s on a few cores, and a hold that ended
/// sooner (or was released because the machine read idle) let several 16-core builds in before any of their CPU showed
/// (2026-11-20). Docker/VM work (its CPU never shows in the tree) holds its whole peak for all of `hold_ms` (at least
/// `RAMP_MS`): before 0.4.6 it kept the 10 s `ramp_hold`, a `docker build` took 10-30 s to show its CPU in the VM, and
/// a second build or a burst of jobs started in between and took the Mac to 100% CPU with load1 130-330
/// (2026-11-21). Job files without `hold_ms` keep the `RAMP_MS` schedule of `ramp_hold`.
#[must_use]
#[expect(
    clippy::too_many_arguments,
    reason = "one job's hold inputs: its size, age, live use and learned schedule"
)]
pub fn cpu_hold(
    peak: u64,
    machine: u64,
    elapsed_ms: i64,
    cpu_pct: u64,
    vm: bool,
    live_cpu: u64,
    hold_ms: Option<i64>,
    settled: bool,
) -> u64 {
    match hold_ms {
        // Docker/VM work: its CPU never shows in the tree (it shows as other programs' CPU, which `headroom_for` nets
        // against this hold), so neither the 3/4 test nor a plateau can release it; only its time can.
        Some(hold) if vm => {
            if elapsed_ms < hold.max(RAMP_MS) {
                peak
            } else {
                0
            }
        }
        Some(hold) => {
            if elapsed_ms < RAMP_FULL_MS {
                peak
            } else if settled || elapsed_ms >= hold || live_cpu * CPU_SHOWN.1 >= peak * CPU_SHOWN.0
            {
                0
            } else {
                peak
            }
        }
        _ => ramp_hold(peak, machine, elapsed_ms, cpu_pct, vm),
    }
}

/// When the CPU hold of a job started at `started_ms` ends at the latest.
fn cpu_hold_end(j: &Job, started_ms: i64) -> i64 {
    started_ms
        + match j.cpu_hold_ms {
            Some(h) if crate::run::hosts_vm_work(&j.cmd) => h.max(RAMP_MS),
            Some(h) => h.max(RAMP_FULL_MS),
            None => RAMP_MS,
        }
}

/// Whether a running job's CPU has plateaued: `samples` are `(ms after the start, centi-cores)` of its process tree,
/// oldest first. Only from `PLATEAU_MS` after `slowest_ms` (its learned SLOWEST time to peak, at least `RAMP_MS`: a
/// median would end the hold before the late half of its runs ramp) on, and only when the last `PLATEAU_MS` is flat
/// within itself: its highest and lowest readings differ by at most 1 core (or 1/8 of the level). A lull between
/// bursts, or a rise, is not flat; a flat run that later rises is no longer plateaued, so its hold is taken again.
/// Such a run has shown its real use: an incremental build, or a test run whose learned peak is one 500 ms spike
/// (2026-11-21: `make check` learned 15 cores, ran on 1.5, and its 2-minute hold kept waiters out at 10-50% CPU).
#[must_use]
pub fn cpu_plateaued(samples: &[(u64, u64)], slowest_ms: u64) -> bool {
    let Some(&(now, _)) = samples.last() else {
        return false;
    };
    let from = slowest_ms.max(u64::try_from(RAMP_MS).unwrap_or(0)) + PLATEAU_MS;
    if now < from {
        return false;
    }
    let cut = now - PLATEAU_MS;
    let recent: Vec<u64> = samples
        .iter()
        .filter(|(ms, _)| *ms > cut)
        .map(|(_, c)| *c)
        .collect();
    let (Some(&hi), Some(&lo)) = (recent.iter().max(), recent.iter().min()) else {
        return false;
    };
    // The window must really span PLATEAU_MS, not one late sample.
    let first = samples
        .iter()
        .find(|(ms, _)| *ms > cut)
        .map_or(now, |s| s.0);
    first <= cut + PLATEAU_MS / 4 && hi - lo <= (hi / 8).max(PLATEAU_SLACK_CPU)
}

/// The machine's sustained CPU %: max(latest, mean of the readings from the last `BUSY_WINDOW_MS`). Fast to block when
/// the CPU rises, slow to release after a dip: a 250 ms window between build steps is not free CPU.
#[must_use]
pub fn sustained_pct(latest: u64, readings: &[(i64, u64)], now_ms: i64) -> u64 {
    let recent: Vec<u64> = readings
        .iter()
        .filter(|(ts, _)| *ts <= now_ms && now_ms - *ts <= BUSY_WINDOW_MS)
        .map(|(_, pct)| *pct)
        .collect();
    let n = u64::try_from(recent.len()).unwrap_or(u64::MAX);
    recent
        .iter()
        .sum::<u64>()
        .checked_div(n)
        .unwrap_or(0)
        .max(latest)
}

/// The highest of the shared CPU readings `(ms, busy %)` in the last `PINNED_WINDOW_MS`; 0 with none.
#[must_use]
pub fn recent_peak_pct(readings: &[(i64, u64)], now_ms: i64) -> u64 {
    readings
        .iter()
        .filter(|(ts, _)| *ts <= now_ms && now_ms - *ts <= PINNED_WINDOW_MS)
        .map(|(_, pct)| *pct)
        .max()
        .unwrap_or(0)
}

/// What is left for a new job once the other programs and the running jobs' real use are counted. CPU counts the
/// larger of the instant use (non-heavy plus each job's live use or ramp hold) and the sustained machine CPU plus the
/// ramp holds not yet in use.
#[cfg(test)]
#[must_use]
pub fn headroom(running: &[&Job], cap: &Capacity, live: &Live, now_ms: i64) -> Usage {
    headroom_for(running, cap, live, now_ms, false)
}

/// A running job's CPU hold (centi-cores) at `now_ms`: its `cpu_hold`, capped to its learned sustained level past its
/// learned peak time (`sustained_hold`) and never under that level (`sustained_floor`). A job not yet stamped holds
/// nothing here.
fn running_hold(j: &Job, cap: &Capacity, live: &Live, now_ms: i64, vm: bool, used: u64) -> u64 {
    let peak = centi(j.weights.cpu).min(centi(cap.cpu));
    j.started_ms.map_or(0, |t| {
        let elapsed = now_ms.saturating_sub(t).max(0);
        let hold = sustained_hold(
            cpu_hold(
                peak,
                centi(cap.cpu),
                elapsed,
                live.cpu_pct,
                vm,
                used,
                j.cpu_hold_ms,
                j.cpu_settled,
            ),
            j.cpu_sustained,
            elapsed,
            vm,
            j.cpu_hold_ms,
        );
        sustained_floor(hold, peak, j.cpu_sustained, vm)
    })
}

/// A running non-VM job with a learned sustained level holds at least that level (at most its peak) for its whole
/// run, even once its peak hold is released (0.4.8): a bursty job (`make lint test-changed`, about 1 core between 10-core
/// spikes for 25 minutes) otherwise counts only its live use in a dip, the next big job starts there, and their spikes
/// coincide (the Mac on 2026-11-21: CPU 100% and load1 up to 77 with six of them running).
#[must_use]
pub fn sustained_floor(hold: u64, peak: u64, sustained: Option<u64>, vm: bool) -> u64 {
    match sustained {
        Some(level) if !vm => hold.max(level.min(peak)),
        _ => hold,
    }
}

/// `headroom` for a request that is `small` (at most `backfill` cores): the unrealized part of the held peaks leaves
/// that backfill share of the CPU band free, so a 1-core waiter is not blocked by a 16-core hold at 13% CPU. A big
/// request sees the whole hold.
#[must_use]
pub fn headroom_for(
    running: &[&Job],
    cap: &Capacity,
    live: &Live,
    now_ms: i64,
    small: bool,
) -> Usage {
    let (mut held, (mut unmet, mut unmet_small), (pre_peak, tail), vm_own, vm_base) =
        running.iter().fold(
            (Usage::default(), (0, 0), (0u64, 0u64), 0u64, 0u64),
            |(a, unmet, learned, vm_own, vm_base), j| {
                let l = live
                    .per_job
                    .iter()
                    .find(|(id, _)| *id == j.id)
                    .map_or_else(Usage::default, |(_, u)| *u);
                let vm = crate::run::hosts_vm_work(&j.cmd);
                let hold = running_hold(j, cap, live, now_ms, vm, l.cpu);
                let cpu = l.cpu.max(hold);
                // A running job not yet stamped, or one with a declared size, holds its whole unused part; a learned size holds
                // it by schedule, and those holds are capped together below.
                let (mem, learned_unmet) = match j.started_ms {
                    Some(t) if !j.mem_declared => (
                        l.mem,
                        mem_unmet_split(
                            j.weights.mem,
                            l.mem,
                            now_ms.saturating_sub(t).max(0),
                            false,
                            j.mem_peak_at_ms,
                        ),
                    ),
                    Some(t) => (
                        l.mem
                            + mem_unmet(
                                j.weights.mem,
                                l.mem,
                                now_ms.saturating_sub(t).max(0),
                                true,
                                None,
                            ),
                        (0, 0),
                    ),
                    None => (l.mem + j.weights.mem.saturating_sub(l.mem), (0, 0)),
                };
                (
                    Usage {
                        cpu: a.cpu + cpu,
                        mem: a.mem + mem,
                        vram: a.vram + l.vram.max(j.weights.vram),
                    },
                    {
                        let own = hold.saturating_sub(l.cpu);
                        // A small job's own unrealized hold is not part of the capped big reservation: it stacks.
                        let is_small =
                            small && centi(j.weights.cpu).min(centi(cap.cpu)) <= backfill(cap);
                        (unmet.0 + own, unmet.1 + if is_small { own } else { 0 })
                    },
                    (learned.0 + learned_unmet.0, learned.1 + learned_unmet.1),
                    // Netted only past `RAMP_MS`: before that, other programs' CPU is not yet this job's.
                    vm_own
                        + u64::from(vm && j.started_ms.is_some_and(|t| now_ms - t >= RAMP_MS))
                            * hold.saturating_sub(l.cpu),
                    // What other programs already used when this job started is not its CPU.
                    vm_base + u64::from(vm) * j.non_heavy_cpu_at_start,
                )
            },
        );
    // A Docker/VM job's CPU shows as other programs' CPU: what shows there is not counted twice with its hold.
    let vm_shown = vm_own.min(live.non_heavy.cpu.saturating_sub(vm_base));
    held.cpu = held.cpu.saturating_sub(vm_shown);
    unmet = unmet.saturating_sub(vm_shown);
    unmet_small = unmet_small.min(unmet);
    let free = ceiling(cap)
        .mem
        .saturating_sub(live.non_heavy.mem)
        .saturating_sub(held.mem);
    // Before a job's learned time-to-peak its hold is full (the cap would leave free memory unprotected while peaks are
    // still coming); only the decaying tail after the peak is capped to a fraction of what is still free.
    held.mem += pre_peak;
    let free = free.saturating_sub(pre_peak);
    held.mem += tail.min(free / MEM_HELD_CAP.1 * MEM_HELD_CAP.0);
    // The unrealized part of a held peak reserves the CPU band, except a backfill share: a big hold (16 cores on 16)
    // would otherwise block even a 1-core waiter for its whole hold while the machine reads 13%. Real use still counts in
    // full, so the band is never exceeded by what is measured, only by what is merely expected.
    let limit = if small {
        ceiling(cap).cpu.saturating_sub(backfill(cap))
    } else {
        u64::MAX
    };
    // The backfill share is one shared budget: the big holds are capped to leave it free, and every admitted small
    // job's own unrealized hold (`unmet_small`) is then spent from it, on top of the cap.
    let live_jobs = held.cpu.saturating_sub(unmet);
    let held_cpu = held
        .cpu
        .saturating_sub(unmet_small)
        .min(limit.saturating_sub(live.non_heavy.cpu))
        .max(live_jobs)
        + unmet_small;
    let measured = live.cpu_sustained_pct * centi(cap.cpu) / 100;
    let instant = live.non_heavy.cpu + held_cpu;
    let sustained = (measured + unmet - unmet_small).min(limit).max(measured) + unmet_small;
    let room = ceiling(cap)
        .saturating_sub(live.non_heavy)
        .saturating_sub(held);
    Usage {
        cpu: ceiling(cap).cpu.saturating_sub(instant.max(sustained)),
        ..room
    }
}

/// The disk cannot hold the request even with no heavy job running: waiting would never help.
#[must_use]
pub fn disk_full(req: Weights, cap: &Capacity, live: &Live) -> Option<String> {
    let need = u128::from(req.disk) + u128::from(cap.disk_total) / 10;
    (u128::from(live.disk_free) < need).then(|| {
        format!(
            "the disk is full: {} free, need {} (the request plus 10% of the disk). Clean up, or ask Todd",
            crate::sizes::fmt_size(live.disk_free),
            crate::sizes::fmt_size(u64::try_from(need).unwrap_or(u64::MAX))
        )
    })
}

/// Load counts as rising only when load1 exceeds load5 by this factor, so jitter at steady load does not flip it.
const RISING_MARGIN: f64 = 1.1;

/// Live guards, a veto only. The 1-minute load blocks at 4 x cores always without Linux PSI (macOS), and with it once the
/// CPU is at least 50% busy or PSI cpu `some` reads at least 25% (runaway load), 6 x cores always, and critical memory pressure (macOS level 4, Linux PSI) blocks. From 2 x
/// cores up a PSI cpu `some` of 25% blocks too, and the load blocks while it is still rising (load1 > 1.1 x load5)
/// with the CPU at least 75% busy, and while the CPU is at least 90% busy (the CPU is the larger of the latest and the
/// sustained reading); a high load with a calm CPU is I/O wait (macOS counts blocked threads), so it admits. Memory used
/// at 95% blocks too, even a lone job (no exception: a lone 8 GB job at 97% used thrashes), and so does macOS warn
/// pressure with memory used at 85%. Warn alone never blocks (2026-11-21: three jobs queued 40+ minutes with nothing
/// running at 27% CPU, on warn pressure at 49% used).
#[must_use]
pub fn guard_block(cap: &Capacity, live: &Live) -> Option<(String, Block)> {
    let cores = f64::from(cap.cpu);
    let (soft, hard) = (LOAD_SOFT * cores, LOAD_HARD * cores);
    let cpu = live.cpu_pct.max(live.cpu_sustained_pct);
    let peak = live.cpu_pct.max(live.cpu_recent_peak_pct);
    if peak >= CPU_PINNED_PCT {
        return Some((
            format!(
                "cpu pinned: {peak}% busy in the last {} s",
                PINNED_WINDOW_MS / 1_000
            ),
            Block::Cpu,
        ));
    }
    let psi = live.cpu_pressure.filter(|p| *p >= CPU_PSI_PCT);
    let psi_note = psi.map_or_else(String::new, |p| format!(", cpu pressure {p}%"));
    if live.load1 >= LOAD_EXTREME * cores {
        return Some((
            format!(
                "1-minute load {:.1} >= {:.0} (6 x {} cores)",
                live.load1,
                LOAD_EXTREME * cores,
                cap.cpu
            ),
            Block::Load1,
        ));
    }
    // Without PSI (macOS, or an unreadable file) nothing can tell CPU overload from I/O wait, so 4 x cores blocks
    // unconditionally there, as before 0.4.8; only a PSI reading under `CPU_PSI_PCT` with a calm CPU relaxes it.
    let unconfirmed = live.cpu_pressure.is_none();
    if live.load1 >= hard && (unconfirmed || cpu >= LOAD_HARD_CPU_PCT || psi.is_some()) {
        return Some((
            format!(
                "1-minute load {:.1} >= {hard:.0} (4 x {} cores), cpu {cpu}% busy{psi_note}",
                live.load1, cap.cpu
            ),
            Block::Load1,
        ));
    }
    if live.mem_pressure {
        return Some(("critical memory pressure".into(), Block::Mem));
    }
    if live.load1 >= soft {
        if live.load1 > live.load5 * RISING_MARGIN && cpu >= LOAD_RISING_CPU_PCT {
            return Some((
                format!(
                    "1-minute load {:.1} >= {soft:.0} (2 x {} cores) and still rising (5-minute {:.1}), cpu {cpu}% busy",
                    live.load1, cap.cpu, live.load5
                ),
                Block::Load1,
            ));
        }
        if cpu >= LOAD_BUSY_CPU_PCT || psi.is_some() {
            return Some((
                format!(
                    "1-minute load {:.1} >= {soft:.0} (2 x {} cores) and cpu {cpu}% busy{psi_note}",
                    live.load1, cap.cpu
                ),
                Block::Load1,
            ));
        }
    }
    if live.mem_used_pct >= MEM_PCT {
        return Some((
            format!("memory {}% used >= {MEM_PCT}%", live.mem_used_pct),
            Block::Mem,
        ));
    }
    if live.mem_pressure_warn && live.mem_used_pct >= WARN_MEM_PCT {
        return Some((
            format!(
                "memory pressure warn with memory {}% used >= {WARN_MEM_PCT}%",
                live.mem_used_pct
            ),
            Block::Mem,
        ));
    }
    None
}

/// Why a request cannot start now, or `None`. Alone (nothing running) a clamped request always passes
/// the resource checks, so a busy desktop cannot starve it forever; guards still apply.
fn blocker(
    w: Weights,
    sustained: Option<u64>,
    running: &[&Job],
    cap: &Capacity,
    live: &Live,
    now_ms: i64,
    waited_ms: i64,
) -> Option<Blocked> {
    if !running.is_empty() {
        if !fits_reservations(w, running, cap) {
            return Some(blocked("vram reservations full", false, Block::Vram));
        }
        let small = centi(w.cpu) <= backfill(cap);
        let mut ask = request(w);
        if small {
            // A small waiter's learned peak must fit in what the band has left after every outstanding hold.
            ask.cpu = ask.cpu.max(centi(w.cpu));
        } else {
            // A big waiter's projected peak (half its learned peak) must fit within every core on top of the projected
            // CPU: one free core under the band let 13-core builds in at 83% busy, and they took the machine to 100%
            // with load1 at 34 (2026-11-21). room = band - projected, so projected + peak/2 <= all cores is this ask.
            // A whole-machine waiter (cold, or a learned 16-core peak) that has waited past `BACKFILL_WINDOW_MS` (it holds the queue) drops this: a cold head asks for the
            // whole machine, and its projected peak fits only at 50% busy, which left a machine with one long job at 50-60%
            // while jobs queued. It then starts under the band like in 0.4.3; the load, memory and stagger guards stay.
            if waited_ms < BACKFILL_WINDOW_MS || w.cpu < cap.cpu {
                let over_band = centi(cap.cpu) - ceiling(cap).cpu;
                ask.cpu = ask.cpu.max(
                    projected_peak(centi(w.cpu).min(centi(cap.cpu)), sustained)
                        .saturating_sub(over_band),
                );
            }
        }
        let room_at = |t: i64| headroom_for(running, cap, live, t, small);
        if !fits(ask, room_at(now_ms)) {
            // Would it fit without the ramp holds? Then the ramp is the blocker, and the holds shrink on a known schedule:
            // name the first moment it fits with the machine as measured now (at the latest, when the last ramp ends).
            if fits(ask, room_at(i64::MAX)) {
                let last = running
                    .iter()
                    .filter_map(|j| j.started_ms.map(|t| cpu_hold_end(j, t)))
                    .filter(|e| *e > now_ms)
                    .max();
                let end = last.map(|last| {
                    // Every step, plus the exact moments the stagger floors end (where an idle machine releases a hold).
                    let floors = running
                        .iter()
                        .filter_map(|j| j.started_ms)
                        .map(|t| t + RAMP_FULL_MS);
                    let mut at: Vec<i64> = (1..=(last - now_ms) / RAMP_STEP_MS)
                        .map(|k| now_ms + k * RAMP_STEP_MS)
                        .chain(floors)
                        .filter(|t| *t > now_ms && *t < last)
                        .collect();
                    at.sort_unstable();
                    at.into_iter()
                        .find(|t| fits(ask, room_at(*t)))
                        .unwrap_or(last)
                });
                return Some(Blocked {
                    reason: format!(
                        "cpu held for jobs still ramping up: needs {} cores, {} free now under the {CPU_PCT}% band",
                        cores(ask.cpu),
                        cores(room_at(now_ms).cpu)
                    ),
                    live: true,
                    block: Block::Ramp,
                    ramp_end_ms: end,
                });
            }
            let room = room_at(now_ms);
            let (reason, block) = if ask.cpu > room.cpu {
                (
                    format!(
                        "cpu: needs {} cores, {} free under the {CPU_PCT}% band (machine {}% busy)",
                        cores(ask.cpu),
                        cores(room.cpu),
                        live.cpu_pct.max(live.cpu_sustained_pct)
                    ),
                    Block::Cpu,
                )
            } else if ask.mem > room.mem {
                (
                    format!(
                        "mem: needs {}, {} free under {MEM_PCT}% of RAM after running jobs' holds",
                        crate::sizes::fmt_size(ask.mem),
                        crate::sizes::fmt_size(room.mem)
                    ),
                    Block::Mem,
                )
            } else {
                (
                    format!(
                        "vram: needs {}, {} free",
                        crate::sizes::fmt_size(ask.vram),
                        crate::sizes::fmt_size(room.vram)
                    ),
                    Block::Vram,
                )
            };
            return Some(blocked(reason, true, block));
        }
    }
    guard_block(cap, live).map(|(why, block)| blocked(why, true, block))
}

/// A big waiter's projected peak (centi-cores), what must fit on top of the projected CPU within every core: 2/5 of its
/// learned `peak` (`PROJECTED_PEAK`), or its learned sustained level when lower (0.4.8, `Job::cpu_sustained`).
#[must_use]
pub fn projected_peak(peak: u64, sustained: Option<u64>) -> u64 {
    (peak * PROJECTED_PEAK.0 / PROJECTED_PEAK.1).min(sustained.unwrap_or(u64::MAX))
}

/// A running job's CPU hold with its learned sustained level (`sustained`, centi-cores) applied: once past both
/// `SUSTAINED_FULL_MS` and its learned time to peak plus margin (`hold_ms`, `cpu_hold_ms`), a non-VM job holds at most
/// that level, not its brief learned peak. Before then its peak may still be ahead, so it keeps `hold`. Docker/VM work
/// (its CPU does not show in the tree, so no sustained level is learned for it), jobs without a level and jobs without
/// a learned time to peak keep `hold`.
#[must_use]
pub fn sustained_hold(
    hold: u64,
    sustained: Option<u64>,
    elapsed_ms: i64,
    vm: bool,
    hold_ms: Option<i64>,
) -> u64 {
    match (sustained, hold_ms) {
        (Some(level), Some(peak_by)) if !vm && elapsed_ms >= peak_by.max(SUSTAINED_FULL_MS) => {
            hold.min(level)
        }
        _ => hold,
    }
}

/// The sustained level of CPU samples `(ms after the start, centi-cores)`, oldest first: the highest mean over any
/// `SUSTAINED_WINDOW_MS` window (the mean of the whole run when it is shorter). 0 with no samples.
#[must_use]
pub fn sustained_level(samples: &[(u64, u64)]) -> u64 {
    let Some(&(last, _)) = samples.last() else {
        return 0;
    };
    let mean = |w: &[(u64, u64)]| {
        w.iter().map(|s| s.1).sum::<u64>() / u64::try_from(w.len().max(1)).unwrap_or(1)
    };
    if last < SUSTAINED_WINDOW_MS {
        return mean(samples);
    }
    let mut best = 0;
    let mut from = 0;
    for (i, &(at, _)) in samples.iter().enumerate() {
        while samples[from].0 + SUSTAINED_WINDOW_MS <= at {
            from += 1;
        }
        if at >= SUSTAINED_WINDOW_MS {
            best = best.max(mean(&samples[from..=i]));
        }
    }
    best
}

/// Whether a job may use the fast lane: its slowest recent run (`history::Defaults::slowest_run_ms`) was at most
/// `FAST_RUN_MS`, and it reserves at most `FAST_MAX_CPU` cores, a tiny share of RAM and no VRAM.
#[must_use]
pub fn fast_lane_eligible(w: Weights, cap: &Capacity, slowest_run_ms: Option<u64>) -> bool {
    slowest_run_ms.is_some_and(|ms| ms <= FAST_RUN_MS)
        && w.cpu <= FAST_MAX_CPU
        && w.mem <= cap.mem / TINY_MEM.1 * TINY_MEM.0
        && w.vram == 0
}

/// A running fast job whose live CPU is above `FAST_MAX_CPU` was misclassified (a cached no-op that became a real
/// build): the lane closes until it ends, so a second one cannot join it.
fn fast_job_outgrew_lane(running: &[&Job], live: &Live) -> bool {
    running.iter().filter(|j| j.fast).any(|j| {
        live.per_job
            .iter()
            .any(|(id, u)| *id == j.id && u.cpu > centi(FAST_MAX_CPU))
    })
}

/// Real CPU room for the lane: the machine is below 100% busy and at least `FAST_MAX_CPU` cores are free by the live
/// sample, so a misclassified job cannot stack onto a saturated machine.
fn fast_cpu_room(cap: &Capacity, live: &Live) -> bool {
    let busy = live.cpu_pct.max(live.cpu_sustained_pct);
    let free_centi = u64::from(cap.cpu) * 100 * 100u64.saturating_sub(busy) / 100;
    busy < 100 && free_centi >= centi(FAST_MAX_CPU)
}

/// The fast lane: a fast job (`Job::fast`) starts past the CPU band, ramp holds and the queue while fewer than
/// `FAST_MAX_JOBS` fast jobs run, its memory fits the measured headroom and no guard (load, memory pressure, memory
/// used) vetoes. A 1 s, 1-core `make lint` otherwise waited 204 s on a rig at 95-98% busy that it would have added
/// next to nothing to (2026-11-21). False when the lane does not apply; the normal checks decide then.
fn fast_lane(job: &Job, running: &[&Job], cap: &Capacity, live: &Live, now_ms: i64) -> bool {
    job.fast
        && running.iter().filter(|j| j.fast).count() < FAST_MAX_JOBS
        && !fast_job_outgrew_lane(running, live)
        && fast_cpu_room(cap, live)
        && guard_block(cap, live).is_none()
        && fits_reservations(job.weights, running, cap)
        && job.weights.mem <= headroom_for(running, cap, live, now_ms, true).mem
}

/// Would `job`, started at `now_ms`, still run (by its learned p90 run time) past the head's backfill time plus
/// `BACKFILL_OVERRUN_MS`? True with no learned run time.
fn outlasts_backfill(job: &Job, head: &Job, now_ms: i64) -> bool {
    let by = head.enqueued_ms + TINY_BYPASS_MS + BACKFILL_OVERRUN_MS;
    job.run_p90_ms
        .and_then(|d| i64::try_from(d).ok())
        .is_none_or(|d| now_ms.saturating_add(d) > by)
}

/// Can `job` start now, given every job file (already pruned of dead ones)?
#[must_use]
pub fn evaluate(job: &Job, jobs: &[Job], cap: &Capacity, live: &Live, now_ms: i64) -> Decision {
    let running: Vec<&Job> = jobs.iter().filter(|j| j.state == State::Running).collect();
    // A waiter that is stopped (Ctrl-Z) cannot start, so it never blocks the queue behind it.
    let mut queued: Vec<&Job> = jobs
        .iter()
        .filter(|j| j.state == State::Queued && (j.id == job.id || !live.stopped.contains(&j.id)))
        .collect();
    queued.sort_by(|a, b| (a.enqueued_ms, &a.id).cmp(&(b.enqueued_ms, &b.id)));

    if let Some(why) = disk_full(job.weights, cap, live) {
        return Decision::Fail(why);
    }
    if fast_lane(job, &running, cap, live, now_ms) {
        return Decision::Start;
    }
    if let Some(head) = queued.first().filter(|h| h.id != job.id) {
        let head_blocker = |rs: &[&Job]| {
            blocker(
                head.weights,
                head.cpu_sustained,
                rs,
                cap,
                live,
                now_ms,
                now_ms - head.enqueued_ms,
            )
        };
        let head_block = head_blocker(&running);
        let me = Job {
            state: State::Running,
            started_ms: Some(now_ms),
            ..job.clone()
        };
        let mut with_me = running.clone();
        with_me.push(&me);
        if head_block.is_none() {
            // The head could start now: this job may go first only if the head still fits next to it.
            if head_blocker(&with_me).is_some() {
                return wait("queued behind a job that fits now", Block::Queue);
            }
        } else if !tiny(job.weights, cap)
            || head_block.as_ref().is_some_and(|b| match b.block {
                Block::Cpu => true,
                // Behind a ramp hold, only if the head's moment to fit does not move later.
                Block::Ramp => head_blocker(&with_me).is_none_or(|after| {
                    after.block != Block::Ramp
                        || after.ramp_end_ms.unwrap_or(i64::MAX) > b.ramp_end_ms.unwrap_or(i64::MAX)
                }),
                _ => now_ms - head.enqueued_ms >= TINY_BYPASS_MS,
            })
        {
            // A tiny job passes a head blocked by memory, VRAM or a guard until it has waited `TINY_BYPASS_MS`, and one held back by ramp holds
            // when it does not delay the head's start: it takes next to nothing of what the head waits for. Behind CPU
            // room it would, and a stream of them could starve the head.
            // Past the window a waiter no bigger than the head still passes a head held back by CPU room while the machine reads
            // underused (`UNDERUSED_CPU_PCT`), for the first `TINY_BYPASS_MS` of the head's wait.
            // 0.4.8: any waiter no bigger than the head (checked below), not only a small one.
            let backfills_idle_cpu = now_ms - head.enqueued_ms < TINY_BYPASS_MS
                && live.cpu_pct.max(live.cpu_sustained_pct) < UNDERUSED_CPU_PCT
                && head_block
                    .as_ref()
                    .is_some_and(|b| matches!(b.block, Block::Cpu | Block::Ramp));
            if now_ms - head.enqueued_ms >= BACKFILL_WINDOW_MS && !backfills_idle_cpu {
                return wait(
                    format!("queued behind {} (waited over 60 s)", head.id),
                    Block::Queue,
                );
            }
            let (a, h) = (job.weights, head.weights);
            if a.cpu > h.cpu || a.mem > h.mem || a.vram > h.vram {
                return wait("queued behind a smaller-or-equal head", Block::Queue);
            }
            // A backfiller bigger than tiny must be done before the head's backfill time is up (plus a small bound), so
            // it cannot keep the head's room past it; with no learned run time it does not backfill at all.
            if !tiny(a, cap) && outlasts_backfill(job, head, now_ms) {
                return wait(
                    format!(
                        "queued behind {} (its run would outlast the head's backfill time)",
                        head.id
                    ),
                    Block::Queue,
                );
            }
        }
    }
    match blocker(
        job.weights,
        job.cpu_sustained,
        &running,
        cap,
        live,
        now_ms,
        now_ms - job.enqueued_ms,
    ) {
        Some(b) => Decision::Wait {
            reason: b.reason,
            live: b.live,
            block: b.block,
            ramp_end_ms: b.ramp_end_ms,
        },
        None => Decision::Start,
    }
}

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

    const G: u64 = 1 << 30;

    fn cap() -> Capacity {
        Capacity {
            cpu: 10,
            mem: 100 * G,
            vram: 0,
            disk_total: 1000 * G,
            vram_is_ram: false,
        }
    }
    fn calm() -> Live {
        Live {
            load1: 0.5,
            mem_used_pct: 10,
            disk_free: 900 * G,
            ..Live::default()
        }
    }
    fn job(id: &str, cpu: u32, mem_g: u64, state: State, enq: i64) -> Job {
        Job {
            id: id.into(),
            pid: 1,
            start_time: 0,
            weights: Weights {
                cpu,
                mem: mem_g * G,
                vram: 0,
                disk: 0,
            },
            cmd: vec!["x".into()],
            cwd: "/".into(),
            state,
            enqueued_ms: enq,
            started_ms: None,
            blocked_by: None,
            mem_declared: false,
            mem_peak_at_ms: None,
            cpu_hold_ms: None,
            cpu_settled: false,
            non_heavy_cpu_at_start: 0,
            fast: false,
            cpu_sustained: None,
            run_p90_ms: None,
        }
    }
    fn waits(d: &Decision) -> bool {
        matches!(d, Decision::Wait { .. })
    }

    #[test]
    fn alone_always_runs() {
        let me = job("a", 10, 100, State::Queued, 0);
        let busy = Live {
            non_heavy: Usage {
                cpu: 900,
                mem: 90 * G,
                vram: 0,
            },
            ..calm()
        };
        assert_eq!(
            evaluate(&me, std::slice::from_ref(&me), &cap(), &busy, 0),
            Decision::Start
        );
    }

    #[test]
    fn ninety_percent_vram_reservation_ceiling() {
        let c = Capacity {
            vram: 100 * G,
            ..cap()
        };
        let with_vram = |id: &str, g: u64, state| {
            let j = job(id, 1, 1, state, 0);
            Job {
                weights: Weights {
                    vram: g * G,
                    ..j.weights
                },
                ..j
            }
        };
        let run = with_vram("r", 50, State::Running);
        let fits = with_vram("a", 40, State::Queued);
        let over = with_vram("b", 41, State::Queued);
        assert_eq!(
            evaluate(&fits, &[run.clone(), fits.clone()], &c, &calm(), 2),
            Decision::Start
        );
        let d = evaluate(&over, &[run, over.clone()], &c, &calm(), 2);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    live: false,
                    block: Block::Vram,
                    ..
                }
            ),
            "{d:?}"
        );
    }

    #[test]
    fn declared_reservations_over_the_ceiling_admit_when_measured_use_is_low() {
        // The wtlayer case: running reservations (learned/declared) total 88G of 100G, measured memory 43% used.
        let c = cap();
        let live = Live {
            mem_used_pct: 43,
            non_heavy: Usage {
                cpu: 0,
                mem: 20 * G,
                vram: 0,
            },
            per_job: vec![
                (
                    "r1".into(),
                    Usage {
                        cpu: 100,
                        mem: 12 * G,
                        vram: 0,
                    },
                ),
                (
                    "r2".into(),
                    Usage {
                        cpu: 100,
                        mem: 11 * G,
                        vram: 0,
                    },
                ),
            ],
            ..calm()
        };
        let old = |id: &str| Job {
            started_ms: Some(0),
            ..job(id, 2, 44, State::Running, 0)
        };
        let me = job("w", 2, 20, State::Queued, 1);
        let jobs = [old("r1"), old("r2"), me.clone()];
        assert_eq!(
            evaluate(&me, &jobs, &c, &live, 100_000),
            Decision::Start,
            "reservations 88G + 20G > 90G, measured 43G"
        );
        // Right after admission the unused reservation still counts: the same pair blocks as a ramp, then releases.
        let d = evaluate(&me, &jobs, &c, &live, 1_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ramp_end_ms: Some(_),
                    ..
                }
            ),
            "{d:?}"
        );
        // Real pressure still blocks: measured use leaves no room for the request.
        let full = Live {
            non_heavy: Usage {
                cpu: 0,
                mem: 60 * G,
                vram: 0,
            },
            ..live.clone()
        };
        let d = evaluate(&me, &jobs, &c, &full, 100_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Mem,
                    live: true,
                    ..
                }
            ),
            "{d:?}"
        );
    }

    #[test]
    fn mem_unmet_is_held_to_the_learned_peak_then_decays() {
        let unmet = |at: i64, declared, peak| mem_unmet(10 * G, 3 * G, at, declared, peak);
        assert_eq!(
            mem_unmet(10 * G, 12 * G, 0, false, None),
            0,
            "live use over the reservation leaves nothing unmet"
        );
        // Learned peak at 90 s: held in full until then, half left 30 s later, nothing after the decay.
        assert_eq!(unmet(RAMP_MS, false, Some(90_000)), 7 * G);
        assert_eq!(unmet(90_000, false, Some(90_000)), 7 * G);
        assert_eq!(
            unmet(90_000 + MEM_DECAY_MS / 2, false, Some(90_000)),
            7 * G / 2
        );
        assert_eq!(unmet(90_000 + MEM_DECAY_MS, false, Some(90_000)), 0);
        // A peak earlier than the ramp still holds through the ramp; an unknown peak uses the fallback hold.
        assert_eq!(unmet(RAMP_MS, false, Some(2_000)), 7 * G);
        assert_eq!(unmet(MEM_FALLBACK_HOLD_MS, false, None), 7 * G);
        assert_eq!(unmet(MEM_FALLBACK_HOLD_MS + MEM_DECAY_MS, false, None), 0);
        // A declared size is held for the whole run.
        assert_eq!(unmet(10_000_000, true, None), 7 * G);
    }

    fn big_mac() -> Capacity {
        Capacity {
            cpu: 16,
            mem: 64 * G,
            vram: 0,
            disk_total: 1000 * G,
            vram_is_ram: false,
        }
    }

    /// How many of 12 waiters, each with a learned 12G peak that use 1G for their first minutes, start in turn on a
    /// 64G Mac with 10G of other programs.
    fn admitted_of_twelve(declared: bool, now: impl Fn(usize) -> i64) -> usize {
        let cap = big_mac();
        let mut running: Vec<Job> = vec![];
        for i in 0..12_i64 {
            let w = Job {
                mem_declared: declared,
                mem_peak_at_ms: Some(120_000),
                ..job(&format!("w{i:02}"), 1, 12, State::Queued, i)
            };
            let live = Live {
                non_heavy: Usage {
                    cpu: 0,
                    mem: 10 * G,
                    vram: 0,
                },
                per_job: running
                    .iter()
                    .map(|j: &Job| {
                        (
                            j.id.clone(),
                            Usage {
                                cpu: 50,
                                mem: G,
                                vram: 0,
                            },
                        )
                    })
                    .collect(),
                ..calm()
            };
            let mut all = running.clone();
            all.push(w.clone());
            if evaluate(&w, &all, &cap, &live, now(usize::try_from(i).unwrap_or(0)))
                == Decision::Start
            {
                running.push(Job {
                    state: State::Running,
                    started_ms: Some(0),
                    ..w
                });
            }
        }
        running.len()
    }

    #[test]
    fn twelve_late_peaking_jobs_do_not_all_start_on_a_64g_mac() {
        // Reviewer's case: 144G of peaks on 64G. 0.4.1 admitted 4; releasing every hold at 10 s admitted all 12.
        // Held until the learned peak (120 s), 30 s in: a few start, never all (4 x 12G + 10G within 95% of 64G).
        assert_eq!(admitted_of_twelve(false, |_| 30_000), 4);
        // Past peak and decay (3 minutes) the holds are gone and measured use (1G each) admits them all.
        assert_eq!(admitted_of_twelve(false, |_| 180_000), 12);
        // Declared sizes are held whatever the time.
        assert_eq!(admitted_of_twelve(true, |_| 3_600_000), 4);
    }

    #[test]
    fn the_free_memory_cap_binds_only_the_decaying_tail_not_the_hold_before_the_peak() {
        // 64G Mac (57.6G usable), 10G other programs, one learned 40G job (peak at 120 s) using nothing yet.
        // Old cap: min(40G, 3/4 of 47.6G free = 35.7G) left 4.3G of its reservation unprotected before the peak.
        let cap = big_mac();
        let live = Live {
            non_heavy: Usage {
                cpu: 0,
                mem: 10 * G,
                vram: 0,
            },
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 50,
                    mem: 0,
                    vram: 0,
                },
            )],
            ..calm()
        };
        let r = Job {
            started_ms: Some(0),
            mem_peak_at_ms: Some(120_000),
            ..job("r", 1, 40, State::Running, 0)
        };
        let usable = ceiling(&cap).mem;
        let at = |ms| headroom(&[&r], &cap, &live, ms).mem;
        // Before the learned peak the hold is full: free = usable - 10G - 40G exactly.
        assert_eq!(at(30_000), usable - 50 * G);
        assert_eq!(at(120_000), usable - 50 * G);
        // After the peak, the decaying tail (here 20G at the midpoint) is still under the cap, so it is held as is.
        assert_eq!(at(150_000), usable - 30 * G);
        // A tail larger than 3/4 of what is free is capped: 3/4 of 47.6G, not the whole hold.
        let big = Job {
            weights: Weights {
                mem: 80 * G,
                ..r.weights
            },
            ..r.clone()
        };
        let free = usable - 10 * G;
        let tail = 80 * G / 2;
        assert!(tail > free / 4 * 3);
        assert_eq!(
            headroom(&[&big], &cap, &live, 150_000).mem,
            free - free / 4 * 3
        );
    }

    #[test]
    fn a_declared_mem_is_held_for_the_whole_run() {
        let cap = big_mac();
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 100,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        let me = job("w", 1, 30, State::Queued, 1);
        let held = |declared: bool, now: i64| {
            let r = Job {
                started_ms: Some(0),
                mem_declared: declared,
                mem_peak_at_ms: Some(5_000),
                ..job("r", 1, 40, State::Running, 0)
            };
            evaluate(&me, &[r, me.clone()], &cap, &live, now)
        };
        // Declared 40G, using 2G, an hour in: 38G still held, so 30G does not fit under the 57.6G ceiling.
        assert!(
            matches!(
                held(true, 3_600_000),
                Decision::Wait {
                    block: Block::Mem,
                    ..
                }
            ),
            "{:?}",
            held(true, 3_600_000)
        );
        // The same learned size is gone after its peak time and decay.
        assert_eq!(held(false, 3_600_000), Decision::Start);
    }

    #[test]
    fn headroom_math_with_fake_non_heavy_usage() {
        // 10 cores, 100G. Ceiling 950 centi-cores (95% of every core), 95G. Non-heavy: 2 cores, 30G.
        // Running job reserves 10G but really uses 3 cores / 20G: CPU is live, memory max(reservation, live).
        let run = job("r", 2, 10, State::Running, 0);
        let live = Live {
            non_heavy: Usage {
                cpu: 200,
                mem: 30 * G,
                vram: 0,
            },
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 300,
                    mem: 20 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        let room = headroom(&[&run], &cap(), &live, 100_000);
        assert_eq!(
            room,
            Usage {
                cpu: 950 - 200 - 300,
                mem: 95 * G - 30 * G - 20 * G,
                vram: 0
            }
        );
        // Memory fits at exactly the edge, blocked one GiB over; both pass the reservation-only check.
        let edge = job("e", 4, 45, State::Queued, 1);
        assert_eq!(
            evaluate(&edge, &[run.clone(), edge.clone()], &cap(), &live, 2),
            Decision::Start
        );
        let over = job("o", 5, 46, State::Queued, 1);
        let d = evaluate(&over, &[run.clone(), over.clone()], &cap(), &live, 2);
        assert!(matches!(d, Decision::Wait { live: true, .. }), "{d:?}");
        // Past its hold and decay an unused reservation holds nothing; CPU and memory are both just live.
        let idle = Live {
            per_job: vec![("r".into(), Usage::default())],
            non_heavy: Usage::default(),
            ..calm()
        };
        let run = Job {
            started_ms: Some(0),
            ..run
        };
        let room = headroom(&[&run], &cap(), &idle, 200_000);
        assert_eq!((room.cpu, room.mem), (950, 95 * G));
        // Inside the ramp the unused part of the reservation still counts.
        let room = headroom(&[&run], &cap(), &idle, 1_000);
        assert_eq!(room.mem, 85 * G);
    }

    #[test]
    fn non_heavy_is_machine_minus_heavy_trees() {
        let machine = Usage {
            cpu: 800,
            mem: 50 * G,
            vram: 2 * G,
        };
        let trees = Usage {
            cpu: 600,
            mem: 20 * G,
            vram: 5 * G,
        };
        assert_eq!(
            non_heavy(machine, trees),
            Usage {
                cpu: 200,
                mem: 30 * G,
                vram: 0
            }
        );
    }

    #[test]
    fn smoother_is_fast_to_rise_and_slow_to_fall() {
        let mut s = Smoother::default();
        let low = Usage {
            cpu: 100,
            mem: 2 * G,
            vram: 0,
        };
        let hi = Usage {
            cpu: 900,
            mem: 12 * G,
            vram: 0,
        };
        assert_eq!(s.push(low), low);
        assert_eq!(s.push(low), low);
        // A jump counts in full at once (a mean of the window would say 366).
        assert_eq!(s.push(hi), hi, "a rise is not averaged away");
        // After it, the mean (the window holds low, hi, low) releases slowly.
        assert_eq!(
            s.push(low),
            Usage {
                cpu: 366,
                mem: 16 * G / 3,
                vram: 0
            },
            "a fall is released slowly"
        );
        assert_eq!(
            s.push(low),
            Usage {
                cpu: 366,
                mem: 16 * G / 3,
                vram: 0
            }
        );
        for _ in 0..SMOOTH_WINDOW {
            s.push(Usage::default());
        }
        assert_eq!(
            s.push(Usage::default()),
            Usage::default(),
            "old peaks age out"
        );
    }

    #[test]
    fn a_fresh_waiter_sees_a_jump_at_once() {
        // A new waiter's smoother is empty: its first sample is the latest, so a loaded machine blocks at once.
        let mut s = Smoother::default();
        let hot = Usage {
            cpu: 1500,
            mem: 30 * G,
            vram: 0,
        };
        assert_eq!(s.push(hot), hot);
    }

    #[test]
    fn many_tiny_jobs_run_together() {
        let mut all: Vec<Job> = (0..50)
            .map(|i| job(&format!("r{i:02}"), 0, 0, State::Running, 0))
            .collect();
        let me = job("a", 0, 0, State::Queued, 1);
        all.push(me.clone());
        assert_eq!(
            evaluate(&me, &all, &cap(), &calm(), 2),
            Decision::Start,
            "no cap on the number of jobs"
        );
    }

    #[test]
    fn guards_veto() {
        let me = job("a", 1, 1, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        // 10 cores: load 20 blocks only with a busy CPU, load 40 always.
        let busy = Live {
            load1: 21.0,
            load5: 22.0,
            cpu_pct: 95,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, one, &cap(), &busy, 0),
            Decision::Wait {
                live: true,
                block: Block::Load1,
                ..
            }
        ));
        let calm_1m = Live {
            load1: 19.0,
            load5: 5.0,
            cpu_pct: 95,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &calm_1m, 0),
            Decision::Start,
            "macOS load reads high: 2 x cores"
        );
        let io_bound = Live {
            load1: 35.0,
            load5: 36.0,
            cpu_pct: 40,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &io_bound, 0),
            Decision::Start,
            "high, falling load with a calm CPU is threads waiting on I/O"
        );
        let runaway = Live {
            load1: 40.0,
            cpu_pct: 50,
            ..calm()
        };
        assert!(
            matches!(
                evaluate(&me, one, &cap(), &runaway, 0),
                Decision::Wait {
                    block: Block::Load1,
                    ..
                }
            ),
            "4 x cores blocks with the CPU half busy"
        );
        let io_storm = Live {
            cpu_pct: 10,
            cpu_pressure: Some(0),
            ..runaway.clone()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &io_storm, 0),
            Decision::Start,
            "0.4.8: 4 x cores at 10% CPU with PSI showing no CPU pressure is I/O wait"
        );
        let no_psi = Live {
            cpu_pressure: None,
            ..io_storm
        };
        assert!(
            waits(&evaluate(&me, one, &cap(), &no_psi, 0)),
            "without PSI (macOS) 4 x cores blocks whatever the CPU says"
        );
        // Memory used at 95% blocks, a lone job too.
        let mem = Live {
            mem_used_pct: 95,
            ..calm()
        };
        let run = job("r", 1, 1, State::Running, 0);
        assert!(waits(&evaluate(&me, &[run, me.clone()], &cap(), &mem, 0)));
        assert!(waits(&evaluate(&me, one, &cap(), &mem, 0)), "even alone");
        // 2026-11-21 review: 97% used, level 2 pressure, nothing running: an 8 GB job must not start.
        let thrash = Live {
            mem_used_pct: 97,
            mem_pressure_warn: true,
            ..calm()
        };
        let big = job("b", 1, 8, State::Queued, 0);
        assert!(waits(&evaluate(
            &big,
            std::slice::from_ref(&big),
            &cap(),
            &thrash,
            0
        )));
    }

    #[test]
    fn rising_load_blocks_at_two_times_cores_but_falling_load_admits() {
        let me = job("a", 1, 1, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        // 10 cores, soft limit 20. A rising load with a CPU at least 75% busy is builds piling up: blocked.
        let rising = Live {
            load1: 30.0,
            load5: 22.0,
            cpu_pct: 80,
            ..calm()
        };
        let d = evaluate(&me, one, &cap(), &rising, 0);
        assert!(
            matches!(&d, Decision::Wait { block: Block::Load1, live: true, reason, .. } if reason.contains("rising")),
            "{d:?}"
        );
        // The same rising load with a calm CPU is threads waiting on I/O, not CPU overload: admitted.
        let rising_io = Live {
            cpu_pct: 30,
            ..rising.clone()
        };
        assert_eq!(evaluate(&me, one, &cap(), &rising_io, 0), Decision::Start);
        let falling = Live {
            load1: 30.0,
            load5: 38.0,
            cpu_pct: 30,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &falling, 0),
            Decision::Start,
            "falling and CPU under 90%"
        );
        let level = Live {
            load1: 30.0,
            load5: 30.0,
            cpu_pct: 30,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &level, 0),
            Decision::Start,
            "load1 <= load5 is not rising"
        );
        let jitter = Live {
            load1: 31.5,
            load5: 30.0,
            cpu_pct: 30,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, one, &cap(), &jitter, 0),
            Decision::Start,
            "load1 = load5 x 1.05 is jitter, not rising"
        );
        // Falling but the CPU is busy: still blocked.
        let falling_busy = Live {
            cpu_pct: 92,
            ..falling.clone()
        };
        assert!(waits(&evaluate(&me, one, &cap(), &falling_busy, 0)));
        // Below 2 x cores a rising load is fine; at 4 x cores nothing helps.
        let ramping_up = Live {
            load1: 15.0,
            load5: 5.0,
            cpu_pct: 30,
            ..calm()
        };
        assert_eq!(evaluate(&me, one, &cap(), &ramping_up, 0), Decision::Start);
        let hard = Live {
            load1: 41.0,
            load5: 80.0,
            cpu_pct: 55,
            ..calm()
        };
        assert!(waits(&evaluate(&me, one, &cap(), &hard, 0)));
    }

    #[test]
    fn memory_pressure_blocks() {
        let me = job("a", 1, 1, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        let pressured = Live {
            mem_pressure: true,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, one, &cap(), &pressured, 0),
            Decision::Wait {
                block: Block::Mem,
                live: true,
                ..
            }
        ));
        assert_eq!(evaluate(&me, one, &cap(), &calm(), 0), Decision::Start);
    }

    #[test]
    fn eight_cold_builds_start_one_ramp_apart() {
        // 16 cores, 8 jobs with no history: each asks for the whole machine, so each holds all 16 cores while ramping.
        let c = Capacity { cpu: 16, ..cap() };
        let mut jobs: Vec<Job> = (0..8)
            .map(|i| job(&format!("j{i}"), 16, 1, State::Queued, i))
            .collect();
        let mut starts = Vec::new();
        let mut t = 100;
        // Every waiter looks every 100 ms; they admit in FIFO order, as the lock serializes them.
        while t < 100 + 8 * RAMP_MS && starts.len() < 8 {
            for i in 0..jobs.len() {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &calm(), t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                    starts.push(t);
                }
            }
            t += 100;
        }
        assert_eq!(starts.len(), 8);
        // Even on a machine that reads idle, whole-machine holds are never released early: one cold build per ramp.
        assert!(
            starts.windows(2).all(|w| w[1] - w[0] >= RAMP_MS),
            "one cold build per ramp: {starts:?}"
        );
        // Same with the CPU measured 40% busy (a whole-machine waiter needs half the machine free, so not 60%).
        let busy = Live {
            cpu_pct: 40,
            non_heavy: Usage {
                cpu: 640,
                mem: 0,
                vram: 0,
            },
            ..calm()
        };
        let mut jobs: Vec<Job> = (0..3)
            .map(|i| job(&format!("k{i}"), 16, 1, State::Queued, i))
            .collect();
        let mut starts = Vec::new();
        let mut t = 100;
        while t < 100 + 4 * RAMP_MS && starts.len() < 3 {
            for i in 0..jobs.len() {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &busy, t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                    starts.push(t);
                }
            }
            t += 100;
        }
        assert_eq!(starts.len(), 3);
        assert!(
            starts.windows(2).all(|w| w[1] - w[0] >= RAMP_MS),
            "busy: one cold build per ramp: {starts:?}"
        );
        // At one instant only the first is admitted.
        let mut now = jobs.clone();
        for j in &mut now {
            j.state = State::Queued;
            j.started_ms = None;
        }
        let first = evaluate(&now[0], &now, &c, &calm(), 5000);
        assert_eq!(first, Decision::Start);
    }

    #[test]
    fn disk_guard() {
        let mut me = job("a", 1, 1, State::Queued, 0);
        me.weights.disk = 500 * G;
        let low = Live {
            disk_free: 550 * G,
            ..calm()
        };
        assert!(
            matches!(evaluate(&me, std::slice::from_ref(&me), &cap(), &low, 0), Decision::Fail(m) if m.contains("disk is full"))
        );
        let ok = Live {
            disk_free: 600 * G,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, std::slice::from_ref(&me), &cap(), &ok, 0),
            Decision::Start
        );
    }

    #[test]
    fn fifo_head_blocks_non_fitting_follower() {
        let run = job("r", 8, 50, State::Running, 0);
        let head = job("h", 5, 30, State::Queued, 1);
        let big = job("z", 6, 40, State::Queued, 2);
        assert!(waits(&evaluate(
            &big,
            &[run, head, big.clone()],
            &cap(),
            &calm(),
            3
        )));
    }

    #[test]
    fn backfill_only_while_head_is_young_and_follower_smaller() {
        let run = job("r", 8, 70, State::Running, 0);
        let head = job("h", 5, 30, State::Queued, 1);
        let small = Job {
            run_p90_ms: Some(30_000),
            ..job("s", 1, 5, State::Queued, 2)
        };
        let all = [run, head, small.clone()];
        assert_eq!(
            evaluate(&small, &all, &cap(), &calm(), 1000),
            Decision::Start
        );
        assert!(waits(&evaluate(
            &small,
            &all,
            &cap(),
            &calm(),
            BACKFILL_WINDOW_MS + 1
        )));
    }

    #[test]
    fn follower_starts_when_it_fits_together_with_the_head() {
        let head = job("h", 5, 10, State::Queued, 1);
        let small = job("s", 1, 5, State::Queued, 2);
        let all = [head.clone(), small.clone()];
        assert_eq!(evaluate(&small, &all, &cap(), &calm(), 3), Decision::Start);
        assert_eq!(evaluate(&head, &all, &cap(), &calm(), 3), Decision::Start);
    }

    #[test]
    fn follower_waits_when_it_would_stop_the_head_fitting() {
        // The memory ceiling is 90G: head 50 fits alone, but 50 + 50 does not.
        let head = job("h", 5, 50, State::Queued, 1);
        let other = job("o", 5, 50, State::Queued, 2);
        let all = [head.clone(), other.clone()];
        assert!(waits(&evaluate(&other, &all, &cap(), &calm(), 3)));
        assert_eq!(evaluate(&head, &all, &cap(), &calm(), 3), Decision::Start);
        // Same with a running job: head fits (50 + 30), a follower of 20 would push it over 90.
        let run = job("r", 3, 30, State::Running, 0);
        let follow = job("f", 2, 20, State::Queued, 3);
        let all = [run, head.clone(), follow.clone()];
        assert!(waits(&evaluate(&follow, &all, &cap(), &calm(), 4)));
    }

    #[test]
    fn a_ramp_blocker_names_the_moment_it_ends() {
        let c = Capacity { cpu: 16, ..cap() };
        let live = Live {
            non_heavy: Usage {
                cpu: 320,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let ra = Job {
            state: State::Running,
            started_ms: Some(10),
            ..job("a", 16, 8, State::Running, 0)
        };
        let b = job("b", 16, 8, State::Queued, 2);
        // A whole-machine hold (cold) lasts the full ramp, idle or not.
        let d = evaluate(&b, &[ra.clone(), b.clone()], &c, &live, 500);
        assert!(
            matches!(d, Decision::Wait { block: Block::Ramp, ramp_end_ms: Some(e), live: true, .. } if e == 10 + RAMP_MS),
            "{d:?}"
        );
        let warm = Live {
            cpu_pct: 60,
            ..live.clone()
        };
        let d = evaluate(&b, &[ra, b.clone()], &c, &warm, 500);
        assert!(
            matches!(d, Decision::Wait { block: Block::Ramp, ramp_end_ms: Some(e), .. } if e == 10 + RAMP_MS),
            "{d:?}"
        );
        // A learned 8-core peak (under 75%) on a machine that reads idle: released when the stagger floor ends.
        let live = Live {
            non_heavy: Usage {
                cpu: 800,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let warm = Live {
            cpu_pct: 60,
            ..live.clone()
        };
        let rl = Job {
            state: State::Running,
            started_ms: Some(10),
            ..job("l", 8, 8, State::Running, 0)
        };
        // A 4-core waiter asks for one free core (a whole-machine one would need half the machine free).
        let b = job("b", 4, 8, State::Queued, 2);
        let d = evaluate(&b, &[rl.clone(), b.clone()], &c, &live, 500);
        assert!(
            matches!(d, Decision::Wait { block: Block::Ramp, ramp_end_ms: Some(e), .. } if e == 10 + RAMP_FULL_MS),
            "{d:?}"
        );
        // At 60% busy it shrinks linearly: 800 x (10 s - e) / 7 s, rounded down, fits the 620 left (1520 - 800 - the
        // 100 ask) from e = 4.58 s; the next 250 ms step is 4.75 s.
        let d = evaluate(&b, &[rl.clone(), b.clone()], &c, &warm, 500);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ramp_end_ms: Some(4750),
                    ..
                }
            ),
            "{d:?}"
        );
        assert_eq!(
            evaluate(&b, &[rl, b.clone()], &c, &warm, 4750),
            Decision::Start
        );
        // A genuinely busy CPU is a cpu block, with no ramp time.
        let busy = Live {
            non_heavy: Usage {
                cpu: 1550,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            ..job("r", 1, 8, State::Running, 0)
        };
        let d = evaluate(&b, &[run, b.clone()], &c, &busy, 100_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Cpu,
                    ramp_end_ms: None,
                    ..
                }
            ),
            "{d:?}"
        );
    }

    #[test]
    fn peak_core_waiters_start_on_a_mostly_idle_machine() {
        // Both builds peaked near all cores in history (weights.cpu = ncpu); live CPU is 20%.
        let c = Capacity { cpu: 16, ..cap() };
        let live = Live {
            non_heavy: Usage {
                cpu: 320,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let a = job("a", 16, 8, State::Queued, 1);
        let b = job("b", 16, 8, State::Queued, 2);
        assert_eq!(
            evaluate(&a, &[a.clone(), b.clone()], &c, &live, 10),
            Decision::Start
        );
        // a was admitted just now and holds its full 16 cores while ramping: b waits for the ramp, then starts.
        let ra = Job {
            state: State::Running,
            started_ms: Some(10),
            ..a
        };
        assert!(
            waits(&evaluate(&b, &[ra.clone(), b.clone()], &c, &live, 11)),
            "blocked by a's ramp hold"
        );
        assert!(
            waits(&evaluate(
                &b,
                &[ra.clone(), b.clone()],
                &c,
                &live,
                10 + RAMP_FULL_MS
            )),
            "a whole-machine hold is not released early"
        );
        assert_eq!(
            evaluate(&b, &[ra.clone(), b.clone()], &c, &live, 10 + RAMP_MS),
            Decision::Start,
            "the second starts once the first one's ramp has ended"
        );
        let ca = job("c", 16, 8, State::Queued, 3);
        // A genuinely busy CPU still blocks.
        let busy = Live {
            non_heavy: Usage {
                cpu: 1550,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            ..job("r", 16, 8, State::Running, 0)
        };
        assert!(waits(&evaluate(
            &ca,
            &[run, ca.clone()],
            &c,
            &busy,
            100_000
        )));
    }

    #[test]
    fn burst_is_held_back_by_ramp_holds() {
        // 16 cores, ceiling 1520 (95%); every build peaked at 4 cores but is at 0% live while ramping.
        let c = Capacity { cpu: 16, ..cap() };
        let mut jobs: Vec<Job> = (0..8)
            .map(|i| job(&format!("j{i}"), 4, 1, State::Queued, i))
            .collect();
        let mut started = 0;
        // All eight evaluate at the same instant; admit in FIFO order, as the lock serializes them.
        for i in 0..jobs.len() {
            let me = jobs[i].clone();
            if evaluate(&me, &jobs, &c, &calm(), 100) == Decision::Start {
                jobs[i].state = State::Running;
                jobs[i].started_ms = Some(100);
                started += 1;
            }
        }
        assert_eq!(
            started, 4,
            "holds of 400 each leave 320 for the 4th and none for the 5th: not a burst of 8"
        );
        // Once the ramp window passes and live CPU is low, the rest follow.
        let next = jobs
            .iter()
            .find(|j| j.state == State::Queued)
            .unwrap()
            .clone();
        assert_eq!(
            evaluate(&next, &jobs, &c, &calm(), 100 + RAMP_MS),
            Decision::Start
        );
        // Not blocked on peaks long-term: after the ramp the hold is gone entirely.
        let ramped = Job {
            state: State::Running,
            started_ms: Some(0),
            ..job("r", 16, 1, State::Running, 0)
        };
        let room = headroom(&[&ramped], &c, &calm(), RAMP_MS + 1);
        assert_eq!(room.cpu, 1520);
    }

    #[test]
    fn stopped_waiter_file_does_not_block_the_next_waiter() {
        let run = job("r", 1, 50, State::Running, 0);
        let head = job("h", 1, 30, State::Queued, 1);
        let next = job("n", 1, 40, State::Queued, 2);
        let t = 3 + BACKFILL_WINDOW_MS;
        assert!(waits(&evaluate(
            &next,
            &[run.clone(), head.clone(), next.clone()],
            &cap(),
            &calm(),
            t
        )));
        let stopped = Job {
            state: State::Stopped,
            ..head
        };
        assert_eq!(
            evaluate(&next, &[run, stopped, next.clone()], &cap(), &calm(), t),
            Decision::Start
        );
    }

    #[test]
    fn stopped_head_does_not_block_the_next_waiter() {
        let run = job("r", 1, 50, State::Running, 0);
        let head = job("h", 1, 30, State::Queued, 1);
        let next = job("n", 1, 40, State::Queued, 2);
        let all = [run, head, next.clone()];
        assert!(
            waits(&evaluate(
                &next,
                &all,
                &cap(),
                &calm(),
                3 + BACKFILL_WINDOW_MS
            )),
            "a live head blocks the bigger follower"
        );
        let live = Live {
            stopped: vec!["h".into()],
            ..calm()
        };
        assert_eq!(
            evaluate(&next, &all, &cap(), &live, 3 + BACKFILL_WINDOW_MS),
            Decision::Start
        );
    }

    fn mac() -> Capacity {
        Capacity {
            cpu: 16,
            mem: 64 * G,
            vram: 0,
            disk_total: 1000 * G,
            vram_is_ram: true,
        }
    }

    #[test]
    fn a_lagging_five_minute_load_never_blocks_an_idle_machine() {
        // 2026-11-20 03:08: cpu 12%, load1 22.6, load5 34.2, nothing running, one waiter blocked by load5.
        let me = job("a", 4, 4, State::Queued, 0);
        let live = Live {
            load1: 22.6,
            load5: 34.2,
            cpu_pct: 12,
            mem_used_pct: 46,
            non_heavy: Usage {
                cpu: 192,
                mem: 29 * G,
                vram: 0,
            },
            ..calm()
        };
        assert_eq!(
            evaluate(&me, std::slice::from_ref(&me), &mac(), &live, 0),
            Decision::Start
        );
        // 03:22: cpu 16%, load1 21.3, load5 32.9, one job running, three waiting.
        let run = Job {
            started_ms: Some(0),
            ..job("r", 4, 4, State::Running, 0)
        };
        let live = Live {
            load1: 21.3,
            load5: 32.9,
            cpu_pct: 16,
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 100,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 156,
                mem: 24 * G,
                vram: 0,
            },
            ..live
        };
        assert_eq!(
            evaluate(&me, &[run, me.clone()], &mac(), &live, 100_000),
            Decision::Start
        );
    }

    #[test]
    fn a_small_job_starts_at_seventy_percent_cpu() {
        // 2026-11-20 03:31-03:36: cpu 67-73%, one or two jobs running, a waiter blocked by cpu.
        let run = Job {
            started_ms: Some(0),
            ..job("r", 8, 4, State::Running, 0)
        };
        let me = job("a", 4, 4, State::Queued, 1);
        let live = Live {
            load1: 26.0,
            load5: 31.0,
            cpu_pct: 72,
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 800,
                    mem: 4 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 352,
                mem: 22 * G,
                vram: 0,
            },
            ..calm()
        };
        assert_eq!(
            evaluate(&me, &[run.clone(), me.clone()], &mac(), &live, 100_000),
            Decision::Start
        );
        // Jobs keep starting until about one core is left (15 of 16 busy), then wait on cpu.
        let full = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 1100,
                    mem: 4 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 420,
                mem: 22 * G,
                vram: 0,
            },
            cpu_pct: 95,
            ..live
        };
        assert!(matches!(
            evaluate(&me, &[run, me.clone()], &mac(), &full, 100_000),
            Decision::Wait {
                block: Block::Cpu,
                ..
            }
        ));
    }

    #[test]
    fn ramp_hold_is_released_while_measured_cpu_is_low() {
        // 2026-11-20 07:01:33: cpu 20%, one job running (ramping), one waiting, blocked by ramp.
        // 0.3.0 held the running job's peak for the whole 10 s ramp, so the waiter sat with 80% of the CPU idle.
        // Here the running job has a learned 8-core peak (under 75% of the machine), and the waiter a 4-core one.
        let run = Job {
            started_ms: Some(0),
            ..job("r", 8, 4, State::Running, 0)
        };
        let me = job("a", 4, 4, State::Queued, 1);
        let all = [run.clone(), me.clone()];
        let live = Live {
            load1: 29.4,
            load5: 23.7,
            cpu_pct: 20,
            mem_used_pct: 38,
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 150,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 800,
                mem: 22 * G,
                vram: 0,
            },
            ..calm()
        };
        // Inside the stagger floor the hold is full: no simultaneous starts.
        let d = evaluate(&me, &all, &mac(), &live, 1_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ramp_end_ms: Some(RAMP_FULL_MS),
                    ..
                }
            ),
            "{d:?}"
        );
        // After it, the idle machine shows the ramping job's real use: admitted (0.3.0 waited until 10 s).
        assert_eq!(evaluate(&me, &all, &mac(), &live, 4_000), Decision::Start);
        assert_eq!(
            evaluate(&me, &all, &mac(), &live, RAMP_FULL_MS),
            Decision::Start
        );
        // The same moment with a cold running job (whole-machine hold): held for the full 10 s, as in 0.3.0.
        let cold = Job {
            started_ms: Some(0),
            ..job("r", 16, 4, State::Running, 0)
        };
        let all_cold = [cold, me.clone()];
        let d = evaluate(&me, &all_cold, &mac(), &live, 4_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ramp_end_ms: Some(RAMP_MS),
                    ..
                }
            ),
            "{d:?}"
        );
        assert!(waits(&evaluate(&me, &all_cold, &mac(), &live, RAMP_MS - 1)));
        assert_eq!(
            evaluate(&me, &all_cold, &mac(), &live, RAMP_MS),
            Decision::Start
        );
    }

    #[test]
    fn ramp_hold_shrinks_for_a_recent_job_with_a_learned_peak() {
        let me = job("a", 4, 4, State::Queued, 1);
        // 06:22:23: cpu 24%, four running (three ramped, one admitted 5 s ago with a learned 8-core peak), one waiting.
        let mut all: Vec<Job> = (0..3)
            .map(|i| Job {
                started_ms: Some(0),
                ..job(&format!("d{i}"), 4, 2, State::Running, 0)
            })
            .collect();
        all.push(Job {
            started_ms: Some(95_000),
            ..job("new", 8, 2, State::Running, 1)
        });
        all.push(me.clone());
        let live = Live {
            load1: 15.5,
            load5: 14.3,
            cpu_pct: 24,
            mem_used_pct: 46,
            per_job: vec![
                (
                    "d0".into(),
                    Usage {
                        cpu: 80,
                        mem: G,
                        vram: 0,
                    },
                ),
                (
                    "d1".into(),
                    Usage {
                        cpu: 60,
                        mem: G,
                        vram: 0,
                    },
                ),
                (
                    "d2".into(),
                    Usage {
                        cpu: 40,
                        mem: G,
                        vram: 0,
                    },
                ),
                (
                    "new".into(),
                    Usage {
                        cpu: 50,
                        mem: G,
                        vram: 0,
                    },
                ),
            ],
            non_heavy: Usage {
                cpu: 150,
                mem: 25 * G,
                vram: 0,
            },
            ..calm()
        };
        assert_eq!(evaluate(&me, &all, &mac(), &live, 100_000), Decision::Start);
        // The same moment with the CPU busy keeps a shrinking hold: 1180 busy plus the new job's 571 held (800 x 5/7) is
        // over the 1500 that leaves a core free.
        let busy = Live {
            cpu_pct: 70,
            non_heavy: Usage {
                cpu: 1180 - 230,
                mem: 25 * G,
                vram: 0,
            },
            ..live
        };
        assert!(matches!(
            evaluate(&me, &all, &mac(), &busy, 100_000),
            Decision::Wait {
                block: Block::Ramp,
                ..
            }
        ));
    }

    #[test]
    fn big_learned_peaks_and_docker_keep_the_full_hold() {
        let c = Capacity { cpu: 16, ..cap() };
        let idle = Live {
            non_heavy: Usage {
                cpu: 100,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let b = job("b", 15, 8, State::Queued, 2);
        // Two learned 15-core waiters arriving together on an idle machine start at least 10 s apart.
        let ra = Job {
            state: State::Running,
            started_ms: Some(10),
            ..job("a", 15, 8, State::Running, 0)
        };
        assert!(
            waits(&evaluate(
                &b,
                &[ra.clone(), b.clone()],
                &c,
                &idle,
                10 + RAMP_FULL_MS
            )),
            "no early release at 94%"
        );
        assert!(waits(&evaluate(
            &b,
            &[ra.clone(), b.clone()],
            &c,
            &idle,
            10 + RAMP_MS - 1
        )));
        assert_eq!(
            evaluate(&b, &[ra, b.clone()], &c, &idle, 10 + RAMP_MS),
            Decision::Start
        );
        // Under 75% (8 of 16 cores) is still released at 3 s on an idle machine.
        let busy_other = Live {
            non_heavy: Usage {
                cpu: 800,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let rh = Job {
            state: State::Running,
            started_ms: Some(10),
            ..job("h", 8, 8, State::Running, 0)
        };
        assert!(waits(&evaluate(
            &b,
            &[rh.clone(), b.clone()],
            &c,
            &busy_other,
            11
        )));
        assert_eq!(
            evaluate(&b, &[rh, b.clone()], &c, &busy_other, 10 + RAMP_FULL_MS),
            Decision::Start
        );
        // A learned Docker job keeps the 10 s hold even at 8 cores.
        let rd = Job {
            state: State::Running,
            started_ms: Some(10),
            cmd: vec!["docker".into(), "build".into()],
            ..job("d", 8, 8, State::Running, 0)
        };
        assert!(waits(&evaluate(
            &b,
            &[rd.clone(), b.clone()],
            &c,
            &busy_other,
            10 + RAMP_FULL_MS
        )));
        assert_eq!(
            evaluate(&b, &[rd, b.clone()], &c, &busy_other, 10 + RAMP_MS),
            Decision::Start
        );
        // The 75% line itself: 12 of 16 cores is a full hold, 11 is not.
        assert_eq!(ramp_hold(1200, 1600, RAMP_FULL_MS, 0, false), 1200);
        assert_eq!(ramp_hold(1100, 1600, RAMP_FULL_MS, 0, false), 0);
        assert_eq!(ramp_hold(800, 1600, RAMP_FULL_MS, 0, true), 800);
    }

    #[test]
    fn ramp_hold_schedule() {
        let (peak, machine) = (800, 1600);
        assert_eq!(
            ramp_hold(peak, machine, 0, 0, false),
            peak,
            "full at admission"
        );
        assert_eq!(
            ramp_hold(peak, machine, RAMP_FULL_MS - 1, 0, false),
            peak,
            "full through the floor, however idle"
        );
        assert_eq!(
            ramp_hold(peak, machine, RAMP_FULL_MS, 49, false),
            0,
            "released on an idle machine"
        );
        assert_eq!(
            ramp_hold(peak, machine, RAMP_FULL_MS, 50, false),
            peak,
            "shrinks from the full peak on a busy one"
        );
        assert_eq!(
            ramp_hold(peak, machine, 6_500, 80, false),
            400,
            "halfway down at the middle of the shrink"
        );
        assert_eq!(
            ramp_hold(peak, machine, RAMP_MS, 100, false),
            0,
            "gone when the ramp ends"
        );
        // A whole-machine hold (cold or Docker) is full for the whole ramp, however idle the machine reads.
        assert_eq!(ramp_hold(machine, machine, RAMP_FULL_MS, 0, false), machine);
        assert_eq!(ramp_hold(machine, machine, RAMP_MS - 1, 0, false), machine);
        assert_eq!(ramp_hold(machine, machine, RAMP_MS, 0, false), 0);
    }

    #[test]
    fn rising_load_with_idle_cpu_is_io_wait_not_overload() {
        // 2026-11-20 06:59-07:01, a power and network outage: load1 46-58 against load5 24-26 (rising), cpu 16-28%,
        // nothing heavy running. 0.3.0 blocked on the rising load; it is threads stuck in I/O, not CPU work.
        let me = job("a", 4, 4, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        for (load1, load5, cpu_pct) in [(57.85, 24.18, 26), (53.44, 24.32, 28), (46.16, 25.83, 16)]
        {
            let live = Live {
                load1,
                load5,
                cpu_pct,
                mem_used_pct: 36,
                non_heavy: Usage {
                    cpu: cpu_pct * 16,
                    mem: 23 * G,
                    vram: 0,
                },
                ..calm()
            };
            assert_eq!(
                evaluate(&me, one, &mac(), &live, 0),
                Decision::Start,
                "load1 {load1} cpu {cpu_pct}%"
            );
            // The same load with a CPU 80% busy is builds piling up: still blocked.
            let busy = Live {
                cpu_pct: 80,
                ..live.clone()
            };
            assert!(
                matches!(
                    evaluate(&me, one, &mac(), &busy, 0),
                    Decision::Wait {
                        block: Block::Load1,
                        ..
                    }
                ),
                "load1 {load1} busy"
            );
        }
        // 4 x cores (64 on 16) at 16% CPU: the Mac has no PSI, so it blocks whatever the CPU says. Where PSI reads no
        // CPU pressure it is I/O wait (0.4.8); CPU pressure confirms it, and memory pressure blocks.
        let hard = Live {
            load1: 64.0,
            load5: 24.0,
            cpu_pct: 16,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, one, &mac(), &hard, 0),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
        let hard = Live {
            cpu_pressure: Some(0),
            ..hard
        };
        assert_eq!(evaluate(&me, one, &mac(), &hard, 0), Decision::Start);
        let hard = Live {
            cpu_pressure: Some(30),
            ..hard
        };
        assert!(matches!(
            evaluate(&me, one, &mac(), &hard, 0),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
        let pressured = Live {
            load1: 50.0,
            load5: 24.0,
            cpu_pct: 16,
            mem_pressure: true,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, one, &mac(), &pressured, 0),
            Decision::Wait {
                block: Block::Mem,
                ..
            }
        ));
    }

    #[test]
    fn nothing_starts_while_the_cpu_reads_pinned() {
        // 2026-11-21 on 0.4.7: 190 of 272 Mac starts in 6 hours came at 95-100% CPU, most in a dip between spikes of
        // bursty jobs. A pinned reading in the last 10 s blocks every start, the fast lane and a job alone included.
        let me = job("a", 1, 0, State::Queued, 0);
        let fast = Job {
            fast: true,
            ..me.clone()
        };
        let dip = Live {
            cpu_pct: 40,
            cpu_sustained_pct: 70,
            cpu_recent_peak_pct: CPU_PINNED_PCT,
            ..calm()
        };
        for j in [&me, &fast] {
            assert!(matches!(
                evaluate(j, std::slice::from_ref(j), &mac(), &dip, 0),
                Decision::Wait {
                    block: Block::Cpu,
                    ..
                }
            ));
        }
        let calm_again = Live {
            cpu_recent_peak_pct: CPU_PINNED_PCT - 1,
            ..dip
        };
        assert_eq!(
            evaluate(&me, std::slice::from_ref(&me), &mac(), &calm_again, 0),
            Decision::Start
        );
        assert_eq!(
            recent_peak_pct(&[(0, 100), (5_000, 60), (12_000, 50)], 12_000),
            60,
            "only the last 10 s count"
        );
        assert_eq!(recent_peak_pct(&[], 0), 0);
    }

    #[test]
    fn a_bursty_job_keeps_its_sustained_level_after_its_hold_is_released() {
        // Six `make lint test-changed` runs (about 1 core between 10-core spikes for 25 minutes) pinned the Mac on
        // 2026-11-21: each counted only its live use in a dip once its peak hold was released.
        assert_eq!(sustained_floor(0, 1_000, Some(400), false), 400);
        assert_eq!(sustained_floor(900, 1_000, Some(400), false), 900);
        assert_eq!(
            sustained_floor(0, 300, Some(400), false),
            300,
            "never over the peak"
        );
        assert_eq!(
            sustained_floor(0, 1_000, Some(400), true),
            0,
            "a VM job shows as other programs"
        );
        assert_eq!(sustained_floor(0, 1_000, None, false), 0);
        let c = mac();
        let run = Job {
            started_ms: Some(0),
            cpu_hold_ms: Some(RAMP_MS),
            cpu_sustained: Some(1_100),
            ..job("bursty", 11, 2, State::Running, 0)
        };
        let dip = Live {
            cpu_pct: 10,
            cpu_sustained_pct: 10,
            per_job: vec![(
                "bursty".into(),
                Usage {
                    cpu: 100,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        let now = 10 * 60_000;
        let free = headroom(&[&run], &c, &dip, now).cpu;
        assert!(free <= ceiling(&c).cpu - 1_100, "free {free}");
        let next = job("next", 12, 2, State::Queued, now);
        let jobs = [run, next.clone()];
        assert!(waits(&evaluate(&next, &jobs, &c, &dip, now)));
    }

    #[test]
    fn a_saturated_machine_still_blocks() {
        // 2026-11-20 03:19: cpu 100%, load1 55: the guards hold even for a job that would run alone. A pinned CPU is
        // named first; at 90% busy the load guard holds.
        let me = job("a", 4, 4, State::Queued, 0);
        let live = Live {
            load1: 55.3,
            load5: 39.6,
            cpu_pct: 100,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, std::slice::from_ref(&me), &mac(), &live, 0),
            Decision::Wait {
                block: Block::Cpu,
                ..
            }
        ));
        let loaded = Live {
            cpu_pct: 90,
            ..live
        };
        assert!(matches!(
            evaluate(&me, std::slice::from_ref(&me), &mac(), &loaded, 0),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
        // Load 120 on 16 cores (2026-11-19) blocks even if the CPU reads idle: 6 x cores always blocks.
        let storm = Live {
            load1: 120.0,
            cpu_pct: 5,
            ..calm()
        };
        assert!(matches!(
            evaluate(&me, std::slice::from_ref(&me), &mac(), &storm, 0),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
    }

    #[test]
    fn clamp_to_machine_and_fold_vram() {
        let c = cap();
        let w = c.clamp(Weights {
            cpu: 64,
            mem: 999 * G,
            vram: 5 * G,
            disk: 9999 * G,
        });
        assert_eq!(
            w,
            Weights {
                cpu: 10,
                mem: 100 * G,
                vram: 0,
                disk: 1000 * G
            }
        );
        let mac = Capacity {
            vram_is_ram: true,
            ..c
        };
        assert_eq!(
            mac.clamp(Weights {
                cpu: 1,
                mem: 4 * G,
                vram: 2 * G,
                disk: 0
            })
            .mem,
            6 * G
        );
    }

    /// Two builds that started long ago (no ramp holds) using `jobs` centi-cores between them, the rest non-heavy.
    fn pinned(jobs: u64, non_heavy: u64) -> (Vec<Job>, Live) {
        let a = Job {
            started_ms: Some(0),
            ..job("a", 8, 2, State::Running, 0)
        };
        let b = Job {
            started_ms: Some(0),
            ..job("b", 8, 2, State::Running, 0)
        };
        let live = Live {
            cpu_pct: (jobs + non_heavy) / 16,
            per_job: vec![
                (
                    "a".into(),
                    Usage {
                        cpu: jobs / 2,
                        mem: 2 * G,
                        vram: 0,
                    },
                ),
                (
                    "b".into(),
                    Usage {
                        cpu: jobs / 2,
                        mem: 2 * G,
                        vram: 0,
                    },
                ),
            ],
            non_heavy: Usage {
                cpu: non_heavy,
                mem: 20 * G,
                vram: 0,
            },
            ..calm()
        };
        (vec![a, b], live)
    }

    #[test]
    fn a_dip_between_build_steps_does_not_admit_onto_a_pinned_machine() {
        // 2026-11-20 on the Mac and the rig: samples read 98-100% for minutes, yet jobs were admitted between them. A
        // waiter's single 250 ms window that fell between two builds' steps read 80% (1280 of 1600). 0.3.1 measured
        // headroom against every core (1600 - 1280 = 320 >= one core) and started another build into a pinned machine.
        let (mut jobs, dip) = pinned(1_100, 180);
        let me = job("c", 4, 2, State::Queued, 50_000);
        jobs.push(me.clone());
        assert_eq!(dip.cpu_pct, 80);
        // With the readings every heavy process shared over the last 20 s (100, 100, 98, then this 80): mean 94%.
        let readings = [(40_000, 100), (45_000, 100), (52_000, 98), (60_000, 80)];
        let live = Live {
            cpu_sustained_pct: sustained_pct(dip.cpu_pct, &readings, 60_000),
            ..dip.clone()
        };
        assert_eq!(live.cpu_sustained_pct, 94);
        let d = evaluate(&me, &jobs, &mac(), &live, 60_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Cpu,
                    ramp_end_ms: None,
                    ..
                }
            ),
            "{d:?}"
        );
        // Once the machine really has settled at 80% (the readings agree), the job starts: inside the band.
        let settled = [(45_000, 81), (52_000, 79), (60_000, 80)];
        let live = Live {
            cpu_sustained_pct: sustained_pct(80, &settled, 60_000),
            ..dip
        };
        assert_eq!(evaluate(&me, &jobs, &mac(), &live, 60_000), Decision::Start);
    }

    #[test]
    fn jobs_start_up_to_the_band_and_wait_inside_it() {
        // 16 cores: the ceiling is 1520 (95%) and a job asks for one core (100), so it starts up to 88% busy.
        let me = job("c", 4, 2, State::Queued, 1);
        for (busy, starts) in [
            (60, true),
            (75, true),
            (83, true),
            (88, true),
            (89, false),
            (93, false),
            (100, false),
        ] {
            let (mut jobs, live) = pinned(busy * 16 - 160, 160);
            jobs.push(me.clone());
            let live = Live {
                cpu_sustained_pct: busy,
                ..live
            };
            assert_eq!(
                evaluate(&me, &jobs, &mac(), &live, 100_000) == Decision::Start,
                starts,
                "{busy}% busy"
            );
        }
    }

    #[test]
    fn sustained_cpu_rises_at_once_and_falls_slowly() {
        assert_eq!(sustained_pct(70, &[], 0), 70, "no readings: the latest");
        assert_eq!(
            sustained_pct(10, &[(0, 10), (90_000, 100)], 5_000),
            10,
            "a reading from the future (clock skew) is dropped"
        );
        assert_eq!(
            sustained_pct(100, &[(0, 40), (5_000, 40)], 5_000),
            100,
            "a rise counts at once"
        );
        assert_eq!(
            sustained_pct(40, &[(0, 100), (10_000, 100), (20_000, 40)], 20_000),
            80,
            "a fall is averaged"
        );
        assert_eq!(
            sustained_pct(40, &[(0, 100), (25_000, 40)], 25_000),
            40,
            "readings over 20 s old are dropped"
        );
    }

    #[test]
    fn a_rising_load_in_the_underused_zone_admits() {
        // 2026-11-20 on the Mac: waiters blocked on a rising load1 over 32 with the CPU at 60-74%, under the band.
        let me = job("c", 4, 2, State::Queued, 1);
        let (mut jobs, live) = pinned(1_000, 120);
        jobs.push(me.clone());
        let rising = Live {
            load1: 40.0,
            load5: 30.0,
            cpu_sustained_pct: 70,
            ..live
        };
        assert_eq!(rising.cpu_pct, 70);
        assert_eq!(
            evaluate(&me, &jobs, &mac(), &rising, 100_000),
            Decision::Start
        );
        // The same rising load with the sustained CPU at 80% is builds piling up: blocked.
        let busy = Live {
            cpu_sustained_pct: 80,
            ..rising
        };
        assert!(matches!(
            evaluate(&me, &jobs, &mac(), &busy, 100_000),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
    }

    #[test]
    fn thread_inflated_memory_reservations_no_longer_starve_an_idle_rig() {
        // 2026-11-20 09:00 on the rig: cpu 21%, memory 6% used, 3 running, a waiter blocked on "mem". Each `cargo
        // install` had learned a 46 GB peak by summing every rustc thread's copy of its process RSS (2.6 GB real).
        let rig = Capacity {
            cpu: 32,
            mem: 64 * G,
            vram: 0,
            disk_total: 1000 * G,
            vram_is_ram: false,
        };
        let live = Live {
            cpu_pct: 21,
            cpu_sustained_pct: 21,
            mem_used_pct: 6,
            ..calm()
        };
        let me = job("w", 4, 3, State::Queued, 1);
        let inflated = |id: &str| Job {
            started_ms: Some(0),
            ..job(id, 32, 46, State::Running, 0)
        };
        let d = evaluate(
            &me,
            &[inflated("r"), inflated("s"), me.clone()],
            &rig,
            &live,
            100_000,
        );
        // Past the ramp the inflated reservations are only a number: measured memory is 6% used, so the job starts.
        assert_eq!(d, Decision::Start, "{d:?}");
        // Learned without threads (3 GB, 4 cores) the same job starts.
        let real = |id: &str| Job {
            started_ms: Some(0),
            ..job(id, 4, 3, State::Running, 0)
        };
        assert_eq!(
            evaluate(
                &me,
                &[real("r"), real("s"), me.clone()],
                &rig,
                &live,
                100_000
            ),
            Decision::Start
        );
    }

    /// Six cargo-like builds, each with a learned 16-core peak and time to peak `ttp`, queued at once on the 16-core
    /// Mac. Each runs on 2 cores until `ttp` after its start, then takes all 16 (scaled down when over-subscribed),
    /// and finishes `run` after its start. Returns the start times and the most builds ever running before their peak.
    fn burst_of_six(cpu_hold: Option<i64>, ttp: i64, run: i64) -> (Vec<i64>, usize) {
        let c = mac();
        let mut jobs: Vec<Job> = (0..6)
            .map(|i| Job {
                cpu_hold_ms: cpu_hold,
                ..job(&format!("b{i}"), 16, 2, State::Queued, i)
            })
            .collect();
        let (mut starts, mut most_ramping) = (Vec::new(), 0);
        let mut t = 0;
        while t <= 700_000 && starts.len() < 6 {
            jobs.retain(|j| j.started_ms.is_none_or(|s| t - s < run));
            let demand: Vec<(String, u64)> = jobs
                .iter()
                .filter_map(|j| {
                    j.started_ms
                        .map(|s| (j.id.clone(), if t - s < ttp { 200 } else { 1600 }))
                })
                .collect();
            let total: u64 = demand.iter().map(|d| d.1).sum();
            let pct = total.min(1600) * 100 / 1600;
            let live = Live {
                cpu_pct: pct,
                cpu_sustained_pct: pct,
                per_job: demand
                    .iter()
                    .map(|(id, d)| {
                        let cpu = if total > 1600 { d * 1600 / total } else { *d };
                        (
                            id.clone(),
                            Usage {
                                cpu,
                                mem: 2 * G,
                                vram: 0,
                            },
                        )
                    })
                    .collect(),
                ..calm()
            };
            // Every waiter evaluates; the state lock serializes them in FIFO order.
            for i in 0..jobs.len() {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &live, t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                    starts.push(t);
                }
            }
            let ramping = jobs
                .iter()
                .filter(|j| j.started_ms.is_some_and(|s| t - s < ttp))
                .count();
            most_ramping = most_ramping.max(ramping);
            t += 500;
        }
        (starts, most_ramping)
    }

    #[test]
    fn a_burst_of_six_16_core_cargo_builds_starts_one_at_a_time_as_their_peaks_show() {
        // 2026-11-20 after 0.4.2: holds that ended 10 s after admission let builds in before their CPU showed; CPU sat at
        // 95-100% with load1 over 48 (3 x cores). Before the fix (no learned hold): three builds in the first 30 s.
        let (old, old_ramping) = burst_of_six(None, 30_000, 90_000);
        assert!(
            old.iter().filter(|t| **t < 30_000).count() >= 3 && old_ramping >= 3,
            "the 0.4.2 schedule admits a burst: {old:?}"
        );
        // Held until its peak shows (or its learned 30 s time to peak passes): one build at a time.
        let (starts, ramping) = burst_of_six(Some(cpu_hold_ms(Some(30_000))), 30_000, 90_000);
        assert_eq!(ramping, 1, "never two builds ramping at once: {starts:?}");
        assert_eq!(
            starts.len(),
            6,
            "all six still run (no starvation): {starts:?}"
        );
        assert!(
            starts.windows(2).all(|w| w[1] - w[0] >= 30_000),
            "each start waits for the previous peak: {starts:?}"
        );
        // A history from before 0.4.3 (time to peak unknown) holds for the 30 s fallback: still one at a time.
        let (starts, ramping) = burst_of_six(Some(cpu_hold_ms(None)), 20_000, 60_000);
        assert_eq!((ramping, starts.len()), (1, 6), "{starts:?}");
        // Cold jobs (whole machine, nothing learned) get the same hold: never admitted 10 s apart.
        let (starts, ramping) = burst_of_six(Some(CPU_FALLBACK_HOLD_MS), 25_000, 60_000);
        assert_eq!((ramping, starts.len()), (1, 6), "{starts:?}");
        assert!(
            starts.windows(2).all(|w| w[1] - w[0] >= 25_000),
            "cold jobs wait for each other's peak: {starts:?}"
        );
    }

    #[test]
    fn a_hold_from_the_slowest_ramp_outlasts_a_median_length_ramp() {
        // Runs peaked at 20, 30 and 40 s: the median is 30 s. A build that ramps for 38 s is still ramping when a
        // median-length hold ends, but not when the hold is the slowest ramp plus a margin.
        let median_hold = 30_000;
        let hold = cpu_hold_ms(Some(40_000));
        assert!(hold > 40_000, "{hold}");
        let (peak, machine) = (1_600, 1_600);
        let still_ramping = |at, h| cpu_hold(peak, machine, at, 10, false, 200, Some(h), false);
        assert_eq!(still_ramping(38_000, median_hold), 0);
        assert_eq!(still_ramping(38_000, hold), peak);
        assert_eq!(still_ramping(hold, hold), 0, "still bounded");
    }

    #[test]
    fn a_learned_cpu_peak_is_held_until_it_shows_or_its_time_passes() {
        let (peak, machine) = (1_600, 1_600);
        let hold = Some(cpu_hold_ms(Some(32_000)));
        assert_eq!(hold, Some(40_000), "the slowest ramp plus 25%");
        // Before the floor: full, whatever the job shows.
        assert_eq!(
            cpu_hold(peak, machine, 1_000, 10, false, 1_600, hold, false),
            peak
        );
        // After the 0.4.2 ramp end and on an idle-looking machine, a peak that has not shown is still held.
        assert_eq!(
            cpu_hold(peak, machine, 20_000, 10, false, 200, hold, false),
            peak
        );
        // Shown (3/4 of it in live use): live use counts instead.
        assert_eq!(
            cpu_hold(peak, machine, 20_000, 90, false, 1_200, hold, false),
            0
        );
        // Its time to peak passed without it showing (an incremental build): released, so the machine is not kept idle.
        assert_eq!(
            cpu_hold(peak, machine, 40_000, 10, false, 200, hold, false),
            0
        );
        // Docker work holds for its whole hold time (0.4.6), whatever its tree shows or a plateau says.
        assert_eq!(
            cpu_hold(peak, machine, 9_000, 10, true, 0, hold, false),
            peak
        );
        assert_eq!(
            cpu_hold(peak, machine, 39_999, 10, true, 1_600, hold, true),
            peak
        );
        assert_eq!(cpu_hold(peak, machine, 40_000, 10, true, 0, hold, false), 0);
        // Docker work from old job files keeps the 10 s ramp schedule.
        assert_eq!(
            cpu_hold(peak, machine, RAMP_MS, 10, true, 0, None, false),
            0
        );
        assert_eq!(
            cpu_hold(peak, machine, RAMP_MS, 10, false, 0, None, false),
            0
        );
        // The hold length: history's slowest ramp plus 25%, clamped to 10 s .. 2 min, 30 s when unknown.
        assert_eq!(cpu_hold_ms(None), CPU_FALLBACK_HOLD_MS);
        assert_eq!(cpu_hold_ms(Some(500)), RAMP_MS);
        assert_eq!(cpu_hold_ms(Some(3_600_000)), CPU_MAX_HOLD_MS);
    }

    #[test]
    fn a_small_waiter_starts_under_a_held_16_core_peak_when_the_band_has_room() {
        let c = mac();
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(40_000),
            ..job("r", 16, 2, State::Running, 0)
        };
        // The 16-core build ramps on 2 cores; the machine reads 13%.
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 200,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: 13,
            cpu_sustained_pct: 13,
            ..calm()
        };
        let one = job("one", 1, 1, State::Queued, 1);
        assert_eq!(
            evaluate(&one, &[run.clone(), one.clone()], &c, &live, 20_000),
            Decision::Start,
            "a 1-core waiter fits in the band minus the held reservation"
        );
        // A big waiter still waits for the hold: it sees the whole 16-core reservation.
        let big = job("big", 16, 1, State::Queued, 1);
        assert!(waits(&evaluate(
            &big,
            &[run.clone(), big.clone()],
            &c,
            &live,
            20_000
        )));
        // Real use counts in full: with the machine measured at 90% the small waiter waits too.
        let busy = Live {
            cpu_pct: 90,
            cpu_sustained_pct: 90,
            ..live
        };
        assert!(waits(&evaluate(
            &one,
            &[run, one.clone()],
            &c,
            &busy,
            20_000
        )));
    }

    fn six_small_waiters(live: &Live, run: &Job, now: i64) -> usize {
        let c = mac();
        let mut running = vec![run.clone()];
        for i in 0..6 {
            let id = format!("s{i}");
            let w = job(&id, 2, 1, State::Queued, 1);
            let mut jobs = running.clone();
            jobs.push(w.clone());
            if evaluate(&w, &jobs, &c, live, now) == Decision::Start {
                running.push(Job {
                    state: State::Running,
                    started_ms: Some(now),
                    cpu_hold_ms: Some(40_000),
                    ..w
                });
            }
        }
        running.len() - 1
    }

    fn held_big() -> (Job, Live) {
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(40_000),
            ..job("r", 16, 2, State::Running, 0)
        };
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 200,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: 13,
            cpu_sustained_pct: 13,
            ..calm()
        };
        (run, live)
    }

    #[test]
    fn small_waiters_share_one_backfill_budget_under_a_held_peak() {
        let (run, live) = held_big();
        // Band 14.4 cores, big hold capped to leave 2 free: only one 2-core waiter fits, not all six.
        assert_eq!(six_small_waiters(&live, &run, 20_000), 1);
    }

    #[test]
    fn the_rest_start_once_the_big_peak_shows_or_its_hold_expires() {
        let (run, live) = held_big();
        // Peak shows (1200+ cores-centi in live use at 75% of 16): live use counts, holds are gone; 6 x 2 cores fit
        // only as far as the measured 75% leaves room.
        let shown = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 1_200,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: 75,
            cpu_sustained_pct: 75,
            ..live.clone()
        };
        assert_eq!(six_small_waiters(&shown, &run, 20_000), 1);
        // Hold expired with the machine reading low (an incremental build): all six are admitted.
        assert_eq!(six_small_waiters(&live, &run, 41_000), 6);
    }

    #[test]
    fn a_ramp_blocker_on_a_learned_hold_names_the_hold_end() {
        let c = mac();
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(40_000),
            ..job("r", 16, 2, State::Running, 0)
        };
        let me = job("w", 8, 2, State::Queued, 1);
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 200,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: 13,
            cpu_sustained_pct: 13,
            ..calm()
        };
        let d = evaluate(&me, &[run.clone(), me.clone()], &c, &live, 20_000);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ramp_end_ms: Some(40_000),
                    ..
                }
            ),
            "{d:?}"
        );
        assert_eq!(
            evaluate(&me, &[run, me.clone()], &c, &live, 40_000),
            Decision::Start
        );
    }

    #[test]
    fn sustained_overload_is_blocked_by_the_two_times_cores_rule() {
        let c = mac();
        let over = Live {
            load1: 49.0,
            load5: 60.0,
            cpu_pct: 96,
            cpu_sustained_pct: 97,
            ..calm()
        };
        let (why, block) = guard_block(&c, &over).unwrap();
        assert_eq!(block, Block::Load1);
        assert!(
            why.contains("2 x 16 cores") && why.contains("cpu 97% busy"),
            "{why}"
        );
        // Alone on the machine it still waits: overload protection has no exception.
        let me = job("a", 1, 1, State::Queued, 0);
        assert!(waits(&evaluate(
            &me,
            std::slice::from_ref(&me),
            &c,
            &over,
            0
        )));
        // The same load with a calm CPU is I/O wait, not overload.
        let io = Live {
            cpu_pct: 30,
            cpu_sustained_pct: 30,
            ..over
        };
        assert_eq!(guard_block(&c, &io), None);
    }

    #[test]
    fn a_run_plateaus_once_its_cpu_is_flat_past_its_slowest_time_to_peak() {
        let run = |f: &dyn Fn(u64) -> u64, until: u64| -> Vec<(u64, u64)> {
            (0..=until / 500).map(|k| (k * 500, f(k * 500))).collect()
        };
        // Flat at 1.5 cores (an incremental `make check` with a learned 15-core spike): settled 10 s after the
        // 10 s ramp floor, not before.
        let flat = |_| 150;
        assert!(!cpu_plateaued(&run(&flat, 19_500), 9_000));
        assert!(cpu_plateaued(&run(&flat, 20_000), 9_000));
        // Still rising: never settled.
        let rising = |ms| 100 + ms / 50;
        assert!(!cpu_plateaued(&run(&rising, 60_000), 9_000));
        // Step ramp: flat on 2 cores until its 30 s slowest ramp, then 16. Not settled while it waits, nor in the
        // window that contains the step.
        let cargo = |ms| if ms < 30_000 { 200 } else { 1_600 };
        assert!(!cpu_plateaued(&run(&cargo, 29_500), 30_000));
        assert!(!cpu_plateaued(&run(&cargo, 35_000), 30_000));
        assert!(!cpu_plateaued(&run(&cargo, 39_500), 30_000));
        // A step later than a short slowest time (20 s here, ramp at 25 s): the window with the step is not flat.
        let late = |ms| if ms < 25_000 { 200 } else { 1_600 };
        assert!(!cpu_plateaued(&run(&late, 25_500), 15_000));
        // Spike, then a lull, then the real ramp at 40 s (slowest 40 s): the lull never releases, and the ramp
        // takes it back.
        let lull = |ms| {
            if (1_000..40_000).contains(&ms) {
                150
            } else {
                1_500
            }
        };
        assert!(!cpu_plateaued(&run(&lull, 30_000), 40_000));
        assert!(!cpu_plateaued(&run(&lull, 45_000), 40_000));
        // Settled in a lull after the slowest time, then the CPU rises: no longer plateaued (re-reserved).
        let again = |ms| if ms < 30_000 { 150 } else { 1_500 };
        assert!(cpu_plateaued(&run(&again, 29_500), 5_000));
        assert!(!cpu_plateaued(&run(&again, 33_000), 5_000));
        // Jitter within a core (or 1/8 of the level) is flat; an empty run is not.
        let jitter = |ms| if (ms / 500) % 2 == 0 { 800 } else { 880 };
        assert!(cpu_plateaued(&run(&jitter, 20_000), 0));
        assert!(!cpu_plateaued(&[], 0));
    }

    #[test]
    fn a_cold_head_that_waited_starts_beside_one_long_job_under_the_band() {
        // One long 10-core job (62% of 16 cores) and a cold whole-machine head: it must not wait for 60% busy for as long
        // as the job runs. Past the backfill window it starts like in 0.4.3 (the band), with the guards still on.
        let c = mac();
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(cpu_hold_ms(Some(4_000))),
            ..job("long", 10, 2, State::Running, 0)
        };
        let head = job("cold", 16, 2, State::Queued, 1_000);
        let behind = Job {
            run_p90_ms: Some(60_000),
            ..job("small", 4, 2, State::Queued, 2_000)
        };
        let live = Live {
            per_job: vec![(
                "long".into(),
                Usage {
                    cpu: 1_000,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: 62,
            cpu_sustained_pct: 62,
            ..calm()
        };
        let all = [run, head.clone(), behind.clone()];
        let t0 = 1_000 + 10_000;
        assert!(waits(&evaluate(&head, &all, &c, &live, t0)));
        let t = 1_000 + BACKFILL_WINDOW_MS;
        assert_eq!(evaluate(&head, &all, &c, &live, t), Decision::Start);
        // The 4x load guard still blocks it.
        let hot = Live {
            load1: 70.0,
            load5: 70.0,
            ..live.clone()
        };
        assert!(waits(&evaluate(&head, &all, &c, &hot, t)));
        // Before then the smaller waiter backfills, so the machine is not idle while the head waits.
        assert_eq!(evaluate(&behind, &all, &c, &live, t0), Decision::Start);
    }

    /// A running 15-core-peak job (a 2-minute learned hold) on 1.5 cores, the Mac at 15%, and an 8-core waiter.
    fn low_cpu_hold(settled: bool) -> Decision {
        let c = mac();
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(CPU_MAX_HOLD_MS),
            cpu_settled: settled,
            ..job("r", 15, 2, State::Running, 0)
        };
        let me = job("w", 8, 2, State::Queued, 1);
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: 150,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 100,
                ..Usage::default()
            },
            cpu_pct: 15,
            cpu_sustained_pct: 15,
            ..calm()
        };
        evaluate(&me, &[run, me.clone()], &c, &live, 30_000)
    }

    #[test]
    fn a_plateaued_hold_is_released_while_the_machine_reads_low() {
        // 2026-11-21: ramp holds kept waiters out at 10-50% CPU on the Mac (and 2-9% on the rig) for up to 2 minutes.
        assert!(
            matches!(
                low_cpu_hold(false),
                Decision::Wait {
                    block: Block::Ramp,
                    ..
                }
            ),
            "an unsettled hold still holds"
        );
        assert_eq!(
            low_cpu_hold(true),
            Decision::Start,
            "settled: the job's real use counts"
        );
        // Docker/VM work keeps its full 10 s ramp hold whatever the file says (its CPU never shows in the tree).
        assert_eq!(
            cpu_hold(
                1_500,
                1_600,
                5_000,
                15,
                true,
                0,
                Some(CPU_MAX_HOLD_MS),
                true
            ),
            1_500
        );
        // The stagger floor holds even a settled job.
        assert_eq!(
            cpu_hold(
                1_500,
                1_600,
                1_000,
                15,
                false,
                0,
                Some(CPU_MAX_HOLD_MS),
                true
            ),
            1_500
        );
    }

    /// The Mac with one running job past its hold on `busy` centi-cores, and a waiter with a learned `cpu` peak.
    fn onto_busy_mac(busy: u64, cpu: u32) -> Decision {
        let c = mac();
        let run = Job {
            state: State::Running,
            started_ms: Some(0),
            cpu_hold_ms: Some(RAMP_MS),
            ..job("r", 13, 2, State::Running, 0)
        };
        let me = job("w", cpu, 2, State::Queued, 1);
        let pct = busy * 100 / 1_600;
        let live = Live {
            per_job: vec![(
                "r".into(),
                Usage {
                    cpu: busy,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            cpu_pct: pct,
            cpu_sustained_pct: pct,
            ..calm()
        };
        evaluate(&me, &[run, me.clone()], &c, &live, 60_000)
    }

    #[test]
    fn a_big_waiter_starts_only_where_two_fifths_of_its_peak_fit_on_the_projected_cpu() {
        // 2026-11-21: 13-core builds admitted at up to 83% busy took the Mac to 100% with load1 34. Half the peak (0.4.4)
        // kept them out above 59%; 2/5 of it admits them up to 67%.
        assert!(
            matches!(
                onto_busy_mac(1_100, 13),
                Decision::Wait {
                    block: Block::Cpu,
                    ..
                }
            ),
            "68% busy + 5.2 cores > 16"
        );
        assert_eq!(onto_busy_mac(1_080, 13), Decision::Start, "67% + 5.2 fits");
        assert_eq!(
            onto_busy_mac(900, 13),
            Decision::Start,
            "56% fits (blocked in 0.4.4 above 59%)"
        );
        // Small and mid-size waiters fill the band under 95%; a mid-size one up to one free core.
        assert_eq!(
            onto_busy_mac(1_300, 2),
            Decision::Start,
            "a small waiter asks its own peak"
        );
        assert_eq!(onto_busy_mac(1_400, 4), Decision::Start);
        assert!(waits(&onto_busy_mac(1_440, 4)));
        // A whole-machine (cold) waiter starts up to 60% busy (50% in 0.4.4).
        assert!(waits(&onto_busy_mac(1_000, 16)));
        assert_eq!(onto_busy_mac(960, 16), Decision::Start);
    }

    /// Eight 13-core-peak jobs queued at once on the 16-core Mac. Each runs 150 s: 3 s on 1 core, then cycles of 15 s
    /// at its 13-core peak and 25 s on 2 cores (compile, then test). Demand over 16 cores is scaled down. Returns the
    /// share (%) of the samples where demand exceeded the machine, the share where jobs waited at under 75% CPU, and
    /// when the last job started.
    fn bursty_eight() -> (u64, u64, i64) {
        let c = mac();
        let mut jobs: Vec<Job> = (0..8)
            .map(|i| Job {
                cpu_hold_ms: Some(cpu_hold_ms(Some(4_000))),
                ..job(&format!("b{i}"), 13, 2, State::Queued, i)
            })
            .collect();
        let demand_at = |since: i64| -> u64 {
            if since < 3_000 {
                100
            } else if (since - 3_000) % 40_000 < 15_000 {
                1_300
            } else {
                200
            }
        };
        let (mut samples, mut over, mut under, mut last) = (0u64, 0u64, 0u64, 0);
        let mut readings: Vec<(i64, u64)> = Vec::new();
        let mut t = 0;
        while t <= 1_200_000 && !jobs.is_empty() {
            jobs.retain(|j| j.started_ms.is_none_or(|s| t - s < 150_000));
            let demand: Vec<(String, u64)> = jobs
                .iter()
                .filter_map(|j| j.started_ms.map(|s| (j.id.clone(), demand_at(t - s))))
                .collect();
            let total: u64 = demand.iter().map(|d| d.1).sum();
            let pct = total.min(1_600) * 100 / 1_600;
            readings.push((t, pct));
            readings.retain(|(ts, _)| t - ts <= BUSY_WINDOW_MS);
            let live = Live {
                cpu_pct: pct,
                cpu_sustained_pct: sustained_pct(pct, &readings, t),
                per_job: demand
                    .iter()
                    .map(|(id, d)| {
                        let cpu = if total > 1_600 { d * 1_600 / total } else { *d };
                        (
                            id.clone(),
                            Usage {
                                cpu,
                                mem: 2 * G,
                                vram: 0,
                            },
                        )
                    })
                    .collect(),
                ..calm()
            };
            let waiting = jobs.iter().any(|j| j.state == State::Queued);
            samples += 1;
            over += u64::from(total > 1_600);
            under += u64::from(waiting && pct < 75);
            for i in 0..jobs.len() {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &live, t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                    last = t;
                }
            }
            t += 500;
        }
        assert!(jobs.is_empty(), "every job ran");
        (over * 100 / samples, under * 100 / samples, last)
    }

    #[test]
    fn bursty_big_jobs_start_one_at_a_time_without_pinning_the_machine() {
        let (over, under, last) = bursty_eight();
        // 0.4.3 (one free core under the band) read over the machine 67% of the time; 0.4.4 reads 0% over, 22% under.
        assert!(over <= 10, "demand over the machine {over}% of the time");
        assert!(
            under <= 30,
            "jobs waited at under 75% CPU {under}% of the time"
        );
        assert!(last <= 600_000, "the last job started at {last} ms");
    }

    /// 2026-11-21, 10:17-11:18 local, from the job files and history: four jobs queued, nothing running, the Mac 27-41%
    /// busy, 49-58% memory used, load1 8-12 on 16 cores, macOS pressure level 2 (warn) throughout with 1.8 of 3 GB swap.
    /// 0.4.4 counted level 2 as pressure and vetoed even the 1-core head: 40+ minutes idle.
    fn stuck_queue() -> (Vec<Job>, Live) {
        let mi = 1 << 20;
        let jobs = vec![
            Job {
                weights: Weights {
                    cpu: 1,
                    mem: 148 * mi,
                    vram: 0,
                    disk: 0,
                },
                mem_peak_at_ms: Some(2_190),
                cpu_hold_ms: Some(RAMP_MS),
                ..job("lint", 1, 0, State::Queued, 1_000)
            },
            Job {
                mem_peak_at_ms: Some(106_250),
                cpu_hold_ms: Some(CPU_MAX_HOLD_MS),
                ..job("ui-update-ios", 11, 7, State::Queued, 331_000)
            },
            job("xcodebuild", 8, 8, State::Queued, 1_111_000),
            Job {
                weights: Weights {
                    cpu: 1,
                    mem: 310 * mi,
                    vram: 0,
                    disk: 0,
                },
                ..job("typecheck", 1, 0, State::Queued, 3_534_000)
            },
        ];
        let live = Live {
            load1: 8.0,
            load5: 8.0,
            mem_used_pct: 49,
            cpu_pct: 27,
            cpu_sustained_pct: 27,
            mem_pressure_warn: true,
            non_heavy: Usage {
                cpu: 430,
                mem: 31 * G,
                vram: 0,
            },
            ..calm()
        };
        (jobs, live)
    }

    #[test]
    fn replay_the_stuck_queue_of_2026_11_21() {
        let c = mac();
        let (mut jobs, live) = stuck_queue();
        let now = 3_600_000;
        // The head starts at once: warn pressure at 49% used is not exhaustion.
        assert_eq!(evaluate(&jobs[0], &jobs, &c, &live, now), Decision::Start);
        // Critical pressure (level 4) still vetoes it, alone or not.
        let critical = Live {
            mem_pressure: true,
            ..live.clone()
        };
        assert!(matches!(
            evaluate(&jobs[0], &jobs, &c, &critical, now),
            Decision::Wait {
                block: Block::Mem,
                ..
            }
        ));
        // Admit in queue order as each re-evaluates: the queue drains instead of stalling, the big ones staggered by
        // their holds, and the machine is never left idle with jobs waiting.
        let mut t = now;
        while jobs.iter().any(|j| j.state == State::Queued) && t < now + 600_000 {
            let order: Vec<usize> = (0..jobs.len()).collect();
            for i in order {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &live, t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                }
            }
            t += 500;
        }
        let started: Vec<i64> = jobs.iter().map(|j| j.started_ms.unwrap_or(-1)).collect();
        assert!(
            started.iter().all(|s| *s >= 0),
            "every job started: {started:?}"
        );
        assert_eq!(started[0], now, "the head at once");
        assert_eq!(started[3], now, "the tiny typecheck beside it");
        assert!(
            started[2] <= now + CPU_MAX_HOLD_MS,
            "the xcodebuild once the 11-core hold ends: {started:?}"
        );
    }

    #[test]
    fn warn_pressure_blocks_only_with_memory_nearly_used_up() {
        let me = job("a", 1, 1, State::Queued, 1);
        let run = Job {
            started_ms: Some(0),
            ..job("r", 1, 1, State::Running, 0)
        };
        let both = [run, me.clone()];
        let warn = |mem_used_pct| Live {
            mem_pressure_warn: true,
            mem_used_pct,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, &both, &cap(), &warn(84), 100_000),
            Decision::Start
        );
        assert!(matches!(
            evaluate(&me, &both, &cap(), &warn(85), 100_000),
            Decision::Wait {
                block: Block::Mem,
                ..
            }
        ));
        // Without warn, memory used blocks from 95% (90% in 0.4.4).
        let used = |mem_used_pct| Live {
            mem_used_pct,
            ..calm()
        };
        assert_eq!(
            evaluate(&me, &both, &cap(), &used(94), 100_000),
            Decision::Start
        );
        assert!(waits(&evaluate(&me, &both, &cap(), &used(95), 100_000)));
    }

    #[test]
    fn a_lone_job_is_held_by_the_memory_and_runaway_guards_but_not_by_warn_alone() {
        let me = job("a", 16, 8, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        let c = mac();
        // 2026-11-21: warn pressure at 49% used with nothing running starts the job.
        let warn = Live {
            mem_used_pct: 49,
            mem_pressure_warn: true,
            cpu_pct: 27,
            ..calm()
        };
        assert_eq!(evaluate(&me, one, &c, &warn, 0), Decision::Start);
        // 95% used blocks a lone job, with or without warn.
        for warn_on in [false, true] {
            let full = Live {
                mem_used_pct: 97,
                mem_pressure_warn: warn_on,
                ..calm()
            };
            assert!(matches!(
                evaluate(&me, one, &c, &full, 0),
                Decision::Wait {
                    block: Block::Mem,
                    ..
                }
            ));
        }
        let critical = Live {
            mem_pressure: true,
            ..warn.clone()
        };
        assert!(waits(&evaluate(&me, one, &c, &critical, 0)));
        let runaway = Live {
            load1: 64.0,
            load5: 30.0,
            cpu_pct: 55,
            ..warn
        };
        assert!(matches!(
            evaluate(&me, one, &c, &runaway, 0),
            Decision::Wait {
                block: Block::Load1,
                ..
            }
        ));
    }

    #[test]
    fn tiny_jobs_stop_passing_a_memory_blocked_head_after_the_bypass_window() {
        let c = mac();
        let run = Job {
            started_ms: Some(0),
            mem_declared: true,
            ..job("r", 2, 40, State::Running, 0)
        };
        let head = job("head", 4, 30, State::Queued, 1_000);
        let tiny_one = job("tiny", 1, 1, State::Queued, 2_000);
        let all = [run, head.clone(), tiny_one.clone()];
        let live = Live {
            non_heavy: Usage {
                cpu: 200,
                mem: 15 * G,
                vram: 0,
            },
            ..calm()
        };
        let before = 1_000 + TINY_BYPASS_MS - 1;
        assert_eq!(
            evaluate(&tiny_one, &all, &c, &live, before),
            Decision::Start
        );
        let after = 1_000 + TINY_BYPASS_MS;
        assert!(matches!(
            evaluate(&tiny_one, &all, &c, &live, after),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
    }

    #[test]
    fn a_tiny_job_passes_a_vram_blocked_head_until_the_bypass_window_ends() {
        let c = Capacity {
            vram: 100 * G,
            ..cap()
        };
        let vr = |id: &str, g: u64, state| {
            let j = job(id, 1, 1, state, 0);
            Job {
                weights: Weights {
                    vram: g * G,
                    ..j.weights
                },
                started_ms: Some(0),
                ..j
            }
        };
        let run = vr("r", 50, State::Running);
        let head = Job {
            enqueued_ms: 1_000,
            ..vr("head", 41, State::Queued)
        };
        let tiny_one = Job {
            enqueued_ms: 2_000,
            ..vr("tiny", 0, State::Queued)
        };
        let all = [run, head.clone(), tiny_one.clone()];
        let t = 1_000 + BACKFILL_WINDOW_MS + 1;
        assert!(matches!(
            evaluate(&head, &all, &c, &calm(), t),
            Decision::Wait {
                block: Block::Vram,
                ..
            }
        ));
        assert_eq!(evaluate(&tiny_one, &all, &c, &calm(), t), Decision::Start);
        assert!(waits(&evaluate(
            &tiny_one,
            &all,
            &c,
            &calm(),
            1_000 + TINY_BYPASS_MS
        )));
    }

    #[test]
    fn a_tiny_job_passes_a_ramp_blocked_head_only_if_the_head_is_not_delayed() {
        let c = mac();
        let ra = Job {
            started_ms: Some(10),
            ..job("a", 16, 8, State::Running, 0)
        };
        let head = job("b", 16, 8, State::Queued, 2);
        let tiny_one = job("t", 1, 1, State::Queued, 3);
        let all = [ra, head.clone(), tiny_one.clone()];
        let live = Live {
            non_heavy: Usage {
                cpu: 320,
                mem: 8 * G,
                vram: 0,
            },
            ..calm()
        };
        let d = evaluate(&head, &all, &c, &live, 500);
        assert!(
            matches!(
                d,
                Decision::Wait {
                    block: Block::Ramp,
                    ..
                }
            ),
            "{d:?}"
        );
        // The tiny job takes next to nothing of the held CPU: it starts, and the head's ramp end does not move.
        assert_eq!(evaluate(&tiny_one, &all, &c, &live, 500), Decision::Start);
    }

    #[test]
    fn a_tiny_job_passes_an_old_head_blocked_by_memory_but_not_by_cpu() {
        let c = mac();
        let run = Job {
            started_ms: Some(0),
            mem_declared: true,
            ..job("r", 2, 40, State::Running, 0)
        };
        // The head needs 30G; the running job's declared 40G plus 15G of other programs leave 5.8G.
        let head = job("head", 4, 30, State::Queued, 1_000);
        let tiny_one = job("tiny", 1, 1, State::Queued, 2_000);
        let mid = job("mid", 4, 1, State::Queued, 3_000);
        let all = [run, head.clone(), tiny_one.clone(), mid.clone()];
        let live = Live {
            non_heavy: Usage {
                cpu: 200,
                mem: 15 * G,
                vram: 0,
            },
            ..calm()
        };
        let t = 1_000 + BACKFILL_WINDOW_MS + 1;
        assert!(matches!(
            evaluate(&head, &all, &c, &live, t),
            Decision::Wait {
                block: Block::Mem,
                ..
            }
        ));
        assert_eq!(evaluate(&tiny_one, &all, &c, &live, t), Decision::Start);
        assert!(
            matches!(
                evaluate(&mid, &all, &c, &live, t),
                Decision::Wait {
                    block: Block::Queue,
                    ..
                }
            ),
            "4 cores is not tiny: it keeps the 60 s rule"
        );
        // A head blocked on CPU room keeps every follower behind it after 60 s, tiny ones too.
        let busy = Live {
            cpu_pct: 90,
            cpu_sustained_pct: 90,
            non_heavy: Usage {
                cpu: 1_440,
                mem: 0,
                vram: 0,
            },
            ..calm()
        };
        assert!(matches!(
            evaluate(&tiny_one, &all, &c, &busy, t),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
    }

    #[test]
    fn a_blocked_waiter_says_why_with_the_numbers() {
        let d = onto_busy_mac(1_100, 13);
        let Decision::Wait { reason, .. } = d else {
            panic!("{d:?}")
        };
        assert_eq!(
            reason,
            "cpu: needs 4.40 cores, 4.20 free under the 95% band (machine 68% busy)"
        );
    }

    /// 2026-11-21, 19:47-20:31 UTC: a cold `docker build` (the whole machine, 30 s fallback hold) on a calm Mac. Its
    /// work runs in Docker's VM, so its tree reads 0.1 cores and the VM's CPU shows late, as other programs' CPU.
    fn docker_build_at(other_cpu: u64, pct: u64) -> (Vec<Job>, Live) {
        let build = |id: &str, state, enq| Job {
            cmd: vec!["docker".into(), "build".into(), ".".into()],
            cpu_hold_ms: Some(cpu_hold_ms(None)),
            ..job(id, 16, 4, state, enq)
        };
        let run = Job {
            started_ms: Some(0),
            ..build("b1", State::Running, 0)
        };
        let live = Live {
            cpu_pct: pct,
            cpu_sustained_pct: pct,
            non_heavy: Usage {
                cpu: other_cpu,
                mem: 20 * G,
                vram: 0,
            },
            per_job: vec![(
                "b1".into(),
                Usage {
                    cpu: 10,
                    mem: G / 10,
                    vram: 0,
                },
            )],
            ..calm()
        };
        (vec![run, build("b2", State::Queued, 1_000)], live)
    }

    #[test]
    fn a_docker_build_holds_the_machine_until_its_vm_cpu_shows() {
        let c = mac();
        // 15 s in, the VM has not ramped yet (3 cores of other programs, 20% busy). 0.4.5 released the hold at 10 s and
        // started the second build here; both then ran and the Mac read 100% with load1 130-330.
        let (jobs, live) = docker_build_at(300, 20);
        assert!(matches!(
            evaluate(&jobs[1], &jobs, &c, &live, 15_000),
            Decision::Wait {
                block: Block::Ramp,
                ..
            }
        ));
        let small = job("lint", 4, 2, State::Queued, 2_000);
        let with_small = [jobs[0].clone(), small.clone()];
        assert!(waits(&evaluate(&small, &with_small, &c, &live, 15_000)));
        // Its hold ends with its time (30 s, cold): a lull then admits the next one.
        assert_eq!(
            evaluate(&jobs[1], &jobs, &c, &live, CPU_FALLBACK_HOLD_MS),
            Decision::Start
        );
        // While held, the VM CPU that already shows (as other programs) is not counted twice: an 8-core learned build
        // 20 s in with 6 of its cores showing holds 8 cores in all, not 6 + 8.
        let d8 = Job {
            started_ms: Some(0),
            cmd: vec!["docker".into(), "build".into(), ".".into()],
            cpu_hold_ms: Some(cpu_hold_ms(None)),
            ..job("d8", 8, 4, State::Running, 0)
        };
        let showing = Live {
            non_heavy: Usage {
                cpu: 600,
                mem: 20 * G,
                vram: 0,
            },
            per_job: vec![],
            ..calm()
        };
        assert_eq!(headroom(&[&d8], &c, &showing, 20_000).cpu, 1_520 - 800);
        // In its first 10 s the hold still counts on top of everything else, as before.
        assert_eq!(headroom(&[&d8], &c, &showing, 5_000).cpu, 1_520 - 1_400);
    }

    /// A docker build WITH history: its VM CPU peaked 20 s in (learned from the other-programs sampler), so it holds
    /// 8 cores for 25 s, not the 10 s a docker CLI tree peak would give.
    #[test]
    fn a_docker_build_with_history_holds_until_its_learned_vm_cpu_time() {
        let c = mac();
        let d8 = Job {
            started_ms: Some(0),
            cmd: vec!["docker".into(), "build".into(), ".".into()],
            cpu_hold_ms: Some(cpu_hold_ms(Some(20_000))),
            ..job("d8", 8, 4, State::Running, 0)
        };
        assert_eq!(d8.cpu_hold_ms, Some(25_000));
        let live = Live {
            per_job: vec![],
            ..calm()
        };
        assert_eq!(headroom(&[&d8], &c, &live, 15_000).cpu, 1_520 - 800);
        assert_eq!(headroom(&[&d8], &c, &live, 24_000).cpu, 1_520 - 800);
        assert_eq!(headroom(&[&d8], &c, &live, 26_000).cpu, 1_520);
    }

    /// 4 cores of unrelated other-program CPU were already there when the 8-core docker build started: the hold at 11 s
    /// counts 12 cores (4 + 8), not 8. Only the rise above that baseline is the build's.
    #[test]
    fn a_docker_hold_is_netted_only_against_the_rise_above_its_start_baseline() {
        let c = mac();
        let d8 = Job {
            started_ms: Some(0),
            cmd: vec!["docker".into(), "build".into(), ".".into()],
            cpu_hold_ms: Some(cpu_hold_ms(Some(20_000))),
            non_heavy_cpu_at_start: 400,
            ..job("d8", 8, 4, State::Running, 0)
        };
        let live = |other| Live {
            non_heavy: Usage {
                cpu: other,
                mem: 20 * G,
                vram: 0,
            },
            per_job: vec![],
            ..calm()
        };
        assert_eq!(headroom(&[&d8], &c, &live(400), 11_000).cpu, 1_520 - 1_200);
        // The VM's own 3 cores showing (400 + 300) are netted once: 7 cores in all.
        assert_eq!(headroom(&[&d8], &c, &live(700), 11_000).cpu, 1_520 - 1_200);
    }

    /// 2026-11-21, 20:19-20:48 UTC: one long 10-core job, the Mac at 70%, a 13-core head that needs 4.4 free cores, and
    /// a 2-core waiter behind it.
    fn big_head_at(pct: u64) -> (Vec<Job>, Live) {
        let run = Job {
            started_ms: Some(0),
            cpu_hold_ms: Some(cpu_hold_ms(Some(4_000))),
            ..job("long", 10, 6, State::Running, 0)
        };
        let head = Job {
            cpu_hold_ms: Some(CPU_MAX_HOLD_MS),
            ..job("ui-update", 13, 4, State::Queued, 100_000)
        };
        let small = Job {
            cpu_hold_ms: Some(RAMP_MS),
            run_p90_ms: Some(30_000),
            ..job("typecheck", 2, 4, State::Queued, 101_000)
        };
        let live = Live {
            cpu_pct: pct,
            cpu_sustained_pct: pct,
            non_heavy: Usage {
                cpu: 100,
                mem: 20 * G,
                vram: 0,
            },
            per_job: vec![(
                "long".into(),
                Usage {
                    cpu: 900,
                    mem: 6 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        (vec![run, head, small], live)
    }

    #[test]
    fn a_small_job_passes_a_cpu_blocked_head_on_an_underused_machine() {
        let c = mac();
        let (jobs, live) = big_head_at(70);
        let past = 100_000 + BACKFILL_WINDOW_MS + 1;
        assert!(matches!(
            evaluate(&jobs[1], &jobs, &c, &live, past),
            Decision::Wait {
                block: Block::Cpu,
                ..
            }
        ));
        // 0.4.5 queued it behind the head (strict FIFO past 60 s) for as long as the head waited.
        assert_eq!(evaluate(&jobs[2], &jobs, &c, &live, past), Decision::Start);
        // At 75% busy the machine is in the band's approach: it waits for the head again.
        let (jobs, warm) = big_head_at(UNDERUSED_CPU_PCT);
        assert!(matches!(
            evaluate(&jobs[2], &jobs, &c, &warm, past),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        // And once the head has waited 5 minutes, so a stream of small jobs cannot starve it.
        assert!(matches!(
            evaluate(&jobs[2], &jobs, &c, &live, 100_000 + TINY_BYPASS_MS),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        // 0.4.8: a mid-size waiter no bigger than the head backfills too (0.4.7 kept it behind the 60 s rule), when its
        // learned run time ends within the head's backfill time; with none learned it waits.
        let mid = job("check", 4, 4, State::Queued, 102_000);
        let all = [jobs[0].clone(), jobs[1].clone(), mid.clone()];
        assert!(matches!(
            evaluate(&mid, &all, &c, &live, past),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        let mid = Job {
            run_p90_ms: Some(60_000),
            ..mid
        };
        let all = [jobs[0].clone(), jobs[1].clone(), mid.clone()];
        assert_eq!(evaluate(&mid, &all, &c, &live, past), Decision::Start);
    }

    /// The rig on 2026-11-21: 16 cores, 10G of VRAM, a 14-core test run and the desktop keeping it 97% busy.
    fn busy_rig() -> (Capacity, Vec<Job>, Live) {
        let c = Capacity {
            cpu: 16,
            mem: 64 * G,
            vram: 10 * G,
            disk_total: 1000 * G,
            vram_is_ram: false,
        };
        let big = Job {
            started_ms: Some(0),
            cpu_hold_ms: Some(RAMP_MS),
            ..job("tests", 14, 12, State::Running, 0)
        };
        let live = Live {
            load1: 20.0,
            load5: 20.0,
            cpu_pct: 97,
            cpu_sustained_pct: 97,
            per_job: vec![(
                "tests".into(),
                Usage {
                    cpu: 1_400,
                    mem: 8 * G,
                    vram: 0,
                },
            )],
            non_heavy: Usage {
                cpu: 150,
                mem: 10 * G,
                vram: 2 * G,
            },
            ..calm()
        };
        (c, vec![big], live)
    }

    /// The busy rig with 2.4 free cores: the fast lane needs real room (`fast_cpu_room`).
    fn roomy(live: Live) -> Live {
        Live {
            cpu_pct: 85,
            cpu_sustained_pct: 85,
            ..live
        }
    }

    fn lint(id: &str, enq: i64, fast: bool, state: State) -> Job {
        let mut j = job(id, 1, 0, state, enq);
        j.weights.mem = 72 << 20;
        j.fast = fast;
        if state == State::Running {
            j.started_ms = Some(enq);
        }
        j
    }

    #[test]
    fn a_learned_short_small_job_starts_in_the_fast_lane_on_a_busy_machine() {
        // 2026-11-21 on the rig: `make lint` (1 core, 72M, ran 1.2 s) waited 204 s behind "cpu: needs 1.00 cores,
        // 0.00 free under the 95% band (machine 95-98% busy)" with a bigger job queued ahead of it.
        let (c, mut jobs, live) = busy_rig();
        let live = roomy(live);
        jobs.push(job("head", 8, 4, State::Queued, 50_000));
        let now = 60_000;
        let slow = lint("lint", 55_000, false, State::Queued);
        let mut all = jobs.clone();
        all.push(slow.clone());
        assert!(
            waits(&evaluate(&slow, &all, &c, &live, now)),
            "no fast lane: it waits"
        );
        let quick = lint("lint", 55_000, true, State::Queued);
        let mut all = jobs.clone();
        all.push(quick.clone());
        assert_eq!(evaluate(&quick, &all, &c, &live, now), Decision::Start);
    }

    #[test]
    fn the_fast_lane_is_bounded_and_keeps_the_guards() {
        let (c, jobs, live) = busy_rig();
        let live = roomy(live);
        let now = 60_000;
        let with = |extra: &[Job]| {
            let mut v = jobs.clone();
            v.extend_from_slice(extra);
            v
        };
        let me = lint("me", 59_000, true, State::Queued);
        // `FAST_MAX_JOBS` fast jobs already running: a third waits, even one that ran long (never forgotten).
        let running = [
            lint("f1", 1_000, true, State::Running),
            lint("f2", 58_000, true, State::Running),
        ];
        let all = with(&[running[0].clone(), running[1].clone(), me.clone()]);
        assert!(waits(&evaluate(&me, &all, &c, &live, now)));
        // One slot left: it starts.
        let all = with(&[running[1].clone(), me.clone()]);
        assert_eq!(evaluate(&me, &all, &c, &live, now), Decision::Start);
        // Guards still veto: a runaway load, critical memory pressure, memory 95% used.
        let all = with(std::slice::from_ref(&me));
        for bad in [
            Live {
                load1: 64.0,
                ..live.clone()
            },
            Live {
                mem_pressure: true,
                ..live.clone()
            },
            Live {
                mem_used_pct: 96,
                ..live.clone()
            },
        ] {
            assert!(waits(&evaluate(&me, &all, &c, &bad, now)), "{bad:?}");
        }
        // Memory still has to fit the measured headroom.
        let full = Live {
            non_heavy: Usage {
                mem: 52 * G,
                ..live.non_heavy
            },
            ..live.clone()
        };
        assert!(waits(&evaluate(&me, &all, &c, &full, now)));
    }

    #[test]
    fn a_running_fast_job_using_16_cores_closes_the_lane() {
        let (c, jobs, live) = busy_rig();
        let live = roomy(live);
        let now = 60_000;
        let me = lint("me", 59_000, true, State::Queued);
        let runner = lint("f1", 58_000, true, State::Running);
        let mut all = jobs;
        all.extend([runner, me.clone()]);
        assert_eq!(evaluate(&me, &all, &c, &live, now), Decision::Start);
        let mut hot = live.clone();
        hot.per_job.push((
            "f1".into(),
            Usage {
                cpu: 1_600,
                mem: 72 << 20,
                vram: 0,
            },
        ));
        assert!(waits(&evaluate(&me, &all, &c, &hot, now)));
    }

    #[test]
    fn a_machine_with_no_free_cores_refuses_the_fast_lane() {
        let (c, mut jobs, live) = busy_rig();
        let now = 60_000;
        let me = lint("me", 59_000, true, State::Queued);
        jobs.push(me.clone());
        for pct in [97, 100] {
            let full = Live {
                cpu_pct: pct,
                cpu_sustained_pct: pct,
                ..live.clone()
            };
            assert!(waits(&evaluate(&me, &jobs, &c, &full, now)), "{pct}%");
        }
        assert!(!fast_cpu_room(&c, &live));
        assert!(fast_cpu_room(&c, &roomy(live)));
    }

    #[test]
    fn only_short_small_jobs_without_vram_are_fast_lane_eligible() {
        let c = Capacity {
            cpu: 16,
            mem: 64 * G,
            vram: 10 * G,
            disk_total: 1000 * G,
            vram_is_ram: false,
        };
        let w = |cpu, mem, vram| Weights {
            cpu,
            mem,
            vram,
            disk: 0,
        };
        assert!(fast_lane_eligible(w(1, 72 << 20, 0), &c, Some(1_285)));
        assert!(fast_lane_eligible(
            w(FAST_MAX_CPU, 2 * G, 0),
            &c,
            Some(FAST_RUN_MS)
        ));
        assert!(!fast_lane_eligible(w(1, 0, 0), &c, None), "cold or pooled");
        assert!(
            !fast_lane_eligible(w(1, 0, 0), &c, Some(FAST_RUN_MS + 1)),
            "one recent run was long"
        );
        assert!(!fast_lane_eligible(
            w(FAST_MAX_CPU + 1, 0, 0),
            &c,
            Some(1_000)
        ));
        assert!(
            !fast_lane_eligible(w(1, 3 * G, 0), &c, Some(1_000)),
            "over 1/32 of RAM"
        );
        assert!(
            !fast_lane_eligible(w(1, 0, 1 << 30), &c, Some(1_000)),
            "uses VRAM"
        );
    }

    #[test]
    fn a_burst_of_fast_jobs_adds_at_most_the_lane_cap_to_a_pinned_machine() {
        // Twelve fast jobs arrive at once on the busy rig: each start is written as running before the next decides.
        let (c, jobs, live) = busy_rig();
        let live = roomy(live);
        let mut all = jobs.clone();
        let mut started = 0;
        for k in 0..12 {
            let me = lint(&format!("l{k:02}"), 60_000 + k, true, State::Queued);
            all.push(me.clone());
            if evaluate(&me, &all, &c, &live, 61_000) == Decision::Start {
                started += 1;
                let last = all.len() - 1;
                all[last].state = State::Running;
                all[last].started_ms = Some(61_000);
            }
        }
        assert_eq!(started, FAST_MAX_JOBS);
    }

    #[test]
    fn a_high_load_blocks_only_when_the_cpu_or_cpu_pressure_confirms_it() {
        // 2026-11-21 on the rig (16 cores): load1 35 with the CPU 8-15% busy and PSI cpu some 0.19: threads in I/O wait.
        let c = Capacity { cpu: 16, ..cap() };
        let me = job("a", 1, 1, State::Queued, 0);
        let one = std::slice::from_ref(&me);
        let rig = Live {
            load1: 35.4,
            load5: 30.0,
            cpu_pct: 15,
            cpu_pressure: Some(0),
            ..calm()
        };
        assert_eq!(evaluate(&me, one, &c, &rig, 0), Decision::Start);
        // Even at 4 x cores (64), I/O wait alone admits; PSI cpu or a half-busy CPU confirms it.
        let storm = Live {
            load1: 70.0,
            load5: 60.0,
            ..rig.clone()
        };
        assert_eq!(evaluate(&me, one, &c, &storm, 0), Decision::Start);
        for confirmed in [
            Live {
                cpu_pressure: Some(CPU_PSI_PCT),
                ..storm.clone()
            },
            Live {
                cpu_pct: LOAD_HARD_CPU_PCT,
                ..storm.clone()
            },
        ] {
            let (why, block) = guard_block(&c, &confirmed).expect("blocked");
            assert_eq!(block, Block::Load1);
            assert!(why.contains("4 x 16 cores"), "{why}");
        }
        // From 2 x cores, tasks queueing for the CPU (PSI) block at a calm CPU reading too.
        let queued = Live {
            cpu_pressure: Some(40),
            ..rig.clone()
        };
        let (why, _) = guard_block(&c, &queued).expect("blocked");
        assert!(why.contains("cpu pressure 40%"), "{why}");
        assert_eq!(
            guard_block(
                &c,
                &Live {
                    load1: 20.0,
                    ..queued
                }
            ),
            None,
            "under 2 x cores PSI alone never blocks"
        );
        // The 2026-11-19 Mac (no PSI): load 120 on 16 cores with the CPU pinned still blocks.
        let mac_meltdown = Live {
            load1: 120.0,
            load5: 90.0,
            cpu_pct: 100,
            ..calm()
        };
        assert!(guard_block(&c, &mac_meltdown).is_some());
    }

    /// A 13-core head on the Mac, enqueued at 0, with a 6-core waiter behind it and the machine `pct` busy from one
    /// long-running job.
    fn mid_behind_head(pct: u64) -> (Vec<Job>, Live) {
        let run = Job {
            started_ms: Some(0),
            cpu_hold_ms: Some(RAMP_MS),
            ..job("long", 10, 6, State::Running, 0)
        };
        let head = Job {
            cpu_hold_ms: Some(CPU_MAX_HOLD_MS),
            ..job("lint", 13, 8, State::Queued, 0)
        };
        let mid = Job {
            cpu_hold_ms: Some(RAMP_MS),
            run_p90_ms: Some(20_000),
            ..job("clippy", 6, 4, State::Queued, 1_000)
        };
        let busy = pct * 1_600 / 100;
        let live = Live {
            cpu_pct: pct,
            cpu_sustained_pct: pct,
            per_job: vec![(
                "long".into(),
                Usage {
                    cpu: busy,
                    mem: 6 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        (vec![run, head, mid], live)
    }

    #[test]
    fn a_mid_size_job_backfills_a_young_cpu_blocked_head_on_an_underused_machine() {
        // 2026-11-21 after 0.4.7: 6-core clippy and test runs waited 73-74 minutes behind 11-core make lint heads, at
        // p50 21 minutes for 3-8 core jobs, while the Mac sat idle 23% of the time jobs waited.
        let c = mac();
        let (jobs, live) = mid_behind_head(72);
        let past = BACKFILL_WINDOW_MS + 1;
        assert!(matches!(
            evaluate(&jobs[1], &jobs, &c, &live, past),
            Decision::Wait {
                block: Block::Cpu,
                ..
            }
        ));
        assert_eq!(evaluate(&jobs[2], &jobs, &c, &live, past), Decision::Start);
        // Not near the band, not once the head has waited 5 minutes, and never a waiter bigger than the head.
        let (_, warm) = mid_behind_head(UNDERUSED_CPU_PCT);
        assert!(waits(&evaluate(&jobs[2], &jobs, &c, &warm, past)));
        assert!(matches!(
            evaluate(&jobs[2], &jobs, &c, &live, TINY_BYPASS_MS),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        let bigger = Job {
            weights: Weights {
                cpu: 14,
                ..jobs[2].weights
            },
            ..jobs[2].clone()
        };
        let all = [jobs[0].clone(), jobs[1].clone(), bigger.clone()];
        assert!(matches!(
            evaluate(&bigger, &all, &c, &live, past),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
    }

    #[test]
    fn a_long_backfiller_cannot_hold_the_head_past_its_backfill_time() {
        // A 12-core, 70-minute job arriving at 4:59 of the 13-core head's wait on an underused Mac: passing would keep
        // the head's room for 70 minutes. It waits; a shorter one passes only if it ends within the bound.
        let c = mac();
        let (mut jobs, live) = mid_behind_head(72);
        let at = TINY_BYPASS_MS - 1_000;
        jobs[2] = Job {
            run_p90_ms: Some(70 * 60_000),
            ..job("long-test", 12, 4, State::Queued, at)
        };
        assert!(matches!(
            evaluate(&jobs[2], &jobs, &c, &live, at),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        // A 6-core one fits the room: it passes only if its run ends within the bound.
        jobs[2] = Job {
            cpu_hold_ms: Some(RAMP_MS),
            ..job("clippy", 6, 4, State::Queued, at)
        };
        jobs[2].run_p90_ms = Some(u64::try_from(1_000 + BACKFILL_OVERRUN_MS).unwrap_or(0));
        assert_eq!(evaluate(&jobs[2], &jobs, &c, &live, at), Decision::Start);
        jobs[2].run_p90_ms = Some(u64::try_from(2_000 + BACKFILL_OVERRUN_MS).unwrap_or(0));
        assert!(
            waits(&evaluate(&jobs[2], &jobs, &c, &live, at)),
            "past the bound"
        );
        jobs[2].run_p90_ms = None;
        assert!(
            waits(&evaluate(&jobs[2], &jobs, &c, &live, at)),
            "no learned run time"
        );
        // A tiny job needs no learned run time.
        let tiny_job = job("fmt", 1, 1, State::Queued, at);
        let all = [jobs[0].clone(), jobs[1].clone(), tiny_job.clone()];
        assert_eq!(evaluate(&tiny_job, &all, &c, &live, at), Decision::Start);
    }

    #[test]
    fn a_head_that_holds_the_queue_is_never_passed_and_projects_its_sustained_level() {
        assert_eq!(projected_peak(1_300, None), 520, "2/5 of the peak");
        assert_eq!(
            projected_peak(1_300, Some(300)),
            300,
            "a lower sustained level"
        );
        assert_eq!(
            projected_peak(1_300, Some(900)),
            520,
            "never above 2/5 of the peak"
        );
        // Once the head has waited `TINY_BYPASS_MS`, the mid job no longer backfills, even on an underused machine.
        let c = mac();
        let (jobs, live) = mid_behind_head(72);
        let held = TINY_BYPASS_MS;
        assert_eq!(
            evaluate(&jobs[2], &jobs, &c, &live, held - 1),
            Decision::Start
        );
        assert!(matches!(
            evaluate(&jobs[2], &jobs, &c, &live, held),
            Decision::Wait {
                block: Block::Queue,
                ..
            }
        ));
        // A learned sustained level of 3 cores lets the 13-core head fit at 72% busy (2/5 of its peak would not).
        assert!(waits(&evaluate(&jobs[1], &jobs, &c, &live, held)));
        let mut lower = jobs.clone();
        lower[1].cpu_sustained = Some(300);
        assert_eq!(
            evaluate(&lower[1], &lower, &c, &live, held),
            Decision::Start
        );
    }

    #[test]
    fn a_held_peak_drops_to_the_sustained_level_only_after_its_learned_peak_time() {
        let by = Some(cpu_hold_ms(Some(60_000)));
        assert_eq!(
            sustained_hold(1_100, Some(300), 0, false, by),
            1_100,
            "full peak while it ramps"
        );
        assert_eq!(
            sustained_hold(1_100, Some(300), SUSTAINED_FULL_MS, false, by),
            1_100,
            "its learned peak (60 s plus margin) is still ahead"
        );
        assert_eq!(
            sustained_hold(1_100, Some(300), 75_000, false, by),
            300,
            "past the learned peak time and margin"
        );
        assert_eq!(
            sustained_hold(1_100, Some(300), SUSTAINED_FULL_MS, false, Some(RAMP_MS)),
            300,
            "an early peak: from SUSTAINED_FULL_MS"
        );
        assert_eq!(sustained_hold(1_100, Some(1_500), 75_000, false, by), 1_100);
        assert_eq!(
            sustained_hold(0, Some(300), 75_000, false, by),
            0,
            "a released hold stays released"
        );
        assert_eq!(
            sustained_hold(1_100, Some(300), 200_000, true, by),
            1_100,
            "Docker/VM keeps its hold"
        );
        assert_eq!(
            sustained_hold(1_100, None, 200_000, false, by),
            1_100,
            "nothing learned"
        );
        assert_eq!(
            sustained_hold(1_100, Some(300), 200_000, false, None),
            1_100,
            "no learned time to peak"
        );
        // 2026-11-21: make lint test-changed learned 11 cores (a brief spike at 15 s) and averaged 1.2. Its peak stays
        // held until 15 s plus margin even with a 3-core sustained level learned; a 6-core waiter fits only after.
        let c = mac();
        let lint = Job {
            started_ms: Some(0),
            cpu_hold_ms: Some(cpu_hold_ms(Some(15_000))),
            cpu_sustained: Some(300),
            ..job("lint", 11, 4, State::Running, 0)
        };
        let me = job("clippy", 6, 4, State::Queued, 1);
        let live = Live {
            cpu_pct: 32,
            cpu_sustained_pct: 32,
            non_heavy: Usage {
                cpu: 400,
                mem: 10 * G,
                vram: 0,
            },
            per_job: vec![(
                "lint".into(),
                Usage {
                    cpu: 120,
                    mem: 2 * G,
                    vram: 0,
                },
            )],
            ..calm()
        };
        let at = |t| evaluate(&me, &[lint.clone(), me.clone()], &c, &live, t);
        assert!(waits(&at(5_000)), "the full peak during the ramp");
        assert!(
            waits(&at(12_000)),
            "the full peak before its learned peak time"
        );
        assert_eq!(at(cpu_hold_ms(Some(15_000))), Decision::Start);
    }

    /// Three 16-core-peak jobs on the 16-core Mac that each sit on 1 core for 60 s, spike to 16 cores for 2 s (a link
    /// or test fan-out) and run 1 core to 120 s. Their best 10 s mean is under 5 cores, so a sustained cap that kicked
    /// in at 10 s would let all three in within seconds of each other, and at 60 s they would spike to 48 cores at once.
    #[test]
    fn late_spiking_jobs_are_not_let_in_together_by_their_sustained_level() {
        let c = mac();
        let shape = |since: i64| -> u64 {
            if (60_000..62_000).contains(&since) {
                1_600
            } else {
                100
            }
        };
        let samples: Vec<(u64, u64)> = (0..240)
            .map(|i| (i * 500, shape(i64::try_from(i * 500).unwrap_or(0))))
            .collect();
        let level = sustained_level(&samples);
        assert!(level < 500, "the learned sustained level {level}");
        let mut jobs: Vec<Job> = (0..3)
            .map(|i| Job {
                cpu_hold_ms: Some(cpu_hold_ms(Some(60_000))),
                cpu_sustained: Some(level),
                run_p90_ms: Some(120_000),
                ..job(&format!("s{i}"), 16, 2, State::Queued, i)
            })
            .collect();
        let (mut worst, mut t) = (0u64, 0);
        while t <= 900_000 && !jobs.is_empty() {
            jobs.retain(|j| j.started_ms.is_none_or(|s| t - s < 120_000));
            let demand: Vec<(String, u64)> = jobs
                .iter()
                .filter_map(|j| j.started_ms.map(|s| (j.id.clone(), shape(t - s))))
                .collect();
            let total: u64 = demand.iter().map(|d| d.1).sum();
            worst = worst.max(total);
            let pct = total.min(1_600) * 100 / 1_600;
            let live = Live {
                cpu_pct: pct,
                cpu_sustained_pct: pct,
                per_job: demand
                    .iter()
                    .map(|(id, d)| {
                        (
                            id.clone(),
                            Usage {
                                cpu: (*d).min(1_600),
                                mem: 2 * G,
                                vram: 0,
                            },
                        )
                    })
                    .collect(),
                ..calm()
            };
            for i in 0..jobs.len() {
                if jobs[i].state == State::Queued
                    && evaluate(&jobs[i].clone(), &jobs, &c, &live, t) == Decision::Start
                {
                    jobs[i].state = State::Running;
                    jobs[i].started_ms = Some(t);
                }
            }
            t += 500;
        }
        assert!(jobs.is_empty(), "every job ran");
        assert!(
            worst <= 1_700,
            "demand peaked at {worst} centi-cores on a 16-core machine"
        );
    }

    #[test]
    fn the_sustained_level_is_the_best_ten_second_mean() {
        assert_eq!(sustained_level(&[]), 0);
        // A 500 ms spike to 10 cores in a run on 1 core: the level stays near 1 core.
        let mut spike: Vec<(u64, u64)> = (0..60).map(|i| (i * 500, 100)).collect();
        spike[30].1 = 1_000;
        assert_eq!(sustained_level(&spike), 145);
        // 15 s at 8 cores, then 1 core: the 10 s window inside the burst.
        let burst: Vec<(u64, u64)> = (0..80)
            .map(|i| (i * 500, if i < 30 { 800 } else { 100 }))
            .collect();
        assert_eq!(sustained_level(&burst), 800);
        // Shorter than the window: the mean of the run.
        assert_eq!(sustained_level(&[(0, 100), (500, 300)]), 200);
    }
}