dynamo-llm 1.7.0

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

//! Backend admission gates: one per backend worker, shared by every backend
//! request path that serves for that worker.
//!
//! Admission happens where a backend receives its typed requests, never in the
//! generic transport. The request planes keep routing serialized requests,
//! responses, cancellation and errors to registered endpoints; a backend's own
//! engine wrapper admits each request through its worker's gate —
//! [`BackendAdmissionGate::admit`], directly or through [`AdmissionEngine`] —
//! before handing it to its engine, and the stream that comes back holds the
//! request's capacity.
//!
//! ```text
//!                                      ┌─> native backend (PreprocessedRequest) ─┐
//! TCP / NATS request plane ─> Ingress ─┤                                         ├─> worker's gate ─> engine
//!                                      └─> Python backend (PythonPayload) ───────┘
//! ```
//!
//! Each backend worker owns its gate through a [`WorkerAdmissionGate`] held by
//! the object that is the worker — the backend-common `Worker`, a native
//! `EngineConfig::InProcessTokens`, or the Python `DistributedRuntime` that
//! serves a Python backend's endpoints — and every endpoint serving for that
//! worker is built with a clone of it. Endpoints of one worker therefore draw
//! on the same capacity, while independent workers, even in one process, share
//! none; nothing ever looks a gate up. Ordinary runtime endpoints — control,
//! indexer and other RPCs, and generic Python endpoints — never reach a gate,
//! and neither do a worker's local health-check canaries, which call its engine
//! directly.
//!
//! # Engine limits
//!
//! Two independent limits govern entry to the engine, and a request enters only
//! when both have room:
//!
//! - The **engine request limit** bounds admitted requests that have not
//!   finished. A request holds request capacity from admission until its
//!   response stream ends or is dropped, however long it then runs.
//! - The **engine request waiting limit** bounds admitted requests still
//!   waiting for their engine's output. A request holds waiting capacity from
//!   admission until the gate observes its first generated token or its
//!   completion, whichever comes first, on every worker role (see
//!   [`ResponseOutput::ends_wait`]). Interim responses — metadata or control
//!   only, such as a disaggregation bootstrap announcement or a cache report —
//!   leave it waiting. The backend classifies its own responses through
//!   [`AdmissionResponse`]; the gate never parses a payload. Obtaining the
//!   stream is not a response.
//!
//! Either limit may be unlimited: it then always has room, but its occupancy is
//! still counted and published. With both unlimited, admission control is
//! disabled (see [Configuration](#configuration)).
//!
//! Admission reserves both together, under one lock, so no request ever holds
//! one while it waits for the other. A request whose stream never produces a
//! response that ends its wait — `generate` fails, the stream ends or fails
//! first, or the request is cancelled or dropped — releases both on the way
//! out. A request whose wait has ended, even by a completion, keeps its request
//! capacity until its stream ends. Every release hands capacity to the queues,
//! so queued work proceeds as soon as it has room.
//!
//! # DP ranks
//!
//! A worker may serve several data-parallel ranks, which its model card reports
//! as a range of global rank IDs: start rank `A` and count `N` serve
//! `A..A + N`. Every limit applies to each rank, and the worker-wide limits
//! aggregate that same capacity, `N` times each per-rank limit, without adding
//! any. A request is admitted under the rank its own decoded body names, read
//! through [`AdmissionRequest`] from the field the backend also reads to choose
//! its engine rank, when that rank is one the worker serves: it then needs room
//! under both its rank's limits and the worker-wide ones, and counts at both.
//! Any other request — naming no rank, arriving before the worker has reported
//! its ranks, or naming a rank the worker does not serve — is admitted as
//! **unspecified**: it needs room under the worker-wide limits only and counts
//! only there, sharing, not adding to, the capacity of every rank. A request
//! keeps the rank it was classified under for its whole stay, however the
//! reported ranks later change, so every release returns exactly what it took.
//!
//! # Queues
//!
//! A request that cannot enter immediately waits in a bounded FIFO queue,
//! holding no engine capacity while it does. Each served rank has its own
//! queue, bounded by the queue limit, and unspecified requests share one more;
//! all of them together are bounded by the worker-wide queue limit. A new
//! arrival is admitted directly only when its own queue is empty, so it never
//! bypasses an older request in it. Whenever capacity is released, the oldest
//! request at the head of any queue that now has all the room it needs is
//! admitted, so a rank at its own limit never blocks another queue and no
//! eligible queue starves. When its queue is full the request is rejected before
//! it reaches the engine; a queue limit of zero disables queueing. Queue
//! residence has no age limit: a request leaves the queue only by admission or
//! cancellation.
//!
//! A rejection is [`ErrorType::WorkerRankOverloaded`] with the request's rank
//! when it is limited to that rank and the worker could still admit or queue
//! other work. Otherwise it is [`ErrorType::WorkerOverloaded`]. A rank-local
//! rejection does not make routing back off from the whole worker.
//!
//! Every queue operation is O(1) in the queue's length: the queues are doubly
//! linked lists threaded through one preallocated pool of slots, and a queued
//! request keeps a handle to its own slot, so a cancellation unlinks exactly
//! that entry without searching, and its slot is reused at once.
//!
//! Choosing the next request to admit scans no queues either. The gate keeps
//! the head of every queue whose rank has room for it in a schedule ordered by
//! arrival, and a transition reschedules only the queues it changed, each at
//! O(log Q) in the Q queues there are: one per rank with queued requests, served
//! or no longer, and one for unspecified work. A head stays scheduled while only
//! the worker-wide limits are full, so whatever frees worker-wide room hands it
//! to the oldest scheduled head at once. Only a change of limits or ranks
//! reschedules every queue.
//!
//! # Configuration
//!
//! Each setting is a per-rank limit, read once when a worker's gate is created,
//! from the first of its environment names that holds a valid value:
//!
//! | Setting | Environment names, in precedence order | Default |
//! |---|---|---|
//! | Engine request limit | `DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT`, `DYN_ENGINE_REQUEST_LIMIT` | unlimited |
//! | Engine request waiting limit | `DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT`, `DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT` | unlimited |
//! | Request queue limit | `DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT`, `DYN_DYNAMO_REQUEST_QUEUE_LIMIT` | `0` |
//!
//! Engine limits must be positive integers, and the queue limit a non-negative
//! one. A value that is set but invalid is warned about and passed over. A
//! Python worker that accepts `--engine-request-limit` applies its value to the
//! canonical engine request limit name before the gate is created, so an
//! explicit flag takes precedence over both environment names.
//!
//! Setting either engine limit enables admission control, and an engine limit
//! left unset stays unlimited. With both unset, the default, admission control
//! is disabled: [`BackendAdmissionGate::admit`] passes every request straight
//! to its engine without taking the gate's lock, counting it or queueing it, so
//! the gate neither delays nor refuses any request and its metrics stay at
//! zero. A positive queue limit then fails the gate's creation, and with it the
//! worker's startup; a queue limit of zero is accepted. Queue storage follows
//! the queue limit either way, so the default queue allocates none.
//!
//! The per-rank limits never change once the gate is created. The engine's
//! reported `max_num_seqs` is only logged, to help tune them. Its reported DP
//! ranks set how many ranks the worker-wide limits aggregate over, at any time,
//! without resetting live occupancy; until they are reported the gate assumes
//! one rank. A lower aggregate evicts nothing: it holds further admission back
//! until occupancy falls below it.
//!
//! TCP requests pass through the TCP work queue and worker pool before reaching
//! this gate, then keep their worker-pool permit while waiting here. The TCP
//! pool can therefore limit how many requests reach the gate at once. Its
//! `DYN_TCP_WORKER_POOL_SIZE` / `DYN_TCP_WORK_QUEUE_SIZE` controls remain
//! separately configured from this gate; NATS has no corresponding TCP-side
//! bound.

use std::collections::{BTreeMap, HashMap};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::Poll;

use dynamo_runtime::component::Component;
use dynamo_runtime::engine::{
    AsyncEngine, AsyncEngineContext, AsyncEngineContextProvider, AsyncEngineStream, Data,
    EngineStream,
};
use dynamo_runtime::error::{BackendError, DynamoError, ErrorType};
use dynamo_runtime::pipeline::{ManyOut, ServiceEngine, SingleIn};
use dynamo_runtime::protocols::annotated::Annotated;
use futures::Stream;
use parking_lot::Mutex;
use tokio::sync::oneshot;

use crate::model_card::ModelDeploymentCard;

mod metrics;

use metrics::{AdmissionSource, BackendAdmissionMetrics, DP_RANK_UNSPECIFIED, RankSeries};

/// Maximum admitted requests that have not finished, per DP rank.
/// `--engine-request-limit` reaches the gate through this name.
const DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT: &str =
    "DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT";

/// Legacy alias of [`DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT`].
const DYN_ENGINE_REQUEST_LIMIT: &str = "DYN_ENGINE_REQUEST_LIMIT";

/// Maximum admitted requests still waiting for the engine's output — a first
/// generated token or a completion, whichever comes first — per DP rank.
const DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT: &str =
    "DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT";

/// Former name of [`DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT`], still
/// accepted as its alias.
const DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT: &str = "DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT";

/// Maximum requests waiting in each DP rank's gate queue.
const DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT: &str = "DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT";

/// Legacy alias of [`DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT`].
const DYN_DYNAMO_REQUEST_QUEUE_LIMIT: &str = "DYN_DYNAMO_REQUEST_QUEUE_LIMIT";

const DEFAULT_REQUEST_QUEUE_LIMIT: usize = 0;

/// How far a limit may exceed the engine's reported capacity before the gate
/// warns that it is unlikely to hold any work back.
const CAPACITY_WARNING_FACTOR: usize = 10;

/// One configuration setting: its environment names in precedence order, and
/// the smallest value it accepts.
struct Setting {
    names: &'static [&'static str],
    min: usize,
}

const ENGINE_REQUEST_LIMIT: Setting = Setting {
    names: &[
        DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT,
        DYN_ENGINE_REQUEST_LIMIT,
    ],
    min: 1,
};

const ENGINE_REQUEST_WAITING_LIMIT: Setting = Setting {
    names: &[
        DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT,
        DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT,
    ],
    min: 1,
};

/// Zero is valid: it disables queueing.
const REQUEST_QUEUE_LIMIT: Setting = Setting {
    names: &[
        DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT,
        DYN_DYNAMO_REQUEST_QUEUE_LIMIT,
    ],
    min: 0,
};

impl Setting {
    /// The first name `lookup` finds valid, with its value, or `None` when the
    /// setting is left at its default.
    ///
    /// A value that is set but is not an integer of at least `min` is warned
    /// about and passed over, so it cannot hide a valid value behind it.
    fn resolve(&self, lookup: &impl Fn(&str) -> Option<String>) -> Option<(&'static str, usize)> {
        for &name in self.names {
            let Some(raw) = lookup(name) else {
                continue;
            };
            match raw.trim().parse::<usize>() {
                Ok(value) if value >= self.min => return Some((name, value)),
                _ => tracing::warn!(
                    env = name,
                    value = %raw,
                    minimum = self.min,
                    "Ignoring invalid backend admission setting; expected an integer no less \
                     than the minimum"
                ),
            }
        }
        None
    }
}

/// The per-rank values configured explicitly, each `None` when left at its
/// default. Read once, when the gate is created; nothing ever replaces one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct ExplicitLimits {
    engine_request_limit: Option<usize>,
    engine_request_waiting_limit: Option<usize>,
    request_queue_limit: Option<usize>,
}

impl ExplicitLimits {
    fn from_environment() -> Result<Self, DynamoError> {
        Self::resolve(|name| std::env::var(name).ok())
    }

    /// Resolve every setting through `lookup`. Pure, so the names, their
    /// precedence and their validation are testable without touching the
    /// process environment.
    ///
    /// A positive queue limit with neither engine limit set is an error: with
    /// admission control disabled, nothing would ever be queued.
    fn resolve(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, DynamoError> {
        let value = |setting: &Setting| setting.resolve(&lookup).map(|(_, value)| value);
        let engine_request_limit = value(&ENGINE_REQUEST_LIMIT);
        let engine_request_waiting_limit = value(&ENGINE_REQUEST_WAITING_LIMIT);
        let request_queue_limit = REQUEST_QUEUE_LIMIT.resolve(&lookup);
        let explicit = Self {
            engine_request_limit,
            engine_request_waiting_limit,
            request_queue_limit: request_queue_limit.map(|(_, limit)| limit),
        };
        if let Some((name, limit)) = request_queue_limit
            && limit > 0
            && !explicit.admission_enabled()
        {
            return Err(DynamoError::builder()
                .error_type(ErrorType::Backend(BackendError::InvalidArgument))
                .message(format!(
                    "Backend admission request queue limit {name}={limit} requires an engine \
                     limit: set {DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT} (or \
                     --engine-request-limit) or {DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT}, \
                     or set {name} to 0"
                ))
                .build());
        }
        Ok(explicit)
    }

    /// Whether these settings enable admission control: either engine limit is
    /// set. A queue limit alone does not.
    fn admission_enabled(&self) -> bool {
        self.engine_request_limit.is_some() || self.engine_request_waiting_limit.is_some()
    }
}

/// The global DP ranks a worker serves, as its model card reports
/// them: `start` through `start + count - 1`, which map to local slots `0`
/// through `count - 1`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RankRange {
    start: u32,
    /// At least one.
    count: u32,
}

impl RankRange {
    fn contains(&self, rank: u32) -> bool {
        rank.checked_sub(self.start)
            .is_some_and(|slot| slot < self.count)
    }

    fn ranks(&self) -> impl Iterator<Item = u32> + '_ {
        (0..self.count).map_while(|slot| self.start.checked_add(slot))
    }
}

impl std::fmt::Display for RankRange {
    /// As the half-open range of global rank IDs, e.g. `[4, 6)`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let end = u64::from(self.start) + u64::from(self.count);
        write!(f, "[{}, {end})", self.start)
    }
}

/// The limits the gate enforces. Each is per DP rank; its worker-wide limit is
/// the same capacity aggregated over `rank_count` ranks. An engine limit of
/// `None` is unlimited.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct AdmissionLimits {
    /// Admitted requests that have not finished.
    engine_request_limit: Option<usize>,
    /// Admitted requests still waiting for the engine's output.
    engine_request_waiting_limit: Option<usize>,
    /// Requests waiting in a queue.
    request_queue_limit: usize,
    /// The ranks the worker serves: one until it reports them.
    rank_count: usize,
}

impl AdmissionLimits {
    /// The limits for these explicit settings over `rank_count` ranks. Each
    /// setting resolves independently, to its explicit value or its default:
    /// unlimited for an engine limit, and no queue. The engine's capacity never
    /// enters into them.
    fn resolve(explicit: &ExplicitLimits, rank_count: usize) -> Self {
        Self {
            engine_request_limit: explicit.engine_request_limit,
            engine_request_waiting_limit: explicit.engine_request_waiting_limit,
            request_queue_limit: explicit
                .request_queue_limit
                .unwrap_or(DEFAULT_REQUEST_QUEUE_LIMIT),
            rank_count,
        }
    }

    /// The worker-wide limit for a per-rank one.
    fn aggregate(&self, per_rank_limit: usize) -> usize {
        per_rank_limit.saturating_mul(self.rank_count)
    }
}

/// The capacity a worker's engine has reported to its gate: its `max_num_seqs`
/// per rank and the DP ranks it serves, each `None` until reported. Logged with
/// the configuration to help tune the limits; it never sets one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct DetectedCapacity {
    max_num_seqs: Option<usize>,
    served: Option<RankRange>,
}

/// The effective configuration, copied out of the gate's state so it is logged
/// with no lock held.
#[derive(Clone, Copy, Debug)]
struct LimitsSnapshot {
    limits: AdmissionLimits,
    detected: DetectedCapacity,
}

impl LimitsSnapshot {
    /// Log it at INFO: each per-rank limit, an unset engine limit as
    /// `unlimited`, and the engine's detected DP ranks and `max_num_seqs`,
    /// each still unreported as `unavailable`.
    fn log(&self) {
        fn shown(value: Option<impl std::fmt::Display>, missing: &str) -> String {
            value.map_or_else(|| missing.to_string(), |value| value.to_string())
        }
        let limits = self.limits;
        tracing::info!(
            engine_request_limit = %shown(limits.engine_request_limit, "unlimited"),
            engine_request_waiting_limit = %shown(limits.engine_request_waiting_limit, "unlimited"),
            request_queue_limit = limits.request_queue_limit,
            detected_dp_ranks = %shown(self.detected.served, "unavailable"),
            detected_max_num_seqs = %shown(self.detected.max_num_seqs, "unavailable"),
            "Backend admission configuration"
        );
    }
}

/// A nonzero limit more than [`CAPACITY_WARNING_FACTOR`] times the engine's
/// reported capacity, which is unlikely to hold any work back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct CapacityWarning {
    setting: &'static str,
    per_rank_limit: usize,
    max_num_seqs: usize,
    rank_count: usize,
}

impl CapacityWarning {
    /// Every limit in `limits` that exceeds `max_num_seqs` by more than the
    /// warning factor; an unlimited one is no such limit. A per-rank limit is
    /// compared with per-rank capacity; the worker-wide one with the worker's
    /// capacity, which is the same ratio.
    fn check(limits: &AdmissionLimits, max_num_seqs: usize) -> Vec<Self> {
        let threshold = max_num_seqs.saturating_mul(CAPACITY_WARNING_FACTOR);
        [
            (
                DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT,
                limits.engine_request_limit,
            ),
            (
                DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT,
                limits.engine_request_waiting_limit,
            ),
            (
                DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT,
                Some(limits.request_queue_limit),
            ),
        ]
        .into_iter()
        .filter_map(|(setting, limit)| limit.map(|limit| (setting, limit)))
        .filter(|&(_, limit)| limit > threshold)
        .map(|(setting, per_rank_limit)| Self {
            setting,
            per_rank_limit,
            max_num_seqs,
            rank_count: limits.rank_count,
        })
        .collect()
    }

    fn log(&self) {
        tracing::warn!(
            setting = self.setting,
            per_rank_limit = self.per_rank_limit,
            per_rank_capacity = self.max_num_seqs,
            worker_limit = self.per_rank_limit.saturating_mul(self.rank_count),
            worker_capacity = self.max_num_seqs.saturating_mul(self.rank_count),
            "Backend admission limit is more than {CAPACITY_WARNING_FACTOR}x the engine's \
             reported max_num_seqs, so it is unlikely to hold work back"
        );
    }
}

/// The message a shed request is refused with when the worker can take no more
/// work.
const OVERLOADED_MESSAGE: &str = "Server overloaded: worker at capacity";

/// The message a shed request is refused with when only its DP rank is full.
const RANK_OVERLOADED_MESSAGE: &str = "Server overloaded: DP rank at capacity";

/// The message a request cancelled while queued is refused with. It is
/// deliberately not an overload: the caller went away, which is not
/// backpressure.
const CANCELLED_MESSAGE: &str = "Request cancelled while queued for backend admission";

/// Shares one worker's gate between model registration and endpoint serving
/// setup, which Python backends can run concurrently. Serving paths therefore
/// need a shared handle before registration initializes the gate.
///
/// Model registration supplies the component needed to register gate metrics
/// and initializes the gate before publishing the backend. Invalid gate
/// configuration aborts registration, so model requests should always find an
/// initialized gate; the error from `get()` is only a failsafe.
///
/// Initializing during endpoint serving setup instead would leave model-card
/// reports from earlier registration waiting for a gate, requiring additional
/// coordination. Remove this wrapper when startup runs model registration to
/// completion before constructing the serving paths; those paths can then
/// receive the initialized `Arc<BackendAdmissionGate>` directly.
///
/// Clones share one gate; separately created handles never do.
#[derive(Clone, Default)]
pub struct WorkerAdmissionGate(Arc<OnceLock<Arc<BackendAdmissionGate>>>);

impl WorkerAdmissionGate {
    /// The worker's gate, created by the first call — as the worker first
    /// registers or serves as a model backend — with its settings read from
    /// the environment then, once. An invalid configuration fails the call
    /// and creates nothing, so the worker must not start serving.
    ///
    /// `component` is the one the worker serves. It only labels the gate's
    /// metric family and exposes it, once, on that component's registry when
    /// the gate is created (see [`metrics`]); it never selects a gate, and a
    /// later call through any endpoint of the worker returns the same one.
    pub fn get_or_create(
        &self,
        component: &Component,
    ) -> Result<Arc<BackendAdmissionGate>, DynamoError> {
        if let Some(gate) = self.0.get() {
            return Ok(Arc::clone(gate));
        }
        let explicit = ExplicitLimits::from_environment()?;
        Ok(Arc::clone(self.0.get_or_init(|| {
            BackendAdmissionGate::for_component(component, explicit)
        })))
    }

    /// Return the gate initialized during backend startup, or log and return
    /// an error if startup has not initialized it.
    pub fn get(&self) -> Result<Arc<BackendAdmissionGate>, DynamoError> {
        self.0.get().cloned().ok_or_else(|| {
            let message = "Backend admission gate has not been initialized";
            tracing::error!("{message}");
            DynamoError::builder()
                .error_type(ErrorType::Internal)
                .message(message)
                .build()
        })
    }
}

/// A backend request, which may name the global DP rank its router selected
/// for it.
///
/// Only backend request types implement this, at the boundary where their
/// backend admits them; the generic transport never asks. The gate admits a
/// request under this rank, so it must be the rank in the request's own body —
/// the field the backend reads to choose the engine rank that serves it — set
/// by routing for each dispatch. It is read once, before admission, so it must
/// be a constant-time read of the decoded request, never a parse.
pub trait AdmissionRequest {
    /// The global DP rank this request names, or `None` when it names none.
    fn dp_rank(&self) -> Option<u32>;
}

/// What one backend response carries, as far as its request's wait for the
/// engine is concerned: the backend's own reading of its response contract.
///
/// The two facts are independent. A response may carry both — a last token
/// with its finish reason — or neither: an interim response, metadata or
/// control only, such as a disaggregation bootstrap announcement, a cache
/// report or an annotation. A completion response may report an error finish
/// reason; an annotated error frame remains interim.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ResponseOutput {
    /// It carries at least one generated token.
    pub generated_token: bool,
    /// It is the backend's completion response for the request, which need
    /// not carry a token.
    pub completion: bool,
}

impl ResponseOutput {
    /// Metadata or control only.
    pub const INTERIM: Self = Self {
        generated_token: false,
        completion: false,
    };

    /// Whether a response carrying this output ends its request's wait: it
    /// carries a generated token or is the completion. The gate applies this
    /// one rule to every worker role, and reads no classification after the
    /// first response that ends the wait, so a backend classifying its
    /// responses as it produces them can stop there too.
    #[inline]
    pub fn ends_wait(self) -> bool {
        self.generated_token || self.completion
    }
}

/// A backend response type, which classifies each of its items for admission.
///
/// The backend implements this from its own response contract, at its own
/// boundary; the gate only applies [`ResponseOutput::ends_wait`] to the
/// classification and never interprets a payload itself. It is asked about
/// each item while the request still holds waiting capacity, so it must be a
/// cheap read of the item, never a parse.
pub trait AdmissionResponse {
    fn admission_output(&self) -> ResponseOutput;
}

/// Only an annotated response's data can carry output: an error frame, or an
/// event or comment without data, is interim.
impl<T: AdmissionResponse> AdmissionResponse for Annotated<T> {
    fn admission_output(&self) -> ResponseOutput {
        match &self.data {
            Some(data) if !self.is_error() => data.admission_output(),
            _ => ResponseOutput::INTERIM,
        }
    }
}

/// A backend engine whose every request is admitted through its worker's gate
/// first: the typed wrapper a native backend serves on its network ingress.
///
/// Each request is admitted under the rank it names, and its stream holds
/// waiting capacity until the first response that ends the wait. Serve only
/// the network path through it: local callers and health-check canaries use
/// the inner engine, outside admission.
pub struct AdmissionEngine<Req: Data, Resp: Data> {
    gate: Arc<BackendAdmissionGate>,
    engine: ServiceEngine<SingleIn<Req>, ManyOut<Resp>>,
}

impl<Req: Data, Resp: Data> AdmissionEngine<Req, Resp> {
    /// Admit `engine`'s network requests through `gate`, its worker's.
    pub fn new(
        gate: Arc<BackendAdmissionGate>,
        engine: ServiceEngine<SingleIn<Req>, ManyOut<Resp>>,
    ) -> Arc<Self> {
        Arc::new(Self { gate, engine })
    }
}

#[async_trait::async_trait]
impl<Req, Resp> AsyncEngine<SingleIn<Req>, ManyOut<Resp>, anyhow::Error>
    for AdmissionEngine<Req, Resp>
where
    Req: Data + AdmissionRequest,
    Resp: Data + AdmissionResponse,
{
    async fn generate(&self, request: SingleIn<Req>) -> anyhow::Result<ManyOut<Resp>> {
        if !self.gate.enabled {
            return self.engine.generate(request).await;
        }
        let context = request.context();
        let dp_rank = AdmissionRequest::dp_rank(&*request);
        self.gate
            .admit(&context, dp_rank, self.engine.generate(request))
            .await
    }
}

/// Why the gate refused a request. Private: callers see only the typed error
/// [`reject`] builds from it, so no admission state escapes this module.
enum Rejection {
    /// The request could not be admitted and its queue had no room for it.
    /// `dp_rank` is its DP rank when the worker could still take other work
    /// (see [`GateState::refusal_rank`]), or `None` for the whole worker.
    QueueFull { dp_rank: Option<u32> },
    /// The request was cancelled before it was admitted.
    Cancelled,
}

/// Trace a refusal against the request it refused, and build the error the
/// caller fails it with.
///
/// Shedding is backpressure on this one worker, so it carries
/// [`ErrorType::WorkerOverloaded`], or [`ErrorType::WorkerRankOverloaded`] when
/// it is limited to the request's DP rank. A cancellation is not backpressure: the
/// caller went away, so classifying it as an overload would misreport a worker
/// that never refused anything.
fn reject(rejection: Rejection, context: Option<&Arc<dyn AsyncEngineContext>>) -> DynamoError {
    let request_id = context.map(|context| context.id()).unwrap_or_default();
    let (error_type, message) = match rejection {
        Rejection::QueueFull { dp_rank: None } => {
            tracing::warn!(
                request_id,
                "Worker at capacity (an engine limit and the queue are both full), rejecting \
                 request"
            );
            (ErrorType::WorkerOverloaded, OVERLOADED_MESSAGE)
        }
        Rejection::QueueFull {
            dp_rank: Some(dp_rank),
        } => {
            tracing::warn!(
                request_id,
                dp_rank,
                "DP rank at capacity while the worker can still take other work, rejecting \
                 request"
            );
            (
                ErrorType::WorkerRankOverloaded(dp_rank),
                RANK_OVERLOADED_MESSAGE,
            )
        }
        Rejection::Cancelled => {
            tracing::debug!(request_id, "{CANCELLED_MESSAGE}");
            (ErrorType::Cancelled, CANCELLED_MESSAGE)
        }
    };
    DynamoError::builder()
        .error_type(error_type)
        .message(message)
        .build()
}

/// The occupancy a request is counted under for its whole stay at the gate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum AdmissionRank {
    /// A global DP rank the worker served when the request arrived.
    Rank(u32),
    /// No usable rank: none was supplied, the worker had not reported its
    /// ranks yet, or it does not serve the supplied one.
    Unspecified,
}

impl AdmissionRank {
    /// The `dp_rank` label of this rank's metric series.
    fn label(self) -> String {
        match self {
            AdmissionRank::Rank(rank) => rank.to_string(),
            AdmissionRank::Unspecified => DP_RANK_UNSPECIFIED.to_string(),
        }
    }
}

/// Why a request that supplied a rank is admitted as unspecified.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RankFallback {
    /// The worker has not reported which ranks it serves yet.
    RanksUnreported { supplied: u32 },
    /// The worker does not serve the supplied rank.
    OutOfRange { supplied: u32, served: RankRange },
}

impl RankFallback {
    fn warn(self, request_id: &str) {
        match self {
            RankFallback::RanksUnreported { supplied } => tracing::warn!(
                request_id,
                dp_rank = supplied,
                "DP rank setup is not reported yet; admitting the request as unspecified-rank \
                 work"
            ),
            RankFallback::OutOfRange { supplied, served } => tracing::warn!(
                request_id,
                dp_rank = supplied,
                served_dp_ranks = %served,
                "Request names a DP rank this worker does not serve; admitting it as \
                 unspecified-rank work"
            ),
        }
    }
}

/// Classify a request's supplied rank against the ranks the worker serves.
///
/// A rank inside the served range is used as is. Without a supplied rank the
/// request is unspecified, with nothing to warn about. A supplied rank the gate
/// cannot use — the ranks are not reported yet, or it is outside them — is
/// also unspecified, never rejected, and reported as a fallback to warn about.
/// The request's own routing fields are untouched either way.
fn classify(
    supplied: Option<u32>,
    served: Option<RankRange>,
) -> (AdmissionRank, Option<RankFallback>) {
    match (supplied, served) {
        (None, _) => (AdmissionRank::Unspecified, None),
        (Some(supplied), None) => (
            AdmissionRank::Unspecified,
            Some(RankFallback::RanksUnreported { supplied }),
        ),
        (Some(rank), Some(served)) if served.contains(rank) => (AdmissionRank::Rank(rank), None),
        (Some(supplied), Some(served)) => (
            AdmissionRank::Unspecified,
            Some(RankFallback::OutOfRange { supplied, served }),
        ),
    }
}

/// Occupancy of one admission measure across a worker's DP ranks.
///
/// The gate keeps three: engine requests, engine-waiting requests and queued
/// requests. Each owns its measure's limits and counts and nothing else — no
/// lock, no queue, no request lifetimes. The gate checks every measure a
/// transition needs before changing any of them, under its one mutex, so the
/// three always change together.
///
/// A request with a rank counts at that rank and in the worker total; an
/// unspecified one counts only in the total, through the unspecified count. The
/// total is therefore always the ranks' counts plus the unspecified count, and
/// both kinds draw on the one aggregate limit: unspecified requests have no
/// capacity of their own. An unlimited measure always has room, and counts all
/// the same.
#[derive(Debug)]
struct DpRankCounts {
    /// Each rank's limit, or `None` when unlimited.
    per_rank_limit: Option<usize>,
    /// The worker-wide limit: the per-rank limit over every served rank.
    aggregate_limit: Option<usize>,
    /// Each rank's count, for ranks with any; a rank that drains is dropped.
    ranks: HashMap<u32, usize>,
    /// Requests counted without a rank.
    unspecified: usize,
    /// Every request counted, with a rank or without.
    total: usize,
}

impl DpRankCounts {
    fn new(per_rank_limit: Option<usize>, rank_count: usize) -> Self {
        Self {
            per_rank_limit,
            aggregate_limit: per_rank_limit.map(|limit| limit.saturating_mul(rank_count)),
            ranks: HashMap::new(),
            unspecified: 0,
            total: 0,
        }
    }

    /// Replace the limits, keeping every count: a lower limit evicts nothing,
    /// it only holds further acquisitions back until the counts fall below it.
    fn set_limits(&mut self, per_rank_limit: Option<usize>, rank_count: usize) {
        self.per_rank_limit = per_rank_limit;
        self.aggregate_limit = per_rank_limit.map(|limit| limit.saturating_mul(rank_count));
    }

    /// Whether one more request fits under the worker-wide limit, whatever
    /// its rank.
    fn has_aggregate_room(&self) -> bool {
        self.aggregate_limit.is_none_or(|limit| self.total < limit)
    }

    /// Whether one more request of `rank` fits under its rank's own limit,
    /// whatever the worker-wide one: always, for an unspecified request, which
    /// has no rank limit.
    fn has_rank_room(&self, rank: AdmissionRank) -> bool {
        match rank {
            AdmissionRank::Rank(_) => self
                .per_rank_limit
                .is_none_or(|limit| self.count(rank) < limit),
            AdmissionRank::Unspecified => true,
        }
    }

    /// Whether one more request of `rank` fits: under the worker-wide limit,
    /// and under its rank's limit when it has one.
    fn has_room(&self, rank: AdmissionRank) -> bool {
        self.has_aggregate_room() && self.has_rank_room(rank)
    }

    /// Count one request of `rank`. The caller has already checked
    /// [`Self::has_room`] for everything the transition needs.
    fn acquire(&mut self, rank: AdmissionRank) {
        match rank {
            AdmissionRank::Rank(rank) => *self.ranks.entry(rank).or_default() += 1,
            AdmissionRank::Unspecified => self.unspecified += 1,
        }
        self.total += 1;
    }

    /// Stop counting one request of `rank`, which it acquired under that same
    /// rank.
    fn release(&mut self, rank: AdmissionRank) {
        match rank {
            AdmissionRank::Rank(rank) => {
                let count = self
                    .ranks
                    .get_mut(&rank)
                    .expect("released a DP rank that holds no count");
                *count -= 1;
                if *count == 0 {
                    self.ranks.remove(&rank);
                }
            }
            AdmissionRank::Unspecified => {
                self.unspecified = self
                    .unspecified
                    .checked_sub(1)
                    .expect("released an unspecified count that was never acquired");
            }
        }
        self.total -= 1;
    }

    /// The count of `rank`: one rank's, or the unspecified count.
    fn count(&self, rank: AdmissionRank) -> usize {
        match rank {
            AdmissionRank::Rank(rank) => self.ranks.get(&rank).copied().unwrap_or_default(),
            AdmissionRank::Unspecified => self.unspecified,
        }
    }

    /// Every request counted, with a rank or without.
    #[cfg(test)]
    fn total(&self) -> usize {
        self.total
    }
}

/// No slot: the end of a list.
const NIL: u32 = u32::MAX;

/// One FIFO of queued requests: its two ends in the shared [`QueueSlots`]
/// pool. Each rank with queued requests has one, and so do unspecified
/// requests.
#[derive(Debug)]
struct Fifo {
    head: u32,
    tail: u32,
    /// The arrival its head is scheduled under in [`GateState::schedule`],
    /// while it is scheduled.
    scheduled: Option<u64>,
}

impl Fifo {
    fn new() -> Self {
        Self {
            head: NIL,
            tail: NIL,
            scheduled: None,
        }
    }

    fn is_empty(&self) -> bool {
        self.head == NIL
    }
}

/// Where a queued request sits: its slot, and the generation the slot had when
/// the request took it. Every release of a slot advances its generation, so a
/// handle that outlives its entry can never reach the request that reuses the
/// slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct QueueHandle {
    slot: u32,
    generation: u64,
}

/// A queued request, as the gate sees it.
struct Waiter {
    /// Sending on it hands the request engine capacity already reserved for
    /// it. Dropping it unsent tells the request the gate discarded it,
    /// cancelled, at its dequeue.
    grant: oneshot::Sender<()>,
    /// Arrival order across every queue, so capacity goes to the oldest
    /// request that can use it.
    arrival: u64,
    /// The caller's context, checked once more at the dequeue decision.
    context: Option<Arc<dyn AsyncEngineContext>>,
}

/// One entry of the slot pool: either queued, and linked into its FIFO, or
/// free, and linked into the free list through `next`.
struct Slot {
    prev: u32,
    next: u32,
    generation: u64,
    waiter: Option<Waiter>,
}

/// Storage for every gate queue: one pool of slots, threaded into doubly
/// linked FIFOs and a free list.
///
/// Every operation is O(1) in the queue's length — enqueue, inspecting and
/// removing the head, and removing any entry through its handle, which unlinks
/// exactly that slot from its neighbours with no search. A removed slot is
/// reused at once, so storage stays bounded by the most requests ever queued
/// at the same time. Slots are allocated only by [`Self::reserve`], when the
/// gate is created or its queue capacity grows, never by a queue operation.
struct QueueSlots {
    slots: Vec<Slot>,
    /// The first free slot, or [`NIL`] when every slot is taken.
    free: u32,
    /// Slot reads and writes, so tests can prove an operation does constant
    /// work however long the queue is.
    #[cfg(test)]
    steps: usize,
}

impl QueueSlots {
    /// The most slots the pool can index; [`NIL`] is reserved.
    const MAX_SLOTS: usize = NIL as usize;

    fn with_capacity(capacity: usize) -> Self {
        let mut slots = Self {
            slots: Vec::new(),
            free: NIL,
            #[cfg(test)]
            steps: 0,
        };
        slots.reserve(capacity);
        slots
    }

    /// Slots in the pool, free or queued.
    #[cfg(test)]
    fn capacity(&self) -> usize {
        self.slots.len()
    }

    /// Grow the pool to hold at least `capacity` requests at once. Never
    /// shrinks it, so every live handle stays valid. If the allocation fails,
    /// the pool keeps its size and the gate rejects what it cannot queue.
    fn reserve(&mut self, capacity: usize) {
        let capacity = capacity.min(Self::MAX_SLOTS);
        let additional = capacity.saturating_sub(self.slots.len());
        if additional == 0 {
            return;
        }
        if let Err(error) = self.slots.try_reserve_exact(additional) {
            tracing::error!(
                %error,
                capacity,
                "Cannot allocate backend admission queue storage; requests beyond the existing \
                 storage will be rejected"
            );
            return;
        }
        // New slots go to the front of the free list, each pointing at the one
        // after it and the last at the old head.
        let first = self.slots.len() as u32;
        let last = (self.slots.len() + additional - 1) as u32;
        for index in first..=last {
            let next = if index == last { self.free } else { index + 1 };
            self.slots.push(Slot {
                prev: NIL,
                next,
                generation: 0,
                waiter: None,
            });
        }
        self.free = first;
    }

    fn slot(&self, index: u32) -> &Slot {
        &self.slots[index as usize]
    }

    fn slot_mut(&mut self, index: u32) -> &mut Slot {
        #[cfg(test)]
        {
            self.steps += 1;
        }
        &mut self.slots[index as usize]
    }

    /// Whether the pool has a free slot, so a request can queue.
    fn has_free_slot(&self) -> bool {
        self.free != NIL
    }

    /// Queue `waiter` at the tail of `fifo`, or hand it back when the pool is
    /// full.
    fn push_back(&mut self, fifo: &mut Fifo, waiter: Waiter) -> Result<QueueHandle, Waiter> {
        let index = self.free;
        if index == NIL {
            return Err(waiter);
        }
        let tail = fifo.tail;
        let slot = self.slot_mut(index);
        let free = slot.next;
        slot.prev = tail;
        slot.next = NIL;
        slot.waiter = Some(waiter);
        let generation = slot.generation;
        self.free = free;
        if tail == NIL {
            fifo.head = index;
        } else {
            self.slot_mut(tail).next = index;
        }
        fifo.tail = index;
        Ok(QueueHandle {
            slot: index,
            generation,
        })
    }

    /// The request at the head of `fifo`.
    fn front(&self, fifo: &Fifo) -> Option<&Waiter> {
        if fifo.is_empty() {
            return None;
        }
        self.slot(fifo.head).waiter.as_ref()
    }

    /// Dequeue the request at the head of `fifo`.
    fn pop_front(&mut self, fifo: &mut Fifo) -> Option<Waiter> {
        if fifo.is_empty() {
            return None;
        }
        Some(self.unlink(fifo, fifo.head))
    }

    /// Dequeue the request `handle` names, wherever it is in `fifo`, or `None`
    /// when the handle no longer names a queued request: it was dequeued
    /// already, and its slot may since hold another request.
    fn remove(&mut self, fifo: &mut Fifo, handle: QueueHandle) -> Option<Waiter> {
        let slot = self.slots.get(handle.slot as usize)?;
        if slot.generation != handle.generation || slot.waiter.is_none() {
            return None;
        }
        Some(self.unlink(fifo, handle.slot))
    }

    /// Unlink the queued slot `index` from `fifo` by joining its neighbours —
    /// or moving the head or tail when it is at an end — then free it under a
    /// new generation.
    fn unlink(&mut self, fifo: &mut Fifo, index: u32) -> Waiter {
        let free = self.free;
        let slot = self.slot_mut(index);
        let (prev, next) = (slot.prev, slot.next);
        let waiter = slot
            .waiter
            .take()
            .expect("unlinked a slot that holds no queued request");
        slot.generation += 1;
        slot.prev = NIL;
        slot.next = free;
        self.free = index;
        if prev == NIL {
            fifo.head = next;
        } else {
            self.slot_mut(prev).next = next;
        }
        if next == NIL {
            fifo.tail = prev;
        } else {
            self.slot_mut(next).prev = prev;
        }
        waiter
    }
}

/// The gate's state, behind its one lock.
struct GateState {
    explicit: ExplicitLimits,
    /// The engine's `max_num_seqs` per rank and the ranks the worker serves,
    /// each once a model card reports it.
    detected: DetectedCapacity,
    limits: AdmissionLimits,
    /// Admitted requests that have not finished, including those whose wait
    /// for the engine's output has already ended.
    engine_requests: DpRankCounts,
    /// Admitted requests still waiting for the engine's output; each is also
    /// counted in `engine_requests`.
    engine_requests_waiting: DpRankCounts,
    /// Requests waiting in a queue; they hold neither engine count.
    queued: DpRankCounts,
    /// The queue of each rank with queued requests, and of unspecified ones.
    /// Never empty: a queue is dropped as its last request leaves.
    queues: HashMap<AdmissionRank, Fifo>,
    /// The candidates for the next admission: the head of every queue whose
    /// rank's own limits have room for it, by arrival, oldest first. The
    /// worker-wide limits are the same for every queue, so they are checked
    /// apart, and a head stays scheduled while only they are full.
    schedule: BTreeMap<u64, AdmissionRank>,
    slots: QueueSlots,
    next_arrival: u64,
    metrics: BackendAdmissionMetrics,
    /// Each rank's series, resolved once, and whether the current transition
    /// changed its occupancy.
    series: HashMap<AdmissionRank, RankMetrics>,
    /// Ranks whose occupancy the current transition changed, each once, to
    /// publish.
    touched: Vec<AdmissionRank>,
    /// The limits and capacity the capacity warning was last checked for, so
    /// a repeated report does not repeat it.
    capacity_checked: Option<(AdmissionLimits, usize)>,
    /// Queues the scheduler examined, so tests can prove a transition examines
    /// only those it changed, however many there are.
    #[cfg(test)]
    schedule_steps: usize,
    /// Ranks published, so tests can prove a transition publishes each rank it
    /// changed exactly once, and no other.
    #[cfg(test)]
    publications: usize,
}

/// One rank's metric series, resolved once so the gate never formats a label
/// on its hot path, and whether the current transition has changed the rank's
/// occupancy, so it is listed for publication once however often it changes.
struct RankMetrics {
    series: Arc<RankSeries>,
    touched: bool,
}

impl GateState {
    fn new(explicit: ExplicitLimits, metrics: BackendAdmissionMetrics) -> Self {
        let limits = AdmissionLimits::resolve(&explicit, 1);
        let mut state = Self {
            explicit,
            detected: DetectedCapacity::default(),
            limits,
            engine_requests: DpRankCounts::new(limits.engine_request_limit, limits.rank_count),
            engine_requests_waiting: DpRankCounts::new(
                limits.engine_request_waiting_limit,
                limits.rank_count,
            ),
            queued: DpRankCounts::new(Some(limits.request_queue_limit), limits.rank_count),
            queues: HashMap::new(),
            schedule: BTreeMap::new(),
            slots: QueueSlots::with_capacity(limits.aggregate(limits.request_queue_limit)),
            next_arrival: 0,
            metrics,
            series: HashMap::new(),
            touched: Vec::new(),
            capacity_checked: None,
            #[cfg(test)]
            schedule_steps: 0,
            #[cfg(test)]
            publications: 0,
        };
        // Scrapeable at zero before the first request.
        state.series(AdmissionRank::Unspecified);
        state
    }

    fn snapshot(&self) -> LimitsSnapshot {
        LimitsSnapshot {
            limits: self.limits,
            detected: self.detected,
        }
    }

    /// The metrics of `rank`, its series created at zero on first use.
    fn rank_metrics(&mut self, rank: AdmissionRank) -> &mut RankMetrics {
        let metrics = &self.metrics;
        self.series.entry(rank).or_insert_with(|| RankMetrics {
            series: Arc::new(metrics.series(&rank.label())),
            touched: false,
        })
    }

    /// The metric series of `rank`, created at zero on first use.
    fn series(&mut self, rank: AdmissionRank) -> Arc<RankSeries> {
        Arc::clone(&self.rank_metrics(rank).series)
    }

    /// Note that `rank`'s occupancy changed, so the transition publishes it,
    /// once however often it changes: its own flag says whether it is listed
    /// already, so noting it is O(1) however many ranks the transition changes.
    fn touch(&mut self, rank: AdmissionRank) {
        if !std::mem::replace(&mut self.rank_metrics(rank).touched, true) {
            self.touched.push(rank);
        }
    }

    /// Publish the occupancy of every rank the transition changed, from the
    /// authoritative counts, and nothing else. The scratch list keeps its
    /// capacity, so a warm gate allocates nothing here.
    fn publish(&mut self) {
        let mut touched = std::mem::take(&mut self.touched);
        for rank in touched.drain(..) {
            let engine_requests = self.engine_requests.count(rank);
            let waiting = self.engine_requests_waiting.count(rank);
            let queued = self.queued.count(rank);
            let metrics = self
                .series
                .get_mut(&rank)
                .expect("a touched rank has its series");
            metrics.touched = false;
            metrics
                .series
                .set_occupancy(engine_requests, waiting, queued);
            #[cfg(test)]
            {
                self.publications += 1;
            }
        }
        self.touched = touched;
    }

    /// Whether the worker-wide limits of both engine measures have room for
    /// one more request, whatever its rank.
    fn has_aggregate_engine_room(&self) -> bool {
        self.engine_requests.has_aggregate_room()
            && self.engine_requests_waiting.has_aggregate_room()
    }

    /// Whether `rank`'s own limits of both engine measures have room for one
    /// more of its requests: always, for unspecified work.
    fn has_rank_engine_room(&self, rank: AdmissionRank) -> bool {
        self.engine_requests.has_rank_room(rank) && self.engine_requests_waiting.has_rank_room(rank)
    }

    /// Whether one more request of `rank` can enter the engine: both engine
    /// measures need room, at its rank and worker-wide.
    fn has_engine_room(&self, rank: AdmissionRank) -> bool {
        self.has_aggregate_engine_room() && self.has_rank_engine_room(rank)
    }

    /// The DP rank to limit the refusal of a request of `rank` to, when it
    /// could neither enter the engine nor queue: its own while the worker could
    /// still take other work, or `None` to refuse it for the whole worker.
    ///
    /// Whichever limit refused this request, the worker could take other work
    /// in either of two ways. An unspecified request could enter the engine at
    /// once while both engine measures have worker-wide room, since no
    /// unspecified request is left queued then; and it could queue while the
    /// worker-wide queue limit has room and the queue storage, which every
    /// queue shares, has a free slot. Only when neither holds is the refusal
    /// the whole worker's, as an unspecified request's refusal therefore
    /// always is.
    fn refusal_rank(&self, rank: AdmissionRank) -> Option<u32> {
        let AdmissionRank::Rank(rank) = rank else {
            return None;
        };
        let can_enter = self.has_aggregate_engine_room();
        let can_queue = self.queued.has_aggregate_room() && self.slots.has_free_slot();
        (can_enter || can_queue).then_some(rank)
    }

    /// Reserve both engine measures for one request of `rank` entering the
    /// engine. Always together, so no request holds one while it waits for the
    /// other.
    fn take_engine(&mut self, rank: AdmissionRank) {
        self.engine_requests.acquire(rank);
        self.engine_requests_waiting.acquire(rank);
        self.touch(rank);
        self.reschedule(rank);
    }

    /// Bring `rank`'s queue up to date in the schedule after its head, or its
    /// rank's room, changed: its head is scheduled under its own arrival
    /// exactly while its rank's limits have room for it. A queue left empty is
    /// dropped.
    ///
    /// Examines that one queue, at O(log Q) in the Q queues scheduled, so a
    /// transition never revisits a queue it did not change. A rank with no
    /// queue, the usual case, costs one lookup.
    fn reschedule(&mut self, rank: AdmissionRank) {
        let Some(fifo) = self.queues.get_mut(&rank) else {
            return;
        };
        #[cfg(test)]
        {
            self.schedule_steps += 1;
        }
        let head = self.slots.front(fifo).map(|waiter| waiter.arrival);
        // [`Self::has_rank_engine_room`], on the counts beside the queue.
        let scheduled = head.filter(|_| {
            self.engine_requests.has_rank_room(rank)
                && self.engine_requests_waiting.has_rank_room(rank)
        });
        if fifo.scheduled != scheduled {
            if let Some(arrival) = fifo.scheduled {
                self.schedule.remove(&arrival);
            }
            if let Some(arrival) = scheduled {
                self.schedule.insert(arrival, rank);
            }
            fifo.scheduled = scheduled;
        }
        if head.is_none() {
            self.queues.remove(&rank);
        }
    }

    /// Reschedule every queue at once, after a change of limits, which may
    /// change any rank's room: served ranks', retired ranks' still holding
    /// queued requests, and unspecified work's.
    fn reschedule_all(&mut self) {
        let Self {
            queues,
            schedule,
            slots,
            engine_requests,
            engine_requests_waiting,
            ..
        } = self;
        schedule.clear();
        for (&rank, fifo) in queues.iter_mut() {
            let has_room =
                engine_requests.has_rank_room(rank) && engine_requests_waiting.has_rank_room(rank);
            fifo.scheduled = slots
                .front(fifo)
                .map(|waiter| waiter.arrival)
                .filter(|_| has_room);
            if let Some(arrival) = fifo.scheduled {
                schedule.insert(arrival, rank);
            }
        }
        #[cfg(test)]
        {
            self.schedule_steps += self.queues.len();
        }
    }

    /// Queue one request of `rank` at the tail of its rank's FIFO, counting it
    /// there. `None` when the queue storage could not be allocated.
    fn enqueue(
        &mut self,
        rank: AdmissionRank,
        context: Option<Arc<dyn AsyncEngineContext>>,
    ) -> Option<(QueueHandle, oneshot::Receiver<()>)> {
        let (grant, granted) = oneshot::channel();
        let waiter = Waiter {
            grant,
            arrival: self.next_arrival,
            context,
        };
        let fifo = self.queues.entry(rank).or_insert_with(Fifo::new);
        let handle = match self.slots.push_back(fifo, waiter) {
            Ok(handle) => handle,
            Err(_) => {
                if fifo.is_empty() {
                    self.queues.remove(&rank);
                }
                return None;
            }
        };
        self.next_arrival += 1;
        self.queued.acquire(rank);
        self.touch(rank);
        // The request heads its queue when the queue was empty.
        self.reschedule(rank);
        Some((handle, granted))
    }

    /// Dequeue the request `handle` names from `rank`'s FIFO, if it is still
    /// queued there, releasing its queue place.
    fn remove_queued(&mut self, rank: AdmissionRank, handle: QueueHandle) -> Option<Waiter> {
        let fifo = self.queues.get_mut(&rank)?;
        let waiter = self.slots.remove(fifo, handle)?;
        self.queued.release(rank);
        self.touch(rank);
        // A removed head hands the schedule to the request behind it, if any.
        self.reschedule(rank);
        Some(waiter)
    }

    /// Hand engine capacity to queued requests for as long as the worker-wide
    /// limits have room and a queue's head is scheduled, oldest arrival first.
    /// Each admission reads the schedule's oldest head and reschedules only that
    /// head's queue, so it never scans the other queues.
    ///
    /// The head is checked for cancellation once more at this dequeue
    /// decision: a request whose caller has gone is discarded without engine
    /// capacity, counted as cancelled here, and dropping its grant unsent tells
    /// it so; processing continues with the next. A grant the request then
    /// refuses is refunded by its ticket, which calls back here.
    fn admit_queued(&mut self) {
        while self.has_aggregate_engine_room() {
            let Some((_, &rank)) = self.schedule.first_key_value() else {
                break;
            };
            #[cfg(test)]
            {
                self.schedule_steps += 1;
            }
            let fifo = self
                .queues
                .get_mut(&rank)
                .expect("a scheduled queue exists");
            let waiter = self
                .slots
                .pop_front(fifo)
                .expect("a scheduled queue has a head");
            self.queued.release(rank);
            self.touch(rank);
            if waiter
                .context
                .as_ref()
                .is_some_and(|context| context.is_stopped())
            {
                self.series(rank).cancelled();
                self.reschedule(rank);
                continue;
            }
            // A successful send means the ticket is still there to receive the
            // offer, not that it will take it: a request cancelled while queued
            // may still refuse the capacity, refunding it as it settles. The
            // capacity moves here because the ticket now owns it; the admission
            // is counted only once the request actually reaches the engine.
            if waiter.grant.send(()).is_ok() {
                // Reschedules the queue for its new head and its rank's room.
                self.take_engine(rank);
            } else {
                // Its ticket was dropped without leaving the queue first, which
                // no ticket does; account for it here rather than lose it.
                self.series(rank).cancelled();
                self.reschedule(rank);
            }
        }
    }

    /// Release the waiting measure of a request of `rank` whose wait has
    /// ended, and pass the capacity on.
    fn release_waiting(&mut self, rank: AdmissionRank) {
        self.engine_requests_waiting.release(rank);
        self.touch(rank);
        self.reschedule(rank);
        self.admit_queued();
    }

    /// Release the request measure of a request of `rank` that finished,
    /// failed or went away, or of an offer a queued request refused — with its
    /// waiting measure too when it still holds that — and pass the capacity
    /// on.
    fn release_engine(&mut self, rank: AdmissionRank, holds_waiting: bool) {
        self.engine_requests.release(rank);
        if holds_waiting {
            self.engine_requests_waiting.release(rank);
        }
        self.touch(rank);
        self.reschedule(rank);
        self.admit_queued();
    }

    /// Apply a model card's report, returning what changed for logging. The
    /// reported ranks set the rank count the limits aggregate over; a reported
    /// `max_num_seqs` changes no limit.
    fn apply_report(
        &mut self,
        max_num_seqs: Option<usize>,
        served: Option<RankRange>,
    ) -> ReportOutcome {
        let before = self.detected;
        if max_num_seqs.is_some() {
            self.detected.max_num_seqs = max_num_seqs;
        }
        if served.is_some() {
            self.detected.served = served;
        }
        let rank_count = self
            .detected
            .served
            .map_or(1, |served| served.count as usize);
        let limits = AdmissionLimits::resolve(&self.explicit, rank_count);
        if limits != self.limits {
            self.set_limits(limits);
        }
        if let Some(served) = self.detected.served {
            // Every served rank is scrapeable at zero before its first request.
            for rank in served.ranks() {
                self.series(AdmissionRank::Rank(rank));
            }
        }
        // Only an enabled gate's limits can hold work back: a disabled gate
        // leaves even its queue unused.
        let warnings = match self.detected.max_num_seqs {
            Some(max_num_seqs)
                if self.explicit.admission_enabled()
                    && self.capacity_checked != Some((limits, max_num_seqs)) =>
            {
                self.capacity_checked = Some((limits, max_num_seqs));
                CapacityWarning::check(&limits, max_num_seqs)
            }
            _ => Vec::new(),
        };
        ReportOutcome {
            changed: (self.detected != before).then(|| self.snapshot()),
            warnings,
        }
    }

    /// Put new limits in force without resetting any occupancy, queue handle
    /// or permit: queue storage only grows, and a raised limit admits whatever
    /// it now fits.
    fn set_limits(&mut self, limits: AdmissionLimits) {
        self.limits = limits;
        self.engine_requests
            .set_limits(limits.engine_request_limit, limits.rank_count);
        self.engine_requests_waiting
            .set_limits(limits.engine_request_waiting_limit, limits.rank_count);
        self.queued
            .set_limits(Some(limits.request_queue_limit), limits.rank_count);
        self.slots
            .reserve(limits.aggregate(limits.request_queue_limit));
        self.reschedule_all();
        self.admit_queued();
    }
}

/// What a model card's report changed, logged once the lock is released.
struct ReportOutcome {
    /// The configuration, when the report changed the detected capacity.
    changed: Option<LimitsSnapshot>,
    warnings: Vec<CapacityWarning>,
}

/// One worker's two engine limits plus bounded FIFO queues, per DP rank,
/// shared by every endpoint serving for that worker. Reached only through the
/// [`WorkerAdmissionGate`] its worker holds.
pub struct BackendAdmissionGate {
    /// Whether admission control is enabled: either engine limit is set.
    /// Fixed as the gate is created; while it is not, every request bypasses
    /// `state`.
    enabled: bool,
    state: Mutex<GateState>,
}

impl BackendAdmissionGate {
    /// The gate of a worker serving `component`, with the settings read from
    /// the environment, and its metric family created, once, on `component`,
    /// as the component's own metrics are.
    fn for_component(component: &Component, explicit: ExplicitLimits) -> Arc<Self> {
        let metrics = BackendAdmissionMetrics::new(component);
        Self::with_metrics(explicit, metrics)
    }

    /// Build a standalone gate whose metrics are exposed nowhere, so tests
    /// never contend for any worker's capacity.
    #[cfg(test)]
    fn new(explicit: ExplicitLimits) -> Arc<Self> {
        Self::with_metrics(
            explicit,
            BackendAdmissionMetrics::new(&metrics::TestHierarchy::standalone()),
        )
    }

    /// Build the gate and log its configuration, with no capacity detected
    /// yet.
    fn with_metrics(explicit: ExplicitLimits, metrics: BackendAdmissionMetrics) -> Arc<Self> {
        let state = GateState::new(explicit, metrics);
        // The limits are not exported as metrics.
        state.snapshot().log();
        Arc::new(Self {
            enabled: explicit.admission_enabled(),
            state: Mutex::new(state),
        })
    }

    /// Run `generate` under engine capacity reserved for one backend request
    /// of this gate's worker, under the DP rank it names, and return the
    /// engine's own stream, which holds waiting capacity until the first
    /// response that ends the wait (see [`ResponseOutput::ends_wait`]) and
    /// request capacity until the stream ends.
    ///
    /// This is a backend boundary's whole admission interface. Call it inside
    /// the backend's typed `generate`, with the request's own context, before
    /// the request reaches the engine: capacity is reserved *before* `generate`
    /// is polled, so a refused request never reaches the engine, and the
    /// refusal is this call's error — [`ErrorType::WorkerOverloaded`] when the
    /// gate is full, or [`ErrorType::WorkerRankOverloaded`] while the worker
    /// could still take other work — before any response stream exists. The gate watches
    /// `context` while the request is queued, and refuses it as
    /// [`ErrorType::Cancelled`] once stopped. An engine failure keeps its own
    /// error untouched.
    ///
    /// While admission control is disabled, with neither engine limit set,
    /// this is `generate` alone: the request is neither counted, queued nor
    /// refused, and its stream is returned as the engine produced it.
    pub async fn admit<R, F>(
        self: &Arc<Self>,
        context: &Arc<dyn AsyncEngineContext>,
        dp_rank: Option<u32>,
        generate: F,
    ) -> anyhow::Result<EngineStream<R>>
    where
        R: Data + AdmissionResponse,
        F: Future<Output = anyhow::Result<EngineStream<R>>>,
    {
        self.admit_inner(Some(context), dp_rank, generate).await
    }

    /// Accept the capacity and DP ranks a model card this worker registered
    /// reports, once its registration has succeeded. A LoRA adapter's card
    /// carries no capacity of its own, so it changes nothing.
    pub fn record_model_card(&self, card: &ModelDeploymentCard) {
        if card.lora.is_some() {
            return;
        }
        self.record_engine_capacity(
            card.runtime_config.max_num_seqs,
            card.runtime_config.data_parallel_start_rank,
            card.runtime_config.data_parallel_size,
        );
    }

    /// Apply one state transition under the lock, then publish the occupancy
    /// it changed from the authoritative counts. Every mutation goes through
    /// here, so no transition can drift a gauge, and nothing is awaited while
    /// the lock is held.
    fn transition<T>(&self, apply: impl FnOnce(&mut GateState) -> T) -> T {
        let mut state = self.state.lock();
        let result = apply(&mut state);
        state.publish();
        result
    }

    /// Run `generate` under engine capacity reserved by both limits, for the
    /// DP rank the request names (see [`AdmissionRequest`]), if any, watching
    /// `context` when there is one: [`Self::admit`], which tests also drive
    /// without a context.
    ///
    /// The result is exactly [`AsyncEngine::generate`]'s own result type:
    /// capacity is reserved *before* `generate` is polled, so a refused request
    /// never reaches the engine, and what comes back is the engine's stream —
    /// no permit, no admission outcome, nothing to match on. The stream holds
    /// request capacity until it ends or is dropped, and waiting capacity until
    /// the first response that ends the wait; a `generate` that fails after
    /// admission releases both at once.
    ///
    /// Every request entering here is counted as received, and one that
    /// reaches `generate` as admitted, under the rank it is admitted as. A
    /// refusal is traced and classified here and surfaces as the standardized
    /// [`DynamoError`]; an engine failure keeps its own error untouched. While
    /// admission control is disabled, nothing here happens: the request goes
    /// straight to `generate`.
    async fn admit_inner<R, F>(
        self: &Arc<Self>,
        context: Option<&Arc<dyn AsyncEngineContext>>,
        dp_rank: Option<u32>,
        generate: F,
    ) -> anyhow::Result<EngineStream<R>>
    where
        R: Data + AdmissionResponse,
        F: Future<Output = anyhow::Result<EngineStream<R>>>,
    {
        if !self.enabled {
            return generate.await;
        }
        let (permit, source) = self
            .acquire(context, dp_rank)
            .await
            .map_err(anyhow::Error::new)?;
        // Polling `generate` is the engine handoff, and nothing can intervene
        // between here and that first poll, so this — not reserving capacity —
        // is where the request is counted as admitted, exactly once. Whatever
        // the engine then does with it does not undo that.
        permit.series.admitted(source);
        let stream = generate.await?;
        Ok(Box::pin(AdmittedStream {
            inner: stream,
            permit: Some(permit),
        }))
    }

    /// Classify the request's rank and reserve engine capacity for it under
    /// both limits, waiting in its rank's FIFO when it cannot enter yet, and
    /// report whether it had to queue.
    ///
    /// The lock is never held across an await: the decision is made under the
    /// lock, and only the handoff is awaited.
    async fn acquire(
        self: &Arc<Self>,
        context: Option<&Arc<dyn AsyncEngineContext>>,
        dp_rank: Option<u32>,
    ) -> Result<(EnginePermit, AdmissionSource), DynamoError> {
        enum Decision {
            Cancelled,
            Admitted,
            Queued(QueueHandle, oneshot::Receiver<()>),
            Rejected(Option<u32>),
        }

        let (rank, fallback, series, decision) = self.transition(|state| {
            let (rank, fallback) = classify(dp_rank, state.detected.served);
            let series = state.series(rank);
            series.received();
            // A caller that has already gone away must neither queue nor enter
            // the engine. Direct admission never awaits, so this is the only
            // point at which that can be caught before `generate` is polled;
            // the queued path checks again while it waits and at its dequeue.
            let decision = if context.is_some_and(|context| context.is_stopped()) {
                // Counted as a cancellation, which a rejection never is.
                series.cancelled();
                Decision::Cancelled
            } else if !state.queues.contains_key(&rank) && state.has_engine_room(rank) {
                // Direct admission only when nothing of its rank is waiting, so
                // a new request never bypasses an older one in its queue.
                state.take_engine(rank);
                Decision::Admitted
            } else if let Some((handle, granted)) = state
                .queued
                .has_room(rank)
                .then(|| state.enqueue(rank, context.cloned()))
                .flatten()
            {
                Decision::Queued(handle, granted)
            } else {
                series.rejected();
                // Scoped under the same lock, from the state that refused it.
                Decision::Rejected(state.refusal_rank(rank))
            };
            (rank, fallback, series, decision)
        });

        if let Some(fallback) = fallback {
            fallback.warn(context.map(|context| context.id()).unwrap_or_default());
        }
        match decision {
            Decision::Cancelled => Err(reject(Rejection::Cancelled, context)),
            Decision::Admitted => Ok((
                EnginePermit::new(Arc::clone(self), rank, series),
                AdmissionSource::Direct,
            )),
            Decision::Rejected(dp_rank) => Err(reject(Rejection::QueueFull { dp_rank }, context)),
            Decision::Queued(handle, granted) => {
                let permit = AdmissionTicket {
                    gate: Arc::clone(self),
                    rank,
                    series,
                    handle,
                    granted,
                    settled: false,
                }
                .wait(context)
                .await?;
                Ok((permit, AdmissionSource::Queue))
            }
        }
    }

    /// Release the waiting capacity of a request whose wait has ended, and
    /// pass it on to the queues.
    fn release_waiting(&self, rank: AdmissionRank) {
        self.transition(|state| state.release_waiting(rank));
    }

    /// Release the request capacity of a request that finished, failed or went
    /// away, or of an offer a queued request refused — with its waiting
    /// capacity too when it still holds that — and pass it on to the queues.
    fn release_request(&self, rank: AdmissionRank, holds_waiting: bool) {
        self.transition(|state| state.release_engine(rank, holds_waiting));
    }

    /// Remove an abandoned request from its queue in O(1) through its handle,
    /// freeing its queue place at once and counting its cancellation, if it is
    /// still queued. `false` when the gate dequeued it first.
    fn remove_queued(&self, rank: AdmissionRank, handle: QueueHandle, series: &RankSeries) -> bool {
        let removed = self.transition(|state| {
            let removed = state.remove_queued(rank, handle);
            if removed.is_some() {
                series.cancelled();
            }
            removed
        });
        // Its context and grant are dropped outside the lock.
        removed.is_some()
    }

    /// Accept the capacity and DP ranks this worker's engine reports:
    /// `max_num_seqs` per rank, and the ranks `data_parallel_start_rank`
    /// through `data_parallel_start_rank + data_parallel_size - 1`.
    ///
    /// Sets the rank count the worker-wide limits aggregate over, whenever a
    /// report arrives or changes; no report changes a per-rank limit. A report
    /// that changes the detected `max_num_seqs` or ranks logs the
    /// configuration again, with them, to help tune the limits; one that
    /// changes neither logs no configuration. Live occupancy, queued requests
    /// and outstanding permits are kept; a request already classified keeps its
    /// rank.
    pub fn record_engine_capacity(
        &self,
        max_num_seqs: Option<u64>,
        data_parallel_start_rank: u32,
        data_parallel_size: u32,
    ) {
        let max_num_seqs = match max_num_seqs {
            Some(0) => {
                tracing::warn!("Ignoring a reported max_num_seqs of 0 for backend admission");
                None
            }
            max_num_seqs => max_num_seqs.map(|value| usize::try_from(value).unwrap_or(usize::MAX)),
        };
        let served = if data_parallel_size == 0 {
            tracing::warn!(
                data_parallel_start_rank,
                "Ignoring a reported data_parallel_size of 0 for backend admission"
            );
            None
        } else {
            Some(RankRange {
                start: data_parallel_start_rank,
                count: data_parallel_size,
            })
        };
        let outcome = self.transition(|state| state.apply_report(max_num_seqs, served));
        if let Some(snapshot) = outcome.changed {
            snapshot.log();
        }
        for warning in outcome.warnings {
            warning.log();
        }
    }
}

/// Engine capacity held by one admitted request: request capacity until it
/// finishes, and waiting capacity until the response that ends its wait, both
/// under the rank it was admitted as. Private, and never named in any signature
/// a caller can reach: only `admit` and the [`AdmittedStream`] it returns ever
/// own one, so no caller can hold, forget or forge one.
struct EnginePermit {
    gate: Arc<BackendAdmissionGate>,
    rank: AdmissionRank,
    series: Arc<RankSeries>,
    /// Still waiting for the engine's output, so still holding waiting
    /// capacity.
    holds_waiting: bool,
}

impl EnginePermit {
    fn new(gate: Arc<BackendAdmissionGate>, rank: AdmissionRank, series: Arc<RankSeries>) -> Self {
        Self {
            gate,
            rank,
            series,
            holds_waiting: true,
        }
    }

    /// The response that ends the request's wait: release waiting capacity,
    /// exactly once, and keep request capacity while the request continues.
    fn end_waiting(&mut self) {
        if std::mem::take(&mut self.holds_waiting) {
            self.gate.release_waiting(self.rank);
        }
    }
}

impl Drop for EnginePermit {
    fn drop(&mut self) {
        // The request finished, failed or went away: release everything it
        // still holds.
        self.gate.release_request(self.rank, self.holds_waiting);
    }
}

/// The engine's own response stream, holding the capacity it was admitted on.
///
/// It is an [`EngineStream`] like any other — item type, items and context are
/// all the engine's — so the caller sees no admission type at all.
struct AdmittedStream<R: Data> {
    inner: EngineStream<R>,
    /// Taken when the stream ends, so its request capacity is released exactly
    /// once; `Drop` covers a stream abandoned before that.
    permit: Option<EnginePermit>,
}

impl<R: Data + AdmissionResponse> Stream for AdmittedStream<R> {
    type Item = R;

    #[inline]
    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        let polled = self.inner.as_mut().poll_next(cx);
        match &polled {
            // A response the backend classified. While the request still
            // waits, the first one that ends the wait releases waiting capacity
            // to the queues before the item is forwarded, unchanged; an interim
            // one, and every one after the wait has ended, releases nothing.
            Poll::Ready(Some(item)) => {
                if let Some(permit) = self.permit.as_mut()
                    && permit.holds_waiting
                    && item.admission_output().ends_wait()
                {
                    permit.end_waiting();
                }
            }
            // The stream finished: release everything this request still holds,
            // including waiting capacity if no response ever ended its wait.
            Poll::Ready(None) => drop(self.permit.take()),
            Poll::Pending => {}
        }
        polled
    }
}

impl<R: Data + AdmissionResponse> AsyncEngineContextProvider for AdmittedStream<R> {
    fn context(&self) -> Arc<dyn AsyncEngineContext> {
        self.inner.context()
    }
}

impl<R: Data + AdmissionResponse> AsyncEngineStream<R> for AdmittedStream<R> {}

impl<R: Data> std::fmt::Debug for AdmittedStream<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AdmittedStream")
            .field("inner", &self.inner)
            .finish()
    }
}

/// A place in a FIFO. However the request leaves without becoming an
/// admission — its caller's cancellation is observed, or the whole future is
/// dropped — the ticket settles it exactly once: still queued, it is removed
/// through its handle and counted as cancelled; already offered capacity, the
/// offer is refunded and counted; already discarded at its dequeue, the gate
/// has counted it.
struct AdmissionTicket {
    gate: Arc<BackendAdmissionGate>,
    rank: AdmissionRank,
    series: Arc<RankSeries>,
    handle: QueueHandle,
    granted: oneshot::Receiver<()>,
    /// Set once the request's outcome has been accounted for — converted into
    /// an [`EnginePermit`], or settled as a cancellation — so `Drop` has
    /// nothing left to do.
    settled: bool,
}

/// How a queued request's wait ended.
enum WaitOutcome {
    /// The gate reserved engine capacity for it.
    Granted,
    /// The gate found it cancelled at its dequeue, discarded it and counted it.
    Discarded,
    /// Its caller's context stopped.
    Stopped,
}

impl AdmissionTicket {
    async fn wait(
        mut self,
        context: Option<&Arc<dyn AsyncEngineContext>>,
    ) -> Result<EnginePermit, DynamoError> {
        // Cancellation while queued must be prompt, and it must win a
        // simultaneous offer: one can be sent to this request after its context
        // stopped but before this future is polled again, and admitting then
        // would run a request the caller already abandoned. The precheck plus
        // the biased ordering give the stop strictly higher priority; an offer
        // that had already arrived is then refused in `leave`.
        let outcome = match context {
            Some(context) if context.is_stopped() => WaitOutcome::Stopped,
            Some(context) => tokio::select! {
                biased;
                _ = context.stopped() => WaitOutcome::Stopped,
                granted = &mut self.granted => match granted {
                    Ok(()) => WaitOutcome::Granted,
                    Err(_) => WaitOutcome::Discarded,
                },
            },
            None => match (&mut self.granted).await {
                Ok(()) => WaitOutcome::Granted,
                Err(_) => WaitOutcome::Discarded,
            },
        };
        match outcome {
            // The one place a queued request takes the capacity it was offered:
            // `admit` counts the admission when it hands the request to the
            // engine.
            WaitOutcome::Granted => {
                self.settled = true;
                Ok(EnginePermit::new(
                    Arc::clone(&self.gate),
                    self.rank,
                    Arc::clone(&self.series),
                ))
            }
            WaitOutcome::Discarded => {
                self.settled = true;
                Err(reject(Rejection::Cancelled, context))
            }
            // A cancellation is the caller leaving: never a rejection, and
            // never an admission either.
            WaitOutcome::Stopped => {
                self.leave();
                Err(reject(Rejection::Cancelled, context))
            }
        }
    }

    /// Settle a request leaving without admission, exactly once.
    ///
    /// Removal and dequeue both run under the gate lock, so exactly one of them
    /// takes the request off its queue. If the removal wins, it frees the queue
    /// place and counts the cancellation. Otherwise the gate already dequeued
    /// it: either it sent capacity, which closing the channel first makes this
    /// function's to take and refund — cancellation wins an offer that is
    /// already there, because honoring it would admit a caller that has gone
    /// and hold capacity ahead of live requests — or it discarded the request
    /// as cancelled and counted it, leaving nothing here.
    fn leave(&mut self) {
        self.settled = true;
        if self
            .gate
            .remove_queued(self.rank, self.handle, &self.series)
        {
            return;
        }
        self.granted.close();
        if self.granted.try_recv().is_ok() {
            self.series.cancelled();
            self.gate.release_request(self.rank, true);
        }
    }
}

impl Drop for AdmissionTicket {
    fn drop(&mut self) {
        // Reaching here unsettled means the whole future was dropped while the
        // request waited.
        if !self.settled {
            self.leave();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::{FutureExt, StreamExt};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    use dynamo_runtime::pipeline::context::Controller;

    /// A gate with these explicit per-rank limits, whose process has not
    /// reported its ranks: one rank's worth of capacity, every request
    /// unspecified.
    fn gate(
        engine_request_limit: usize,
        engine_request_waiting_limit: usize,
        request_queue_limit: usize,
    ) -> Arc<BackendAdmissionGate> {
        BackendAdmissionGate::new(ExplicitLimits {
            engine_request_limit: Some(engine_request_limit),
            engine_request_waiting_limit: Some(engine_request_waiting_limit),
            request_queue_limit: Some(request_queue_limit),
        })
    }

    /// [`gate`] for a process serving ranks `start..start + count`.
    fn ranked_gate(
        limits: (usize, usize, usize),
        start: u32,
        count: u32,
    ) -> Arc<BackendAdmissionGate> {
        let gate = gate(limits.0, limits.1, limits.2);
        gate.record_engine_capacity(None, start, count);
        gate
    }

    const UNSPECIFIED: AdmissionRank = AdmissionRank::Unspecified;

    fn rank(rank: u32) -> AdmissionRank {
        AdmissionRank::Rank(rank)
    }

    /// Published process totals as (engine requests, engine-waiting requests,
    /// queued): the sum over every `dp_rank` series, which is the whole
    /// process.
    fn published(gate: &Arc<BackendAdmissionGate>) -> (i64, i64, i64) {
        let state = gate.state.lock();
        state.series.values().fold((0, 0, 0), |sum, metrics| {
            let (requests, waiting, queued) = metrics.series.published();
            (sum.0 + requests, sum.1 + waiting, sum.2 + queued)
        })
    }

    /// Published occupancy of one `dp_rank` series.
    fn published_at(gate: &Arc<BackendAdmissionGate>, at: AdmissionRank) -> (i64, i64, i64) {
        gate.state.lock().series(at).published()
    }

    /// Outcome counters of one `dp_rank` series as (received, admitted direct,
    /// admitted from the queue, rejected, cancelled).
    fn outcomes_at(
        gate: &Arc<BackendAdmissionGate>,
        at: AdmissionRank,
    ) -> (u64, u64, u64, u64, u64) {
        gate.state.lock().series(at).outcomes()
    }

    /// Outcome counters summed over every `dp_rank` series.
    fn outcomes(gate: &Arc<BackendAdmissionGate>) -> (u64, u64, u64, u64, u64) {
        let state = gate.state.lock();
        state.series.values().fold((0, 0, 0, 0, 0), |sum, metrics| {
            let o = metrics.series.outcomes();
            (
                sum.0 + o.0,
                sum.1 + o.1,
                sum.2 + o.2,
                sum.3 + o.3,
                sum.4 + o.4,
            )
        })
    }

    fn receives(gate: &Arc<BackendAdmissionGate>) -> u64 {
        outcomes(gate).0
    }

    /// Requests passed into the engine as (direct, queue).
    fn admissions(gate: &Arc<BackendAdmissionGate>) -> (u64, u64) {
        let o = outcomes(gate);
        (o.1, o.2)
    }

    fn rejections(gate: &Arc<BackendAdmissionGate>) -> u64 {
        outcomes(gate).3
    }

    fn cancellations(gate: &Arc<BackendAdmissionGate>) -> u64 {
        outcomes(gate).4
    }

    /// Requests queued process-wide.
    fn queued(gate: &Arc<BackendAdmissionGate>) -> usize {
        gate.state.lock().queued.total()
    }

    /// Authoritative occupancy of one rank as (engine requests, engine-waiting
    /// requests, queued).
    fn occupancy(gate: &Arc<BackendAdmissionGate>, at: AdmissionRank) -> (usize, usize, usize) {
        let state = gate.state.lock();
        (
            state.engine_requests.count(at),
            state.engine_requests_waiting.count(at),
            state.queued.count(at),
        )
    }

    /// The scheduling tests drive [`BackendAdmissionGate::acquire`] directly:
    /// FIFO order, refunds and both limits are decided before an engine is ever
    /// involved, and a permit is what those transitions move around. Calling
    /// [`EnginePermit::end_waiting`] and dropping the permit stand in for the
    /// response that ends a request's wait and the end of its stream. The
    /// stream-returning [`BackendAdmissionGate::admit`], which does both from
    /// the engine's own stream, is covered separately.
    type Acquired = Result<(EnginePermit, AdmissionSource), DynamoError>;

    fn permit(acquired: Acquired) -> EnginePermit {
        acquired.expect("expected admission").0
    }

    /// [`BackendAdmissionGate::acquire`], counting the admission at the
    /// handoff as [`BackendAdmissionGate::admit`] does, so the outcome counters
    /// read as they would for a real engine.
    async fn handoff(
        gate: &Arc<BackendAdmissionGate>,
        context: Option<&Arc<dyn AsyncEngineContext>>,
        dp_rank: Option<u32>,
    ) -> Acquired {
        let acquired = gate.acquire(context, dp_rank).await;
        if let Ok((permit, source)) = &acquired {
            permit.series.admitted(*source);
        }
        acquired
    }

    /// Yield, never sleep, until the queue holds `expected` requests.
    async fn await_queued(gate: &Arc<BackendAdmissionGate>, expected: usize) {
        for _ in 0..1_000 {
            if queued(gate) == expected {
                return;
            }
            tokio::task::yield_now().await;
        }
        panic!(
            "the queue holds {} requests, never {expected}",
            queued(gate)
        );
    }

    /// Spawn an acquisition for `dp_rank` — it only resolves once the gate
    /// decides, so a queueing request can never be awaited on the test task —
    /// and return once it has joined a FIFO.
    async fn spawn_queued_at(
        gate: &Arc<BackendAdmissionGate>,
        dp_rank: Option<u32>,
        context: Option<Arc<dyn AsyncEngineContext>>,
    ) -> tokio::task::JoinHandle<Acquired> {
        let before = queued(gate);
        let handle = tokio::spawn({
            let gate = Arc::clone(gate);
            async move { handoff(&gate, context.as_ref(), dp_rank).await }
        });
        await_queued(gate, before + 1).await;
        handle
    }

    /// [`spawn_queued_at`] without a rank or a context.
    async fn spawn_queued_admit(
        gate: &Arc<BackendAdmissionGate>,
    ) -> tokio::task::JoinHandle<Acquired> {
        spawn_queued_at(gate, None, None).await
    }

    /// The outcome of a spawned request, failing rather than hanging if the gate
    /// never decides it.
    async fn outcome<T>(handle: tokio::task::JoinHandle<T>) -> T {
        tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("the gate must decide promptly")
            .expect("the request task completes")
    }

    /// The `(type, message)` pair a refusal carries, or `None` once admitted.
    fn refusal(acquired: &Acquired) -> Option<(ErrorType, &str)> {
        acquired
            .as_ref()
            .err()
            .map(|error| (error.error_type(), error.message()))
    }

    /// Refused as an overload of the whole worker.
    fn is_queue_full(acquired: &Acquired) -> bool {
        refusal(acquired) == Some((ErrorType::WorkerOverloaded, OVERLOADED_MESSAGE))
    }

    /// Refused as an overload of DP rank `dp_rank` alone.
    fn is_rank_full(acquired: &Acquired, dp_rank: u32) -> bool {
        refusal(acquired)
            == Some((
                ErrorType::WorkerRankOverloaded(dp_rank),
                RANK_OVERLOADED_MESSAGE,
            ))
    }

    fn is_cancelled(acquired: &Acquired) -> bool {
        refusal(acquired) == Some((ErrorType::Cancelled, CANCELLED_MESSAGE))
    }

    fn stoppable() -> (Arc<Controller>, Arc<dyn AsyncEngineContext>) {
        let controller = Arc::new(Controller::default());
        let context: Arc<dyn AsyncEngineContext> = controller.clone();
        (controller, context)
    }

    ///////////////////// CONFIGURATION /////////////////////

    /// Explicit settings resolved from exactly these environment values.
    fn resolve_from(env: &[(&str, &str)]) -> Result<ExplicitLimits, DynamoError> {
        ExplicitLimits::resolve(|name| {
            env.iter()
                .find(|(key, _)| *key == name)
                .map(|(_, value)| value.to_string())
        })
    }

    /// Explicit settings resolved from exactly these valid environment values.
    fn explicit_from(env: &[(&str, &str)]) -> ExplicitLimits {
        resolve_from(env).unwrap_or_else(|error| panic!("{env:?}: {error}"))
    }

    /// With nothing set, both engine limits are unlimited and there is no
    /// queue, which leaves admission control disabled.
    #[test]
    fn unset_settings_keep_their_defaults() {
        let defaults = explicit_from(&[]);
        assert_eq!(defaults, ExplicitLimits::default());
        assert_eq!(
            AdmissionLimits::resolve(&defaults, 1),
            AdmissionLimits {
                engine_request_limit: None,
                engine_request_waiting_limit: None,
                request_queue_limit: 0,
                rank_count: 1,
            }
        );
        assert!(!defaults.admission_enabled());
    }

    /// The canonical name outranks its legacy alias, and a value that is not a
    /// positive integer is passed over rather than hiding the next source. It
    /// configures the full-request limit and nothing else.
    #[test]
    fn the_engine_request_limit_reads_the_canonical_name_then_its_legacy_alias() {
        const CANONICAL: &str = DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT;
        const LEGACY: &str = DYN_ENGINE_REQUEST_LIMIT;
        for (env, expected) in [
            (vec![(CANONICAL, "7")], Some(7)),
            (vec![(LEGACY, "5")], Some(5)),
            (vec![(CANONICAL, "7"), (LEGACY, "5")], Some(7)),
            (vec![(CANONICAL, "7"), (LEGACY, "invalid")], Some(7)),
            (vec![(CANONICAL, "7"), (LEGACY, "0")], Some(7)),
            (vec![(CANONICAL, " 7 ")], Some(7)),
            (vec![(CANONICAL, "0"), (LEGACY, "5")], Some(5)),
            (vec![(CANONICAL, "-1"), (LEGACY, "5")], Some(5)),
            (vec![(CANONICAL, "invalid"), (LEGACY, "5")], Some(5)),
            (vec![(CANONICAL, ""), (LEGACY, "5")], Some(5)),
            (vec![(CANONICAL, "0"), (LEGACY, "0")], None),
            (vec![(CANONICAL, "99999999999999999999999999999999")], None),
        ] {
            let resolved = explicit_from(&env);
            assert_eq!(resolved.engine_request_limit, expected, "{env:?}");
            assert_eq!(
                (
                    resolved.engine_request_waiting_limit,
                    resolved.request_queue_limit
                ),
                (None, None),
                "{env:?} configures the full-request limit alone"
            );
        }
    }

    /// The waiting limit's canonical name outranks the name it was renamed
    /// from, which still configures it as an alias. Neither name of the
    /// full-request limit reaches it.
    #[test]
    fn the_engine_request_waiting_limit_reads_the_canonical_name_then_its_former_name() {
        const CANONICAL: &str = DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT;
        const FORMER: &str = DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT;
        for (env, expected) in [
            (vec![(CANONICAL, "3")], Some(3)),
            (vec![(CANONICAL, " 3 ")], Some(3)),
            (vec![(FORMER, "4")], Some(4)),
            (vec![(CANONICAL, "3"), (FORMER, "4")], Some(3)),
            (vec![(CANONICAL, "0"), (FORMER, "4")], Some(4)),
            (vec![(CANONICAL, "invalid"), (FORMER, "4")], Some(4)),
            (vec![(CANONICAL, "0")], None),
            (vec![(CANONICAL, "-1")], None),
            (vec![(FORMER, "invalid")], None),
        ] {
            assert_eq!(
                explicit_from(&env).engine_request_waiting_limit,
                expected,
                "{env:?}"
            );
        }
        for name in [
            DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT,
            DYN_ENGINE_REQUEST_LIMIT,
        ] {
            assert_eq!(
                explicit_from(&[(name, "5")]).engine_request_waiting_limit,
                None,
                "{name}"
            );
        }
    }

    /// Zero is a valid queue limit under either name: it disables queueing.
    #[test]
    fn the_queue_limit_accepts_zero_and_reads_the_canonical_name_then_its_legacy_alias() {
        const CANONICAL: &str = DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT;
        const LEGACY: &str = DYN_DYNAMO_REQUEST_QUEUE_LIMIT;
        for (env, expected) in [
            (vec![(CANONICAL, "17")], Some(17)),
            (vec![(LEGACY, "9")], Some(9)),
            (vec![(CANONICAL, "17"), (LEGACY, "9")], Some(17)),
            (vec![(CANONICAL, "17"), (LEGACY, "invalid")], Some(17)),
            (vec![(CANONICAL, "0")], Some(0)),
            (vec![(LEGACY, "0")], Some(0)),
            (vec![(CANONICAL, " 0 "), (LEGACY, "9")], Some(0)),
            (vec![(CANONICAL, "0"), (LEGACY, "-1")], Some(0)),
            (vec![(CANONICAL, "-1"), (LEGACY, "9")], Some(9)),
            (vec![(CANONICAL, "invalid")], None),
            (vec![(CANONICAL, "")], None),
        ] {
            // A positive queue limit needs an engine limit to queue behind.
            let env = [env, vec![(DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "1")]].concat();
            assert_eq!(explicit_from(&env).request_queue_limit, expected, "{env:?}");
        }
    }

    /// A positive queue limit with neither engine limit set fails, naming the
    /// setting that supplied it and how to set an engine limit. Zero stays
    /// valid alone, and any queue limit is valid beside either engine limit.
    #[test]
    fn a_positive_queue_limit_requires_an_engine_limit() {
        const QUEUE: &str = DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT;
        const LEGACY_QUEUE: &str = DYN_DYNAMO_REQUEST_QUEUE_LIMIT;
        for (env, source) in [
            (vec![(QUEUE, "4")], QUEUE),
            (vec![(LEGACY_QUEUE, "4")], LEGACY_QUEUE),
            (vec![(QUEUE, "4"), (LEGACY_QUEUE, "0")], QUEUE),
            (vec![(QUEUE, "invalid"), (LEGACY_QUEUE, "4")], LEGACY_QUEUE),
            // An invalid engine limit is passed over, so it sets none.
            (
                vec![
                    (QUEUE, "4"),
                    (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "0"),
                ],
                QUEUE,
            ),
        ] {
            let error = resolve_from(&env).unwrap_err();
            assert_eq!(
                error.error_type(),
                ErrorType::Backend(BackendError::InvalidArgument)
            );
            assert_eq!(
                error.message(),
                format!(
                    "Backend admission request queue limit {source}=4 requires an engine \
                     limit: set DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT (or \
                     --engine-request-limit) or \
                     DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT, or set {source} to 0"
                ),
                "{env:?}"
            );
        }
        for (env, expected) in [
            (vec![(QUEUE, "0")], 0),
            (vec![(LEGACY_QUEUE, "0")], 0),
            (vec![(QUEUE, "0"), (LEGACY_QUEUE, "4")], 0),
            (vec![(QUEUE, "4"), (DYN_ENGINE_REQUEST_LIMIT, "1")], 4),
            (
                vec![
                    (LEGACY_QUEUE, "4"),
                    (DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT, "1"),
                ],
                4,
            ),
        ] {
            assert_eq!(
                explicit_from(&env).request_queue_limit,
                Some(expected),
                "{env:?}"
            );
        }
    }

    /// A valid canonical value ends the search: the alias it shadows is never
    /// read, so an invalid alias can neither replace it nor be warned about.
    #[test]
    fn a_valid_canonical_value_never_reads_its_shadowed_alias() {
        let env = [
            (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "7"),
            (DYN_ENGINE_REQUEST_LIMIT, "invalid"),
            (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT, "3"),
            (DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT, "invalid"),
            (DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT, "0"),
            (DYN_DYNAMO_REQUEST_QUEUE_LIMIT, "-1"),
        ];
        let read = std::cell::RefCell::new(Vec::new());
        let resolved = ExplicitLimits::resolve(|name| {
            read.borrow_mut().push(name.to_string());
            env.iter()
                .find(|(key, _)| *key == name)
                .map(|(_, value)| value.to_string())
        })
        .unwrap();
        assert_eq!(
            resolved,
            ExplicitLimits {
                engine_request_limit: Some(7),
                engine_request_waiting_limit: Some(3),
                request_queue_limit: Some(0),
            }
        );
        assert_eq!(
            *read.borrow(),
            [
                DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT,
                DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT,
                DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT,
            ]
        );
    }

    /// Reports never change a per-rank limit, default or explicit: a reported
    /// `max_num_seqs` changes none, and a reported rank count only multiplies
    /// each worker-wide limit, once, leaving unlimited ones unlimited. Queue
    /// storage holds the whole worker-wide queue, so the default allocates
    /// none.
    #[test]
    fn reports_set_only_the_rank_count_the_limits_aggregate_over() {
        let reports = [(Some(8), 0, 1), (Some(256), 4, 4), (None, 4, 3)];
        let defaults = BackendAdmissionGate::new(ExplicitLimits::default());
        for (max_num_seqs, start, count) in reports {
            defaults.record_engine_capacity(max_num_seqs, start, count);
        }
        {
            let state = defaults.state.lock();
            assert_eq!(
                state.limits,
                AdmissionLimits {
                    engine_request_limit: None,
                    engine_request_waiting_limit: None,
                    request_queue_limit: 0,
                    rank_count: 3,
                }
            );
            assert_eq!(
                (
                    state.engine_requests.aggregate_limit,
                    state.engine_requests_waiting.aggregate_limit,
                    state.queued.aggregate_limit,
                ),
                (None, None, Some(0))
            );
            assert_eq!(state.slots.capacity(), 0, "no queue, no queue storage");
        }

        let configured = BackendAdmissionGate::new(ExplicitLimits {
            engine_request_limit: Some(5),
            engine_request_waiting_limit: Some(3),
            request_queue_limit: Some(7),
        });
        for (max_num_seqs, start, count) in reports {
            configured.record_engine_capacity(max_num_seqs, start, count);
        }
        let state = configured.state.lock();
        assert_eq!(
            state.limits,
            AdmissionLimits {
                engine_request_limit: Some(5),
                engine_request_waiting_limit: Some(3),
                request_queue_limit: 7,
                rank_count: 3,
            }
        );
        assert_eq!(
            (
                state.engine_requests.aggregate_limit,
                state.engine_requests_waiting.aggregate_limit,
                state.queued.aggregate_limit,
            ),
            (Some(15), Some(9), Some(21))
        );
        assert_eq!(
            state.slots.capacity(),
            28,
            "queue storage held four ranks' queues once, and never shrinks"
        );
    }

    /// Each setting resolves on its own: one engine limit set leaves the other
    /// unlimited and no queue, and a queue limit set alone leaves both engine
    /// limits unlimited. Explicit values stay per-rank.
    #[test]
    fn each_setting_resolves_independently() {
        let request_only = ExplicitLimits {
            engine_request_limit: Some(5),
            ..ExplicitLimits::default()
        };
        let waiting_only = ExplicitLimits {
            engine_request_waiting_limit: Some(3),
            ..ExplicitLimits::default()
        };
        assert_eq!(
            [
                AdmissionLimits::resolve(&request_only, 2),
                AdmissionLimits::resolve(&waiting_only, 2)
            ],
            [
                AdmissionLimits {
                    engine_request_limit: Some(5),
                    engine_request_waiting_limit: None,
                    request_queue_limit: 0,
                    rank_count: 2,
                },
                AdmissionLimits {
                    engine_request_limit: None,
                    engine_request_waiting_limit: Some(3),
                    request_queue_limit: 0,
                    rank_count: 2,
                },
            ]
        );
        for queue in [0, 1_000] {
            let queue_only = ExplicitLimits {
                request_queue_limit: Some(queue),
                ..ExplicitLimits::default()
            };
            let limits = AdmissionLimits::resolve(&queue_only, 2);
            assert_eq!(
                (
                    limits.request_queue_limit,
                    limits.aggregate(limits.request_queue_limit)
                ),
                (queue, queue * 2)
            );
            assert_eq!(
                (
                    limits.engine_request_limit,
                    limits.engine_request_waiting_limit
                ),
                (None, None)
            );
        }
    }

    /// Either engine limit enables admission control, under any of its names;
    /// with neither set, by default or with a queue limit of zero, it is
    /// disabled.
    #[test]
    fn only_an_engine_limit_enables_admission_control() {
        for (env, enabled) in [
            (vec![], false),
            (
                vec![(DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT, "0")],
                false,
            ),
            (vec![(DYN_DYNAMO_REQUEST_QUEUE_LIMIT, "0")], false),
            (
                vec![(DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "0")],
                false,
            ),
            (
                vec![(DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "4")],
                true,
            ),
            (vec![(DYN_ENGINE_REQUEST_LIMIT, "4")], true),
            (
                vec![(DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT, "2")],
                true,
            ),
            (vec![(DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT, "2")], true),
            (
                vec![
                    (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "4"),
                    (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT, "2"),
                    (DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT, "8"),
                ],
                true,
            ),
        ] {
            let explicit = explicit_from(&env);
            assert_eq!(explicit.admission_enabled(), enabled, "{env:?}");
            assert_eq!(
                BackendAdmissionGate::new(explicit).enabled,
                enabled,
                "{env:?}"
            );
        }
    }

    /// The warning compares each finite, nonzero limit with the reported
    /// capacity, per rank and process-wide, and fires only beyond ten times
    /// it. An unlimited engine limit and no queue never trigger it.
    #[test]
    fn capacity_warnings_name_every_limit_more_than_ten_times_the_capacity() {
        let limits = AdmissionLimits {
            engine_request_limit: Some(2_561),
            engine_request_waiting_limit: Some(2_560),
            request_queue_limit: 40_000,
            rank_count: 2,
        };
        assert_eq!(
            CapacityWarning::check(&limits, 256),
            [
                CapacityWarning {
                    setting: DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT,
                    per_rank_limit: 2_561,
                    max_num_seqs: 256,
                    rank_count: 2,
                },
                CapacityWarning {
                    setting: DYN_BACKEND_ADMISSION_REQUEST_QUEUE_LIMIT,
                    per_rank_limit: 40_000,
                    max_num_seqs: 256,
                    rank_count: 2,
                },
            ]
        );
        let unlimited = AdmissionLimits::resolve(&ExplicitLimits::default(), 2);
        assert!(CapacityWarning::check(&unlimited, 256).is_empty());
        let within = AdmissionLimits {
            engine_request_limit: Some(2_560),
            request_queue_limit: 2_560,
            ..unlimited
        };
        assert!(CapacityWarning::check(&within, 256).is_empty());
    }

    /// The warning is evaluated when capacity first arrives, never guessed
    /// before it, and not repeated by a report that changes nothing. A disabled
    /// gate is never warned about: even its queue holds nothing back.
    #[test]
    fn the_capacity_warning_is_evaluated_once_per_change() {
        let gate = BackendAdmissionGate::new(ExplicitLimits {
            engine_request_limit: Some(10_000),
            ..ExplicitLimits::default()
        });
        let report = |gate: &Arc<BackendAdmissionGate>, max_num_seqs, count| {
            gate.state
                .lock()
                .apply_report(max_num_seqs, Some(RankRange { start: 0, count }))
                .warnings
                .len()
        };
        assert_eq!(report(&gate, None, 1), 0, "no capacity, no guess");
        assert_eq!(
            report(&gate, Some(256), 1),
            1,
            "evaluated when capacity arrives"
        );
        assert_eq!(report(&gate, Some(256), 1), 0, "not repeated");
        assert_eq!(
            report(&gate, Some(256), 2),
            1,
            "re-evaluated when the limits change"
        );
        assert_eq!(
            report(&gate, Some(2_000), 2),
            0,
            "and when capacity changes"
        );

        let disabled = BackendAdmissionGate::new(ExplicitLimits {
            request_queue_limit: Some(10_000),
            ..ExplicitLimits::default()
        });
        assert_eq!(report(&disabled, Some(256), 1), 0);
    }

    /// Assert that `line` is the configuration record at INFO, ending in
    /// exactly its message and fields: the three per-rank limits, then the
    /// detected DP ranks and `max_num_seqs`.
    fn assert_configuration(
        line: &str,
        [request, waiting, queue]: [&str; 3],
        [dp_ranks, max_num_seqs]: [&str; 2],
    ) {
        let expected = format!(
            "Backend admission configuration engine_request_limit={request} \
             engine_request_waiting_limit={waiting} request_queue_limit={queue} \
             detected_dp_ranks={dp_ranks} detected_max_num_seqs={max_num_seqs}"
        );
        assert!(
            line.contains("INFO") && line.ends_with(&expected),
            "{expected}: {line}"
        );
    }

    /// The configuration is logged once as the gate is created, at INFO and
    /// with nothing at WARN, whether admission control is disabled — by
    /// default, or with a queue limit of zero — or enabled: each per-rank
    /// limit, whichever name set it, unset engine limits as `unlimited`, and
    /// the detected DP ranks and `max_num_seqs`, `unavailable` until reported.
    #[test]
    fn the_configuration_is_logged_at_info_as_the_gate_is_created() {
        for (env, limits) in [
            (vec![], ["unlimited", "unlimited", "0"]),
            (
                vec![(DYN_DYNAMO_REQUEST_QUEUE_LIMIT, "0")],
                ["unlimited", "unlimited", "0"],
            ),
            (
                vec![(DYN_BACKEND_ADMISSION_ENGINE_REQUEST_WAITING_LIMIT, "3")],
                ["unlimited", "3", "0"],
            ),
            (
                vec![
                    (DYN_ENGINE_REQUEST_LIMIT, "4"),
                    (DYN_BACKEND_ADMISSION_ENGINE_WAIT_LIMIT, "2"),
                    (DYN_DYNAMO_REQUEST_QUEUE_LIMIT, "8"),
                ],
                ["4", "2", "8"],
            ),
        ] {
            let (_, logged) = logged(tracing::Level::INFO, || {
                BackendAdmissionGate::new(explicit_from(&env))
            });
            let lines: Vec<_> = logged.lines().collect();
            assert_eq!(lines.len(), 1, "{env:?}: {logged}");
            assert_configuration(lines[0], limits, ["unavailable"; 2]);
        }
    }

    /// A report that changes the detected DP ranks or `max_num_seqs` logs the
    /// configuration again, once and at INFO, with them; one that changes
    /// neither — a repeat, or one without `max_num_seqs`, which keeps the last
    /// — logs nothing. The limits logged stay the configured ones, enabled or
    /// not: the detected capacity never sets them.
    #[test]
    fn the_configuration_is_logged_again_only_when_the_detected_capacity_changes() {
        let request_limit = ExplicitLimits {
            engine_request_limit: Some(5),
            ..ExplicitLimits::default()
        };
        for (settings, limits) in [
            (ExplicitLimits::default(), ["unlimited", "unlimited", "0"]),
            (request_limit, ["5", "unlimited", "0"]),
        ] {
            let gate = BackendAdmissionGate::new(settings);
            for (report, detected) in [
                ((None, 0, 1), Some(["[0, 1)", "unavailable"])),
                ((Some(256), 0, 1), Some(["[0, 1)", "256"])),
                ((Some(256), 0, 1), None),
                ((None, 0, 1), None),
                ((Some(256), 4, 2), Some(["[4, 6)", "256"])),
                ((None, 4, 3), Some(["[4, 7)", "256"])),
                ((Some(128), 4, 3), Some(["[4, 7)", "128"])),
            ] {
                let ((), logged) = logged(tracing::Level::INFO, || {
                    gate.record_engine_capacity(report.0, report.1, report.2)
                });
                let Some(detected) = detected else {
                    assert_eq!(logged, "", "{report:?}");
                    continue;
                };
                let lines: Vec<_> = logged.lines().collect();
                assert_eq!(lines.len(), 1, "{report:?}: {logged}");
                assert_configuration(lines[0], limits, detected);
            }
        }
    }

    /// Invalid settings and reports are still warned about, while the
    /// configuration they leave in force is logged at INFO: an invalid setting
    /// is passed over for the next source, and a report of zero `max_num_seqs`
    /// or DP ranks changes nothing, so it logs no configuration.
    #[test]
    fn invalid_settings_and_reports_are_still_warned_about() {
        let (gate, created) = logged(tracing::Level::INFO, || {
            BackendAdmissionGate::new(explicit_from(&[
                (DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT, "0"),
                (DYN_ENGINE_REQUEST_LIMIT, "5"),
            ]))
        });
        let lines: Vec<_> = created.lines().collect();
        assert_eq!(lines.len(), 2, "{created}");
        for expected in [
            "WARN",
            "Ignoring invalid backend admission setting",
            "env=\"DYN_BACKEND_ADMISSION_ENGINE_REQUEST_LIMIT\"",
        ] {
            assert!(lines[0].contains(expected), "{expected}: {created}");
        }
        assert_configuration(lines[1], ["5", "unlimited", "0"], ["unavailable"; 2]);

        let ((), reported) = logged(tracing::Level::INFO, || {
            gate.record_engine_capacity(Some(0), 0, 0)
        });
        let lines: Vec<_> = reported.lines().collect();
        assert_eq!(lines.len(), 2, "{reported}");
        for (line, expected) in lines
            .into_iter()
            .zip(["max_num_seqs of 0", "data_parallel_size of 0"])
        {
            assert!(
                line.contains("WARN") && line.contains(expected),
                "{expected}: {reported}"
            );
        }
    }

    ///////////////////// RANK CLASSIFICATION /////////////////////

    /// Start rank 4 serving two ranks serves 4 and 5. Both boundaries are
    /// served; a rank below the start, at the exclusive end or beyond it falls
    /// back to unspecified with a warning naming the rank and the range. A
    /// missing rank is unspecified without a warning.
    #[test]
    fn supplied_ranks_are_used_only_inside_the_reported_range() {
        let served = RankRange { start: 4, count: 2 };
        assert_eq!(served.to_string(), "[4, 6)");
        assert_eq!(served.ranks().collect::<Vec<_>>(), [4, 5]);
        for supplied in [4, 5] {
            assert_eq!(
                classify(Some(supplied), Some(served)),
                (rank(supplied), None)
            );
        }
        for supplied in [0, 3, 6, 7, u32::MAX] {
            assert_eq!(
                classify(Some(supplied), Some(served)),
                (
                    UNSPECIFIED,
                    Some(RankFallback::OutOfRange { supplied, served })
                ),
                "{supplied}"
            );
        }
        assert_eq!(classify(None, Some(served)), (UNSPECIFIED, None));
    }

    /// Before the process reports its ranks every request is unspecified; a
    /// supplied rank — even zero — warns that rank setup is unavailable rather
    /// than establishing rank zero.
    #[test]
    fn every_request_is_unspecified_before_ranks_are_reported() {
        for supplied in [0, 3] {
            assert_eq!(
                classify(Some(supplied), None),
                (
                    UNSPECIFIED,
                    Some(RankFallback::RanksUnreported { supplied })
                )
            );
        }
        assert_eq!(classify(None, None), (UNSPECIFIED, None));
    }

    /// A single-rank process serves its one rank; any other supplied rank
    /// falls back to unspecified with a warning, and a missing rank is
    /// unspecified without one — never attributed to rank zero.
    #[test]
    fn a_single_rank_process_treats_other_ranks_as_unspecified() {
        let served = RankRange { start: 0, count: 1 };
        assert_eq!(classify(Some(0), Some(served)), (rank(0), None));
        assert_eq!(
            classify(Some(1), Some(served)),
            (
                UNSPECIFIED,
                Some(RankFallback::OutOfRange {
                    supplied: 1,
                    served
                })
            )
        );
        assert_eq!(classify(None, Some(served)), (UNSPECIFIED, None));
    }

    /// Everything the gate logs at warning level or above while `run` runs.
    fn warnings_during(run: impl FnOnce()) -> String {
        logged(tracing::Level::WARN, run).1
    }

    /// What `run` returns, and everything the gate logs at `level` or above
    /// while it runs.
    fn logged<T>(level: tracing::Level, run: impl FnOnce() -> T) -> (T, String) {
        // Tracing caches each callsite's interest process-wide. While at most
        // one dispatcher is registered, it takes a new callsite's interest from
        // the registering thread's default alone, so a concurrent test without
        // a subscriber could disable a callsite this capture needs. A permanent
        // dispatcher that records nothing makes it consult every registered
        // dispatcher, this capture's included.
        static IDLE_DISPATCHER: OnceLock<tracing::Dispatch> = OnceLock::new();
        IDLE_DISPATCHER
            .get_or_init(|| tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default()));

        #[derive(Clone, Default)]
        struct Captured(Arc<std::sync::Mutex<Vec<u8>>>);

        impl std::io::Write for Captured {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                self.0.lock().unwrap().extend_from_slice(buf);
                Ok(buf.len())
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let captured = Captured::default();
        let writer = captured.clone();
        let _interest_guard = crate::test_utils::tracing_interest_guard();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(move || writer.clone())
            .with_ansi(false)
            .with_max_level(level)
            .finish();
        let returned = tracing::subscriber::with_default(subscriber, run);
        let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
        (returned, logged)
    }

    #[test]
    fn getting_an_uninitialized_gate_logs_and_returns_an_error() {
        let holder = WorkerAdmissionGate::default();
        let (error, output) = logged(tracing::Level::ERROR, || {
            holder.get().err().expect("the gate is not initialized")
        });
        assert_eq!(error.error_type(), ErrorType::Internal);
        assert_eq!(
            error.message(),
            "Backend admission gate has not been initialized"
        );
        assert!(output.contains("ERROR"), "{output}");
        assert!(output.contains(error.message()), "{output}");
        assert!(
            holder.0.get().is_none(),
            "retrieval must not initialize the gate"
        );
    }

    /// A supplied rank the gate cannot use warns with the rank, and the range
    /// once it is known — before the ranks are reported, and outside them on a
    /// single-rank process — while a request without a rank warns about
    /// nothing. Neither is rejected.
    #[test]
    fn only_an_unusable_supplied_rank_warns() {
        let gate = gate(4, 4, 0);
        let admit = |dp_rank| {
            let acquired = gate.acquire(None, dp_rank).now_or_never();
            permit(acquired.expect("admitted without waiting"))
        };

        let unreported = warnings_during(|| drop(admit(Some(0))));
        assert!(unreported.contains("WARN"), "{unreported}");
        assert!(unreported.contains("dp_rank=0"), "{unreported}");
        assert!(unreported.contains("not reported"), "{unreported}");

        gate.record_engine_capacity(None, 0, 1);
        let out_of_range = warnings_during(|| drop(admit(Some(1))));
        assert!(out_of_range.contains("dp_rank=1"), "{out_of_range}");
        assert!(
            out_of_range.contains("served_dp_ranks=[0, 1)"),
            "{out_of_range}"
        );

        assert_eq!(warnings_during(|| drop(admit(None))), "");
        assert_eq!(warnings_during(|| drop(admit(Some(0)))), "");
        assert_eq!(outcomes_at(&gate, UNSPECIFIED).3, 0, "never rejected");
    }

    /// The gate classifies with the ranks reported when the request arrives,
    /// counts the fallback under `unspecified`, and admits it rather than
    /// rejecting it for its rank.
    #[tokio::test]
    async fn the_gate_admits_fallback_ranks_as_unspecified() {
        let gate = gate(4, 4, 0);
        let before_ranks = permit(handoff(&gate, None, Some(4)).await);
        assert_eq!(before_ranks.rank, UNSPECIFIED);

        gate.record_engine_capacity(None, 4, 2);
        let served = permit(handoff(&gate, None, Some(5)).await);
        let below = permit(handoff(&gate, None, Some(3)).await);
        let at_end = permit(handoff(&gate, None, Some(6)).await);
        assert_eq!(
            (served.rank, below.rank, at_end.rank),
            (rank(5), UNSPECIFIED, UNSPECIFIED)
        );
        assert_eq!(occupancy(&gate, UNSPECIFIED), (3, 3, 0));
        assert_eq!(occupancy(&gate, rank(5)), (1, 1, 0));
        assert_eq!(outcomes_at(&gate, UNSPECIFIED), (3, 3, 0, 0, 0));
        assert_eq!(outcomes_at(&gate, rank(5)), (1, 1, 0, 0, 0));
    }

    ///////////////////// DP-RANK COUNTING /////////////////////

    impl DpRankCounts {
        /// `total` is always the ranks' counts plus the unspecified count.
        fn assert_consistent(&self) {
            assert_eq!(
                self.total,
                self.ranks.values().sum::<usize>() + self.unspecified,
                "{self:?}"
            );
        }
    }

    /// A specified request counts at its rank and in the total; an unspecified
    /// one only in the total; release undoes exactly what was counted.
    #[test]
    fn specified_and_unspecified_requests_count_at_their_own_scopes() {
        let mut counts = DpRankCounts::new(Some(2), 3);
        counts.acquire(rank(1));
        counts.acquire(UNSPECIFIED);
        assert_eq!(
            (
                counts.count(rank(1)),
                counts.count(UNSPECIFIED),
                counts.total()
            ),
            (1, 1, 2)
        );
        assert_eq!(counts.count(rank(0)), 0);
        counts.assert_consistent();

        counts.release(UNSPECIFIED);
        assert_eq!(
            (
                counts.count(rank(1)),
                counts.count(UNSPECIFIED),
                counts.total()
            ),
            (1, 0, 1)
        );
        counts.release(rank(1));
        assert_eq!(counts.total(), 0);
        assert!(counts.ranks.is_empty(), "a drained rank is dropped");
        counts.assert_consistent();
    }

    /// The plan's example: three ranks with limit 2, one request per rank, then
    /// an unspecified request and another rank-2 request give rank counts
    /// `[1, 1, 2]`, unspecified `1`, and a process count of `5` of `6`.
    #[test]
    fn three_ranks_with_limit_two_share_their_aggregate_with_unspecified_work() {
        let mut counts = DpRankCounts::new(Some(2), 3);
        for rank_id in 0..3 {
            counts.acquire(rank(rank_id));
        }
        counts.acquire(UNSPECIFIED);
        assert!(counts.has_room(rank(2)));
        counts.acquire(rank(2));
        assert_eq!(
            (0..3).map(|r| counts.count(rank(r))).collect::<Vec<_>>(),
            [1, 1, 2]
        );
        assert_eq!(counts.count(UNSPECIFIED), 1);
        assert_eq!((counts.total(), counts.aggregate_limit), (5, Some(6)));
        counts.assert_consistent();

        // Rank 2 is at its own limit; the others and unspecified work still fit.
        assert!(!counts.has_room(rank(2)));
        assert!(counts.has_room(rank(0)));
        assert!(counts.has_room(UNSPECIFIED));
        // One more of anything exhausts the aggregate for everyone.
        counts.acquire(UNSPECIFIED);
        assert_eq!(counts.total(), 6);
        for at in [rank(0), rank(1), rank(2), UNSPECIFIED] {
            assert!(!counts.has_room(at), "{at:?}");
        }
        counts.assert_consistent();
    }

    /// The per-rank and aggregate boundaries are exact, and unspecified work
    /// has no capacity beyond the aggregate.
    #[test]
    fn per_rank_and_aggregate_limits_bound_exactly() {
        let mut counts = DpRankCounts::new(Some(2), 2);
        counts.acquire(rank(7));
        assert!(counts.has_room(rank(7)));
        counts.acquire(rank(7));
        assert!(!counts.has_room(rank(7)), "rank 7 at its limit");
        assert!(counts.has_room(rank(8)));
        assert!(counts.has_room(UNSPECIFIED));

        counts.acquire(UNSPECIFIED);
        counts.acquire(UNSPECIFIED);
        assert_eq!(counts.total(), 4);
        assert!(
            !counts.has_room(rank(8)),
            "unspecified work used rank 8's share"
        );
        assert!(
            !counts.has_room(UNSPECIFIED),
            "and has nothing of its own beyond it"
        );

        counts.release(rank(7));
        assert!(counts.has_room(rank(7)) && counts.has_room(rank(8)));
        counts.assert_consistent();
    }

    /// An unlimited measure always has room, at every rank and worker-wide,
    /// and still counts each request at its own scope.
    #[test]
    fn an_unlimited_measure_always_has_room_and_still_counts() {
        let mut counts = DpRankCounts::new(None, 2);
        for _ in 0..1_000 {
            counts.acquire(rank(7));
            counts.acquire(UNSPECIFIED);
        }
        assert!(counts.has_room(rank(7)) && counts.has_room(UNSPECIFIED));
        assert_eq!(
            (
                counts.count(rank(7)),
                counts.count(UNSPECIFIED),
                counts.total()
            ),
            (1_000, 1_000, 2_000)
        );
        counts.set_limits(None, 4);
        assert_eq!(counts.aggregate_limit, None);
        counts.assert_consistent();
    }

    /// New limits keep every count; a lower one only blocks until the counts
    /// fall below it.
    #[test]
    fn changing_limits_keeps_every_count() {
        let mut counts = DpRankCounts::new(Some(4), 2);
        for _ in 0..3 {
            counts.acquire(rank(0));
        }
        counts.acquire(UNSPECIFIED);
        counts.set_limits(Some(1), 1);
        assert_eq!(
            (
                counts.count(rank(0)),
                counts.count(UNSPECIFIED),
                counts.total()
            ),
            (3, 1, 4)
        );
        assert!(!counts.has_room(rank(0)) && !counts.has_room(UNSPECIFIED));
        for _ in 0..3 {
            counts.release(rank(0));
        }
        assert!(
            !counts.has_room(UNSPECIFIED),
            "still at the lower aggregate"
        );
        counts.release(UNSPECIFIED);
        assert!(counts.has_room(rank(0)));
        counts.assert_consistent();
    }

    ///////////////////// QUEUE STORAGE /////////////////////

    /// A waiter whose arrival stands in for its identity.
    fn waiter(arrival: u64) -> Waiter {
        Waiter {
            grant: oneshot::channel().0,
            arrival,
            context: None,
        }
    }

    impl QueueSlots {
        /// Arrivals in `fifo` from head to tail, checking every link both ways.
        fn arrivals(&self, fifo: &Fifo) -> Vec<u64> {
            let mut arrivals = Vec::new();
            let (mut prev, mut index) = (NIL, fifo.head);
            while index != NIL {
                let slot = self.slot(index);
                assert_eq!(slot.prev, prev, "backward link of slot {index}");
                arrivals.push(
                    slot.waiter
                        .as_ref()
                        .expect("a linked slot is queued")
                        .arrival,
                );
                prev = index;
                index = slot.next;
            }
            assert_eq!(fifo.tail, prev, "tail");
            arrivals
        }

        /// Slots on the free list.
        fn free_slots(&self) -> usize {
            let (mut count, mut index) = (0, self.free);
            while index != NIL {
                assert!(self.slot(index).waiter.is_none());
                count += 1;
                index = self.slot(index).next;
            }
            count
        }
    }

    fn filled(slots: &mut QueueSlots, fifo: &mut Fifo, count: u64) -> Vec<QueueHandle> {
        (0..count)
            .map(|arrival| {
                slots
                    .push_back(fifo, waiter(arrival))
                    .unwrap_or_else(|_| panic!("room for {arrival}"))
            })
            .collect()
    }

    /// `A ↔ B ↔ C ↔ D`: removing `C` joins `B` and `D`; removing the head or
    /// tail moves that end. The survivors keep FIFO order with intact links.
    #[test]
    fn removal_unlinks_exactly_one_entry_at_the_head_middle_or_tail() {
        let mut slots = QueueSlots::with_capacity(4);
        let mut fifo = Fifo::new();
        let handles = filled(&mut slots, &mut fifo, 4);

        assert_eq!(
            slots.remove(&mut fifo, handles[2]).map(|w| w.arrival),
            Some(2)
        );
        assert_eq!(slots.arrivals(&fifo), [0, 1, 3]);
        assert_eq!(
            slots.remove(&mut fifo, handles[0]).map(|w| w.arrival),
            Some(0)
        );
        assert_eq!(slots.arrivals(&fifo), [1, 3]);
        assert_eq!(
            slots.remove(&mut fifo, handles[3]).map(|w| w.arrival),
            Some(3)
        );
        assert_eq!(slots.arrivals(&fifo), [1]);
        assert_eq!(slots.pop_front(&mut fifo).map(|w| w.arrival), Some(1));
        assert!(fifo.is_empty() && slots.arrivals(&fifo).is_empty());
        assert_eq!(slots.free_slots(), 4, "every slot is reusable");
    }

    /// A handle is good for exactly one removal: once its entry leaves, by
    /// removal or dequeue, it reaches nothing — not even the request that
    /// reuses its slot.
    #[test]
    fn a_stale_handle_never_reaches_the_request_reusing_its_slot() {
        let mut slots = QueueSlots::with_capacity(1);
        let mut fifo = Fifo::new();
        let stale = slots.push_back(&mut fifo, waiter(0)).ok().unwrap();
        assert_eq!(slots.pop_front(&mut fifo).map(|w| w.arrival), Some(0));
        let reused = slots.push_back(&mut fifo, waiter(1)).ok().unwrap();
        assert_eq!(reused.slot, stale.slot, "the slot was reused");

        assert!(slots.remove(&mut fifo, stale).is_none());
        assert_eq!(slots.arrivals(&fifo), [1], "the newer request is untouched");
        assert_eq!(slots.remove(&mut fifo, reused).map(|w| w.arrival), Some(1));
        assert!(slots.remove(&mut fifo, reused).is_none(), "and only once");
    }

    /// Several FIFOs share the pool without touching each other's links.
    #[test]
    fn fifos_sharing_the_pool_stay_independent() {
        let mut slots = QueueSlots::with_capacity(6);
        let (mut even, mut odd) = (Fifo::new(), Fifo::new());
        let mut handles = Vec::new();
        for arrival in 0..6 {
            let fifo = if arrival % 2 == 0 {
                &mut even
            } else {
                &mut odd
            };
            handles.push(slots.push_back(fifo, waiter(arrival)).ok().unwrap());
        }
        assert!(
            slots.push_back(&mut even, waiter(6)).is_err(),
            "the pool is full"
        );
        assert_eq!(
            slots.remove(&mut odd, handles[3]).map(|w| w.arrival),
            Some(3)
        );
        assert_eq!(slots.arrivals(&even), [0, 2, 4]);
        assert_eq!(slots.arrivals(&odd), [1, 5]);
        // The freed slot goes to whichever queue needs it next.
        assert!(slots.push_back(&mut even, waiter(6)).is_ok());
        assert_eq!(slots.arrivals(&even), [0, 2, 4, 6]);
    }

    /// Every operation touches at most a fixed number of slots — itself and its
    /// two neighbours — at the head, middle or tail of a queue of any length:
    /// nothing scans.
    #[test]
    fn every_queue_operation_does_constant_work_at_any_length() {
        let cost = |length: u64, position: usize| {
            let mut slots = QueueSlots::with_capacity(length as usize);
            let mut fifo = Fifo::new();
            let handles = filled(&mut slots, &mut fifo, length);
            let before = slots.steps;
            slots.remove(&mut fifo, handles[position]).expect("queued");
            let removal = slots.steps - before;
            let before = slots.steps;
            slots.pop_front(&mut fifo).expect("queued");
            let dequeue = slots.steps - before;
            let before = slots.steps;
            slots.push_back(&mut fifo, waiter(u64::MAX)).ok().unwrap();
            (removal, dequeue, slots.steps - before)
        };
        for length in [8, 1_000, 100_000] {
            for position in [0, length as usize / 2, length as usize - 1] {
                let (removal, dequeue, enqueue) = cost(length, position);
                assert!(removal <= 3, "removal at {position} of {length}: {removal}");
                assert!(dequeue <= 2, "dequeue from {length}: {dequeue}");
                assert!(enqueue <= 2, "enqueue onto {length}: {enqueue}");
            }
        }
    }

    /// Repeated cancellation and replacement reuses the same storage, at
    /// constant work per operation, and cancelling `k` entries costs O(k) in
    /// total, whatever order they go in.
    #[test]
    fn cancellation_reuses_bounded_storage_with_linear_total_work() {
        const QUEUED: u64 = 4_096;
        let mut slots = QueueSlots::with_capacity(QUEUED as usize);
        let mut fifo = Fifo::new();
        let mut handles = filled(&mut slots, &mut fifo, QUEUED);

        // Churn: cancel one entry and queue its replacement, many times over.
        let before = slots.steps;
        for (round, arrival) in (0..10_000usize).zip(QUEUED..) {
            let index = (round * 7_919) % handles.len();
            slots.remove(&mut fifo, handles[index]).expect("queued");
            handles[index] = slots
                .push_back(&mut fifo, waiter(arrival))
                .ok()
                .expect("the freed slot is reused");
        }
        assert!(
            slots.steps - before <= 10_000 * 5,
            "constant work per churn"
        );
        assert_eq!(slots.capacity(), QUEUED as usize, "storage never grew");
        assert_eq!(slots.arrivals(&fifo).len(), QUEUED as usize);

        // Mass cancellation, in an order unrelated to the queue's.
        let before = slots.steps;
        for index in (0..handles.len()).map(|i| (i * 2_053) % handles.len()) {
            slots.remove(&mut fifo, handles[index]).expect("queued");
        }
        assert!(fifo.is_empty());
        assert!(
            slots.steps - before <= 3 * QUEUED as usize,
            "linear total work: {}",
            slots.steps - before
        );
        assert_eq!(slots.free_slots(), QUEUED as usize);
    }

    /// Growing the pool keeps every live handle and the queue's order.
    #[test]
    fn growing_the_pool_preserves_live_entries() {
        let mut slots = QueueSlots::with_capacity(2);
        let mut fifo = Fifo::new();
        let handles = filled(&mut slots, &mut fifo, 2);
        slots.reserve(5);
        slots.reserve(3);
        assert_eq!(slots.capacity(), 5, "never shrinks");
        let more: Vec<_> = (2..5)
            .map(|arrival| slots.push_back(&mut fifo, waiter(arrival)).ok().unwrap())
            .collect();
        assert_eq!(slots.arrivals(&fifo), [0, 1, 2, 3, 4]);
        assert_eq!(
            slots.remove(&mut fifo, handles[1]).map(|w| w.arrival),
            Some(1)
        );
        assert_eq!(slots.remove(&mut fifo, more[1]).map(|w| w.arrival), Some(3));
        assert_eq!(slots.arrivals(&fifo), [0, 2, 4]);
    }

    ///////////////////// ENGINE LIMITS /////////////////////

    /// The request limit is unlimited, but the one request still waiting holds
    /// all the waiting capacity, so the next request queues until its wait
    /// ends. The request that answered keeps its request capacity, which is
    /// counted and published although unlimited.
    #[tokio::test]
    async fn the_waiting_limit_alone_holds_admission_until_a_wait_ends() {
        let gate = BackendAdmissionGate::new(ExplicitLimits {
            engine_request_waiting_limit: Some(1),
            request_queue_limit: Some(4),
            ..ExplicitLimits::default()
        });
        let mut waiting = permit(gate.acquire(None, None).await);
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (1, 1, 1));

        waiting.end_waiting();
        let (admitted, source) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(source, AdmissionSource::Queue);
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "the answering request still holds request capacity"
        );

        drop((admitted, waiting));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// The waiting limit is unlimited, and the one admitted request's wait has
    /// ended, but it keeps its request capacity until it finishes. Waiting
    /// occupancy is counted and published although unlimited.
    #[tokio::test]
    async fn the_request_limit_alone_holds_admission_until_a_request_finishes() {
        let gate = BackendAdmissionGate::new(ExplicitLimits {
            engine_request_limit: Some(1),
            request_queue_limit: Some(4),
            ..ExplicitLimits::default()
        });
        let mut running = permit(gate.acquire(None, None).await);
        running.end_waiting();
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (1, 0, 1));

        drop(running);
        let (admitted, source) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(source, AdmissionSource::Queue);
        assert_eq!(published(&gate), (1, 1, 0));

        drop(admitted);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// With both limits exhausted, an ended wait frees waiting capacity but
    /// admits nothing while request capacity is still full.
    #[tokio::test]
    async fn an_ended_wait_admits_only_when_the_request_limit_has_room() {
        let gate = gate(2, 1, 4);
        let mut running = permit(gate.acquire(None, None).await);
        running.end_waiting();
        let mut waiting = permit(gate.acquire(None, None).await);
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (2, 1, 1), "both limits are exhausted");

        waiting.end_waiting();
        assert_eq!(
            published(&gate),
            (2, 0, 1),
            "waiting capacity alone admits nothing"
        );

        drop(running);
        let (admitted, _) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(published(&gate), (2, 1, 0));

        drop((admitted, waiting));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// The mirror case: a request that finishes frees request capacity but
    /// admits nothing while waiting capacity is still full.
    #[tokio::test]
    async fn a_completion_admits_only_when_the_waiting_limit_has_room() {
        let gate = gate(2, 1, 4);
        let mut running = permit(gate.acquire(None, None).await);
        running.end_waiting();
        let mut waiting = permit(gate.acquire(None, None).await);
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (2, 1, 1), "both limits are exhausted");

        drop(running);
        assert_eq!(
            published(&gate),
            (1, 1, 1),
            "request capacity alone admits nothing"
        );

        waiting.end_waiting();
        let (admitted, _) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(published(&gate), (2, 1, 0));

        drop((admitted, waiting));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Waiting capacity is released once, when the wait ends, however often
    /// that is reported; request capacity is released once, at the end. A
    /// second request holds both kinds throughout, so a repeated release would
    /// show as a count below it rather than vanish at zero.
    #[tokio::test]
    async fn each_kind_of_capacity_is_released_exactly_once() {
        let gate = gate(10, 10, 0);
        let _held = permit(gate.acquire(None, None).await);
        let mut permit = permit(gate.acquire(None, None).await);
        assert_eq!(published(&gate), (2, 2, 0));

        permit.end_waiting();
        permit.end_waiting();
        assert_eq!(published(&gate), (2, 1, 0));

        drop(permit);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    ///////////////////// QUEUE /////////////////////

    #[tokio::test]
    async fn zero_queue_rejects_without_capacity_and_admits_after_release() {
        // Whichever engine limit is set, the other unlimited or not.
        for (request_limit, waiting_limit) in [(Some(1), Some(1)), (Some(1), None), (None, Some(1))]
        {
            let gate = BackendAdmissionGate::new(ExplicitLimits {
                engine_request_limit: request_limit,
                engine_request_waiting_limit: waiting_limit,
                request_queue_limit: Some(0),
            });
            let held = permit(gate.acquire(None, None).await);
            let overflow = gate
                .acquire(None, None)
                .now_or_never()
                .expect("must not wait");
            assert!(is_queue_full(&overflow));
            assert_eq!(published(&gate), (1, 1, 0));
            assert_eq!(rejections(&gate), 1);

            drop(held);
            let next = permit(
                gate.acquire(None, None)
                    .now_or_never()
                    .expect("capacity is free"),
            );
            assert_eq!(published(&gate), (1, 1, 0));
            drop(next);
            assert_eq!(published(&gate), (0, 0, 0));
        }
    }

    #[tokio::test]
    async fn n_direct_admissions_then_exactly_q_queued_then_reject() {
        let gate = gate(2, 2, 3);
        let held = vec![
            permit(gate.acquire(None, None).await),
            permit(gate.acquire(None, None).await),
        ];
        let mut waiters = Vec::new();
        for _ in 0..3 {
            waiters.push(spawn_queued_admit(&gate).await);
        }
        assert_eq!(
            published(&gate),
            (2, 2, 3),
            "queued requests hold no engine capacity"
        );

        assert!(
            is_queue_full(&gate.acquire(None, None).await),
            "the Q+1th request must be shed"
        );
        assert_eq!(queued(&gate), 3, "a rejection must not consume queue space");

        drop(held);
        for waiter in waiters {
            drop(permit(outcome(waiter).await));
        }
        assert_eq!(published(&gate), (0, 0, 0));
    }

    #[tokio::test]
    async fn queue_is_fifo_and_a_new_request_never_bypasses_an_older_waiter() {
        let gate = gate(1, 1, 8);
        let held = permit(gate.acquire(None, None).await);

        let order = Arc::new(Mutex::new(Vec::new()));
        let mut handles = Vec::new();
        // Each arrival joins behind the waiters already queued, so the last one
        // in must also be the last one served.
        for index in 0..5usize {
            let before = queued(&gate);
            handles.push(tokio::spawn({
                let gate = Arc::clone(&gate);
                let order = Arc::clone(&order);
                async move {
                    let permit = permit(gate.acquire(None, None).await);
                    order.lock().push(index);
                    drop(permit);
                }
            }));
            await_queued(&gate, before + 1).await;
        }

        drop(held);
        for handle in handles {
            outcome(handle).await;
        }
        assert_eq!(
            *order.lock(),
            vec![0, 1, 2, 3, 4],
            "queued requests must be admitted oldest first"
        );
        assert_eq!(published(&gate), (0, 0, 0));
    }

    ///////////////////// DP RANKS /////////////////////

    /// A rank at its own limit queues its next request but never blocks
    /// another rank, which is admitted directly while the aggregate has room.
    #[tokio::test]
    async fn a_full_rank_never_blocks_another_rank() {
        let gate = ranked_gate((1, 1, 2), 4, 2);
        let four = permit(gate.acquire(None, Some(4)).await);
        let queued_four = spawn_queued_at(&gate, Some(4), None).await;
        assert_eq!(occupancy(&gate, rank(4)), (1, 1, 1));

        let five = gate
            .acquire(None, Some(5))
            .now_or_never()
            .expect("rank 5 has room and must not wait");
        let (five, source) = five.expect("admitted");
        assert_eq!((five.rank, source), (rank(5), AdmissionSource::Direct));
        assert_eq!(occupancy(&gate, rank(5)), (1, 1, 0));

        drop(four);
        let (queued_four, source) = outcome(queued_four).await.expect("admitted");
        assert_eq!(
            (queued_four.rank, source),
            (rank(4), AdmissionSource::Queue)
        );
        drop((queued_four, five));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Each rank's queue is FIFO, and its queue limit is its own: a full queue
    /// on one rank rejects there, and a release on one rank admits that rank's
    /// oldest request and nothing from another rank's queue.
    #[tokio::test]
    async fn each_rank_has_its_own_fifo_and_queue_limit() {
        let gate = ranked_gate((1, 1, 2), 0, 2);
        let zero = permit(gate.acquire(None, Some(0)).await);
        let one = permit(gate.acquire(None, Some(1)).await);
        let zero_a = spawn_queued_at(&gate, Some(0), None).await;
        let one_a = spawn_queued_at(&gate, Some(1), None).await;
        let zero_b = spawn_queued_at(&gate, Some(0), None).await;
        let one_b = spawn_queued_at(&gate, Some(1), None).await;
        assert_eq!(occupancy(&gate, rank(0)), (1, 1, 2));
        assert_eq!(occupancy(&gate, rank(1)), (1, 1, 2));
        assert!(
            is_queue_full(&gate.acquire(None, Some(0)).await),
            "rank 0's queue is full"
        );
        assert_eq!(outcomes_at(&gate, rank(0)).3, 1, "rejected under rank 0");
        assert_eq!(outcomes_at(&gate, rank(1)).3, 0);

        // Releasing rank 0 admits rank 0's oldest request, and only that one.
        drop(zero);
        let zero_a = permit(outcome(zero_a).await);
        assert_eq!(zero_a.rank, rank(0));
        assert_eq!(occupancy(&gate, rank(0)), (1, 1, 1), "0b still waits");
        assert_eq!(occupancy(&gate, rank(1)), (1, 1, 2), "rank 1 is untouched");

        drop(one);
        let one_a = permit(outcome(one_a).await);
        assert_eq!(one_a.rank, rank(1));
        assert_eq!(occupancy(&gate, rank(1)), (1, 1, 1), "1b still waits");

        drop(zero_a);
        assert_eq!(permit(outcome(zero_b).await).rank, rank(0));
        drop(one_a);
        assert_eq!(permit(outcome(one_b).await).rank, rank(1));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Unspecified work shares the aggregate with every rank and has no
    /// capacity of its own, so it interferes both ways: it can use a rank's
    /// unused share, and a rank can use what unspecified work leaves.
    #[tokio::test]
    async fn unspecified_and_ranked_work_share_the_aggregate_both_ways() {
        let gate = ranked_gate((2, 2, 0), 0, 2);
        // Unspecified work fills the aggregate of 4 by itself.
        let unspecified: Vec<_> =
            futures::future::join_all((0..4).map(|_| gate.acquire(None, None)))
                .await
                .into_iter()
                .map(permit)
                .collect();
        assert_eq!(occupancy(&gate, UNSPECIFIED), (4, 4, 0));
        assert!(
            is_queue_full(&gate.acquire(None, Some(0)).await),
            "rank 0 is empty, but unspecified work used its share"
        );
        assert!(is_queue_full(&gate.acquire(None, None).await));

        // Freed aggregate capacity goes to ranked work, up to the rank's own limit.
        drop(unspecified);
        let ranked: Vec<_> = futures::future::join_all((0..2).map(|_| gate.acquire(None, Some(1))))
            .await
            .into_iter()
            .map(permit)
            .collect();
        assert!(
            is_rank_full(&gate.acquire(None, Some(1)).await, 1),
            "rank 1 is at its own limit, but the aggregate has room for other work"
        );
        let more_unspecified: Vec<_> =
            futures::future::join_all((0..2).map(|_| gate.acquire(None, None)))
                .await
                .into_iter()
                .map(permit)
                .collect();
        assert!(
            is_queue_full(&gate.acquire(None, Some(0)).await),
            "rank 1 and unspecified work together fill the aggregate"
        );
        assert_eq!(gate.state.lock().engine_requests.total(), 4);
        drop((ranked, more_unspecified));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Unspecified requests queue in their own FIFO against the aggregate queue
    /// limit only, consuming the same capacity as every rank's queue.
    #[tokio::test]
    async fn unspecified_requests_queue_against_the_aggregate_queue_limit() {
        let gate = ranked_gate((1, 1, 1), 0, 2);
        let held: Vec<_> =
            futures::future::join_all([Some(0), Some(1)].map(|r| gate.acquire(None, r)))
                .await
                .into_iter()
                .map(permit)
                .collect();
        // Aggregate queue limit 2: two unspecified requests fill it.
        let first = spawn_queued_at(&gate, None, None).await;
        let second = spawn_queued_at(&gate, None, None).await;
        assert_eq!(occupancy(&gate, UNSPECIFIED).2, 2);
        assert!(
            is_queue_full(&gate.acquire(None, Some(0)).await),
            "rank 0's queue is empty, but the aggregate queue is full"
        );
        drop(held);
        for waiter in [first, second] {
            assert_eq!(permit(outcome(waiter).await).rank, UNSPECIFIED);
        }
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A refusal names its rank exactly while the worker could still take
    /// other work, by either path: entering the engine, or queueing. Once it
    /// could do neither, every refusal is the whole worker's, as an
    /// unspecified request's always is — including one naming a rank the
    /// worker does not serve.
    #[tokio::test]
    async fn a_refusal_names_its_rank_only_while_the_worker_can_take_other_work() {
        // Without queues the aggregate queue is always full, yet rank 5 can
        // still enter the engine while rank 4 is at its own limit.
        let gate = ranked_gate((1, 1, 0), 4, 2);
        let four = permit(gate.acquire(None, Some(4)).await);
        assert!(is_rank_full(&gate.acquire(None, Some(4)).await, 4));
        let five = permit(
            gate.acquire(None, Some(5))
                .now_or_never()
                .expect("rank 5 enters"),
        );
        for dp_rank in [Some(4), Some(5), None] {
            assert!(
                is_queue_full(&gate.acquire(None, dp_rank).await),
                "{dp_rank:?}"
            );
        }
        drop((four, five));

        let gate = ranked_gate((1, 1, 1), 4, 2);
        let four = permit(gate.acquire(None, Some(4)).await);
        let queued_four = spawn_queued_at(&gate, Some(4), None).await;
        assert!(is_rank_full(&gate.acquire(None, Some(4)).await, 4));
        let five = permit(
            gate.acquire(None, Some(5))
                .now_or_never()
                .expect("rank 5 enters"),
        );
        // The aggregate engine limits are full now, but other work can queue.
        assert!(is_rank_full(&gate.acquire(None, Some(4)).await, 4));
        let queued_five = spawn_queued_at(&gate, Some(5), None).await;
        for dp_rank in [Some(4), Some(5), None, Some(6)] {
            assert!(
                is_queue_full(&gate.acquire(None, dp_rank).await),
                "{dp_rank:?}"
            );
        }
        assert_eq!(
            outcomes_at(&gate, rank(4)).3,
            3,
            "each counted under rank 4"
        );
        assert_eq!(outcomes_at(&gate, rank(5)).3, 1);
        assert_eq!(outcomes_at(&gate, UNSPECIFIED).3, 2);

        drop(four);
        let queued_four = permit(outcome(queued_four).await);
        drop(five);
        drop((queued_four, permit(outcome(queued_five).await)));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Queue storage that could not grow refuses requests the queue limits
    /// would still take, and blocks queueing for every rank alike, not just
    /// the refused request's: such a refusal names its rank only while other
    /// work can still enter the engine.
    #[tokio::test]
    async fn a_refusal_for_want_of_queue_storage_names_its_rank_only_while_other_work_can_enter() {
        let gate = ranked_gate((1, 1, 2), 4, 2);
        // As if growing it had failed: one slot, under a worker-wide queue
        // limit of four.
        gate.state.lock().slots = QueueSlots::with_capacity(1);
        let four = permit(gate.acquire(None, Some(4)).await);
        let queued_four = spawn_queued_at(&gate, Some(4), None).await;
        assert!(is_rank_full(&gate.acquire(None, Some(4)).await, 4));
        let five = permit(
            gate.acquire(None, Some(5))
                .now_or_never()
                .expect("rank 5 enters"),
        );
        for dp_rank in [Some(5), None] {
            assert!(
                is_queue_full(&gate.acquire(None, dp_rank).await),
                "{dp_rank:?}"
            );
        }
        assert_eq!(queued(&gate), 1);

        drop(four);
        let queued_four = permit(outcome(queued_four).await);
        drop((five, queued_four));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Released capacity goes to the oldest request that can use it, across
    /// queues: an older unspecified request goes before a younger ranked one.
    #[tokio::test]
    async fn released_capacity_goes_to_the_oldest_eligible_request_across_queues() {
        let gate = ranked_gate((2, 2, 4), 0, 1);
        let held: Vec<_> = futures::future::join_all((0..2).map(|_| gate.acquire(None, Some(0))))
            .await
            .into_iter()
            .map(permit)
            .collect();
        let older_unspecified = spawn_queued_at(&gate, None, None).await;
        let younger_ranked = spawn_queued_at(&gate, Some(0), None).await;

        let mut held = held.into_iter();
        drop(held.next());
        let admitted = permit(outcome(older_unspecified).await);
        assert_eq!(admitted.rank, UNSPECIFIED);
        assert_eq!(
            occupancy(&gate, rank(0)).2,
            1,
            "the younger request still waits"
        );
        drop(admitted);
        assert_eq!(permit(outcome(younger_ranked).await).rank, rank(0));
    }

    /// For each occupancy gauge, every served rank and `unspecified` have their
    /// own series, and the series sum to the process occupancy without double
    /// counting.
    #[tokio::test]
    async fn each_gauge_has_a_series_per_served_rank_and_unspecified() {
        let gate = ranked_gate((1, 1, 2), 4, 2);
        let four = permit(gate.acquire(None, Some(4)).await);
        let mut five = permit(gate.acquire(None, Some(5)).await);
        five.end_waiting();
        let queued_four = spawn_queued_at(&gate, Some(4), None).await;
        let unspecified_queued = spawn_queued_at(&gate, None, None).await;

        assert_eq!(published_at(&gate, rank(4)), (1, 1, 1));
        assert_eq!(published_at(&gate, rank(5)), (1, 0, 0));
        assert_eq!(published_at(&gate, UNSPECIFIED), (0, 0, 1));
        let state_totals = {
            let state = gate.state.lock();
            (
                state.engine_requests.total() as i64,
                state.engine_requests_waiting.total() as i64,
                state.queued.total() as i64,
            )
        };
        assert_eq!(published(&gate), state_totals);
        assert_eq!(published(&gate), (2, 1, 2));
        let labels: std::collections::BTreeSet<String> = gate
            .state
            .lock()
            .series
            .keys()
            .map(|rank| rank.label())
            .collect();
        assert_eq!(
            labels,
            ["4", "5", "unspecified"].map(String::from).into(),
            "served ranks and unspecified, and no aggregate series"
        );

        drop((four, five));
        drop(permit(outcome(queued_four).await));
        drop(permit(outcome(unspecified_queued).await));
        assert_eq!(published(&gate), (0, 0, 0));
        for at in [rank(4), rank(5), UNSPECIFIED] {
            assert_eq!(published_at(&gate, at), (0, 0, 0), "{at:?}");
        }
    }

    ///////////////////// REPORTS WITH LIVE REQUESTS /////////////////////

    /// Unspecified requests admitted or queued before ranks are reported keep
    /// their unspecified accounting and label once ranks arrive, and release
    /// exactly what they took.
    #[tokio::test]
    async fn requests_keep_their_classification_when_ranks_arrive() {
        let gate = gate(1, 1, 2);
        let early = permit(gate.acquire(None, Some(0)).await);
        let early_queued = spawn_queued_at(&gate, Some(0), None).await;
        assert_eq!(occupancy(&gate, UNSPECIFIED), (1, 1, 1));

        // Two ranks double the aggregate, which admits the queued request at
        // once — still as unspecified work, not reassigned to rank 0.
        gate.record_engine_capacity(Some(1), 0, 2);
        let early_queued = permit(outcome(early_queued).await);
        assert_eq!(early_queued.rank, UNSPECIFIED);
        assert_eq!(occupancy(&gate, UNSPECIFIED), (2, 2, 0));
        assert_eq!(occupancy(&gate, rank(0)), (0, 0, 0));
        assert_eq!(published_at(&gate, UNSPECIFIED), (2, 2, 0));
        assert_eq!(published_at(&gate, rank(0)), (0, 0, 0));

        // Unspecified work now fills the aggregate, so ranked work waits for
        // it, and enters once unspecified work releases exactly what it held.
        let ranked = spawn_queued_at(&gate, Some(0), None).await;
        drop(early);
        let ranked = permit(outcome(ranked).await);
        assert_eq!(ranked.rank, rank(0));
        assert_eq!(occupancy(&gate, UNSPECIFIED), (1, 1, 0));
        assert_eq!(occupancy(&gate, rank(0)), (1, 1, 0));
        drop((early_queued, ranked));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A late rank report raises the worker-wide limits and admits queued work
    /// at once; a lower rank count evicts nothing and admits again only once
    /// occupancy falls below it. Queue handles and permits survive both.
    #[tokio::test]
    async fn rank_count_changes_never_disturb_live_requests() {
        let gate = ranked_gate((1, 1, 2), 0, 1);
        let held = permit(gate.acquire(None, None).await);
        let first = spawn_queued_at(&gate, None, None).await;
        let second = spawn_queued_at(&gate, None, None).await;
        assert_eq!(occupancy(&gate, UNSPECIFIED), (1, 1, 2));

        // Three ranks: both queued requests now fit.
        gate.record_engine_capacity(None, 0, 3);
        let first = permit(outcome(first).await);
        let second = permit(outcome(second).await);
        assert_eq!(occupancy(&gate, UNSPECIFIED), (3, 3, 0));

        // One rank again, below occupancy: nothing is evicted, and a new
        // request queues until occupancy is below the new limit.
        gate.record_engine_capacity(None, 0, 1);
        assert_eq!(occupancy(&gate, UNSPECIFIED), (3, 3, 0));
        let third = spawn_queued_at(&gate, None, None).await;
        drop(held);
        drop(first);
        assert_eq!(
            occupancy(&gate, UNSPECIFIED),
            (1, 1, 1),
            "still at the lower limit"
        );
        drop(second);
        let third = permit(outcome(third).await);
        assert_eq!(occupancy(&gate, UNSPECIFIED), (1, 1, 0));
        drop(third);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Changing the rank count rescales the aggregate once; a rank no longer
    /// served keeps its live requests, admitted and queued, under its own label
    /// until they finish, while new requests naming it fall back to
    /// unspecified.
    #[tokio::test]
    async fn rank_changes_keep_requests_under_the_rank_they_were_admitted_as() {
        let gate = ranked_gate((1, 1, 1), 0, 3);
        assert_eq!(gate.state.lock().engine_requests.aggregate_limit, Some(3));
        let two = permit(gate.acquire(None, Some(2)).await);
        let queued_two = spawn_queued_at(&gate, Some(2), None).await;

        gate.record_engine_capacity(None, 0, 2);
        assert_eq!(gate.state.lock().engine_requests.aggregate_limit, Some(2));
        assert_eq!(occupancy(&gate, rank(2)), (1, 1, 1));
        let fallback = permit(gate.acquire(None, Some(2)).await);
        assert_eq!(fallback.rank, UNSPECIFIED, "rank 2 is no longer served");

        drop(two);
        let queued_two = permit(outcome(queued_two).await);
        assert_eq!(queued_two.rank, rank(2));
        assert_eq!(published_at(&gate, rank(2)), (1, 1, 0));
        drop((queued_two, fallback));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    ///////////////////// SCHEDULE /////////////////////

    impl GateState {
        /// The schedule holds exactly the head of every queue whose rank's own
        /// limits have room, under that head's arrival, and each queue records
        /// the arrival it is scheduled under; no queue is empty or out of FIFO
        /// order; and no scheduled head is left waiting while the process-wide
        /// limits have room.
        fn assert_schedule_exact(&self) {
            let mut expected = BTreeMap::new();
            for (&rank, fifo) in &self.queues {
                let arrivals = self.slots.arrivals(fifo);
                assert!(!arrivals.is_empty(), "{rank:?}: an empty queue is dropped");
                assert!(arrivals.is_sorted(), "{rank:?}: FIFO order {arrivals:?}");
                let scheduled = self.has_rank_engine_room(rank).then_some(arrivals[0]);
                assert_eq!(fifo.scheduled, scheduled, "{rank:?}");
                expected.extend(scheduled.map(|arrival| (arrival, rank)));
            }
            assert_eq!(self.schedule, expected);
            assert!(
                self.schedule.is_empty() || !self.has_aggregate_engine_room(),
                "a scheduled head is left waiting while the gate has room: {:?}",
                self.schedule
            );
        }
    }

    /// The schedule, oldest first, once it is checked exact.
    fn scheduled(gate: &Arc<BackendAdmissionGate>) -> Vec<(u64, AdmissionRank)> {
        let state = gate.state.lock();
        state.assert_schedule_exact();
        state
            .schedule
            .iter()
            .map(|(&arrival, &rank)| (arrival, rank))
            .collect()
    }

    /// Queues the scheduler has examined so far.
    fn schedule_steps(gate: &Arc<BackendAdmissionGate>) -> usize {
        gate.state.lock().schedule_steps
    }

    /// A request waiting in its FIFO, polled only when a test asks.
    type QueuedRequest = Pin<Box<dyn Future<Output = Acquired>>>;

    /// A request for `dp_rank` that joins its FIFO: polled exactly once, so it
    /// registers there, and never again until a test asks, so the gate's
    /// decisions about it can be read one at a time without spawning.
    fn queue_at(
        gate: &Arc<BackendAdmissionGate>,
        dp_rank: Option<u32>,
        context: Option<Arc<dyn AsyncEngineContext>>,
    ) -> QueuedRequest {
        let gate = Arc::clone(gate);
        let mut request: QueuedRequest =
            Box::pin(async move { gate.acquire(context.as_ref(), dp_rank).await });
        assert!(
            (&mut request).now_or_never().is_none(),
            "the request must queue"
        );
        request
    }

    /// The gate's decision on a queued request, if it has made one.
    fn decided(request: &mut QueuedRequest) -> Option<Acquired> {
        request.now_or_never()
    }

    /// While only the process-wide limits are full, the head of every queue
    /// whose rank has room stays scheduled, so process-wide room freed by any
    /// request — unspecified, or of another rank — goes straight to the oldest
    /// of them, across rank and unspecified queues alike, while an older head
    /// whose own rank is full waits for that rank to free room. A head admitted
    /// hands its queue to the request behind it, under its own arrival.
    #[tokio::test]
    async fn freed_process_wide_room_goes_to_the_oldest_scheduled_head() {
        let gate = ranked_gate((1, 1, 4), 0, 3);
        let zero = permit(handoff(&gate, None, Some(0)).await);
        let unspecified = permit(handoff(&gate, None, None).await);
        let two = permit(handoff(&gate, None, Some(2)).await);
        // Oldest first: rank 0's request, whose rank is full; rank 1's;
        // unspecified; and rank 1's again, behind its first.
        let mut queued_zero = queue_at(&gate, Some(0), None);
        let mut queued_one = queue_at(&gate, Some(1), None);
        let mut queued_unspecified = queue_at(&gate, None, None);
        let mut queued_one_again = queue_at(&gate, Some(1), None);
        assert_eq!(
            scheduled(&gate),
            [(1, rank(1)), (2, UNSPECIFIED)],
            "heads stay scheduled while only the process is full"
        );

        drop(unspecified);
        let one = permit(decided(&mut queued_one).expect("unspecified work's room"));
        assert_eq!(one.rank, rank(1));
        assert!(decided(&mut queued_zero).is_none());
        assert!(decided(&mut queued_unspecified).is_none());
        assert_eq!(
            scheduled(&gate),
            [(2, UNSPECIFIED)],
            "rank 1 is full, so the head behind its first waits unscheduled"
        );

        drop(two);
        let unspecified = permit(decided(&mut queued_unspecified).expect("rank 2's room"));
        assert_eq!(unspecified.rank, UNSPECIFIED);
        assert!(scheduled(&gate).is_empty(), "ranks 0 and 1 are full");

        drop(zero);
        let zero = permit(decided(&mut queued_zero).expect("rank 0's own room"));
        assert_eq!(zero.rank, rank(0));
        drop(one);
        let one = permit(decided(&mut queued_one_again).expect("rank 1's own room"));
        assert_eq!(one.rank, rank(1));
        assert!(scheduled(&gate).is_empty());

        drop((zero, one, unspecified));
        assert_eq!(published(&gate), (0, 0, 0));
        assert!(gate.state.lock().queues.is_empty());
    }

    /// Cancelling a queued head hands the schedule to the request behind it,
    /// under that request's own arrival, and cancelling one behind the head
    /// changes nothing; an offer the scheduled head refuses is refunded to the
    /// oldest scheduled head of any queue.
    #[tokio::test]
    async fn cancelled_heads_and_refused_offers_keep_the_schedule_exact() {
        let gate = ranked_gate((2, 2, 4), 0, 2);
        // Rank 1 and unspecified work fill the process; rank 0 has room of its
        // own.
        let mut held: Vec<_> = futures::future::join_all(
            [Some(1), Some(1), None, None].map(|dp_rank| handoff(&gate, None, dp_rank)),
        )
        .await
        .into_iter()
        .map(permit)
        .collect();
        let controllers: Vec<_> = (0..3).map(|_| stoppable()).collect();
        let mut zero: Vec<_> = controllers
            .iter()
            .map(|(_, context)| queue_at(&gate, Some(0), Some(Arc::clone(context))))
            .collect();
        let mut later_unspecified = queue_at(&gate, None, None);
        assert_eq!(scheduled(&gate), [(0, rank(0)), (3, UNSPECIFIED)]);

        controllers[1].0.stop_generating();
        assert!(is_cancelled(&decided(&mut zero[1]).expect("observed")));
        assert_eq!(
            scheduled(&gate),
            [(0, rank(0)), (3, UNSPECIFIED)],
            "a request behind the head changes nothing"
        );
        controllers[0].0.stop_generating();
        assert!(is_cancelled(&decided(&mut zero[0]).expect("observed")));
        assert_eq!(
            scheduled(&gate),
            [(2, rank(0)), (3, UNSPECIFIED)],
            "the request behind the head takes its place, under its own arrival"
        );

        // Unspecified work frees room, offered to rank 0's head, whose caller
        // then leaves: the refund goes to the oldest scheduled head left.
        drop(held.pop());
        assert_eq!(occupancy(&gate, rank(0)), (1, 1, 0), "offered");
        controllers[2].0.stop_generating();
        assert!(is_cancelled(&decided(&mut zero[2]).expect("observed")));
        let later = permit(decided(&mut later_unspecified).expect("refunded room"));
        assert_eq!(later.rank, UNSPECIFIED);
        assert!(scheduled(&gate).is_empty());
        assert_eq!(cancellations(&gate), 3);

        drop((held, later));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A change of ranks reschedules every queue, including the queue of a
    /// rank no longer served, whose requests keep their rank and their place
    /// in the schedule. A higher rank count admits the oldest heads its
    /// worker-wide room fits, a retired rank's among them; a lower one evicts
    /// nothing.
    #[tokio::test]
    async fn rank_changes_reschedule_every_queue_including_retired_ranks() {
        let gate = ranked_gate((2, 2, 4), 0, 3);
        // Ranks 2 and 0 and unspecified work fill the worker-wide limits, while
        // each rank keeps room of its own.
        let held: Vec<_> = futures::future::join_all(
            [Some(2), Some(0), None, None, None, None].map(|dp_rank| handoff(&gate, None, dp_rank)),
        )
        .await
        .into_iter()
        .map(permit)
        .collect();
        let mut two = queue_at(&gate, Some(2), None);
        let mut zero = queue_at(&gate, Some(0), None);
        let mut two_again = queue_at(&gate, Some(2), None);
        assert_eq!(
            scheduled(&gate),
            [(0, rank(2)), (1, rank(0))],
            "heads stay scheduled while only the process is full"
        );

        // Rank 2 is retired; its queue stays, under its own rank, and still
        // scheduled, while the process is still full.
        gate.record_engine_capacity(None, 0, 2);
        assert_eq!(scheduled(&gate), [(0, rank(2)), (1, rank(0))]);
        assert_eq!(occupancy(&gate, rank(2)), (1, 1, 2));

        // Ranks 3 to 6 alone are served now, which retires rank 0 too, with
        // room for two more worker-wide: they go to the two oldest heads,
        // retired rank 2's, which fills its rank, and retired rank 0's, each
        // under its own rank.
        gate.record_engine_capacity(None, 3, 4);
        let admitted_two = permit(decided(&mut two).expect("the oldest scheduled head"));
        let admitted_zero = permit(decided(&mut zero).expect("the next oldest"));
        assert_eq!((admitted_two.rank, admitted_zero.rank), (rank(2), rank(0)));
        assert!(
            scheduled(&gate).is_empty(),
            "rank 2 is full, so the head behind its first waits unscheduled"
        );

        // Back below occupancy: nothing is evicted.
        gate.record_engine_capacity(None, 3, 2);
        assert!(decided(&mut two_again).is_none());
        assert_eq!(occupancy(&gate, rank(2)), (2, 2, 1));
        assert_eq!(occupancy(&gate, rank(0)), (2, 2, 0));

        drop(two_again);
        drop((held, admitted_two, admitted_zero));
        assert_eq!(published(&gate), (0, 0, 0));
        assert!(scheduled(&gate).is_empty());
    }

    /// Admitting from the queues examines only the queues the transition
    /// changes, however many wait: freeing process-wide room examines just the
    /// admitted head's queue, picked and then rescheduled, with 8 queues
    /// waiting or 1,024. Only a change of limits or ranks examines every queue,
    /// once.
    #[tokio::test]
    async fn a_transition_examines_only_the_queues_it_changes() {
        for ranks in [8u32, 1_024] {
            let gate = ranked_gate((1, 1, 1), 0, ranks);
            // Unspecified work fills the process, so every rank's request
            // queues with room of its own, and every head is scheduled.
            let mut held: Vec<_> = (0..ranks)
                .map(|_| permit(gate.acquire(None, None).now_or_never().expect("room")))
                .collect();
            // Queued from the highest rank down, so the oldest head is not the
            // lowest rank.
            let mut queued: Vec<_> = (0..ranks)
                .rev()
                .map(|dp_rank| queue_at(&gate, Some(dp_rank), None))
                .collect();
            assert_eq!(scheduled(&gate).len(), ranks as usize);

            for (index, request) in queued.iter_mut().enumerate().take(3) {
                let before = schedule_steps(&gate);
                drop(held.pop());
                assert_eq!(
                    schedule_steps(&gate) - before,
                    2,
                    "{ranks} queues: only the admitted head's queue is examined"
                );
                let admitted = permit(decided(request).expect("the oldest head"));
                assert_eq!(admitted.rank, rank(ranks - 1 - index as u32));
                held.push(admitted);
            }

            let queues = gate.state.lock().queues.len();
            let before = schedule_steps(&gate);
            gate.record_engine_capacity(None, 0, ranks + 1);
            assert_eq!(
                schedule_steps(&gate) - before,
                queues + 2,
                "{ranks} queues: a change of ranks examines every queue once, then admits \
                 the one head it made room for"
            );
            assert_eq!(scheduled(&gate).len(), queues - 1);

            drop(queued);
            drop(held);
            assert_eq!(published(&gate), (0, 0, 0));
        }
    }

    /// The schedule stays exact through any sequence of transitions: arrivals
    /// with and without a usable rank, admissions, ended waits, completions,
    /// cancellations observed while queued or first seen at the dequeue,
    /// refused offers, abandoned waiters, and reports that raise, lower and
    /// retire ranks. Every request is accounted for once at the end, with both
    /// engine limits set, and with either one unlimited.
    #[tokio::test]
    async fn the_schedule_stays_exact_through_every_kind_of_transition() {
        for (request_limit, waiting_limit) in [(Some(2), Some(1)), (None, Some(1)), (Some(1), None)]
        {
            let gate = BackendAdmissionGate::new(ExplicitLimits {
                engine_request_limit: request_limit,
                engine_request_waiting_limit: waiting_limit,
                request_queue_limit: Some(2),
            });
            // The driver polls every request itself, all within this one task
            // poll, so Tokio's cooperative budget must not apply: spent, it
            // would leave a granted request pending until it was cancelled.
            tokio::task::unconstrained(async { fuzz_the_schedule(&gate) }).await;
        }
    }

    /// Drive `gate` through random transitions, checking its schedule and
    /// counts after each, then drain it and check every request's outcome.
    fn fuzz_the_schedule(gate: &Arc<BackendAdmissionGate>) {
        let mut seed = 0x9E37_79B9_7F4A_7C15_u64;
        let mut next = |bound: usize| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed % bound as u64) as usize
        };
        let mut permits: Vec<EnginePermit> = Vec::new();
        let mut waiting: Vec<(QueuedRequest, Arc<Controller>)> = Vec::new();
        for _ in 0..5_000 {
            match next(8) {
                0 | 1 => {
                    let dp_rank = match next(6) {
                        5 => None,
                        dp_rank => Some(dp_rank as u32),
                    };
                    let (controller, context) = stoppable();
                    let arriving = Arc::clone(gate);
                    let mut request: QueuedRequest =
                        Box::pin(async move { handoff(&arriving, Some(&context), dp_rank).await });
                    match (&mut request).now_or_never() {
                        Some(Ok((permit, _))) => permits.push(permit),
                        Some(Err(_)) => {}
                        None => waiting.push((request, controller)),
                    }
                }
                2 if !permits.is_empty() => {
                    permits.swap_remove(next(permits.len()));
                }
                3 if !permits.is_empty() => {
                    let index = next(permits.len());
                    permits[index].end_waiting();
                }
                4 if !waiting.is_empty() => {
                    let index = next(waiting.len());
                    waiting[index].1.stop_generating();
                }
                5 if !waiting.is_empty() => {
                    // Abandoned: the whole waiting future is dropped.
                    drop(waiting.swap_remove(next(waiting.len())));
                }
                6 => waiting.retain_mut(|(request, _)| match decided(request) {
                    Some(Ok((permit, _))) => {
                        permits.push(permit);
                        false
                    }
                    Some(Err(_)) => false,
                    None => true,
                }),
                7 => {
                    let max_num_seqs = 1 + next(3) as u64;
                    let rank_count = 1 + next(4) as u32;
                    gate.record_engine_capacity(Some(max_num_seqs), 0, rank_count);
                }
                _ => {}
            }
            let state = gate.state.lock();
            state.assert_schedule_exact();
            for counts in [
                &state.engine_requests,
                &state.engine_requests_waiting,
                &state.queued,
            ] {
                counts.assert_consistent();
            }
        }

        drop(waiting);
        drop(permits);
        assert_eq!(published(gate), (0, 0, 0));
        assert!(scheduled(gate).is_empty());
        let counted = outcomes(gate);
        let (received, direct, queue, rejected, cancelled) = counted;
        assert_eq!(received, direct + queue + rejected + cancelled);
        let limits = gate.state.lock().limits;
        assert!(
            direct > 0 && queue > 0 && rejected > 0 && cancelled > 0,
            "every outcome occurs under {limits:?}: {counted:?}"
        );
    }

    ///////////////////// CANCELLATION AND REFUND /////////////////////

    /// An already-cancelled arrival neither queues nor enters the engine, and
    /// counts one cancellation under its rank — not a rejection.
    #[tokio::test]
    async fn an_already_cancelled_arrival_is_neither_queued_nor_admitted() {
        let gate = ranked_gate((1, 1, 4), 0, 1);
        let (controller, context) = stoppable();
        controller.stop_generating();
        let refused = gate.acquire(Some(&context), Some(0)).await;
        assert!(is_cancelled(&refused));
        assert_eq!(published(&gate), (0, 0, 0));
        assert_eq!(outcomes_at(&gate, rank(0)), (1, 0, 0, 0, 1));

        // Also when the gate is full and it would otherwise have queued.
        let _held = permit(handoff(&gate, None, Some(0)).await);
        assert!(is_cancelled(&gate.acquire(Some(&context), Some(0)).await));
        assert_eq!(queued(&gate), 0);
        assert_eq!(outcomes_at(&gate, rank(0)), (3, 1, 0, 0, 2));
    }

    #[tokio::test]
    async fn a_dropped_queued_waiter_frees_its_queue_place_immediately() {
        let gate = gate(1, 1, 1);
        let held = permit(gate.acquire(None, None).await);

        let waiter = spawn_queued_admit(&gate).await;
        assert!(
            is_queue_full(&gate.acquire(None, None).await),
            "queue is full"
        );

        waiter.abort();
        let _ = waiter.await;
        await_queued(&gate, 0).await;
        assert_eq!(cancellations(&gate), 1);

        // The freed queue place is reusable: this request queues rather than
        // being shed.
        let reuse = spawn_queued_admit(&gate).await;
        drop(held);
        drop(permit(outcome(reuse).await));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Cancellation observed in a queued request's context removes it at once
    /// — from the head, middle or tail, without waiting to reach the head or
    /// for capacity — frees its place for the next arrival, lowers the gauge,
    /// counts once, and leaves the survivors in FIFO order.
    #[tokio::test]
    async fn an_observed_queued_cancellation_frees_its_place_at_once() {
        for cancelled in 0..3usize {
            let gate = ranked_gate((1, 1, 3), 0, 1);
            let held = permit(handoff(&gate, None, Some(0)).await);
            let mut controllers = Vec::new();
            let mut waiters = Vec::new();
            let order = Arc::new(Mutex::new(Vec::new()));
            for index in 0..3usize {
                let (controller, context) = stoppable();
                controllers.push(controller);
                let before = queued(&gate);
                waiters.push(tokio::spawn({
                    let gate = Arc::clone(&gate);
                    let order = Arc::clone(&order);
                    async move {
                        let acquired = handoff(&gate, Some(&context), Some(0)).await;
                        if acquired.is_ok() {
                            order.lock().push(index);
                        }
                        acquired.map(|(permit, _)| drop(permit))
                    }
                }));
                await_queued(&gate, before + 1).await;
            }
            assert_eq!(published_at(&gate, rank(0)), (1, 1, 3));

            controllers[cancelled].stop_generating();
            let refused = outcome(waiters.remove(cancelled)).await;
            assert_eq!(
                refused.err().map(|error| error.error_type()),
                Some(ErrorType::Cancelled)
            );
            assert_eq!(published_at(&gate, rank(0)), (1, 1, 2), "removed at once");
            assert_eq!(outcomes_at(&gate, rank(0)).4, 1);
            // The freed place is reusable straight away.
            let replacement = spawn_queued_at(&gate, Some(0), None).await;

            drop(held);
            for waiter in waiters {
                outcome(waiter).await.expect("survivor admitted");
            }
            drop(permit(outcome(replacement).await));
            let survivors: Vec<_> = (0..3).filter(|index| *index != cancelled).collect();
            assert_eq!(*order.lock(), survivors, "cancelled {cancelled}");
            assert_eq!(outcomes_at(&gate, rank(0)), (5, 1, 3, 0, 1));
            assert_eq!(published(&gate), (0, 0, 0));
        }
    }

    /// The race the dequeue check cannot see: capacity is offered while the
    /// caller is still there, then the caller leaves before taking it, so both
    /// outcomes are ready when the request is next polled. Cancellation must
    /// win the offer that is already there, refund both kinds to the next
    /// request in FIFO order, and count once.
    #[tokio::test]
    async fn cancellation_beats_a_simultaneous_offer_and_refunds_both_kinds() {
        let gate = gate(1, 1, 4);
        let held = permit(handoff(&gate, None, None).await);

        // Waiter A is cancellable; poll it exactly once so it registers in the
        // FIFO and then stops being polled.
        let (controller, context) = stoppable();
        let mut doomed = Box::pin(gate.acquire(Some(&context), None));
        assert!(futures::poll!(&mut doomed).is_pending());

        // Waiter B queues behind it and is the one that must inherit the
        // capacity.
        let survivor = spawn_queued_admit(&gate).await;

        // The released capacity is offered to A while its caller is still
        // there, and then the caller stops, before A is polled again.
        drop(held);
        assert_eq!(
            published(&gate),
            (1, 1, 1),
            "the capacity was offered to the live head"
        );
        controller.stop_generating();
        assert!(
            is_cancelled(&doomed.await),
            "a cancelled request must not be admitted by a racing offer"
        );

        // The refund covers both kinds, so the next live waiter is admitted.
        let survivor = permit(outcome(survivor).await);
        assert_eq!(published(&gate), (1, 1, 0));
        drop(survivor);
        assert_eq!(published(&gate), (0, 0, 0));
        assert_eq!(cancellations(&gate), 1);
        assert_eq!(
            admissions(&gate),
            (1, 1),
            "only the holder and the survivor"
        );
        assert_eq!(
            Arc::strong_count(&gate),
            1,
            "tickets and permits must not retain the gate"
        );
    }

    /// A request whose cancellation is first observed at its dequeue decision
    /// is discarded there: no engine capacity, one cancellation, and FIFO
    /// processing continues with the next request.
    #[tokio::test]
    async fn a_cancellation_first_seen_at_the_dequeue_decision_is_discarded() {
        let gate = gate(1, 1, 4);
        let held = permit(handoff(&gate, None, None).await);
        let (controller, context) = stoppable();
        // Queued, then never polled again, so only the dequeue check can see
        // its stop.
        let mut doomed = Box::pin(gate.acquire(Some(&context), None));
        assert!(futures::poll!(&mut doomed).is_pending());
        let next = spawn_queued_admit(&gate).await;
        controller.stop_generating();

        drop(held);
        let next = permit(outcome(next).await);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "the next request got the capacity"
        );
        assert_eq!(cancellations(&gate), 1, "counted at the dequeue");
        assert!(
            is_cancelled(&doomed.await),
            "and the discarded request learns it"
        );
        assert_eq!(cancellations(&gate), 1, "without counting again");
        assert_eq!(admissions(&gate), (1, 1));
        drop(next);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A queued request that leaves without being admitted is a cancellation
    /// exactly once, whether its own future observed the stop or the whole task
    /// was dropped first. Neither shape is a rejection.
    #[tokio::test]
    async fn a_queued_cancellation_counts_once_whether_observed_or_dropped() {
        let gate = gate(1, 1, 4);
        let _held = permit(gate.acquire(None, None).await);

        // Observed: the waiting request is polled again and sees the stop.
        let (controller, context) = stoppable();
        let waiting = spawn_queued_at(&gate, None, Some(context)).await;
        controller.stop_generating();
        assert!(is_cancelled(&outcome(waiting).await));
        assert_eq!(queued(&gate), 0, "cancellation frees the queue place");
        assert_eq!(cancellations(&gate), 1, "counted where observed");

        // Dropped: the task is aborted, so only the ticket's own `Drop` can
        // account for it.
        let abandoned = spawn_queued_admit(&gate).await;
        abandoned.abort();
        let _ = abandoned.await;
        await_queued(&gate, 0).await;
        assert_eq!(cancellations(&gate), 2);

        assert_eq!(rejections(&gate), 0);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    /// Cancelling every queued request — in any order, from every queue —
    /// releases each place once, rank and aggregate, and counts each once.
    #[tokio::test]
    async fn mass_cancellation_releases_every_place_once() {
        let gate = ranked_gate((1, 1, 50), 0, 2);
        let held: Vec<_> =
            futures::future::join_all([Some(0), Some(1)].map(|r| gate.acquire(None, r)))
                .await
                .into_iter()
                .map(permit)
                .collect();
        let mut controllers = Vec::new();
        let mut waiters = Vec::new();
        for index in 0..100u32 {
            let (controller, context) = stoppable();
            controllers.push(controller);
            let dp_rank = (index % 3 != 2).then_some(index % 2);
            waiters.push(spawn_queued_at(&gate, dp_rank, Some(context)).await);
        }
        assert_eq!(queued(&gate), 100);
        for index in (0..100).map(|i| (i * 37) % 100) {
            controllers[index].stop_generating();
        }
        for waiter in waiters {
            assert!(is_cancelled(&outcome(waiter).await));
        }
        assert_eq!(queued(&gate), 0);
        assert!(gate.state.lock().queues.is_empty());
        assert_eq!(cancellations(&gate), 100);
        assert_eq!(published(&gate), (2, 2, 0));
        drop(held);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Cancellation after admission is not the gate's: the request stays an
    /// admission, and its permit releases normally.
    #[tokio::test]
    async fn a_cancellation_after_admission_is_not_a_gate_cancellation() {
        let gate = gate(1, 1, 4);
        let held = permit(gate.acquire(None, None).await);
        let (controller, context) = stoppable();
        let queued = spawn_queued_at(&gate, None, Some(Arc::clone(&context))).await;
        drop(held);
        let (admitted, source) = outcome(queued).await.expect("admitted");
        assert_eq!(source, AdmissionSource::Queue);

        controller.stop_generating();
        assert_eq!(cancellations(&gate), 0);
        drop(admitted);
        assert_eq!(published(&gate), (0, 0, 0));
        assert_eq!(cancellations(&gate), 0);
    }

    #[test]
    fn shedding_is_a_worker_scoped_overload() {
        // Backpressure on this one worker. A pool-scoped `ResourceExhausted`
        // would claim the whole pool is out of room, and a `Backend` error
        // would report a fault that did not happen.
        let error = reject(Rejection::QueueFull { dp_rank: None }, None);
        assert_eq!(error.error_type(), ErrorType::WorkerOverloaded);
        assert_eq!(error.message(), OVERLOADED_MESSAGE);

        // The same overload, limited to one DP rank.
        let error = reject(Rejection::QueueFull { dp_rank: Some(4) }, None);
        assert_eq!(error.error_type(), ErrorType::WorkerRankOverloaded(4));
        assert_eq!(error.message(), RANK_OVERLOADED_MESSAGE);
    }

    #[test]
    fn a_cancellation_is_not_an_overload() {
        // The caller went away. Reporting that as backpressure would migrate or
        // shed against a worker that never refused the request.
        let error = reject(Rejection::Cancelled, None);
        assert_eq!(error.error_type(), ErrorType::Cancelled);
        assert_eq!(error.message(), CANCELLED_MESSAGE);
    }

    ///////////////////// THE ADMITTED STREAM /////////////////////

    /// A stand-in engine response: a sequence number, and what its backend says
    /// it carries.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct Item {
        n: usize,
        output: ResponseOutput,
    }

    impl AdmissionResponse for Item {
        fn admission_output(&self) -> ResponseOutput {
            self.output
        }
    }

    /// Metadata or control only: a bootstrap announcement, a cache report.
    fn interim(n: usize) -> Item {
        Item {
            n,
            output: ResponseOutput::INTERIM,
        }
    }

    /// A generated token that completes nothing.
    fn token(n: usize) -> Item {
        Item {
            n,
            output: ResponseOutput {
                generated_token: true,
                completion: false,
            },
        }
    }

    /// The backend's completion response, carrying no token.
    fn completion(n: usize) -> Item {
        Item {
            n,
            output: ResponseOutput {
                generated_token: false,
                completion: true,
            },
        }
    }

    /// A last token, carried by the completion response itself.
    fn last_token(n: usize) -> Item {
        Item {
            n,
            output: ResponseOutput {
                generated_token: true,
                completion: true,
            },
        }
    }

    /// A stand-in engine: it records that it ran, then returns the two tokens
    /// its stream yields, on its own context.
    async fn generate(
        ran: Arc<AtomicUsize>,
        context: Arc<dyn AsyncEngineContext>,
    ) -> anyhow::Result<EngineStream<Item>> {
        ran.fetch_add(1, Ordering::SeqCst);
        Ok(dynamo_runtime::engine::ResponseStream::new(
            Box::pin(futures::stream::iter([token(1), token(2)])),
            context,
        ))
    }

    /// A stand-in engine whose stream yields exactly `items`, then ends.
    async fn generate_items(items: Vec<Item>) -> anyhow::Result<EngineStream<Item>> {
        Ok(dynamo_runtime::engine::ResponseStream::new(
            Box::pin(futures::stream::iter(items)),
            engine_context(),
        ))
    }

    /// A stand-in engine whose stream yields `items`, then stays open without
    /// another response until it is dropped.
    async fn generate_then_hold(items: Vec<Item>) -> anyhow::Result<EngineStream<Item>> {
        Ok(dynamo_runtime::engine::ResponseStream::new(
            Box::pin(futures::stream::iter(items).chain(futures::stream::pending())),
            engine_context(),
        ))
    }

    /// A stand-in engine whose stream ends without a single response.
    async fn generate_nothing() -> anyhow::Result<EngineStream<Item>> {
        generate_items(Vec::new()).await
    }

    fn engine_context() -> Arc<dyn AsyncEngineContext> {
        Arc::new(Controller::default())
    }

    async fn admit_two(
        gate: &Arc<BackendAdmissionGate>,
        ran: &Arc<AtomicUsize>,
    ) -> EngineStream<Item> {
        gate.admit_inner(None, None, generate(Arc::clone(ran), engine_context()))
            .await
            .expect("admitted")
    }

    /// Admit a stream of `items`, alongside a stream that holds both kinds of
    /// capacity throughout, so a repeated release would show as a count below
    /// it rather than vanish at zero.
    async fn admit_items_beside_a_held_one(
        gate: &Arc<BackendAdmissionGate>,
        items: Vec<Item>,
    ) -> (EngineStream<Item>, EngineStream<Item>) {
        let held = gate
            .admit_inner(None, None, generate_then_hold(Vec::new()))
            .await
            .expect("admitted");
        let stream = gate
            .admit_inner(None, None, generate_items(items))
            .await
            .expect("admitted");
        (held, stream)
    }

    /// The stream is the engine's own. It holds waiting capacity until its
    /// first token and request capacity until it ends, each released exactly
    /// once: a second stream holds both kinds throughout, so a repeated release
    /// would show as a count below it.
    #[tokio::test]
    async fn an_admitted_stream_holds_each_kind_of_capacity_for_its_own_lifetime() {
        let gate = gate(10, 10, 0);
        let ran = Arc::new(AtomicUsize::new(0));
        let _held = admit_two(&gate, &ran).await;
        let context = engine_context();
        let mut stream = gate
            .admit_inner(None, None, generate(Arc::clone(&ran), Arc::clone(&context)))
            .await
            .expect("admitted");
        assert_eq!(ran.load(Ordering::SeqCst), 2);
        assert_eq!(
            published(&gate),
            (2, 2, 0),
            "obtaining the stream is not a response"
        );
        assert!(
            Arc::ptr_eq(&stream.context(), &context),
            "the engine's own context must be delegated, not replaced"
        );

        // The items are the engine's, unchanged.
        assert_eq!(stream.next().await, Some(token(1)));
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "the first token releases waiting capacity only"
        );
        assert_eq!(stream.next().await, Some(token(2)));
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "a later token releases nothing"
        );
        assert_eq!(stream.next().await, None);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "the end of the stream releases request capacity"
        );
        drop(stream);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "and dropping it releases nothing more"
        );
    }

    /// A first token admits the next queued request while the stream that
    /// answered keeps running and keeps its request capacity until it ends.
    #[tokio::test]
    async fn the_first_token_admits_a_queued_request_while_its_stream_continues() {
        let gate = gate(2, 1, 4);
        let ran = Arc::new(AtomicUsize::new(0));
        let mut first = admit_two(&gate, &ran).await;
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(
            published(&gate),
            (1, 1, 1),
            "no token yet, so the next waits"
        );

        assert_eq!(first.next().await, Some(token(1)));
        let (admitted, source) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(source, AdmissionSource::Queue);
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "the queued request waits for its own first token"
        );

        assert_eq!(first.next().await, Some(token(2)));
        assert_eq!(first.next().await, None);
        assert_eq!(published(&gate), (1, 1, 0));
        drop(admitted);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Interim responses — a bootstrap announcement, a cache report — leave the
    /// request waiting; its first token ends the wait, exactly once, and every
    /// response reaches the caller unchanged.
    #[tokio::test]
    async fn interim_responses_leave_a_request_waiting_until_its_first_token() {
        let gate = gate(10, 10, 0);
        let items = vec![interim(1), interim(2), token(3), token(4), last_token(5)];
        let (_held, mut stream) = admit_items_beside_a_held_one(&gate, items.clone()).await;
        assert_eq!(published(&gate), (2, 2, 0));

        let mut seen = Vec::new();
        for (index, expected) in [(2, 2, 0), (2, 2, 0), (2, 1, 0), (2, 1, 0), (2, 1, 0)]
            .into_iter()
            .enumerate()
        {
            seen.push(stream.next().await.expect("the engine's response"));
            assert_eq!(published(&gate), expected, "after response {index}");
        }
        assert_eq!(seen, items, "responses pass through unchanged");
        assert_eq!(stream.next().await, None);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "the end releases request capacity once"
        );
        drop(stream);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    /// A completion that carries no token ends its request's wait at once,
    /// while its stream stays open: the freed waiting capacity admits the next
    /// request then, not when the stream finally ends, and the open stream
    /// keeps its request capacity. A token after it releases nothing more.
    #[tokio::test]
    async fn a_tokenless_completion_ends_the_wait_while_its_stream_stays_open() {
        let gate = gate(10, 1, 4);
        let mut stream = gate
            .admit_inner(
                None,
                None,
                generate_then_hold(vec![interim(1), completion(2), token(3)]),
            )
            .await
            .expect("admitted");
        let queued = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (1, 1, 1));

        assert_eq!(stream.next().await, Some(interim(1)));
        assert_eq!(
            published(&gate),
            (1, 1, 1),
            "an interim response ends no wait"
        );
        assert_eq!(stream.next().await, Some(completion(2)));
        let (next, _) = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "the completion ended the wait; its stream is still open"
        );
        assert_eq!(stream.next().await, Some(token(3)));
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "a token after the completion releases nothing more"
        );
        assert!(
            futures::poll!(stream.next()).is_pending(),
            "the stream is held open"
        );

        drop(stream);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "dropping the open stream releases its request capacity only"
        );
        drop(next);
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A token ends the wait even when the completion comes later, as a
    /// prefill's may: neither the completion nor anything else after the token
    /// releases more, and the end releases request capacity once.
    #[tokio::test]
    async fn a_token_before_the_completion_ends_the_wait_at_the_token() {
        let gate = gate(10, 10, 0);
        let items = vec![interim(1), token(2), interim(3), completion(4), interim(5)];
        let (_held, mut stream) = admit_items_beside_a_held_one(&gate, items.clone()).await;

        let mut seen = Vec::new();
        for (index, expected) in [(2, 2, 0), (2, 1, 0), (2, 1, 0), (2, 1, 0), (2, 1, 0)]
            .into_iter()
            .enumerate()
        {
            seen.push(stream.next().await.expect("the engine's response"));
            assert_eq!(published(&gate), expected, "after response {index}");
        }
        assert_eq!(seen, items, "responses pass through unchanged");
        assert_eq!(stream.next().await, None);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    /// A completion response that also carries the last token ends the wait
    /// once, however many qualifying responses follow.
    #[tokio::test]
    async fn a_completion_carrying_a_token_ends_the_wait_once() {
        let gate = gate(10, 10, 0);
        let (_held, mut stream) = admit_items_beside_a_held_one(
            &gate,
            vec![last_token(1), last_token(2), completion(3), token(4)],
        )
        .await;

        assert_eq!(stream.next().await, Some(last_token(1)));
        assert_eq!(published(&gate), (2, 1, 0));
        while stream.next().await.is_some() {
            assert_eq!(published(&gate), (2, 1, 0));
        }
        assert_eq!(published(&gate), (1, 1, 0));
    }

    /// The gate reads a response's classification only while its request still
    /// waits, so never after the first response that ends the wait — a token
    /// or a completion, whichever comes first — however many follow: what lets
    /// a backend stop classifying its responses there, and leave every later
    /// one interim.
    #[tokio::test]
    async fn the_gate_reads_no_classification_after_the_wait_ends() {
        /// An [`Item`] that counts how often the gate reads it.
        #[derive(Debug)]
        struct Read {
            item: Item,
            reads: Arc<AtomicUsize>,
        }

        impl AdmissionResponse for Read {
            fn admission_output(&self) -> ResponseOutput {
                self.reads.fetch_add(1, Ordering::SeqCst);
                self.item.output
            }
        }

        // Each sequence, with the index of the response that ends its wait.
        let token_first = vec![interim(1), token(2), completion(3), token(4), last_token(5)];
        let completion_first = vec![interim(1), interim(2), completion(3), token(4), token(5)];
        let both_at_once = vec![last_token(1), completion(2), token(3)];
        for (items, decisive) in [(token_first, 1), (completion_first, 2), (both_at_once, 0)] {
            let gate = gate(10, 10, 0);
            let reads = Arc::new(AtomicUsize::new(0));
            let responses: Vec<_> = items
                .iter()
                .map(|&item| Read {
                    item,
                    reads: Arc::clone(&reads),
                })
                .collect();
            let mut stream = gate
                .admit_inner(None, None, async {
                    let stream: EngineStream<Read> = dynamo_runtime::engine::ResponseStream::new(
                        Box::pin(futures::stream::iter(responses)),
                        engine_context(),
                    );
                    Ok(stream)
                })
                .await
                .expect("admitted");
            for (index, item) in items.iter().enumerate() {
                assert_eq!(stream.next().await.map(|read| read.item), Some(*item));
                assert_eq!(
                    reads.load(Ordering::SeqCst),
                    index.min(decisive) + 1,
                    "response {decisive} ends the wait"
                );
            }
            assert!(stream.next().await.is_none());
            assert_eq!(published(&gate), (0, 0, 0));
        }
    }

    /// A stream of interim responses only — a prefill that announces its
    /// handoff and then simply ends — releases both kinds at its end, once.
    #[tokio::test]
    async fn a_stream_of_interim_responses_releases_both_kinds_once_at_its_end() {
        let gate = gate(10, 10, 0);
        let (_held, mut stream) =
            admit_items_beside_a_held_one(&gate, vec![interim(1), interim(2)]).await;
        assert_eq!(stream.next().await, Some(interim(1)));
        assert_eq!(stream.next().await, Some(interim(2)));
        assert_eq!(published(&gate), (2, 2, 0));
        assert_eq!(stream.next().await, None);
        assert_eq!(published(&gate), (1, 1, 0));
        drop(stream);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    /// Only an annotated response's data can carry output: an error frame, and
    /// an event or comment without data, are interim whatever else they hold.
    #[test]
    fn annotations_carry_output_only_in_their_data() {
        let data = Annotated::from_data(last_token(1));
        assert_eq!(data.admission_output(), last_token(1).output);
        assert_eq!(
            Annotated::<Item>::from_error("engine failed").admission_output(),
            ResponseOutput::INTERIM
        );
        let mut error_with_data = Annotated::from_data(token(1));
        error_with_data.event = Some("error".to_string());
        assert_eq!(error_with_data.admission_output(), ResponseOutput::INTERIM);
        let event_only = Annotated::<Item> {
            data: None,
            id: None,
            event: Some("worker_instance_id".to_string()),
            comment: Some(vec!["7".to_string()]),
            error: None,
        };
        assert_eq!(event_only.admission_output(), ResponseOutput::INTERIM);
    }

    /// One rule, whatever the worker's role: a response ends its request's
    /// wait when it carries a generated token, is the completion, or both; an
    /// interim response never does.
    #[test]
    fn a_token_or_a_completion_ends_the_wait() {
        assert!(!ResponseOutput::INTERIM.ends_wait());
        for item in [token(1), completion(1), last_token(1)] {
            assert!(item.output.ends_wait(), "{item:?}");
        }
    }

    #[tokio::test]
    async fn a_stream_that_ends_without_a_response_releases_both_kinds_once() {
        let gate = gate(10, 10, 0);
        let ran = Arc::new(AtomicUsize::new(0));
        let _held = admit_two(&gate, &ran).await;
        let mut empty = gate
            .admit_inner(None, None, generate_nothing())
            .await
            .expect("admitted");
        assert_eq!(published(&gate), (2, 2, 0));

        assert_eq!(
            empty.next().await,
            None,
            "the engine ended without answering"
        );
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "an empty end releases both kinds"
        );
        drop(empty);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "and dropping the ended stream releases nothing more"
        );
    }

    /// Cancellation, task abort and a client that goes away all end in a drop.
    #[tokio::test]
    async fn a_stream_dropped_before_its_wait_ends_releases_both_kinds() {
        let gate = gate(10, 10, 0);
        let (_held, mut stream) =
            admit_items_beside_a_held_one(&gate, vec![interim(1), token(2)]).await;
        assert_eq!(stream.next().await, Some(interim(1)));
        assert_eq!(published(&gate), (2, 2, 0));

        drop(stream);
        assert_eq!(published(&gate), (1, 1, 0));
    }

    #[tokio::test]
    async fn a_stream_dropped_after_its_wait_ends_releases_only_request_capacity() {
        let gate = gate(10, 10, 0);
        let ran = Arc::new(AtomicUsize::new(0));
        let _held = admit_two(&gate, &ran).await;
        let mut stream = admit_two(&gate, &ran).await;
        assert_eq!(stream.next().await, Some(token(1)));
        assert_eq!(published(&gate), (2, 1, 0));

        drop(stream);
        assert_eq!(
            published(&gate),
            (1, 1, 0),
            "waiting capacity is not released a second time"
        );
    }

    #[tokio::test]
    async fn aborting_admit_while_generate_is_pending_releases_both_kinds() {
        // Capacity is reserved before `generate` is polled, so the window
        // between admission and a stream existing has no wrapper to release it
        // — only dropping the `admit` future itself can.
        let gate = gate(1, 1, 4);
        let running = Arc::new(AtomicUsize::new(0));
        let task = tokio::spawn({
            let gate = Arc::clone(&gate);
            let running = Arc::clone(&running);
            async move {
                gate.admit_inner(None, None, async move {
                    running.fetch_add(1, Ordering::SeqCst);
                    std::future::pending::<anyhow::Result<EngineStream<Item>>>().await
                })
                .await
            }
        });
        while running.load(Ordering::SeqCst) == 0 {
            tokio::task::yield_now().await;
        }
        assert_eq!(published(&gate), (1, 1, 0), "held while generate runs");

        task.abort();
        let _ = task.await;
        assert_eq!(
            published(&gate),
            (0, 0, 0),
            "aborting mid-generate releases both"
        );
    }

    #[tokio::test]
    async fn a_failed_generate_releases_both_kinds_and_keeps_its_own_error() {
        let gate = gate(1, 1, 0);

        let error = gate
            .admit_inner(None, None, async {
                Err::<EngineStream<Item>, _>(anyhow::anyhow!("engine failed to start"))
            })
            .await
            .expect_err("the engine failed");
        assert_eq!(error.to_string(), "engine failed to start");
        assert!(
            error.downcast_ref::<DynamoError>().is_none(),
            "an engine failure must pass through untouched"
        );
        assert_eq!(
            published(&gate),
            (0, 0, 0),
            "a failed generate frees both at once"
        );
    }

    #[tokio::test]
    async fn a_refused_request_never_reaches_the_engine() {
        let gate = gate(1, 1, 0);
        let ran = Arc::new(AtomicUsize::new(0));
        let _held = admit_two(&gate, &ran).await;

        let error = gate
            .admit_inner(None, None, generate(Arc::clone(&ran), engine_context()))
            .await
            .expect_err("the second request is refused");
        assert_eq!(
            ran.load(Ordering::SeqCst),
            1,
            "a refused request must not run the engine"
        );

        // The refusal reaches the caller as the standardized error, through the
        // engine's own result type.
        let rejection = error
            .downcast_ref::<DynamoError>()
            .expect("a refusal is a DynamoError");
        assert_eq!(rejection.error_type(), ErrorType::WorkerOverloaded);
        assert_eq!(rejection.message(), OVERLOADED_MESSAGE);
    }

    /// An already-cancelled request must not reach the engine even when the gate
    /// is idle. Direct admission never awaits, so nothing downstream of the
    /// decision would ever notice the caller had gone.
    #[tokio::test]
    async fn an_already_cancelled_request_never_reaches_the_engine() {
        let gate = gate(1, 1, 4);
        let ran = Arc::new(AtomicUsize::new(0));
        let (controller, context) = stoppable();
        controller.stop_generating();

        let error = gate
            .admit_inner(
                Some(&context),
                None,
                generate(Arc::clone(&ran), engine_context()),
            )
            .await
            .expect_err("a cancelled request must be refused");

        assert_eq!(
            ran.load(Ordering::SeqCst),
            0,
            "generate must never be polled"
        );
        let rejection = error
            .downcast_ref::<DynamoError>()
            .expect("a refusal is a DynamoError");
        assert_eq!(rejection.error_type(), ErrorType::Cancelled);
        assert_eq!(rejection.message(), CANCELLED_MESSAGE);
        assert_eq!(
            published(&gate),
            (0, 0, 0),
            "nothing was reserved or queued"
        );
    }

    ///////////////////// DISABLED ADMISSION CONTROL /////////////////////

    #[tokio::test]
    async fn the_disabled_native_gate_forwards_without_reading_admission_metadata() {
        struct Request;
        impl AdmissionRequest for Request {
            fn dp_rank(&self) -> Option<u32> {
                panic!("an unlimited gate needs no admission rank");
            }
        }

        struct Response;
        impl AdmissionResponse for Response {
            fn admission_output(&self) -> ResponseOutput {
                panic!("an unlimited gate needs no response classification");
            }
        }

        struct Inner;
        #[async_trait::async_trait]
        impl AsyncEngine<SingleIn<Request>, ManyOut<Response>, anyhow::Error> for Inner {
            async fn generate(
                &self,
                request: SingleIn<Request>,
            ) -> anyhow::Result<ManyOut<Response>> {
                Ok(dynamo_runtime::engine::ResponseStream::new(
                    Box::pin(futures::stream::iter([Response, Response])),
                    request.context(),
                ))
            }
        }

        for queue in [None, Some(4)] {
            let gate = BackendAdmissionGate::new(ExplicitLimits {
                request_queue_limit: queue,
                ..ExplicitLimits::default()
            });
            let inner: ServiceEngine<SingleIn<Request>, ManyOut<Response>> = Arc::new(Inner);
            let served: ServiceEngine<SingleIn<Request>, ManyOut<Response>> =
                AdmissionEngine::new(Arc::clone(&gate), Arc::clone(&inner));
            assert!(
                !Arc::ptr_eq(&served, &inner),
                "the admission gate stays in the request path"
            );
            let responses = served.generate(SingleIn::new(Request)).await.unwrap();
            assert_eq!(responses.count().await, 2);
            assert_eq!(outcomes(&gate), (0, 0, 0, 0, 0));
            assert_eq!(published(&gate), (0, 0, 0));
        }
    }

    /// With neither engine limit set, by default or with only a queue limit,
    /// every request goes straight to the engine without the gate's lock: here
    /// another thread holds it throughout. However many requests the engine
    /// holds, with a rank or without, even one already cancelled, none is
    /// counted, queued or refused, and each stream is the engine's own.
    #[test]
    fn a_disabled_gate_passes_every_request_straight_to_the_engine() {
        for queue in [None, Some(4)] {
            let gate = BackendAdmissionGate::new(ExplicitLimits {
                request_queue_limit: queue,
                ..ExplicitLimits::default()
            });
            gate.record_engine_capacity(Some(1), 0, 1);
            let ran = Arc::new(AtomicUsize::new(0));
            let (controller, cancelled) = stoppable();
            controller.stop_generating();
            let requests = [
                (None, None),
                (None, Some(0)),
                (None, Some(7)),
                (Some(cancelled), None),
            ];

            let lock = gate.state.lock();
            let (sender, received) = std::sync::mpsc::channel();
            std::thread::spawn({
                let (gate, ran) = (Arc::clone(&gate), Arc::clone(&ran));
                move || {
                    let streams: Vec<_> = requests
                        .into_iter()
                        .map(|(context, dp_rank)| {
                            gate.admit_inner(
                                context.as_ref(),
                                dp_rank,
                                generate(Arc::clone(&ran), engine_context()),
                            )
                            .now_or_never()
                        })
                        .collect();
                    let _ = sender.send(streams);
                }
            });
            let streams = received
                .recv_timeout(Duration::from_secs(5))
                .expect("admitted while another thread holds the gate's lock");
            drop(lock);

            assert_eq!(ran.load(Ordering::SeqCst), 4, "every request ran");
            for stream in streams {
                let stream = stream.expect("never waits").expect("never refused");
                let items: Vec<_> = futures::executor::block_on(stream.collect());
                assert_eq!(items, [token(1), token(2)]);
            }
            assert_eq!(published(&gate), (0, 0, 0));
            assert_eq!(outcomes(&gate), (0, 0, 0, 0, 0), "nothing is counted");
            assert_eq!(
                gate.state.lock().series.len(),
                2,
                "rank 0 and unspecified exist at zero"
            );
        }
    }

    ///////////////////// METRICS /////////////////////

    /// [`spawn_queued_admit`] through the public interface, with the
    /// [`generate`] stand-in as the engine.
    async fn spawn_queued_generate(
        gate: &Arc<BackendAdmissionGate>,
        ran: &Arc<AtomicUsize>,
        context: Option<Arc<dyn AsyncEngineContext>>,
    ) -> tokio::task::JoinHandle<anyhow::Result<EngineStream<Item>>> {
        let before = queued(gate);
        let handle = tokio::spawn({
            let gate = Arc::clone(gate);
            let ran = Arc::clone(ran);
            async move {
                gate.admit_inner(context.as_ref(), None, generate(ran, engine_context()))
                    .await
            }
        });
        await_queued(gate, before + 1).await;
        handle
    }

    /// The typed refusal an `admit` error carries.
    fn admit_refusal(admitted: &anyhow::Result<EngineStream<Item>>) -> Option<(ErrorType, &str)> {
        admitted
            .as_ref()
            .err()
            .and_then(|error| error.downcast_ref::<DynamoError>())
            .map(|error| (error.error_type(), error.message()))
    }

    /// The gauges come from the gate's own counts, so they follow every
    /// transition: direct admission, enqueue, an ended wait with a queued
    /// handoff, completion, and drain.
    #[tokio::test]
    async fn the_gauges_follow_every_transition() {
        let gate = gate(2, 1, 4);
        assert_eq!(published(&gate), (0, 0, 0));
        let mut held = permit(gate.acquire(None, None).await);
        assert_eq!(published(&gate), (1, 1, 0), "direct admission");
        let waiter = spawn_queued_admit(&gate).await;
        assert_eq!(published(&gate), (1, 1, 1), "enqueue");
        held.end_waiting();
        let mut granted = permit(outcome(waiter).await);
        assert_eq!(published(&gate), (2, 1, 0), "ended wait and handoff");
        drop(held);
        assert_eq!(published(&gate), (1, 1, 0), "completion");
        granted.end_waiting();
        assert_eq!(
            published(&gate),
            (1, 0, 0),
            "the handed-off request answers"
        );
        drop(granted);
        assert_eq!(published(&gate), (0, 0, 0), "drain");
    }

    /// Ranks published so far.
    fn publications(gate: &Arc<BackendAdmissionGate>) -> usize {
        gate.state.lock().publications
    }

    /// One transition can change many ranks, each several times — here a rank
    /// report doubles the worker-wide limits, which admits a queued request on
    /// each of 512 ranks, changing both its queue and its engine counts — and
    /// publishes each of them exactly once, from the authoritative counts,
    /// leaving none listed for the next transition, which publishes only the
    /// rank it changes.
    #[tokio::test]
    async fn a_transition_publishes_each_rank_it_changes_once() {
        const RANKS: u32 = 512;
        let gate = ranked_gate((2, 2, 1), 0, RANKS);
        // Unspecified work and one request on each rank fill the worker-wide
        // limits, so each rank's next request queues with room of its own.
        let mut held: Vec<_> = (0..RANKS)
            .map(|_| None)
            .chain((0..RANKS).map(Some))
            .map(|dp_rank| permit(gate.acquire(None, dp_rank).now_or_never().expect("room")))
            .collect();
        let queued: Vec<_> = (0..RANKS)
            .map(|dp_rank| queue_at(&gate, Some(dp_rank), None))
            .collect();

        let before = publications(&gate);
        gate.record_engine_capacity(None, 0, 2 * RANKS);
        assert_eq!(publications(&gate) - before, RANKS as usize);
        for dp_rank in 0..RANKS {
            assert_eq!(occupancy(&gate, rank(dp_rank)), (2, 2, 0), "{dp_rank}");
            assert_eq!(published_at(&gate, rank(dp_rank)), (2, 2, 0), "{dp_rank}");
        }
        {
            let state = gate.state.lock();
            assert!(state.touched.is_empty());
            assert!(state.series.values().all(|metrics| !metrics.touched));
        }

        let before = publications(&gate);
        drop(held.pop());
        assert_eq!(publications(&gate) - before, 1, "only the rank it changes");
        assert_eq!(published_at(&gate, rank(RANKS - 1)), (1, 1, 0));

        drop((queued, held));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// A transition never republishes a rank it does not change: a value
    /// written straight into another rank's series survives it, until a
    /// transition of that rank publishes its counts.
    #[tokio::test]
    async fn a_transition_leaves_the_ranks_it_does_not_change_alone() {
        let gate = ranked_gate((2, 2, 0), 0, 2);
        gate.state.lock().series(rank(1)).set_occupancy(7, 7, 7);
        let zero = permit(gate.acquire(None, Some(0)).await);
        assert_eq!(published_at(&gate, rank(1)), (7, 7, 7));
        let one = permit(gate.acquire(None, Some(1)).await);
        assert_eq!(published_at(&gate, rank(1)), (1, 1, 0));
        drop((zero, one));
        assert_eq!(published(&gate), (0, 0, 0));
    }

    /// Every request the gate receives is counted once on entry, and once more
    /// as admitted only when it is handed to the engine — directly, or after
    /// waiting in the queue. Waiting is not an admission, a shed or
    /// already-cancelled request is never one, and an engine that fails after
    /// the handoff does not undo one.
    #[tokio::test]
    async fn every_request_is_received_once_and_admitted_only_at_the_engine_handoff() {
        let gate = gate(2, 1, 1);
        let ran = Arc::new(AtomicUsize::new(0));
        assert_eq!((receives(&gate), admissions(&gate)), (0, (0, 0)));

        let mut held = admit_two(&gate, &ran).await;
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (1, (1, 0)),
            "free capacity is a direct admission"
        );

        let queued = spawn_queued_generate(&gate, &ran, None).await;
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (2, (1, 0)),
            "waiting in the queue is not an admission"
        );

        let shed = gate
            .admit_inner(None, None, generate(Arc::clone(&ran), engine_context()))
            .await;
        assert_eq!(
            admit_refusal(&shed),
            Some((ErrorType::WorkerOverloaded, OVERLOADED_MESSAGE))
        );
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (3, (1, 0)),
            "a shed request is received but never admitted"
        );
        assert_eq!(rejections(&gate), 1);

        let (controller, context) = stoppable();
        controller.stop_generating();
        let cancelled = gate
            .admit_inner(
                Some(&context),
                None,
                generate(Arc::clone(&ran), engine_context()),
            )
            .await;
        assert_eq!(
            admit_refusal(&cancelled),
            Some((ErrorType::Cancelled, CANCELLED_MESSAGE))
        );
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (4, (1, 0)),
            "nor is one already cancelled on arrival"
        );
        assert_eq!(cancellations(&gate), 1);
        assert_eq!(rejections(&gate), 1, "which is not a rejection");

        // The holder's first token hands waiting capacity to the queued
        // request, which is admitted as it is handed to the engine.
        assert_eq!(held.next().await, Some(token(1)));
        let queued = outcome(queued).await.expect("admitted from the queue");
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (4, (1, 1)),
            "a queued request is admitted at the handoff"
        );
        assert_eq!(
            ran.load(Ordering::SeqCst),
            2,
            "only the admitted requests ran"
        );

        // Never answered, so dropping it frees both kinds for the next one,
        // whose engine then fails.
        drop(queued);
        let failed = gate
            .admit_inner(None, None, async {
                Err::<EngineStream<Item>, _>(anyhow::anyhow!("engine failed to start"))
            })
            .await;
        assert!(failed.is_err());
        assert_eq!(
            (receives(&gate), admissions(&gate)),
            (5, (2, 1)),
            "an engine failure after the handoff stays an admission"
        );

        // Every request received is accounted for exactly once.
        let (direct, queue) = admissions(&gate);
        assert_eq!(
            receives(&gate),
            direct + queue + rejections(&gate) + cancellations(&gate)
        );
    }

    /// The settled identity `receive = admit_direct + admit_queue + rejection +
    /// cancellation` holds for each `dp_rank` series as well as in total.
    #[tokio::test]
    async fn the_settled_accounting_identity_holds_per_rank() {
        let gate = ranked_gate((1, 1, 1), 0, 2);
        let zero = permit(handoff(&gate, None, Some(0)).await);
        let queued_zero = spawn_queued_at(&gate, Some(0), None).await;
        assert!(is_rank_full(&gate.acquire(None, Some(0)).await, 0));
        let (controller, context) = stoppable();
        let queued_one_cancelled = {
            let _one = permit(handoff(&gate, None, Some(1)).await);
            let waiter = spawn_queued_at(&gate, Some(1), Some(context)).await;
            controller.stop_generating();
            outcome(waiter).await
        };
        assert!(is_cancelled(&queued_one_cancelled));
        // Rank 1 has gone quiet, which leaves aggregate room for this one.
        let unspecified = permit(
            handoff(&gate, None, None)
                .now_or_never()
                .expect("aggregate room is free"),
        );
        drop(zero);
        drop(permit(outcome(queued_zero).await));
        drop(unspecified);

        for at in [rank(0), rank(1), UNSPECIFIED] {
            let (received, direct, queue, rejected, cancelled) = outcomes_at(&gate, at);
            assert_eq!(received, direct + queue + rejected + cancelled, "{at:?}");
        }
        assert_eq!(outcomes_at(&gate, rank(0)), (3, 1, 1, 1, 0));
        assert_eq!(outcomes_at(&gate, rank(1)), (2, 1, 0, 0, 1));
        assert_eq!(outcomes_at(&gate, UNSPECIFIED), (1, 1, 0, 0, 0));
    }

    /// A request cancelled while queued, whether its own future observed the
    /// stop or the whole task was dropped, is received and cancelled but never
    /// admitted, and never reaches the engine.
    #[tokio::test]
    async fn a_request_cancelled_while_queued_is_received_but_never_admitted() {
        let gate = gate(1, 1, 4);
        let ran = Arc::new(AtomicUsize::new(0));
        let _held = admit_two(&gate, &ran).await;

        // Observed: the waiting request is polled again and sees the stop.
        let (controller, context) = stoppable();
        let waiting = spawn_queued_generate(&gate, &ran, Some(context)).await;
        controller.stop_generating();
        assert_eq!(
            admit_refusal(&outcome(waiting).await),
            Some((ErrorType::Cancelled, CANCELLED_MESSAGE))
        );

        // Dropped: the task is aborted while it waits.
        let abandoned = spawn_queued_generate(&gate, &ran, None).await;
        abandoned.abort();
        let _ = abandoned.await;
        await_queued(&gate, 0).await;

        assert_eq!(
            ran.load(Ordering::SeqCst),
            1,
            "only the holder reached the engine"
        );
        assert_eq!(receives(&gate), 3, "both cancelled requests were received");
        assert_eq!(
            admissions(&gate),
            (1, 0),
            "neither cancelled request was admitted"
        );
        assert_eq!(cancellations(&gate), 2);
        assert_eq!(rejections(&gate), 0);
    }

    /// A candidate whose caller has already gone is absent, not admitted. Its
    /// receiver stays open, so the gate's offer succeeds and only the ticket can
    /// refuse it: the capacity must not count as an admission or reach the
    /// engine, and must move on to the next request in FIFO order.
    #[tokio::test]
    async fn a_cancelled_candidate_is_never_admitted_and_its_capacity_moves_on() {
        let gate = gate(10, 1, 8);
        let ran = Arc::new(AtomicUsize::new(0));
        let mut held = admit_two(&gate, &ran).await;

        let (controller, context) = stoppable();
        let mut doomed = Box::pin(gate.admit_inner(
            Some(&context),
            None,
            generate(Arc::clone(&ran), engine_context()),
        ));
        assert!(futures::poll!(&mut doomed).is_pending());
        let next = spawn_queued_generate(&gate, &ran, None).await;
        assert_eq!(published(&gate), (1, 1, 2));

        // Offered while its caller is still there, then stopped before it is
        // polled again.
        assert_eq!(held.next().await, Some(token(1)));
        assert_eq!(
            published(&gate),
            (2, 1, 1),
            "the capacity was offered to the candidate"
        );
        controller.stop_generating();

        assert_eq!(
            admit_refusal(&doomed.await),
            Some((ErrorType::Cancelled, CANCELLED_MESSAGE)),
            "cancellation wins the offer"
        );

        let _next = outcome(next).await.expect("admitted from the queue");
        assert_eq!(
            published(&gate),
            (2, 1, 0),
            "the refund went to the next request in FIFO order"
        );
        assert_eq!(
            ran.load(Ordering::SeqCst),
            2,
            "the candidate never reached the engine"
        );
        assert_eq!(
            admissions(&gate),
            (1, 1),
            "the candidate was never admitted"
        );
        assert_eq!(cancellations(&gate), 1);
        assert_eq!(rejections(&gate), 0);
        assert_eq!(receives(&gate), 3);
    }

    /// Collectors are per gate: one gate's counts are invisible to another. The
    /// family a gate registers is covered in
    /// [`metrics`].
    #[tokio::test]
    async fn each_gate_owns_its_collectors() {
        let one = gate(1, 1, 0);
        let two = gate(1, 1, 0);
        let _held = permit(one.acquire(None, None).await);
        assert!(is_queue_full(&one.acquire(None, None).await));
        assert_eq!((rejections(&one), rejections(&two)), (1, 0));
        assert_eq!((published(&one), published(&two)), ((1, 1, 0), (0, 0, 0)));
    }
}