runnerd-core 0.1.1

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

use std::fmt::Write as _;
use std::panic::AssertUnwindSafe;
use std::time::SystemTime;

use futures_util::FutureExt as _;

use super::*;
use crate::admission::host;
use crate::admission::pooled::{self, POOL_AFTER};
use crate::api::{Basis, HoldCause, JobPeak};
use crate::config::Admission;
use crate::observe::metrics::Events;
use crate::scheduler::engine::clock::Clock;
use crate::scheduler::engine::control::RunningJobs;
use crate::scheduler::engine::tick::Scope;
use crate::scheduler::{Decision, IDLE_TIMEOUT, PRIORITY_AFTER};
use crate::store::{RunnerRecord, SampleRecord};
use crate::time;

const G: u64 = 1 << 30;
const M: u64 = 1 << 20;

/// The slice's `MemoryMax`: two heavy runners, or one and a light one, not two and a light one: a runner counted
/// at less than it holds lets one start too many.
const MEMORY_MAX: u64 = 8 * G + 512 * M;

/// The slice's CPUs, in millicores: one heavy runner and one light one under `cpu_overcommit = 1.0`, where memory
/// has room for two heavy ones, so CPU binds before memory.
const SLICE_CPUS: u64 = 3000;

/// What the host has, in all.
const HOST_TOTAL: u64 = 64 * G;

/// The host's margin for page cache (ADR 0055): the larger of 2G and a sixteenth of the host.
const HOST_MARGIN: u64 = HOST_TOTAL / 16;

/// How a seed container's start ends in the names of what a tick started.
const SEED_START: &str = "'s seed container";

/// Cases run by default; `RUNNERD_INVARIANT_CASES` sets another number.
const CASES: u64 = 64;

/// Events in a case.
const EVENTS: usize = 40;

/// How far apart the model's ticks are, for the running jobs' reads: a third of the default `poll_interval` (ADR 0124).
/// A command's tick comes this long after the last.
const TICK_EVERY: Duration = Duration::from_secs(5);

/// The config's `poll_interval`: the default. A `Tick` comes this long after the last, every repository due.
const POLL_INTERVAL: Duration = Duration::from_secs(15);

/// A deterministic generator (SplitMix64): the same seed gives the same sequence on every machine.
pub(super) struct Rng(pub(super) u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }

    pub(super) fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }

    fn index(&mut self) -> usize {
        usize::try_from(self.below(8)).unwrap()
    }
}

/// The config a case runs with: two profiles, `o/r` in both, `o/s` beside it in `heavy`.
#[derive(Debug, Clone, Copy, PartialEq)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each is a config choice a reload flips on its own"
)]
struct Shape {
    admission: Admission,
    cpu_overcommit: bool,
    heavy_slots: u32,
    /// `None`: the `light` profile is gone, and with it `o/r`'s light pool.
    light_slots: Option<u32>,
    /// Whether `o/r` has its light pool, for `r-light` jobs.
    light_pool: bool,
    /// Whether `o/s` is configured.
    second_repository: bool,
    /// `[host] pooled_count`.
    pooled_count: bool,
    /// The `heavy` profile's memory, in gigabytes.
    heavy_memory: u64,
    /// `[caches] mirror`'s `enabled`.
    mirror: bool,
    /// The `heavy` profile's `record_failures`.
    record_failures: bool,
    /// Whether the engine has a build cache, which it is given at its start.
    build_cache: bool,
}

/// A pool as the config has it.
struct PoolShape {
    repository: &'static str,
    profile: &'static str,
    labels: &'static [&'static str],
}

impl Shape {
    const START: Shape = Shape {
        admission: Admission::Caps,
        cpu_overcommit: false,
        heavy_slots: 2,
        light_slots: Some(2),
        light_pool: true,
        second_repository: true,
        pooled_count: true,
        heavy_memory: 4,
        mirror: false,
        record_failures: false,
        build_cache: false,
    };

    fn pools(&self) -> Vec<PoolShape> {
        let mut pools = vec![PoolShape {
            repository: "o/r",
            profile: "heavy",
            labels: &["self-hosted", "app"],
        }];
        if self.light_pool && self.light_slots.is_some() {
            pools.push(PoolShape {
                repository: "o/r",
                profile: "light",
                labels: &["r-light"],
            });
        }
        if self.second_repository {
            pools.push(PoolShape {
                repository: "o/s",
                profile: "heavy",
                labels: &["self-hosted", "s-app"],
            });
        }
        // A third repository, whose jobs come rarely: idle while the others are active (ADR 0128).
        pools.push(PoolShape {
            repository: "o/t",
            profile: "heavy",
            labels: &["self-hosted", "t-app"],
        });
        pools
    }

    fn toml(&self) -> String {
        let mut host = String::new();
        host.push_str(match self.admission {
            Admission::Caps => "admission = \"caps\"\n",
            Admission::Measured => "admission = \"measured\"\n",
        });
        if self.cpu_overcommit {
            host.push_str("cpu_overcommit = 1.0\n");
        }
        if !self.pooled_count {
            host.push_str("pooled_count = false\n");
        }
        let mut config = format!(
            r#"
[host]
slice = "ci.slice"
isolation = "sysbox"
{host}
[caches]
mirror = {{ enabled = {}, memory = "512M", cpus = 1, ttl = "168h" }}
pnpm = {{ max_size = "5G" }}
maven = {{ max_size = "5G" }}

[profiles.heavy]
image_stage = "app"
cpus = 2
memory = "{}G"
slots = {}
record_failures = {}
"#,
            self.mirror, self.heavy_memory, self.heavy_slots, self.record_failures
        );
        if let Some(slots) = self.light_slots {
            let _ = write!(
                config,
                "\n[profiles.light]\nimage_stage = \"app\"\ncpus = 1\nmemory = \"1G\"\nslots = {slots}\n"
            );
        }
        for pool in self.pools() {
            let labels: Vec<String> = pool
                .labels
                .iter()
                .map(|label| format!("{label:?}"))
                .collect();
            let _ = write!(
                config,
                "\n[[repositories]]\nname = {:?}\nprofile = {:?}\nlabels = [{}]\nwarm = 0\n",
                pool.repository,
                pool.profile,
                labels.join(", ")
            );
        }
        config
    }

    /// The profile of the pool that serves a job, by GitHub's rule: a runner takes a job whose every label it has,
    /// compared without case. A job asking for no label is no pool's (ADR 0058).
    fn serves(&self, repository: &str, labels: &[String]) -> Option<&'static str> {
        if labels.is_empty() {
            return None;
        }
        let serving: Vec<&'static str> = self
            .pools()
            .into_iter()
            .filter(|pool| {
                pool.repository == repository
                    && labels.iter().all(|label| {
                        pool.labels
                            .iter()
                            .any(|has| has.eq_ignore_ascii_case(label))
                    })
            })
            .map(|pool| pool.profile)
            .collect();
        assert!(serving.len() <= 1, "the shape has pools sharing labels");
        serving.first().copied()
    }

    fn configures(&self, repository: &str) -> bool {
        self.pools()
            .iter()
            .any(|pool| pool.repository == repository)
    }
}

/// The labels a generated job asks for.
#[derive(Debug, Clone, Copy)]
enum Labels {
    /// Its repository's heavy pool's.
    Heavy,
    /// `o/r`'s light pool's, or for `o/s` a light label it has no pool for.
    Light,
    /// Only `self-hosted`, which the heavy pools have.
    SelfHosted,
    /// A typo of a pool's label.
    Typo,
    /// None at all, as a job naming only a runner group.
    Empty,
    /// One GitHub-hosted runner's.
    Hosted,
}

impl Labels {
    fn of(self, repository: &str) -> Vec<String> {
        let labels: &[&str] = match (self, repository) {
            (Labels::Heavy, "o/r") => &["self-hosted", "app"],
            (Labels::Heavy, "o/t") => &["self-hosted", "t-app"],
            (Labels::Heavy, _) => &["self-hosted", "s-app"],
            (Labels::Light, "o/r") => &["r-light"],
            (Labels::Light, _) => &["s-light"],
            (Labels::SelfHosted, _) => &["self-hosted"],
            (Labels::Typo, _) => &["r-lite"],
            (Labels::Empty, _) => &[],
            (Labels::Hosted, _) => &["ubuntu-latest"],
        };
        labels.iter().map(|label| (*label).to_owned()).collect()
    }
}

/// A change a reload makes to the shape.
#[derive(Debug, Clone, Copy)]
enum Change {
    HeavySlots(u32),
    LightSlots(u32),
    LightPool,
    SecondRepository,
    LightProfile,
    Policy,
    CpuOvercommit,
    PooledCount,
    HeavyMemory,
    Mirror,
    RecordFailures,
}

/// One thing that happens. Indexes pick among the candidates there are then, modulo their number.
#[derive(Debug, Clone, Copy)]
enum Step {
    /// GitHub queues a job of `o/r` (`second` false) or `o/s`.
    Queue {
        second: bool,
        labels: Labels,
    },
    /// GitHub gives a queued job to an idle runner of this machine whose labels it matches.
    Assign(usize),
    /// As `Assign`, but GitHub's listing of queued jobs still shows the job for as long as `POLL_INTERVAL` after the
    /// first runners listing that shows its runner busy, as it does for a few seconds (ADR 0128).
    AssignListed(usize),
    /// GitHub queues a job of `o/t`, the repository that is otherwise idle.
    QueueQuiet {
        labels: Labels,
    },
    /// A tick `after` seconds after the last, at most `TICK_EVERY`, as the repository due first brings, whose
    /// listings went at another time than the others': it lists the repositories due.
    TickSoon {
        after: u64,
    },
    /// ADR 0107's rule forgets every repository's jobs, as ten minutes on: only a runner holding a job keeps its
    /// repository active.
    Quiet,
    /// A running job finishes and its runner exits.
    Finish(usize),
    /// A queued job is cancelled.
    Cancel(usize),
    /// A running job's container vanishes, as when someone removes it.
    Lose(usize),
    /// Someone removes a running job's container, and Docker takes until after the next tick or pass: it refuses its
    /// log and a second removal meanwhile.
    Removing(usize),
    /// The next runner fails to start in Docker.
    StartFails,
    /// The next runner fails to start after Docker made and started its container, which GitHub may give a job
    /// meanwhile; the start's removal of it may fail too, which leaves it running.
    StartFailsLate {
        takes_job: bool,
        cleanup_fails: bool,
    },
    /// The next log capture fails to start, or prints what it has and breaks off.
    CaptureFails {
        mid_stream: bool,
    },
    /// An idle runner exits at once, without a job.
    ExitsAtOnce(usize),
    /// An idle runner exits without a job after waiting `IDLE_TIMEOUT`.
    ExitsIdle(usize),
    /// An idle runner connected and exits without a job, as when its job is cancelled before it begins.
    ExitsConnected(usize),
    /// Docker fails the next inspect of a runner's container.
    InspectFails(usize),
    /// Docker fails the first inspect of the next runner container started.
    StartedInspectFails,
    /// Docker fails the next remove.
    RemoveFails,
    /// The sampler reads the slice and the host: busy runners use `percent` of their caps, the host has
    /// `available` gigabytes available, and its tasks stall or not.
    Sample {
        percent: u64,
        available: u64,
        stalled: bool,
    },
    /// As `Sample`, while the next runner starts: after the plan, and before the tick's later starts.
    SampleDuringStart {
        percent: u64,
        available: u64,
        stalled: bool,
    },
    /// Someone asks to reseed the heavy (`light` false) or the light profile.
    Reseed {
        light: bool,
    },
    Reload(Change),
    /// The daemon restarts: a new engine on the same history and Docker.
    Restart,
    /// The daemon restarts and a signal stops it before its first tick, so before any listing says which of the
    /// runners it adopted are idle; then it starts again.
    RestartThenStop,
    /// As `Restart`, while Docker fails the first inspect of a runner's container.
    RestartInspectFails(usize),
    /// The daemon stops, then starts again: on a signal, or with `runnerd stop` once Docker is gone.
    Stop {
        docker_gone: bool,
    },
    /// Time passes: idle runners waited `IDLE_TIMEOUT`, holds after failures ran out.
    Elapse,
    /// The growth count's window passes with the sampler reading all along (ADR 0130): the brake a restart, a reload
    /// or the guard set lets go at the next look, a brake for growth only after more windows, and the readings are fresh
    /// at `percent` of each runner's cap.
    GrowthWindow {
        percent: u64,
    },
    /// Running jobs pass their first minute, and the predictor says what each reservation goes by from here on.
    Settle,
    /// Each repository's `build` has runs behind it in the heavy pool, so its prediction goes by them.
    PastRuns,
    /// Each repository's `build` has runs behind it in the heavy pool peaking at 3G, and `o/r`'s `lint` in the light
    /// pool at 768M: reservations near their caps, whose headroom can pass what the host keeps for growth.
    PastLargeRuns,
    Tick,
    /// Docker says runners stopped, and a pass between ticks frees their slots and starts runners from the last
    /// tick's listings (ADR 0095).
    Pass,
    /// A running job's runner and container go, and GitHub goes on saying the job is in progress.
    RunnerGoes(usize),
    /// As `RunnerGoes`, and GitHub goes on listing the job queued.
    RunnerGoesStillListed(usize),
    /// GitHub says a job whose runner went completed, and stops listing it.
    OpenJobCompletes(usize),
    /// A forced pause of `o/r` or `o/s`: their runs are cancelled.
    ForcedPause {
        second: bool,
    },
    Resume {
        second: bool,
    },
    /// GitHub lists a runner of this machine's, busy, that no slot holds: its deletes answer `Busy`.
    BusyOrphan,
    /// The heavy profile's snapshot measures over `snapshot_max` at the next check, which no runner is in the way of.
    OversizedSnapshot,
    /// As `Restart`, while Docker fails the restart's first read of a container's log.
    RestartLogsFail,
    /// The daemon restarts with a build cache.
    UseBuildCache,
    /// A running job saves to the build cache while GitHub names no runner for it.
    SaveUnnamed(usize),
    /// GitHub names the runner of a job whose save went unnamed, as it does once the job is over, and says what
    /// started its run.
    RunnerNamed(usize),
    /// GitHub fails every read of a job no runner of this machine runs, until a runner takes it.
    JobReadFails {
        pick: usize,
        how: ReadFailure,
    },
    /// GitHub fails the registration `after` registrations from now: the next one, or one in the middle of a batch.
    RegisterFailsMidBatch {
        after: u32,
    },
    /// GitHub refuses the registration `after` registrations from now for its used-up rate limit, which resets 30
    /// minutes on; every request fails at once until then, as the client fails them.
    RateLimitedDuringStart {
        after: u32,
    },
    /// Docker fails to prepare the caches of the runner `after` preparations from now.
    PrepareFailsMidBatch {
        after: u32,
    },
    /// The daemon is asked to stop `after` registrations or launches from now: on a signal, or with `runnerd stop`
    /// once Docker is gone. At a registration, the batch's starts behind it wait for their turn to register; at a
    /// launch, as the runner's caches are prepared, between it and the batch's next launch. The stop runs to its end,
    /// then the daemon starts again.
    StopDuringStart {
        docker_gone: bool,
        after: u32,
        at: StopAt,
    },
    /// Docker takes 200 ms more to start the next runner container, much more than the others of its batch.
    SlowStart,
    /// The sampler stops while the next runner container starts: the slice's sample turns stale with starts in flight.
    SliceSampleStallsDuringStart,
    /// The daemon goes in the middle of a batch: one start's container runs, Docker's answer not given; the next
    /// start's registration is made, GitHub's answer not given; any later ones wait for their turn to register. Then
    /// it starts again.
    AbortMidBatch,
}

/// Where a `StopDuringStart` comes.
#[derive(Debug, Clone, Copy, PartialEq)]
enum StopAt {
    /// As GitHub registers a runner.
    Registration,
    /// As a launched runner's caches are prepared.
    Launch,
}

/// How GitHub fails a job's reads.
#[derive(Debug, Clone, Copy, PartialEq)]
enum ReadFailure {
    /// 404, as when its run was deleted.
    Gone,
    /// Its rate limit is used up.
    Limited,
    /// 502.
    Other,
}

fn generate(rng: &mut Rng) -> Vec<Step> {
    (0..EVENTS)
        .map(|_| match rng.below(125) {
            0..=17 => Step::Queue {
                second: rng.below(3) == 0,
                labels: match rng.below(10) {
                    0..=3 => Labels::Heavy,
                    4..=5 => Labels::Light,
                    6 => Labels::SelfHosted,
                    7 => Labels::Typo,
                    8 => Labels::Empty,
                    _ => Labels::Hosted,
                },
            },
            18..=26 => Step::Assign(rng.index()),
            27..=29 => Step::AssignListed(rng.index()),
            30..=37 => Step::Finish(rng.index()),
            38..=39 => Step::Cancel(rng.index()),
            40 => Step::Lose(rng.index()),
            96 => Step::Removing(rng.index()),
            41..=42 => Step::StartFails,
            43 => Step::ExitsAtOnce(rng.index()),
            44 => Step::ExitsIdle(rng.index()),
            95 => Step::ExitsConnected(rng.index()),
            45..=46 => Step::InspectFails(rng.index()),
            47 => Step::RemoveFails,
            48..=54 => Step::Sample {
                percent: [10, 50, 90, 120][rng.index() % 4],
                available: [3, 6, 8, 9, 20, 50][rng.index() % 6],
                stalled: rng.below(5) == 0,
            },
            55..=62 => Step::Reload(reload(rng)),
            63..=64 => Step::Restart,
            65 => Step::RestartThenStop,
            66..=67 => Step::RestartInspectFails(rng.index()),
            68..=71 => Step::Elapse,
            97..=98 => Step::GrowthWindow {
                percent: [10, 50, 90][rng.index() % 3],
            },
            72..=73 => Step::Reseed {
                light: rng.below(2) == 0,
            },
            74 => Step::StartedInspectFails,
            75..=76 => Step::StartFailsLate {
                takes_job: rng.below(2) == 0,
                cleanup_fails: rng.below(2) == 0,
            },
            77..=78 => Step::SampleDuringStart {
                percent: [10, 50, 90, 120][rng.index() % 4],
                available: [3, 8, 20, 50][rng.index() % 4],
                stalled: rng.below(5) == 0,
            },
            79..=80 => Step::CaptureFails {
                mid_stream: rng.below(2) == 0,
            },
            81..=82 => Step::Stop {
                docker_gone: rng.below(2) == 0,
            },
            83..=89 => Step::Pass,
            90..=93 => Step::Settle,
            100..=101 => Step::RunnerGoes(rng.index()),
            102 => Step::RunnerGoesStillListed(rng.index()),
            103..=104 => Step::OpenJobCompletes(rng.index()),
            105 => Step::ForcedPause {
                second: rng.below(3) == 0,
            },
            106 => Step::Resume {
                second: rng.below(3) == 0,
            },
            107 => Step::BusyOrphan,
            108 => Step::OversizedSnapshot,
            109 => Step::Reload(Change::Mirror),
            110 => Step::Reload(Change::RecordFailures),
            111 => Step::RestartLogsFail,
            99 => Step::JobReadFails {
                pick: rng.index(),
                how: [ReadFailure::Gone, ReadFailure::Limited, ReadFailure::Other][rng.index() % 3],
            },
            fault @ 112..=118 => mid_batch(rng, fault),
            119..=121 => Step::TickSoon {
                after: [2, 3, 5][rng.index() % 3],
            },
            122 => Step::Quiet,
            123 => Step::QueueQuiet {
                labels: if rng.below(4) == 0 {
                    Labels::Typo
                } else {
                    Labels::Heavy
                },
            },
            _ => Step::Tick,
        })
        .collect()
}

/// A change of config, as `generate` drew a reload.
fn reload(rng: &mut Rng) -> Change {
    match rng.below(10) {
        0 => Change::HeavySlots(1 + u32::try_from(rng.below(3)).unwrap()),
        1 => Change::LightSlots(1 + u32::try_from(rng.below(3)).unwrap()),
        2 => Change::LightPool,
        3 => Change::SecondRepository,
        4 => Change::LightProfile,
        5 => Change::Policy,
        6 => Change::PooledCount,
        7 => Change::HeavyMemory,
        _ => Change::CpuOvercommit,
    }
}

/// A fault in the middle of a batch of starts, as `generate` drew `fault` from 112 to 118.
fn mid_batch(rng: &mut Rng, fault: u64) -> Step {
    match fault {
        112 => Step::RegisterFailsMidBatch {
            after: u32::try_from(rng.below(4)).unwrap(),
        },
        113 => Step::RateLimitedDuringStart {
            after: u32::try_from(rng.below(4)).unwrap(),
        },
        114 => Step::PrepareFailsMidBatch {
            after: u32::try_from(rng.below(4)).unwrap(),
        },
        115 => Step::StopDuringStart {
            docker_gone: rng.below(2) == 0,
            after: u32::try_from(rng.below(4)).unwrap(),
            at: if rng.below(2) == 0 {
                StopAt::Registration
            } else {
                StopAt::Launch
            },
        },
        116 => Step::SlowStart,
        117 => Step::SliceSampleStallsDuringStart,
        _ => Step::AbortMidBatch,
    }
}

/// How a tick of the model comes.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Comes {
    /// `POLL_INTERVAL` after the last, every repository due: it lists them, their runners on their turn.
    Due,
    /// This long after the last: it lists the repositories due.
    Soon(Duration),
    /// `TICK_EVERY` after the last, brought by a command: it lists every repository and its runners.
    Command,
}

/// What GitHub's listing of queued jobs shows of a job a runner just took.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Listing {
    /// It no longer lists it.
    Current,
    /// It still lists it for a while (`Step::AssignListed`).
    Stale,
}

/// When an idle runner exits without a job.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Exit {
    AtOnce,
    AfterIdleTimeout,
    Connected,
}

/// A runner the harness made exit without a job, until a tick or a pass frees its slot.
#[derive(Debug, Clone)]
struct ExitWatch {
    container: String,
    repository: String,
    profile: String,
    exit: Exit,
    /// Its pool was held, or a streak of runners that left was under way, when it exited.
    quiet_before: bool,
}

/// Where a job is, as GitHub knows it.
#[derive(Debug, Clone, PartialEq)]
enum Phase {
    Queued,
    /// A runner of this machine runs it.
    Running {
        container: String,
    },
    /// Its runner went and GitHub has not said it ended: `ran` as for `Done`, once it does.
    Open {
        ran: Option<(String, String)>,
    },
    /// Over: `ran` is the profile and repository of the runner that ran it, if one of this machine's did.
    Done {
        ran: Option<(String, String)>,
    },
}

#[derive(Debug, Clone)]
struct JobModel {
    repository: &'static str,
    /// `lint` for a light job, `build` for any other: a third job beside each repository's `build`, so the host's
    /// credit, which keeps the two largest jobs' headroom, can stand (ADR 0108).
    name: &'static str,
    labels: Vec<String>,
    phase: Phase,
    /// The profile and repository of the runner that took it.
    taken_by: Option<(String, String)>,
    /// A tick saw it queued, so the engine follows it.
    listed: bool,
    /// The last listing of its repository's queued jobs since it queued showed it, served by a pool or not, so the
    /// status lists it while it stays queued. One that failed forgets it, as the engine forgets what a failed listing
    /// showed; that repository keeps its cadence (ADR 0128), so a tick before it is due again does not list it back.
    shown: bool,
    /// A tick saw it running once it was listed and no longer queued: GitHub's details then name its runner,
    /// whatever its log capture said.
    named_by_github: bool,
}

/// A reading of the host the harness gave the sampler.
#[derive(Debug, Clone, Copy)]
struct HostReading {
    /// Unix seconds.
    at: u64,
    slice: u64,
    available: u64,
    stalled: bool,
}

impl HostReading {
    /// Whether admission still goes by it at `now` (ms): it is from the last three sample intervals.
    fn fresh(&self, now: u64) -> bool {
        self.at + 3 * api::SAMPLE_INTERVAL >= now / 1000
    }
}

/// A broken invariant: which, at which step, and what was seen.
#[derive(Debug, Clone)]
struct Violation {
    invariant: &'static str,
    step: usize,
    detail: String,
}

/// What changed as a runner of a batch started, and how many runners the batch's engine had launched by then: the
/// launches after those go by it, and those before by what their plan had, whenever their registration or Docker's
/// start came.
#[derive(Debug, Clone, Copy)]
struct MidBatch {
    /// The sampler's reading then, if it took one.
    reading: Option<HostReading>,
    launched: usize,
}

/// A stop a `StopDuringStart` asked for, with what the engine had done by then.
#[derive(Debug, Clone)]
struct AskedStop {
    docker_gone: bool,
    at: StopAt,
    /// How many runners the engine had launched, and how many calls GitHub had seen, when it was asked for.
    launched: usize,
    calls: usize,
}

/// A case: the engine on the fakes, and what GitHub and Docker hold as the world sees it.
/// How many checks saw what they exist for: none of either in all cases, and they check nothing.
#[derive(Debug, Clone, Copy, Default)]
struct Seen {
    barriers: usize,
    credits: usize,
    /// Checks that found the host's credit standing (ADR 0108).
    host_credits: usize,
    /// Checks of the growth count while it counts.
    growth_counts: usize,
    /// Ticks that left the larger margin standing with waiters, none fitting the plain one.
    bands: usize,
    /// Ticks that gave it up for a job that fits the plain one, which the next plan starts.
    released: usize,
    /// Runners that exited without a job and whose slots were freed.
    exits_freed: usize,
    /// Jobs a runner started for that had not taken it yet.
    runners_starting: usize,
    /// Ticks that ended with a job whose runner went and that GitHub has not said ended.
    closing: usize,
    /// Ticks that ended with a runner's build cache uploads waiting for GitHub's word.
    ended_uploads: usize,
    /// Ticks that decided such uploads by GitHub's word, before `ENDED_WAIT`.
    decided_uploads: usize,
    /// Cases that ended with a job lost: GitHub did not say it completed for `LOST_AFTER` after its runner went.
    lost_closes: usize,
    /// Cases that ended with a job closed as run elsewhere because GitHub said it was gone, or failed every read of
    /// it for `LOST_AFTER`.
    unanswered_closes: usize,
    /// Ticks that ended with a cancelled run's runner waiting to exit.
    cancelling: usize,
    /// Ticks that ended with a busy registration no slot holds.
    busy_orphans: usize,
    /// Ticks that listed one repository's queued jobs but not another's, whose runner a runners listing showed busy
    /// with a job GitHub still lists queued (ADR 0128).
    beside_still_listed: usize,
    /// Ticks that listed one repository's queued jobs alone: the active one, while the others were not due.
    one_due: usize,
    /// Ticks that ended with a snapshot marked over its limit.
    oversized: usize,
    /// Ticks that ended with a leftover container Docker could not say what to do with.
    unread: usize,
    /// Ticks that ended with the registry mirror running.
    mirrors: usize,
    /// Ticks that ended with a pool's memory and CPU waits on different jobs.
    split_waits: usize,
    /// Ticks that ended with a capture running beside its next start's memory of where it broke.
    captures_with_recaptures: usize,
    /// Starts whose registration GitHub failed.
    registrations_failed: usize,
    /// Starts whose registration GitHub refused for its rate limit.
    registrations_limited: usize,
    /// Starts whose caches Docker failed to prepare.
    prepares_failed: usize,
    /// Stops asked for while GitHub registered a runner.
    stops_during_start: usize,
    /// Stops asked for between two launches of a batch.
    stops_between_launches: usize,
    /// Slow runner starts beside other starts of their batch.
    slow_starts: usize,
    /// Slice samples that turned stale with starts in flight.
    stalls_during_start: usize,
    /// Daemons gone with one start's container made and the next start's registration made.
    aborts_mid_batch: usize,
}

impl Seen {
    fn add(&mut self, case: Seen) {
        self.barriers += case.barriers;
        self.exits_freed += case.exits_freed;
        self.runners_starting += case.runners_starting;
        self.closing += case.closing;
        self.ended_uploads += case.ended_uploads;
        self.decided_uploads += case.decided_uploads;
        self.lost_closes += case.lost_closes;
        self.unanswered_closes += case.unanswered_closes;
        self.cancelling += case.cancelling;
        self.busy_orphans += case.busy_orphans;
        self.beside_still_listed += case.beside_still_listed;
        self.one_due += case.one_due;
        self.oversized += case.oversized;
        self.unread += case.unread;
        self.mirrors += case.mirrors;
        self.split_waits += case.split_waits;
        self.captures_with_recaptures += case.captures_with_recaptures;
        self.registrations_failed += case.registrations_failed;
        self.registrations_limited += case.registrations_limited;
        self.prepares_failed += case.prepares_failed;
        self.stops_during_start += case.stops_during_start;
        self.stops_between_launches += case.stops_between_launches;
        self.slow_starts += case.slow_starts;
        self.stalls_during_start += case.stalls_during_start;
        self.aborts_mid_batch += case.aborts_mid_batch;
        self.growth_counts += case.growth_counts;
    }

    /// The states no generated case reached, so nothing checks them.
    fn unreached(&self) -> Vec<&'static str> {
        [
            ("a barrier", self.barriers),
            ("the growth count counting", self.growth_counts),
            ("a runner that left without a job", self.exits_freed),
            ("a runner started before its job", self.runners_starting),
            ("a job whose runner went, still open", self.closing),
            ("uploads waiting for GitHub", self.ended_uploads),
            ("uploads GitHub's word decided", self.decided_uploads),
            ("a job lost", self.lost_closes),
            ("a job GitHub stopped answering for", self.unanswered_closes),
            ("a cancelled run's runner", self.cancelling),
            ("a busy orphan registration", self.busy_orphans),
            (
                "a listing beside a repository whose taken job GitHub still lists",
                self.beside_still_listed,
            ),
            ("a tick listing one repository alone", self.one_due),
            ("an oversized snapshot", self.oversized),
            ("an unread leftover", self.unread),
            ("the mirror running", self.mirrors),
            (
                "a pool's memory and CPU waits on different jobs",
                self.split_waits,
            ),
            (
                "a capture beside a recapture",
                self.captures_with_recaptures,
            ),
            ("a registration that failed", self.registrations_failed),
            (
                "a registration refused for the rate limit",
                self.registrations_limited,
            ),
            ("caches that failed to prepare", self.prepares_failed),
            ("a stop while a runner registers", self.stops_during_start),
            ("a stop between two launches", self.stops_between_launches),
            ("a slow start beside others", self.slow_starts),
            ("a slice sample stale mid-batch", self.stalls_during_start),
            ("a daemon gone mid-batch", self.aborts_mid_batch),
        ]
        .into_iter()
        .filter_map(|(state, count)| (count == 0).then_some(state))
        .collect()
    }
}

struct Case {
    /// What the checks saw.
    seen: Seen,
    /// What the age of a reading goes by, the engine's too, stopped: only `Elapse` writes an old one, however slow the
    /// machine. A runner's start goes by the system's clock, so never reads old.
    clock: Clock,
    github: FakeGithub,
    docker: FakeDocker,
    dir: TestDir,
    engine: Engine<FakeGithub, FakeDocker>,
    handle: Handle,
    shape: Shape,
    jobs: BTreeMap<u64, JobModel>,
    next_job: u64,
    /// Containers that took a job, which are no longer idle.
    took_job: BTreeSet<String>,
    /// Jobs a runner took that GitHub still lists queued, with the model's time of the first runners listing of their
    /// repository since, which shows the runner busy: GitHub stops listing each `POLL_INTERVAL` after that.
    still_listed: BTreeMap<u64, Option<Duration>>,
    /// By repository, the jobs its last listing showed queued that were cancelled since: a plan of a tick that does
    /// not list it, or of a pass, plans from that listing.
    cancelled_since_listed: BTreeMap<&'static str, BTreeSet<u64>>,
    /// How long the model has run: what the ticks' spacing added up to.
    model: Duration,
    /// Docker calls checked so far.
    calls_seen: usize,
    /// The last reading of the host this daemon's store has, which a restart loses.
    host: Option<HostReading>,
    /// What a `SampleDuringStart` or a `SliceSampleStallsDuringStart` changed as a runner started, until the tick
    /// it came in checks the starts launched after it.
    mid_batch: Arc<Mutex<Option<MidBatch>>>,
    /// The stop a `StopDuringStart` asked for, until the step carries it out.
    stop_during_start: Arc<Mutex<Option<AskedStop>>>,
    /// Log captures `CaptureFails` failed, by container, as of the start of the last tick.
    capture_faults: HashMap<String, u32>,
    /// Runners that exited without a job, whose slots the engine has not freed yet. A restart forgets them, as it
    /// forgets holds: recovery removes such a container without a verdict on its pool.
    exits: Vec<ExitWatch>,
    /// Each busy runner as the tick or pass began: its container, repository and profile. One that ends in it proves
    /// its pool works and ends any hold.
    busy_before: Vec<(String, String, String)>,
    /// Runners whose job ended since the engine last looked, as in `busy_before`: one that took and finished a job
    /// between two looks was never seen busy.
    ended_between: Vec<(String, String, String)>,
    /// Jobs GitHub goes on listing queued after their runner went.
    listed_after_runner: BTreeSet<u64>,
    /// Containers of runs a forced pause cancelled: the engine may remove them, ending their jobs.
    forced: BTreeSet<String>,
    /// Registrations `BusyOrphan` made.
    orphans: Vec<u64>,
    /// The runners of jobs whose saves went unnamed, by job.
    unnamed_saves: BTreeMap<u64, String>,
    /// When the case began, which the trace's times of the jobs it closed count from.
    began_ms: u64,
    /// What the case asked of the fakes, step by step, when traced.
    trace: Option<Vec<String>>,
    step: usize,
    /// The second every engine of the case starts from as its last runner's, as when each restart comes within one
    /// second of the clock; 0 for the clock's.
    names_from: u64,
}

fn violation(case: &Case, invariant: &'static str, detail: String) -> Result<(), Violation> {
    Err(Violation {
        invariant,
        step: case.step,
        detail,
    })
}

impl Case {
    fn new() -> Case {
        let github = FakeGithub::default();
        let docker = FakeDocker::default();
        github.0.lock().unwrap().strict = true;
        {
            let mut state = docker.0.lock().unwrap();
            state.captures_wait = Some(github.clone());
            state.seed_exit = Some(0);
        }
        let dir = TestDir::new("invariants");
        let shape = Shape::START;
        let clock = Clock::stopped();
        let (engine, handle) = Case::engine(&github, &docker, &dir, shape, clock.clone());
        Case {
            seen: Seen::default(),
            clock,
            github,
            docker,
            dir,
            engine,
            handle,
            shape,
            jobs: BTreeMap::new(),
            next_job: 1,
            took_job: BTreeSet::new(),
            still_listed: BTreeMap::new(),
            cancelled_since_listed: BTreeMap::new(),
            model: Duration::ZERO,
            calls_seen: 0,
            host: None,
            mid_batch: Arc::default(),
            stop_during_start: Arc::default(),
            capture_faults: HashMap::new(),
            exits: Vec::new(),
            busy_before: Vec::new(),
            ended_between: Vec::new(),
            listed_after_runner: BTreeSet::new(),
            forced: BTreeSet::new(),
            orphans: Vec::new(),
            unnamed_saves: BTreeMap::new(),
            began_ms: time::now_ms(),
            trace: None,
            step: 0,
            names_from: 0,
        }
    }

    fn engine(
        github: &FakeGithub,
        docker: &FakeDocker,
        dir: &TestDir,
        shape: Shape,
        clock: Clock,
    ) -> (Engine<FakeGithub, FakeDocker>, Handle) {
        let (mut engine, handle) = if shape.build_cache {
            let (engine, handle, _cache) =
                build_cache::engine_with_cache(github, docker, dir, &shape.toml());
            (engine, handle)
        } else {
            engine_with(github, docker, dir, &shape.toml())
        };
        engine.clock = clock;
        // A daemon's start, by the clock it reads.
        engine.measured.restart_growth(engine.now());
        engine.memory_max = Some(MEMORY_MAX);
        engine.cpus = Some(SLICE_CPUS);
        (engine, handle)
    }

    /// Recovers as `Engine::run` does: again until Docker answers.
    async fn recover(&mut self) -> Result<(), Violation> {
        for _ in 0..10 {
            if self.engine.recover().await.is_ok() {
                return Ok(());
            }
        }
        violation(
            self,
            "recovery_succeeds",
            "Docker never answered".to_owned(),
        )
    }

    /// The runner containers Docker runs, by ID.
    fn running_containers(&self) -> Vec<Container> {
        self.docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .filter(|container| container.running && container.labels.contains_key("runnerd.job"))
            .cloned()
            .collect()
    }

    /// Running runner containers of this machine that took no job, which GitHub may give one.
    fn idle_containers(&self) -> Vec<Container> {
        self.running_containers()
            .into_iter()
            .filter(|container| !self.took_job.contains(&container.id))
            .collect()
    }

    fn queued(&self) -> Vec<u64> {
        self.jobs
            .iter()
            .filter(|(_, job)| job.phase == Phase::Queued)
            .map(|(id, _)| *id)
            .collect()
    }

    fn running(&self) -> Vec<(u64, String)> {
        self.jobs
            .iter()
            .filter_map(|(id, job)| match &job.phase {
                Phase::Running { container } => Some((*id, container.clone())),
                _ => None,
            })
            .collect()
    }

    /// When traced, records what this step asked of the fakes, once the background work it began has run.
    async fn trace_step(&mut self, step: &str) {
        if self.trace.is_none() {
            return;
        }
        self.settle_background().await;
        let status = steady(&steady_status(&self.status()).to_string());
        let github = std::mem::take(&mut self.github.0.lock().unwrap().trace);
        let (docker, execs) = {
            let mut state = self.docker.0.lock().unwrap();
            (
                std::mem::take(&mut state.trace),
                std::mem::take(&mut state.exec_trace),
            )
        };
        if let Some(trace) = self.trace.as_mut() {
            trace.push(format!("-- {step}"));
            trace.push(format!("status {status}"));
            trace.extend(github.iter().map(|call| format!("github {}", steady(call))));
            trace.extend(docker.iter().map(|call| format!("docker {}", steady(call))));
            trace.extend(execs.iter().map(|call| format!("capture {}", steady(call))));
        }
    }

    /// Waits until what the step set going has stopped calling the fakes: until the calls stop growing for
    /// `QUIET_ROUNDS` rounds in a row, each round letting blocking threads and the runtime's tasks run.
    async fn settle_background(&mut self) {
        let mut quiet = 0;
        let mut last = (usize::MAX, usize::MAX);
        while quiet < QUIET_ROUNDS {
            self.handle.store.flush().await;
            for _ in 0..16 {
                tokio::task::yield_now().await;
            }
            tokio::time::sleep(Duration::from_millis(1)).await;
            let now = (self.github.0.lock().unwrap().trace.len(), {
                let state = self.docker.0.lock().unwrap();
                state.trace.len() + state.exec_trace.len()
            });
            quiet = if now == last { quiet + 1 } else { 0 };
            last = now;
        }
    }

    /// The seconds between two ticks: what runs beside the engine, as a reseed or a measure, goes on until it calls
    /// the fakes no more for two rounds, or for at most `QUIET_ROUNDS` rounds, so it never waits on what a step holds.
    /// A tick that lists only the repositories due yields less on its own than one that lists them all.
    async fn between_ticks(&mut self) {
        let calls = || {
            (
                self.github.calls().len(),
                self.docker.0.lock().unwrap().calls.len(),
            )
        };
        let (mut last, mut quiet) = (calls(), 0);
        for _ in 0..QUIET_ROUNDS {
            for _ in 0..16 {
                tokio::task::yield_now().await;
            }
            tokio::time::sleep(Duration::from_millis(1)).await;
            let now = calls();
            quiet = if now == last { quiet + 1 } else { 0 };
            if quiet == 2 {
                return;
            }
            last = now;
        }
    }

    /// Counts the jobs the engine closed for GitHub's silence, as the history ends.
    async fn note_closes(&mut self) {
        self.handle.store.flush().await;
        let db = rusqlite::Connection::open(self.dir.0.join("history.db")).unwrap();
        let count = |condition: &str| {
            db.query_row(
                &format!("SELECT count(*) FROM jobs WHERE {condition}"),
                [],
                |row| row.get::<_, i64>(0),
            )
            .map(|count| usize::try_from(count).unwrap())
            .unwrap()
        };
        self.seen.lost_closes += count("state = 'lost'");
        self.seen.unanswered_closes += count("state = 'elsewhere' AND conclusion IS NULL");
    }

    /// Counts the faults of a start's registration and preparation that a start met.
    fn note_start_faults(&mut self) {
        let github = self.github.0.lock().unwrap();
        self.seen.registrations_failed += github.registrations_failed;
        self.seen.registrations_limited += github.registrations_limited_once;
        drop(github);
        self.seen.prepares_failed += self.docker.0.lock().unwrap().prepares_failed;
    }

    /// The trace, with what the case left in its history's jobs table.
    async fn finished_trace(mut self) -> Vec<String> {
        self.handle.store.flush().await;
        let mut trace = self.trace.take().unwrap_or_default();
        trace.push("-- jobs".to_owned());
        let db = rusqlite::Connection::open(self.dir.0.join("history.db")).unwrap();
        let mut rows = db
            .prepare(
                "SELECT id, repository, state, conclusion, github_completed, runner, \
                 started_at IS NOT NULL, finished_at IS NOT NULL, slot_waited > 0, host_waited > 0, \
                 CASE WHEN state = 'lost' OR (state = 'elsewhere' AND conclusion IS NULL) THEN finished_at END \
                 FROM jobs ORDER BY id",
            )
            .unwrap();
        // The time the engine closed a job at, in minutes from the case's start: `Elapse` moves it back by
        // `LOST_AFTER`, so a clock kept or started over shows.
        let began = i64::try_from(self.began_ms).unwrap();
        let jobs = rows
            .query_map([], |row| {
                Ok(format!(
                    "{} {} {} {:?} {} {:?} {} {} slot_waited {} host_waited {} closed {:?}",
                    row.get::<_, i64>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, i64>(4)?,
                    row.get::<_, Option<String>>(5)?.map(|name| steady(&name)),
                    row.get::<_, bool>(6)?,
                    row.get::<_, bool>(7)?,
                    row.get::<_, bool>(8)?,
                    row.get::<_, bool>(9)?,
                    row.get::<_, Option<i64>>(10)?
                        .map(|at| (at - began + 30_000).div_euclid(60_000)),
                ))
            })
            .unwrap();
        trace.extend(jobs.map(Result::unwrap));
        trace
    }

    fn status(&mut self) -> api::Status {
        self.engine.publish();
        self.handle.status.borrow().clone()
    }

    #[allow(
        clippy::too_many_lines,
        reason = "one arm per step, which split up would only be listed twice"
    )]
    async fn apply(&mut self, step: Step) -> Result<(), Violation> {
        match step {
            Step::Queue { second, labels } => {
                self.queue(if second { "o/s" } else { "o/r" }, labels);
            }
            Step::QueueQuiet { labels } => self.queue("o/t", labels),
            Step::TickSoon { after } => {
                self.tick_as(Comes::Soon(Duration::from_secs(after)))
                    .await?;
            }
            Step::Quiet => self
                .engine
                .warm
                .testing_learned(crate::scheduler::warm::Learned::default()),
            Step::Assign(pick) => self.assign(pick, Listing::Current).await,
            Step::AssignListed(pick) => self.assign(pick, Listing::Stale).await,
            Step::Finish(pick) => {
                let running = self.running();
                if let Some((id, container)) = pick_from(&running, pick).cloned() {
                    self.end_job(id, &container, "success");
                    // As for `Lose`: Docker runs no capture in a container that stopped.
                    if (self.unobserved(&container) || self.capture_unread(id, &container))
                        && let Some(job) = self.jobs.get_mut(&id)
                    {
                        job.phase = Phase::Done { ran: None };
                    }
                    let name = self.jobs[&id].name;
                    let mut docker = self.docker.0.lock().unwrap();
                    docker
                        .container_logs
                        .insert(container.clone(), format!("Running job: {name}\n"));
                    set_running(&mut docker, &container, false);
                }
            }
            Step::Cancel(pick) => {
                let queued = self.queued();
                if let Some(id) = pick_from(&queued, pick).copied() {
                    let mut github = self.github.0.lock().unwrap();
                    github.queued.retain(|job| job.id != id);
                    let mut cancelled = details(id, "completed", Some("cancelled"));
                    cancelled.runner_name = None;
                    github.jobs.insert(id, cancelled);
                    let job = self.jobs.get_mut(&id).unwrap();
                    job.phase = Phase::Done { ran: None };
                    if job.listed {
                        self.cancelled_since_listed
                            .entry(job.repository)
                            .or_default()
                            .insert(id);
                    }
                }
            }
            Step::Lose(pick) => self.lose(pick),
            Step::Removing(pick) => self.removing(pick),
            Step::StartFails => self.docker.0.lock().unwrap().fail_starts += 1,
            Step::StartFailsLate {
                takes_job,
                cleanup_fails,
            } => {
                let failure = LateFailure {
                    takes_job,
                    cleanup_fails,
                };
                self.docker
                    .0
                    .lock()
                    .unwrap()
                    .late_failures
                    .push_back(failure);
            }
            Step::CaptureFails { mid_stream } => {
                let mut docker = self.docker.0.lock().unwrap();
                *if mid_stream {
                    &mut docker.break_captures
                } else {
                    &mut docker.fail_execs
                } += 1;
            }
            Step::ExitsAtOnce(pick) => self.exit_idle(pick, Exit::AtOnce),
            Step::ExitsIdle(pick) => self.exit_idle(pick, Exit::AfterIdleTimeout),
            Step::ExitsConnected(pick) => self.exit_idle(pick, Exit::Connected),
            Step::InspectFails(pick) => self.inspect_fails(pick),
            Step::StartedInspectFails => self.docker.0.lock().unwrap().fail_started_inspects += 1,
            Step::RemoveFails => self.docker.0.lock().unwrap().fail_removes += 1,
            Step::Sample {
                percent,
                available,
                stalled,
            } => {
                let docker = self.docker.0.lock().unwrap();
                let reading = sample(
                    &docker,
                    &self.handle.store,
                    &self.took_job,
                    self.clock.now_ms(),
                    percent,
                    available,
                    stalled,
                );
                drop(docker);
                self.host = Some(reading);
            }
            Step::SampleDuringStart {
                percent,
                available,
                stalled,
            } => self.sample_during_start(percent, available, stalled),
            // Refused for a profile reseeding already, one a reload removed and one a shell holds.
            Step::Reseed { light } => {
                let _ = self
                    .engine
                    .request_reseed(if light { "light" } else { "heavy" });
            }
            Step::Reload(change) => {
                self.reload(change).await?;
                self.tick_as(Comes::Command).await?;
            }
            Step::Restart => {
                self.restart().await?;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::RestartThenStop => {
                self.restart().await?;
                self.stop(false).await?;
                self.restart().await?;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::Stop { docker_gone } => {
                self.stop(docker_gone).await?;
                self.restart().await?;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::RestartInspectFails(pick) => {
                self.inspect_fails(pick);
                self.restart().await?;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::Elapse => self.elapse(),
            Step::GrowthWindow { percent } => {
                // Not by the clock, which a start does not read: its runners would read old at once.
                self.engine
                    .measured
                    .age_growth(api::GROWTH_WINDOW + Duration::from_secs(1));
                let docker = self.docker.0.lock().unwrap();
                let reading = sample(
                    &docker,
                    &self.handle.store,
                    &self.took_job,
                    self.clock.now_ms(),
                    percent,
                    50,
                    false,
                );
                drop(docker);
                self.host = Some(reading);
            }
            Step::Settle => self.settle(),
            Step::PastRuns => {
                self.past_runs(&[("o/r", "build", "heavy", G), ("o/s", "build", "heavy", G)])
                    .await;
            }
            Step::PastLargeRuns => {
                let runs = [
                    ("o/r", "build", "heavy", 3 * G),
                    ("o/s", "build", "heavy", 3 * G),
                    ("o/r", "lint", "light", 768 * M),
                ];
                self.past_runs(&runs).await;
            }
            Step::Tick => self.tick().await?,
            Step::Pass => self.pass().await?,
            Step::RunnerGoes(pick) => self.runner_goes(pick, Listing::Current),
            Step::RunnerGoesStillListed(pick) => self.runner_goes(pick, Listing::Stale),
            Step::OpenJobCompletes(pick) => self.open_job_completes(pick),
            Step::ForcedPause { second } => self.forced_pause(second).await,
            Step::Resume { second } => self.resume(second).await,
            Step::BusyOrphan => self.busy_orphan(),
            Step::OversizedSnapshot => self.oversized_snapshot(),
            Step::RestartLogsFail => {
                self.docker.0.lock().unwrap().fail_logs = 1;
                self.restart().await?;
                // For the restart alone: a later log that cannot be read says nothing of why its runner left.
                self.docker.0.lock().unwrap().fail_logs = 0;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::UseBuildCache => {
                self.shape.build_cache = true;
                self.restart().await?;
                self.tick().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
            Step::SaveUnnamed(pick) => self.save_unnamed(pick).await,
            Step::RunnerNamed(pick) => self.runner_named(pick),
            Step::JobReadFails { pick, how } => self.job_read_fails(pick, how),
            Step::RegisterFailsMidBatch { after } => {
                let mut github = self.github.0.lock().unwrap();
                github.pass_before_fault = after;
                github.fail_registrations += 1;
            }
            Step::RateLimitedDuringStart { after } => {
                let mut github = self.github.0.lock().unwrap();
                github.pass_before_fault = after;
                github.limit_registrations += 1;
            }
            Step::PrepareFailsMidBatch { after } => {
                let mut docker = self.docker.0.lock().unwrap();
                docker.prepares_before_fault = after;
                docker.fail_prepares += 1;
            }
            Step::StopDuringStart {
                docker_gone,
                after,
                at,
            } => self.stop_during_start(docker_gone, after, at),
            Step::SlowStart => {
                self.docker.0.lock().unwrap().slow_start = Some(Duration::from_millis(200));
            }
            Step::SliceSampleStallsDuringStart => self.slice_sample_stalls_during_start(),
            Step::AbortMidBatch => {
                self.abort_mid_batch().await;
                self.restart().await?;
                self.tick().await?;
                self.a_restart_cleans_up_an_aborted_batch().await?;
                self.a_restart_takes_the_host_credit_back()?;
            }
        }
        self.finish_stop_during_start().await?;
        self.no_removal_of_a_running_job()
    }

    /// Asks for a stop `after` registrations or launches from now, which the step that started it then carries out.
    /// GitHub queues a job of `repository` asking for `labels`.
    fn queue(&mut self, repository: &'static str, labels: Labels) {
        let id = self.next_job;
        self.next_job += 1;
        let name = if matches!(labels, Labels::Light) {
            "lint"
        } else {
            "build"
        };
        let labels = labels.of(repository);
        let mut github = self.github.0.lock().unwrap();
        github.queued.push(QueuedJob {
            id,
            run_id: id,
            name: name.to_owned(),
            labels: labels.clone(),
            created_at: time::now_ms(),
            ..QueuedJob::default()
        });
        github.queued_on.insert(id, repository.to_owned());
        // GitHub answers what started each even run, so the build cache can decide its writes.
        if id.is_multiple_of(2) {
            github
                .triggers
                .insert(id, build_cache::trigger("push", "main"));
        }
        self.jobs.insert(
            id,
            JobModel {
                repository,
                name,
                labels,
                phase: Phase::Queued,
                taken_by: None,
                listed: false,
                shown: false,
                named_by_github: false,
            },
        );
    }

    fn stop_during_start(&mut self, docker_gone: bool, after: u32, at: StopAt) {
        let (control, asked, launches, github) = (
            self.handle.control.clone(),
            self.stop_during_start.clone(),
            self.engine.launches(),
            self.github.clone(),
        );
        // Under the lock of the fake whose call runs it: the other one's is free.
        let ask = move |calls: usize| {
            control.shutdown(if docker_gone {
                Shutdown::Graceful
            } else {
                Shutdown::Detach
            });
            *asked.lock().unwrap() = Some(AskedStop {
                docker_gone,
                at,
                launched: launches.count(),
                calls,
            });
        };
        match at {
            StopAt::Registration => {
                let docker = self.docker.clone();
                let mut state = self.github.0.lock().unwrap();
                state.register_hook_after = after;
                state.on_register = Some(Box::new(move |_| {
                    if docker_gone {
                        docker.set_outage(Outage::Refused);
                    }
                    // GitHub's lock is held: its calls so far include this registration, which is answered after.
                    ask(usize::MAX);
                }));
            }
            StopAt::Launch => {
                let mut state = self.docker.0.lock().unwrap();
                state.prepare_hook_after = after;
                state.on_prepare = Some(Box::new(move |docker| {
                    if docker_gone {
                        docker.outage = Outage::Refused;
                    }
                    ask(github.calls().len());
                }));
            }
        }
    }

    /// Carries out the stop a `StopDuringStart` asked for, if it did, as `Stop` does: to its end, then a restart.
    async fn finish_stop_during_start(&mut self) -> Result<(), Violation> {
        let Some(asked) = self.stop_during_start.lock().unwrap().take() else {
            return Ok(());
        };
        match asked.at {
            StopAt::Registration => self.seen.stops_during_start += 1,
            StopAt::Launch => self.seen.stops_between_launches += 1,
        }
        self.no_start_after_a_stop(&asked)?;
        self.stop(asked.docker_gone).await?;
        self.restart().await?;
        self.tick().await?;
        self.a_restart_takes_the_host_credit_back()
    }

    /// ADR 0126: once a stop is asked for, no runner launches and GitHub is asked to register none, not even for a
    /// start in flight that waited for its turn; one GitHub registered as the stop came does not start its container.
    /// The registrations answered before the stop may go on to Docker, and the stop removes their runners.
    fn no_start_after_a_stop(&self, asked: &AskedStop) -> Result<(), Violation> {
        let mut launched = self.engine.launches().after(asked.launched);
        // A stop asked for as a launch prepared its runner's caches came after that launch's checks: it is noted once
        // it ends, and its task registers nothing, which the check of the registrations below sees.
        if asked.at == StopAt::Launch && !launched.is_empty() {
            launched.remove(0);
        }
        if !launched.is_empty() {
            return violation(
                self,
                "no_start_after_a_stop",
                format!("{launched:?} launched after the stop"),
            );
        }
        let (calls, hooked) = {
            let github = self.github.0.lock().unwrap();
            (github.calls.clone(), github.hooked_registration.clone())
        };
        // At a registration, the stop came after the calls up to that registration's own.
        let from = match asked.at {
            StopAt::Registration => calls
                .iter()
                .position(|call| {
                    hooked
                        .as_ref()
                        .is_some_and(|name| *call == format!("register {name}"))
                })
                .map_or(calls.len(), |at| at + 1),
            StopAt::Launch => asked.calls.min(calls.len()),
        };
        let registered: Vec<&String> = calls[from..]
            .iter()
            .filter(|call| call.starts_with("register "))
            .collect();
        if !registered.is_empty() {
            return violation(
                self,
                "no_start_after_a_stop",
                format!("{registered:?} after the stop"),
            );
        }
        if let Some(name) = hooked.filter(|_| asked.at == StopAt::Registration)
            && self
                .docker
                .calls()
                .iter()
                .any(|call| *call == format!("start {name}"))
        {
            return violation(
                self,
                "no_start_after_a_stop",
                format!("{name}, registered as the stop came, started its container"),
            );
        }
        Ok(())
    }

    /// Makes the slice's sample stale as the next runner container starts, with the starts launched before it in
    /// flight.
    fn slice_sample_stalls_during_start(&mut self) {
        let (clock, launches, mid_batch) = (
            self.clock.clone(),
            self.engine.launches(),
            self.mid_batch.clone(),
        );
        self.docker.0.lock().unwrap().on_start = Some(Box::new(move |_| {
            clock.advance(Duration::from_secs(3 * api::SAMPLE_INTERVAL + 1));
            *mid_batch.lock().unwrap() = Some(MidBatch {
                reading: None,
                launched: launches.count(),
            });
        }));
    }

    /// Runs a tick until a start's container is made and held, gives its batch's other starts time to reach their
    /// own hold or their turn to register, and drops the engine there, as a daemon that goes does.
    async fn abort_mid_batch(&mut self) {
        let (github, docker) = (self.github.clone(), self.docker.clone());
        docker.hold_started();
        github.0.lock().unwrap().answered.send_replace(Some(1));
        // Holds a start's container, or a registration's answer, once every container start in flight is held and,
        // with no answer held, nothing registers: the first start may fail before Docker, another's registration may
        // fail.
        let all_held = async {
            loop {
                let (starts, in_docker) = {
                    let state = docker.0.lock().unwrap();
                    (state.starts_waiting, state.runner_starts)
                };
                let (answers, registering) = {
                    let state = github.0.lock().unwrap();
                    (state.waiting, state.registering)
                };
                if starts + answers > 0 && in_docker == starts && (answers > 0 || registering == 0)
                {
                    return answers > 0 && starts > 0;
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        };
        let both = tokio::select! {
            _ = self.engine.tick(Shutdown::No) => false,
            both = all_held => both,
        };
        if both {
            self.seen.aborts_mid_batch += 1;
        }
        github.0.lock().unwrap().answered.send_replace(None);
        docker.release_started();
    }

    /// ADR 0125, 0126: once a restart after an aborted batch has ticked, every registration of this machine has a
    /// container, and every build cache open is a runner's. Recovery holds its containers in slots, which
    /// `docker_runs_no_runner_the_engine_lost` checks.
    async fn a_restart_cleans_up_an_aborted_batch(&mut self) -> Result<(), Violation> {
        // The deletes a failed start sends in the background.
        self.settle_background().await;
        let containers: BTreeSet<String> = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .filter(|container| container.labels.contains_key("runnerd.job"))
            .map(|container| container.name.clone())
            .collect();
        let bare: Vec<String> = self
            .github
            .0
            .lock()
            .unwrap()
            .runners
            .iter()
            .filter(|runner| {
                !self.orphans.contains(&runner.id) && !containers.contains(&runner.name)
            })
            .map(|runner| runner.name.clone())
            .collect();
        if !bare.is_empty() {
            return violation(
                self,
                "a_restart_cleans_up_an_aborted_batch",
                format!("{bare:?} stay registered with no container"),
            );
        }
        self.no_build_cache_left_open_without_a_runner()
    }

    /// A build cache opens for a runner about to start and closes with it, or with its start that failed: one stays
    /// open only for a runner in a slot, or for one removed whose uploads wait for GitHub's word.
    fn no_build_cache_left_open_without_a_runner(&self) -> Result<(), Violation> {
        let held: BTreeSet<&str> = self
            .engine
            .occupied()
            .map(|(_, occupant)| occupant.runner_name.as_str())
            .collect();
        let ended = self.engine.ended_upload_runners();
        let open: Vec<String> = self
            .engine
            .build_cache_runners()
            .into_iter()
            .filter(|runner| !held.contains(runner.as_str()) && !ended.contains(runner))
            .collect();
        if open.is_empty() {
            Ok(())
        } else {
            violation(
                self,
                "no_build_cache_left_open_without_a_runner",
                format!("{open:?} are open with no runner"),
            )
        }
    }

    /// L4 of 4b's challenge: GitHub is never asked to register a name it has registered, and Docker never runs two
    /// runner containers of one name. The history's runners are keyed by name, so it keeps one row per name.
    fn runner_names_are_unique(&self) -> Result<(), Violation> {
        let reused = self.github.0.lock().unwrap().duplicate_names.clone();
        if !reused.is_empty() {
            return violation(
                self,
                "runner_names_are_unique",
                format!("GitHub was asked to register {reused:?} again"),
            );
        }
        let mut names = BTreeSet::new();
        let twice: Vec<String> = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .filter(|container| container.labels.contains_key("runnerd.job"))
            .filter(|container| !names.insert(container.name.clone()))
            .map(|container| container.name.clone())
            .collect();
        if twice.is_empty() {
            Ok(())
        } else {
            violation(
                self,
                "runner_names_are_unique",
                format!("Docker runs two containers named {twice:?}"),
            )
        }
    }

    /// A running job's runner and container go while GitHub goes on saying the job runs, and with `Listing::Stale`
    /// goes on listing it queued too.
    fn runner_goes(&mut self, pick: usize, listing: Listing) {
        let running = self.running();
        let Some((id, container)) = pick_from(&running, pick).cloned() else {
            return;
        };
        let ran = if self.unobserved(&container) || self.capture_unread(id, &container) {
            None
        } else {
            self.jobs[&id].taken_by.clone()
        };
        let job = self.jobs.get_mut(&id).unwrap();
        job.phase = Phase::Open { ran };
        let (name, labels) = (job.name, job.labels.clone());
        let mut docker = self.docker.0.lock().unwrap();
        let runner = docker
            .containers
            .iter()
            .find(|candidate| candidate.id == container)
            .map(|candidate| candidate.name.clone());
        docker
            .containers
            .retain(|candidate| candidate.id != container);
        drop(docker);
        let mut github = self.github.0.lock().unwrap();
        github
            .runners
            .retain(|registered| Some(&registered.name) != runner.as_ref());
        github.queued.retain(|queued| queued.id != id);
        if listing == Listing::Stale {
            github.queued.push(QueuedJob {
                id,
                run_id: id,
                name: name.to_owned(),
                labels,
                created_at: time::now_ms(),
                ..QueuedJob::default()
            });
            self.listed_after_runner.insert(id);
        }
        self.still_listed.remove(&id);
        drop(github);
        self.took_job.remove(&container);
        // Its runner ran a job, which proves its pool works, as `end_job`'s does.
        if let Some((slot, occupant)) = self
            .engine
            .occupied()
            .find(|(_, occupant)| occupant.container == container)
        {
            let repository = occupant.repository.clone();
            self.ended_between
                .push((container, repository, slot.profile));
        }
    }

    /// The jobs whose runner went and that GitHub has not said ended.
    fn open(&self) -> Vec<u64> {
        self.jobs
            .iter()
            .filter(|(_, job)| matches!(job.phase, Phase::Open { .. }))
            .map(|(id, _)| *id)
            .collect()
    }

    fn open_job_completes(&mut self, pick: usize) {
        let open = self.open();
        let Some(id) = pick_from(&open, pick).copied() else {
            return;
        };
        let job = self.jobs.get_mut(&id).unwrap();
        let Phase::Open { ran } = job.phase.clone() else {
            return;
        };
        job.phase = Phase::Done { ran };
        let name = job.name;
        let mut github = self.github.0.lock().unwrap();
        let runner = github.jobs.get(&id).and_then(|job| job.runner_name.clone());
        let mut completed = details(id, "completed", Some("success"));
        completed.run_id = id;
        completed.name = name.to_owned();
        completed.runner_name = runner;
        github.jobs.insert(id, completed);
        github.queued.retain(|job| job.id != id);
        drop(github);
        self.listed_after_runner.remove(&id);
    }

    async fn forced_pause(&mut self, second: bool) {
        let repository = if second { "o/s" } else { "o/r" };
        let running = self.running();
        self.forced.extend(
            running
                .into_iter()
                .filter(|(id, _)| self.jobs[id].repository == repository)
                .map(|(_, container)| container),
        );
        let (reply, answer) = tokio::sync::oneshot::channel();
        self.engine
            .command(Command::Pause {
                target: Target::Repository(repository.to_owned()),
                jobs: RunningJobs::Kill,
                reply,
            })
            .await;
        // Refused for a repository a reload removed.
        let _ = answer.await;
    }

    async fn resume(&mut self, second: bool) {
        let repository = if second { "o/s" } else { "o/r" };
        let (reply, answer) = tokio::sync::oneshot::channel();
        self.engine
            .command(Command::Resume {
                target: Target::Repository(repository.to_owned()),
                reply,
            })
            .await;
        let _ = answer.await;
    }

    /// The jobs of containers a forced pause's kill removed are over.
    fn forced_jobs_end(&mut self) {
        let gone: Vec<(u64, String)> = {
            let docker = self.docker.0.lock().unwrap();
            self.running()
                .into_iter()
                .filter(|(_, container)| {
                    self.forced.contains(container)
                        && !docker.containers.iter().any(|c| c.id == *container)
                })
                .collect()
        };
        for (id, container) in gone {
            self.end_job(id, &container, "cancelled");
            self.jobs.get_mut(&id).unwrap().phase = Phase::Done { ran: None };
        }
    }

    fn busy_orphan(&mut self) {
        let name = format!(
            "{}orphan-{}",
            self.engine.runner_prefix(),
            self.orphans.len()
        );
        let mut github = self.github.0.lock().unwrap();
        github.registrations += 1;
        let id = 1000 + github.registrations;
        github.runners.push(Runner {
            id,
            name,
            status: "online".to_owned(),
            busy: true,
        });
        drop(github);
        self.orphans.push(id);
    }

    /// The heavy profile's snapshot is too large, which a check of the caches finds once no runner runs.
    fn oversized_snapshot(&mut self) {
        let volume = Names::new("runnerd").base("heavy");
        self.docker
            .0
            .lock()
            .unwrap()
            .volume_sizes
            .insert(volume, u64::MAX / 2);
        self.engine.make_trim_due();
    }

    /// A running job saves to the build cache while GitHub says it is queued on no runner.
    async fn save_unnamed(&mut self, pick: usize) {
        let running = self.running();
        let Some((id, container)) = pick_from(&running, pick).cloned() else {
            return;
        };
        let name = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .find(|candidate| candidate.id == container)
            .map(|candidate| candidate.name.clone());
        let Some(socket) = name.and_then(|name| build_cache::socket_of(&self.docker, &name)) else {
            return;
        };
        if let Some(details) = self.github.0.lock().unwrap().jobs.get_mut(&id) {
            details.status = "queued".to_owned();
            if let Some(runner) = details.runner_name.take() {
                self.unnamed_saves.insert(id, runner);
            }
        }
        build_cache::save(&socket).await;
    }

    fn runner_named(&mut self, pick: usize) {
        let unnamed: Vec<u64> = self.unnamed_saves.keys().copied().collect();
        let Some(id) = pick_from(&unnamed, pick).copied() else {
            return;
        };
        let runner = self.unnamed_saves.remove(&id);
        let mut github = self.github.0.lock().unwrap();
        if let Some(details) = github.jobs.get_mut(&id) {
            details.runner_name = runner;
        }
        github
            .triggers
            .insert(id, build_cache::trigger("push", "main"));
    }

    /// GitHub fails the reads of a queued job, or of one no runner of this machine runs any more.
    fn job_read_fails(&mut self, pick: usize, how: ReadFailure) {
        let candidates: Vec<u64> = self
            .jobs
            .iter()
            .filter(|(_, job)| !matches!(job.phase, Phase::Running { .. }))
            .map(|(id, _)| *id)
            .collect();
        let Some(id) = pick_from(&candidates, pick).copied() else {
            return;
        };
        let mut github = self.github.0.lock().unwrap();
        match how {
            ReadFailure::Gone => drop(github.gone_jobs.insert(id)),
            ReadFailure::Limited => drop(
                github
                    .limited_jobs
                    .insert(id, SystemTime::now() + Duration::from_secs(3600)),
            ),
            ReadFailure::Other => drop(github.failed_jobs.insert(id)),
        }
    }

    /// A running job's container vanishes, as when someone removes it.
    fn lose(&mut self, pick: usize) {
        if let Some(container) = self.end_running(pick) {
            self.docker
                .0
                .lock()
                .unwrap()
                .containers
                .retain(|candidate| candidate.id != container);
        }
    }

    /// Someone starts removing a running job's container.
    fn removing(&mut self, pick: usize) {
        if let Some(container) = self.end_running(pick) {
            let mut docker = self.docker.0.lock().unwrap();
            set_running(&mut docker, &container, false);
            docker.being_removed.insert(container);
        }
    }

    /// Docker finishes the removals someone began.
    fn removals_finish(&mut self) {
        let mut docker = self.docker.0.lock().unwrap();
        let removed = std::mem::take(&mut docker.being_removed);
        docker
            .containers
            .retain(|candidate| !removed.contains(&candidate.id));
    }

    /// Ends a running job whose container goes without a word from it, and says which container that is.
    fn end_running(&mut self, pick: usize) -> Option<String> {
        let running = self.running();
        let (id, container) = pick_from(&running, pick).cloned()?;
        self.end_job(id, &container, "failure");
        // Gone before Docker answered any inspect of it: nothing read its log, so nothing can name
        // the runner that ran the job.
        if (self.unobserved(&container) || self.capture_unread(id, &container))
            && let Some(job) = self.jobs.get_mut(&id)
        {
            job.phase = Phase::Done { ran: None };
        }
        Some(container)
    }

    fn inspect_fails(&mut self, pick: usize) {
        let containers = self.running_containers();
        if let Some(container) = pick_from(&containers, pick) {
            *self
                .docker
                .0
                .lock()
                .unwrap()
                .fail_inspects
                .entry(container.id.clone())
                .or_default() += 1;
        }
    }

    /// GitHub gives a queued job to an idle runner of its repository whose labels it matches.
    async fn assign(&mut self, pick: usize, listing: Listing) {
        let idle = self.idle_containers();
        let registered: BTreeSet<String> = self
            .github
            .0
            .lock()
            .unwrap()
            .runners
            .iter()
            .map(|runner| runner.name.clone())
            .collect();
        let candidates: Vec<(u64, Container)> = self
            .queued()
            .into_iter()
            .flat_map(|id| {
                let job = &self.jobs[&id];
                idle.iter()
                    .filter(|container| {
                        let label =
                            |name: &str| container.labels.get(name).cloned().unwrap_or_default();
                        let labels: Vec<String> = label("runnerd.labels")
                            .split(',')
                            .map(str::to_owned)
                            .collect();
                        registered.contains(&container.name)
                            && label("runnerd.repository") == job.repository
                            && !job.labels.is_empty()
                            && job.labels.iter().all(|wanted| {
                                labels.iter().any(|has| has.eq_ignore_ascii_case(wanted))
                            })
                    })
                    .map(move |container| (id, container.clone()))
                    .collect::<Vec<_>>()
            })
            .collect();
        let Some((id, container)) = pick_from(&candidates, pick).cloned() else {
            return;
        };
        let profile = container.labels["runnerd.profile"].clone();
        let repository = container.labels["runnerd.repository"].clone();
        {
            let mut github = self.github.0.lock().unwrap();
            if listing == Listing::Stale {
                self.still_listed.insert(id, None);
            } else {
                github.queued.retain(|job| job.id != id);
            }
            let mut runner_id = None;
            for runner in &mut github.runners {
                if runner.name == container.name {
                    runner.busy = true;
                    runner_id = Some(runner.id);
                }
            }
            let mut running = details(id, "in_progress", None);
            running.run_id = id;
            running.name = self.jobs[&id].name.to_owned();
            running.runner_name = Some(container.name.clone());
            running.labels = self.jobs[&id].labels.clone();
            github.jobs.insert(id, running);
            // GitHub answers for the job a runner took.
            github.gone_jobs.remove(&id);
            github.limited_jobs.remove(&id);
            github.failed_jobs.remove(&id);
            assert!(runner_id.is_some(), "an assigned runner is registered");
        }
        {
            let mut docker = self.docker.0.lock().unwrap();
            docker
                .container_captures
                .insert(container.id.clone(), format!("@@job {id} {id}\n"));
            docker
                .diag
                .insert(container.id.clone(), docker::tests::diag_archive(id));
        }
        self.took_job.insert(container.id.clone());
        let job = self.jobs.get_mut(&id).unwrap();
        job.phase = Phase::Running {
            container: container.id.clone(),
        };
        job.taken_by = Some((profile, repository));
        // Lets its capture report the job, as it does within moments of the runner taking it.
        for _ in 0..100 {
            self.handle.store.flush().await;
            if self
                .handle
                .store
                .job(id)
                .await
                .unwrap()
                .is_some_and(|job| job.summary.runner.is_some())
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(2)).await;
        }
    }

    /// GitHub completes a running job, and its ephemeral runner leaves. Its stopped container's log still names the
    /// job, as Docker keeps it until the container is removed; the engine names a slot's later runners otherwise, so
    /// none takes its log.
    ///
    /// It also leaves GitHub's queued listing, even if `AssignListed` left it there: the harness assumes a stale
    /// listing never outlives its job. Where it does, as for a runner killed during its job's setup within GitHub's
    /// few seconds of lag, the engine no longer counts the job as taken once its runner exits, and starts a second
    /// runner for it, which waits out `IDLE_TIMEOUT`: one idle runner, rare enough to leave.
    fn end_job(&mut self, id: u64, container: &str, conclusion: &str) {
        let job = self.jobs.get_mut(&id).unwrap();
        job.phase = Phase::Done {
            ran: job.taken_by.clone(),
        };
        let by_container = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .find(|candidate| candidate.id == container)
            .map(|candidate| candidate.name.clone());
        let mut github = self.github.0.lock().unwrap();
        let name = github
            .jobs
            .get(&id)
            .and_then(|details| details.runner_name.clone())
            .or(by_container);
        let mut completed = details(id, "completed", Some(conclusion));
        completed.run_id = id;
        completed.name = job.name.to_owned();
        completed.runner_name = name.clone();
        github.jobs.insert(id, completed);
        // GitHub lists a job queued a few seconds after a runner took it, never once it completed.
        github.queued.retain(|job| job.id != id);
        self.still_listed.remove(&id);
        github
            .runners
            .retain(|runner| Some(&runner.name) != name.as_ref());
        drop(github);
        self.took_job.remove(container);
        if let Some((slot, occupant)) = self
            .engine
            .occupied()
            .find(|(_, occupant)| occupant.container == container)
        {
            let repository = occupant.repository.clone();
            self.ended_between
                .push((container.to_owned(), repository, slot.profile));
        }
    }

    /// An idle runner's container exits without a job: at once, after `IDLE_TIMEOUT`, or having connected.
    fn exit_idle(&mut self, pick: usize, exit: Exit) {
        let idle = self.idle_containers();
        let Some(container) = pick_from(&idle, pick).cloned() else {
            return;
        };
        if exit == Exit::AfterIdleTimeout {
            for occupant in self.engine.occupants_mut() {
                if occupant.container == container.id {
                    occupant.started_at -= IDLE_TIMEOUT;
                }
            }
        }
        let watch = self
            .engine
            .occupied()
            .find(|(_, occupant)| occupant.container == container.id)
            .map(|(slot, occupant)| ExitWatch {
                container: container.id.clone(),
                repository: occupant.repository.clone(),
                profile: slot.profile,
                // `Elapse` aged it: the engine reads that as having waited, and so as having connected.
                exit: match occupant.started_at.elapsed() {
                    Ok(waited) if exit == Exit::AtOnce && waited >= IDLE_TIMEOUT => {
                        Exit::AfterIdleTimeout
                    }
                    _ => exit,
                },
                quiet_before: false,
            });
        self.exits.extend(watch.map(|watch| ExitWatch {
            quiet_before: self.pool_is_quiet(&watch.repository, &watch.profile),
            ..watch
        }));
        let log = match exit {
            Exit::Connected => "Listening for Jobs\n",
            Exit::AtOnce | Exit::AfterIdleTimeout => "",
        };
        let mut docker = self.docker.0.lock().unwrap();
        docker
            .container_logs
            .insert(container.id.clone(), log.to_owned());
        set_running(&mut docker, &container.id, false);
    }

    /// Notes the busy runners, as a tick or a pass begins.
    fn note_busy(&mut self) {
        self.busy_before = self
            .engine
            .occupied()
            .filter(|(_, occupant)| {
                occupant.listed_busy()
                    || occupant.named_job().is_some()
                    || self.took_job.contains(&occupant.container)
            })
            .map(|(slot, occupant)| {
                let repository = occupant.repository.clone();
                (occupant.container.clone(), repository, slot.profile)
            })
            .collect();
        self.busy_before.append(&mut self.ended_between);
    }

    /// Whether a pool is neither held now nor in a streak of runners that left without a job.
    fn pool_is_quiet(&self, repository: &str, profile: &str) -> bool {
        self.engine
            .pool_is_quiet(repository, profile, SystemTime::now())
    }

    /// Invariant 8 (ADR 0104), as a tick or a pass frees slots: a pool whose runner exited without connecting is held
    /// back, so a pool whose runners keep failing to start backs off, and a runner that connected and left a quiet
    /// pool brings no hold, as it says nothing of the next start. Another runner of the pool failing in the meantime
    /// is a hold of its own, so that pool proves nothing.
    fn exits_hold_only_what_failed_to_start(&mut self) -> Result<(), Violation> {
        let in_slots: BTreeSet<String> = self
            .engine
            .occupied()
            .map(|(_, occupant)| occupant.container.clone())
            .collect();
        let (waiting, freed): (Vec<ExitWatch>, Vec<ExitWatch>) = std::mem::take(&mut self.exits)
            .into_iter()
            .partition(|watch| in_slots.contains(&watch.container));
        self.exits = waiting;
        let now = SystemTime::now();
        for watch in &freed {
            let Some(hold) = self.engine.pool_hold(&watch.repository, &watch.profile) else {
                continue;
            };
            let standing = hold.held.filter(|held| held.until > now);
            let job_ended = self
                .busy_before
                .iter()
                .any(|(container, repository, profile)| {
                    !in_slots.contains(container)
                        && *repository == watch.repository
                        && *profile == watch.profile
                });
            match watch.exit {
                Exit::AtOnce if standing.is_none() && !job_ended => {
                    let detail = format!("{watch:?} failed to start and {hold:?} holds nothing");
                    return violation(self, "exits_hold_only_what_failed_to_start", detail);
                }
                Exit::Connected if watch.quiet_before && standing.is_some() => {
                    let failed = freed.iter().any(|other| {
                        other.exit == Exit::AtOnce
                            && other.repository == watch.repository
                            && other.profile == watch.profile
                    });
                    let cause = standing.map(|held| held.cause);
                    if !failed && matches!(cause, Some(HoldCause::NoJob | HoldCause::IdleExits)) {
                        let detail = format!("{watch:?} connected and {hold:?} holds its pool");
                        return violation(self, "exits_hold_only_what_failed_to_start", detail);
                    }
                }
                _ => {}
            }
            self.seen.exits_freed += 1;
        }
        Ok(())
    }

    /// Takes a `sample` while the next runner starts.
    fn sample_during_start(&mut self, percent: u64, available: u64, stalled: bool) {
        let (store, took_job, mid_batch, clock, launches) = (
            self.handle.store.clone(),
            self.took_job.clone(),
            self.mid_batch.clone(),
            self.clock.clone(),
            self.engine.launches(),
        );
        self.docker.0.lock().unwrap().on_start = Some(Box::new(move |docker| {
            let now = clock.now_ms();
            let reading = sample(docker, &store, &took_job, now, percent, available, stalled);
            *mid_batch.lock().unwrap() = Some(MidBatch {
                reading: Some(reading),
                launched: launches.count(),
            });
        }));
    }

    /// Whether the engine has not watched `container` yet, as Docker failed every inspect of it.
    fn unobserved(&self, container: &str) -> bool {
        self.engine.occupied().any(|(_, occupant)| {
            occupant.container == container
                && !self.engine.watches.is_watched(&occupant.runner_name)
        })
    }

    /// Whether job `id`, running in `container`, may end without the engine ever reading its log: its log capture
    /// failed and no tick has started it again since, or it failed twice, after which the next start waits longer
    /// than a sequence runs. Not once GitHub named its runner to the engine (`named_by_github`).
    fn capture_unread(&self, id: u64, container: &str) -> bool {
        let faults = self.capture_faults_of(container);
        let retried = self.capture_faults.get(container).copied().unwrap_or(0);
        !self.jobs[&id].named_by_github && (faults >= 2 || faults > retried)
    }

    /// How many log captures in `container` failed so far.
    fn capture_faults_of(&self, container: &str) -> u32 {
        self.docker
            .0
            .lock()
            .unwrap()
            .capture_faults
            .get(container)
            .copied()
            .unwrap_or(0)
    }

    async fn reload(&mut self, change: Change) -> Result<(), Violation> {
        let mut shape = self.shape;
        match change {
            Change::HeavySlots(slots) => shape.heavy_slots = slots,
            Change::LightSlots(slots) => {
                if shape.light_slots.is_some() {
                    shape.light_slots = Some(slots);
                }
            }
            Change::LightPool => shape.light_pool = !shape.light_pool,
            Change::SecondRepository => shape.second_repository = !shape.second_repository,
            Change::LightProfile => {
                shape.light_slots = match shape.light_slots {
                    Some(_) => None,
                    None => Some(2),
                };
            }
            Change::Policy => {
                shape.admission = match shape.admission {
                    Admission::Caps => Admission::Measured,
                    Admission::Measured => Admission::Caps,
                };
            }
            Change::CpuOvercommit => shape.cpu_overcommit = !shape.cpu_overcommit,
            Change::PooledCount => shape.pooled_count = !shape.pooled_count,
            // Down and back: a restart whose inspect fails must still count a runner at the cap it started with.
            Change::HeavyMemory => shape.heavy_memory = if shape.heavy_memory == 4 { 2 } else { 4 },
            Change::Mirror => shape.mirror = !shape.mirror,
            Change::RecordFailures => shape.record_failures = !shape.record_failures,
        }
        let (reply, answer) = tokio::sync::oneshot::channel();
        self.engine
            .command(Command::ReplaceConfig {
                config: Box::new(Config::parse(&shape.toml()).unwrap()),
                memory_max: Some(MEMORY_MAX),
                cpus: Some(SLICE_CPUS),
                commit: Commit::new(|| Ok(None)),
                running: RunningSlots::Drain,
                author: Author::Owner,
                reply,
            })
            .await;
        let applied = answer.await;
        if applied != Ok(Ok(Vec::new())) {
            return violation(
                self,
                "a_reload_applies",
                format!("{change:?} answered {applied:?}"),
            );
        }
        self.shape = shape;
        Ok(())
    }

    /// Invariant 7: a stop on a signal, or one Docker fails, ends at once and leaves every container that runs a job
    /// running, for the next start.
    async fn stop(&mut self, docker_gone: bool) -> Result<(), Violation> {
        let running = self.running();
        let mode = if docker_gone {
            self.docker.set_outage(Outage::Refused);
            Shutdown::Graceful
        } else {
            Shutdown::Detach
        };
        // Asked for already by a `StopDuringStart`, which this asks for again.
        self.handle.control.shutdown(mode);
        // Far past what a stop takes, so only a stop that hangs fails it, however slow the machine.
        let stopped = tokio::time::timeout(Duration::from_secs(300), self.engine.schedule()).await;
        self.docker.set_outage(Outage::None);
        if stopped.is_err() {
            return violation(self, "a_stop_ends", format!("{mode:?} never ended"));
        }
        let left: BTreeSet<String> = self
            .running_containers()
            .into_iter()
            .map(|container| container.id)
            .collect();
        let gone: Vec<&(u64, String)> = running
            .iter()
            .filter(|(_, container)| !left.contains(container))
            .collect();
        if !gone.is_empty() {
            let detail = format!("{mode:?} took the containers of running jobs {gone:?}");
            return violation(self, "a_stop_leaves_running_jobs", detail);
        }
        if mode == Shutdown::Detach {
            self.a_detach_deregisters_idle_runners()?;
        }
        Ok(())
    }

    /// ADR 0091: a detaching stop leaves no runner that took no job registered, adopted ones too, even before a
    /// listing said they were idle: one left would take a job with no daemon to watch it.
    fn a_detach_deregisters_idle_runners(&self) -> Result<(), Violation> {
        // While GitHub refuses every request for its used-up rate limit, no deregistration gets through: the runners
        // left keep their containers, which the next start adopts or removes (ADR 0076).
        let blocked = self.github.0.lock().unwrap().blocked_until;
        if blocked.is_some_and(|until| until > SystemTime::now()) {
            return Ok(());
        }
        let registered: BTreeSet<String> = self
            .github
            .0
            .lock()
            .unwrap()
            .runners
            .iter()
            .map(|runner| runner.name.clone())
            .collect();
        let idle: Vec<String> = self
            .idle_containers()
            .into_iter()
            .map(|container| container.name)
            .filter(|name| registered.contains(name))
            .collect();
        if idle.is_empty() {
            return Ok(());
        }
        violation(
            self,
            "a_detach_deregisters_idle_runners",
            format!("{idle:?} stay registered with no job"),
        )
    }

    async fn restart(&mut self) -> Result<(), Violation> {
        self.engine.abort_captures();
        self.handle.store.flush().await;
        let (engine, handle) = Case::engine(
            &self.github,
            &self.docker,
            &self.dir,
            self.shape,
            self.clock.clone(),
        );
        self.engine = engine;
        self.engine.named = self.names_from;
        self.handle = handle;
        // The store keeps the host's reading in memory only, and a sample still to come goes to the old store.
        self.host = None;
        self.exits.clear();
        {
            let mut docker = self.docker.0.lock().unwrap();
            docker.on_start = None;
            docker.on_prepare = None;
        }
        // A stop asked for of the engine gone would never be carried out, nor one it was asked already.
        self.github.0.lock().unwrap().on_register = None;
        let asked = self.stop_during_start.lock().unwrap().take();
        // Docker comes back for the next start, as `stop` brings it back.
        if asked.is_some_and(|asked| asked.docker_gone) {
            self.docker.set_outage(Outage::None);
        }
        // A new daemon's client knows nothing of the rate limit the old one met.
        self.github.unblock();
        self.recover().await
    }

    fn elapse(&mut self) {
        // The sampler stopped: the last readings are older than admission goes by.
        let old = self.clock.now_ms() - 1000 * (3 * api::SAMPLE_INTERVAL + 1);
        let docker = self.docker.0.lock().unwrap();
        let reading = sample(
            &docker,
            &self.handle.store,
            &self.took_job,
            old,
            50,
            50,
            false,
        );
        drop(docker);
        self.host = Some(reading);
        for occupant in self.engine.occupants_mut() {
            occupant.started_at -= IDLE_TIMEOUT;
        }
        for watch in &mut self.exits {
            if watch.exit == Exit::AtOnce {
                watch.exit = Exit::AfterIdleTimeout;
            }
        }
        let past = SystemTime::now() - Duration::from_secs(1);
        self.engine.expire_holds(past);
        self.engine.expire_github_limit(past);
        self.github.unblock();
        self.engine.age_waits(PRIORITY_AFTER);
        self.engine.expire_cancelling();
        self.engine.make_unread_due();
        self.engine
            .age_ended_uploads(crate::scheduler::engine::build_cache::ENDED_WAIT);
        self.engine
            .age_followed_jobs(crate::scheduler::engine::history::LOST_AFTER);
    }

    fn settle(&mut self) {
        for occupant in self.engine.occupants_mut() {
            occupant.age_job_start(POOL_AFTER);
            if let Some(admission) = occupant.admission.as_mut() {
                admission.basis = Basis::Job {
                    runs: 10,
                    peak: JobPeak::P95,
                };
            }
        }
    }

    /// Ten finished runs of each repository's job in a profile, peaking as given, with IDs no generated job takes.
    async fn past_runs(&mut self, runs: &[(&str, &str, &str, u64)]) {
        let at = time::now_ms() - 3600 * 1000;
        let store = &self.handle.store;
        for (first, (repository, name, profile, peak)) in (1_u64..).map(|n| n * 1_000_000).zip(runs)
        {
            for id in first..first + 10 {
                let runner = format!("earlier-{id}");
                store.queued(
                    repository,
                    &QueuedJob {
                        id,
                        run_id: id,
                        name: (*name).to_owned(),
                        created_at: at,
                        ..QueuedJob::default()
                    },
                    at,
                );
                store.runner_started(RunnerRecord {
                    purpose: None,
                    name: runner.clone(),
                    repository: (*repository).to_owned(),
                    profile: (*profile).to_owned(),
                    slot: 1,
                    container: format!("c-{id}"),
                    started_at: at,
                    memory_cap: Some(if *profile == "heavy" { 4 * G } else { G }),
                    cpu_cap: Some(2000),
                    admission: None,
                });
                store.claimed(id, id, &runner, at + 1000);
                store.samples(vec![SampleRecord {
                    runner: runner.clone(),
                    at: at + 2000,
                    cpu: 0,
                    cpu_usage: 0,
                    memory: *peak,
                    network_received: 0,
                    network_sent: 0,
                    cpu_held: crate::observe::metrics::CpuHeld::default(),
                    events: Events::default(),
                }]);
                let mut ran = details(id, "completed", Some("success"));
                ran.run_id = id;
                ran.name = (*name).to_owned();
                ran.runner_name = Some(runner.clone());
                ran.steps = Vec::new();
                store.details(ran);
                store.runner_removed(&runner, at + 60_000);
            }
        }
        store.flush().await;
        self.engine.forget_predictor();
    }

    /// A runner whose registration GitHub deleted exits, as a JIT runner does.
    fn unregistered_runners_exit(&mut self) {
        let registered: BTreeSet<String> = self
            .github
            .0
            .lock()
            .unwrap()
            .runners
            .iter()
            .map(|runner| runner.name.clone())
            .collect();
        let mut docker = self.docker.0.lock().unwrap();
        for container in &mut docker.containers {
            if container.running
                && container.labels.contains_key("runnerd.job")
                && !registered.contains(&container.name)
            {
                container.running = false;
            }
        }
    }

    /// What GitHub knows of the runners whose start failed after Docker made their container: a job one took runs
    /// on in its container if the start left it, and fails once GitHub notices its runner gone otherwise.
    fn failed_late(&mut self) {
        let failed = std::mem::take(&mut self.docker.0.lock().unwrap().late_started);
        for (container, job) in failed {
            let Some(id) = job else { continue };
            let left = self
                .running_containers()
                .into_iter()
                .find(|candidate| candidate.id == container);
            if let Some(left) = left {
                let label = |name: &str| left.labels.get(name).cloned().unwrap_or_default();
                self.took_job.insert(container.clone());
                let job = self.jobs.get_mut(&id).unwrap();
                job.phase = Phase::Running { container };
                job.taken_by = Some((label("runnerd.profile"), label("runnerd.repository")));
            } else {
                self.jobs.get_mut(&id).unwrap().taken_by = None;
                self.end_job(id, &container, "failure");
            }
        }
    }

    /// A tick `POLL_INTERVAL` after the last, when every repository is due.
    async fn tick(&mut self) -> Result<(), Violation> {
        self.tick_as(Comes::Due).await
    }

    /// A tick, as `comes` says, and the checks after it.
    async fn tick_as(&mut self, comes: Comes) -> Result<(), Violation> {
        let (by, scope) = match comes {
            Comes::Due => (POLL_INTERVAL, Scope::Due),
            Comes::Soon(after) => (after, Scope::Due),
            Comes::Command => (TICK_EVERY, Scope::Every),
        };
        self.model += by;
        self.between_ticks().await;
        self.github_lag_ends();
        self.unregistered_runners_exit();
        let was_short = self.engine.host_is_short();
        let calls_before = self.docker.0.lock().unwrap().calls.len();
        let github_before = self.github.calls().len();
        // The listings that fail from here on, in the same window as the calls: one an aborted tick left belongs to no
        // tick, as the restart after it forgets every listing and lists every repository again.
        self.github.0.lock().unwrap().queued_failures.clear();
        let seeds_before: BTreeSet<String> = self.engine.seed_memories().into_keys().collect();
        self.capture_faults = self.docker.0.lock().unwrap().capture_faults.clone();
        let queued_before: BTreeSet<u64> = self.queued().into_iter().collect();
        self.note_busy();
        let uploads_waiting = self.engine.ended_uploads_waiting();
        // Ticks come every 5 s or more, a third of `poll_interval`, or sooner: the running jobs are read at every
        // third that far apart (ADR 0124).
        self.engine.age_running_reads(by.min(TICK_EVERY));
        self.engine.age_listings(by);
        self.engine.tick_listing(Shutdown::No, scope).await;
        self.note_listings(github_before, &queued_before);
        let ended = self.engine.ended_upload_runners();
        self.seen.decided_uploads += uploads_waiting
            .iter()
            .filter(|runner| !ended.contains(*runner))
            .count();
        self.removals_finish();
        self.failed_late();
        self.exits_hold_only_what_failed_to_start()?;
        let after = self.status();
        // From Docker's starts, not the runners' names: a slot's next runner may take the name of one that stopped
        // this second.
        let running: BTreeSet<String> = self
            .running_containers()
            .into_iter()
            .map(|container| container.name)
            .collect();
        let starts: Vec<String> = self.docker.0.lock().unwrap().calls[calls_before..]
            .iter()
            .filter_map(|call| call.strip_prefix("start "))
            .filter(|name| running.contains(*name))
            .map(str::to_owned)
            .collect();
        self.note_slow_start(starts.len());
        let mut started: BTreeSet<String> = starts.iter().cloned().collect();
        self.no_pool_gets_more_runners_than_its_queued_jobs(&after, &started)?;
        let seeds = self
            .engine
            .seed_memories()
            .keys()
            .filter(|profile| !seeds_before.contains(*profile))
            .map(|profile| format!("{profile}{SEED_START}"))
            .collect::<Vec<_>>();
        self.no_slot_is_left_starting()?;
        self.runner_names_are_unique()?;
        self.no_build_cache_left_open_without_a_runner()?;
        let read_during_start = self.starts_after_a_reading(&starts);
        let same_reading = read_during_start.is_none();
        let seeded = !seeds.is_empty();
        if let Some(after) = read_during_start {
            started = after;
        }
        started.extend(seeds);
        self.starts_fit_the_budget(&after, &started)?;
        self.docker_runs_no_runner_the_engine_lost(&after)?;
        self.no_watch_outlives_its_runner()?;
        // A stop asked for during the tick plans no more, and so says no more which jobs no pool serves.
        if !after.shutting_down {
            self.only_unserved_jobs_wait_for_a_pool(&after)?;
        }
        self.one_barrier_and_only_for_a_queued_job(&after)?;
        self.no_job_waits_for_a_slot_or_the_host_past_its_runners_start(&after)?;
        self.the_count_keeps_its_bounds(&after)?;
        self.a_runner_started_finds_the_mirror_up(&starts)?;
        if same_reading {
            self.the_band_follows_the_waiters(was_short, seeded)?;
        }
        self.note_states();
        self.no_removal_of_a_running_job()
    }

    /// GitHub stops listing queued the jobs whose runners took them `POLL_INTERVAL` after the first runners listing
    /// of their repository since, before the tick at the model's time now lists.
    fn github_lag_ends(&mut self) {
        let model = self.model;
        let ended: BTreeSet<u64> = self
            .still_listed
            .iter()
            .filter(|(_, seen)| seen.is_some_and(|seen| model >= seen + POLL_INTERVAL))
            .map(|(id, _)| *id)
            .collect();
        self.still_listed.retain(|id, _| !ended.contains(id));
        self.github
            .0
            .lock()
            .unwrap()
            .queued
            .retain(|job| !ended.contains(&job.id));
    }

    /// What the tick's listings, the GitHub calls from `github_before`, showed: each job of `queued_before` is shown, and one a pool
    /// serves is listed, once its repository's queued jobs were; a running one listed before that its repository's
    /// listing no longer shows is named by GitHub; a runners listing of a repository starts GitHub's lag for the jobs
    /// of it that its runners took and it still lists; a repository listed no longer shows the jobs cancelled since
    /// its last listing; and one whose listing failed shows none of its queued jobs until a listing of it answers.
    fn note_listings(&mut self, github_before: usize, queued_before: &BTreeSet<u64>) {
        let calls = self.github.calls();
        let failed: BTreeSet<String> =
            std::mem::take(&mut self.github.0.lock().unwrap().queued_failures)
                .into_iter()
                .collect();
        let listed: BTreeSet<&str> = calls[github_before..]
            .iter()
            .filter_map(|call| call.strip_prefix("queued "))
            .filter(|repository| !failed.contains(*repository))
            .collect();
        let runners_listed: BTreeSet<&str> = calls[github_before..]
            .iter()
            .filter_map(|call| call.strip_prefix("runners "))
            .collect();
        let unlisted_stale = self
            .still_listed
            .iter()
            .any(|(id, seen)| seen.is_some() && !listed.contains(self.jobs[id].repository));
        if !listed.is_empty() && unlisted_stale {
            self.seen.beside_still_listed += 1;
        }
        if listed.len() == 1 {
            self.seen.one_due += 1;
        }
        for (id, seen) in &mut self.still_listed {
            if runners_listed.contains(self.jobs[id].repository) {
                seen.get_or_insert(self.model);
            }
        }
        for (id, job) in &mut self.jobs {
            if failed.contains(job.repository) && job.phase == Phase::Queued {
                job.shown = false;
            }
            if !listed.contains(job.repository) {
                continue;
            }
            match job.phase {
                Phase::Queued if queued_before.contains(id) => {
                    job.shown = true;
                    job.listed |= self.shape.serves(job.repository, &job.labels).is_some();
                }
                Phase::Running { .. } if job.listed && !self.still_listed.contains_key(id) => {
                    job.named_by_github = true;
                }
                _ => {}
            }
        }
        self.cancelled_since_listed
            .retain(|repository, _| !listed.contains(repository));
    }

    /// ADR 0125: a start in flight lives only inside its batch, which a tick or a pass ends before it returns.
    fn no_slot_is_left_starting(&self) -> Result<(), Violation> {
        if self.engine.any_starting() {
            return violation(
                self,
                "no_slot_is_left_starting",
                "a slot is still starting".to_owned(),
            );
        }
        Ok(())
    }

    /// Counts a slow start among `starts` runners started by one tick or pass.
    fn note_slow_start(&mut self, starts: usize) {
        let slow = std::mem::take(&mut self.docker.0.lock().unwrap().slow_started);
        if slow > 0 && starts > 1 {
            self.seen.slow_starts += 1;
        }
    }

    /// Counts the states the checks exist for, as a tick or a pass leaves them.
    fn note_states(&mut self) {
        let counts = self.engine.state_counts();
        let seen = &mut self.seen;
        seen.closing += counts.closing;
        seen.ended_uploads += counts.ended_uploads;
        seen.cancelling += counts.cancelling;
        seen.busy_orphans += counts.busy_orphans;
        seen.oversized += counts.oversized;
        seen.unread += counts.unread;
        seen.split_waits += counts.split_waits;
        seen.captures_with_recaptures += counts.captures_with_recaptures;
        seen.mirrors += usize::from(
            self.docker
                .0
                .lock()
                .unwrap()
                .containers
                .iter()
                .any(|container| {
                    container.running && container.labels.contains_key("runnerd.mirror")
                }),
        );
    }

    /// The starts a reading taken, or a sample gone stale, while a runner started binds, if one did: those the engine
    /// launched after it that run now. The starts launched before it went by what their plan had, though their
    /// registration or Docker's start came later. Seed containers start after the batch and are added by the caller.
    fn starts_after_a_reading(&mut self, starts: &[String]) -> Option<BTreeSet<String>> {
        let mid_batch = self.mid_batch.lock().unwrap().take()?;
        self.docker.0.lock().unwrap().hooked_start = None;
        match mid_batch.reading {
            Some(reading) => self.host = Some(reading),
            None => self.seen.stalls_during_start += 1,
        }
        let launched = self.engine.launches().after(mid_batch.launched);
        Some(
            launched
                .into_iter()
                .filter(|name| starts.contains(name))
                .collect(),
        )
    }

    /// A pass between ticks, after Docker said every runner may have stopped: the checks of a tick that bind a pass,
    /// which plans from the last tick's listings.
    async fn pass(&mut self) -> Result<(), Violation> {
        self.unregistered_runners_exit();
        let calls_before = self.docker.0.lock().unwrap().calls.len();
        self.engine.exits.any();
        self.note_busy();
        self.engine.turnover().await;
        self.removals_finish();
        self.failed_late();
        self.exits_hold_only_what_failed_to_start()?;
        let after = self.status();
        let running: BTreeSet<String> = self
            .running_containers()
            .into_iter()
            .map(|container| container.name)
            .collect();
        let order: Vec<String> = self.docker.0.lock().unwrap().calls[calls_before..]
            .iter()
            .filter_map(|call| call.strip_prefix("start "))
            .filter(|name| running.contains(*name))
            .map(str::to_owned)
            .collect();
        self.note_slow_start(order.len());
        let starts: BTreeSet<String> = order.iter().cloned().collect();
        self.no_pass_starts_a_second_runner_for_a_job(&after, &starts)?;
        self.no_slot_is_left_starting()?;
        self.runner_names_are_unique()?;
        self.no_build_cache_left_open_without_a_runner()?;
        let bound = self.starts_after_a_reading(&order);
        self.starts_fit_the_budget(&after, bound.as_ref().unwrap_or(&starts))?;
        self.docker_runs_no_runner_the_engine_lost(&after)?;
        self.no_watch_outlives_its_runner()?;
        self.one_barrier_and_only_for_a_queued_job(&after)?;
        self.no_job_waits_for_a_slot_or_the_host_past_its_runners_start(&after)?;
        self.the_count_keeps_its_bounds(&after)?;
        self.note_states();
        self.no_removal_of_a_running_job()
    }

    /// ADR 0110: a job an idle runner will take stopped waiting for a slot and for the host's memory when that runner
    /// started, whether a tick or a pass started it, so neither wait sizing reads goes on to the next commit.
    fn no_job_waits_for_a_slot_or_the_host_past_its_runners_start(
        &mut self,
        status: &api::Status,
    ) -> Result<(), Violation> {
        let engine = &self.engine;
        let still: Vec<u64> = status
            .queued
            .iter()
            .filter(|job| job.waiting == Some(api::Waiting::RunnerStarting))
            .map(|job| job.id)
            .inspect(|_| self.seen.runners_starting += 1)
            .filter(|job| engine.waits_for_a_slot(*job) || engine.waits_for_the_host(*job))
            .collect();
        if still.is_empty() {
            return Ok(());
        }
        violation(
            self,
            "no_job_waits_for_a_slot_or_the_host_past_its_runners_start",
            format!("jobs {still:?} have a runner starting and still wait for a slot or the host"),
        )
    }

    /// Invariant 1 for a pass: a pass that starts runners in a pool leaves it no more runners waiting for a job than
    /// the jobs queued now and those the listing it planned from showed queued that were cancelled since. A job that
    /// left the queue for one of this machine's runners is never counted twice: no job gets a second runner from
    /// a listing older than its first.
    fn no_pass_starts_a_second_runner_for_a_job(
        &self,
        status: &api::Status,
        started: &BTreeSet<String>,
    ) -> Result<(), Violation> {
        let idle: BTreeSet<String> = self.idle_containers().into_iter().map(|c| c.id).collect();
        let pools: BTreeSet<(String, String)> = runners_of(status)
            .filter(|(_, runner)| started.contains(&runner.name))
            .map(|(profile, runner)| (runner.repository.clone(), profile.to_owned()))
            .collect();
        for (repository, profile) in pools {
            let waiting = runners_of(status)
                .filter(|(in_profile, runner)| {
                    *in_profile == profile
                        && runner.repository == repository
                        && idle.contains(&runner.container)
                })
                .count();
            let wanted = self
                .queued()
                .into_iter()
                .chain(self.cancelled_since_listed.values().flatten().copied())
                .chain(self.listed_after_runner.iter().copied())
                .filter(|id| {
                    let job = &self.jobs[id];
                    job.repository == repository
                        && self.shape.serves(job.repository, &job.labels) == Some(profile.as_str())
                })
                .count();
            if waiting > wanted {
                return violation(
                    self,
                    "no_pass_starts_a_second_runner_for_a_job",
                    format!(
                        "{repository} in {profile}: {waiting} runners wait for {wanted} jobs queued or cancelled"
                    ),
                );
            }
        }
        Ok(())
    }

    /// Invariant 1: a tick that starts runners in a pool leaves it no more runners waiting for a job than it has
    /// queued jobs, so no job gets runners in two pools nor more than one.
    fn no_pool_gets_more_runners_than_its_queued_jobs(
        &self,
        status: &api::Status,
        started: &BTreeSet<String>,
    ) -> Result<(), Violation> {
        let mut pools: BTreeSet<(String, String)> = BTreeSet::new();
        for (profile, runner) in runners_of(status) {
            if started.contains(&runner.name) {
                pools.insert((runner.repository.clone(), profile.to_owned()));
            }
        }
        let idle: BTreeSet<String> = self.idle_containers().into_iter().map(|c| c.id).collect();
        for (repository, profile) in pools {
            let waiting = runners_of(status)
                .filter(|(in_profile, runner)| {
                    *in_profile == profile
                        && runner.repository == repository
                        && idle.contains(&runner.container)
                })
                .count();
            let queued = self
                .queued()
                .into_iter()
                .chain(self.cancelled_since_listed.values().flatten().copied())
                .chain(self.listed_after_runner.iter().copied())
                .filter(|id| {
                    let job = &self.jobs[id];
                    job.repository == repository
                        && self.shape.serves(job.repository, &job.labels) == Some(profile.as_str())
                })
                .count();
            if waiting > queued {
                return violation(
                    self,
                    "no_pool_gets_more_runners_than_its_queued_jobs",
                    format!(
                        "{repository} in {profile}: {waiting} runners wait for {queued} queued jobs"
                    ),
                );
            }
        }
        Ok(())
    }

    /// Invariant 2: a tick that starts a runner or a seed container leaves what runs within the slice's
    /// `MemoryMax`, the CPU budget under `cpu_overcommit` and what the host leaves the slice, and starts nothing
    /// while the host stalls short of memory (ADR 0055). What runs may be past it otherwise: nothing is stopped for
    /// it.
    fn starts_fit_the_budget(
        &self,
        status: &api::Status,
        started: &BTreeSet<String>,
    ) -> Result<(), Violation> {
        if started.is_empty() {
            return Ok(());
        }
        let budget = &status.budget;
        // A seed container reserves no CPU, so it starts past a CPU budget a reload lowered under the runners in.
        let runner_started = started.iter().any(|name| !name.ends_with(SEED_START));
        // Under caps, what Docker runs them with, whatever the engine counts.
        if self.shape.admission == Admission::Caps {
            let running = self.running_containers();
            let docker = self.docker.0.lock().unwrap();
            let caps: u64 = running
                .iter()
                .map(|container| docker.memory.get(&container.id).copied().unwrap_or(0))
                .sum();
            let cpus: u64 = running
                .iter()
                .map(|container| docker.cpus.get(&container.id).copied().unwrap_or(0))
                .sum();
            drop(docker);
            // The CPU budget is the slice's CPUs times 1.0; seeds and the mirror reserve none.
            if runner_started && self.shape.cpu_overcommit && cpus > SLICE_CPUS {
                return violation(
                    self,
                    "starts_fit_the_budget",
                    format!("started {started:?} with CPU limits of {cpus} in {SLICE_CPUS}"),
                );
            }
            let seeds: u64 = budget.seed_memory.iter().map(|seed| seed.memory).sum();
            if caps.saturating_add(seeds) > MEMORY_MAX {
                return violation(
                    self,
                    "starts_fit_the_budget",
                    format!(
                        "started {started:?} with caps of {caps} and seeds of {seeds} in {MEMORY_MAX}"
                    ),
                );
            }
        }
        if let Some(max) = budget.memory_max
            && budget.counted() > max
        {
            return violation(
                self,
                "starts_fit_the_budget",
                format!(
                    "started {started:?} with {} of {max} counted, seed containers {:?}",
                    budget.counted(),
                    budget.seed_memory
                ),
            );
        }
        if let Some(cpu) = &budget.cpu
            && runner_started
            && cpu.in_use > cpu.budget
        {
            return violation(
                self,
                "starts_fit_the_budget",
                format!(
                    "started {started:?} with {} of {} millicores reserved",
                    cpu.in_use, cpu.budget
                ),
            );
        }
        // From the harness's own reading, whatever the engine reports: the engine's margin is at least this one.
        let now = self.clock.now_ms();
        if let Some(reading) = self.host.filter(|reading| reading.fresh(now)) {
            let limit = reading
                .slice
                .saturating_add(reading.available)
                .saturating_sub(HOST_MARGIN);
            // The seed containers that run, at their caps; not the room a waiting one holds.
            let seeds: u64 = self.engine.seed_memories().values().sum();
            let credit = host_credit(budget);
            let reserved = runners_of(status)
                .map(|(_, runner)| runner.reserved)
                .fold(seeds, u64::saturating_add)
                .saturating_sub(credit);
            if reserved > limit {
                return violation(
                    self,
                    "starts_fit_the_budget",
                    format!("started {started:?} with {reserved} reserved past the host's {limit}"),
                );
            }
            if reading.stalled && reading.available < 2 * HOST_MARGIN {
                return violation(
                    self,
                    "starts_fit_the_budget",
                    format!(
                        "started {started:?} while the host stalls with {} available",
                        reading.available
                    ),
                );
            }
        }
        Ok(())
    }

    /// Invariant 11 (ADR 0099, 0108, 0130): both credits stay in their bounds through restarts, reloads, stale
    /// readings, stalls and lost runners. What the status shows is what a plan goes by; credits and the growth count
    /// stand only with `pooled_count` under measured admission. Under 0099's and 0108's credits neither count reads
    /// under what eligible runners use with all the rest in full, and the host's keeps at least the 6G floor of their
    /// headroom, or all of it; the host's credit stands only with a fresh reading of the slice and the host, and no
    /// stall. The growth count's bounds are `the_growth_count_keeps_its_bounds`. What a drain leaves reads neither
    /// credit.
    fn the_count_keeps_its_bounds(&mut self, status: &api::Status) -> Result<(), Violation> {
        let budget = &status.budget;
        let credit = budget.pooled.map_or(0, |pooled| pooled.credit);
        let host_credit = host_credit(budget);
        let pools = self.shape.admission == Admission::Measured && self.shape.pooled_count;
        if budget.counted.is_some() != pools || ((credit > 0 || host_credit > 0) && !pools) {
            let detail = format!("{budget:?} under {:?}", self.shape);
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        self.plans_read_the_count(budget, host_credit)?;
        let committed = self.engine.committed_memory();
        if let Some(kept) = budget.counted.as_ref().and_then(|counted| counted.kept) {
            return self.the_growth_count_keeps_its_bounds(budget, kept, committed);
        }
        if credit > pooled::MOST_CREDIT {
            let detail = format!("{budget:?} under {:?}", self.shape);
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let hosted = budget.memory_in_use - host_credit;
        if credit == 0 && host_credit == 0 {
            return Ok(());
        }
        let now = SystemTime::now();
        let fresh_after = self
            .clock
            .now_ms()
            .saturating_sub(3000 * api::SAMPLE_INTERVAL);
        let mut floor = committed;
        let mut headroom = 0;
        for (_, occupant) in self.engine.occupied() {
            let sample = self.handle.store.latest_sample(&occupant.runner_name);
            let settled = occupant
                .job_found_at()
                .and_then(|started| now.duration_since(started).ok())
                .is_some_and(|ran| ran >= POOL_AFTER);
            let predicted = occupant.admission.is_some_and(|admission| {
                matches!(
                    admission.basis,
                    Basis::Job { .. } | Basis::Profile { .. } | Basis::ProfileMax { .. }
                )
            });
            let known = occupant.has_key() && occupant.was_started_here();
            let takes = self.engine.takes(occupant);
            match sample.filter(|sample| sample.at >= fresh_after) {
                Some(sample) if settled && predicted && known => {
                    floor += sample.memory;
                    headroom += takes.saturating_sub(sample.memory);
                }
                _ => floor += takes,
            }
        }
        let slice = self
            .handle
            .store
            .latest_host_sample()
            .filter(|sample| sample.at * 1000 >= fresh_after)
            .map(|sample| sample.memory);
        if host_credit > 0 {
            self.seen.host_credits += 1;
            let kept = headroom.min(pooled::HOST_RESERVE_FLOOR);
            if hosted < floor + kept {
                let detail =
                    format!("{budget:?} counts {hosted} for the host, under {floor} and {kept}");
                return violation(self, "the_count_keeps_its_bounds", detail);
            }
            let read = self
                .host
                .filter(|reading| reading.fresh(self.clock.now_ms()));
            let stalls = budget.host.as_ref().is_none_or(|host| host.stalled);
            if read.is_none() || slice.is_none() || stalls {
                let detail = format!(
                    "a host credit of {host_credit} beside the reading {read:?}, the slice's {slice:?} and {:?}",
                    budget.host
                );
                return violation(self, "the_count_keeps_its_bounds", detail);
            }
        }
        if credit == 0 {
            return Ok(());
        }
        self.seen.credits += 1;
        if budget.counted() < floor {
            let detail = format!("{budget:?} counts under {floor}");
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let host = budget.host.as_ref();
        let keeps = HOST_MARGIN + HOST_TOTAL / 4;
        if host.is_none_or(|host| host.stalled || host.memory.available < keeps + credit) {
            let detail = format!("{credit} of credit beside the host's {host:?}");
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let room = slice.map(|slice| {
            (MEMORY_MAX * 90 / 100)
                .saturating_sub(slice)
                .saturating_sub(pooled::HIGH_WATER_RESERVE)
        });
        if room.is_none_or(|room| credit > room) {
            let detail = format!("{credit} of credit beside the slice's {slice:?}");
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        Ok(())
    }

    /// Part of invariant 11 (ADR 0130): the growth count, which `kept` the room for growth, counts only beside a fresh
    /// reading of the slice and of a host with its margins to spare and no stall. Both counts read at least what
    /// runners with a fresh sample use, beside the rest in full and at least the 6G floor of the sampled ones' headroom,
    /// or all of it; and both credits stay under the host's room past its margins and `GROWTH_CEILING`, `MemoryMax`'s
    /// under the slice's room below its high-water mark.
    fn the_growth_count_keeps_its_bounds(
        &mut self,
        budget: &api::Budget,
        kept: u64,
        committed: u64,
    ) -> Result<(), Violation> {
        self.seen.growth_counts += 1;
        let read = self
            .host
            .filter(|reading| reading.fresh(self.clock.now_ms()));
        let fresh_after = self
            .clock
            .now_ms()
            .saturating_sub(3000 * api::SAMPLE_INTERVAL);
        let slice = self
            .handle
            .store
            .latest_host_sample()
            .filter(|sample| sample.at * 1000 >= fresh_after)
            .map(|sample| sample.memory);
        let keeps = HOST_MARGIN + HOST_TOTAL / 4;
        let host = budget.host.as_ref();
        let (Some(slice), Some(host), Some(_)) = (slice, host, read) else {
            let detail = format!(
                "{budget:?} counts growth beside the reading {read:?} and the slice's {slice:?}"
            );
            return violation(self, "the_count_keeps_its_bounds", detail);
        };
        if host.stalled || host.memory.available < keeps {
            let detail = format!("{budget:?} counts growth beside the host's {host:?}");
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let mut used = committed;
        let mut unsampled = 0;
        let mut headroom = 0;
        for (_, occupant) in self.engine.occupied() {
            let takes = self.engine.takes(occupant);
            match self
                .handle
                .store
                .latest_sample(&occupant.runner_name)
                .filter(|sample| sample.at >= fresh_after)
            {
                Some(sample) => {
                    used += sample.memory.min(takes);
                    headroom += takes.saturating_sub(sample.memory);
                }
                None => unsampled += takes,
            }
        }
        let credit = budget.pooled.map_or(0, |pooled| pooled.credit);
        let host_credit = host_credit(budget);
        let hosted = budget.memory_in_use - host_credit;
        let least = (used + unsampled).max(used + headroom.min(pooled::GROWTH_FLOOR));
        if kept < headroom.min(pooled::GROWTH_FLOOR) || budget.counted().min(hosted) < least {
            let detail = format!(
                "{budget:?} counts under {used} used, {unsampled} unsampled and {headroom} of headroom"
            );
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let host_room = host.memory.available - keeps;
        let slice_room = (MEMORY_MAX * 90 / 100)
            .saturating_sub(slice)
            .saturating_sub(pooled::HIGH_WATER_RESERVE);
        if credit.max(host_credit) > host_room.min(pooled::GROWTH_CEILING) || credit > slice_room {
            let detail = format!(
                "credits of {credit} and {host_credit} beside the host's {host_room}, the slice's {slice_room} and the \
                 ceiling"
            );
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        Ok(())
    }

    /// Part of invariant 11: a plan reads the counts the status shows, the host's limit the plain count less the
    /// host's credit, and a drain neither credit.
    fn plans_read_the_count(
        &mut self,
        budget: &api::Budget,
        host_credit: u64,
    ) -> Result<(), Violation> {
        let admitting = self.engine.admitting(&mut [], None);
        let plan = self.engine.plan_budget(&admitting);
        let left = budget
            .memory_max
            .map(|max| crate::scheduler::left(max, budget.counted()));
        if !admitting.held && plan.memory != left {
            let detail = format!("a plan reads {:?}, the status {left:?}", plan.memory);
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        // The host's limit reads the plain count less the host's credit.
        let hosted = budget.memory_in_use - host_credit;
        let host = admitting
            .host
            .as_ref()
            .map(|host| host::left(host.limit, hosted, host.stalled));
        if !admitting.held && plan.host != host {
            let detail = format!(
                "a plan's host reads {:?}, the host's count {host:?}",
                plan.host
            );
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        let running = self.engine.occupied().next().is_some();
        let committed = self.engine.committed_memory();
        let drained = admitting.host.as_ref().map(|host| {
            let limit = host::limit(&host.memory, running || host.stalled);
            crate::scheduler::left(limit, committed)
        });
        if plan.drained.host != drained {
            let detail = format!("a drain leaves {:?}, not {drained:?}", plan.drained.host);
            return violation(self, "the_count_keeps_its_bounds", detail);
        }
        Ok(())
    }

    /// Invariant 11a (ADR 0108, challenge finding 6): a restarted daemon saw none of the runners it adopted start, so
    /// none counts at its use: the host's credit is gone at its first tick, and nothing starts on it until the plain
    /// count fits, which `starts_fit_the_budget` reads.
    fn a_restart_takes_the_host_credit_back(&mut self) -> Result<(), Violation> {
        let status = self.status();
        if host_credit(&status.budget) > 0 {
            let detail = format!("{:?} after a restart", status.budget.host);
            return violation(self, "a_restart_takes_the_host_credit_back", detail);
        }
        Ok(())
    }

    /// Invariant 12 (ADR 0102), after a tick: a stall keeps the larger margin, and no reading leaves none. A plan by what
    /// the tick remembered shows a job waiting for the host only if the margin stands while it fits the plain one not
    /// at all; and with nothing to start, a host no waiter fits keeps it. The plan may start one and leave others
    /// waiting: the tick after decides for those. A reading taken during the tick's starts binds the next tick, so the
    /// caller skips this then. A seed started after the tick's last plan only raises the count, which can leave a host no
    /// waiter fits at the plain margin for one tick (`seeded`): that plan starts nothing, and the next tick decides.
    fn the_band_follows_the_waiters(
        &mut self,
        was_short: bool,
        seeded: bool,
    ) -> Result<(), Violation> {
        let short = self.engine.host_is_short();
        let (plan, admitting) = self.engine.plan();
        let Some(host) = admitting.host.as_ref() else {
            if short {
                let detail = "the larger margin with no reading".to_owned();
                return violation(self, "the_band_follows_the_waiters", detail);
            }
            return Ok(());
        };
        if host.stalled {
            if !short {
                let detail = format!("a stall without the larger margin: {:?}", host.memory);
                return violation(self, "the_band_follows_the_waiters", detail);
            }
            return Ok(());
        }
        let in_use = self.engine.count(self.engine.host_remembered()).plain;
        let room = host::left(host::limit(&host.memory, false), in_use, false);
        let needs: Vec<i64> = plan
            .waiting
            .values()
            .filter_map(|reason| match reason {
                api::Waiting::HostMemory { needs, .. } => i64::try_from(*needs).ok(),
                _ => None,
            })
            .collect();
        let fits = needs.iter().any(|needs| *needs <= room);
        let starts = plan
            .decisions
            .iter()
            .any(|decision| matches!(decision, Decision::Start { .. }));
        if short && fits {
            let detail = format!("{needs:?} wait, {room} is left by the plain margin");
            return violation(self, "the_band_follows_the_waiters", detail);
        }
        if !short && !fits && !needs.is_empty() && !starts && !seeded {
            let detail = format!("{needs:?} wait, {room} is left, and the margin is plain");
            return violation(self, "the_band_follows_the_waiters", detail);
        }
        self.seen.bands += usize::from(short && !needs.is_empty());
        self.seen.released += usize::from(was_short && !short && starts);
        Ok(())
    }

    /// Invariant 2a (ADR 0096): at most one job holds younger ones back, memory and CPU together. It is queued, older
    /// than each of them and says what it lacks itself; and no wait is kept for a job a listing that succeeded no
    /// longer shows, so no hold outlives its job.
    fn one_barrier_and_only_for_a_queued_job(
        &mut self,
        status: &api::Status,
    ) -> Result<(), Violation> {
        let behind = |reason: &Option<api::Waiting>| match reason {
            Some(api::Waiting::BehindMemory { job } | api::Waiting::BehindCpu { job }) => {
                Some(*job)
            }
            _ => None,
        };
        let owners: BTreeSet<u64> = status
            .queued
            .iter()
            .filter_map(|job| behind(&job.waiting))
            .collect();
        self.seen.barriers += owners.len();
        if owners.len() > 1 {
            return violation(
                self,
                "one_barrier_and_only_for_a_queued_job",
                format!("jobs wait behind each of {owners:?}"),
            );
        }
        for owner in &owners {
            let Some(queued) = status.queued.iter().find(|job| job.id == *owner) else {
                return violation(
                    self,
                    "one_barrier_and_only_for_a_queued_job",
                    format!("jobs wait behind {owner}, which no longer waits"),
                );
            };
            if behind(&queued.waiting).is_some() {
                return violation(
                    self,
                    "one_barrier_and_only_for_a_queued_job",
                    format!("{owner} holds others back and says {:?}", queued.waiting),
                );
            }
            if let Some(younger) = status
                .queued
                .iter()
                .find(|job| behind(&job.waiting).is_some() && job.id <= *owner)
            {
                return violation(
                    self,
                    "one_barrier_and_only_for_a_queued_job",
                    format!(
                        "{} is older than {owner}, which it waits behind",
                        younger.id
                    ),
                );
            }
        }
        for listed in self.engine.listed_repositories() {
            let (name, queued) = (listed.name, listed.queued);
            let waits = listed.waits.iter();
            let kept = waits.flat_map(|waits| waits.memory().into_iter().chain(waits.cpu()));
            if let Some(wait) = kept
                .into_iter()
                .find(|wait| !queued.iter().any(|job| job.id == wait.job))
            {
                return violation(
                    self,
                    "one_barrier_and_only_for_a_queued_job",
                    format!("{name} keeps a wait for job {}, listed no more", wait.job),
                );
            }
            if queued.is_empty() && listed.waits.iter().any(crate::scheduler::Waits::served) {
                return violation(
                    self,
                    "one_barrier_and_only_for_a_queued_job",
                    format!("{name} keeps a served mark with nothing queued"),
                );
            }
        }
        Ok(())
    }

    /// With the mirror enabled, a tick that started a runner leaves the mirror running, as its runners pull through it.
    /// Only an empty slice stops it.
    fn a_runner_started_finds_the_mirror_up(&self, starts: &[String]) -> Result<(), Violation> {
        let held = self.engine.occupied().next().is_some();
        let up = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .any(|container| container.running && container.labels.contains_key("runnerd.mirror"));
        if self.shape.mirror && held && !up && !starts.is_empty() {
            let detail = format!("{starts:?} started and no mirror runs");
            return violation(self, "a_runner_started_finds_the_mirror_up", detail);
        }
        Ok(())
    }

    /// Invariant 3: runnerd never removes a container whose job still runs, whatever restarts, reloads and failed
    /// Docker calls came before.
    fn no_removal_of_a_running_job(&mut self) -> Result<(), Violation> {
        self.forced_jobs_end();
        let calls = self.docker.calls();
        let running: BTreeMap<String, u64> = self
            .running()
            .into_iter()
            .map(|(id, container)| (container, id))
            .collect();
        for call in &calls[self.calls_seen..] {
            // A forced pause's kill may remove one, even if Docker then fails to.
            if let Some(container) = call.strip_prefix("remove ")
                && let Some(job) = running.get(container)
                && !self.forced.contains(container)
            {
                let detail = format!("removed {container}, which runs job {job}");
                self.calls_seen = calls.len();
                return violation(self, "no_removal_of_a_running_job", detail);
            }
        }
        self.calls_seen = calls.len();
        Ok(())
    }

    /// Invariant 4, while the sequence runs: every runner container Docker runs is one the engine holds a slot for.
    fn docker_runs_no_runner_the_engine_lost(&self, status: &api::Status) -> Result<(), Violation> {
        let held: BTreeSet<&str> = runners_of(status)
            .map(|(_, runner)| runner.container.as_str())
            .collect();
        let lost: Vec<String> = self
            .running_containers()
            .into_iter()
            .filter(|container| !held.contains(container.id.as_str()))
            .map(|container| container.id)
            .collect();
        if lost.is_empty() {
            Ok(())
        } else {
            violation(
                self,
                "docker_runs_no_runner_the_engine_lost",
                format!("no slot holds {lost:?}"),
            )
        }
    }

    /// Every runner the engine watches holds a slot: a runner's watch goes with it, and a restart starts none.
    fn no_watch_outlives_its_runner(&self) -> Result<(), Violation> {
        let held: BTreeSet<&str> = self
            .engine
            .occupied()
            .map(|(_, occupant)| occupant.runner_name.as_str())
            .collect();
        let outlived: Vec<&str> = self
            .engine
            .watches
            .runners()
            .filter(|runner| !held.contains(runner))
            .collect();
        if outlived.is_empty() {
            Ok(())
        } else {
            violation(
                self,
                "no_watch_outlives_its_runner",
                format!("{outlived:?} are watched with no slot"),
            )
        }
    }

    /// Invariant 5: a queued job no pool serves waits with `NoPool`, a job a pool serves never does, and a job for
    /// GitHub's own runners is not listed.
    fn only_unserved_jobs_wait_for_a_pool(&self, status: &api::Status) -> Result<(), Violation> {
        for listed in &status.queued {
            let job = &self.jobs[&listed.id];
            let hosted = job.labels == ["ubuntu-latest"];
            let unserved = self.shape.serves(job.repository, &job.labels).is_none();
            let no_pool = matches!(listed.waiting, Some(api::Waiting::NoPool { .. }));
            if hosted || unserved != no_pool {
                return violation(
                    self,
                    "only_unserved_jobs_wait_for_a_pool",
                    format!(
                        "job {} asking for {:?} waits with {:?}",
                        listed.id, job.labels, listed.waiting
                    ),
                );
            }
        }
        // While GitHub's rate limit is used up, every listing fails at once, as the client fails it.
        if status.github_limited_until.is_some() {
            return Ok(());
        }
        for id in self.queued() {
            let job = &self.jobs[&id];
            if job.shown
                && self.shape.configures(job.repository)
                && job.labels != ["ubuntu-latest"]
                && !status.queued.iter().any(|listed| listed.id == id)
            {
                return violation(
                    self,
                    "only_unserved_jobs_wait_for_a_pool",
                    format!("queued job {id} asking for {:?} is not listed", job.labels),
                );
            }
        }
        Ok(())
    }

    /// Ends the sequence: the queued jobs are cancelled, the running ones finish, and time passes.
    async fn drain(&mut self) -> Result<(), Violation> {
        self.step += 1;
        self.github.0.lock().unwrap().on_register = None;
        self.docker.0.lock().unwrap().on_prepare = None;
        while !self.queued().is_empty() {
            self.apply(Step::Cancel(0)).await?;
        }
        while !self.running().is_empty() {
            self.apply(Step::Finish(0)).await?;
        }
        while !self.open().is_empty() {
            self.open_job_completes(0);
        }
        // What GitHub lists of this machine that no slot holds goes when its job does.
        let orphans = std::mem::take(&mut self.orphans);
        self.github
            .0
            .lock()
            .unwrap()
            .runners
            .retain(|runner| !orphans.contains(&runner.id));
        for _ in 0..6 {
            self.elapse();
            self.tick().await?;
        }
        self.no_runner_is_left()?;
        self.names_only_rise()?;
        self.history_names_the_pool_that_ran_each_job().await?;
        self.no_job_stays_running().await
    }

    /// Once drained: each runner GitHub was asked to register is named later than every one before it, across
    /// restarts too, so no name is used twice whatever the clock says.
    fn names_only_rise(&self) -> Result<(), Violation> {
        let named: Vec<String> = self
            .github
            .calls()
            .iter()
            .filter_map(|call| call.strip_prefix("register "))
            .map(str::to_owned)
            .collect();
        let second = |name: &String| {
            name.rsplit_once('-')
                .and_then(|(_, secs)| secs.parse::<u64>().ok())
        };
        match named
            .windows(2)
            .find(|pair| second(&pair[1]) <= second(&pair[0]))
        {
            Some(pair) => violation(
                self,
                "names_only_rise",
                format!("{} was named after {}", pair[1], pair[0]),
            ),
            None => Ok(()),
        }
    }

    /// Invariant 4, once drained: every runner runnerd started has gone, from Docker, its slots and GitHub.
    fn no_runner_is_left(&mut self) -> Result<(), Violation> {
        let status = self.status();
        let containers: Vec<String> = self
            .docker
            .0
            .lock()
            .unwrap()
            .containers
            .iter()
            .filter(|container| container.labels.contains_key("runnerd.job"))
            .map(|container| container.id.clone())
            .collect();
        let slots: Vec<String> = runners_of(&status)
            .map(|(_, runner)| runner.name.clone())
            .collect();
        let registered: Vec<String> = self
            .github
            .0
            .lock()
            .unwrap()
            .runners
            .iter()
            .map(|runner| runner.name.clone())
            .collect();
        if containers.is_empty() && slots.is_empty() && registered.is_empty() {
            Ok(())
        } else {
            violation(
                self,
                "no_runner_is_left",
                format!("containers {containers:?}, slots {slots:?}, registered {registered:?}"),
            )
        }
    }

    /// Invariant 6: the history names the profile and repository of the runner that ran each job.
    async fn history_names_the_pool_that_ran_each_job(&mut self) -> Result<(), Violation> {
        self.handle.store.flush().await;
        let ran: Vec<(u64, (String, String))> = self
            .jobs
            .iter()
            .filter_map(|(id, job)| match &job.phase {
                Phase::Done { ran: Some(ran) } => Some((*id, ran.clone())),
                _ => None,
            })
            .collect();
        for (id, (profile, repository)) in ran {
            let recorded = self.handle.store.job(id).await.unwrap();
            let seen = recorded.as_ref().map(|job| {
                (
                    job.summary
                        .runner
                        .as_ref()
                        .map(|runner| runner.profile.clone()),
                    job.summary.repository.clone(),
                )
            });
            if seen != Some((Some(profile.clone()), repository.clone())) {
                return violation(
                    self,
                    "history_names_the_pool_that_ran_each_job",
                    format!("job {id} ran in {repository} {profile}; the history says {seen:?}"),
                );
            }
        }
        Ok(())
    }

    /// Invariant 7, once drained: no job the history holds stays running, as every runner has gone.
    async fn no_job_stays_running(&mut self) -> Result<(), Violation> {
        for id in self.jobs.keys().copied().collect::<Vec<_>>() {
            let recorded = self.handle.store.job(id).await.unwrap();
            if let Some(job) = recorded.filter(|job| job.summary.state == JobState::Running) {
                return violation(
                    self,
                    "no_job_stays_running",
                    format!("job {id} is still running on {:?}", job.summary.runner),
                );
            }
        }
        Ok(())
    }
}

/// The sampler reads the slice and the host: the runners that took a job (`took_job`) use `percent` of their caps,
/// the others 100M; the host has `available` gigabytes available, and its tasks stall or not.
fn sample(
    docker: &DockerState,
    store: &Store,
    took_job: &BTreeSet<String>,
    now: u64,
    percent: u64,
    available: u64,
    stalled: bool,
) -> HostReading {
    let mut slice = 0;
    let mut samples = Vec::new();
    for container in docker
        .containers
        .iter()
        .filter(|container| container.running && container.labels.contains_key("runnerd.job"))
    {
        let cap = docker.memory.get(&container.id).copied().unwrap_or(G);
        let memory = if took_job.contains(&container.id) {
            cap / 100 * percent
        } else {
            100 * M
        };
        slice += memory;
        samples.push(SampleRecord {
            runner: container.name.clone(),
            at: now,
            cpu: 0,
            cpu_usage: 0,
            memory,
            network_received: 0,
            network_sent: 0,
            cpu_held: crate::observe::metrics::CpuHeld::default(),
            events: Events::default(),
        });
    }
    store.samples(samples);
    store.host_sample(api::HostSample {
        at: now / 1000,
        cpu: 0,
        memory: slice,
    });
    store.host_memory(api::HostMemory {
        at: now / 1000,
        total: HOST_TOTAL,
        available: available * G,
        slice,
        some: Some(api::Pressure::default()),
        full: Some(api::Pressure {
            avg10: if stalled { 600 } else { 0 },
            avg60: 0,
        }),
        holders: Vec::new(),
        ceiling: None,
        swap: None,
    });
    HostReading {
        at: now / 1000,
        slice,
        available: available * G,
        stalled,
    }
}

fn pick_from<T>(items: &[T], pick: usize) -> Option<&T> {
    (!items.is_empty()).then(|| &items[pick % items.len()])
}

fn set_running(docker: &mut DockerState, container: &str, running: bool) {
    for candidate in &mut docker.containers {
        if candidate.id == container {
            candidate.running = running;
        }
    }
}

/// What the host's limit takes off the plain count in `budget` (ADR 0108).
fn host_credit(budget: &api::Budget) -> u64 {
    budget
        .host
        .as_ref()
        .and_then(|host| host.credit)
        .map_or(0, |credit| credit.bytes)
}

/// Every runner in the status, with its profile.
fn runners_of(status: &api::Status) -> impl Iterator<Item = (&str, &api::RunnerStatus)> {
    status.profiles.iter().flat_map(|profile| {
        profile
            .slots
            .iter()
            .filter_map(|slot| slot.runner.as_ref())
            .map(|runner| (profile.name.as_str(), runner))
    })
}

/// The status as a trace compares it: what it says, without the figures a run's clock decides. A seed's reserve and
/// whether a reseed still runs depend on which background task finished first, which is not what a step did.
fn steady_status(status: &api::Status) -> serde_json::Value {
    fn blank(value: &mut serde_json::Value) {
        match value {
            serde_json::Value::Number(_) => *value = 0.into(),
            serde_json::Value::Array(items) => items.iter_mut().for_each(blank),
            serde_json::Value::Object(fields) => {
                fields.retain(|name, _| !UNSTEADY_STATUS.contains(&name.as_str()));
                fields.values_mut().for_each(blank);
            }
            _ => {}
        }
    }
    let mut value = serde_json::to_value(status).unwrap();
    blank(&mut value);
    value
}

/// A runner's name without the second it was started in, which is all of a trace the machine's clock decides.
fn steady(line: &str) -> String {
    let mut out = String::with_capacity(line.len());
    let bytes = line.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let run = bytes[i + 1..]
            .iter()
            .take_while(|byte| byte.is_ascii_digit())
            .count();
        if bytes[i] == b'-' && run == 10 {
            i += 11;
        } else {
            out.push(char::from(bytes[i]));
            i += 1;
        }
    }
    out
}

/// Runs a sequence from a fresh start, then drains it; the first broken invariant.
async fn run(steps: &[Step]) -> Result<Seen, Violation> {
    run_case(steps, Case::new()).await.map(|case| case.seen)
}

async fn run_case(steps: &[Step], mut case: Case) -> Result<Case, Violation> {
    case.recover().await?;
    case.tick().await?;
    case.trace_step("start").await;
    for (index, step) in steps.iter().enumerate() {
        case.step = index;
        case.apply(*step).await?;
        case.trace_step(&format!("{index} {step:?}")).await;
    }
    case.step = steps.len();
    case.drain().await?;
    case.trace_step("drained").await;
    case.note_closes().await;
    case.note_start_faults();
    Ok(case)
}

const LIGHT: Step = Step::Queue {
    second: false,
    labels: Labels::Light,
};

/// ADR 0125, 0126: the daemon goes with one start's container made, the next one's registration made, and the third
/// waiting for its turn to register. The slice's 8.5G takes the two light runners and the heavy one at once.
const A_BATCH_ABORTED: [Step; 4] = [LIGHT, LIGHT, HEAVY, Step::AbortMidBatch];

/// A stop asked for as GitHub registers the second runner of a batch, with the third waiting for its turn.
const A_STOP_WHILE_A_BATCH_REGISTERS: [Step; 5] = [
    LIGHT,
    LIGHT,
    HEAVY,
    Step::StopDuringStart {
        docker_gone: false,
        after: 1,
        at: StopAt::Registration,
    },
    Step::Tick,
];

/// Under measured admission, the first container of a batch takes long to start, and the slice's sample turns stale
/// as it does.
const A_SLOW_STALLING_START_IN_A_BATCH: [Step; 8] = [
    Step::Reload(Change::Policy),
    Step::Sample {
        percent: 50,
        available: 50,
        stalled: false,
    },
    LIGHT,
    LIGHT,
    HEAVY,
    Step::SlowStart,
    Step::SliceSampleStallsDuringStart,
    Step::Tick,
];

/// What a generated case runs: its seed's steps, after the scenarios every so many seeds start from.
fn steps_of(seed: u64) -> Vec<Step> {
    let mut steps = generate(&mut Rng(seed));
    if seed % 2 == 1 {
        steps.splice(0..0, TWO_JOBS_SETTLED);
    }
    match seed % 8 {
        0 => drop(steps.splice(0..0, SLOT_FREED_BETWEEN_TICKS)),
        2 => drop(steps.splice(0..0, BAND_RELEASED[..BAND_STANDS].iter().copied())),
        4 => drop(steps.splice(0..0, THREE_JOBS_SETTLED)),
        6 => drop(steps.splice(0..0, BAND_RELEASED)),
        _ => {}
    }
    if seed.is_multiple_of(32) {
        steps.splice(0..0, WAITS_ON_DIFFERENT_JOBS);
    }
    // First, on seeds no reach check asks a state of and no scenario above needs a clean start: a batch of starts in
    // the middle of which something happens.
    if seed.is_multiple_of(8) && !seed.is_multiple_of(32) {
        let batch: &[Step] = match seed % 32 {
            8 => &A_BATCH_ABORTED,
            16 => &A_STOP_WHILE_A_BATCH_REGISTERS,
            _ => &A_SLOW_STALLING_START_IN_A_BATCH,
        };
        // Two ticks, for what the scenario left to end.
        steps.splice(0..0, batch.iter().copied().chain([Step::Tick, Step::Tick]));
    }
    if seed % 4 == 3 {
        steps.splice(
            0..0,
            A_LISTING_BESIDE_A_NEWLY_BUSY_RUNNER
                .iter()
                .copied()
                .chain([Step::Tick, Step::Tick]),
        );
    }
    if seed % 2 == 1 {
        let rarely: &[Step] = match seed % 16 {
            1 => &A_JOB_STAYS_OPEN,
            3 => &A_JOB_STAYS_LISTED,
            5 => &THE_MIRROR_RUNS,
            7 => &A_FORCED_PAUSE,
            9 => &A_BUSY_ORPHAN,
            11 => &AN_OVERSIZED_SNAPSHOT,
            13 => &AN_UNREAD_LEFTOVER,
            _ if seed % 32 == 31 => &UPLOADS_DECIDED,
            _ => &UPLOADS_WAIT_FOR_GITHUB,
        };
        // Two ticks, for what the scenario left to end, so the slots are free for what starts next.
        steps.splice(0..0, rarely.iter().copied().chain([Step::Tick, Step::Tick]));
    }
    steps
}

/// `run`, with a panic reported as the broken invariant `no_panic`, so it keeps its seed and shrinks like any other;
/// its step is not known, and says 0.
async fn attempt(steps: &[Step]) -> Result<Seen, Violation> {
    match AssertUnwindSafe(run(steps)).catch_unwind().await {
        Ok(outcome) => outcome,
        Err(panic) => Err(Violation {
            invariant: "no_panic",
            step: 0,
            detail: panic
                .downcast_ref::<&str>()
                .map(|message| (*message).to_owned())
                .or_else(|| panic.downcast_ref::<String>().cloned())
                .unwrap_or_default(),
        }),
    }
}

/// The shortest sequence found that still breaks what `found` broke: drops chunks of steps, then single steps, while
/// it does.
async fn shrink(mut steps: Vec<Step>, found: Violation) -> (Vec<Step>, Violation) {
    let mut last = found;
    let mut chunk = steps.len() / 2;
    while chunk >= 1 {
        let mut start = 0;
        while start < steps.len() {
            let mut fewer = steps.clone();
            fewer.drain(start..(start + chunk).min(steps.len()));
            match attempt(&fewer).await {
                Err(found) if found.invariant == last.invariant => {
                    steps = fewer;
                    last = found;
                }
                _ => start += chunk,
            }
        }
        chunk /= 2;
    }
    (steps, last)
}

/// What a case in four starts from: under measured admission a light runner runs and a heavy job waits for a host no
/// margin fits; the host then has room between the margins, so the band lets the job go and the next plan starts it.
const BAND_RELEASED: [Step; 10] = [
    Step::Reload(Change::Policy),
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    Step::Sample {
        percent: 10,
        available: 20,
        stalled: false,
    },
    Step::Tick,
    Step::Queue {
        second: false,
        labels: Labels::Heavy,
    },
    Step::Sample {
        percent: 10,
        available: 3,
        stalled: false,
    },
    Step::Tick,
    Step::Sample {
        percent: 10,
        available: 9,
        stalled: false,
    },
    Step::Tick,
    Step::Tick,
];

/// How many of `BAND_RELEASED`'s steps leave the larger margin standing, for the steps after them to work on.
const BAND_STANDS: usize = 7;

/// What every eighth case starts from: three light jobs for two light slots, so the third waits for a slot until the
/// first job ends and the pass after it starts the third's runner, between ticks (ADR 0110).
const SLOT_FREED_BETWEEN_TICKS: [Step; 7] = [
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    Step::Tick,
    Step::Assign(0),
    Step::Finish(0),
    Step::Pass,
];

/// What every other case starts from: under measured admission, a job of `o/r` and one of `o/s` past their first minute
/// and using a tenth of what they reserve, so the steps after it find a credit to take back. A tick takes what the
/// captures found, as a job's first minute starts there, before it can go by.
const TWO_JOBS_SETTLED: [Step; 11] = [
    Step::PastRuns,
    Step::Reload(Change::Policy),
    Step::Queue {
        second: false,
        labels: Labels::Heavy,
    },
    Step::Queue {
        second: true,
        labels: Labels::Heavy,
    },
    Step::Tick,
    Step::Assign(0),
    Step::Assign(0),
    Step::Tick,
    Step::Settle,
    Step::Sample {
        percent: 10,
        available: 50,
        stalled: false,
    },
    Step::Tick,
];

/// What a case in eight starts from: under measured admission, `o/r`'s and `o/s`'s `build` and `o/r`'s `lint`,
/// predicted near their caps, past their first minute and using a tenth of their caps: their headroom passes what the
/// two largest keep, so the host's credit stands for the steps after it to work on (ADR 0108).
const THREE_JOBS_SETTLED: [Step; 17] = [
    Step::PastLargeRuns,
    Step::Reload(Change::Policy),
    Step::Queue {
        second: false,
        labels: Labels::Heavy,
    },
    Step::Queue {
        second: true,
        labels: Labels::Heavy,
    },
    Step::Tick,
    Step::Assign(0),
    Step::Assign(0),
    Step::Tick,
    Step::Settle,
    Step::Sample {
        percent: 10,
        available: 50,
        stalled: false,
    },
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::Settle,
    Step::Sample {
        percent: 10,
        available: 50,
        stalled: false,
    },
    Step::Tick,
];

const HEAVY: Step = Step::Queue {
    second: false,
    labels: Labels::Heavy,
};

/// A sample of a host with room, or `available` gigabytes of it.
const fn host_has(available: u64) -> Step {
    Step::Sample {
        percent: 10,
        available,
        stalled: false,
    }
}

/// Each scenario below starts one case in sixteen, ends with nothing running, and reaches a state no chance sequence
/// reliably does; `Seen` proves it was.
const A_JOB_STAYS_OPEN: [Step; 7] = [
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::RunnerGoes(0),
    Step::Tick,
    Step::OpenJobCompletes(0),
];

const A_JOB_STAYS_LISTED: [Step; 8] = [
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::RunnerGoesStillListed(0),
    Step::Tick,
    Step::Tick,
    Step::OpenJobCompletes(0),
];

const THE_MIRROR_RUNS: [Step; 7] = [
    Step::Reload(Change::Mirror),
    HEAVY,
    Step::Tick,
    Step::Tick,
    Step::Assign(0),
    Step::Finish(0),
    Step::Tick,
];

/// One plan leaves a pool's memory and CPU waits on different jobs. With a heavy runner up, the next heavy job has the
/// memory it needs and lacks CPU; a light job behind it fits and starts, which leaves the last heavy job short of memory,
/// and memory is what `why_waits` asks about first.
const WAITS_ON_DIFFERENT_JOBS: [Step; 16] = [
    Step::Reload(Change::CpuOvercommit),
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    HEAVY,
    Step::Queue {
        second: false,
        labels: Labels::Light,
    },
    HEAVY,
    Step::Tick,
    // The light runner takes the light job and the heavy ones are cancelled, so what comes next finds the slots free.
    Step::Assign(0),
    Step::Cancel(0),
    Step::Cancel(0),
    Step::Finish(0),
    Step::Finish(0),
    Step::Reload(Change::CpuOvercommit),
    Step::Tick,
];

const A_FORCED_PAUSE: [Step; 9] = [
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::ForcedPause { second: false },
    Step::Tick,
    Step::Elapse,
    Step::Tick,
    Step::Resume { second: false },
];

/// ADR 0128: `o/s`'s runner takes its job, which GitHub lists still, and a runners listing shows it busy; then a tick
/// lists `o/r`, active on another phase, and not `o/s`. Each tick comes as the first repository due brings it: `o/r`,
/// active from its first listing, at 5, 11, 18 and 23 s; `o/s`, idle, at 15 s, and active from there at 20 s.
const A_LISTING_BESIDE_A_NEWLY_BUSY_RUNNER: [Step; 13] = [
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::TickSoon { after: 5 },
    Step::TickSoon { after: 3 },
    Step::TickSoon { after: 3 },
    Step::Queue {
        second: true,
        labels: Labels::Heavy,
    },
    Step::TickSoon { after: 2 },
    Step::TickSoon { after: 2 },
    Step::AssignListed(0),
    Step::TickSoon { after: 3 },
    Step::TickSoon { after: 2 },
    Step::TickSoon { after: 3 },
];

const A_BUSY_ORPHAN: [Step; 2] = [Step::BusyOrphan, Step::Tick];

const AN_OVERSIZED_SNAPSHOT: [Step; 5] = [
    Step::OversizedSnapshot,
    Step::Tick,
    host_has(3),
    Step::Tick,
    host_has(50),
];

const AN_UNREAD_LEFTOVER: [Step; 8] = [
    Step::Reload(Change::RecordFailures),
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::Finish(0),
    Step::RestartLogsFail,
    Step::Tick,
];

const UPLOADS_WAIT_FOR_GITHUB: [Step; 11] = [
    Step::UseBuildCache,
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::SaveUnnamed(0),
    Step::RunnerGoes(0),
    Step::Tick,
    Step::Elapse,
    Step::OpenJobCompletes(0),
    Step::Tick,
];

/// As `UPLOADS_WAIT_FOR_GITHUB`, and GitHub then names the job's runner, so the run's trigger decides them.
const UPLOADS_DECIDED: [Step; 10] = [
    Step::UseBuildCache,
    HEAVY,
    Step::Tick,
    Step::Assign(0),
    Step::Tick,
    Step::SaveUnnamed(0),
    Step::RunnerGoes(0),
    Step::Tick,
    Step::RunnerNamed(0),
    Step::Tick,
];

fn env_u64(name: &str) -> Option<u64> {
    std::env::var(name)
        .ok()
        .and_then(|value| value.parse().ok())
}

/// On Tokio's paused clock: the listings' due times and the claims' marks are Tokio instants the model ages by its
/// own time, and real time a case waits behind the others in the batch would move them on top of that.
#[tokio::test(start_paused = true)]
#[expect(
    clippy::print_stderr,
    reason = "names the failing seed before shrinking, which takes a while and may itself fail"
)]
async fn the_scheduler_keeps_its_invariants_over_generated_sequences() {
    let seeds: Vec<u64> = match env_u64("RUNNERD_INVARIANT_SEED") {
        Some(seed) => vec![seed],
        None => (0..env_u64("RUNNERD_INVARIANT_CASES").unwrap_or(CASES)).collect(),
    };
    let mut seen = Seen::default();
    // Cases at once: each waits now and then for its captures, which the others use.
    for batch in seeds.chunks(64) {
        let runs = batch.iter().map(|&seed| async move {
            let steps = steps_of(seed);
            (seed, attempt(&steps).await, steps)
        });
        for (seed, outcome, steps) in futures_util::future::join_all(runs).await {
            if let Ok(case) = &outcome {
                seen.add(*case);
                assert!(
                    seed % 8 != 2 || case.bands > 0,
                    "seed {seed} starts from a job no margin fits, so the larger margin stands"
                );
                assert!(
                    seed % 8 != 6 || case.released > 0,
                    "seed {seed} starts from a job between the margins, so the band lets it go"
                );
                assert!(
                    seed % 2 == 0 || case.credits > 0,
                    "seed {seed} starts from two settled jobs, so it reaches a credit"
                );
                assert!(
                    seed % 8 != 4 || case.host_credits > 0,
                    "seed {seed} starts from three settled jobs, so it reaches a host credit"
                );
            }
            if let Err(found) = outcome {
                // Before shrinking, which may itself fail: the seed alone replays it.
                eprintln!(
                    "seed {seed} breaks {} at step {}: {}; shrinking",
                    found.invariant, found.step, found.detail
                );
                let (invariant, detail) = (found.invariant, found.detail.clone());
                let (shortest, violation) = shrink(steps, found).await;
                panic!(
                    "seed {seed} breaks {invariant}: {detail}\nshrunk to {shortest:#?}\nwhich breaks it at step {}: {}",
                    violation.step, violation.detail
                );
            }
        }
    }
    assert!(
        seen.unreached().is_empty() || seeds.len() == 1,
        "the generated runs never reach {:?}, so nothing checks them",
        seen.unreached()
    );
}

/// Status fields a trace leaves out (`steady_status`).
const UNSTEADY_STATUS: &[&str] = &["seed_memory", "reseeding"];

/// How many rounds without a call to a fake say that a step's background work has ended.
const QUIET_ROUNDS: u32 = 8;

/// Seeds whose trace differed between runs of one binary, over eight runs of each of the first 64 seeds: a comparison
/// leaves them out. Seed 21 differed once, in where a capture's end reads the runner's files; seed 53 once, under
/// load, in where a capture's inspect and exec land.
const TRACE_UNSTABLE: &[u64] = &[21, 53];

/// Writes each seed's trace under `RUNNERD_INVARIANT_TRACE`, for comparing two commits (see the module's documentation).
#[tokio::test]
async fn the_trace_of_each_seed() {
    let Some(directory) = std::env::var_os("RUNNERD_INVARIANT_TRACE") else {
        return;
    };
    let directory = std::path::PathBuf::from(directory);
    std::fs::create_dir_all(&directory).unwrap();
    for seed in (0..env_u64("RUNNERD_INVARIANT_CASES").unwrap_or(CASES))
        .filter(|seed| !TRACE_UNSTABLE.contains(seed))
    {
        let mut case = Case::new();
        case.trace = Some(Vec::new());
        let case = run_case(&steps_of(seed), case)
            .await
            .unwrap_or_else(|found| {
                panic!("seed {seed} breaks {}: {}", found.invariant, found.detail)
            });
        let trace = case.finished_trace().await;
        std::fs::write(directory.join(format!("{seed}.trace")), trace.join("\n")).unwrap();
    }
}

/// Runs `steps` as the generated test does, and returns what broke.
async fn broken(steps: &[Step]) -> Option<(&'static str, String)> {
    run(steps)
        .await
        .err()
        .map(|found| (found.invariant, found.detail))
}

#[tokio::test]
async fn a_daemon_started_with_a_job_queued_starts_the_mirror_for_its_runner() {
    // The restart finds no mirror, and its first tick starts a runner before any tick found the slice empty.
    let steps = [Step::Reload(Change::Mirror), HEAVY, Step::Restart];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_job_taking_a_waiting_runners_room_still_fits_what_the_host_leaves() {
    let steps = [
        // o/s gets a runner, then its job is cancelled: the runner waits for nothing.
        Step::Queue {
            second: true,
            labels: Labels::Heavy,
        },
        Step::Tick,
        Step::Cancel(0),
        // An o/r job comes while the host has 3G available, under its 4G margin: no 4G runner fits.
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Sample {
            percent: 10,
            available: 3,
            stalled: false,
        },
        Step::Tick,
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_job_that_ends_before_its_broken_capture_comes_back_keeps_its_runner_in_the_history() {
    // Shrunk from seeds 4523 and 4496. The capture breaks and Docker cannot inspect the runner, so the job ends first.
    // The stopped container's worker log still names it, and nothing else links the two.
    let broke = [
        Step::Queue {
            second: false,
            labels: Labels::Light,
        },
        Step::CaptureFails { mid_stream: true },
        Step::RestartInspectFails(0),
        Step::InspectFails(1),
        Step::InspectFails(6),
    ];
    // A tick finds it stopped.
    let tick = [Step::Tick, Step::Tick, Step::Assign(3)];
    assert_eq!(broken(&[&broke[..], &tick].concat()).await, None);
    // A pass reaps it before a tick looks.
    let pass = [
        Step::StartFails,
        Step::Tick,
        Step::Tick,
        Step::Assign(3),
        Step::Finish(0),
        Step::Pass,
    ];
    assert_eq!(broken(&[&broke[..], &pass].concat()).await, None);
    // A restart finds it stopped, its capture gone with the last daemon.
    let restart = [
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Reload(Change::Policy),
        Step::InspectFails(5),
        Step::CaptureFails { mid_stream: false },
        Step::Reload(Change::SecondRepository),
        Step::AssignListed(4),
        Step::Finish(4),
        Step::RestartInspectFails(5),
    ];
    assert_eq!(broken(&restart).await, None);
}

#[tokio::test]
async fn a_runner_whose_inspect_fails_after_a_reload_lowered_its_memory_counts_at_its_own_cap() {
    // Shrunk from seed 487: two heavy runners started at 4G; a reload lowers the profile to 2G; a restart cannot read
    // them. Counted at 2G each, the next start would fit caps that add past the budget.
    let heavy = |second| Step::Queue {
        second,
        labels: Labels::Heavy,
    };
    let steps = [
        heavy(false),
        heavy(true),
        Step::Tick,
        Step::Assign(0),
        Step::Assign(0),
        Step::Reload(Change::HeavyMemory),
        Step::RestartInspectFails(7),
        heavy(false),
        Step::Reload(Change::HeavySlots(3)),
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_stopped_runner_that_recovery_cannot_remove_is_removed_later() {
    let steps = [
        Step::Queue {
            second: false,
            labels: Labels::Light,
        },
        Step::Tick,
        Step::Assign(0),
        // The job ends while the daemon is down, and Docker fails the first remove after the restart.
        Step::RemoveFails,
        Step::Finish(0),
        Step::Restart,
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_runner_watched_through_a_failed_inspect_still_records_the_job_it_runs() {
    let steps = [
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Tick,
        // Docker fails the inspects of the runner's container while a restart adopts it.
        Step::InspectFails(0),
        Step::RestartInspectFails(0),
        Step::Assign(0),
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_job_taking_a_waiting_runners_room_still_fits_the_cpu_budget() {
    // Two heavy runners hold 4000 millicores when a reload turns on a CPU budget of 3000. Once a job ends, a queued
    // one may stop the runner left waiting only if its room pays the 1000 past the budget back first.
    let steps = [
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Queue {
            second: true,
            labels: Labels::Heavy,
        },
        Step::Tick,
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Reload(Change::CpuOvercommit),
        Step::AssignListed(1),
        Step::InspectFails(1),
        Step::Finish(2),
        Step::Tick,
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_seed_container_starts_past_a_cpu_budget_a_reload_lowered() {
    // Shrunk from seed 1006. The runners in hold 4000 millicores when a reload turns on a CPU budget of 3000, and the
    // tick that follows starts a seed container, which reserves none.
    let steps = [
        Step::Assign(6),
        Step::Queue {
            second: false,
            labels: Labels::Light,
        },
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Reload(Change::HeavyMemory),
        Step::AssignListed(4),
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Finish(5),
        Step::Reload(Change::LightSlots(1)),
        Step::Reload(Change::HeavySlots(3)),
        Step::Reload(Change::CpuOvercommit),
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_job_taking_a_waiting_runners_room_still_fits_the_slice_under_measured_admission() {
    let steps = [
        // Three heavy slots, so the third job lacks only memory.
        Step::Reload(Change::Policy),
        Step::Reload(Change::HeavySlots(3)),
        // o/s gets a runner, then its job is cancelled: the runner waits for nothing.
        Step::Queue {
            second: true,
            labels: Labels::Heavy,
        },
        Step::Tick,
        Step::Cancel(0),
        // o/r's runner takes a job and uses past its cap: the two take more than the slice's 8.5G.
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Tick,
        Step::Assign(0),
        Step::Sample {
            percent: 120,
            available: 50,
            stalled: false,
        },
        // Stopping the waiting runner pays that back first, which leaves no room for another 4G.
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Tick,
    ];
    assert_eq!(broken(&steps).await, None);
}

#[tokio::test]
async fn a_reseed_starts_only_where_its_seed_container_fits_the_budget() {
    let steps = [
        // A light job runs in light's slot 1, so the light profile is due a reseed once its slots are free.
        Step::Queue {
            second: false,
            labels: Labels::Light,
        },
        Step::Tick,
        Step::Assign(0),
        // Two heavy runners take 8G of the 8.5G; the light seed container's 1G does not fit beside them.
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Finish(0),
        Step::Tick,
    ];
    assert_eq!(broken(&steps).await, None);
}

/// A runner whose log capture fails takes a queued job just before a poll that lists it busy while GitHub still
/// lists its job queued: no second runner starts for that job.
#[tokio::test]
async fn a_runner_first_listed_busy_beside_its_job_still_listed_gets_no_twin() {
    let steps = [
        Step::StartedInspectFails,
        Step::CaptureFails { mid_stream: false },
        Step::Queue {
            second: false,
            labels: Labels::SelfHosted,
        },
        Step::Restart,
        Step::AssignListed(2),
        Step::Reload(Change::LightPool),
    ];
    assert_eq!(broken(&steps).await, None);
}

/// A start whose runner took a listed job and then failed, leaving nothing in Docker, names no job; a pass after
/// another runner went must not start a runner for that job from the listing that still shows it.
#[tokio::test]
async fn a_pass_starts_no_runner_for_a_job_a_failed_start_may_have_taken() {
    let steps = [
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        Step::Queue {
            second: false,
            labels: Labels::Heavy,
        },
        // The first start leaves its container in its slot; the next, in the tick after the restart, takes job 1
        // after that tick's listing, then fails and leaves nothing.
        Step::StartFailsLate {
            takes_job: false,
            cleanup_fails: true,
        },
        Step::Sample {
            percent: 120,
            available: 8,
            stalled: false,
        },
        Step::StartFailsLate {
            takes_job: true,
            cleanup_fails: false,
        },
        Step::Tick,
        Step::Restart,
        // Job 2 runs in the container the first start left, which someone removes: a pass frees its slot.
        Step::Assign(7),
        Step::Lose(5),
        Step::Pass,
    ];
    assert_eq!(broken(&steps).await, None);
}

/// Shrunk from seed 66. The first runner's inspect fails and its container goes, so neither Docker nor its runner
/// row names it to the daemon that restarts; a runner named later must not take its name. Every engine of the case
/// names from one second, as when each restart comes within it, so a restart that loses the first runner's name
/// gives it again, whatever second the case runs in.
#[tokio::test]
async fn a_runner_started_after_a_restart_never_takes_a_name_nothing_recorded() {
    let queue = |second, labels| Step::Queue { second, labels };
    let steps = [
        queue(false, Labels::SelfHosted),
        Step::StartedInspectFails,
        queue(false, Labels::Typo),
        Step::RestartLogsFail,
        Step::CaptureFails { mid_stream: false },
        queue(true, Labels::Empty),
        queue(true, Labels::Heavy),
        Step::RunnerGoes(4),
        Step::AssignListed(1),
        Step::RunnerGoes(4),
        Step::Elapse,
        Step::RestartInspectFails(3),
        Step::CaptureFails { mid_stream: false },
        Step::Reload(Change::SecondRepository),
        Step::Cancel(7),
        Step::Assign(4),
        Step::OpenJobCompletes(2),
        Step::Stop { docker_gone: false },
    ];
    let mut case = Case::new();
    case.names_from = time::now_ms() / 1000 + 3600;
    case.engine.named = case.names_from;
    let broken = run_case(&steps, case)
        .await
        .err()
        .map(|found| (found.invariant, found.detail));
    assert_eq!(broken, None);
}

/// Shrunk from seed 33, which broke main's CI; seed 184 breaks the same way. A heavy runner's launch checks its fit,
/// then waits for its caches and its name while another runner's container starts and the host is read: that reading
/// leaves no room for it, so it must check again before it starts. Under a paused clock the batch's tasks run in the
/// order that shows it on any machine.
#[tokio::test(start_paused = true)]
async fn a_start_fits_a_reading_taken_while_its_launch_waited() {
    let queue = |second, labels| Step::Queue { second, labels };
    let steps = [
        Step::Tick,
        Step::PastRuns,
        Step::Reload(Change::Policy),
        queue(false, Labels::Heavy),
        queue(true, Labels::Heavy),
        Step::Tick,
        Step::Assign(0),
        Step::Assign(3),
        Step::Finish(1),
        Step::SampleDuringStart {
            percent: 50,
            available: 8,
            stalled: false,
        },
        queue(false, Labels::Heavy),
        queue(true, Labels::SelfHosted),
        Step::Assign(5),
        Step::Lose(4),
        Step::Reload(Change::CpuOvercommit),
    ];
    assert_eq!(broken(&steps).await, None);
}

/// Shrunk from seeds 159 and 143. Job 2's runner goes while GitHub still lists it, so the listing after the restart
/// has it after job 4. The tick starts a runner for each, oldest first, and job 2's wait ends; the next plan must name
/// the idle runner for job 2 as well, not for job 4, which still waits for a slot.
#[tokio::test]
async fn an_idle_runner_is_named_for_the_oldest_job_whatever_order_the_listing_gives() {
    let heavy = |second| Step::Queue {
        second,
        labels: Labels::Heavy,
    };
    let steps = [
        heavy(false),
        heavy(true),
        Step::Tick,
        Step::Assign(0),
        Step::Assign(0),
        heavy(false),
        heavy(true),
        Step::Reload(Change::HeavyMemory),
        Step::Reseed { light: false },
        Step::RunnerGoesStillListed(7),
        Step::Reload(Change::PooledCount),
        Step::Finish(3),
        Step::Elapse,
        Step::Reload(Change::PooledCount),
        Step::RestartInspectFails(2),
    ];
    assert_eq!(broken(&steps).await, None);
}

/// Shrunk from seed 170. Job 2's heavy runner went idle, so the last tick has jobs 2 and 3 wait for the host, which
/// fits neither, and starts a light runner for job 4, which fits the plain margin. That start fails to prepare its
/// caches, so the plan after the starts still starts job 4: a waiter that fits, which keeps the plain margin rather
/// than the larger one that would hold job 4 back at the next plan.
#[tokio::test]
async fn a_start_the_tick_did_not_make_keeps_the_plain_margin() {
    let queue = |labels| Step::Queue {
        second: false,
        labels,
    };
    let steps = [
        queue(Labels::Light),
        Step::PrepareFailsMidBatch { after: 2 },
        queue(Labels::Heavy),
        Step::Stop { docker_gone: false },
        queue(Labels::SelfHosted),
        Step::Tick,
        queue(Labels::Light),
        Step::ExitsIdle(7),
        Step::Sample {
            percent: 10,
            available: 6,
            stalled: false,
        },
        Step::Tick,
    ];
    assert_eq!(broken(&steps).await, None);
}

/// Shrunk from seed 298 of a branch whose generator draws differently; it fails the same way on main. A registration
/// refused for the rate limit leaves the client failing every request, so the reload's tick lists nothing and forgets
/// o/r's jobs. The limit then lifts, and a tick 3 s on lists only what is due: o/r keeps the 5 s cadence its failed
/// listing had (ADR 0128), so job 1 is not shown yet, and comes back at the tick that lists o/r again.
#[tokio::test(start_paused = true)]
async fn a_job_a_failed_listing_forgot_is_shown_again_at_the_next_listing_of_its_repository() {
    let heavy = Step::Queue {
        second: false,
        labels: Labels::Heavy,
    };
    let steps = [
        heavy,
        Step::RateLimitedDuringStart { after: 3 },
        heavy,
        Step::RestartLogsFail,
        Step::Stop { docker_gone: false },
        Step::Reload(Change::CpuOvercommit),
        Step::Elapse,
        Step::TickSoon { after: 3 },
        Step::TickSoon { after: 3 },
    ];
    assert_eq!(broken(&steps).await, None);
}