ferrum-interfaces 0.8.4

Core trait contracts for the Ferrum LLM inference engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
//! Model execution interface with clear prefill/decode separation
//!
//! This module provides the ModelExecutor trait that replaces the "fat" Model
//! interface, focusing purely on tensor operations without tokenization or sampling.

use crate::{KvCacheHandle, RecurrentStateHandle, RecurrentStateSpec, TensorRef};
use async_trait::async_trait;
use ferrum_types::{ExecutorAdmissionLimits, FerrumError, ModelInfo, RequestId, Result, TokenId};
use serde::{Deserialize, Serialize};
use std::{
    collections::{hash_map::DefaultHasher, HashMap, HashSet},
    future::Future,
    hash::{Hash, Hasher},
    num::NonZeroU64,
    ops::Range,
    pin::Pin,
    sync::Arc,
};

/// One model-owned KV slot reservation request.
///
/// `cache_id` is the executor/model cache key attached to a sequence. `target_len`
/// is the sequence length that must be writable before the next forward runs.
/// `admission_target_len`, when present, is a larger known-context bound used
/// only for admission fit checks. Paged models must not allocate future blocks
/// for it; it mirrors vLLM's chunked-prefill full-context fit gate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvSlotRequest {
    pub cache_id: String,
    pub target_len: usize,
    pub admission_target_len: Option<usize>,
}

/// Per-cache outcome from a KV slot reservation attempt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvSlotAllocation {
    pub cache_id: String,
    pub blocks_before: usize,
    pub blocks_after: usize,
    pub new_blocks: usize,
}

/// Model-owned paged-KV reservation evidence.
///
/// Executors that own a vLLM-style physical KV block pool return this after
/// reserving all requested slots. Executors without model-owned paged KV return
/// `None` from `reserve_kv_slots`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvSlotReservation {
    pub block_size: usize,
    pub total_blocks: usize,
    pub free_blocks_before: usize,
    pub free_blocks_after: usize,
    pub allocations: Vec<KvSlotAllocation>,
}

/// Point-in-time model-owned paged-KV capacity snapshot.
///
/// This is intentionally smaller than [`KvSlotReservation`]: it lets the
/// engine observe whether physical block capacity has actually changed after a
/// release, without allocating speculative slots or depending on model-family
/// names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KvSlotCapacitySnapshot {
    pub block_size: usize,
    pub total_blocks: usize,
    pub free_blocks: usize,
}

/// Token-validity mask for model-side greedy argmax.
///
/// `valid_token_mask[id] != 0` means token `id` may be selected. Tokens at or
/// above `valid_token_mask.len()` are invalid. The fingerprint lets model
/// backends cache an uploaded device mask without comparing the full vector on
/// every decode step.
#[derive(Clone)]
pub struct TokenSelectionMask {
    pub fingerprint: u64,
    pub valid_token_mask: Arc<[i8]>,
}

impl TokenSelectionMask {
    pub fn new(valid_token_mask: Vec<i8>) -> Self {
        let fingerprint = Self::fingerprint(&valid_token_mask);
        Self {
            fingerprint,
            valid_token_mask: Arc::from(valid_token_mask),
        }
    }

    fn fingerprint(valid_token_mask: &[i8]) -> u64 {
        let mut hasher = DefaultHasher::new();
        valid_token_mask.hash(&mut hasher);
        hasher.finish()
    }

    /// Change a small set of token-validity slots and refresh the cache key
    /// once. `Arc::make_mut` keeps the common unshared request mask in place
    /// and preserves safety when an in-flight backend policy still owns a
    /// clone.
    pub fn set_tokens_validity(&mut self, token_ids: &[u32], valid: bool) -> bool {
        let value = i8::from(valid);
        let slots = Arc::make_mut(&mut self.valid_token_mask);
        let mut changed = false;
        for &token_id in token_ids {
            if let Some(slot) = slots.get_mut(token_id as usize) {
                if *slot != value {
                    *slot = value;
                    changed = true;
                }
            }
        }
        if changed {
            self.fingerprint = Self::fingerprint(slots);
        }
        changed
    }

    pub fn len(&self) -> usize {
        self.valid_token_mask.len()
    }

    pub fn is_empty(&self) -> bool {
        self.valid_token_mask.is_empty()
    }
}

impl std::fmt::Debug for TokenSelectionMask {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let valid_count = self.valid_token_mask.iter().filter(|&&v| v != 0).count();
        f.debug_struct("TokenSelectionMask")
            .field("fingerprint", &self.fingerprint)
            .field("len", &self.valid_token_mask.len())
            .field("valid_count", &valid_count)
            .finish()
    }
}

#[cfg(test)]
mod token_selection_mask_tests {
    use super::TokenSelectionMask;

    #[test]
    fn response_completion_mask_is_copy_on_write_and_restores_fingerprint() {
        let mut mask = TokenSelectionMask::new(vec![1, 1, 1]);
        let original = mask.clone();
        let original_fingerprint = mask.fingerprint;

        assert!(mask.set_tokens_validity(&[1], false));
        assert_eq!(mask.valid_token_mask.as_ref(), &[1, 0, 1]);
        assert_eq!(original.valid_token_mask.as_ref(), &[1, 1, 1]);
        assert_ne!(mask.fingerprint, original_fingerprint);

        let masked_fingerprint = mask.fingerprint;
        assert!(!mask.set_tokens_validity(&[1], false));
        assert_eq!(mask.fingerprint, masked_fingerprint);

        assert!(mask.set_tokens_validity(&[1], true));
        assert_eq!(mask.fingerprint, original_fingerprint);
    }
}

#[derive(Clone, Debug)]
pub enum LogitsReturnPolicy {
    FullLogits,
    GreedyArgmax {
        token_mask: Option<TokenSelectionMask>,
        repetition_penalty: Option<GreedyRepetitionPenalty>,
    },
}

impl Default for LogitsReturnPolicy {
    fn default() -> Self {
        Self::FullLogits
    }
}

impl LogitsReturnPolicy {
    pub fn requires_full_logits(&self) -> bool {
        matches!(self, Self::FullLogits)
    }
}

/// Typed product output returned by a plan-runtime execution wave.
///
/// A selected token is not a one-element logits vector. Keeping the variants
/// distinct prevents the engine from inferring product semantics from tensor
/// shape and lets full-logits requests retain every host-side sampler,
/// grammar, and structured-output processor.
#[derive(Debug, Clone, PartialEq)]
pub enum ExecutorSamplingOutput {
    FullLogits(Vec<f32>),
    GreedyToken(TokenId),
}

impl ExecutorSamplingOutput {
    pub fn full_logits(logits: Vec<f32>) -> Result<Self> {
        if logits.is_empty() {
            return Err(FerrumError::backend(
                "plan-runtime sampling output requires non-empty logits",
            ));
        }
        Ok(Self::FullLogits(logits))
    }

    pub const fn greedy_token(token: TokenId) -> Self {
        Self::GreedyToken(token)
    }

    /// Validate that a device-selected token was explicitly authorized.
    ///
    /// Returning full logits for a greedy policy remains legal: heterogeneous
    /// batches may deliberately fall back to host sampling. The inverse would
    /// skip required product processors and therefore fails closed.
    pub fn validate_for_policy(
        &self,
        policy: &LogitsReturnPolicy,
        vocabulary_size: usize,
    ) -> Result<()> {
        match self {
            Self::FullLogits(logits) if logits.len() != vocabulary_size => {
                return Err(FerrumError::backend(format!(
                    "plan runtime returned {} logits for vocabulary {vocabulary_size}",
                    logits.len()
                )));
            }
            Self::GreedyToken(_) if policy.requires_full_logits() => {
                return Err(FerrumError::backend(
                    "plan runtime returned a greedy token for a full-logits request",
                ));
            }
            Self::GreedyToken(token)
                if usize::try_from(token.get())
                    .ok()
                    .is_none_or(|token| token >= vocabulary_size) =>
            {
                return Err(FerrumError::backend(format!(
                    "plan runtime returned token {} outside vocabulary {vocabulary_size}",
                    token.get()
                )));
            }
            _ => {}
        }
        Ok(())
    }

    pub fn into_full_logits(self) -> Result<Vec<f32>> {
        match self {
            Self::FullLogits(logits) => Ok(logits),
            Self::GreedyToken(_) => Err(FerrumError::backend(
                "plan-runtime prefill unexpectedly returned a selected token",
            )),
        }
    }
}

#[cfg(test)]
mod executor_sampling_output_tests {
    use super::{ExecutorSamplingOutput, LogitsReturnPolicy};
    use ferrum_types::TokenId;

    #[test]
    fn full_logits_require_exact_vocabulary_width() {
        let output = ExecutorSamplingOutput::full_logits(vec![0.0; 4]).unwrap();
        assert!(output
            .validate_for_policy(&LogitsReturnPolicy::FullLogits, 4)
            .is_ok());
        assert!(output
            .validate_for_policy(&LogitsReturnPolicy::FullLogits, 5)
            .is_err());
    }

    #[test]
    fn greedy_token_requires_greedy_policy_and_in_vocabulary_token() {
        let allowed = LogitsReturnPolicy::GreedyArgmax {
            token_mask: None,
            repetition_penalty: None,
        };
        let output = ExecutorSamplingOutput::greedy_token(TokenId::new(3));
        assert!(output.validate_for_policy(&allowed, 4).is_ok());
        assert!(output.validate_for_policy(&allowed, 3).is_err());
        assert!(output
            .validate_for_policy(&LogitsReturnPolicy::FullLogits, 4)
            .is_err());
    }

    #[test]
    fn full_logits_are_a_legal_greedy_batch_fallback() {
        let policy = LogitsReturnPolicy::GreedyArgmax {
            token_mask: None,
            repetition_penalty: None,
        };
        let output = ExecutorSamplingOutput::full_logits(vec![0.0; 4]).unwrap();
        assert!(output.validate_for_policy(&policy, 4).is_ok());
    }
}

/// Sparse repetition-penalty metadata for model-side greedy argmax.
///
/// The token list is request-local and de-duplicated. Applying the penalty
/// before GPU argmax avoids downloading full `[batch, vocab]` logits for the
/// common greedy chat path while preserving repeat avoidance.
#[derive(Clone, Debug)]
pub struct GreedyRepetitionPenalty {
    penalty: f32,
    token_ids: Arc<[u32]>,
}

impl GreedyRepetitionPenalty {
    pub fn new(penalty: f32, mut token_ids: Vec<u32>) -> Self {
        let mut seen = HashSet::with_capacity(token_ids.len());
        token_ids.retain(|token| seen.insert(*token));
        Self {
            penalty,
            token_ids: Arc::from(token_ids),
        }
    }

    pub const fn penalty(&self) -> f32 {
        self.penalty
    }

    pub fn token_ids(&self) -> &[u32] {
        &self.token_ids
    }

    pub fn is_empty(&self) -> bool {
        self.token_ids.is_empty() || self.penalty == 1.0
    }
}

#[cfg(test)]
mod greedy_repetition_penalty_tests {
    use super::GreedyRepetitionPenalty;

    #[test]
    fn constructor_preserves_first_seen_order_and_removes_duplicates() {
        let repetition = GreedyRepetitionPenalty::new(1.1, vec![7, 3, 7, 9, 3]);
        assert_eq!(repetition.penalty(), 1.1);
        assert_eq!(repetition.token_ids(), [7, 3, 9]);
    }
}

/// Input for prefill phase (processing the initial prompt)
#[derive(Debug, Clone)]
pub struct PrefillInput {
    /// Stable product request identity for plan-runtime resources.
    pub request_id: Option<RequestId>,
    /// Maximum sequence extent this request may reach, including the prompt.
    /// Executors use this for fit validation without allocating future pages.
    pub maximum_sequence_tokens: Option<usize>,
    /// Exact scheduler-owned prompt chunk for this invocation.
    ///
    /// The input tensor still contains the full prompt so token identity and
    /// global offsets remain stable. Plan runtimes execute only this range.
    pub chunk: Option<PrefillChunk>,
    /// Input token IDs [batch_size, sequence_length]
    pub input_ids: TensorRef,
    /// Attention mask [batch_size, sequence_length] (optional)
    pub attention_mask: Option<TensorRef>,
    /// Position IDs [batch_size, sequence_length] (optional, for RoPE)
    pub position_ids: Option<TensorRef>,
    /// Pre-allocated KV cache handle (optional, for paged attention)
    pub kv_cache: Option<Arc<dyn KvCacheHandle>>,
    /// Pre-allocated recurrent-state handle (optional, for state-space layers)
    pub recurrent_state: Option<Arc<dyn RecurrentStateHandle>>,
    /// Request metadata that can affect model execution.
    pub metadata: HashMap<String, serde_json::Value>,
}

impl PrefillInput {
    /// Create new prefill input
    pub fn new(input_ids: TensorRef) -> Self {
        Self {
            request_id: None,
            maximum_sequence_tokens: None,
            chunk: None,
            input_ids,
            attention_mask: None,
            position_ids: None,
            kv_cache: None,
            recurrent_state: None,
            metadata: HashMap::new(),
        }
    }

    /// Attach the typed request boundary consumed by plan runtimes.
    pub fn with_request_context(
        mut self,
        request_id: RequestId,
        maximum_sequence_tokens: usize,
    ) -> Self {
        self.request_id = Some(request_id);
        self.maximum_sequence_tokens = Some(maximum_sequence_tokens);
        self
    }

    /// Attach the exact scheduler-published prompt chunk.
    pub fn with_chunk(mut self, chunk: PrefillChunk) -> Self {
        self.chunk = Some(chunk);
        self
    }

    /// Create prefill input with a pre-allocated KV cache handle.
    pub fn with_kv_cache(mut self, kv_cache: Arc<dyn KvCacheHandle>) -> Self {
        self.kv_cache = Some(kv_cache);
        self
    }

    /// Create prefill input with a pre-allocated recurrent-state handle.
    pub fn with_recurrent_state(mut self, recurrent_state: Arc<dyn RecurrentStateHandle>) -> Self {
        self.recurrent_state = Some(recurrent_state);
        self
    }

    /// Attach request metadata.
    pub fn with_metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Add attention mask
    pub fn with_attention_mask(mut self, mask: TensorRef) -> Self {
        self.attention_mask = Some(mask);
        self
    }

    /// Add position IDs
    pub fn with_position_ids(mut self, positions: TensorRef) -> Self {
        self.position_ids = Some(positions);
        self
    }

    /// Get batch size
    pub fn batch_size(&self) -> usize {
        self.input_ids.shape()[0]
    }

    /// Get sequence length
    pub fn sequence_length(&self) -> usize {
        if self.input_ids.shape().len() >= 2 {
            self.input_ids.shape()[1]
        } else {
            1
        }
    }
}

/// Exact, validated prompt progress assigned to one prefill invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct PrefillChunk {
    tokens_processed: usize,
    tokens_to_process: usize,
    total_prompt_tokens: usize,
}

#[cfg(test)]
mod prefill_chunk_tests {
    use super::PrefillChunk;

    #[test]
    fn validates_exact_progress_and_finality() {
        let first = PrefillChunk::new(0, 3, 8).unwrap();
        assert_eq!(first.range(), 0..3);
        assert_eq!(first.end(), 3);
        assert!(!first.is_final());

        let final_chunk = PrefillChunk::new(3, 5, 8).unwrap();
        assert_eq!(final_chunk.range(), 3..8);
        assert!(final_chunk.is_final());
    }

    #[test]
    fn rejects_empty_out_of_bounds_and_overflowing_progress() {
        assert!(PrefillChunk::new(0, 0, 8).is_err());
        assert!(PrefillChunk::new(0, 1, 0).is_err());
        assert!(PrefillChunk::new(7, 2, 8).is_err());
        assert!(PrefillChunk::new(usize::MAX, 1, usize::MAX).is_err());
    }
}

impl PrefillChunk {
    pub fn new(
        tokens_processed: usize,
        tokens_to_process: usize,
        total_prompt_tokens: usize,
    ) -> Result<Self> {
        let end = tokens_processed
            .checked_add(tokens_to_process)
            .ok_or_else(|| {
                ferrum_types::FerrumError::request_validation("prefill chunk overflows")
            })?;
        if tokens_to_process == 0 || total_prompt_tokens == 0 || end > total_prompt_tokens {
            return Err(ferrum_types::FerrumError::request_validation(
                "prefill chunk must be non-empty and within the full prompt",
            ));
        }
        Ok(Self {
            tokens_processed,
            tokens_to_process,
            total_prompt_tokens,
        })
    }

    pub const fn tokens_processed(self) -> usize {
        self.tokens_processed
    }

    pub const fn tokens_to_process(self) -> usize {
        self.tokens_to_process
    }

    pub const fn total_prompt_tokens(self) -> usize {
        self.total_prompt_tokens
    }

    pub fn range(self) -> Range<usize> {
        self.tokens_processed..self.tokens_processed + self.tokens_to_process
    }

    pub const fn end(self) -> usize {
        self.tokens_processed + self.tokens_to_process
    }

    pub const fn is_final(self) -> bool {
        self.end() == self.total_prompt_tokens
    }
}

/// Output from prefill phase
#[derive(Debug, Clone)]
pub struct PrefillOutput {
    /// Logits for all positions [batch_size, sequence_length, vocab_size]
    pub logits: TensorRef,
    /// KV cache handle populated with prompt states
    pub kv_cache: Arc<dyn KvCacheHandle>,
    /// Recurrent-state handle populated with prompt state, when used.
    pub recurrent_state: Option<Arc<dyn RecurrentStateHandle>>,
    /// Hidden states at each layer (optional, for analysis)
    pub hidden_states: Option<Vec<TensorRef>>,
    /// Attention weights (optional, for analysis)
    pub attention_weights: Option<Vec<TensorRef>>,
}

impl PrefillOutput {
    /// Create new prefill output
    pub fn new(logits: TensorRef, kv_cache: Arc<dyn KvCacheHandle>) -> Self {
        Self {
            logits,
            kv_cache,
            recurrent_state: None,
            hidden_states: None,
            attention_weights: None,
        }
    }

    /// Attach updated recurrent state to the prefill output.
    pub fn with_recurrent_state(mut self, recurrent_state: Arc<dyn RecurrentStateHandle>) -> Self {
        self.recurrent_state = Some(recurrent_state);
        self
    }

    /// Get logits for last position (for next token generation)
    pub fn last_token_logits(&self) -> Result<TensorRef> {
        let shape = self.logits.shape();
        if shape.len() != 3 {
            return Err(ferrum_types::FerrumError::backend(
                "Expected 3D logits tensor [batch, seq, vocab]",
            ));
        }

        let seq_len = shape[1];
        if seq_len == 0 {
            return Err(ferrum_types::FerrumError::backend("Empty sequence"));
        }

        // Extract last position: [batch, seq-1:seq, vocab] -> [batch, vocab]
        self.logits
            .view(&[0, seq_len - 1, 0], &[shape[0], seq_len, shape[2]])
    }
}

/// Input for decode phase (generating one token at a time)
#[derive(Debug, Clone)]
pub struct DecodeInput {
    /// Stable product request identity for plan-runtime resources.
    pub request_id: Option<RequestId>,
    /// Input token ID for current step [batch_size, 1]
    pub input_ids: TensorRef,
    /// Existing KV cache from previous steps
    pub kv_cache: Arc<dyn KvCacheHandle>,
    /// Existing recurrent state from previous steps, when used.
    pub recurrent_state: Option<Arc<dyn RecurrentStateHandle>>,
    /// Position IDs for current step [batch_size, 1] (optional)
    pub position_ids: Option<TensorRef>,
    /// Request metadata that can affect model execution.
    pub metadata: HashMap<String, serde_json::Value>,
    /// How the model may return final-position logits for this request.
    pub logits_policy: LogitsReturnPolicy,
}

impl DecodeInput {
    /// Create new decode input
    pub fn new(input_ids: TensorRef, kv_cache: Arc<dyn KvCacheHandle>) -> Self {
        Self {
            request_id: None,
            input_ids,
            kv_cache,
            recurrent_state: None,
            position_ids: None,
            metadata: HashMap::new(),
            logits_policy: LogitsReturnPolicy::FullLogits,
        }
    }

    /// Attach the product request identity to this decode step.
    pub fn with_request_id(mut self, request_id: RequestId) -> Self {
        self.request_id = Some(request_id);
        self
    }

    /// Add position IDs
    pub fn with_position_ids(mut self, positions: TensorRef) -> Self {
        self.position_ids = Some(positions);
        self
    }

    /// Attach recurrent state for state-space or hybrid layers.
    pub fn with_recurrent_state(mut self, recurrent_state: Arc<dyn RecurrentStateHandle>) -> Self {
        self.recurrent_state = Some(recurrent_state);
        self
    }

    /// Attach request metadata.
    pub fn with_metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = metadata;
        self
    }

    pub fn with_logits_policy(mut self, policy: LogitsReturnPolicy) -> Self {
        self.logits_policy = policy;
        self
    }

    /// Get batch size
    pub fn batch_size(&self) -> usize {
        self.input_ids.shape()[0]
    }
}

/// One sequence's contribution to a unified mixed-batch forward.
///
/// A unified batch lets a single model forward pass process a mix of
/// per-sequence work units: a prefill chunk (q_tokens.len() ≥ 1, possibly
/// continuing from `pos_offset > 0` for chunked prefill) and a decode step
/// (q_tokens.len() == 1, `pos_offset` = current cache length) coexist in
/// the same call. The model layer concatenates all `q_tokens` into one
/// [M_total, hidden] tensor and runs all GEMMs / norms once; only the
/// attention kernel sees per-item segmentation.
///
/// This is the abstraction that enables vLLM-style chunked prefill where
/// decode tokens for already-running sequences are produced in the same
/// iter as a prefill chunk for a newly-arriving sequence.
#[derive(Clone)]
pub struct UnifiedBatchItem {
    /// Identifier matching the sequence's KV cache (model-side keying).
    pub seq_id: String,
    /// Tokens to process this iter. For decode this is exactly 1 token;
    /// for prefill (chunked or whole) this is the chunk's tokens.
    pub q_tokens: Vec<u32>,
    /// KV cache handle for this sequence.
    pub kv_cache: Arc<dyn KvCacheHandle>,
    /// Recurrent-state handle for this sequence, when used.
    pub recurrent_state: Option<Arc<dyn RecurrentStateHandle>>,
    /// Starting absolute position for the FIRST token in `q_tokens`.
    /// 0 for a fresh prefill, `kv_len` for a decode step or a continuing
    /// chunked-prefill slice.
    pub pos_offset: usize,
    /// True iff this item completes the request's prefill (or is a decode
    /// item) — i.e. logits at the last token of `q_tokens` should be
    /// returned for sampling. Intermediate prefill chunks set this false
    /// to skip the lm_head + sampling path.
    pub is_final_chunk: bool,
    /// Request metadata that can affect model execution.
    pub metadata: HashMap<String, serde_json::Value>,
    /// How the model may return final-position logits for this item.
    pub logits_policy: LogitsReturnPolicy,
}

impl std::fmt::Debug for UnifiedBatchItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UnifiedBatchItem")
            .field("seq_id", &self.seq_id)
            .field("q_len", &self.q_tokens.len())
            .field("has_recurrent_state", &self.recurrent_state.is_some())
            .field("pos_offset", &self.pos_offset)
            .field("is_final_chunk", &self.is_final_chunk)
            .finish()
    }
}

/// A mixed-batch forward request: any combination of in-progress prefill
/// chunks and decode steps. See [`UnifiedBatchItem`] for the per-item
/// semantics. The producer (engine) groups all sequences active in this
/// iter into a single batch; the consumer (model) runs one forward and
/// returns per-item logits (only for items with `is_final_chunk = true`,
/// in the order they appear in `items`).
#[derive(Debug, Clone, Default)]
pub struct UnifiedBatch {
    pub items: Vec<UnifiedBatchItem>,
}

impl UnifiedBatch {
    pub fn new() -> Self {
        Self::default()
    }

    /// Total query tokens across all items — corresponds to the M dim of
    /// the model's per-layer GEMMs in the unified forward.
    pub fn total_q_tokens(&self) -> usize {
        self.items.iter().map(|it| it.q_tokens.len()).sum()
    }

    /// Number of items that will produce a logits vector (decode items
    /// always; prefill items only on their final chunk).
    pub fn num_sampled_items(&self) -> usize {
        self.items.iter().filter(|it| it.is_final_chunk).count()
    }
}

/// Tensor-free decode input for an executor with plan-runtime resource
/// authority.
///
/// The runtime already owns the request's physical cache and accepts exactly
/// one token per decode frontier, so materializing a host tensor here adds no
/// information. Legacy and modality executors continue to use [`DecodeInput`].
#[derive(Debug, Clone)]
pub struct PlanRuntimeDecodeInput {
    pub request_id: RequestId,
    pub input_token: TokenId,
    pub kv_cache: Arc<dyn KvCacheHandle>,
    pub logits_policy: LogitsReturnPolicy,
}

impl PlanRuntimeDecodeInput {
    pub fn new(
        request_id: RequestId,
        input_token: TokenId,
        kv_cache: Arc<dyn KvCacheHandle>,
    ) -> Self {
        Self {
            request_id,
            input_token,
            kv_cache,
            logits_policy: LogitsReturnPolicy::FullLogits,
        }
    }

    pub fn with_logits_policy(mut self, logits_policy: LogitsReturnPolicy) -> Self {
        self.logits_policy = logits_policy;
        self
    }
}

/// Tensor-free prefill input for an executor with plan-runtime resource
/// authority.
///
/// The complete prompt remains immutable across chunk retries so scheduler
/// offsets and executor sequence identity cannot drift. Physical KV and
/// recurrent resources remain opaque executor-owned state.
#[derive(Debug, Clone)]
pub struct PlanRuntimePrefillInput {
    pub request_id: RequestId,
    pub input_tokens: Arc<[TokenId]>,
    pub maximum_sequence_tokens: usize,
    pub chunk: PrefillChunk,
}

impl PlanRuntimePrefillInput {
    pub fn new(
        request_id: RequestId,
        input_tokens: impl Into<Arc<[TokenId]>>,
        maximum_sequence_tokens: usize,
        chunk: PrefillChunk,
    ) -> Result<Self> {
        let input_tokens = input_tokens.into();
        if input_tokens.is_empty() {
            return Err(FerrumError::request_validation(
                "plan-runtime prefill requires at least one input token",
            ));
        }
        if chunk.total_prompt_tokens() != input_tokens.len() {
            return Err(FerrumError::request_validation(format!(
                "plan-runtime prefill chunk declares {} prompt tokens for input length {}",
                chunk.total_prompt_tokens(),
                input_tokens.len()
            )));
        }
        if maximum_sequence_tokens < input_tokens.len() {
            return Err(FerrumError::request_validation(format!(
                "plan-runtime sequence ceiling {maximum_sequence_tokens} does not cover prompt length {}",
                input_tokens.len()
            )));
        }
        Ok(Self {
            request_id,
            input_tokens,
            maximum_sequence_tokens,
            chunk,
        })
    }
}

/// Output from decode phase
#[derive(Debug, Clone)]
pub struct DecodeOutput {
    /// Logits for next token [batch_size, vocab_size]
    pub logits: TensorRef,
    /// Updated KV cache with new token state
    pub kv_cache: Arc<dyn KvCacheHandle>,
    /// Updated recurrent state, when used.
    pub recurrent_state: Option<Arc<dyn RecurrentStateHandle>>,
    /// Hidden state for current token (optional)
    pub hidden_state: Option<TensorRef>,
    /// Attention weights for current token (optional)
    pub attention_weights: Option<Vec<TensorRef>>,
}

impl DecodeOutput {
    /// Create new decode output
    pub fn new(logits: TensorRef, kv_cache: Arc<dyn KvCacheHandle>) -> Self {
        Self {
            logits,
            kv_cache,
            recurrent_state: None,
            hidden_state: None,
            attention_weights: None,
        }
    }

    /// Attach updated recurrent state to the decode output.
    pub fn with_recurrent_state(mut self, recurrent_state: Arc<dyn RecurrentStateHandle>) -> Self {
        self.recurrent_state = Some(recurrent_state);
        self
    }
}

/// Tensor-free decode output from a plan-runtime executor.
#[derive(Debug, Clone)]
pub struct PlanRuntimeDecodeOutput {
    pub sampling_output: ExecutorSamplingOutput,
    pub kv_cache: Arc<dyn KvCacheHandle>,
}

impl PlanRuntimeDecodeOutput {
    pub fn new(sampling_output: ExecutorSamplingOutput, kv_cache: Arc<dyn KvCacheHandle>) -> Self {
        Self {
            sampling_output,
            kv_cache,
        }
    }
}

/// Product state emitted by one completed plan-runtime prefill chunk.
#[derive(Debug)]
pub enum PlanRuntimePrefillProduct {
    /// An intermediate chunk updates executor-owned state but is not sampleable.
    Intermediate,
    /// A final chunk returns the complete vocabulary row to the engine.
    FinalLogits(Vec<f32>),
}

/// Exact executor-owned authority advanced by one prefill completion.
#[derive(Debug)]
pub struct PlanRuntimePrefillAuthority {
    request_id: RequestId,
    committed_tokens: usize,
    kv_cache: Arc<dyn KvCacheHandle>,
}

impl PlanRuntimePrefillAuthority {
    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    pub const fn committed_tokens(&self) -> usize {
        self.committed_tokens
    }

    pub fn kv_cache(&self) -> &Arc<dyn KvCacheHandle> {
        &self.kv_cache
    }

    pub fn into_cache(self) -> Arc<dyn KvCacheHandle> {
        self.kv_cache
    }
}

/// Tensor-free prefill output bound to one request and committed KV extent.
#[derive(Debug)]
pub struct PlanRuntimePrefillOutput {
    authority: PlanRuntimePrefillAuthority,
    product: PlanRuntimePrefillProduct,
}

impl PlanRuntimePrefillOutput {
    pub fn intermediate(
        request_id: RequestId,
        committed_tokens: usize,
        kv_cache: Arc<dyn KvCacheHandle>,
    ) -> Self {
        Self {
            authority: PlanRuntimePrefillAuthority {
                request_id,
                committed_tokens,
                kv_cache,
            },
            product: PlanRuntimePrefillProduct::Intermediate,
        }
    }

    pub fn final_logits(
        request_id: RequestId,
        committed_tokens: usize,
        logits: Vec<f32>,
        kv_cache: Arc<dyn KvCacheHandle>,
    ) -> Result<Self> {
        if logits.is_empty() {
            return Err(FerrumError::backend(
                "plan-runtime final prefill returned empty logits",
            ));
        }
        Ok(Self {
            authority: PlanRuntimePrefillAuthority {
                request_id,
                committed_tokens,
                kv_cache,
            },
            product: PlanRuntimePrefillProduct::FinalLogits(logits),
        })
    }

    pub fn request_id(&self) -> &RequestId {
        self.authority.request_id()
    }

    pub const fn committed_tokens(&self) -> usize {
        self.authority.committed_tokens()
    }

    pub fn product(&self) -> &PlanRuntimePrefillProduct {
        &self.product
    }

    pub fn kv_cache(&self) -> &Arc<dyn KvCacheHandle> {
        self.authority.kv_cache()
    }

    pub fn validate_for_completion(
        &self,
        expected_request_id: &RequestId,
        completed_chunk: PrefillChunk,
        vocabulary_size: usize,
    ) -> Result<()> {
        if self.request_id() != expected_request_id {
            return Err(FerrumError::backend(format!(
                "plan runtime returned prefill output for request {}, expected {expected_request_id}",
                self.request_id()
            )));
        }
        if self.committed_tokens() != completed_chunk.end() {
            return Err(FerrumError::backend(format!(
                "plan runtime returned prefill extent {}, expected {}",
                self.committed_tokens(),
                completed_chunk.end()
            )));
        }
        if self.kv_cache().num_tokens() != self.committed_tokens() {
            return Err(FerrumError::backend(format!(
                "plan runtime prefill cache `{}` reports {} tokens for committed extent {}",
                self.kv_cache().cache_id(),
                self.kv_cache().num_tokens(),
                self.committed_tokens()
            )));
        }
        match (&self.product, completed_chunk.is_final()) {
            (PlanRuntimePrefillProduct::Intermediate, false) => Ok(()),
            (PlanRuntimePrefillProduct::FinalLogits(logits), true)
                if logits.len() == vocabulary_size =>
            {
                Ok(())
            }
            (PlanRuntimePrefillProduct::FinalLogits(logits), true) => {
                Err(FerrumError::backend(format!(
                    "plan runtime returned {} final prefill logits for vocabulary {vocabulary_size}",
                    logits.len()
                )))
            }
            (PlanRuntimePrefillProduct::Intermediate, true) => Err(FerrumError::backend(
                "plan runtime returned an intermediate product for a final prefill chunk",
            )),
            (PlanRuntimePrefillProduct::FinalLogits(_), false) => Err(FerrumError::backend(
                "plan runtime returned final logits for an intermediate prefill chunk",
            )),
        }
    }

    pub fn into_parts(self) -> (PlanRuntimePrefillAuthority, PlanRuntimePrefillProduct) {
        (self.authority, self.product)
    }
}

/// Product-authoritative evidence for a successfully completed sequence.
///
/// Physical cache release is not completion evidence: cancellation, failure,
/// recompute, and successful generation all release the same cache authority.
/// The engine constructs this receipt only after it has finalized user-visible
/// token usage, allowing plan runtimes to reconcile terminal events without
/// inferring output counts from execution frames.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutorSequenceCompletion {
    request_id: RequestId,
    cache_id: String,
    input_tokens: u64,
    output_tokens: u64,
}

impl ExecutorSequenceCompletion {
    pub fn new(
        request_id: RequestId,
        cache_id: String,
        input_tokens: usize,
        output_tokens: usize,
    ) -> Result<Self> {
        if cache_id.is_empty() {
            return Err(FerrumError::request_validation(
                "executor sequence completion requires a cache identity",
            ));
        }
        let input_tokens = u64::try_from(input_tokens).map_err(|_| {
            FerrumError::request_validation("executor completion input token count exceeds u64")
        })?;
        let output_tokens = u64::try_from(output_tokens).map_err(|_| {
            FerrumError::request_validation("executor completion output token count exceeds u64")
        })?;
        Ok(Self {
            request_id,
            cache_id,
            input_tokens,
            output_tokens,
        })
    }

    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    pub fn cache_id(&self) -> &str {
        &self.cache_id
    }

    pub const fn input_tokens(&self) -> u64 {
        self.input_tokens
    }

    pub const fn output_tokens(&self) -> u64 {
        self.output_tokens
    }
}

pub use ferrum_types::ExecutionResourceAuthority;

/// Request-scoped authority selected for a capacity-pressure preemption.
///
/// The cache identity prevents the engine from releasing a newer sequence
/// incarnation after a stale scheduler decision. Implementations must retire
/// retained prefill and active decode authority through the same operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutorExecutionCapacityPreemption {
    request_id: RequestId,
    cache_id: String,
}

impl ExecutorExecutionCapacityPreemption {
    pub fn new(request_id: RequestId, cache_id: String) -> Result<Self> {
        if cache_id.is_empty() {
            return Err(FerrumError::request_validation(
                "execution-capacity preemption requires a cache identity",
            ));
        }
        Ok(Self {
            request_id,
            cache_id,
        })
    }

    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    pub fn cache_id(&self) -> &str {
        &self.cache_id
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutorExecutionCapacityPreemptionAuthority {
    RetainedPrefill,
    ActiveSequence,
}

/// Proof that the executor retired one exact request authority to a terminal
/// state. Source-generation advancement remains independently verified by the
/// engine before the scheduler may resume another frontier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutorExecutionCapacityPreemptionReceipt {
    request_id: RequestId,
    cache_id: String,
    authority: ExecutorExecutionCapacityPreemptionAuthority,
}

impl ExecutorExecutionCapacityPreemptionReceipt {
    pub fn new(
        request_id: RequestId,
        cache_id: String,
        authority: ExecutorExecutionCapacityPreemptionAuthority,
    ) -> Self {
        Self {
            request_id,
            cache_id,
            authority,
        }
    }

    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    pub fn cache_id(&self) -> &str {
        &self.cache_id
    }

    pub const fn authority(&self) -> ExecutorExecutionCapacityPreemptionAuthority {
        self.authority
    }
}

/// Point-in-time memory evidence emitted by the shared plan runtime.
///
/// Static model allocations are separated from dynamic request resources so
/// product telemetry never reports model weights as KV or recurrent-state
/// usage. Process-wide claims are included because another live plan can
/// consume capacity visible to this runtime. Dynamic free bytes remain
/// reusable by this plan; quarantined and other claimed bytes do not.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanRuntimeResourceSnapshot {
    device_capacity_bytes: u64,
    usable_capacity_bytes: u64,
    process_claimed_bytes: u64,
    plan_claimed_bytes: u64,
    static_bytes: u64,
    dynamic_resident_bytes: u64,
    dynamic_free_bytes: u64,
    pending_growth_bytes: u64,
    quarantined_bytes: u64,
}

impl PlanRuntimeResourceSnapshot {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        device_capacity_bytes: u64,
        usable_capacity_bytes: u64,
        process_claimed_bytes: u64,
        plan_claimed_bytes: u64,
        static_bytes: u64,
        dynamic_resident_bytes: u64,
        dynamic_free_bytes: u64,
        pending_growth_bytes: u64,
        quarantined_bytes: u64,
    ) -> Result<Self> {
        let snapshot = Self {
            device_capacity_bytes,
            usable_capacity_bytes,
            process_claimed_bytes,
            plan_claimed_bytes,
            static_bytes,
            dynamic_resident_bytes,
            dynamic_free_bytes,
            pending_growth_bytes,
            quarantined_bytes,
        };
        snapshot.validate()?;
        Ok(snapshot)
    }

    /// Revalidates deserialized evidence before it crosses a trusted failure or
    /// profile boundary.
    pub fn validate(&self) -> Result<()> {
        if self.usable_capacity_bytes > self.device_capacity_bytes {
            return Err(ferrum_types::FerrumError::internal(format!(
                "plan runtime usable capacity {} exceeds device capacity {}",
                self.usable_capacity_bytes, self.device_capacity_bytes
            )));
        }
        if self.process_claimed_bytes > self.usable_capacity_bytes {
            return Err(ferrum_types::FerrumError::internal(format!(
                "plan runtime process claims {} exceed usable capacity {}",
                self.process_claimed_bytes, self.usable_capacity_bytes
            )));
        }
        if self.plan_claimed_bytes > self.process_claimed_bytes {
            return Err(ferrum_types::FerrumError::internal(format!(
                "plan runtime plan claims {} exceed process claims {}",
                self.plan_claimed_bytes, self.process_claimed_bytes
            )));
        }
        if self.dynamic_free_bytes > self.dynamic_resident_bytes {
            return Err(ferrum_types::FerrumError::internal(format!(
                "plan runtime dynamic free bytes {} exceed resident bytes {}",
                self.dynamic_free_bytes, self.dynamic_resident_bytes
            )));
        }
        let minimum_plan_claim = self
            .static_bytes
            .checked_add(self.dynamic_resident_bytes)
            .and_then(|bytes| bytes.checked_add(self.quarantined_bytes))
            .ok_or_else(|| {
                ferrum_types::FerrumError::internal(
                    "plan runtime static, resident, and quarantined bytes overflow u64",
                )
            })?;
        if minimum_plan_claim > self.plan_claimed_bytes {
            return Err(ferrum_types::FerrumError::internal(format!(
                "plan runtime accounted plan bytes {minimum_plan_claim} exceed plan claims {}",
                self.plan_claimed_bytes
            )));
        }
        Ok(())
    }

    pub const fn device_capacity_bytes(&self) -> u64 {
        self.device_capacity_bytes
    }

    pub const fn usable_capacity_bytes(&self) -> u64 {
        self.usable_capacity_bytes
    }

    pub const fn process_claimed_bytes(&self) -> u64 {
        self.process_claimed_bytes
    }

    pub const fn plan_claimed_bytes(&self) -> u64 {
        self.plan_claimed_bytes
    }

    pub const fn static_bytes(&self) -> u64 {
        self.static_bytes
    }

    pub const fn dynamic_resident_bytes(&self) -> u64 {
        self.dynamic_resident_bytes
    }

    pub const fn dynamic_free_bytes(&self) -> u64 {
        self.dynamic_free_bytes
    }

    pub const fn dynamic_used_bytes(&self) -> u64 {
        self.dynamic_resident_bytes - self.dynamic_free_bytes
    }

    pub const fn pending_growth_bytes(&self) -> u64 {
        self.pending_growth_bytes
    }

    pub const fn quarantined_bytes(&self) -> u64 {
        self.quarantined_bytes
    }

    /// Capacity immediately reusable by this plan without reclaiming another
    /// plan: process-wide unclaimed bytes plus free extents already resident
    /// in this plan's dynamic pools.
    pub fn available_bytes(&self) -> Result<u64> {
        self.usable_capacity_bytes
            .checked_sub(self.process_claimed_bytes)
            .and_then(|bytes| bytes.checked_add(self.dynamic_free_bytes))
            .ok_or_else(|| {
                ferrum_types::FerrumError::internal(
                    "plan runtime available capacity calculation overflowed",
                )
            })
    }

    pub fn used_bytes(&self) -> Result<u64> {
        self.available_bytes().and_then(|available| {
            self.usable_capacity_bytes
                .checked_sub(available)
                .ok_or_else(|| {
                    ferrum_types::FerrumError::internal(
                        "plan runtime available bytes exceed usable capacity",
                    )
                })
        })
    }
}

#[cfg(test)]
mod plan_runtime_resource_snapshot_tests {
    use super::PlanRuntimeResourceSnapshot;

    #[test]
    fn separates_static_and_dynamic_usage() {
        let snapshot =
            PlanRuntimeResourceSnapshot::new(1_000, 900, 710, 710, 400, 300, 200, 20, 10).unwrap();

        assert_eq!(snapshot.available_bytes().unwrap(), 390);
        assert_eq!(snapshot.used_bytes().unwrap(), 510);
        assert_eq!(snapshot.dynamic_resident_bytes(), 300);
        assert_eq!(snapshot.dynamic_used_bytes(), 100);
        assert_eq!(snapshot.dynamic_free_bytes(), 200);
        assert_eq!(snapshot.pending_growth_bytes(), 20);
        assert_eq!(snapshot.quarantined_bytes(), 10);
    }

    #[test]
    fn rejects_incoherent_capacity_evidence() {
        assert!(PlanRuntimeResourceSnapshot::new(1_000, 1_001, 0, 0, 0, 0, 0, 0, 0).is_err());
        assert!(PlanRuntimeResourceSnapshot::new(1_000, 900, 901, 0, 0, 0, 0, 0, 0).is_err());
        assert!(PlanRuntimeResourceSnapshot::new(1_000, 900, 500, 501, 0, 0, 0, 0, 0).is_err());
        assert!(PlanRuntimeResourceSnapshot::new(1_000, 900, 100, 100, 0, 100, 101, 0, 0).is_err());
        assert!(PlanRuntimeResourceSnapshot::new(1_000, 900, 500, 500, 400, 100, 0, 0, 1).is_err());
    }
}

/// Typed origin for an executor-owned request lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutorRequestOrigin {
    Product,
    Startup,
    Diagnostic,
}

impl ExecutorRequestOrigin {
    pub const fn namespace(self) -> &'static str {
        match self {
            Self::Product => "product",
            Self::Startup => "startup",
            Self::Diagnostic => "diagnostic",
        }
    }

    pub fn from_namespaced_request_identity(identity: &str) -> Option<Self> {
        let suffix = identity.strip_prefix("request.")?;
        let (namespace, request_id) = suffix.split_once('.')?;
        if request_id.is_empty() {
            return None;
        }
        match namespace {
            "product" => Some(Self::Product),
            "startup" => Some(Self::Startup),
            "diagnostic" => Some(Self::Diagnostic),
            _ => None,
        }
    }
}

/// Borrowed, already-tokenized input used to probe plan-runtime prefill
/// admission before the request can enter a device submission batch.
///
/// This carries semantic token identity rather than an aggregate token count:
/// vNext derives the exact resource work shape and its fingerprint from this
/// boundary. The request remains owned by the scheduler while the executor
/// retains any admitted authority internally until [`ModelExecutor::prefill`]
/// consumes it or cancellation releases it.
#[derive(Debug, Clone, Copy)]
pub struct ExecutorPrefillAdmission<'a> {
    pub request_id: &'a RequestId,
    pub input_tokens: &'a [TokenId],
    pub maximum_sequence_tokens: usize,
    /// Prompt tokens reported in the final product usage.
    pub product_prompt_tokens: usize,
    /// Already-committed output tokens replayed as part of a recompute input.
    pub replayed_output_tokens: usize,
    pub request_origin: ExecutorRequestOrigin,
}

impl<'a> ExecutorPrefillAdmission<'a> {
    pub const fn for_startup(
        request_id: &'a RequestId,
        input_tokens: &'a [TokenId],
        maximum_sequence_tokens: usize,
    ) -> Self {
        Self {
            request_id,
            input_tokens,
            maximum_sequence_tokens,
            product_prompt_tokens: input_tokens.len(),
            replayed_output_tokens: 0,
            request_origin: ExecutorRequestOrigin::Startup,
        }
    }

    pub const fn for_diagnostic(
        request_id: &'a RequestId,
        input_tokens: &'a [TokenId],
        maximum_sequence_tokens: usize,
    ) -> Self {
        Self {
            request_id,
            input_tokens,
            maximum_sequence_tokens,
            product_prompt_tokens: input_tokens.len(),
            replayed_output_tokens: 0,
            request_origin: ExecutorRequestOrigin::Diagnostic,
        }
    }

    /// Construct admission for a product request whose execution context may
    /// include output tokens replayed after preemption.
    pub fn for_product_request(
        request_id: &'a RequestId,
        input_tokens: &'a [TokenId],
        maximum_sequence_tokens: usize,
        product_prompt_tokens: usize,
        replayed_output_tokens: usize,
    ) -> Result<Self> {
        let admission = Self {
            request_id,
            input_tokens,
            maximum_sequence_tokens,
            product_prompt_tokens,
            replayed_output_tokens,
            request_origin: ExecutorRequestOrigin::Product,
        };
        admission.validate()?;
        Ok(admission)
    }

    pub fn validate(&self) -> Result<()> {
        if self.input_tokens.is_empty() {
            return Err(FerrumError::request_validation(
                "executor prefill admission requires at least one execution-context token",
            ));
        }
        if self.product_prompt_tokens == 0 {
            return Err(FerrumError::request_validation(
                "executor prefill admission requires at least one product prompt token",
            ));
        }
        let execution_context_tokens = self
            .product_prompt_tokens
            .checked_add(self.replayed_output_tokens)
            .ok_or_else(|| {
                FerrumError::request_validation(
                    "executor prefill product token accounting exceeds usize",
                )
            })?;
        if execution_context_tokens != self.input_tokens.len() {
            return Err(FerrumError::request_validation(format!(
                "executor prefill execution context has {} tokens but product accounting declares {} prompt + {} replayed output",
                self.input_tokens.len(),
                self.product_prompt_tokens,
                self.replayed_output_tokens
            )));
        }
        if self.maximum_sequence_tokens < execution_context_tokens {
            return Err(FerrumError::request_validation(format!(
                "executor prefill sequence ceiling {} does not cover execution context {execution_context_tokens}",
                self.maximum_sequence_tokens
            )));
        }
        Ok(())
    }
}

#[cfg(test)]
mod executor_prefill_admission_tests {
    use super::{ExecutorPrefillAdmission, ExecutorRequestOrigin};
    use ferrum_types::{RequestId, TokenId};

    #[test]
    fn product_accounting_distinguishes_replayed_output_from_prompt() {
        let request_id = RequestId::new();
        let tokens = [1, 2, 3, 4, 5]
            .into_iter()
            .map(TokenId::new)
            .collect::<Vec<_>>();

        let admission =
            ExecutorPrefillAdmission::for_product_request(&request_id, &tokens, 8, 3, 2)
                .expect("recompute accounting must be accepted");

        assert_eq!(admission.product_prompt_tokens, 3);
        assert_eq!(admission.replayed_output_tokens, 2);
        assert_eq!(admission.request_origin, ExecutorRequestOrigin::Product);
        assert_eq!(
            ExecutorPrefillAdmission::for_startup(&request_id, &tokens, 8).request_origin,
            ExecutorRequestOrigin::Startup
        );
        assert_eq!(
            ExecutorPrefillAdmission::for_diagnostic(&request_id, &tokens, 8).request_origin,
            ExecutorRequestOrigin::Diagnostic
        );
        assert_eq!(ExecutorRequestOrigin::Product.namespace(), "product");
        assert_eq!(ExecutorRequestOrigin::Startup.namespace(), "startup");
        assert_eq!(ExecutorRequestOrigin::Diagnostic.namespace(), "diagnostic");
        assert_eq!(
            ExecutorRequestOrigin::from_namespaced_request_identity("request.product.123"),
            Some(ExecutorRequestOrigin::Product)
        );
        assert_eq!(
            ExecutorRequestOrigin::from_namespaced_request_identity("request.startup.123"),
            Some(ExecutorRequestOrigin::Startup)
        );
        assert_eq!(
            ExecutorRequestOrigin::from_namespaced_request_identity("request.diagnostic.123"),
            Some(ExecutorRequestOrigin::Diagnostic)
        );
        assert_eq!(
            ExecutorRequestOrigin::from_namespaced_request_identity("request.product."),
            None
        );
        assert_eq!(
            ExecutorRequestOrigin::from_namespaced_request_identity("request/external"),
            None
        );
    }

    #[test]
    fn product_accounting_rejects_context_drift_and_short_ceiling() {
        let request_id = RequestId::new();
        let tokens = [1, 2, 3].into_iter().map(TokenId::new).collect::<Vec<_>>();

        assert!(
            ExecutorPrefillAdmission::for_product_request(&request_id, &tokens, 3, 2, 0).is_err()
        );
        assert!(
            ExecutorPrefillAdmission::for_product_request(&request_id, &tokens, 2, 2, 1).is_err()
        );
    }
}

/// Scheduler-visible proof that an executor retained request and sequence
/// authority for future scheduler-owned prefill chunks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorPrefillAdmissionReceipt {
    pub request_id: RequestId,
}

/// Stable scheduler-facing projection of one plan-runtime capacity domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ExecutorAdmissionEpochs {
    pub coordinator_id: NonZeroU64,
    pub release_epoch: u64,
    pub capacity_epoch: u64,
}

impl ExecutorAdmissionEpochs {
    pub const fn new(coordinator_id: NonZeroU64, release_epoch: u64, capacity_epoch: u64) -> Self {
        Self {
            coordinator_id,
            release_epoch,
            capacity_epoch,
        }
    }

    pub fn from_capacity(epochs: crate::vnext::CapacityEpochs) -> Self {
        Self::new(
            NonZeroU64::new(epochs.coordinator_id().get())
                .expect("core-issued admission coordinator ids are non-zero"),
            epochs.release_epoch(),
            epochs.capacity_epoch(),
        )
    }
}

type ExecutorCapacityWaitFuture =
    Pin<Box<dyn Future<Output = Result<ExecutorAdmissionEpochs>> + Send + 'static>>;

/// Type-erased, single-use registration for one plan-runtime capacity wait.
///
/// Registration is created synchronously so the executor can subscribe before
/// the engine releases its iteration lock. Awaiting it never grants resources;
/// it only returns fresh epochs that permit another authoritative admission
/// probe.
#[must_use = "capacity wait registrations must be awaited or explicitly dropped"]
pub struct ExecutorCapacityWaitRegistration {
    future: ExecutorCapacityWaitFuture,
}

impl ExecutorCapacityWaitRegistration {
    pub fn new<F>(future: F) -> Self
    where
        F: Future<Output = Result<ExecutorAdmissionEpochs>> + Send + 'static,
    {
        Self {
            future: Box::pin(future),
        }
    }

    pub async fn wait_for_change(self) -> Result<ExecutorAdmissionEpochs> {
        self.future.await
    }
}

/// Pre-submit runtime stage that could not acquire its exact dynamic capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutorExecutionCapacityStage {
    SequenceExtension,
    StepAdmission,
    SubmissionWave,
}

/// One exact physical pool mutation completed while an executor was trying to
/// make an unsubmitted frontier runnable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorExecutionMaintenanceMutation {
    pool_id: crate::vnext::DynamicBackingPoolId,
    domain_id: crate::vnext::CapacityDomainId,
    chunk: crate::vnext::BackingChunkIdentity,
    chunk_bytes: u64,
    published_capacity_bytes: u64,
    capacity_epoch: u64,
}

impl ExecutorExecutionMaintenanceMutation {
    pub fn pool_id(&self) -> &crate::vnext::DynamicBackingPoolId {
        &self.pool_id
    }

    pub const fn domain_id(&self) -> crate::vnext::CapacityDomainId {
        self.domain_id
    }

    pub fn chunk(&self) -> &crate::vnext::BackingChunkIdentity {
        &self.chunk
    }

    pub const fn chunk_bytes(&self) -> u64 {
        self.chunk_bytes
    }

    pub const fn published_capacity_bytes(&self) -> u64 {
        self.published_capacity_bytes
    }

    pub const fn capacity_epoch(&self) -> u64 {
        self.capacity_epoch
    }
}

/// Typed proof that a bounded executor call committed relevant backing growth
/// before yielding the same logical frontier back to the scheduler.
///
/// This is deliberately stronger than observing a global capacity epoch. Every
/// mutation is reconstructed from a real growth receipt and bound back to the
/// pool's exact capacity domain. The scheduler may grant one fairness-bounded
/// retry only when this proof is present.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorExecutionMaintenanceProgress {
    attempts: u32,
    coordinator_id: NonZeroU64,
    mutations: Vec<ExecutorExecutionMaintenanceMutation>,
    latest_capacity_epoch: u64,
}

impl ExecutorExecutionMaintenanceProgress {
    pub fn from_growth_receipts(
        attempts: u32,
        observed: ExecutorAdmissionEpochs,
        receipts: &[crate::vnext::DynamicPoolGrowthBatchReceipt],
        pools: &[crate::vnext::DynamicPoolStatus],
    ) -> Result<Self> {
        if attempts == 0 || receipts.is_empty() || receipts.len() > attempts as usize {
            return Err(FerrumError::internal(
                "execution maintenance retry requires bounded, non-empty growth receipts",
            ));
        }

        let mut mutations = Vec::new();
        let mut previous_capacity_epoch = None;
        for receipt in receipts {
            if receipt.coordinator_id().get() != observed.coordinator_id.get() {
                return Err(FerrumError::internal(
                    "execution maintenance receipt belongs to another capacity coordinator",
                ));
            }
            if receipt.growths().is_empty()
                || previous_capacity_epoch
                    .is_some_and(|previous| receipt.capacity_epoch() <= previous)
            {
                return Err(FerrumError::internal(
                    "execution maintenance receipts contain no new ordered capacity mutation",
                ));
            }
            previous_capacity_epoch = Some(receipt.capacity_epoch());

            for growth in receipt.growths() {
                let pool = pools
                    .iter()
                    .find(|pool| pool.pool_id() == growth.pool_id())
                    .ok_or_else(|| {
                        FerrumError::internal(
                            "execution maintenance receipt references an unknown dynamic pool",
                        )
                    })?;
                if growth.chunk().pool_id() != growth.pool_id()
                    || growth.chunk_bytes() == 0
                    || growth.published_capacity_bytes() == 0
                    || growth.capacity_epoch() != receipt.capacity_epoch()
                {
                    return Err(FerrumError::internal(
                        "execution maintenance receipt contains an invalid pool mutation",
                    ));
                }
                if mutations
                    .iter()
                    .any(|mutation: &ExecutorExecutionMaintenanceMutation| {
                        mutation.pool_id() == growth.pool_id() && mutation.chunk() == growth.chunk()
                    })
                {
                    return Err(FerrumError::internal(
                        "execution maintenance receipts repeat one physical pool mutation",
                    ));
                }
                mutations.push(ExecutorExecutionMaintenanceMutation {
                    pool_id: growth.pool_id().clone(),
                    domain_id: pool.domain_id(),
                    chunk: growth.chunk().clone(),
                    chunk_bytes: growth.chunk_bytes(),
                    published_capacity_bytes: growth.published_capacity_bytes(),
                    capacity_epoch: growth.capacity_epoch(),
                });
            }
        }

        let latest_capacity_epoch = previous_capacity_epoch.expect("receipts are non-empty");
        if latest_capacity_epoch > observed.capacity_epoch {
            return Err(FerrumError::internal(
                "execution maintenance receipt is newer than the exported capacity observation",
            ));
        }
        mutations.sort_by(|left, right| {
            (
                left.capacity_epoch,
                left.pool_id.as_str(),
                left.chunk.ordinal(),
                left.chunk.generation(),
            )
                .cmp(&(
                    right.capacity_epoch,
                    right.pool_id.as_str(),
                    right.chunk.ordinal(),
                    right.chunk.generation(),
                ))
        });
        Ok(Self {
            attempts,
            coordinator_id: observed.coordinator_id,
            mutations,
            latest_capacity_epoch,
        })
    }

    pub const fn attempts(&self) -> u32 {
        self.attempts
    }

    pub const fn coordinator_id(&self) -> NonZeroU64 {
        self.coordinator_id
    }

    pub fn mutations(&self) -> &[ExecutorExecutionMaintenanceMutation] {
        &self.mutations
    }

    pub const fn latest_capacity_epoch(&self) -> u64 {
        self.latest_capacity_epoch
    }
}

/// Scheduler-consumable proof binding physical maintenance to the exact
/// logical frontiers whose unsubmitted execution attempt observed it.
///
/// Keeping the request scope inside the proof prevents a caller from attaching
/// one sequence's growth receipt to an unrelated decode cohort.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorExecutionMaintenanceRetry {
    affected_request_ids: Vec<RequestId>,
    progress: ExecutorExecutionMaintenanceProgress,
}

impl ExecutorExecutionMaintenanceRetry {
    fn new(
        affected_request_ids: Vec<RequestId>,
        progress: ExecutorExecutionMaintenanceProgress,
    ) -> Result<Self> {
        let unique = affected_request_ids.iter().collect::<HashSet<_>>();
        if affected_request_ids.is_empty() || unique.len() != affected_request_ids.len() {
            return Err(FerrumError::internal(
                "execution maintenance retry requires unique affected requests",
            ));
        }
        if progress.mutations().is_empty() {
            return Err(FerrumError::internal(
                "execution maintenance retry requires physical mutations",
            ));
        }
        Ok(Self {
            affected_request_ids,
            progress,
        })
    }

    pub fn affected_request_ids(&self) -> &[RequestId] {
        &self.affected_request_ids
    }

    pub const fn progress(&self) -> &ExecutorExecutionMaintenanceProgress {
        &self.progress
    }
}

/// Scheduler-visible proof that an execution attempt was not submitted and
/// must not be retried until one of its exact capacity sources changes.
///
/// This value owns no resource authority. The executor retains the committed
/// request/sequence authority and has already retired any unsubmitted step or
/// submission-wave authority before returning it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutorExecutionCapacityEvidenceOwner {
    Logical,
    Backing,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum ExecutorExecutionCapacityEvidenceKind {
    Logical {
        shortfalls: Vec<crate::vnext::CapacityShortfall>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pressure: Option<crate::vnext::DynamicBackingPressure>,
    },
    BackingDeferred {
        blockers: Vec<crate::vnext::DynamicBackingBlocker>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pressure: Option<crate::vnext::DynamicBackingPressure>,
    },
    BackingPressure {
        pressure: crate::vnext::DynamicBackingPressure,
    },
}

/// Exactly one typed owner for an execution-capacity deferral.
///
/// Its fields are private so callers cannot construct an empty or ambiguous
/// logical/backing evidence combination.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorExecutionCapacityEvidence {
    owner: ExecutorExecutionCapacityEvidenceOwner,
    #[serde(flatten)]
    kind: ExecutorExecutionCapacityEvidenceKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    maintenance_boundary: Option<crate::vnext::DynamicPoolMaintenanceBoundaryReceipt>,
}

impl ExecutorExecutionCapacityEvidence {
    fn logical(shortfalls: Vec<crate::vnext::CapacityShortfall>) -> Result<Self> {
        Self::logical_with_pressure(shortfalls, None)
    }

    fn logical_with_pressure(
        shortfalls: Vec<crate::vnext::CapacityShortfall>,
        pressure: Option<crate::vnext::DynamicBackingPressure>,
    ) -> Result<Self> {
        if shortfalls.is_empty() {
            return Err(FerrumError::internal(
                "logical execution deferral requires at least one shortfall",
            ));
        }
        Ok(Self {
            owner: ExecutorExecutionCapacityEvidenceOwner::Logical,
            kind: ExecutorExecutionCapacityEvidenceKind::Logical {
                shortfalls,
                pressure,
            },
            maintenance_boundary: None,
        })
    }

    fn backing_deferred(blockers: Vec<crate::vnext::DynamicBackingBlocker>) -> Result<Self> {
        Self::backing_deferred_with_pressure(blockers, None)
    }

    fn backing_deferred_with_pressure(
        blockers: Vec<crate::vnext::DynamicBackingBlocker>,
        pressure: Option<crate::vnext::DynamicBackingPressure>,
    ) -> Result<Self> {
        if blockers.is_empty() {
            return Err(FerrumError::internal(
                "physical execution deferral requires at least one backing blocker",
            ));
        }
        Ok(Self {
            owner: ExecutorExecutionCapacityEvidenceOwner::Backing,
            kind: ExecutorExecutionCapacityEvidenceKind::BackingDeferred { blockers, pressure },
            maintenance_boundary: None,
        })
    }

    fn direct_backing_pressure(pressure: crate::vnext::DynamicBackingPressure) -> Self {
        Self {
            owner: ExecutorExecutionCapacityEvidenceOwner::Backing,
            kind: ExecutorExecutionCapacityEvidenceKind::BackingPressure { pressure },
            maintenance_boundary: None,
        }
    }

    pub const fn owner(&self) -> ExecutorExecutionCapacityEvidenceOwner {
        self.owner
    }

    pub fn shortfalls(&self) -> &[crate::vnext::CapacityShortfall] {
        match &self.kind {
            ExecutorExecutionCapacityEvidenceKind::Logical { shortfalls, .. } => shortfalls,
            ExecutorExecutionCapacityEvidenceKind::BackingDeferred { .. }
            | ExecutorExecutionCapacityEvidenceKind::BackingPressure { .. } => &[],
        }
    }

    pub fn backing_blockers(&self) -> &[crate::vnext::DynamicBackingBlocker] {
        match &self.kind {
            ExecutorExecutionCapacityEvidenceKind::BackingDeferred { blockers, .. } => blockers,
            ExecutorExecutionCapacityEvidenceKind::Logical { .. }
            | ExecutorExecutionCapacityEvidenceKind::BackingPressure { .. } => &[],
        }
    }

    pub const fn backing_pressure(&self) -> Option<&crate::vnext::DynamicBackingPressure> {
        match &self.kind {
            ExecutorExecutionCapacityEvidenceKind::Logical { pressure, .. }
            | ExecutorExecutionCapacityEvidenceKind::BackingDeferred { pressure, .. } => {
                pressure.as_ref()
            }
            ExecutorExecutionCapacityEvidenceKind::BackingPressure { pressure } => Some(pressure),
        }
    }

    pub const fn maintenance_boundary(
        &self,
    ) -> Option<&crate::vnext::DynamicPoolMaintenanceBoundaryReceipt> {
        self.maintenance_boundary.as_ref()
    }

    fn with_maintenance_boundary(
        mut self,
        boundary: Option<crate::vnext::DynamicPoolMaintenanceBoundaryReceipt>,
    ) -> Result<Self> {
        match (self.backing_pressure(), boundary.as_ref()) {
            (
                Some(crate::vnext::DynamicBackingPressure::DeviceCapacity(pressure)),
                Some(boundary),
            ) if pressure == boundary.pressure() && !boundary.reclaim_sufficient() => {}
            (Some(crate::vnext::DynamicBackingPressure::PoolResident(_)), None) | (None, None) => {}
            (Some(crate::vnext::DynamicBackingPressure::DeviceCapacity(_)), None) => {
                return Err(FerrumError::internal(
                    "device-capacity execution maintenance lost its boundary receipt",
                ));
            }
            _ => {
                return Err(FerrumError::internal(
                    "execution maintenance boundary differs from its blocked pressure",
                ));
            }
        }
        self.maintenance_boundary = boundary;
        Ok(self)
    }

    fn has_relevant_mutation(&self, mutation: &ExecutorExecutionMaintenanceMutation) -> bool {
        let logical_matches = |shortfalls: &[crate::vnext::CapacityShortfall]| {
            shortfalls.iter().any(|shortfall| {
                shortfall.kind() == crate::vnext::CapacityShortfallKind::BackingGrowthRequired
                    && shortfall.domain() == Some(mutation.domain_id())
            })
        };
        let backing_matches = |blockers: &[crate::vnext::DynamicBackingBlocker]| {
            blockers.iter().any(|blocker| {
                blocker.pool_id() == mutation.pool_id()
                    && blocker.domain_id() == mutation.domain_id()
            })
        };
        match &self.kind {
            ExecutorExecutionCapacityEvidenceKind::Logical { shortfalls, .. } => {
                logical_matches(shortfalls)
            }
            ExecutorExecutionCapacityEvidenceKind::BackingDeferred { blockers, .. } => {
                backing_matches(blockers)
            }
            ExecutorExecutionCapacityEvidenceKind::BackingPressure { .. } => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorExecutionCapacityDeferral {
    observed: ExecutorAdmissionEpochs,
    wait_condition: crate::vnext::CapacityWaitCondition,
    stage: ExecutorExecutionCapacityStage,
    evidence: ExecutorExecutionCapacityEvidence,
    #[serde(skip_serializing_if = "Option::is_none")]
    maintenance_retry: Option<ExecutorExecutionMaintenanceRetry>,
}

impl ExecutorExecutionCapacityDeferral {
    fn with_evidence(
        observed: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        stage: ExecutorExecutionCapacityStage,
        evidence: ExecutorExecutionCapacityEvidence,
    ) -> Result<Self> {
        if wait_condition.coordinator_id().get() != observed.coordinator_id.get() {
            return Err(ferrum_types::FerrumError::request_validation(
                "executor execution deferral belongs to a different capacity coordinator",
            ));
        }
        Ok(Self {
            observed,
            wait_condition,
            stage,
            evidence,
            maintenance_retry: None,
        })
    }

    /// Construct a physical deferral for an executor that observes device or
    /// pool pressure directly rather than through Ferrum's backing allocator.
    pub fn from_backing_pressure(
        observed: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        pressure: crate::vnext::DynamicBackingPressure,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        Self::with_evidence(
            observed,
            wait_condition,
            stage,
            ExecutorExecutionCapacityEvidence::direct_backing_pressure(pressure),
        )
    }

    pub fn from_admission(
        deferred: &crate::vnext::AdmissionDeferred,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        if deferred.action() != crate::vnext::DeferredAction::WaitForRelease {
            return Err(ferrum_types::FerrumError::internal(
                "execution capacity deferral must be reduced to WaitForRelease before export",
            ));
        }
        let evidence = ExecutorExecutionCapacityEvidence::logical(deferred.blockers().to_vec())?;
        Self::with_evidence(
            ExecutorAdmissionEpochs::from_capacity(deferred.epochs()),
            deferred.wait_condition().clone(),
            stage,
            evidence,
        )
    }

    /// Export an unresolved logical backing-growth decision after the
    /// executor's bounded in-call maintenance attempts are exhausted.
    ///
    /// This remains a pre-submit scheduling deferral. The bound controls only
    /// how much allocator maintenance one executor call may perform; it must
    /// not turn temporary capacity pressure into a terminal request failure.
    pub fn from_pending_maintenance(
        deferred: &crate::vnext::AdmissionDeferred,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        if deferred.action() != crate::vnext::DeferredAction::AwaitBackingGrowth {
            return Err(ferrum_types::FerrumError::internal(
                "pending execution maintenance must await backing growth",
            ));
        }
        let evidence = ExecutorExecutionCapacityEvidence::logical(deferred.blockers().to_vec())?;
        Self::with_evidence(
            ExecutorAdmissionEpochs::from_capacity(deferred.epochs()),
            deferred.wait_condition().clone(),
            stage,
            evidence,
        )
    }

    /// Export unresolved physical backing pressure without discarding its
    /// exact pool/domain evidence.
    pub fn from_backing(
        deferred: &crate::vnext::DynamicBackingDeferred,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        let evidence =
            ExecutorExecutionCapacityEvidence::backing_deferred(deferred.blockers().to_vec())?;
        Self::with_evidence(
            ExecutorAdmissionEpochs::from_capacity(deferred.epochs()),
            deferred.wait_condition().clone(),
            stage,
            evidence,
        )
    }

    /// Attach a scheduler retry only when this call produced at least one real
    /// physical mutation relevant to the final blocker. An empty or unrelated
    /// receipt set is an ordinary typed wait, not an internal error.
    pub fn with_relevant_maintenance_retry(
        mut self,
        attempts: u32,
        receipts: &[crate::vnext::DynamicPoolGrowthBatchReceipt],
        pools: &[crate::vnext::DynamicPoolStatus],
        affected_request_ids: Vec<RequestId>,
    ) -> Result<Self> {
        if receipts.is_empty() {
            return Ok(self);
        }
        let progress = ExecutorExecutionMaintenanceProgress::from_growth_receipts(
            attempts,
            self.observed,
            receipts,
            pools,
        )?;
        if progress.coordinator_id() != self.observed.coordinator_id
            || progress.latest_capacity_epoch() > self.observed.capacity_epoch
            || progress.mutations().is_empty()
        {
            return Err(FerrumError::internal(
                "execution maintenance progress does not match the exported deferral",
            ));
        }
        let relevant_mutation = progress
            .mutations()
            .iter()
            .any(|mutation| self.evidence.has_relevant_mutation(mutation));
        if !relevant_mutation {
            return Ok(self);
        }
        let retry = ExecutorExecutionMaintenanceRetry::new(affected_request_ids, progress)?;
        if self.stage == ExecutorExecutionCapacityStage::SequenceExtension
            && retry.affected_request_ids().len() != 1
        {
            return Err(FerrumError::internal(
                "sequence-extension maintenance retry must affect exactly one request",
            ));
        }
        self.maintenance_retry = Some(retry);
        Ok(self)
    }

    pub fn from_admission_maintenance(
        source: &crate::vnext::AdmissionDeferred,
        observed: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        pressure: crate::vnext::DynamicBackingPressure,
        maintenance_boundary: Option<crate::vnext::DynamicPoolMaintenanceBoundaryReceipt>,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        if source.action() != crate::vnext::DeferredAction::AwaitBackingGrowth {
            return Err(ferrum_types::FerrumError::internal(
                "execution maintenance source must await backing growth",
            ));
        }
        let evidence = ExecutorExecutionCapacityEvidence::logical_with_pressure(
            source.blockers().to_vec(),
            Some(pressure),
        )?
        .with_maintenance_boundary(maintenance_boundary)?;
        if evidence.maintenance_boundary().is_some_and(|boundary| {
            boundary.coordinator_id().get() != observed.coordinator_id.get()
        }) {
            return Err(FerrumError::internal(
                "execution maintenance boundary belongs to another coordinator",
            ));
        }
        Self::with_evidence(observed, wait_condition, stage, evidence)
    }

    pub fn from_backing_maintenance(
        source: &crate::vnext::DynamicBackingDeferred,
        observed: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        pressure: crate::vnext::DynamicBackingPressure,
        maintenance_boundary: Option<crate::vnext::DynamicPoolMaintenanceBoundaryReceipt>,
        stage: ExecutorExecutionCapacityStage,
    ) -> Result<Self> {
        let evidence = ExecutorExecutionCapacityEvidence::backing_deferred_with_pressure(
            source.blockers().to_vec(),
            Some(pressure),
        )?
        .with_maintenance_boundary(maintenance_boundary)?;
        if evidence.maintenance_boundary().is_some_and(|boundary| {
            boundary.coordinator_id().get() != observed.coordinator_id.get()
        }) {
            return Err(FerrumError::internal(
                "execution maintenance boundary belongs to another coordinator",
            ));
        }
        Self::with_evidence(observed, wait_condition, stage, evidence)
    }

    pub const fn observed(&self) -> ExecutorAdmissionEpochs {
        self.observed
    }

    pub fn wait_condition(&self) -> &crate::vnext::CapacityWaitCondition {
        &self.wait_condition
    }

    pub const fn stage(&self) -> ExecutorExecutionCapacityStage {
        self.stage
    }

    pub const fn evidence(&self) -> &ExecutorExecutionCapacityEvidence {
        &self.evidence
    }

    pub fn shortfalls(&self) -> &[crate::vnext::CapacityShortfall] {
        self.evidence.shortfalls()
    }

    pub fn backing_blockers(&self) -> &[crate::vnext::DynamicBackingBlocker] {
        self.evidence.backing_blockers()
    }

    pub const fn backing_pressure(&self) -> Option<&crate::vnext::DynamicBackingPressure> {
        self.evidence.backing_pressure()
    }

    pub const fn maintenance_boundary(
        &self,
    ) -> Option<&crate::vnext::DynamicPoolMaintenanceBoundaryReceipt> {
        self.evidence.maintenance_boundary()
    }

    pub fn maintenance_retry(&self) -> Option<&ExecutorExecutionMaintenanceRetry> {
        self.maintenance_retry.as_ref()
    }

    /// Validate the bound retry scope against the authoritative logical
    /// frontiers in the current engine call.
    pub fn validated_maintenance_retry_scope(
        &self,
        current_request_ids: &[RequestId],
    ) -> Result<Option<&ExecutorExecutionMaintenanceRetry>> {
        let Some(retry) = self.maintenance_retry.as_ref() else {
            return Ok(None);
        };
        let current = current_request_ids.iter().collect::<HashSet<_>>();
        if current_request_ids.is_empty() || current.len() != current_request_ids.len() {
            return Err(FerrumError::internal(
                "execution maintenance retry received an invalid current request cohort",
            ));
        }
        let affected = retry.affected_request_ids().iter().collect::<HashSet<_>>();
        if !affected.is_subset(&current) {
            return Err(FerrumError::internal(
                "execution maintenance retry affects a request outside the current cohort",
            ));
        }
        match self.stage {
            ExecutorExecutionCapacityStage::SequenceExtension => {
                if affected.len() != 1 {
                    return Err(FerrumError::internal(
                        "sequence-extension maintenance retry must affect one current request",
                    ));
                }
            }
            ExecutorExecutionCapacityStage::StepAdmission
            | ExecutorExecutionCapacityStage::SubmissionWave => {
                if affected != current {
                    return Err(FerrumError::internal(
                        "cohort maintenance retry must cover the complete current cohort",
                    ));
                }
            }
        }
        Ok(Some(retry))
    }

    /// Return a strictly smaller, capacity-informed prefill width.
    ///
    /// This is a cold pressure-path hint, not allocator authority. The caller
    /// must probe the returned prefix through normal typed admission before any
    /// provider encode or device submission. A bounded reduction prevents a
    /// large frontier from producing an unbounded sequence of near-identical
    /// probes when the shortfall is small.
    pub fn narrower_prefill_tokens(&self, attempted_tokens: usize) -> Option<usize> {
        if attempted_tokens <= 1 {
            return None;
        }
        let maximum_next = attempted_tokens
            .saturating_sub(attempted_tokens.div_ceil(4))
            .max(1);
        let proportional = self
            .shortfalls()
            .iter()
            .filter_map(|shortfall| {
                let requested = shortfall.requested().get();
                let available = shortfall.available().get();
                (requested > available).then(|| {
                    let scaled = (attempted_tokens as u128).saturating_mul(available as u128)
                        / requested as u128;
                    usize::try_from(scaled)
                        .unwrap_or(usize::MAX)
                        .clamp(1, attempted_tokens - 1)
                })
            })
            .min();
        Some(
            proportional
                .unwrap_or_else(|| attempted_tokens.div_ceil(2))
                .min(maximum_next)
                .max(1),
        )
    }
}

/// Scheduler-visible proof that execution is temporarily blocked by a
/// Request-lifetime state hazard rather than by physical capacity.
///
/// The embedded hazard evidence retains the exact plan-local coordinator and
/// supports subscribe-before-recheck waiter registration. The request cohort
/// is the product identity projection used by the scheduler; it must stay
/// separate from the allocator's internal request-authority ids.
#[derive(Debug, Clone, Serialize)]
pub struct ExecutorRequestStateDeferral {
    stage: ExecutorExecutionCapacityStage,
    request_ids: Vec<RequestId>,
    hazard: crate::vnext::RequestStateHazardDeferral,
}

impl ExecutorRequestStateDeferral {
    pub fn new(
        stage: ExecutorExecutionCapacityStage,
        request_ids: Vec<RequestId>,
        hazard: crate::vnext::RequestStateHazardDeferral,
    ) -> Result<Self> {
        let unique = request_ids.iter().collect::<HashSet<_>>();
        if request_ids.is_empty() || unique.len() != request_ids.len() {
            return Err(FerrumError::internal(
                "request-state execution deferral requires a non-empty unique product cohort",
            ));
        }
        if hazard.blockers().is_empty() {
            return Err(FerrumError::internal(
                "request-state execution deferral requires exact blockers",
            ));
        }
        Ok(Self {
            stage,
            request_ids,
            hazard,
        })
    }

    pub const fn stage(&self) -> ExecutorExecutionCapacityStage {
        self.stage
    }

    pub fn request_ids(&self) -> &[RequestId] {
        &self.request_ids
    }

    pub const fn hazard(&self) -> &crate::vnext::RequestStateHazardDeferral {
        &self.hazard
    }

    pub fn register_waiter(&self) -> Result<crate::vnext::RequestStateHazardWaitRegistration> {
        self.hazard
            .register_waiter()
            .map_err(|error| FerrumError::backend(error.to_string()))
    }
}

/// A pre-submit execution frontier can be blocked by independently evolving
/// sources. Capacity waits participate in scheduler pressure/yield policy;
/// Request-state waits never do and resume only from their exact hazard
/// coordinator.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "reason", content = "evidence", rename_all = "snake_case")]
pub enum ExecutorExecutionDeferral {
    Capacity(ExecutorExecutionCapacityDeferral),
    RequestState(ExecutorRequestStateDeferral),
}

impl ExecutorExecutionDeferral {
    pub const fn stage(&self) -> ExecutorExecutionCapacityStage {
        match self {
            Self::Capacity(deferral) => deferral.stage(),
            Self::RequestState(deferral) => deferral.stage(),
        }
    }

    pub const fn as_capacity(&self) -> Option<&ExecutorExecutionCapacityDeferral> {
        match self {
            Self::Capacity(deferral) => Some(deferral),
            Self::RequestState(_) => None,
        }
    }

    pub const fn as_request_state(&self) -> Option<&ExecutorRequestStateDeferral> {
        match self {
            Self::Capacity(_) => None,
            Self::RequestState(deferral) => Some(deferral),
        }
    }
}

impl From<ExecutorExecutionCapacityDeferral> for ExecutorExecutionDeferral {
    fn from(deferral: ExecutorExecutionCapacityDeferral) -> Self {
        Self::Capacity(deferral)
    }
}

impl From<ExecutorRequestStateDeferral> for ExecutorExecutionDeferral {
    fn from(deferral: ExecutorRequestStateDeferral) -> Self {
        Self::RequestState(deferral)
    }
}

#[cfg(test)]
mod execution_capacity_deferral_tests {
    use super::{
        ExecutorAdmissionEpochs, ExecutorExecutionCapacityDeferral,
        ExecutorExecutionCapacityEvidenceOwner, ExecutorExecutionCapacityStage,
        ExecutorExecutionMaintenanceProgress, ExecutorExecutionMaintenanceRetry,
    };
    use crate::vnext::{
        CapacityAvailabilityEpoch, CapacityAvailabilitySource, CapacityWaitCondition,
        DeviceCapacityPressure, DeviceCapacityPressureScope, DynamicBackingPressure,
    };
    use ferrum_types::RequestId;
    use std::num::NonZeroU64;

    fn test_progress() -> ExecutorExecutionMaintenanceProgress {
        ExecutorExecutionMaintenanceProgress {
            attempts: 1,
            coordinator_id: NonZeroU64::new(19).unwrap(),
            mutations: Vec::new(),
            latest_capacity_epoch: 5,
        }
    }

    fn test_deferral(stage: ExecutorExecutionCapacityStage) -> ExecutorExecutionCapacityDeferral {
        let observed =
            CapacityAvailabilityEpoch::new(CapacityAvailabilitySource::ActiveSequenceSlots, 7)
                .unwrap();
        let condition = CapacityWaitCondition::from_observation(19, vec![observed]).unwrap();
        ExecutorExecutionCapacityDeferral::from_backing_pressure(
            ExecutorAdmissionEpochs::new(NonZeroU64::new(19).unwrap(), 3, 5),
            condition,
            test_pressure(),
            stage,
        )
        .unwrap()
    }

    fn test_pressure() -> DynamicBackingPressure {
        DeviceCapacityPressure::new(
            DeviceCapacityPressureScope::PlanBudget,
            "device.execution-capacity-test".to_owned(),
            1,
            1,
            1,
            1,
            1,
        )
        .unwrap()
        .into()
    }

    #[test]
    fn prefill_narrowing_is_strict_bounded_and_stops_at_one_token() {
        let observed =
            CapacityAvailabilityEpoch::new(CapacityAvailabilitySource::ActiveSequenceSlots, 7)
                .unwrap();
        let condition = CapacityWaitCondition::from_observation(19, vec![observed]).unwrap();
        let deferred = ExecutorExecutionCapacityDeferral::from_backing_pressure(
            ExecutorAdmissionEpochs::new(NonZeroU64::new(19).unwrap(), 3, 5),
            condition,
            test_pressure(),
            ExecutorExecutionCapacityStage::StepAdmission,
        )
        .unwrap();

        assert_eq!(deferred.narrower_prefill_tokens(342), Some(171));
        assert_eq!(deferred.narrower_prefill_tokens(2), Some(1));
        assert_eq!(deferred.narrower_prefill_tokens(1), None);
    }

    #[test]
    fn backing_pressure_serializes_one_typed_evidence_owner() {
        let deferred = test_deferral(ExecutorExecutionCapacityStage::SequenceExtension);
        let serialized = serde_json::to_value(&deferred).unwrap();

        assert_eq!(
            deferred.evidence().owner(),
            ExecutorExecutionCapacityEvidenceOwner::Backing
        );
        assert!(deferred.shortfalls().is_empty());
        assert!(deferred.backing_blockers().is_empty());
        assert!(deferred.backing_pressure().is_some());
        assert_eq!(serialized["evidence"]["owner"], "backing");
        assert_eq!(serialized["evidence"]["kind"], "backing_pressure");
        assert!(serialized["evidence"]["pressure"].is_object());
    }

    #[test]
    fn empty_maintenance_receipts_remain_an_ordinary_typed_deferral() {
        let request_id = RequestId::new();
        let deferred = test_deferral(ExecutorExecutionCapacityStage::SequenceExtension)
            .with_relevant_maintenance_retry(2, &[], &[], vec![request_id])
            .unwrap();

        assert!(deferred.maintenance_retry().is_none());
    }

    #[test]
    fn maintenance_retry_rejects_empty_duplicate_or_unproven_scope() {
        let request_id = RequestId::new();
        assert!(ExecutorExecutionMaintenanceRetry::new(Vec::new(), test_progress()).is_err());
        assert!(ExecutorExecutionMaintenanceRetry::new(
            vec![request_id.clone(), request_id.clone()],
            test_progress(),
        )
        .is_err());
        assert!(ExecutorExecutionMaintenanceRetry::new(vec![request_id], test_progress()).is_err());
    }

    #[test]
    fn maintenance_retry_scope_is_fail_closed_for_sequence_and_cohort_stages() {
        let first = RequestId::new();
        let second = RequestId::new();
        let retry = |affected_request_ids| ExecutorExecutionMaintenanceRetry {
            affected_request_ids,
            progress: test_progress(),
        };

        let mut sequence = test_deferral(ExecutorExecutionCapacityStage::SequenceExtension);
        sequence.maintenance_retry = Some(retry(vec![second.clone()]));
        assert_eq!(
            sequence
                .validated_maintenance_retry_scope(&[first.clone(), second.clone()])
                .unwrap()
                .unwrap()
                .affected_request_ids(),
            [second.clone()]
        );
        sequence.maintenance_retry = Some(retry(vec![first.clone(), second.clone()]));
        assert!(sequence
            .validated_maintenance_retry_scope(&[first.clone(), second.clone()])
            .is_err());

        let mut cohort = test_deferral(ExecutorExecutionCapacityStage::SubmissionWave);
        cohort.maintenance_retry = Some(retry(vec![second.clone()]));
        assert!(cohort
            .validated_maintenance_retry_scope(&[first.clone(), second.clone()])
            .is_err());
        cohort.maintenance_retry = Some(retry(vec![first.clone(), second.clone()]));
        assert!(cohort
            .validated_maintenance_retry_scope(&[first, second])
            .unwrap()
            .is_some());
    }
}

/// Capacity-aware batch decode result.
///
/// `Deferred` is only legal before provider encode or device submission. All
/// possibly-submitted failures remain ordinary errors and retain their typed
/// fence/recovery authority inside the executor.
pub enum ExecutorBatchDecodeOutcome {
    Completed(Vec<DecodeOutput>),
    Deferred(ExecutorExecutionDeferral),
}

/// Capacity-aware, tensor-free batch decode result for a plan runtime.
pub enum PlanRuntimeBatchDecodeOutcome {
    Completed(Vec<PlanRuntimeDecodeOutput>),
    Deferred(ExecutorExecutionDeferral),
}

/// Capacity-aware result for one tensor-free plan-runtime prefill frontier.
pub struct PlanRuntimePrefillCompletion {
    output: PlanRuntimePrefillOutput,
    planned_chunk: PrefillChunk,
    completed_chunk: PrefillChunk,
    capacity_probe_count: u32,
}

impl PlanRuntimePrefillCompletion {
    pub fn new(
        output: PlanRuntimePrefillOutput,
        planned_chunk: PrefillChunk,
        completed_chunk: PrefillChunk,
        capacity_probe_count: u32,
    ) -> Result<Self> {
        validate_prefill_completion_shape(planned_chunk, completed_chunk, capacity_probe_count)?;
        Ok(Self {
            output,
            planned_chunk,
            completed_chunk,
            capacity_probe_count,
        })
    }

    pub fn exact(output: PlanRuntimePrefillOutput, chunk: PrefillChunk) -> Self {
        Self {
            output,
            planned_chunk: chunk,
            completed_chunk: chunk,
            capacity_probe_count: 0,
        }
    }

    pub const fn planned_chunk(&self) -> PrefillChunk {
        self.planned_chunk
    }

    pub const fn completed_chunk(&self) -> PrefillChunk {
        self.completed_chunk
    }

    pub const fn capacity_probe_count(&self) -> u32 {
        self.capacity_probe_count
    }

    pub fn output(&self) -> &PlanRuntimePrefillOutput {
        &self.output
    }

    pub fn validate_for(
        &self,
        expected_request_id: &RequestId,
        expected_planned_chunk: PrefillChunk,
        vocabulary_size: usize,
    ) -> Result<()> {
        if self.planned_chunk != expected_planned_chunk {
            return Err(FerrumError::backend(format!(
                "plan runtime completed prefill frontier {:?}, expected {:?}",
                self.planned_chunk.range(),
                expected_planned_chunk.range()
            )));
        }
        validate_prefill_completion_shape(
            self.planned_chunk,
            self.completed_chunk,
            self.capacity_probe_count,
        )?;
        self.output.validate_for_completion(
            expected_request_id,
            self.completed_chunk,
            vocabulary_size,
        )
    }

    pub fn into_parts(self) -> (PlanRuntimePrefillOutput, PrefillChunk, PrefillChunk, u32) {
        (
            self.output,
            self.planned_chunk,
            self.completed_chunk,
            self.capacity_probe_count,
        )
    }
}

pub enum PlanRuntimePrefillOutcome {
    Completed(PlanRuntimePrefillCompletion),
    Deferred(ExecutorExecutionDeferral),
}

pub enum PlanRuntimeBatchPrefillOutcome {
    Completed(Vec<PlanRuntimePrefillCompletion>),
    NotSubmitted(ExecutorExecutionDeferral),
    Unsupported,
}

/// Capacity-aware result for one planned prefill frontier.
///
/// `Deferred` is only legal before provider encode or device submission. The
/// executor may complete a strict prefix after typed capacity probes; the
/// scheduler commits only that prefix and learns the narrower execution ceiling.
pub struct ExecutorPrefillCompletion {
    output: PrefillOutput,
    planned_chunk: PrefillChunk,
    completed_chunk: PrefillChunk,
    capacity_probe_count: u32,
}

impl ExecutorPrefillCompletion {
    pub fn new(
        output: PrefillOutput,
        planned_chunk: PrefillChunk,
        completed_chunk: PrefillChunk,
        capacity_probe_count: u32,
    ) -> Result<Self> {
        validate_prefill_completion_shape(planned_chunk, completed_chunk, capacity_probe_count)?;
        Ok(Self {
            output,
            planned_chunk,
            completed_chunk,
            capacity_probe_count,
        })
    }

    pub fn exact(output: PrefillOutput, chunk: PrefillChunk) -> Self {
        Self {
            output,
            planned_chunk: chunk,
            completed_chunk: chunk,
            capacity_probe_count: 0,
        }
    }

    pub const fn planned_chunk(&self) -> PrefillChunk {
        self.planned_chunk
    }

    pub const fn completed_chunk(&self) -> PrefillChunk {
        self.completed_chunk
    }

    pub const fn capacity_probe_count(&self) -> u32 {
        self.capacity_probe_count
    }

    pub fn into_parts(self) -> (PrefillOutput, PrefillChunk, PrefillChunk, u32) {
        (
            self.output,
            self.planned_chunk,
            self.completed_chunk,
            self.capacity_probe_count,
        )
    }
}

fn validate_prefill_completion_shape(
    planned_chunk: PrefillChunk,
    completed_chunk: PrefillChunk,
    capacity_probe_count: u32,
) -> Result<()> {
    if completed_chunk.tokens_processed() != planned_chunk.tokens_processed()
        || completed_chunk.total_prompt_tokens() != planned_chunk.total_prompt_tokens()
        || completed_chunk.tokens_to_process() > planned_chunk.tokens_to_process()
    {
        return Err(ferrum_types::FerrumError::internal(
            "completed prefill chunk is not a non-empty prefix of its planned chunk",
        ));
    }
    if completed_chunk != planned_chunk && capacity_probe_count == 0 {
        return Err(ferrum_types::FerrumError::internal(
            "partial prefill completion requires a failed capacity probe",
        ));
    }
    Ok(())
}

pub enum ExecutorPrefillOutcome {
    Completed(ExecutorPrefillCompletion),
    Deferred(ExecutorExecutionDeferral),
}

/// Transactional result of attempting one physical prefill batch.
///
/// `NotSubmitted` proves that no participant in the batch reached provider
/// encode or device submission. The caller may therefore retry a narrower
/// partition or the existing per-request capacity path without duplicating
/// model work. `Unsupported` keeps the optimization optional for legacy
/// executors while plan-runtime implementations provide the real batch edge.
pub enum ExecutorBatchPrefillOutcome {
    Completed(Vec<ExecutorPrefillCompletion>),
    NotSubmitted(ExecutorExecutionDeferral),
    Unsupported,
}

/// Stage that must advance before a plan-runtime prefill can be admitted.
///
/// This is scheduler evidence, not allocator authority. The executor retains
/// the sealed logical or physical deferral that authorizes maintenance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutorPrefillMaintenanceStage {
    LogicalCapacity,
    PhysicalBacking,
}

/// Scheduler-visible reason that a prefill needs plan-runtime backing
/// maintenance. These values are projections only and cannot allocate memory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum ExecutorPrefillMaintenanceBlocker {
    Capacity {
        domain_id: Option<u32>,
        kind: crate::vnext::CapacityShortfallKind,
        requested: u64,
        available: u64,
        current_total: u64,
        maximum_total: u64,
    },
    Backing {
        pool_id: String,
        domain_id: u32,
        lifetime: crate::vnext::DynamicBackingClaimScope,
        reason: crate::vnext::DynamicBackingDeferralReason,
        requested_bytes: u64,
        free_bytes: u64,
        largest_contiguous_bytes: u64,
    },
}

/// Non-authoritative projection of plan-runtime maintenance work.
///
/// The request id is the only handle returned to the engine. Implementations
/// must retain the sealed deferral internally and validate it again when
/// [`ModelExecutor::maintain_prefill_backing`] is called.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExecutorPrefillMaintenanceDeferral {
    request_id: RequestId,
    observed: ExecutorAdmissionEpochs,
    wait_condition: crate::vnext::CapacityWaitCondition,
    stage: ExecutorPrefillMaintenanceStage,
    blockers: Vec<ExecutorPrefillMaintenanceBlocker>,
}

impl ExecutorPrefillMaintenanceDeferral {
    pub fn new(
        request_id: RequestId,
        observed: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        stage: ExecutorPrefillMaintenanceStage,
        blockers: Vec<ExecutorPrefillMaintenanceBlocker>,
    ) -> Result<Self> {
        if blockers.is_empty() {
            return Err(ferrum_types::FerrumError::request_validation(
                "executor prefill maintenance deferral requires at least one blocker",
            ));
        }
        if wait_condition.coordinator_id().get() != observed.coordinator_id.get() {
            return Err(ferrum_types::FerrumError::request_validation(
                "executor prefill maintenance wait condition belongs to a different coordinator",
            ));
        }
        Ok(Self {
            request_id,
            observed,
            wait_condition,
            stage,
            blockers,
        })
    }

    pub fn from_admission(
        request_id: &RequestId,
        deferred: &crate::vnext::AdmissionDeferred,
    ) -> Result<Self> {
        if deferred.action() != crate::vnext::DeferredAction::AwaitBackingGrowth {
            return Err(ferrum_types::FerrumError::internal(
                "logical prefill maintenance projection requires AwaitBackingGrowth",
            ));
        }
        let blockers = deferred
            .blockers()
            .iter()
            .map(|blocker| ExecutorPrefillMaintenanceBlocker::Capacity {
                domain_id: blocker.domain().map(|domain| domain.get()),
                kind: blocker.kind(),
                requested: blocker.requested().get(),
                available: blocker.available().get(),
                current_total: blocker.current_total().get(),
                maximum_total: blocker.maximum_total().get(),
            })
            .collect();
        Self::new(
            request_id.clone(),
            ExecutorAdmissionEpochs::from_capacity(deferred.epochs()),
            deferred.wait_condition().clone(),
            ExecutorPrefillMaintenanceStage::LogicalCapacity,
            blockers,
        )
    }

    pub fn from_backing(
        request_id: &RequestId,
        deferred: &crate::vnext::DynamicBackingDeferred,
    ) -> Result<Self> {
        let blockers = deferred
            .blockers()
            .iter()
            .map(|blocker| ExecutorPrefillMaintenanceBlocker::Backing {
                pool_id: blocker.pool_id().as_str().to_string(),
                domain_id: blocker.domain_id().get(),
                lifetime: deferred.scope(),
                reason: blocker.reason(),
                requested_bytes: blocker.requested_bytes(),
                free_bytes: blocker.free_bytes(),
                largest_contiguous_bytes: blocker.largest_contiguous_bytes(),
            })
            .collect();
        Self::new(
            request_id.clone(),
            ExecutorAdmissionEpochs::from_capacity(deferred.epochs()),
            deferred.wait_condition().clone(),
            ExecutorPrefillMaintenanceStage::PhysicalBacking,
            blockers,
        )
    }

    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    pub const fn observed(&self) -> ExecutorAdmissionEpochs {
        self.observed
    }

    pub fn wait_condition(&self) -> &crate::vnext::CapacityWaitCondition {
        &self.wait_condition
    }

    pub const fn stage(&self) -> ExecutorPrefillMaintenanceStage {
        self.stage
    }

    pub fn blockers(&self) -> &[ExecutorPrefillMaintenanceBlocker] {
        &self.blockers
    }
}

/// Result of one bounded plan-runtime backing maintenance attempt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum ExecutorPrefillMaintenanceOutcome {
    /// Cancellation won the race before the maintenance task consumed the
    /// retained deferral.
    NoLongerPending,
    /// The physical allocator changed while maintenance was installing its
    /// wait predicate. The scheduler must clear the old backing deferral and
    /// perform one authoritative admission probe, even if publication of the
    /// corresponding capacity epoch is still in flight.
    RetryAdmission { current: ExecutorAdmissionEpochs },
    /// The requested backing is valid but cannot be installed while current
    /// device claims remain live. The scheduler must wait for release evidence
    /// rather than completing the request as an error.
    WaitForRelease {
        current: ExecutorAdmissionEpochs,
        wait_condition: crate::vnext::CapacityWaitCondition,
        pressure: crate::vnext::DynamicBackingPressure,
    },
    /// The executor installed real backing and published the resulting
    /// capacity epoch.
    Maintained {
        current: ExecutorAdmissionEpochs,
        pools_grown: usize,
        allocated_bytes: u64,
        pools_reclaimed: usize,
        chunks_reclaimed: usize,
        reclaimed_bytes: u64,
        /// Exact allocator-issued rebalance receipt. The aggregate counters
        /// above remain for stable metrics and must reconcile with this value.
        rebalance: Option<crate::vnext::DynamicPoolRebalanceReceipt>,
    },
}

/// Typed result of probing plan-runtime prefill capacity.
///
/// `Deferred` and `MaintenanceDeferred` preserve the capacity domains and
/// epochs required by the plan-local dynamic admission queue. They must never
/// be flattened into a generic resource error at the scheduler boundary.
#[derive(Debug, Clone)]
pub enum ExecutorPrefillAdmissionDecision {
    Admitted(ExecutorPrefillAdmissionReceipt),
    Deferred(crate::vnext::AdmissionDeferred),
    MaintenanceDeferred(ExecutorPrefillMaintenanceDeferral),
    PermanentRejected(crate::vnext::AdmissionRejected),
}

/// Core model executor trait focusing on tensor operations
#[async_trait]
pub trait ModelExecutor: Send + Sync {
    /// Get model information and metadata
    fn info(&self) -> &ModelInfo;

    /// Selects the single authority for request-lifetime model resources.
    /// Existing executors remain on the transitional legacy-engine path by
    /// default. A runtime that returns `PlanRuntime` must return the shared
    /// runtime's opaque cache handle from prefill/decode and delegate release
    /// of that authority from `release_cache`.
    fn execution_resource_authority(&self) -> ExecutionResourceAuthority {
        ExecutionResourceAuthority::LegacyEngine
    }

    /// Immutable admission limits compiled into this executor's runtime plan.
    /// A PlanRuntime executor must return `Some`; legacy executors may defer to
    /// the engine-owned scheduler and recurrent-state limits.
    fn admission_limits(&self) -> Result<Option<ExecutorAdmissionLimits>> {
        Ok(None)
    }

    /// Returns the immutable product plan that owns planning, provider
    /// selection, and resource authority for a plan-runtime executor.
    /// Legacy executors return `None`; `PlanRuntime` executors must expose the
    /// exact plan used for provisioning and dispatch.
    fn resolved_model_plan(&self) -> Option<&crate::vnext::ResolvedModelPlan> {
        None
    }

    /// Returns the authoritative memory breakdown for a shared plan runtime.
    /// `LegacyEngine` executors return `None`; `PlanRuntime` executors must
    /// return `Some` while they are ready.
    fn plan_runtime_resource_snapshot(&self) -> Result<Option<PlanRuntimeResourceSnapshot>> {
        Ok(None)
    }

    /// Whether this executor's backend can run the unified mixed prefill+decode
    /// forward natively. When false, the engine routes Qwen3-MoE batches through
    /// the legacy split path. Reported by the (backend-aware) executor so the
    /// engine stays backend-agnostic — replaces a `cfg(target_os)` branch that
    /// previously hard-coded "Metal/CPU lack native unified" in the hot path.
    ///
    /// Default false (conservative legacy path); accelerators with a native
    /// unified forward override to true.
    fn supports_native_unified_decode(&self) -> bool {
        false
    }

    /// Per-request KV capacity in tokens when the executor owns a smaller
    /// runtime cache window than the model's declared context length.
    fn kv_capacity(&self) -> Option<usize> {
        None
    }

    /// Installs the product-owned execution event sink before requests start.
    ///
    /// Legacy executors have no typed execution journal and keep the default
    /// no-op. Executors backed by the vNext runtime retain this sink with each
    /// admitted request so node/operation events share the product artifact.
    fn attach_execution_event_sink(&self, _sink: Arc<dyn crate::vnext::ExecutionEventSink>) {}

    /// Current plan-local capacity evidence for scheduler wake suppression.
    /// Legacy-engine executors return `None`; an executor declaring
    /// [`ExecutionResourceAuthority::PlanRuntime`] must return `Some`.
    fn execution_capacity_epochs(&self) -> Result<Option<ExecutorAdmissionEpochs>> {
        Ok(None)
    }

    /// Writes the canonical per-source availability generations into
    /// caller-owned storage and returns the matching global audit epochs.
    /// Executors with typed dynamic admission override this to avoid allocating
    /// on steady scheduler ticks.
    fn write_execution_capacity_snapshot(
        &self,
        availability: &mut Vec<crate::vnext::CapacityAvailabilityEpoch>,
    ) -> Result<Option<ExecutorAdmissionEpochs>> {
        availability.clear();
        self.execution_capacity_epochs()
    }

    /// Synchronously subscribes to every source named by one passive capacity
    /// wait. The returned registration must remain alive until it is awaited or
    /// deliberately cancelled by being dropped.
    ///
    /// Legacy-engine executors return `None`. An executor declaring
    /// [`ExecutionResourceAuthority::PlanRuntime`] must return `Some` for a
    /// wait condition issued by its own admission coordinator.
    fn register_execution_capacity_waiter(
        &self,
        _observed: &crate::vnext::CapacityWaitCondition,
    ) -> Result<Option<ExecutorCapacityWaitRegistration>> {
        Ok(None)
    }

    /// Probe and retain the exact request/sequence authority needed by a
    /// future prefill. No provider encode, kernel launch, or device submit may
    /// occur in this method.
    fn try_admit_prefill(
        &self,
        _input: ExecutorPrefillAdmission<'_>,
    ) -> Result<ExecutorPrefillAdmissionDecision> {
        Err(ferrum_types::FerrumError::unsupported(
            "plan-runtime prefill admission is not implemented",
        ))
    }

    /// Release an admitted but not yet active prefill authority.
    ///
    /// Returns true only when a retained authority was found and released.
    fn cancel_prefill_admission(&self, _request_id: &RequestId) -> bool {
        false
    }

    /// Writes the exact availability sources advanced when this request
    /// authority is preempted for recompute.
    ///
    /// `true` proves that `preemption` still identifies a live, quiescently
    /// releasable authority and that `sources` is its complete release
    /// footprint. Callers must treat `false` as not releasable; a generic
    /// "owns some cache" observation is not evidence that another request can
    /// advance the source on which the current frontier is blocked.
    fn write_execution_capacity_release_sources(
        &self,
        _preemption: &ExecutorExecutionCapacityPreemption,
        sources: &mut Vec<crate::vnext::CapacityAvailabilitySource>,
    ) -> Result<bool> {
        sources.clear();
        Ok(false)
    }

    /// Retire one exact request-scoped runtime authority for recompute.
    ///
    /// Success is a terminal release fence: all provider/device work that can
    /// access the authority is quiescent and the request can be admitted as a
    /// new sequence incarnation. Implementations must fail closed on identity
    /// mismatch or an in-flight authority they cannot terminalize.
    async fn preempt_execution_capacity(
        &self,
        _preemption: ExecutorExecutionCapacityPreemption,
    ) -> Result<ExecutorExecutionCapacityPreemptionReceipt> {
        Err(FerrumError::unsupported(
            "request-scoped execution-capacity preemption is not implemented",
        ))
    }

    /// Consume one retained logical/physical backing deferral after the
    /// scheduler waiting lock has been released. Implementations must perform
    /// at most one bounded maintenance attempt and publish capacity epochs only
    /// after real backing is installed.
    fn maintain_prefill_backing(
        &self,
        _request_id: &RequestId,
    ) -> Result<ExecutorPrefillMaintenanceOutcome> {
        Err(ferrum_types::FerrumError::unsupported(
            "plan-runtime prefill backing maintenance is not implemented",
        ))
    }

    /// Reserve model-owned KV slots before a forward is dispatched.
    ///
    /// This is the executor-level admission hook for vLLM-style paged KV. The
    /// engine calls it at the batch boundary so a request that cannot grow its
    /// KV cache is delayed or preempted before kernel launch instead of
    /// panicking inside attention.
    fn reserve_kv_slots(&self, _requests: &[KvSlotRequest]) -> Result<Option<KvSlotReservation>> {
        Ok(None)
    }

    /// Snapshot model-owned paged-KV capacity without allocating slots.
    ///
    /// Executors without model-owned paged KV return `None`.
    fn kv_slot_capacity_snapshot(&self) -> Option<KvSlotCapacitySnapshot> {
        None
    }

    /// Recurrent-state allocation spec for this request, when the model has
    /// state-space or hybrid layers that need per-request recurrent state.
    ///
    /// Attention-only models return `None`. If this returns `Some`, the engine
    /// must allocate a recurrent-state handle before prefill and pass it through
    /// prefill/decode inputs. The default keeps existing executors KV-only.
    fn recurrent_state_spec(
        &self,
        _request_id: &RequestId,
        _input_tokens: &[TokenId],
    ) -> Result<Option<RecurrentStateSpec>> {
        Ok(None)
    }

    /// Execute prefill phase (process initial prompt)
    async fn prefill(&self, input: &PrefillInput) -> Result<PrefillOutput>;

    /// Execute one exact prefill chunk with an explicit pre-submit capacity
    /// deferral edge. Legacy executors inherit full-prefill behavior.
    async fn prefill_with_capacity(&self, input: &PrefillInput) -> Result<ExecutorPrefillOutcome> {
        let output = self.prefill(input).await?;
        let chunk = match input.chunk {
            Some(chunk) => chunk,
            None => PrefillChunk::new(0, input.sequence_length(), input.sequence_length())?,
        };
        Ok(ExecutorPrefillOutcome::Completed(
            ExecutorPrefillCompletion::exact(output, chunk),
        ))
    }

    /// Batch prefill: process multiple prompts' prefill in ONE forward pass.
    ///
    /// Default implementation falls back to per-request `prefill()` (serial,
    /// which is the current behavior the engine sees today). Executors that
    /// support unified mixed-batch forward (e.g. via `model.unified_forward`
    /// over a varlen QKV path) should override this to amortize launch /
    /// kernel-overhead across all `inputs` items in one call.
    ///
    /// Used by the continuous-batching engine to coalesce a cohort of new
    /// prefills (apples M3 c=32 sees 32 simultaneous prefills as one logical
    /// batch; the serial fallback runs each in ~47 ms while a true batched
    /// path runs all 32 in ~100 ms).
    async fn batch_prefill(&self, inputs: &[PrefillInput]) -> Result<Vec<PrefillOutput>> {
        let mut outputs = Vec::with_capacity(inputs.len());
        for input in inputs {
            outputs.push(self.prefill(input).await?);
        }
        Ok(outputs)
    }

    /// Attempt one physical, capacity-aware prefill batch.
    ///
    /// Implementations must either complete every input in original order or
    /// return `NotSubmitted` after restoring every retained prefill authority
    /// to a retryable state. Partial device submission is an ordinary error,
    /// never a `NotSubmitted` result.
    async fn batch_prefill_with_capacity(
        &self,
        _inputs: &[PrefillInput],
    ) -> Result<ExecutorBatchPrefillOutcome> {
        Ok(ExecutorBatchPrefillOutcome::Unsupported)
    }

    /// Tensor-free prefill for executors that declare
    /// [`ExecutionResourceAuthority::PlanRuntime`].
    ///
    /// The default fails closed because adapting through [`PrefillInput`]
    /// would silently restore a host tensor boundary.
    async fn plan_runtime_prefill_with_capacity(
        &self,
        _input: &PlanRuntimePrefillInput,
    ) -> Result<PlanRuntimePrefillOutcome> {
        Err(FerrumError::unsupported(
            "tensor-free plan-runtime prefill is not implemented",
        ))
    }

    /// Attempt one physical tensor-free prefill batch.
    ///
    /// `Unsupported` is an optimization fallback to the typed single-request
    /// method. `NotSubmitted` proves that no participant reached provider
    /// encode or device submission.
    async fn plan_runtime_batch_prefill_with_capacity(
        &self,
        _inputs: &[PlanRuntimePrefillInput],
    ) -> Result<PlanRuntimeBatchPrefillOutcome> {
        Ok(PlanRuntimeBatchPrefillOutcome::Unsupported)
    }

    /// Discard an exact prefill authority after engine-side validation,
    /// sampling, or scheduler commit fails.
    ///
    /// Plan runtimes should override this to remove both retained-prefill and
    /// active state by the exact opaque handle, not by a reusable request id.
    fn discard_plan_runtime_prefill(&self, authority: PlanRuntimePrefillAuthority) -> Result<()> {
        self.release_cache(&authority.kv_cache().cache_id());
        Ok(())
    }

    /// Execute decode phase (generate next token)
    async fn decode(&self, input: &DecodeInput) -> Result<DecodeOutput>;

    /// Batch decode: process multiple sequences in one forward pass.
    ///
    /// A successful result must contain exactly one output per input, in the
    /// original input order, and each output cache must retain the identity of
    /// its corresponding input cache. Implementations must not expose partial
    /// success as a shorter or reordered vector.
    ///
    /// The default implementation falls back to serial per-request `decode()`.
    /// Executors with a typed batch submission path should override this so one
    /// call maps to one resource step and one terminal submission fence.
    async fn batch_decode(&self, inputs: &[DecodeInput]) -> Result<Vec<DecodeOutput>> {
        let mut outputs = Vec::with_capacity(inputs.len());
        for input in inputs {
            outputs.push(self.decode(input).await?);
        }
        Ok(outputs)
    }

    /// Batch decode with an explicit pre-submit capacity deferral edge.
    ///
    /// Legacy executors inherit the successful/error-only behavior. A runtime
    /// with typed resource authority overrides this method so temporary
    /// capacity pressure is never flattened into a stringly resource error.
    async fn batch_decode_with_capacity(
        &self,
        inputs: &[DecodeInput],
    ) -> Result<ExecutorBatchDecodeOutcome> {
        self.batch_decode(inputs)
            .await
            .map(ExecutorBatchDecodeOutcome::Completed)
    }

    /// Tensor-free batch decode for executors that declare
    /// [`ExecutionResourceAuthority::PlanRuntime`].
    ///
    /// Implementations must preserve input ordering and cache identity exactly.
    /// Temporary pressure may return `Deferred` only before device submission.
    /// The default fails closed because adapting through [`DecodeInput`] would
    /// silently restore the host-tensor boundary this contract removes.
    async fn plan_runtime_batch_decode_with_capacity(
        &self,
        _inputs: &[PlanRuntimeDecodeInput],
    ) -> Result<PlanRuntimeBatchDecodeOutcome> {
        Err(FerrumError::unsupported(
            "tensor-free plan-runtime batch decode is not implemented",
        ))
    }

    /// Unified mixed-batch forward: process a [`UnifiedBatch`] containing
    /// any combination of prefill chunks (one or more `q_tokens` per item,
    /// possibly continuing from `pos_offset > 0`) and decode steps
    /// (`q_tokens.len() == 1`, `is_final_chunk = true`) in a single model
    /// forward pass.
    ///
    /// Returns one element per `batch.items[i]`:
    /// - `Some(logits)` for items with `is_final_chunk = true` (the
    ///   request's final-position logits, ready for sampling)
    /// - `None` for intermediate prefill chunks (no lm_head executed —
    ///   model only updates KV state)
    ///
    /// Default implementation returns `Err(unsupported)`. Concrete LLM
    /// executors should override with either:
    /// - A behavioral fallback that dispatches each chunk via existing
    ///   `prefill()` and groups decode items into `batch_decode()` (this
    ///   preserves current behavior; no perf change), OR
    /// - A real unified-forward path that runs all items through one
    ///   `[M_total, hidden]` GEMM chain with a varlen attention kernel
    ///   (this is the chunked-prefill perf unlock).
    async fn unified_decode(&self, _batch: &UnifiedBatch) -> Result<Vec<Option<Vec<f32>>>> {
        Err(ferrum_types::FerrumError::unsupported(
            "unified_decode not implemented for this executor",
        ))
    }

    /// Optional: full forward pass (for non-autoregressive use cases)
    async fn forward(&self, _input: &TensorRef) -> Result<TensorRef> {
        // Default implementation not supported
        Err(ferrum_types::FerrumError::unsupported(
            "Full forward pass not supported by this executor",
        ))
    }

    /// Roll the KV cache for this executor's sequence back to `new_len`.
    /// Used by speculative decoding on partial rejection so the next
    /// iteration sees a KV prefix that matches the accepted token stream.
    /// Default: Ok(()) — executors that don't cache per-sequence state
    /// (stub, mock) are inherently tolerant; real LLM executors override.
    async fn truncate_kv(
        &self,
        _kv_cache: &std::sync::Arc<dyn crate::KvCacheHandle>,
        _new_len: usize,
    ) -> Result<()> {
        Ok(())
    }

    /// Multi-position decode-verify: one forward over `N+1` tokens,
    /// producing one logits row per position. Used by speculative
    /// decoding's target path so we don't pay N+1 sequential forwards.
    ///
    /// Default falls back to N+1 sequential `decode()` calls — correct
    /// but slow; real LLM executors override.
    ///
    /// Returns a `Vec<DecodeOutput>` of length `inputs.len()` with the
    /// final KV handle attached to the last element.
    async fn forward_verify(&self, inputs: &[DecodeInput]) -> Result<Vec<DecodeOutput>> {
        let mut out = Vec::with_capacity(inputs.len());
        for input in inputs {
            out.push(self.decode(input).await?);
        }
        Ok(out)
    }

    /// Get executor capabilities
    fn capabilities(&self) -> ExecutorCapabilities;

    /// Get current executor status
    fn status(&self) -> ExecutorStatus;

    /// Optional model/executor cache metrics.
    ///
    /// Concrete LLM executors use this for model-level paged KV prefix reuse
    /// counters. Default implementations keep non-autoregressive executors
    /// and tests from needing cache-specific plumbing.
    fn cache_metrics_snapshot(&self) -> Option<serde_json::Value> {
        None
    }

    /// Optional compact provider-attribution witness emitted by executors
    /// whose immutable plan can bind quantized source tensors to selected
    /// operation providers without exposing per-tensor logs.
    fn execution_attribution_snapshot(&self) -> Option<serde_json::Value> {
        None
    }

    /// Optional LoRA runtime metrics.
    fn lora_metrics_snapshot(&self) -> Option<serde_json::Value> {
        None
    }

    /// Complete executor-owned startup preparation before either product
    /// entrypoint can accept a request.
    ///
    /// Implementations use this cold-path hook for work that requires the
    /// fully constructed executor but must not be charged to a user's first
    /// request, such as compiling reusable execution shapes. The default is a
    /// no-op so existing executors remain source compatible.
    async fn prepare_startup(&self) -> Result<()> {
        Ok(())
    }

    /// Warm up executor (load model, allocate memory, etc.)
    async fn warmup(&mut self) -> Result<()> {
        // Default no-op implementation
        Ok(())
    }

    /// Shutdown executor gracefully
    async fn shutdown(&mut self) -> Result<()> {
        // Default no-op implementation
        Ok(())
    }

    /// Complete and release one cache authority with product-authoritative
    /// terminal token counts.
    ///
    /// Legacy executors only need physical release and inherit that behavior.
    /// Plan runtimes with terminal journals override this method so completion
    /// cannot be inferred from a generic release operation.
    fn complete_cache(&self, completion: ExecutorSequenceCompletion) -> Result<()> {
        self.release_cache(completion.cache_id());
        Ok(())
    }

    /// Release KV cache and state without asserting successful completion.
    ///
    /// Called for cancellation, failure, recompute, and legacy cleanup. The
    /// `cache_id` matches the value embedded in the `KvCacheHandle` returned by
    /// prefill/decode. Successful product completion uses [`Self::complete_cache`].
    fn release_cache(&self, _cache_id: &str) {
        // Default no-op — executors that manage per-sequence KV caches should override.
    }
}

/// Executor capabilities and configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorCapabilities {
    /// Maximum supported batch size
    pub max_batch_size: usize,
    /// Maximum sequence length
    pub max_sequence_length: usize,
    /// Supported attention mechanisms
    pub attention_mechanisms: Vec<AttentionType>,
    /// Whether executor supports dynamic batching
    pub supports_dynamic_batching: bool,
    /// Whether executor supports continuous batching
    pub supports_continuous_batching: bool,
    /// Whether executor supports speculative decoding
    pub supports_speculative_decoding: bool,
    /// Whether executor supports tensor parallelism
    pub supports_tensor_parallelism: bool,
    /// Whether executor supports pipeline parallelism
    pub supports_pipeline_parallelism: bool,
    /// Supported data types
    pub supported_dtypes: Vec<ferrum_types::DataType>,
    /// Supported devices
    pub supported_devices: Vec<ferrum_types::Device>,
    /// Memory requirements estimation
    pub memory_requirements: MemoryRequirements,
}

/// Attention mechanism types
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum AttentionType {
    /// Standard multi-head attention
    MultiHead,
    /// Multi-query attention (MQA)
    MultiQuery,
    /// Grouped-query attention (GQA)
    GroupedQuery,
    /// Flash attention
    Flash,
    /// Paged attention
    Paged,
    /// Sliding window attention
    SlidingWindow,
}

/// Memory requirements for model execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryRequirements {
    /// Model parameter memory in bytes
    pub parameter_memory: u64,
    /// Minimum activation memory per token
    pub activation_memory_per_token: usize,
    /// KV cache memory per token per layer
    pub kv_cache_memory_per_token: usize,
    /// Additional overhead memory
    pub overhead_memory: u64,
}

impl MemoryRequirements {
    /// Calculate total memory for given configuration
    pub fn calculate_total_memory(
        &self,
        batch_size: usize,
        sequence_length: usize,
        num_layers: usize,
    ) -> u64 {
        let activation_mem =
            (self.activation_memory_per_token * batch_size * sequence_length) as u64;
        let kv_cache_mem =
            (self.kv_cache_memory_per_token * batch_size * sequence_length * num_layers) as u64;

        self.parameter_memory + activation_mem + kv_cache_mem + self.overhead_memory
    }
}

/// Executor status information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorStatus {
    /// Current executor state
    pub state: ExecutorState,
    /// Whether executor is ready to accept requests
    pub is_ready: bool,
    /// Current batch size being processed
    pub current_batch_size: usize,
    /// Number of prefill operations completed
    pub prefill_operations: u64,
    /// Number of decode operations completed
    pub decode_operations: u64,
    /// Average prefill time in milliseconds
    pub avg_prefill_time_ms: f64,
    /// Average decode time in milliseconds
    pub avg_decode_time_ms: f64,
    /// Memory usage statistics
    pub memory_usage: ExecutorMemoryUsage,
    /// Last operation timestamp
    #[serde(skip)]
    pub last_operation: Option<std::time::Instant>,
}

/// Executor state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExecutorState {
    /// Executor is initializing
    Initializing,
    /// Executor is ready to accept requests
    Ready,
    /// Executor is processing requests
    Busy,
    /// Executor encountered an error
    Error,
    /// Executor is shutting down
    Shutdown,
}

/// Executor memory usage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorMemoryUsage {
    /// Total allocated memory in bytes
    pub allocated_bytes: usize,
    /// Currently used memory in bytes
    pub used_bytes: usize,
    /// Peak memory usage
    pub peak_bytes: usize,
    /// Memory utilization percentage
    pub utilization_percent: f32,
}

/// Batch model executor for processing multiple requests efficiently
#[async_trait]
pub trait BatchModelExecutor: ModelExecutor {
    /// Execute batch prefill for multiple sequences
    async fn batch_prefill(&self, inputs: &[PrefillInput]) -> Result<Vec<PrefillOutput>>;

    /// Execute batch decode for multiple sequences
    async fn batch_decode(&self, inputs: &[DecodeInput]) -> Result<Vec<DecodeOutput>>;

    /// Get optimal batch size for current conditions
    fn optimal_batch_size(&self) -> usize;

    /// Check if batch size is supported
    fn supports_batch_size(&self, batch_size: usize) -> bool;
}

/// Speculative execution support
#[async_trait]
pub trait SpeculativeExecutor: ModelExecutor {
    /// Execute speculative decoding with draft model
    async fn speculative_decode(
        &self,
        input: &DecodeInput,
        draft_tokens: &[ferrum_types::TokenId],
        acceptance_threshold: f32,
    ) -> Result<SpeculativeDecodeOutput>;
}

/// Output from speculative decoding
#[derive(Debug, Clone)]
pub struct SpeculativeDecodeOutput {
    /// Accepted tokens (subset of draft tokens)
    pub accepted_tokens: Vec<ferrum_types::TokenId>,
    /// Logits for the next token after last accepted
    pub next_logits: TensorRef,
    /// Updated KV cache
    pub kv_cache: Arc<dyn KvCacheHandle>,
    /// Number of draft tokens accepted
    pub acceptance_count: usize,
}

/// Model executor factory
#[async_trait]
pub trait ModelExecutorFactory: Send + Sync {
    /// Create executor from model configuration
    async fn create_executor(&self, config: &ExecutorConfig) -> Result<Box<dyn ModelExecutor>>;

    /// Create batch executor
    async fn create_batch_executor(
        &self,
        config: &ExecutorConfig,
    ) -> Result<Box<dyn BatchModelExecutor>>;

    /// Get supported executor types
    fn supported_types(&self) -> Vec<ExecutorType>;

    /// Validate configuration
    fn validate_config(&self, config: &ExecutorConfig) -> Result<()>;
}

/// Executor configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorConfig {
    /// Model information
    pub model_info: ModelInfo,
    /// Target device
    pub device: ferrum_types::Device,
    /// Data type for computation
    pub dtype: ferrum_types::DataType,
    /// Maximum batch size
    pub max_batch_size: usize,
    /// Maximum sequence length
    pub max_sequence_length: usize,
    /// Attention configuration
    pub attention_config: ExecutorAttentionConfig,
    /// Memory configuration
    pub memory_config: ExecutorMemoryConfig,
    /// Optimization settings
    pub optimization_config: OptimizationConfig,
    /// Additional executor-specific options
    pub executor_options: HashMap<String, serde_json::Value>,
}

/// Runtime attention configuration for model executor
///
/// Note: This is different from ferrum_types::AttentionConfig which describes
/// the model architecture's attention configuration from config.json.
/// This type describes the runtime execution settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorAttentionConfig {
    /// Type of attention to use
    pub attention_type: AttentionType,
    /// Enable flash attention if available
    pub enable_flash_attention: bool,
    /// Enable paged attention
    pub enable_paged_attention: bool,
    /// Block size for paged attention
    pub block_size: Option<usize>,
    /// Sliding window size (if using sliding window attention)
    pub sliding_window_size: Option<usize>,
}

/// Memory configuration for executor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorMemoryConfig {
    /// Enable memory pooling
    pub enable_memory_pooling: bool,
    /// Memory pool size in bytes (None for auto)
    pub memory_pool_size: Option<usize>,
    /// Enable KV cache sharing
    pub enable_kv_cache_sharing: bool,
    /// Maximum memory usage percentage
    pub max_memory_usage: f32,
}

/// Optimization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationConfig {
    /// Enable CUDA graphs (if supported)
    pub enable_cuda_graphs: bool,
    /// Enable kernel fusion
    pub enable_kernel_fusion: bool,
    /// Enable mixed precision
    pub enable_mixed_precision: bool,
    /// Optimization level (0-3)
    pub optimization_level: u8,
    /// Custom optimization flags
    pub custom_flags: HashMap<String, bool>,
}

/// Supported executor types
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ExecutorType {
    /// Standard sequential executor
    Sequential,
    /// Batch executor for parallel processing
    Batch,
    /// Continuous batching executor
    ContinuousBatch,
    /// Speculative decoding executor
    Speculative,
    /// Pipeline parallel executor
    PipelineParallel,
    /// Tensor parallel executor
    TensorParallel,
}

/// Executor performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutorMetrics {
    /// Total operations executed
    pub total_operations: u64,
    /// Prefill operations
    pub prefill_operations: u64,
    /// Decode operations
    pub decode_operations: u64,
    /// Average prefill latency (ms)
    pub avg_prefill_latency: f64,
    /// Average decode latency (ms)
    pub avg_decode_latency: f64,
    /// P95 prefill latency (ms)
    pub p95_prefill_latency: f64,
    /// P95 decode latency (ms)
    pub p95_decode_latency: f64,
    /// Throughput (tokens per second)
    pub throughput_tps: f64,
    /// Memory efficiency (used/allocated)
    pub memory_efficiency: f32,
    /// Batch utilization
    pub batch_utilization: f32,
}

/// Executor registry for managing multiple executors
pub trait ExecutorRegistry: Send + Sync {
    /// Register executor with name
    fn register(&mut self, name: &str, executor: Box<dyn ModelExecutor>) -> Result<()>;

    /// Get executor by name
    fn get(&self, name: &str) -> Option<&dyn ModelExecutor>;

    /// Remove executor by name
    fn remove(&mut self, name: &str) -> Option<Box<dyn ModelExecutor>>;

    /// List registered executor names
    fn list_names(&self) -> Vec<String>;

    /// Get executor metrics
    fn get_metrics(&self, name: &str) -> Option<ExecutorMetrics>;
}