aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
mod context;
mod handle;
pub mod root_lifecycle;
mod single_flight;
pub use context::{ExecutorApp, ExecutorContext};
pub use root_lifecycle::SubcLifecycleAdmission;

use std::{
    collections::{HashMap, HashSet, VecDeque},
    sync::{
        atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering},
        Arc, Weak,
    },
    thread::{self, JoinHandle},
    time::{Duration, Instant},
};

use crossbeam_channel::{Receiver, RecvError, RecvTimeoutError, Sender};
use parking_lot::{Condvar, Mutex, RwLock};
use tokio::sync::oneshot;

use crate::lock_diagnostics::{LockDiagnostics, TrackedMutex};
use crate::{path_identity::ProjectRootId, protocol::Response};

// Mutation lock order: the executor's per-root mutating lane and context epoch
// gate precede source-file admission, then backup and checkpoint locks. Never
// wait for source-file admission while holding a backup/checkpoint lock. The
// scheduler mutex is not held by handlers.
// Multi-file writers admit their complete set in one registry turn, sorted by
// resolved names with native identities covering hard-link aliases; they never
// hold one file while waiting for another. A patch (and a symbol move) may keep
// not-yet-written files admitted during earlier hunks' formatter runs, bounded
// by formatter timeouts. Completed files are released after their last write
// or delete, before their formatter/LSP waits. Single-file writers release
// admission immediately after the atomic write, before formatting/validation.

pub use single_flight::SingleFlight;

const JOB_COST: isize = 1;
/// How long the subc frame loop's scheduler probes (`try_actor_context`,
/// `try_actor_is_idle`, `try_retire_idle_actor_in_background`) wait for the
/// scheduler lock before answering "busy". The lock guards short map
/// updates; a few milliseconds rides out an ordinary holder that was
/// preempted, while a holder stuck for longer cannot stall the loop.
const SCHEDULER_PROBE_WAIT: Duration = Duration::from_millis(5);
#[rustfmt::skip]
test_support_visibility! {
/// Continuous wake producers must not keep the scheduler mutex across an
/// unbounded receiver drain; health probes and submitters get a lock turn
/// between batches.
const SCHEDULER_EVENT_BATCH_CAP: usize = 64;
}
pub const MAINTENANCE_QUEUE_CAP: usize = 512;
const CALLGRAPH_ACQUISITION_REQUEST_ID: &str = "callgraph-view-acquire";

/// Scheduler lane for command-handler execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Lane {
    /// Pure read-only work. Runs under the actor epoch read gate and is capped
    /// per actor.
    PureRead,
    /// LSP/status work. Serialized per actor by scheduler admission while still
    /// using the shared epoch read gate.
    SerialLspStatus,
    /// Heavy lazy initialization. The scheduler acquires a process-wide heavy
    /// permit before dispatch; cache and index builders reject stale generations
    /// and serialize publication internally, so no actor epoch guard wraps the
    /// command or the delivery of its response.
    HeavyInit,
    /// Mutating work. Becomes a writer barrier at the actor queue head, drains
    /// in-flight reads, and runs under the actor epoch write gate. Reserved for
    /// configure and user-initiated tool mutations: background maintenance must
    /// use `MaintenanceCommit` so it can never exclude interactive reads.
    Mutating,
    /// Maintenance work that mutates only subsystem state behind that
    /// subsystem's own lock (watcher/LSP drains, completed-build installs,
    /// callgraph store writes). Runs under the actor epoch READ gate and
    /// overlaps PureReads; serialized to one in-flight per actor so
    /// maintenance cannot self-stack.
    MaintenanceCommit,
    /// Provider discovery and policy-store operations. Serialized per root on
    /// reserved capacity, without an index epoch hold or writer-barrier wait.
    ProviderMetadata,
    /// Call-ledger bookkeeping for keyed tool calls: the row a call writes
    /// before it dispatches, the settlement its terminal reply waits for
    /// before the transport writer may send it, the row reads a repeated call
    /// makes while it waits for that settlement, and the ledger and grant
    /// writes that end a scope. Each job is one short SQLite transaction
    /// behind the database's own mutex and touches no index state, so it takes
    /// no epoch gate and does not wait for readers, LSP or maintenance jobs,
    /// or a running writer. On the Mutating lane it would wait until every
    /// read on its root had drained, and each keyed reply would wait with it.
    /// Running beside a writer such as a configure loses no protection:
    /// `AppContext::open_db` returns the process-shared database handle and
    /// replaces it only when the storage path changes, so ledger jobs of other
    /// roots always ran beside any configure. Jobs run one at a time per actor
    /// in submission order, so one root's ledger writes land in the order they
    /// were queued; a scope end therefore settles every admission queued on
    /// its root before it. Queued ProviderMetadata jobs are cancelled when the
    /// root's last route unbinds; these are not, because a settlement records
    /// a call that already ran.
    CallLedger,
}

const ALL_LANES: [Lane; 7] = [
    Lane::PureRead,
    Lane::SerialLspStatus,
    Lane::HeavyInit,
    Lane::Mutating,
    Lane::MaintenanceCommit,
    Lane::ProviderMetadata,
    Lane::CallLedger,
];

/// Scheduler class used to keep deferrable maintenance from occupying the
/// workers reserved for interactive route binds, tool calls, and bash.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JobClass {
    Interactive,
    Maintenance,
}

/// Idempotent maintenance drains that can share one queued execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MaintenanceCoalesceKey {
    WatcherDrain,
    LspDrain,
    /// Standing maintenance is coalesced inside each actor queue. The executor
    /// already scopes queue state by root, so this key cannot coalesce work for
    /// separate standing roots.
    StandingPass,
    /// A live config reload re-reads the files, so one queued reload covers
    /// every edit made before it runs.
    ConfigReload,
}

pub type ExecutorJob<C> = Box<dyn FnOnce(&C) -> Response + Send + 'static>;

#[rustfmt::skip]
test_support_visibility! {
/// Age at which a queued interactive mutating job (route binds, edits) jumps
/// ahead of pure reads in interactive admission. Reads-first admission would
/// otherwise let a sustained read stream starve queued writers; this bounds
/// that wait. For binds it matches the half-deadline breadcrumb point: the
/// daemon rejects binds at 12s, so promotion at 6s leaves half the budget for
/// draining readers and running the configure itself.
const INTERACTIVE_WRITER_PROMOTION_AGE: Duration = Duration::from_secs(6);
}
#[rustfmt::skip]
test_support_visibility! {
/// Age at which a queued route-bind configure stops new same-root pure reads
/// from being admitted ahead of it. Much shorter than the general writer
/// promotion: a bind is a short configure, and after a daemon restart dozens
/// arrive together, so reads-first admission must not spend the relay budget.
const BIND_PROMOTION_AGE: Duration = Duration::from_millis(500);
}
#[rustfmt::skip]
test_support_visibility! {
/// Worker threads reserved for route-bind configures, on top of `pool_size`.
/// General interactive and maintenance jobs never occupy them, so a bind never
/// waits for another session's long read, bash call, or maintenance tail to
/// release a worker. Two, so a cold root's slower full configure does not
/// serialize every other bind behind it.
const BIND_RESERVE_WORKERS: usize = 2;
}
#[rustfmt::skip]
test_support_visibility! {
/// Provider metadata (tool catalogs, role descriptions, grants) has reserved
/// workers, so these short requests never wait for an index builder,
/// configure writer or maintenance job to free a worker. Callers such as a
/// worker launch check ask for them under a deadline of a few seconds.
const PROVIDER_RESERVE_WORKERS: usize = 2;
}
#[rustfmt::skip]
test_support_visibility! {
/// Readers older than this still block queued writer jobs; report their job
/// metadata instead of only the generic `waiting_on_readers` diagnosis.
const READER_STUCK_CENSUS_AGE: Duration = Duration::from_secs(60);
}
/// Stack for executor worker threads: the standalone main thread's size, so a
/// request that fits there cannot overflow only under the daemon. Stack pages
/// are committed on touch, so idle workers cost nothing extra.
const EXECUTOR_WORKER_STACK_BYTES: usize = 8 * 1024 * 1024;

#[derive(Debug, Clone)]
pub struct ExecutorConfig {
    pub pool_size: usize,
    pub read_cap: usize,
    pub actor_cap: usize,
    pub heavy_permits: usize,
    pub drr_quantum: isize,
}

impl Default for ExecutorConfig {
    fn default() -> Self {
        let available = thread::available_parallelism()
            .map(usize::from)
            .unwrap_or(2);
        let pool_size = available.saturating_sub(1).clamp(2, 8);
        let actor_cap = pool_size.saturating_sub(1).clamp(1, 4);
        let read_cap = actor_cap.clamp(1, 4);
        let heavy_permits = pool_size.saturating_sub(1).clamp(2, 3);

        Self {
            pool_size,
            read_cap,
            actor_cap,
            heavy_permits,
            drr_quantum: 1,
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug, Clone)]
struct EffectiveConfig {
    pool_size: usize,
    read_cap: usize,
    actor_cap: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub heavy_permits: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    heavy_permits: usize,
    drr_quantum: isize,
    deficit_cap: isize,
    interactive_reserve: usize,
    maintenance_cap: usize,
    /// Workers beyond `pool_size` that only route-bind configures may use.
    bind_reserve: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub provider_reserve: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    provider_reserve: usize,
}
}

impl EffectiveConfig {
    #[rustfmt::skip]
    test_support_visibility! {
    /// Every worker thread, including the bind and provider reservations.
    fn total_workers(&self) -> usize {
        self.pool_size + self.bind_reserve + self.provider_reserve
    }

    }
}

impl ExecutorConfig {
    #[rustfmt::skip]
    test_support_visibility! {
    fn effective(&self) -> EffectiveConfig {
        let pool_size = self.pool_size.clamp(2, 8);
        let max_actor_cap = pool_size.saturating_sub(1).max(1);
        let actor_cap = self.actor_cap.max(1).min(max_actor_cap);
        let read_cap = self.read_cap.max(1).min(actor_cap).min(4);
        // HeavyInit jobs share workers with RouteBind/configure. Keep one worker
        // available even in a two-worker pool so a heavy-init storm cannot hold
        // a fresh bind behind every executor worker.
        let heavy_permits = self
            .heavy_permits
            .max(1)
            .min(pool_size.saturating_sub(1).max(1))
            .min(3);
        let drr_quantum = self.drr_quantum.max(1);
        let deficit_cap = (actor_cap.max(1) as isize) * 4;
        let interactive_reserve = if pool_size >= 4 { 2 } else { 1 };
        let maintenance_cap = pool_size.saturating_sub(interactive_reserve).max(1);

        EffectiveConfig {
            pool_size,
            read_cap,
            actor_cap,
            heavy_permits,
            drr_quantum,
            deficit_cap,
            interactive_reserve,
            maintenance_cap,
            bind_reserve: BIND_RESERVE_WORKERS,
            provider_reserve: PROVIDER_RESERVE_WORKERS,
        }
    }

    }
}

/// Synchronous completion handle used by the executor tests and the
/// future standalone bridge.
pub struct CompletionHandle {
    rx: Receiver<Response>,
}

impl CompletionHandle {
    pub fn recv(self) -> Result<Response, RecvError> {
        self.rx.recv()
    }

    pub fn recv_timeout(&self, timeout: Duration) -> Result<Response, RecvTimeoutError> {
        self.rx.recv_timeout(timeout)
    }

    pub fn into_receiver(self) -> Receiver<Response> {
        self.rx
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchClassQueueSnapshot {
    pub queued: usize,
    pub oldest_age_ms: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchRunningSnapshot {
    pub interactive: usize,
    pub maintenance: usize,
    pub completion_owned_interactive: usize,
    pub completion_owned_maintenance: usize,
    /// Age of the oldest maintenance reservation still owned by a dispatched
    /// worker. This distinguishes a blocked worker from a phantom reservation.
    pub oldest_worker_owned_maintenance_age_ms: Option<u64>,
    pub phantom_interactive: usize,
    pub phantom_maintenance: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchLivenessSnapshot {
    pub interactive: DispatchClassQueueSnapshot,
    pub maintenance: DispatchClassQueueSnapshot,
    pub running: DispatchRunningSnapshot,
    pub phantom_running_maintenance: usize,
    pub interactive_reserve: usize,
    pub maintenance_cap: usize,
}

/// Scheduler-owned mirror read by health probes without taking the actor map
/// lock or scanning every root. Oldest queue timestamps use `0` for absent and
/// elapsed-milliseconds-plus-one for a present timestamp.
struct DispatchLivenessAtomics {
    origin: Instant,
    interactive_queued: AtomicUsize,
    interactive_oldest_enqueued_ms_plus_one: AtomicU64,
    maintenance_queued: AtomicUsize,
    maintenance_oldest_enqueued_ms_plus_one: AtomicU64,
    interactive_running: AtomicUsize,
    maintenance_running: AtomicUsize,
    completion_owned_interactive: AtomicUsize,
    completion_owned_maintenance: AtomicUsize,
    oldest_worker_owned_maintenance_started_ms_plus_one: AtomicU64,
    phantom_interactive: AtomicUsize,
    phantom_maintenance: AtomicUsize,
}

impl DispatchLivenessAtomics {
    fn new() -> Self {
        Self {
            origin: Instant::now(),
            interactive_queued: AtomicUsize::new(0),
            interactive_oldest_enqueued_ms_plus_one: AtomicU64::new(0),
            maintenance_queued: AtomicUsize::new(0),
            maintenance_oldest_enqueued_ms_plus_one: AtomicU64::new(0),
            interactive_running: AtomicUsize::new(0),
            maintenance_running: AtomicUsize::new(0),
            completion_owned_interactive: AtomicUsize::new(0),
            completion_owned_maintenance: AtomicUsize::new(0),
            oldest_worker_owned_maintenance_started_ms_plus_one: AtomicU64::new(0),
            phantom_interactive: AtomicUsize::new(0),
            phantom_maintenance: AtomicUsize::new(0),
        }
    }

    fn now_ms(&self) -> u64 {
        duration_millis_u64(self.origin.elapsed())
    }

    fn record(&self, snapshot: &DispatchLivenessSnapshot) {
        let now_ms = self.now_ms();
        let encode_oldest = |queued: usize, oldest_age_ms: Option<u64>| {
            if queued == 0 {
                0
            } else {
                now_ms
                    .saturating_sub(oldest_age_ms.unwrap_or(0))
                    .saturating_add(1)
            }
        };
        self.interactive_oldest_enqueued_ms_plus_one.store(
            encode_oldest(
                snapshot.interactive.queued,
                snapshot.interactive.oldest_age_ms,
            ),
            Ordering::Relaxed,
        );
        self.maintenance_oldest_enqueued_ms_plus_one.store(
            encode_oldest(
                snapshot.maintenance.queued,
                snapshot.maintenance.oldest_age_ms,
            ),
            Ordering::Relaxed,
        );
        self.interactive_running
            .store(snapshot.running.interactive, Ordering::Release);
        self.maintenance_running
            .store(snapshot.running.maintenance, Ordering::Release);
        self.completion_owned_interactive.store(
            snapshot.running.completion_owned_interactive,
            Ordering::Release,
        );
        self.completion_owned_maintenance.store(
            snapshot.running.completion_owned_maintenance,
            Ordering::Release,
        );
        self.oldest_worker_owned_maintenance_started_ms_plus_one
            .store(
                encode_oldest(
                    snapshot.running.completion_owned_maintenance,
                    snapshot.running.oldest_worker_owned_maintenance_age_ms,
                ),
                Ordering::Relaxed,
            );
        self.phantom_interactive
            .store(snapshot.running.phantom_interactive, Ordering::Release);
        self.phantom_maintenance
            .store(snapshot.running.phantom_maintenance, Ordering::Release);
        self.interactive_queued
            .store(snapshot.interactive.queued, Ordering::Release);
        self.maintenance_queued
            .store(snapshot.maintenance.queued, Ordering::Release);
    }

    fn snapshot(&self, config: &EffectiveConfig) -> DispatchLivenessSnapshot {
        let now_ms = self.now_ms();
        let decode_oldest = |queued: usize, encoded: u64| {
            (queued > 0 && encoded > 0).then(|| now_ms.saturating_sub(encoded - 1))
        };
        let interactive_queued = self.interactive_queued.load(Ordering::Acquire);
        let maintenance_queued = self.maintenance_queued.load(Ordering::Acquire);
        DispatchLivenessSnapshot {
            interactive: DispatchClassQueueSnapshot {
                queued: interactive_queued,
                oldest_age_ms: decode_oldest(
                    interactive_queued,
                    self.interactive_oldest_enqueued_ms_plus_one
                        .load(Ordering::Relaxed),
                ),
            },
            maintenance: DispatchClassQueueSnapshot {
                queued: maintenance_queued,
                oldest_age_ms: decode_oldest(
                    maintenance_queued,
                    self.maintenance_oldest_enqueued_ms_plus_one
                        .load(Ordering::Relaxed),
                ),
            },
            running: DispatchRunningSnapshot {
                interactive: self.interactive_running.load(Ordering::Acquire),
                maintenance: self.maintenance_running.load(Ordering::Acquire),
                completion_owned_interactive: self
                    .completion_owned_interactive
                    .load(Ordering::Acquire),
                completion_owned_maintenance: self
                    .completion_owned_maintenance
                    .load(Ordering::Acquire),
                oldest_worker_owned_maintenance_age_ms: decode_oldest(
                    self.completion_owned_maintenance.load(Ordering::Acquire),
                    self.oldest_worker_owned_maintenance_started_ms_plus_one
                        .load(Ordering::Relaxed),
                ),
                phantom_interactive: self.phantom_interactive.load(Ordering::Acquire),
                phantom_maintenance: self.phantom_maintenance.load(Ordering::Acquire),
            },
            phantom_running_maintenance: self.phantom_maintenance.load(Ordering::Acquire),
            interactive_reserve: config.interactive_reserve,
            maintenance_cap: config.maintenance_cap,
        }
    }
}

/// Progress marker for the scheduler (dispatch) loop, read by the subc stall
/// watchdog from its own thread. Everything here is an atomic or a channel
/// length read, so reading it never waits on the scheduler state mutex that a
/// stalled loop may be blocked on or holding.
pub struct DispatchLoopLiveness<C: ExecutorContext> {
    #[cfg(any(test, feature = "test-support"))]
    pub origin: Instant,
    #[cfg(not(any(test, feature = "test-support")))]
    origin: Instant,
    #[cfg(any(test, feature = "test-support"))]
    /// Milliseconds since `origin` when the loop last became ready to receive
    /// or finished an event.
    pub last_progress_ms: AtomicU64,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Milliseconds since `origin` when the loop last became ready to receive
    /// or finished an event.
    last_progress_ms: AtomicU64,
    #[cfg(any(test, feature = "test-support"))]
    /// True from channel readiness (or a due retry) until the loop has
    /// processed the event and released the scheduler lock.
    pub in_event: AtomicBool,
    #[cfg(not(any(test, feature = "test-support")))]
    /// True from channel readiness (or a due retry) until the loop has
    /// processed the event and released the scheduler lock.
    in_event: AtomicBool,
    #[cfg(any(test, feature = "test-support"))]
    /// Clone of the scheduler's event receiver. Readiness waits and watchdog
    /// queue checks never dequeue; only the scheduler consumes events.
    pub event_rx: Receiver<SchedulerEvent<C>>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Clone of the scheduler's event receiver. Readiness waits and watchdog
    /// queue checks never dequeue; only the scheduler consumes events.
    event_rx: Receiver<SchedulerEvent<C>>,
}

impl<C: ExecutorContext> DispatchLoopLiveness<C> {
    #[rustfmt::skip]
    test_support_visibility! {
    fn new(event_rx: Receiver<SchedulerEvent<C>>) -> Self {
        Self {
            origin: Instant::now(),
            last_progress_ms: AtomicU64::new(0),
            in_event: AtomicBool::new(false),
            event_rx,
        }
    }
    }

    fn now_ms(&self) -> u64 {
        duration_millis_u64(self.origin.elapsed())
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn wait_for_event(&self, next_retry_at: Option<Instant>) -> bool {
        let mut select = crossbeam_channel::Select::new();
        select.recv(&self.event_rx);
        let ready = match next_retry_at {
            Some(at) => select
                .ready_timeout(at.saturating_duration_since(Instant::now()))
                .is_ok(),
            None => {
                select.ready();
                true
            }
        };
        // Readiness does not dequeue. Publish the active marker first so the
        // watchdog cannot see an empty queue with an unmarked received event.
        self.begin_event();
        ready
    }
    }

    fn begin_event(&self) {
        self.last_progress_ms
            .store(self.now_ms(), Ordering::Relaxed);
        self.in_event.store(true, Ordering::Release);
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn end_event(&self) {
        self.last_progress_ms
            .store(self.now_ms(), Ordering::Relaxed);
        self.in_event.store(false, Ordering::Release);
    }
    }

    /// Time since the loop last became ready to receive or finished an event.
    pub fn progress_age(&self) -> Duration {
        let last = self.last_progress_ms.load(Ordering::Relaxed);
        Duration::from_millis(self.now_ms().saturating_sub(last))
    }

    /// The loop owes work when it is inside an event or events are queued for
    /// it. An idle scheduler waiting for readiness with an empty channel owes
    /// nothing, however long ago it last ran.
    pub fn has_pending_work(&self) -> bool {
        // Sample the queue before the marker: receiving the last queued event
        // publishes the marker before emptying the queue.
        !self.event_rx.is_empty() || self.in_event.load(Ordering::Acquire)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MutatingLaneSnapshot {
    pub root_id: ProjectRootId,
    pub request_id: String,
    pub command: String,
    pub started_age_ms: u64,
}

/// Scheduler occupants of one root, including jobs still waiting to enter
/// their callback. Each call has a unique cancellation token, which distinguishes
/// it from an older job that reused the same transport request ID.
#[derive(Debug, Clone)]
pub struct RootJobSnapshot {
    pub job_id: u64,
    pub request_id: String,
    pub command: String,
    pub lane: Lane,
    pub started_age_ms: u64,
    pub execution_started: bool,
    pub is_current: bool,
}

/// Non-blocking scheduler explanation attached to a delayed RouteBind warning.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindBlockerReaderSnapshot {
    pub request_id: String,
    pub command: String,
    pub lane: Lane,
    pub started_age_ms: u64,
    pub execution_started: bool,
    pub started_before_oldest_writer: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindBlockerSnapshot {
    pub configure_state: &'static str,
    pub configure_phase_timings: Option<String>,
    pub blockers: Vec<String>,
    pub oldest_queued_writer_age_ms: Option<u64>,
    pub in_flight_readers: Vec<BindBlockerReaderSnapshot>,
    pub in_flight_writer: Option<MutatingLaneSnapshot>,
    pub reader_admissions_while_promoted_writer_waited: u64,
}

/// Cooperative cancellation for one cancellable executor job.
///
/// One atomic state machine (pending → running → committed | cancelled) is
/// shared by the executor, the canceller, and the job. `cancel` and
/// `try_seal_committed` race through compare-exchange on the same cell, so
/// exactly one wins: a cancel that lands first makes the seal fail (the job
/// must abort before mutating), and a seal that lands first makes the cancel
/// report `RunningCommitted` (the mutation tail finishes normally). A job
/// observes cancellation only at its own checkpoints
/// ([`JobCancellation::cancel_requested_before_commit`]).
#[derive(Debug, Clone)]
pub struct JobCancellation {
    #[cfg(any(test, feature = "test-support"))]
    pub inner: Arc<JobCancellationInner>,
    #[cfg(not(any(test, feature = "test-support")))]
    inner: Arc<JobCancellationInner>,
    root: Option<Arc<std::path::PathBuf>>,
    lifecycle: Option<crate::executor::root_lifecycle::SubcLifecycleAdmission>,
}

#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug)]
struct JobCancellationInner {
    state: AtomicU8,
    progress: Mutex<Option<crate::tool_progress::Progress>>,
    wait_lock: Mutex<()>,
    wake: Condvar,
    #[cfg(any(test, feature = "test-support"))]
    pub root_probe_barrier: Mutex<Option<(Sender<()>, Receiver<()>)>>,
}
}

const JOB_CANCEL_STATE_PENDING: u8 = 0;
const JOB_CANCEL_STATE_RUNNING: u8 = 1;
const JOB_CANCEL_STATE_COMMITTED: u8 = 2;
const JOB_CANCEL_STATE_CANCELLED: u8 = 3;

impl JobCancellation {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(JobCancellationInner {
                state: AtomicU8::new(JOB_CANCEL_STATE_PENDING),
                progress: Mutex::new(None),
                wait_lock: Mutex::new(()),
                wake: Condvar::new(),
                #[cfg(any(test, feature = "test-support"))]
                root_probe_barrier: Mutex::new(None),
            }),
            root: None,
            lifecycle: None,
        }
    }

    pub fn with_root(mut self, root: &std::path::Path) -> Self {
        self.root = Some(Arc::new(root.to_path_buf()));
        self
    }

    pub fn set_progress(&self, progress: crate::tool_progress::Progress) {
        *self.inner.progress.lock() = Some(progress);
    }

    pub fn has_progress_channel(&self, key: usize) -> bool {
        self.inner
            .progress
            .lock()
            .as_ref()
            .is_some_and(|progress| progress.key() == key)
    }

    pub fn report_progress(&self) {
        if !self.cancel_already_requested() {
            let progress = self.inner.progress.lock().clone();
            if let Some(progress) = progress {
                progress.report();
            }
        }
    }

    pub fn with_lifecycle(
        mut self,
        lifecycle: crate::executor::root_lifecycle::SubcLifecycleAdmission,
    ) -> Self {
        self.lifecycle = Some(lifecycle);
        self
    }

    pub fn fresh(&self) -> Self {
        let mut token = Self::new();
        token.root = self.root.clone();
        token.lifecycle = self.lifecycle.clone();
        token
    }

    fn mark_running(&self) -> bool {
        match self.inner.state.compare_exchange(
            JOB_CANCEL_STATE_PENDING,
            JOB_CANCEL_STATE_RUNNING,
            Ordering::SeqCst,
            Ordering::SeqCst,
        ) {
            Ok(_) => true,
            Err(state) => state != JOB_CANCEL_STATE_CANCELLED,
        }
    }

    /// Undo [`JobCancellation::mark_running`] for a job that is being queued
    /// again without having committed. Returns false when a cancel already
    /// won, in which case the job must be settled as cancelled instead.
    fn return_to_pending(&self) -> bool {
        match self.inner.state.compare_exchange(
            JOB_CANCEL_STATE_RUNNING,
            JOB_CANCEL_STATE_PENDING,
            Ordering::SeqCst,
            Ordering::SeqCst,
        ) {
            Ok(_) => true,
            Err(state) => {
                debug_assert_ne!(
                    state, JOB_CANCEL_STATE_COMMITTED,
                    "a bind queued again must not have committed"
                );
                state == JOB_CANCEL_STATE_PENDING
            }
        }
    }

    fn try_cancel_before_running(&self) -> bool {
        let cancelled = self
            .inner
            .state
            .compare_exchange(
                JOB_CANCEL_STATE_PENDING,
                JOB_CANCEL_STATE_CANCELLED,
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .is_ok();
        if cancelled {
            let _wait_guard = self.inner.wait_lock.lock();
            self.inner.wake.notify_all();
        }
        cancelled
    }

    /// Seal the job as committed. Returns `false` when a cancel already won
    /// the race: the job must return early WITHOUT mutating, because the
    /// canceller was told `RunningSignalled` and will discard its completion.
    #[must_use]
    pub fn try_seal_committed(&self) -> bool {
        loop {
            let current = self.state();
            match current {
                JOB_CANCEL_STATE_CANCELLED => return false,
                JOB_CANCEL_STATE_COMMITTED => return true,
                _ => {
                    if self
                        .inner
                        .state
                        .compare_exchange(
                            current,
                            JOB_CANCEL_STATE_COMMITTED,
                            Ordering::SeqCst,
                            Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        return true;
                    }
                }
            }
        }
    }

    /// Move to cancelled unless the job already sealed its commit. Returns the
    /// state the transition observed (`COMMITTED` when the seal won).
    fn signal_cancel(&self) -> u8 {
        let observed = loop {
            let current = self.state();
            match current {
                JOB_CANCEL_STATE_COMMITTED | JOB_CANCEL_STATE_CANCELLED => break current,
                _ => {
                    if self
                        .inner
                        .state
                        .compare_exchange(
                            current,
                            JOB_CANCEL_STATE_CANCELLED,
                            Ordering::SeqCst,
                            Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        break current;
                    }
                }
            }
        };
        if observed != JOB_CANCEL_STATE_COMMITTED {
            let _wait_guard = self.inner.wait_lock.lock();
            self.inner.wake.notify_all();
        }
        if observed != JOB_CANCEL_STATE_COMMITTED {
            crate::cold_build_limiter::progress::cancel_token(self.progress_key());
        }
        observed
    }

    fn state(&self) -> u8 {
        self.inner.state.load(Ordering::SeqCst)
    }

    /// Request cooperative cancellation without requiring an executor actor.
    /// Detached continuations use this after their setup job has already left
    /// the scheduler's running-job table.
    pub fn request_cancel(&self) {
        self.signal_cancel();
    }

    pub(crate) fn progress_key(&self) -> usize {
        Arc::as_ptr(&self.inner) as usize
    }

    /// True when a cancel has already won the state race. A pure read: unlike
    /// [`Self::cancel_requested_before_commit`] it never checks the root on
    /// disk or the abandon grace and never signals, so it is safe to call
    /// while holding `wait_lock` and from observers such as health reports.
    pub fn cancel_already_requested(&self) -> bool {
        self.state() == JOB_CANCEL_STATE_CANCELLED
    }

    /// True when a cancel won the state race and the job must abort.
    ///
    /// This also cancels the job when its root was deleted or abandoned, which
    /// signals and so takes `wait_lock`. Never call it while holding that lock
    /// (it is not reentrant), and keep it out of read-only observers.
    pub fn cancel_requested_before_commit(&self) -> bool {
        let state = self.state();
        match state {
            JOB_CANCEL_STATE_CANCELLED => return true,
            JOB_CANCEL_STATE_COMMITTED => return false,
            _ => {}
        }
        if let Some(lifecycle) = &self.lifecycle {
            lifecycle.cancel_if_abandoned(|| self.request_cancel());
            if self.cancel_already_requested() {
                return true;
            }
        }
        if self.root.is_none() {
            return false;
        }
        // Every checkpoint observes explicit cancellation and the in-memory
        // lifecycle signal. Only the filesystem deletion probe is bounded to
        // one per 256 checkpoints or 50ms on each worker, whichever comes
        // first. A weak identity prevents a new token reusing an allocation
        // from inheriting the previous job's delay.
        // The first running checkpoint probes again after admission: setup may
        // have blocked before the command got a chance to observe its root.
        thread_local! {
            static LAST_PROBE: std::cell::RefCell<Option<(std::sync::Weak<JobCancellationInner>, u8, u16, Instant)>> =
                const { std::cell::RefCell::new(None) };
        }
        let probe = LAST_PROBE.with(|slot| {
            let mut last = slot.borrow_mut();
            if let Some((identity, previous_state, items, when)) = last.as_mut() {
                if identity.as_ptr() == Arc::as_ptr(&self.inner) && *previous_state == state {
                    *items += 1;
                    #[cfg(not(any(test, feature = "test-support")))]
                    let elapsed = when.elapsed();
                    #[cfg(any(test, feature = "test-support"))]
                    let elapsed = crate::executor::audit::audit_cancel_elapsed(*when);
                    if *items < 256 && elapsed < Duration::from_millis(50) {
                        return false;
                    }
                    *items = 0;
                    *when = Instant::now();
                    return true;
                }
            }
            *last = Some((Arc::downgrade(&self.inner), state, 0, Instant::now()));
            true
        });
        #[cfg(any(test, feature = "test-support"))]
        let barrier = self.inner.root_probe_barrier.lock().take();
        #[cfg(any(test, feature = "test-support"))]
        let probe = probe || barrier.is_some();
        if !probe {
            return self.state() == JOB_CANCEL_STATE_CANCELLED;
        }
        #[cfg(any(test, feature = "test-support"))]
        crate::executor::audit::audit_record(|work| work.cancel_probes += 1);
        #[cfg(any(test, feature = "test-support"))]
        {
            if let Some((parked, release)) = barrier {
                parked.send(()).unwrap();
                release.recv().unwrap();
            }
        }
        // A deleted checkout cannot publish useful work. Check here as well as
        // at admission so deletion during a batch does not wait for the reaper.
        // Permission/transient I/O failures do not prove that it was deleted.
        if self
            .root
            .as_ref()
            .is_some_and(|root| match std::fs::metadata(root.as_path()) {
                Ok(metadata) => !metadata.is_dir(),
                Err(error) => matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ),
            })
        {
            self.request_cancel();
        }
        self.state() == JOB_CANCEL_STATE_CANCELLED
    }

    /// Sleep until cancellation is requested or the timeout expires.
    ///
    /// Cancellation takes the same lock before notifying, so a waiter cannot
    /// miss a signal between its state check and the condition-variable wait.
    pub fn wait_for_cancellation(&self, timeout: Duration) -> bool {
        if self.cancel_requested_before_commit() {
            return true;
        }
        {
            let mut guard = self.inner.wait_lock.lock();
            // Only the pure state read may run under `wait_lock`: the full check
            // can decide the root is deleted or abandoned and signal, and
            // signalling takes this same lock. Doing that here deadlocked the
            // waiting job and then every caller that signalled it, including
            // the health report on the module's frame loop.
            if self.cancel_already_requested() {
                return true;
            }
            self.inner.wake.wait_for(&mut guard, timeout);
        }
        self.cancel_requested_before_commit()
    }

    fn same_token(&self, other: &JobCancellation) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

/// Outcome of [`Executor::cancel_job`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JobCancelOutcome {
    /// The job had not started; it was removed from the queue and its
    /// completion settled with `request_cancelled`.
    QueuedRemoved,
    /// The job is running; its token is signalled and the job returns through
    /// its normal completion path at the next checkpoint.
    RunningSignalled,
    /// The job already sealed its commit; it finishes normally and the caller
    /// must discard its late completion.
    RunningCommitted,
    /// No queued or tracked job matched the token.
    NotFound,
}

/// Result of cancelling only work whose command closure has not started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreExecutionCancelOutcome {
    QueuedRemoved,
    DispatchedCancelled,
    AlreadyStarted,
}

thread_local! {
    static CURRENT_JOB_CANCELLATION: std::cell::RefCell<Option<JobCancellation>> =
        const { std::cell::RefCell::new(None) };
}

/// The cancellation token of the job running on this worker thread, when the
/// job was submitted through [`Executor::submit_cancellable_async`].
pub fn current_job_cancellation() -> Option<JobCancellation> {
    CURRENT_JOB_CANCELLATION.with(|slot| slot.borrow().clone())
}

pub fn current_job_cancelled() -> bool {
    CURRENT_JOB_CANCELLATION.with(|slot| {
        slot.borrow()
            .as_ref()
            .is_some_and(JobCancellation::cancel_requested_before_commit)
    })
}

pub struct JobCancellationContextGuard {
    previous: Option<JobCancellation>,
}

impl JobCancellationContextGuard {
    fn install(token: Option<JobCancellation>) -> Self {
        let previous = CURRENT_JOB_CANCELLATION.with(|slot| slot.replace(token));
        Self { previous }
    }
}

impl Drop for JobCancellationContextGuard {
    fn drop(&mut self) {
        CURRENT_JOB_CANCELLATION.with(|slot| {
            *slot.borrow_mut() = self.previous.take();
        });
    }
}

/// Install a cancellable executor job's token on a continuation thread.
///
/// Executor workers install this automatically. A setup job that hands work to
/// a detached thread must install the same token there so existing cooperative
/// checkpoints keep observing route or transport abandonment.
pub fn install_job_cancellation(token: JobCancellation) -> JobCancellationContextGuard {
    JobCancellationContextGuard::install(Some(token))
}

/// The writer demand of one actor as seen by a job running on it: interactive
/// writers still queued, and detached threads waiting to write the actor's
/// epoch gate (content-addressed view publication).
#[derive(Clone)]
struct ActorWriterDemand {
    queued: Arc<AtomicUsize>,
    detached: Option<Arc<AtomicUsize>>,
}

impl ActorWriterDemand {
    fn waiting(&self) -> bool {
        self.queued.load(Ordering::Acquire) > 0
            || self
                .detached
                .as_ref()
                .is_some_and(|detached| detached.load(Ordering::Acquire) > 0)
    }
}

thread_local! {
    static CURRENT_ACTOR_WAITING_WRITERS: std::cell::RefCell<Option<ActorWriterDemand>> =
        const { std::cell::RefCell::new(None) };
}

/// True when interactive mutating work (a route-bind configure or a tool
/// edit) is queued on the actor whose job runs on this worker thread, or a
/// detached view publication is parked waiting to write the actor's epoch.
///
/// A long maintenance job holds its actor's epoch read gate, and a queued
/// writer can only start once that gate is free. Maintenance that runs in
/// resumable steps polls this between steps and hands the actor back instead
/// of making the writer wait for the whole job. The parked publication counts
/// too: the epoch lock is task-fair, so while that thread waits every new
/// reader of the actor (reads, shared route binds, the next tail unit) is
/// held behind it, and its write is a short install once the gate is free.
/// Always false off an executor worker.
pub fn current_actor_writer_waiting() -> bool {
    CURRENT_ACTOR_WAITING_WRITERS.with(|slot| {
        slot.borrow()
            .as_ref()
            .is_some_and(ActorWriterDemand::waiting)
    })
}

#[rustfmt::skip]
test_support_visibility! {
pub(crate) struct ActorWaitingWritersGuard {
    previous: Option<ActorWriterDemand>,
}
}

impl ActorWaitingWritersGuard {
    fn install(demand: ActorWriterDemand) -> Self {
        let previous = CURRENT_ACTOR_WAITING_WRITERS.with(|slot| slot.replace(Some(demand)));
        Self { previous }
    }
}

impl Drop for ActorWaitingWritersGuard {
    fn drop(&mut self) {
        CURRENT_ACTOR_WAITING_WRITERS.with(|slot| {
            *slot.borrow_mut() = self.previous.take();
        });
    }
}

/// Make [`current_actor_writer_waiting`] report the given counter on this
/// thread, for tests that run a maintenance step outside an executor worker.
#[cfg(any(test, feature = "test-support"))]
pub fn install_actor_waiting_writers_for_test(
    waiting: Arc<AtomicUsize>,
) -> ActorWaitingWritersGuard {
    ActorWaitingWritersGuard::install(ActorWriterDemand {
        queued: waiting,
        detached: None,
    })
}

/// A route-bind job that can run more than once. The scheduler may admit such
/// a bind beside a running maintenance job or interactive readers with only a
/// shared hold on the actor's epoch gate; when the configure finds it must change the root, the
/// run is discarded and the same job is queued again as an exclusive writer.
pub type RepeatableJob<C> = Arc<dyn Fn(&C) -> Response + Send + Sync + 'static>;

thread_local! {
    /// True while the job on this worker is a route bind holding its actor's
    /// epoch gate only for reading.
    static CURRENT_BIND_GATE_SHARED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// Set by a shared-hold bind that needs exclusive use of its actor.
    static EXCLUSIVE_RERUN_REQUESTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Marks the job on this worker as a shared-hold bind for its lifetime.
struct SharedBindScope;

impl SharedBindScope {
    fn install() -> Self {
        CURRENT_BIND_GATE_SHARED.with(|shared| shared.set(true));
        EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(false));
        Self
    }

    /// True when the job asked, through [`request_exclusive_rerun`], to be run
    /// again with exclusive use of the actor.
    fn rerun_requested(&self) -> bool {
        EXCLUSIVE_RERUN_REQUESTED.with(std::cell::Cell::get)
    }
}

impl Drop for SharedBindScope {
    fn drop(&mut self) {
        CURRENT_BIND_GATE_SHARED.with(|shared| shared.set(false));
        EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(false));
    }
}

/// True while the job on this worker is a route bind that holds its actor's
/// epoch gate only for reading.
///
/// Most route binds re-attach a session to a root whose configuration is
/// unchanged. That rebind only reads the published configuration and records
/// the session in state behind its own locks, so it is safe next to readers,
/// and making it wait for exclusive use would park it behind a configure tail
/// unit that can run for many seconds on a large root, or behind a slow
/// interactive read for as long as that read runs. Such a bind starts with a
/// shared hold beside whatever already holds the gate for reading; a
/// configure that turns out to change the root calls
/// [`request_exclusive_rerun`] before its first change to actor state.
pub fn current_bind_gate_is_shared() -> bool {
    CURRENT_BIND_GATE_SHARED.with(std::cell::Cell::get)
}

/// Ask for the shared-hold bind on this worker to be run again as an exclusive
/// writer. Returns false (and does nothing) for every other job.
///
/// The caller must return at once, without changing actor state: the executor
/// discards the response, frees the worker, and queues the same job at the
/// head of the actor's binds, where it counts as a waiting writer (so a
/// running configure tail steps aside at its next unit) and is admitted once
/// no reader or maintenance job holds the gate. The rerun starts from
/// scratch and observes whatever changed meanwhile. No worker ever waits for
/// the actor on the bind's behalf.
pub fn request_exclusive_rerun() -> bool {
    if !current_bind_gate_is_shared() {
        return false;
    }
    EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(true));
    true
}

#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug, Clone)]
struct RunningJob {
    #[cfg(any(test, feature = "test-support"))]
    pub root_id: ProjectRootId,
    #[cfg(not(any(test, feature = "test-support")))]
    root_id: ProjectRootId,
    #[cfg(any(test, feature = "test-support"))]
    pub request_id: String,
    #[cfg(not(any(test, feature = "test-support")))]
    request_id: String,
    command: String,
    job_class: JobClass,
    lane: Lane,
    #[cfg(any(test, feature = "test-support"))]
    pub started_at: Instant,
    #[cfg(not(any(test, feature = "test-support")))]
    started_at: Instant,
    #[cfg(any(test, feature = "test-support"))]
    pub execution_started: Arc<AtomicBool>,
    #[cfg(not(any(test, feature = "test-support")))]
    execution_started: Arc<AtomicBool>,
    completion_ownership: Weak<JobCompletionOwnership>,
    occupancy_reported: bool,
    cancellation: Option<JobCancellation>,
}
}

#[derive(Debug, Clone)]
pub struct LongRunningInteractiveJobSnapshot {
    pub root_id: ProjectRootId,
    pub request_id: String,
    pub command: String,
    pub lane: Lane,
    pub age: Duration,
    pub execution_started: bool,
}

#[derive(Debug, Clone)]
struct RunningMutatingJob {
    request_id: String,
    command: String,
    started_at: Instant,
}

/// Concurrent scheduler-dispatch executor.
pub struct Executor<C: ExecutorContext> {
    #[cfg(any(test, feature = "test-support"))]
    pub inner: Arc<ExecutorInner<C>>,
    #[cfg(not(any(test, feature = "test-support")))]
    inner: Arc<ExecutorInner<C>>,
}

/// A root may submit maintenance without keeping its owning executor alive.
/// The weak link avoids a cycle through the executor's actor context.
#[derive(Clone)]
pub struct RootMaintenanceExecutor {
    inner: Arc<dyn MaintenanceSubmit>,
}

type MaintenanceJob = Box<dyn FnOnce() -> Response + Send + 'static>;

trait MaintenanceSubmit: Send + Sync {
    fn submit_maintenance(
        &self,
        request_id: &str,
        lane: Lane,
        cancellation: JobCancellation,
        job: MaintenanceJob,
    ) -> bool;
}

struct TypedMaintenanceExecutor<C: ExecutorContext> {
    inner: std::sync::Weak<ExecutorInner<C>>,
    root_id: ProjectRootId,
}

struct SubmissionExecutor<C: ExecutorContext>(Option<Executor<C>>);

impl<C: ExecutorContext> Drop for SubmissionExecutor<C> {
    fn drop(&mut self) {
        let executor = self.0.take();
        if current_thread_is_executor_worker() {
            // Shutdown may leave this temporary as the last executor owner.
            // Other workers can depend on this worker returning, so release
            // the temporary off-worker rather than joining them here.
            std::thread::spawn(move || drop(executor));
        }
    }
}

impl RootMaintenanceExecutor {
    fn new<C: ExecutorContext>(
        inner: std::sync::Weak<ExecutorInner<C>>,
        root_id: ProjectRootId,
    ) -> Self {
        Self {
            inner: Arc::new(TypedMaintenanceExecutor::<C> { inner, root_id }),
        }
    }
    /// Admits `job` as this root's maintenance and runs it at once on the
    /// calling thread, with the root's cancellation installed as the current
    /// job's: `cancellation` gains the root and its bind lifecycle, so a root
    /// unbinding cancels whatever the job starts at its checkpoints. The
    /// executor refuses the job, and drops it unrun, under the same rules as
    /// a maintenance job on a worker: the root is unbound, its folder is
    /// gone, its actor is not registered or failed, or the token is already
    /// cancelled. `false` when the executor has shut down; the caller must
    /// not run the work some other way, which would reactivate a retired
    /// root.
    ///
    /// The data layer's background work is the only caller, and its job only
    /// hands the work to a pool of its own threads. The job does not wait
    /// for a worker: a call-graph read waits on a worker for the build or
    /// refresh it asked for, and the scheduler keeps its last
    /// `interactive_reserve` general workers from maintenance. When the
    /// handoff was queued as maintenance, two such reads on a four-worker
    /// pool (one on a two-worker pool) held exactly the workers the handoff
    /// waited for, so the build started only after each read had given up.
    /// `lane` only labels the admission in the log.
    pub fn submit_maintenance(
        &self,
        request_id: &str,
        lane: Lane,
        cancellation: JobCancellation,
        job: MaintenanceJob,
    ) -> bool {
        self.inner
            .submit_maintenance(request_id, lane, cancellation, job)
    }
}

impl<C: ExecutorContext> MaintenanceSubmit for TypedMaintenanceExecutor<C> {
    fn submit_maintenance(
        &self,
        request_id: &str,
        lane: Lane,
        cancellation: JobCancellation,
        job: MaintenanceJob,
    ) -> bool {
        let Some(inner) = self.inner.upgrade() else {
            return false;
        };
        // Dropped off-worker if it turns out to be the executor's last owner.
        let owner = SubmissionExecutor::<C>(Some(Executor::<C> { inner }));
        let executor = owner.0.as_ref().unwrap();
        // A root stat can stall on disk I/O; probe it before taking the
        // scheduler lock, as a queued submission does.
        let root_exists = executor.maintenance_root_is_dir(&self.root_id);
        let admitted = {
            let state = executor.inner.state.lock();
            state
                .actors
                .get(&self.root_id)
                .filter(|actor| !actor.fatal && !actor.ctx.subc_unbound_quiesced())
                .map(|actor| {
                    let token = cancellation
                        .with_root(self.root_id.as_path())
                        .with_lifecycle(actor.ctx.subc_lifecycle_admission());
                    (Arc::clone(&actor.ctx), token)
                })
        };
        let Some((_ctx, token)) = admitted.filter(|_| root_exists) else {
            log::debug!(
                "executor refused maintenance: request_id={request_id} lane={lane:?} root={} \
                 (unbound, missing or unregistered)",
                self.root_id.as_path().display()
            );
            return true;
        };
        if token.cancel_requested_before_commit() || !token.mark_running() {
            return true;
        }
        log::debug!(
            "executor admitted maintenance: request_id={request_id} lane={lane:?} root={}",
            self.root_id.as_path().display()
        );
        let _installed = JobCancellationContextGuard::install(Some(token));
        let _ = job();
        true
    }
}

impl<C: ExecutorContext> Default for Executor<C> {
    fn default() -> Self {
        Self::new()
    }
}

#[rustfmt::skip]
test_support_visibility! {
struct ExecutorInner<C: ExecutorContext> {
    #[cfg(any(test, feature = "test-support"))]
    pub state: Arc<TrackedMutex<SchedulerState<C>>>,
    #[cfg(not(any(test, feature = "test-support")))]
    state: Arc<TrackedMutex<SchedulerState<C>>>,
    event_tx: Sender<SchedulerEvent<C>>,
    scheduler_handle: Mutex<Option<JoinHandle<()>>>,
    worker_handles: Mutex<Vec<JoinHandle<()>>>,
    #[cfg(any(test, feature = "test-support"))]
    pub config: EffectiveConfig,
    #[cfg(not(any(test, feature = "test-support")))]
    config: EffectiveConfig,
    nonrunnable_dispatches: Arc<AtomicUsize>,
    completed_interactive: Arc<AtomicU64>,
    completed_maintenance: Arc<AtomicU64>,
    dispatch_liveness: Arc<DispatchLivenessAtomics>,
    dispatch_loop_liveness: Arc<DispatchLoopLiveness<C>>,
    #[cfg(any(test, feature = "test-support"))]
    pub maintenance_root_check_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}
}

impl<C: ExecutorContext> Drop for ExecutorInner<C> {
    fn drop(&mut self) {
        // Stop maintenance before joining workers. Queued closures must also
        // release their captured builders instead of surviving a stopped loop.
        {
            let mut state = self.state.lock();
            for job in state.running_jobs.values() {
                if job.job_class == JobClass::Maintenance {
                    if let Some(token) = &job.cancellation {
                        token.request_cancel();
                    }
                }
            }
            for actor in state.actors.values_mut() {
                actor.maintenance.cancel_queued_jobs();
            }
        }
        let _ = self.event_tx.send(SchedulerEvent::<C>::Shutdown);

        if let Some(handle) = self.scheduler_handle.lock().take() {
            if handle.thread().id() != std::thread::current().id() {
                let _ = handle.join();
            }
        }

        let mut workers = self.worker_handles.lock();
        for handle in workers.drain(..) {
            // A job can own the last Executor handle. Its worker will exit once
            // this job returns; joining that same thread would panic.
            if handle.thread().id() != std::thread::current().id() {
                let _ = handle.join();
            }
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
struct SchedulerState<C: ExecutorContext> {
    #[cfg(any(test, feature = "test-support"))]
    pub actors: HashMap<ProjectRootId, ActorState<C>>,
    #[cfg(not(any(test, feature = "test-support")))]
    actors: HashMap<ProjectRootId, ActorState<C>>,
    #[cfg(any(test, feature = "test-support"))]
    pub actor_order: Vec<ProjectRootId>,
    #[cfg(not(any(test, feature = "test-support")))]
    actor_order: Vec<ProjectRootId>,
    cursor: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub idle_workers: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    idle_workers: usize,
    interactive_inflight: usize,
    maintenance_inflight: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub provider_inflight: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    provider_inflight: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub binds_inflight: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    binds_inflight: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub config: EffectiveConfig,
    #[cfg(not(any(test, feature = "test-support")))]
    config: EffectiveConfig,
    #[cfg(any(test, feature = "test-support"))]
    pub running_jobs: HashMap<u64, RunningJob>,
    #[cfg(not(any(test, feature = "test-support")))]
    running_jobs: HashMap<u64, RunningJob>,
    next_job_id: u64,
    /// Set when a bind was queued again with a retry time, so the loop knows
    /// to look for the earliest one and wake for it.
    bind_retry_pending: bool,
}
}

impl<C: ExecutorContext> SchedulerState<C> {
    #[rustfmt::skip]
    test_support_visibility! {
    fn new(config: EffectiveConfig) -> Self {
        Self {
            actors: HashMap::new(),
            actor_order: Vec::new(),
            cursor: 0,
            idle_workers: config.total_workers(),
            interactive_inflight: 0,
            maintenance_inflight: 0,
            provider_inflight: 0,
            binds_inflight: 0,
            config,
            running_jobs: HashMap::new(),
            next_job_id: 1,
            bind_retry_pending: false,
        }
    }
    }

    /// The earliest time a bind queued with a retry time becomes admissible,
    /// clearing `bind_retry_pending` once none is left.
    fn next_bind_retry_at(&mut self) -> Option<Instant> {
        if !self.bind_retry_pending {
            return None;
        }
        let next = self
            .actors
            .values()
            .flat_map(|actor| actor.interactive.queue(Lane::Mutating).iter())
            .filter_map(|job| job.not_before)
            .min();
        self.bind_retry_pending = next.is_some();
        next
    }

    fn dispatch_liveness_snapshot(&self) -> DispatchLivenessSnapshot {
        self.assert_running_invariants();
        let now = Instant::now();
        let (completion_owned_interactive, completion_owned_maintenance) = self
            .running_jobs
            .values()
            .filter(|job| job.completion_ownership.strong_count() > 0)
            .fold((0, 0), |(interactive, maintenance), job| {
                match job.job_class {
                    JobClass::Interactive => (interactive + 1, maintenance),
                    JobClass::Maintenance => (interactive, maintenance + 1),
                }
            });
        let oldest_worker_owned_maintenance_age_ms = self
            .running_jobs
            .values()
            .filter(|job| {
                job.job_class == JobClass::Maintenance
                    && job.completion_ownership.strong_count() > 0
            })
            .map(|job| duration_millis_u64(now.saturating_duration_since(job.started_at)))
            .max();
        let mut interactive = QueueSnapshotAccumulator::default();
        let mut maintenance = QueueSnapshotAccumulator::default();
        for actor in self.actors.values() {
            interactive.add(actor.class_queues(JobClass::Interactive), now);
            maintenance.add(actor.class_queues(JobClass::Maintenance), now);
        }

        DispatchLivenessSnapshot {
            interactive: interactive.finish(),
            maintenance: maintenance.finish(),
            running: DispatchRunningSnapshot {
                interactive: self.interactive_inflight,
                maintenance: self.maintenance_inflight,
                completion_owned_interactive,
                completion_owned_maintenance,
                oldest_worker_owned_maintenance_age_ms,
                phantom_interactive: self
                    .interactive_inflight
                    .saturating_sub(completion_owned_interactive),
                phantom_maintenance: self
                    .maintenance_inflight
                    .saturating_sub(completion_owned_maintenance),
            },
            phantom_running_maintenance: self
                .maintenance_inflight
                .saturating_sub(completion_owned_maintenance),
            interactive_reserve: self.config.interactive_reserve,
            maintenance_cap: self.config.maintenance_cap,
        }
    }

    fn assert_running_invariants(&self) {
        let interactive = self
            .running_jobs
            .values()
            .filter(|job| job.job_class == JobClass::Interactive)
            .count();
        let maintenance = self
            .running_jobs
            .values()
            .filter(|job| job.job_class == JobClass::Maintenance)
            .count();
        debug_assert_eq!(self.interactive_inflight, interactive);
        debug_assert_eq!(self.maintenance_inflight, maintenance);
        debug_assert_eq!(
            self.binds_inflight,
            self.running_jobs
                .values()
                .filter(|job| is_bind_job(job.job_class, job.lane, &job.request_id))
                .count()
        );
        debug_assert_eq!(
            self.provider_inflight,
            self.running_jobs
                .values()
                .filter(|job| job.lane == Lane::ProviderMetadata)
                .count()
        );
        debug_assert!(self.provider_inflight <= self.config.provider_reserve);
        debug_assert_eq!(
            self.idle_workers + self.running_jobs.len(),
            self.config.total_workers()
        );
        debug_assert!(self
            .running_jobs
            .values()
            .all(|job| job.completion_ownership.strong_count() > 0));
    }

    fn next_job_id(&mut self) -> u64 {
        let job_id = self.next_job_id;
        self.next_job_id = self.next_job_id.wrapping_add(1).max(1);
        job_id
    }

    fn mutating_lane_snapshots(&self) -> Vec<MutatingLaneSnapshot> {
        let now = Instant::now();
        let mut snapshots: Vec<_> = self
            .actors
            .iter()
            .filter_map(|(root_id, actor)| {
                actor
                    .mutating_inflight
                    .as_ref()
                    .map(|job| MutatingLaneSnapshot {
                        root_id: root_id.clone(),
                        request_id: job.request_id.clone(),
                        command: job.command.clone(),
                        started_age_ms: duration_millis_u64(
                            now.saturating_duration_since(job.started_at),
                        ),
                    })
            })
            .collect();
        snapshots.sort_by(|left, right| left.root_id.as_path().cmp(right.root_id.as_path()));
        snapshots
    }

    /// When the most recently admitted reader still running on `root_id`
    /// started, for interactive admission (see `next_interactive_lane`).
    fn newest_in_flight_reader_started_at(&self, root_id: &ProjectRootId) -> Option<Instant> {
        self.running_jobs
            .values()
            .filter(|job| {
                job.root_id == *root_id
                    && matches!(job.lane, Lane::PureRead | Lane::SerialLspStatus)
            })
            .map(|job| job.started_at)
            .max()
    }

    fn mutating_job_state_label(&self, root_id: &ProjectRootId, request_id: &str) -> &'static str {
        let Some(actor) = self.actors.get(root_id) else {
            return "actor_missing";
        };
        if actor
            .mutating_inflight
            .as_ref()
            .is_some_and(|job| job.request_id == request_id)
        {
            return "running";
        }
        if actor.has_queued_mutating_job(request_id) {
            return "queued";
        }
        if actor.writer_inflight {
            return "blocked_by_other_mutating";
        }
        "not_found"
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn bind_blocker_snapshot(
        &self,
        root_id: &ProjectRootId,
        request_id: &str,
    ) -> BindBlockerSnapshot {
        let configure_state = self.mutating_job_state_label(root_id, request_id);
        let now = Instant::now();
        let actor = self.actors.get(root_id);
        let oldest_queued_writer_at = actor.and_then(ActorState::<C>::oldest_queued_writer_at);
        let oldest_queued_writer_age_ms = oldest_queued_writer_at
            .map(|queued_at| duration_millis_u64(now.saturating_duration_since(queued_at)));
        let mut in_flight_readers = self
            .running_jobs
            .values()
            .filter(|job| {
                job.root_id == *root_id
                    && matches!(job.lane, Lane::PureRead | Lane::SerialLspStatus)
            })
            .map(|job| BindBlockerReaderSnapshot {
                request_id: job.request_id.clone(),
                command: job.command.clone(),
                lane: job.lane,
                started_age_ms: duration_millis_u64(now.saturating_duration_since(job.started_at)),
                execution_started: job.execution_started.load(Ordering::Acquire),
                started_before_oldest_writer: oldest_queued_writer_at
                    .is_some_and(|queued_at| job.started_at <= queued_at),
            })
            .collect::<Vec<_>>();
        in_flight_readers.sort_by(|left, right| left.request_id.cmp(&right.request_id));
        // The bind's own configure job can hold the mutating slot while it
        // runs. It is not a blocker of the bind; reporting it as one would
        // tell the caller to wait for a different job when the bind's own
        // configure is what is slow.
        let in_flight_writer = actor
            .and_then(|actor| actor.mutating_inflight.as_ref())
            .filter(|job| job.request_id != request_id)
            .map(|job| MutatingLaneSnapshot {
                root_id: root_id.clone(),
                request_id: job.request_id.clone(),
                command: job.command.clone(),
                started_age_ms: duration_millis_u64(now.saturating_duration_since(job.started_at)),
            });

        let mut blockers = Vec::new();
        if let Some(actor) = actor {
            if configure_state == "queued" {
                let configure_count = actor.pending_configure_count();
                if configure_count > 0 {
                    blockers.push(format!("queued_behind_configure({configure_count})"));
                }
                if actor.read_inflight > 0 || actor.lsp_inflight {
                    let zombie_readers = in_flight_readers
                        .iter()
                        .filter(|reader| !reader.execution_started)
                        .map(format_bind_blocker_reader)
                        .collect::<Vec<_>>();
                    let stuck_readers = in_flight_readers
                        .iter()
                        .filter(|reader| {
                            reader.execution_started
                                && reader.started_age_ms
                                    >= duration_millis_u64(READER_STUCK_CENSUS_AGE)
                        })
                        .map(format_bind_blocker_reader)
                        .collect::<Vec<_>>();
                    if !zombie_readers.is_empty() {
                        blockers.push(format!("zombie_reader({})", zombie_readers.join("; ")));
                    } else if !stuck_readers.is_empty() {
                        blockers.push(format!(
                            "waiting_on_readers_stuck({})",
                            stuck_readers.join("; ")
                        ));
                    } else {
                        blockers.push("waiting_on_readers".to_string());
                    }
                }
            }
        }

        if configure_state == "queued" {
            let maintenance: Vec<_> = self
                .running_jobs
                .values()
                .filter(|job| job.job_class == JobClass::Maintenance)
                .collect();
            if !maintenance.is_empty() {
                blockers.push(format!(
                    "queued_behind_maintenance({})",
                    format_running_jobs(&maintenance)
                ));
            }
        }

        if let Some(actor) = actor {
            if configure_state == "queued" && actor.interactive.first_bind_is_forced_exclusive() {
                blockers.push("rerun_as_exclusive_writer".to_string());
            }
            if actor.detached_writers.load(Ordering::Acquire) > 0 {
                blockers.push("detached_view_publication_writer_waiting".to_string());
            }
            // Name the configure-tail stage in progress on this root, so a
            // bind held up by a long tail unit says which one.
            if let Some(stage) = actor.ctx.configure_tail_stage_snapshot() {
                blockers.push(format!("configure_tail_stage({stage})"));
            }
        }

        if self.idle_workers == 0 {
            let running: Vec<_> = self.running_jobs.values().collect();
            blockers.push(format!(
                "idle_workers==0({})",
                format_running_jobs(&running)
            ));
        }

        BindBlockerSnapshot {
            configure_state,
            configure_phase_timings: actor.map(|actor| actor.ctx.configure_ack_phase_snapshot()),
            blockers,
            oldest_queued_writer_age_ms,
            in_flight_readers,
            in_flight_writer,
            reader_admissions_while_promoted_writer_waited: actor
                .map(|actor| actor.reader_admissions_while_promoted_writer_waited)
                .unwrap_or(0),
        }
    }

    }
}

fn is_configure_request(request_id: &str) -> bool {
    request_id.starts_with("subc-bind-")
}

fn is_bind_job(job_class: JobClass, lane: Lane, request_id: &str) -> bool {
    job_class == JobClass::Interactive && lane == Lane::Mutating && is_configure_request(request_id)
}

fn is_callgraph_acquisition(job_class: JobClass, lane: Lane, request_id: &str) -> bool {
    job_class == JobClass::Maintenance
        && lane == Lane::HeavyInit
        && request_id == CALLGRAPH_ACQUISITION_REQUEST_ID
}

fn format_bind_blocker_reader(reader: &BindBlockerReaderSnapshot) -> String {
    format!(
        "job={} command={} lane={:?} age_ms={} execution_started={} started_before_oldest_writer={}",
        reader.request_id,
        reader.command,
        reader.lane,
        reader.started_age_ms,
        reader.execution_started,
        reader.started_before_oldest_writer
    )
}

fn format_running_jobs(jobs: &[&RunningJob]) -> String {
    let now = Instant::now();
    let mut labels: Vec<_> = jobs
        .iter()
        .map(|job| {
            format!(
                "job={} command={} lane={:?} root={} age_ms={}",
                job.request_id,
                job.command,
                job.lane,
                job.root_id.as_path().display(),
                duration_millis_u64(now.saturating_duration_since(job.started_at))
            )
        })
        .collect();
    labels.sort();
    labels.truncate(4);
    labels.join("; ")
}

#[derive(Default)]
struct QueueSnapshotAccumulator {
    queued: usize,
    oldest_age_ms: Option<u64>,
}

impl QueueSnapshotAccumulator {
    fn add<C: ExecutorContext>(&mut self, queues: &ClassQueues<C>, now: Instant) {
        self.queued += queues.queued_count();
        if let Some(queued_at) = queues.oldest_queued_at() {
            let age_ms = duration_millis_u64(now.saturating_duration_since(queued_at));
            self.oldest_age_ms = Some(
                self.oldest_age_ms
                    .map_or(age_ms, |oldest| oldest.max(age_ms)),
            );
        }
    }

    fn finish(self) -> DispatchClassQueueSnapshot {
        DispatchClassQueueSnapshot {
            queued: self.queued,
            oldest_age_ms: self.oldest_age_ms,
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {

fn duration_millis_u64(duration: Duration) -> u64 {
    duration.as_millis().min(u128::from(u64::MAX)) as u64
}
}

#[rustfmt::skip]
test_support_visibility! {
struct ActorState<C: ExecutorContext> {
    ctx: Arc<C>,
    #[cfg(any(test, feature = "test-support"))]
    pub epoch: Arc<RwLock<()>>,
    #[cfg(not(any(test, feature = "test-support")))]
    epoch: Arc<RwLock<()>>,
    #[cfg(any(test, feature = "test-support"))]
    pub read_inflight: usize,
    #[cfg(not(any(test, feature = "test-support")))]
    read_inflight: usize,
    lsp_inflight: bool,
    actor_total_inflight: usize,
    writer_inflight: bool,
    /// The running writer is a route bind that started with a shared epoch
    /// hold beside running maintenance or readers (see
    /// `current_bind_gate_is_shared`).
    shared_bind_inflight: bool,
    maintenance_commit_inflight: bool,
    /// Only the internal callgraph acquisition bypasses interactive capacity.
    callgraph_acquisition_inflight: bool,
    provider_inflight: bool,
    call_ledger_inflight: bool,
    mutating_inflight: Option<RunningMutatingJob>,
    reader_admissions_while_promoted_writer_waited: u64,
    deficit: isize,
    interactive: ClassQueues<C>,
    maintenance: ClassQueues<C>,
    fatal: bool,
    #[cfg(any(test, feature = "test-support"))]
    /// Number of queued interactive mutating jobs, shared with this actor's
    /// running jobs through [`current_actor_writer_waiting`]. Kept equal to
    /// `interactive.mutating.len()` by every method that changes that queue.
    pub waiting_writers: Arc<AtomicUsize>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Number of queued interactive mutating jobs, shared with this actor's
    /// running jobs through [`current_actor_writer_waiting`]. Kept equal to
    /// `interactive.mutating.len()` by every method that changes that queue.
    waiting_writers: Arc<AtomicUsize>,
    #[cfg(any(test, feature = "test-support"))]
    /// Detached threads (content-addressed view publication) waiting to write
    /// this actor's epoch gate. Reported through
    /// [`current_actor_writer_waiting`].
    pub detached_writers: Arc<AtomicUsize>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Detached threads (content-addressed view publication) waiting to write
    /// this actor's epoch gate. Reported through
    /// [`current_actor_writer_waiting`].
    detached_writers: Arc<AtomicUsize>,
}
}

impl<C: ExecutorContext> ActorState<C> {
    #[rustfmt::skip]
    test_support_visibility! {
    fn new(ctx: Arc<C>) -> Self {
        Self {
            ctx,
            epoch: Arc::new(RwLock::new(())),
            read_inflight: 0,
            lsp_inflight: false,
            actor_total_inflight: 0,
            writer_inflight: false,
            shared_bind_inflight: false,
            maintenance_commit_inflight: false,
            callgraph_acquisition_inflight: false,
            provider_inflight: false,
            call_ledger_inflight: false,
            mutating_inflight: None,
            reader_admissions_while_promoted_writer_waited: 0,
            deficit: 0,
            interactive: ClassQueues::<C>::new(),
            maintenance: ClassQueues::<C>::new(),
            fatal: false,
            waiting_writers: Arc::new(AtomicUsize::new(0)),
            detached_writers: Arc::new(AtomicUsize::new(0)),
        }
    }
    }

    fn sync_waiting_writers(&self) {
        self.waiting_writers
            .store(self.interactive.mutating.len(), Ordering::Release);
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn push_job(&mut self, job_class: JobClass, lane: Lane, job: QueuedJob<C>) {
        self.class_queues_mut(job_class).push_job(lane, job);
        self.sync_waiting_writers();
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn has_queued_jobs(&self) -> bool {
        self.interactive.has_queued_jobs() || self.maintenance.has_queued_jobs()
    }
    }

    fn is_idle(&self) -> bool {
        self.actor_total_inflight == 0 && !self.has_queued_jobs()
    }

    fn has_queued_jobs_for(&self, job_class: JobClass) -> bool {
        if job_class == JobClass::Interactive {
            // Provider and call-ledger jobs are admitted by their own passes.
            self.interactive
                .order
                .iter()
                .any(|lane| !matches!(lane, Lane::ProviderMetadata | Lane::CallLedger))
        } else {
            self.class_queues(job_class).has_queued_jobs()
        }
    }

    fn front_lane(&self, job_class: JobClass) -> Option<Lane> {
        self.class_queues(job_class).front_lane()
    }

    fn pop_front_job(&mut self, job_class: JobClass, lane: Lane) -> Option<QueuedJob<C>> {
        let job = self.class_queues_mut(job_class).pop_front_job(lane);
        self.sync_waiting_writers();
        job
    }

    fn pop_first_bind_job(&mut self) -> Option<QueuedJob<C>> {
        let job = self.interactive.remove_first_bind_job();
        self.sync_waiting_writers();
        job
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn higher_priority_writer_barrier_blocks(&self, job_class: JobClass) -> bool {
        // Maintenance must not start while interactive mutating work (tool
        // mutations, route binds) waits: a maintenance job that takes the
        // actor's writer slot would push the interactive writer behind it.
        matches!(job_class, JobClass::Maintenance)
            && !self.interactive.queue(Lane::Mutating).is_empty()
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn class_queues(&self, job_class: JobClass) -> &ClassQueues<C> {
        match job_class {
            JobClass::Interactive => &self.interactive,
            JobClass::Maintenance => &self.maintenance,
        }
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn class_queues_mut(&mut self, job_class: JobClass) -> &mut ClassQueues<C> {
        match job_class {
            JobClass::Interactive => &mut self.interactive,
            JobClass::Maintenance => &mut self.maintenance,
        }
    }
    }

    fn fail_queued_jobs(&mut self) {
        self.interactive.fail_queued_jobs();
        self.maintenance.fail_queued_jobs();
        self.sync_waiting_writers();
    }

    fn cancel_queued_root_work(&mut self) -> usize {
        self.maintenance.cancel_queued_jobs() + self.interactive.cancel_queued_provider_jobs()
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn has_queued_mutating_job(&self, request_id: &str) -> bool {
        self.interactive.has_queued_mutating_job(request_id)
            || self.maintenance.has_queued_mutating_job(request_id)
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn remove_queued_cancellable(&mut self, token: &JobCancellation) -> Option<QueuedJob<C>> {
        let removed = self
            .interactive
            .remove_cancellable(token)
            .or_else(|| self.maintenance.remove_cancellable(token));
        self.sync_waiting_writers();
        removed
    }
    }

    fn oldest_queued_writer_at(&self) -> Option<Instant> {
        [
            self.interactive.queue(Lane::Mutating).front(),
            self.maintenance.queue(Lane::Mutating).front(),
        ]
        .into_iter()
        .flatten()
        .map(|job| job.queued_at)
        .min()
    }

    fn pending_configure_count(&self) -> usize {
        usize::from(
            self.mutating_inflight
                .as_ref()
                .is_some_and(|job| is_configure_request(&job.request_id)),
        ) + self.interactive.queued_configure_count()
            + self.maintenance.queued_configure_count()
    }
}

#[rustfmt::skip]
test_support_visibility! {
struct ClassQueues<C: ExecutorContext> {
    order: VecDeque<Lane>,
    pure_reads: VecDeque<QueuedJob<C>>,
    lsp_status: VecDeque<QueuedJob<C>>,
    heavy_init: VecDeque<QueuedJob<C>>,
    mutating: VecDeque<QueuedJob<C>>,
    maintenance_commit: VecDeque<QueuedJob<C>>,
    provider_metadata: VecDeque<QueuedJob<C>>,
    call_ledger: VecDeque<QueuedJob<C>>,
}
}

impl<C: ExecutorContext> ClassQueues<C> {
    fn new() -> Self {
        Self {
            order: VecDeque::new(),
            pure_reads: VecDeque::new(),
            lsp_status: VecDeque::new(),
            heavy_init: VecDeque::new(),
            mutating: VecDeque::new(),
            maintenance_commit: VecDeque::new(),
            provider_metadata: VecDeque::new(),
            call_ledger: VecDeque::new(),
        }
    }

    fn push_job(&mut self, lane: Lane, job: QueuedJob<C>) {
        self.order.push_back(lane);
        self.queue_mut(lane).push_back(job);
    }

    /// Queue a job ahead of everything else in its lane. `order` pairs its
    /// lane entries with each lane's queue first-to-first, so the entry goes
    /// to the front as well.
    fn push_front_job(&mut self, lane: Lane, job: QueuedJob<C>) {
        self.order.push_front(lane);
        self.queue_mut(lane).push_front(job);
    }

    /// The route bind the bind pass would admit next.
    fn first_bind_job(&self) -> Option<&QueuedJob<C>> {
        self.mutating
            .iter()
            .find(|job| is_configure_request(&job.request_id))
    }

    fn first_bind_is_forced_exclusive(&self) -> bool {
        self.first_bind_job().is_some_and(|job| job.force_exclusive)
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn has_queued_jobs(&self) -> bool {
        !self.order.is_empty()
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn front_lane(&self) -> Option<Lane> {
        self.order.front().copied()
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    /// Interactive admission order: a starved writer preempts everything so
    /// its deadline survives. A queued RouteBind configure counts as starved
    /// after `BIND_PROMOTION_AGE`, any other writer after
    /// `INTERACTIVE_WRITER_PROMOTION_AGE`. Otherwise pure reads go first (they
    /// overlap each other and never barrier the actor), then remaining lanes
    /// in arrival order. Maintenance keeps strict arrival order via
    /// `front_lane`.
    ///
    /// `newest_reader_started_at` is when the most recently admitted reader
    /// still running on this actor started. A writer is not promoted while
    /// every running reader started before it queued and has run for
    /// `READER_STUCK_CENSUS_AGE`: the writer cannot run until those readers
    /// end, which may be never, so holding back new reads would only add an
    /// outage of every read on the root to the writer's own wait.
    fn next_interactive_lane(
        &self,
        now: Instant,
        newest_reader_started_at: Option<Instant>,
    ) -> Option<Lane> {
        let stuck_readers_started_by = newest_reader_started_at
            .filter(|started| now.saturating_duration_since(*started) >= READER_STUCK_CENSUS_AGE);
        let starved_writer = self.mutating.iter().any(|job| {
            let promotion_age = if is_configure_request(&job.request_id) {
                BIND_PROMOTION_AGE
            } else {
                INTERACTIVE_WRITER_PROMOTION_AGE
            };
            let waits_only_on_stuck_readers =
                stuck_readers_started_by.is_some_and(|newest| newest <= job.queued_at);
            now.saturating_duration_since(job.queued_at) >= promotion_age
                && !waits_only_on_stuck_readers
        });
        if starved_writer {
            // Also stops NEW readers from being admitted on this actor while
            // the promoted writer waits for in-flight readers to drain.
            return Some(Lane::Mutating);
        }
        if !self.pure_reads.is_empty() {
            return Some(Lane::PureRead);
        }
        self.order.iter().copied().find(|lane| {
            !matches!(
                lane,
                Lane::PureRead | Lane::ProviderMetadata | Lane::CallLedger
            )
        })
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn pop_front_job(&mut self, lane: Lane) -> Option<QueuedJob<C>> {
        // Keep `order` consistent with per-lane queues when admission picks a
        // lane other than the arrival-order head: remove the FIRST occurrence
        // of the chosen lane from `order`, not necessarily the front.
        let position = self.order.iter().position(|queued| *queued == lane)?;
        self.order.remove(position);
        self.queue_mut(lane).pop_front()
    }
    }

    fn queued_count(&self) -> usize {
        self.order.len()
    }

    fn has_maintenance_coalesce_key(&self, key: MaintenanceCoalesceKey) -> bool {
        ALL_LANES.into_iter().any(|lane| {
            self.queue(lane)
                .iter()
                .any(|job| job.maintenance_coalesce_key == Some(key))
        })
    }

    /// Remove only redundant idempotent drains while preserving survivor order.
    fn remove_duplicate_maintenance_jobs(&mut self) -> Vec<QueuedJob<C>> {
        let mut seen = HashSet::new();
        let mut lane_positions = [0usize; ALL_LANES.len()];
        let mut duplicates = Vec::new();

        for (order_position, lane) in self.order.iter().copied().enumerate() {
            let lane_index = lane_index(lane);
            let queue_position = lane_positions[lane_index];
            lane_positions[lane_index] += 1;
            let Some(key) = self
                .queue(lane)
                .get(queue_position)
                .and_then(|job| job.maintenance_coalesce_key)
            else {
                continue;
            };
            if !seen.insert(key) {
                duplicates.push((order_position, lane, queue_position));
            }
        }

        let mut removed = Vec::with_capacity(duplicates.len());
        for (order_position, lane, queue_position) in duplicates.into_iter().rev() {
            self.order.remove(order_position);
            if let Some(job) = self.queue_mut(lane).remove(queue_position) {
                removed.push(job);
            }
        }
        removed
    }

    fn oldest_queued_at(&self) -> Option<Instant> {
        self.front_lane()
            .and_then(|lane| self.queue(lane).front().map(|job| job.queued_at))
    }

    fn fail_queued_jobs(&mut self) {
        self.order.clear();
        fail_queued_job_queue(&mut self.pure_reads);
        fail_queued_job_queue(&mut self.lsp_status);
        fail_queued_job_queue(&mut self.heavy_init);
        fail_queued_job_queue(&mut self.mutating);
        fail_queued_job_queue(&mut self.maintenance_commit);
        fail_queued_job_queue(&mut self.provider_metadata);
        fail_queued_job_queue(&mut self.call_ledger);
    }

    fn cancel_queued_jobs(&mut self) -> usize {
        self.order.clear();
        cancel_queued_job_queue(&mut self.pure_reads)
            + cancel_queued_job_queue(&mut self.lsp_status)
            + cancel_queued_job_queue(&mut self.heavy_init)
            + cancel_queued_job_queue(&mut self.mutating)
            + cancel_queued_job_queue(&mut self.maintenance_commit)
            + cancel_queued_job_queue(&mut self.provider_metadata)
            + cancel_queued_job_queue(&mut self.call_ledger)
    }

    fn cancel_queued_provider_jobs(&mut self) -> usize {
        self.order.retain(|lane| *lane != Lane::ProviderMetadata);
        let cancelled = self.provider_metadata.len();
        for queued in self.provider_metadata.drain(..) {
            if let Some(token) = &queued.cancellation {
                let _ = token.try_cancel_before_running();
            }
            queued.completion.send(Response::error(
                queued.request_id,
                "request_cancelled",
                "provider metadata root has no bound routes",
            ));
        }
        cancelled
    }

    fn has_queued_mutating_job(&self, request_id: &str) -> bool {
        self.mutating.iter().any(|job| job.request_id == request_id)
    }

    /// Remove the oldest queued route-bind configure from the Mutating lane,
    /// even when other mutating jobs are ahead of it. Keeps `order` paired
    /// with the lane queue the same way `remove_cancellable` does.
    fn remove_first_bind_job(&mut self) -> Option<QueuedJob<C>> {
        let position = self
            .mutating
            .iter()
            .position(|job| is_configure_request(&job.request_id))?;
        let removed = self.mutating.remove(position);
        let mut occurrence = 0usize;
        if let Some(order_position) = self.order.iter().position(|entry| {
            if *entry != Lane::Mutating {
                return false;
            }
            let matched = occurrence == position;
            occurrence += 1;
            matched
        }) {
            self.order.remove(order_position);
        }
        removed
    }

    /// Remove the queued job carrying this exact cancellation token.
    ///
    /// `order` holds one lane entry per push, and per-lane entries pair FIFO
    /// with the lane queue: the k-th occurrence of a lane in `order`
    /// corresponds to the k-th element of that lane's queue. Removing the
    /// FIRST matching order entry for a job deeper in its lane queue would
    /// shift the pairing and reorder the survivors, so the occurrence at the
    /// job's own queue position is removed instead.
    fn remove_cancellable(&mut self, token: &JobCancellation) -> Option<QueuedJob<C>> {
        for lane in ALL_LANES {
            let queue = self.queue_mut(lane);
            let position = queue.iter().position(|queued| {
                queued
                    .cancellation
                    .as_ref()
                    .is_some_and(|candidate| candidate.same_token(token))
            });
            if let Some(position) = position {
                let removed = queue.remove(position);
                let mut occurrence = 0usize;
                if let Some(order_position) = self.order.iter().position(|entry| {
                    if *entry != lane {
                        return false;
                    }
                    let matched = occurrence == position;
                    occurrence += 1;
                    matched
                }) {
                    self.order.remove(order_position);
                }
                return removed;
            }
        }
        None
    }

    fn queued_configure_count(&self) -> usize {
        self.mutating
            .iter()
            .filter(|job| is_configure_request(&job.request_id))
            .count()
    }

    /// Queue time of the oldest queued route-bind configure, if any.
    fn oldest_queued_bind_at(&self) -> Option<Instant> {
        self.mutating
            .iter()
            .filter(|job| is_configure_request(&job.request_id))
            .map(|job| job.queued_at)
            .min()
    }

    fn queue(&self, lane: Lane) -> &VecDeque<QueuedJob<C>> {
        match lane {
            Lane::PureRead => &self.pure_reads,
            Lane::SerialLspStatus => &self.lsp_status,
            Lane::HeavyInit => &self.heavy_init,
            Lane::Mutating => &self.mutating,
            Lane::MaintenanceCommit => &self.maintenance_commit,
            Lane::ProviderMetadata => &self.provider_metadata,
            Lane::CallLedger => &self.call_ledger,
        }
    }

    fn queue_mut(&mut self, lane: Lane) -> &mut VecDeque<QueuedJob<C>> {
        match lane {
            Lane::PureRead => &mut self.pure_reads,
            Lane::SerialLspStatus => &mut self.lsp_status,
            Lane::HeavyInit => &mut self.heavy_init,
            Lane::Mutating => &mut self.mutating,
            Lane::MaintenanceCommit => &mut self.maintenance_commit,
            Lane::ProviderMetadata => &mut self.provider_metadata,
            Lane::CallLedger => &mut self.call_ledger,
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
struct QueuedJob<C: ExecutorContext> {
    #[cfg(any(test, feature = "test-support"))]
    pub job: ExecutorJob<C>,
    #[cfg(not(any(test, feature = "test-support")))]
    job: ExecutorJob<C>,
    #[cfg(any(test, feature = "test-support"))]
    pub completion: CompletionSender,
    #[cfg(not(any(test, feature = "test-support")))]
    completion: CompletionSender,
    #[cfg(any(test, feature = "test-support"))]
    pub request_id: String,
    #[cfg(not(any(test, feature = "test-support")))]
    request_id: String,
    #[cfg(any(test, feature = "test-support"))]
    pub command: String,
    #[cfg(not(any(test, feature = "test-support")))]
    command: String,
    #[cfg(any(test, feature = "test-support"))]
    pub queued_at: Instant,
    #[cfg(not(any(test, feature = "test-support")))]
    queued_at: Instant,
    #[cfg(any(test, feature = "test-support"))]
    pub cancellation: Option<JobCancellation>,
    #[cfg(not(any(test, feature = "test-support")))]
    cancellation: Option<JobCancellation>,
    #[cfg(any(test, feature = "test-support"))]
    pub maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
    #[cfg(not(any(test, feature = "test-support")))]
    maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
    #[cfg(any(test, feature = "test-support"))]
    /// Present for a route bind that may run beside maintenance with a shared
    /// hold and be queued again (see [`RepeatableJob`]).
    pub rerun: Option<RepeatableJob<C>>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Present for a route bind that may run beside maintenance with a shared
    /// hold and be queued again (see [`RepeatableJob`]).
    rerun: Option<RepeatableJob<C>>,
    #[cfg(any(test, feature = "test-support"))]
    /// A bind queued again after a shared-hold attempt: it is admitted only
    /// with exclusive use of the actor.
    pub force_exclusive: bool,
    #[cfg(not(any(test, feature = "test-support")))]
    /// A bind queued again after a shared-hold attempt: it is admitted only
    /// with exclusive use of the actor.
    force_exclusive: bool,
    #[cfg(any(test, feature = "test-support"))]
    /// Not admissible before this time: a bind that found the epoch gate
    /// held by a detached writer backs off instead of waiting on a worker.
    pub not_before: Option<Instant>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Not admissible before this time: a bind that found the epoch gate
    /// held by a detached writer backs off instead of waiting on a worker.
    not_before: Option<Instant>,
    #[cfg(any(test, feature = "test-support"))]
    /// How many times this bind found the gate held by a detached writer.
    pub exclusive_attempts: u32,
    #[cfg(not(any(test, feature = "test-support")))]
    /// How many times this bind found the gate held by a detached writer.
    exclusive_attempts: u32,
    #[cfg(any(test, feature = "test-support"))]
    /// Checked before metadata starts, so unbind or reconfiguration rejects
    /// queued or dispatched work from an older configure generation.
    pub provider_generation: Option<u64>,
    #[cfg(not(any(test, feature = "test-support")))]
    /// Checked before metadata starts, so unbind or reconfiguration rejects
    /// queued or dispatched work from an older configure generation.
    provider_generation: Option<u64>,
}
}

fn lane_index(lane: Lane) -> usize {
    match lane {
        Lane::PureRead => 0,
        Lane::SerialLspStatus => 1,
        Lane::HeavyInit => 2,
        Lane::Mutating => 3,
        Lane::MaintenanceCommit => 4,
        Lane::ProviderMetadata => 5,
        Lane::CallLedger => 6,
    }
}

fn fail_queued_job_queue<C: ExecutorContext>(queue: &mut VecDeque<QueuedJob<C>>) {
    for queued in queue.drain(..) {
        queued
            .completion
            .send(actor_fatal_response(queued.request_id));
    }
}

fn cancel_queued_job_queue<C: ExecutorContext>(queue: &mut VecDeque<QueuedJob<C>>) -> usize {
    let cancelled = queue.len();
    for queued in queue.drain(..) {
        queued.completion.send(Response::error(
            queued.request_id,
            "maintenance_cancelled",
            "maintenance cancelled because the actor has no bound routes",
        ));
    }
    cancelled
}

fn job_command(job_class: JobClass, lane: Lane) -> String {
    format!("executor::{job_class:?}::{lane:?}")
}

fn maintenance_allowed_while_unbound(command: &str) -> bool {
    matches!(command, "unbound-teardown-persist" | "lsp-event-drain")
}

fn maintenance_cancelled_response(
    request_id: impl Into<String>,
    message: impl Into<String>,
) -> Response {
    Response::error(request_id, "maintenance_cancelled", message)
}

fn maintenance_backpressure_response(request_id: impl Into<String>) -> Response {
    Response::error_with_data(
        request_id,
        "maintenance_backpressure",
        format!("maintenance queue reached its per-actor capacity of {MAINTENANCE_QUEUE_CAP} jobs"),
        serde_json::json!({
            "retryable": true,
            "queue_cap": MAINTENANCE_QUEUE_CAP,
        }),
    )
}

fn actor_fatal_response(request_id: impl Into<String>) -> Response {
    Response::error(
        request_id,
        "actor_fatal",
        "executor actor is fatal after a mutating job panic",
    )
}

fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
    if let Some(message) = payload.downcast_ref::<&'static str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

fn panic_response(
    request_id: impl Into<String>,
    command: &str,
    payload: &(dyn std::any::Any + Send),
) -> Response {
    let panic_message = panic_payload_message(payload);
    Response::error(
        request_id,
        "actor_fatal",
        format!("command '{command}' panicked: {panic_message}"),
    )
}

#[rustfmt::skip]
test_support_visibility! {
enum CompletionSender {
    Sync(Sender<Response>),
    Async(oneshot::Sender<Response>),
}
}

impl CompletionSender {
    fn send(self, response: Response) {
        match self {
            Self::Sync(tx) => {
                let _ = tx.send(response);
            }
            Self::Async(tx) => {
                let _ = tx.send(response);
            }
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
struct RunJob<C: ExecutorContext> {
    root_id: ProjectRootId,
    job_class: JobClass,
    lane: Lane,
    ctx: Arc<C>,
    epoch: Arc<RwLock<()>>,
    job: ExecutorJob<C>,
    completion: Option<CompletionSender>,
    #[cfg(any(test, feature = "test-support"))]
    pub request_id: String,
    #[cfg(not(any(test, feature = "test-support")))]
    request_id: String,
    command: String,
    heavy_permit: Option<HeavyPermit>,
    cancellation: Option<JobCancellation>,
    execution_started: Arc<AtomicBool>,
    #[cfg(any(test, feature = "test-support"))]
    pub completion_guard: Option<JobCompletionGuard<C>>,
    #[cfg(not(any(test, feature = "test-support")))]
    completion_guard: Option<JobCompletionGuard<C>>,
    /// The actor's queued-interactive-writer counter, exposed to the running
    /// job through [`current_actor_writer_waiting`].
    waiting_writers: Arc<AtomicUsize>,
    /// The actor's parked detached writers, also reported through
    /// [`current_actor_writer_waiting`].
    detached_writers: Arc<AtomicUsize>,
    /// A route bind admitted while a maintenance job or reader held the epoch
    /// gate: it runs with a shared hold (see [`current_bind_gate_is_shared`]).
    shared_bind_gate: bool,
    /// How to run this bind again if it has to be queued again.
    rerun: Option<RepeatableJob<C>>,
    /// When the job first queued; a requeued bind keeps its age so its
    /// promotion over new readers is not reset.
    queued_at: Instant,
    exclusive_attempts: u32,
    provider_generation: Option<u64>,
}
}

struct JobCompletionOwnership;

#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum JobCompletionOutcome {
    Completed,
    Panicked,
    Abandoned,
}
}

#[rustfmt::skip]
test_support_visibility! {
struct CompletionEvent<C: ExecutorContext> {
    job_id: u64,
    heavy_permit: Option<HeavyPermit>,
    outcome: JobCompletionOutcome,
    ownership: Arc<JobCompletionOwnership>,
    /// A shared-hold bind that must run again as an exclusive writer. The
    /// scheduler queues it at the head of the actor's binds in the same step
    /// that releases the finished run's reservation.
    requeue: Option<QueuedJob<C>>,
}
}

#[rustfmt::skip]
test_support_visibility! {
struct JobCompletionGuard<C: ExecutorContext> {
    event_tx: Sender<SchedulerEvent<C>>,
    event: Option<CompletionEvent<C>>,
}
}

impl<C: ExecutorContext> JobCompletionGuard<C> {
    fn new(event_tx: Sender<SchedulerEvent<C>>, event: CompletionEvent<C>) -> Self {
        Self {
            event_tx,
            event: Some(event),
        }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn set_outcome(&mut self, outcome: JobCompletionOutcome) {
        if let Some(event) = self.event.as_mut() {
            event.outcome = outcome;
        }
    }
    }

    fn set_requeue(&mut self, job: QueuedJob<C>) {
        if let Some(event) = self.event.as_mut() {
            event.requeue = Some(job);
        }
    }
}

impl<C: ExecutorContext> Drop for JobCompletionGuard<C> {
    fn drop(&mut self) {
        let Some(mut event) = self.event.take() else {
            return;
        };
        if std::thread::panicking() {
            event.outcome = JobCompletionOutcome::Panicked;
        }
        let _ = self.event_tx.send(SchedulerEvent::<C>::Completed(event));
    }
}

#[rustfmt::skip]
test_support_visibility! {
enum SchedulerEvent<C: ExecutorContext> {
    Wake,
    Completed(CompletionEvent<C>),
    Shutdown,
}
}

fn scheduler_loop<C: ExecutorContext>(
    state: Arc<TrackedMutex<SchedulerState<C>>>,
    heavy: Arc<HeavySemaphore>,
    run_tx: Sender<RunJob<C>>,
    event_tx: Sender<SchedulerEvent<C>>,
    event_rx: Receiver<SchedulerEvent<C>>,
    nonrunnable_dispatches: Arc<AtomicUsize>,
    completed_interactive: Arc<AtomicU64>,
    completed_maintenance: Arc<AtomicU64>,
    dispatch_liveness: Arc<DispatchLivenessAtomics>,
    loop_liveness: Arc<DispatchLoopLiveness<C>>,
) {
    let mut next_retry_at: Option<Instant> = None;
    loop {
        // A bind waiting out a retry time has no event to wake the loop, so
        // the loop wakes itself when the earliest one comes due.
        let event = if loop_liveness.wait_for_event(next_retry_at) {
            // Select readiness can be spurious. Do not block with the active
            // marker set when there is actually no event to process.
            match event_rx.try_recv() {
                Ok(event) => event,
                Err(crossbeam_channel::TryRecvError::Empty) => {
                    loop_liveness.end_event();
                    continue;
                }
                Err(crossbeam_channel::TryRecvError::Disconnected) => {
                    loop_liveness.end_event();
                    break;
                }
            }
        } else {
            SchedulerEvent::<C>::Wake
        };
        let shutdown;
        {
            let mut state = state.lock();
            shutdown = process_scheduler_event_batch(
                event,
                &event_rx,
                &mut state,
                &completed_interactive,
                &completed_maintenance,
            );

            if !shutdown {
                dispatch_runnable(
                    &mut state,
                    &heavy,
                    &run_tx,
                    &event_tx,
                    &nonrunnable_dispatches,
                );
            }
            dispatch_liveness.record(&state.dispatch_liveness_snapshot());
            next_retry_at = state.next_bind_retry_at();
        }
        loop_liveness.end_event();

        if shutdown {
            break;
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {

fn process_scheduler_event_batch<C: ExecutorContext>(
    first: SchedulerEvent<C>,
    event_rx: &Receiver<SchedulerEvent<C>>,
    state: &mut SchedulerState<C>,
    completed_interactive: &AtomicU64,
    completed_maintenance: &AtomicU64,
) -> bool {
    let mut event = Some(first);
    for _ in 0..SCHEDULER_EVENT_BATCH_CAP {
        let Some(current) = event.take().or_else(|| event_rx.try_recv().ok()) else {
            break;
        };
        if process_scheduler_event(current, state, completed_interactive, completed_maintenance) {
            return true;
        }
    }
    false
}
}

fn note_completed_class(
    job_class: JobClass,
    completed_interactive: &AtomicU64,
    completed_maintenance: &AtomicU64,
) {
    match job_class {
        JobClass::Interactive => {
            completed_interactive.fetch_add(1, Ordering::Relaxed);
        }
        JobClass::Maintenance => {
            completed_maintenance.fetch_add(1, Ordering::Relaxed);
        }
    }
}

fn process_scheduler_event<C: ExecutorContext>(
    event: SchedulerEvent<C>,
    state: &mut SchedulerState<C>,
    completed_interactive: &AtomicU64,
    completed_maintenance: &AtomicU64,
) -> bool {
    match event {
        SchedulerEvent::<C>::Wake => false,
        SchedulerEvent::<C>::Completed(event) => {
            if let Some(job_class) = complete_job(state, event) {
                note_completed_class(job_class, completed_interactive, completed_maintenance);
            }
            false
        }
        SchedulerEvent::<C>::Shutdown => true,
    }
}

#[rustfmt::skip]
test_support_visibility! {

fn complete_job<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    event: CompletionEvent<C>,
) -> Option<JobClass> {
    let CompletionEvent::<C> {
        job_id,
        heavy_permit,
        outcome,
        ownership,
        requeue,
    } = event;
    let Some(running) = state.running_jobs.remove(&job_id) else {
        log::error!("executor completion: unknown job_id={job_id} outcome={outcome:?}");
        return None;
    };
    debug_assert!(running
        .completion_ownership
        .upgrade()
        .is_some_and(|current| Arc::ptr_eq(&current, &ownership)));

    let RunningJob {
        root_id,
        request_id,
        job_class,
        lane,
        ..
    } = running;
    log::debug!(
        "executor completion: job_id={job_id} class={job_class:?} lane={lane:?} outcome={outcome:?} request_id={request_id} root={}",
        root_id.as_path().display()
    );

    match job_class {
        JobClass::Interactive => {
            debug_assert!(state.interactive_inflight > 0);
            state.interactive_inflight = state.interactive_inflight.saturating_sub(1);
        }
        JobClass::Maintenance => {
            debug_assert!(state.maintenance_inflight > 0);
            state.maintenance_inflight = state.maintenance_inflight.saturating_sub(1);
        }
    }

    if lane == Lane::ProviderMetadata {
        state.provider_inflight = state.provider_inflight.saturating_sub(1);
    }
    if is_bind_job(job_class, lane, &request_id) {
        state.binds_inflight = state.binds_inflight.saturating_sub(1);
    }
    if let Some(actor) = state.actors.get_mut(&root_id) {
        actor.actor_total_inflight = actor.actor_total_inflight.saturating_sub(1);
        match lane {
            Lane::PureRead => {
                actor.read_inflight = actor.read_inflight.saturating_sub(1);
            }
            Lane::SerialLspStatus => {
                actor.lsp_inflight = false;
            }
            Lane::HeavyInit => {
                if is_callgraph_acquisition(job_class, lane, &request_id) {
                    actor.callgraph_acquisition_inflight = false;
                }
            }
            Lane::Mutating => {
                actor.writer_inflight = false;
                actor.shared_bind_inflight = false;
                actor.mutating_inflight = None;
            }
            Lane::MaintenanceCommit => {
                actor.maintenance_commit_inflight = false;
            }
            Lane::ProviderMetadata => actor.provider_inflight = false,
            Lane::CallLedger => actor.call_ledger_inflight = false,
        }

        if outcome == JobCompletionOutcome::Panicked && lane == Lane::Mutating {
            actor.fatal = true;
            actor.fail_queued_jobs();
        }
    }

    if let Some(queued) = requeue {
        match state.actors.get_mut(&root_id) {
            // A cancel that landed after the worker returned the token to
            // pending, but before this event, found the job neither queued
            // nor able to observe it. Settle it here, under the scheduler
            // lock that `cancel_job` also takes, instead of queuing cancelled
            // writer demand behind whatever holds the actor.
            _ if queued
                .cancellation
                .as_ref()
                .is_some_and(JobCancellation::cancel_already_requested) =>
            {
                queued.completion.send(Response::error(
                    queued.request_id,
                    "request_cancelled",
                    "request cancelled before execution",
                ));
            }
            Some(actor) if !actor.fatal => {
                // Pending-bind diagnostics read the configure phases; name the
                // wait instead of leaving the phase the discarded run reached.
                actor.ctx.begin_configure_ack_phase("requeued_exclusive");
                let has_retry_time = queued.not_before.is_some();
                actor.interactive.push_front_job(Lane::Mutating, queued);
                actor.sync_waiting_writers();
                state.bind_retry_pending |= has_retry_time;
            }
            Some(_) => queued
                .completion
                .send(actor_fatal_response(queued.request_id)),
            None => queued.completion.send(Response::error(
                queued.request_id,
                "actor_not_registered",
                "executor actor is not registered",
            )),
        }
    }

    drop(heavy_permit);
    drop(ownership);
    state.idle_workers += 1;
    state.assert_running_invariants();
    Some(job_class)
}
}

#[rustfmt::skip]
test_support_visibility! {

fn dispatch_runnable<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    heavy: &Arc<HeavySemaphore>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
) {
    while state.idle_workers > 0 && !state.actor_order.is_empty() {
        let mut made_progress = false;
        let mut dispatch_failed = false;

        // Route binds first, on any idle worker including the bind reserve:
        // subc refuses the module once a bind relay exceeds its deadline, so a
        // bind must never wait for a DRR turn behind other roots' work.
        made_progress |= dispatch_queued_binds(
            state,
            heavy,
            run_tx,
            event_tx,
            nonrunnable_dispatches,
            &mut dispatch_failed,
        );
        if dispatch_failed || state.idle_workers == 0 {
            return;
        }

        made_progress |= dispatch_provider_metadata(
            state,
            heavy,
            run_tx,
            event_tx,
            nonrunnable_dispatches,
            &mut dispatch_failed,
        );
        if dispatch_failed || state.idle_workers == 0 {
            return;
        }

        made_progress |= dispatch_call_ledger(
            state,
            heavy,
            run_tx,
            event_tx,
            nonrunnable_dispatches,
            &mut dispatch_failed,
        );
        if dispatch_failed || state.idle_workers == 0 {
            return;
        }

        made_progress |= dispatch_runnable_class(
            state,
            JobClass::Interactive,
            heavy,
            run_tx,
            event_tx,
            nonrunnable_dispatches,
            &mut dispatch_failed,
        );
        if dispatch_failed || state.idle_workers == 0 {
            return;
        }

        if can_dispatch_class(state, JobClass::Maintenance) {
            made_progress |= dispatch_runnable_class(
                state,
                JobClass::Maintenance,
                heavy,
                run_tx,
                event_tx,
                nonrunnable_dispatches,
                &mut dispatch_failed,
            );
            if dispatch_failed {
                return;
            }
        }

        if !made_progress {
            break;
        }
    }
}
}

fn dispatch_runnable_class<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    job_class: JobClass,
    heavy: &Arc<HeavySemaphore>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
    dispatch_failed: &mut bool,
) -> bool {
    if !can_dispatch_class(state, job_class) || state.actor_order.is_empty() {
        return false;
    }

    let actor_count = state.actor_order.len();
    let mut made_progress = false;

    for _ in 0..actor_count {
        if !can_dispatch_class(state, job_class) || state.actor_order.is_empty() {
            break;
        }

        if state.cursor >= state.actor_order.len() {
            state.cursor = 0;
        }
        let root_id = state.actor_order[state.cursor].clone();
        state.cursor = (state.cursor + 1) % state.actor_order.len();
        let newest_reader_started_at = match job_class {
            JobClass::Interactive => state.newest_in_flight_reader_started_at(&root_id),
            JobClass::Maintenance => None,
        };

        let run_job = {
            let Some(actor) = state.actors.get_mut(&root_id) else {
                continue;
            };

            if actor.fatal {
                actor.fail_queued_jobs();
                actor.deficit = 0;
                continue;
            }

            if !actor.has_queued_jobs() {
                actor.deficit = 0;
                continue;
            }

            if !actor.has_queued_jobs_for(job_class) {
                continue;
            }

            actor.deficit =
                (actor.deficit + state.config.drr_quantum).min(state.config.deficit_cap);
            if actor.deficit < JOB_COST {
                continue;
            }

            try_admit_actor(
                &root_id,
                actor,
                AdmissionPass::Class(job_class),
                &state.config,
                heavy,
                newest_reader_started_at,
            )
        };

        if let Some(run_job) = run_job {
            made_progress = true;
            if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
                *dispatch_failed = true;
                return made_progress;
            }
        }
    }

    made_progress
}

/// Admit every queued route-bind configure whose actor can take a writer now,
/// oldest bind first. Binds skip the DRR deficit and the per-actor interactive
/// cap: a configure is short, and waiting a round-robin turn behind dozens of
/// busy roots is what pushed binds past the daemon's relay deadline.
fn dispatch_queued_binds<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    heavy: &Arc<HeavySemaphore>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
    dispatch_failed: &mut bool,
) -> bool {
    let mut candidates = state
        .actors
        .iter()
        .filter(|(_, actor)| !actor.fatal)
        .filter_map(|(root_id, actor)| {
            actor
                .interactive
                .oldest_queued_bind_at()
                .map(|queued_at| (queued_at, root_id.clone()))
        })
        .collect::<Vec<_>>();
    if candidates.is_empty() {
        return false;
    }
    candidates.sort_by(|left, right| left.0.cmp(&right.0));

    let mut made_progress = false;
    for (_, root_id) in candidates {
        if state.idle_workers
            <= state
                .config
                .provider_reserve
                .saturating_sub(state.provider_inflight)
        {
            break;
        }
        let run_job = {
            let Some(actor) = state.actors.get_mut(&root_id) else {
                continue;
            };
            try_admit_actor(
                &root_id,
                actor,
                AdmissionPass::Bind,
                &state.config,
                heavy,
                None,
            )
        };
        if let Some(run_job) = run_job {
            made_progress = true;
            if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
                *dispatch_failed = true;
                return made_progress;
            }
        }
    }
    made_progress
}

/// Provider work uses the same root queues, completion and cancellation machinery
/// as other jobs, but never waits for an index lane's capacity or epoch gate.
fn dispatch_provider_metadata<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    heavy: &Arc<HeavySemaphore>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
    dispatch_failed: &mut bool,
) -> bool {
    let mut made_progress = false;
    for _ in 0..state.actor_order.len() {
        if state.idle_workers == 0 || state.provider_inflight >= state.config.provider_reserve {
            break;
        }
        state.cursor %= state.actor_order.len();
        let root_id = state.actor_order[state.cursor].clone();
        state.cursor = (state.cursor + 1) % state.actor_order.len();
        let Some(actor) = state.actors.get_mut(&root_id).filter(|actor| !actor.fatal) else {
            continue;
        };
        if let Some(run_job) = try_admit_actor(
            &root_id,
            actor,
            AdmissionPass::ProviderMetadata,
            &state.config,
            heavy,
            None,
        ) {
            made_progress = true;
            if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
                *dispatch_failed = true;
                break;
            }
        }
    }
    made_progress
}

/// Call-ledger jobs are admitted ahead of the interactive deficit round-robin
/// (DRR) pass, on general workers, without the actor's read cap, epoch gate or
/// writer barrier: a keyed reply cannot be written until its settlement
/// commits, so it must not wait for the reads queued or running on its root.
/// Each actor runs one at a time, in submission order.
fn dispatch_call_ledger<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    heavy: &Arc<HeavySemaphore>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
    dispatch_failed: &mut bool,
) -> bool {
    let mut made_progress = false;
    for _ in 0..state.actor_order.len() {
        if !can_dispatch_class(state, JobClass::Interactive) {
            break;
        }
        state.cursor %= state.actor_order.len();
        let root_id = state.actor_order[state.cursor].clone();
        state.cursor = (state.cursor + 1) % state.actor_order.len();
        let Some(actor) = state.actors.get_mut(&root_id).filter(|actor| !actor.fatal) else {
            continue;
        };
        if let Some(run_job) = try_admit_actor(
            &root_id,
            actor,
            AdmissionPass::CallLedger,
            &state.config,
            heavy,
            None,
        ) {
            made_progress = true;
            if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
                *dispatch_failed = true;
                break;
            }
        }
    }
    made_progress
}

/// Record an admitted job as running and hand it to a worker. Returns false
/// when the worker channel is closed.
fn launch_run_job<C: ExecutorContext>(
    state: &mut SchedulerState<C>,
    mut run_job: RunJob<C>,
    run_tx: &Sender<RunJob<C>>,
    event_tx: &Sender<SchedulerEvent<C>>,
    nonrunnable_dispatches: &AtomicUsize,
) -> bool {
    let job_id = state.next_job_id();
    let ownership = Arc::new(JobCompletionOwnership);
    run_job.completion_guard = Some(JobCompletionGuard::<C>::new(
        event_tx.clone(),
        CompletionEvent::<C> {
            job_id,
            heavy_permit: run_job.heavy_permit.take(),
            outcome: JobCompletionOutcome::Abandoned,
            ownership: Arc::clone(&ownership),
            requeue: None,
        },
    ));
    let replaced = state.running_jobs.insert(
        job_id,
        RunningJob {
            root_id: run_job.root_id.clone(),
            request_id: run_job.request_id.clone(),
            command: run_job.command.clone(),
            job_class: run_job.job_class,
            lane: run_job.lane,
            started_at: Instant::now(),
            execution_started: Arc::clone(&run_job.execution_started),
            completion_ownership: Arc::downgrade(&ownership),
            occupancy_reported: false,
            cancellation: run_job.cancellation.clone(),
        },
    );
    debug_assert!(replaced.is_none());
    state.idle_workers -= 1;
    match run_job.job_class {
        JobClass::Interactive => state.interactive_inflight += 1,
        JobClass::Maintenance => state.maintenance_inflight += 1,
    }
    if run_job.lane == Lane::ProviderMetadata {
        state.provider_inflight += 1;
    }
    if is_bind_job(run_job.job_class, run_job.lane, &run_job.request_id) {
        state.binds_inflight += 1;
    }
    state.assert_running_invariants();
    log::debug!(
        "executor dispatch: job_id={job_id} class={:?} lane={:?} request_id={} root={}",
        run_job.job_class,
        run_job.lane,
        run_job.request_id,
        run_job.root_id.as_path().display()
    );
    if run_tx.send(run_job).is_err() {
        nonrunnable_dispatches.fetch_add(1, Ordering::AcqRel);
        return false;
    }
    true
}

fn can_dispatch_class<C: ExecutorContext>(state: &SchedulerState<C>, job_class: JobClass) -> bool {
    // Running binds and metadata have already reduced idle_workers. Hold back
    // only the unused part of each reservation, or each running bind would also
    // remove a general-pool slot. All jobs still use one worker channel.
    let provider_idle = state
        .config
        .provider_reserve
        .saturating_sub(state.provider_inflight);
    let bind_idle = state
        .config
        .bind_reserve
        .saturating_sub(state.binds_inflight);
    let general_idle = state.idle_workers.saturating_sub(bind_idle + provider_idle);
    if general_idle == 0 {
        return false;
    }
    match job_class {
        JobClass::Interactive => true,
        JobClass::Maintenance => {
            state.maintenance_inflight < state.config.maintenance_cap
                && general_idle > state.config.interactive_reserve
        }
    }
}

#[rustfmt::skip]
test_support_visibility! {
/// Which dispatch pass is asking an actor for a job.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AdmissionPass {
    /// The route-bind pass: only a queued route-bind configure, taken from the
    /// Mutating lane ahead of any other writer queued before it. This pass may
    /// use the reserved bind workers, so it must never admit anything else.
    Bind,
    /// Provider jobs bypass ordinary per-root deficit scheduling and do not
    /// acquire the index epoch gate.
    ProviderMetadata,
    /// Call-ledger jobs: like provider jobs they bypass the deficit round-robin
    /// pass and the epoch gate, but they use general workers.
    CallLedger,
    /// The ordinary DRR pass for one job class.
    Class(JobClass),
}
}

#[rustfmt::skip]
test_support_visibility! {

fn try_admit_actor<C: ExecutorContext>(
    root_id: &ProjectRootId,
    actor: &mut ActorState<C>,
    pass: AdmissionPass,
    config: &EffectiveConfig,
    heavy: &Arc<HeavySemaphore>,
    newest_reader_started_at: Option<Instant>,
) -> Option<RunJob<C>> {
    let bind_pass = pass == AdmissionPass::Bind;
    let job_class = match pass {
        AdmissionPass::Bind | AdmissionPass::ProviderMetadata | AdmissionPass::CallLedger => {
            JobClass::Interactive
        }
        AdmissionPass::Class(job_class) => job_class,
    };
    let lane = match pass {
        AdmissionPass::ProviderMetadata => actor
            .interactive
            .provider_metadata
            .front()
            .map(|_| Lane::ProviderMetadata)?,
        AdmissionPass::CallLedger => actor
            .interactive
            .call_ledger
            .front()
            .map(|_| Lane::CallLedger)?,
        // Only the bind itself: an edit queued ahead of it waits for the
        // general pool (it is not admitted here, so it can never occupy a
        // reserved bind worker), and the bind runs first.
        AdmissionPass::Bind => actor
            .interactive
            .oldest_queued_bind_at()
            .map(|_| Lane::Mutating)?,
        AdmissionPass::Class(JobClass::Interactive) => actor
            .class_queues(JobClass::Interactive)
            .next_interactive_lane(Instant::now(), newest_reader_started_at)?,
        AdmissionPass::Class(JobClass::Maintenance) => actor.front_lane(job_class)?,
    };
    let mut heavy_permit = None;
    let callgraph_acquisition = actor
        .class_queues(job_class)
        .queue(lane)
        .front()
        .is_some_and(|job| is_callgraph_acquisition(job_class, lane, &job.request_id));

    // A bind that runs with a shared hold (see `current_bind_gate_is_shared`)
    // blocks other writers and maintenance like any running writer, but
    // readers may keep coming: it never waits for exclusive use in place.
    let shared_bind_admits_lane = actor.shared_bind_inflight
        && matches!(
            lane,
            Lane::PureRead | Lane::SerialLspStatus | Lane::HeavyInit
        );
    if !matches!(lane, Lane::ProviderMetadata | Lane::CallLedger)
        && ((actor.writer_inflight && !shared_bind_admits_lane)
            || actor.higher_priority_writer_barrier_blocks(job_class))
    {
        return None;
    }
    // A bind backing off from a detached writer waits out its retry time.
    if lane == Lane::Mutating {
        let head = if bind_pass {
            actor.interactive.first_bind_job()
        } else {
            actor.class_queues(job_class).queue(Lane::Mutating).front()
        };
        if head
            .and_then(|job| job.not_before)
            .is_some_and(|not_before| Instant::now() < not_before)
        {
            return None;
        }
    }

    let has_epoch_reader =
        actor.read_inflight > 0 || actor.lsp_inflight || actor.maintenance_commit_inflight;
    // Only a repeatable bind that has not already been sent back may start
    // with a shared hold: a run that finds it must change the root has to be
    // able to hand its worker back and run again.
    let bind_may_share = bind_pass
        && actor
            .interactive
            .first_bind_job()
            .is_some_and(|job| job.rerun.is_some() && !job.force_exclusive);
    // MaintenanceCommit and callgraph acquisition use global maintenance capacity and
    // must not consume the per-actor slots reserved for interactive work. This
    // matters when a two-worker executor has actor_cap=1: the global reserve
    // leaves one worker idle, and this accounting makes that worker reachable
    // by an interactive request for the same actor.
    let actor_interactive_inflight = actor
        .actor_total_inflight
        .saturating_sub(usize::from(actor.maintenance_commit_inflight))
        .saturating_sub(usize::from(actor.callgraph_acquisition_inflight))
        .saturating_sub(usize::from(actor.provider_inflight))
        .saturating_sub(usize::from(actor.call_ledger_inflight));
    let actor_has_interactive_capacity = actor_interactive_inflight < config.actor_cap;
    let runnable = match lane {
        Lane::PureRead => actor.read_inflight < config.read_cap && actor_has_interactive_capacity,
        Lane::SerialLspStatus => !actor.lsp_inflight && actor_has_interactive_capacity,
        Lane::HeavyInit => {
            let capacity = if callgraph_acquisition {
                !actor.callgraph_acquisition_inflight
            } else {
                actor_has_interactive_capacity
            };
            if !capacity {
                false
            } else if let Some(permit) = heavy.try_acquire() {
                heavy_permit = Some(permit);
                true
            } else {
                false
            }
        }
        // A bind skips the per-actor interactive cap: HeavyInit jobs count
        // toward that cap without holding the epoch gate, and the writer only
        // needs the gate itself to be free. A repeatable bind also does not
        // wait for whatever holds the gate for reading (a configure tail,
        // whose single units can run for seconds on a large root, or
        // interactive readers, which are usually short but are not bounded:
        // one slow read would otherwise hold every bind of its root until the
        // bind deadline). It starts beside them with a shared hold, which is
        // all a rebind of an unchanged root needs, the same hold readers
        // admitted after it already overlap. A run that must change the root
        // is sent back and queued again as an exclusive writer, which does
        // wait for readers and maintenance. `writer_inflight` above still
        // serializes binds and other writers per root.
        Lane::Mutating => {
            bind_may_share || (!has_epoch_reader && (bind_pass || actor_has_interactive_capacity))
        }
        // This lane has separate global and per-actor bounds: maintenance_cap
        // reserves workers globally, and the boolean prevents same-actor
        // maintenance from stacking without consuming an interactive slot.
        Lane::MaintenanceCommit => !actor.maintenance_commit_inflight,
        Lane::ProviderMetadata => !actor.provider_inflight,
        // Short database bookkeeping, outside the per-actor interactive cap:
        // one at a time keeps each actor's ledger writes in submission order.
        Lane::CallLedger => !actor.call_ledger_inflight,
    };

    if !runnable {
        return None;
    }
    let shared_bind_gate = bind_may_share && has_epoch_reader;

    let promoted_writer_waiting = actor.oldest_queued_writer_at().is_some_and(|queued_at| {
        Instant::now().saturating_duration_since(queued_at) >= INTERACTIVE_WRITER_PROMOTION_AGE
    });
    if promoted_writer_waiting && matches!(lane, Lane::PureRead | Lane::SerialLspStatus) {
        actor.reader_admissions_while_promoted_writer_waited = actor
            .reader_admissions_while_promoted_writer_waited
            .saturating_add(1);
    }

    let queued = if bind_pass {
        actor.pop_first_bind_job()?
    } else {
        actor.pop_front_job(job_class, lane)?
    };
    // The bind pass runs outside DRR, so it does not spend the actor's turn.
    if matches!(pass, AdmissionPass::Class(_)) {
        actor.deficit -= JOB_COST;
    }
    if lane == Lane::Mutating {
        actor.mutating_inflight = Some(RunningMutatingJob {
            request_id: queued.request_id.clone(),
            command: queued.command.clone(),
            started_at: Instant::now(),
        });
    }
    match lane {
        Lane::PureRead => {
            actor.read_inflight += 1;
            actor.actor_total_inflight += 1;
        }
        Lane::SerialLspStatus => {
            actor.lsp_inflight = true;
            actor.actor_total_inflight += 1;
        }
        Lane::HeavyInit => {
            if callgraph_acquisition {
                actor.callgraph_acquisition_inflight = true;
            }
            actor.actor_total_inflight += 1;
        }
        Lane::Mutating => {
            actor.writer_inflight = true;
            actor.shared_bind_inflight = shared_bind_gate;
            actor.actor_total_inflight += 1;
        }
        Lane::MaintenanceCommit => {
            actor.maintenance_commit_inflight = true;
            actor.actor_total_inflight += 1;
        }
        Lane::ProviderMetadata => {
            actor.provider_inflight = true;
            actor.actor_total_inflight += 1;
        }
        Lane::CallLedger => {
            actor.call_ledger_inflight = true;
            actor.actor_total_inflight += 1;
        }
    }

    Some(RunJob::<C> {
        root_id: root_id.clone(),
        job_class,
        lane,
        ctx: Arc::clone(&actor.ctx),
        epoch: Arc::clone(&actor.epoch),
        job: queued.job,
        completion: Some(queued.completion),
        request_id: queued.request_id,
        command: queued.command,
        heavy_permit,
        cancellation: queued.cancellation,
        execution_started: Arc::new(AtomicBool::new(false)),
        completion_guard: None,
        waiting_writers: Arc::clone(&actor.waiting_writers),
        detached_writers: Arc::clone(&actor.detached_writers),
        shared_bind_gate,
        rerun: queued.rerun,
        queued_at: queued.queued_at,
        exclusive_attempts: queued.exclusive_attempts,
        provider_generation: queued.provider_generation,
    })
}
}

thread_local! {
    static IS_EXECUTOR_WORKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

pub fn current_thread_is_executor_worker() -> bool {
    IS_EXECUTOR_WORKER.with(std::cell::Cell::get)
}

fn worker_loop<C: ExecutorContext>(run_rx: Receiver<RunJob<C>>) {
    IS_EXECUTOR_WORKER.with(|worker| worker.set(true));
    while let Ok(mut run_job) = run_rx.recv() {
        let response =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_lane_job(&mut run_job)));
        let panicked = response.is_err();
        let response = match response {
            Ok(LaneRun::Finished(response)) => response,
            Ok(LaneRun::RerunExclusive { retry_after }) => {
                match requeue_as_exclusive(&mut run_job, retry_after) {
                    Ok(queued) => {
                        let guard = run_job
                            .completion_guard
                            .as_mut()
                            .expect("dispatched executor job is missing its completion guard");
                        guard.set_requeue(queued);
                        guard.set_outcome(JobCompletionOutcome::Completed);
                        continue;
                    }
                    Err(response) => response,
                }
            }
            Err(payload) => panic_response(
                run_job.request_id.clone(),
                &run_job.command,
                payload.as_ref(),
            ),
        };

        if let Some(completion) = run_job.completion.take() {
            completion.send(response);
        }
        run_job
            .completion_guard
            .as_mut()
            .expect("dispatched executor job is missing its completion guard")
            .set_outcome(if panicked {
                JobCompletionOutcome::Panicked
            } else {
                JobCompletionOutcome::Completed
            });
    }
}

/// Rebuild a shared-hold bind that must run again as a queued exclusive
/// writer, keeping its completion, cancellation token, and original age.
/// Returns the response to send instead when the bind was cancelled meanwhile.
fn requeue_as_exclusive<C: ExecutorContext>(
    run_job: &mut RunJob<C>,
    retry_after: Option<Duration>,
) -> Result<QueuedJob<C>, Response> {
    let cancelled = || {
        Response::error(
            run_job.request_id.clone(),
            "request_cancelled",
            "request cancelled before execution",
        )
    };
    // The token went to running when the first attempt started. Put it back
    // to pending so the queued job is cancellable exactly like any other
    // queued job; a cancel that already landed wins.
    if run_job
        .cancellation
        .as_ref()
        .is_some_and(|token| !token.return_to_pending())
    {
        return Err(cancelled());
    }
    requeue_handoff_hook_for_test(&run_job.request_id);
    // Root and lifecycle probes can block. Keep them on the worker; completion
    // still checks the atomic cancellation state under the scheduler lock so a
    // cancel in the handoff window cannot leave queued writer demand behind.
    if run_job
        .cancellation
        .as_ref()
        .is_some_and(JobCancellation::cancel_requested_before_commit)
    {
        return Err(cancelled());
    }
    #[cfg(any(test, feature = "test-support"))]
    requeue_after_probe_hook_for_test(&run_job.request_id);
    let rerun = run_job
        .rerun
        .clone()
        .expect("only a repeatable bind runs with a shared hold");
    let completion = run_job
        .completion
        .take()
        .expect("a requeued bind still owns its completion");
    let next_run = Arc::clone(&rerun);
    Ok(QueuedJob::<C> {
        job: Box::new(move |ctx| next_run(ctx)),
        completion,
        request_id: run_job.request_id.clone(),
        command: run_job.command.clone(),
        queued_at: run_job.queued_at,
        cancellation: run_job.cancellation.clone(),
        maintenance_coalesce_key: None,
        rerun: Some(rerun),
        force_exclusive: true,
        not_before: retry_after.map(|delay| Instant::now() + delay),
        exclusive_attempts: run_job.exclusive_attempts + u32::from(retry_after.is_some()),
        provider_generation: None,
    })
}

/// A request id and callback for one worker-to-scheduler requeue handoff.
#[cfg(any(test, feature = "test-support"))]
type RequeueHandoffHook = (String, Box<dyn FnOnce() + Send>);

#[cfg(any(test, feature = "test-support"))]
static REQUEUE_HANDOFF_HOOK: Mutex<Option<RequeueHandoffHook>> = Mutex::new(None);

/// Run `hook` after returning `request_id`'s token to pending, before the
/// worker's full cancellation probe.
#[cfg(any(test, feature = "test-support"))]
pub fn set_requeue_handoff_hook_for_test(request_id: &str, hook: impl FnOnce() + Send + 'static) {
    *REQUEUE_HANDOFF_HOOK.lock() = Some((request_id.to_string(), Box::new(hook)));
}

#[cfg(any(test, feature = "test-support"))]
fn requeue_handoff_hook_for_test(request_id: &str) {
    let hook = {
        let mut slot = REQUEUE_HANDOFF_HOOK.lock();
        match slot.take() {
            Some((id, hook)) if id == request_id => Some(hook),
            other => {
                *slot = other;
                None
            }
        }
    };
    if let Some(hook) = hook {
        hook();
    }
}

#[cfg(not(any(test, feature = "test-support")))]
fn requeue_handoff_hook_for_test(_request_id: &str) {}

#[cfg(any(test, feature = "test-support"))]
static REQUEUE_AFTER_PROBE_HOOK: Mutex<Option<RequeueHandoffHook>> = Mutex::new(None);

/// Run `hook` after the worker's cancellation probe passes, before the
/// scheduler receives `request_id`'s requeue.
#[cfg(any(test, feature = "test-support"))]
pub fn set_requeue_after_probe_hook_for_test(
    request_id: &str,
    hook: impl FnOnce() + Send + 'static,
) {
    *REQUEUE_AFTER_PROBE_HOOK.lock() = Some((request_id.to_string(), Box::new(hook)));
}

#[cfg(any(test, feature = "test-support"))]
fn requeue_after_probe_hook_for_test(request_id: &str) {
    let hook = {
        let mut slot = REQUEUE_AFTER_PROBE_HOOK.lock();
        match slot.take() {
            Some((id, hook)) if id == request_id => Some(hook),
            other => {
                *slot = other;
                None
            }
        }
    };
    if let Some(hook) = hook {
        hook();
    }
}

#[rustfmt::skip]
test_support_visibility! {
/// How one dispatched job ended on its worker.
enum LaneRun {
    Finished(Response),
    /// A repeatable bind that must run again as an exclusive writer; its
    /// response (if it ran at all) is discarded. `retry_after` delays the
    /// next admission when a detached writer held the epoch gate.
    RerunExclusive {
        retry_after: Option<Duration>,
    },
}
}

/// Delay before a repeatable bind that found the epoch gate held by a
/// detached writer is admitted again: 10 ms, doubling, capped at 200 ms.
fn detached_writer_backoff(attempts: u32) -> Duration {
    Duration::from_millis(10u64.saturating_mul(1u64 << attempts.min(5)).min(200))
}

/// Poll interval for epoch waits that must stay responsive to cancellation.
const EPOCH_WAIT_POLL: Duration = Duration::from_millis(25);

#[rustfmt::skip]
test_support_visibility! {

fn run_lane_job<C: ExecutorContext>(run_job: &mut RunJob<C>) -> LaneRun {
    let _cancellation_ctx = JobCancellationContextGuard::install(run_job.cancellation.clone());
    let _waiting_writers_ctx = ActorWaitingWritersGuard::install(ActorWriterDemand {
        queued: Arc::clone(&run_job.waiting_writers),
        detached: Some(Arc::clone(&run_job.detached_writers)),
    });
    let missing_request_id = run_job.request_id.clone();
    let job = std::mem::replace(
        &mut run_job.job,
        Box::new(move |_| {
            Response::error(
                missing_request_id,
                "job_missing",
                "executor job already taken",
            )
        }),
    );

    let cancelled_before_execution = || {
        Response::error(
            run_job.request_id.clone(),
            "request_cancelled",
            "request cancelled before execution",
        )
    };
    let cancel_requested = || {
        run_job
            .cancellation
            .as_ref()
            .is_some_and(JobCancellation::cancel_requested_before_commit)
    };
    let run = |job: ExecutorJob<C>| {
        if cancel_requested()
            || ((run_job.job_class == JobClass::Maintenance
                || run_job.command == "inspect"
                || run_job.lane == Lane::ProviderMetadata)
                && ((run_job.ctx.subc_unbound_quiesced()
                    && !maintenance_allowed_while_unbound(&run_job.command))
                    || !run_job.root_id.as_path().is_dir()))
        {
            return cancelled_before_execution();
        }
        let can_start = if let Some(generation) = run_job.provider_generation {
            // Only the start decision holds the root lifecycle lock. Once a
            // provider may have committed policy, unbind must not discard it.
            run_job
                .ctx
                .run_if_subc_bound_generation(generation, || {
                    run_job
                        .cancellation
                        .as_ref()
                        .is_none_or(|token| token.mark_running() && token.try_seal_committed())
                })
                .unwrap_or(false)
        } else {
            run_job
                .cancellation
                .as_ref()
                .is_none_or(JobCancellation::mark_running)
        };
        if !can_start {
            return cancelled_before_execution();
        }
        run_job.execution_started.store(true, Ordering::Release);
        job(&run_job.ctx)
    };

    let response = match run_job.lane {
        Lane::PureRead | Lane::SerialLspStatus => {
            if run_job.cancellation.is_some() {
                loop {
                    if let Some(_epoch) = run_job.epoch.try_read_for(EPOCH_WAIT_POLL) {
                        return LaneRun::Finished(run(job));
                    }
                    if cancel_requested() {
                        return LaneRun::Finished(cancelled_before_execution());
                    }
                }
            }
            let _epoch = run_job.epoch.read();
            run(job)
        }
        // Cache and index builders reject stale generations and serialize
        // publication internally. Taking the actor write gate after the command
        // constructs its response would delay completion behind maintenance and
        // park later readers behind an otherwise unnecessary writer.
        Lane::HeavyInit => run(job),
        Lane::ProviderMetadata => {
            let _config = run_job.ctx.pin_config();
            run(job)
        }
        // Call-ledger writes go through the database's own mutex and touch no
        // index state, so they take no epoch gate.
        Lane::CallLedger => run(job),
        Lane::Mutating if run_job.shared_bind_gate => {
            // A cancelled bind never touches the gate.
            if cancel_requested() {
                return LaneRun::Finished(cancelled_before_execution());
            }
            // The epoch lock is task-fair: a reader waits behind any parked
            // writer (a detached view publication, typically) even while only
            // readers hold it. Never wait here; a bind that cannot take the
            // shared hold at once is queued again as an exclusive writer.
            let Some(_epoch) = run_job.epoch.try_read() else {
                return LaneRun::RerunExclusive { retry_after: None };
            };
            let scope = SharedBindScope::install();
            let response = run(job);
            if scope.rerun_requested() {
                return LaneRun::RerunExclusive { retry_after: None };
            }
            response
        }
        // An exclusive repeatable bind is admitted only when no scheduler-
        // tracked reader or maintenance job holds the gate, so a held gate
        // here means a detached view publication. Its write can outlast one
        // install (it takes the process-wide publication lock while holding
        // the gate), so the bind backs off in the queue rather than wait on
        // a worker.
        Lane::Mutating if run_job.rerun.is_some() => {
            if cancel_requested() {
                return LaneRun::Finished(cancelled_before_execution());
            }
            let Some(_epoch) = run_job.epoch.try_write() else {
                return LaneRun::RerunExclusive {
                    retry_after: Some(detached_writer_backoff(run_job.exclusive_attempts)),
                };
            };
            run(job)
        }
        Lane::Mutating => {
            if run_job.cancellation.is_some() {
                loop {
                    if let Some(_epoch) = run_job.epoch.try_write_for(EPOCH_WAIT_POLL) {
                        return LaneRun::Finished(run(job));
                    }
                    if cancel_requested() {
                        return LaneRun::Finished(cancelled_before_execution());
                    }
                }
            }
            let _epoch = run_job.epoch.write();
            run(job)
        }
        Lane::MaintenanceCommit => {
            // Same gate as reads: the job's mutations are protected by the
            // touched subsystems' own locks, and holding only the read gate
            // lets interactive PureReads overlap freely.
            loop {
                if cancel_requested() {
                    return LaneRun::Finished(cancelled_before_execution());
                }
                if let Some(_epoch) = run_job.epoch.try_read_for(EPOCH_WAIT_POLL) {
                    return LaneRun::Finished(run(job));
                }
            }
        }
    };
    LaneRun::Finished(response)
}
}

#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug)]
struct HeavySemaphore {
    available: AtomicUsize,
    max: usize,
}
}

impl HeavySemaphore {
    #[rustfmt::skip]
    test_support_visibility! {
    fn new(permits: usize) -> Self {
        Self {
            available: AtomicUsize::new(permits),
            max: permits,
        }
    }
    }

    #[rustfmt::skip]
    test_support_visibility! {

    fn try_acquire(self: &Arc<Self>) -> Option<HeavyPermit> {
        loop {
            let available = self.available.load(Ordering::Acquire);
            if available == 0 {
                return None;
            }
            if self
                .available
                .compare_exchange(
                    available,
                    available - 1,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_ok()
            {
                return Some(HeavyPermit {
                    semaphore: Arc::clone(self),
                });
            }
        }
    }

    }
}

#[rustfmt::skip]
test_support_visibility! {
struct HeavyPermit {
    semaphore: Arc<HeavySemaphore>,
}
}

impl Drop for HeavyPermit {
    fn drop(&mut self) {
        let previous = self.semaphore.available.fetch_add(1, Ordering::Release);
        debug_assert!(previous < self.semaphore.max);
    }
}

#[cfg(any(test, feature = "test-support"))]
pub mod audit;

#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests;