inky-engine 3.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! Byte-level RFC 8259 JSON pushdown grammar mask for constrained tool-call sampling.
//!
//! Tracks active tool-call spans (`<|message_model|><header><|content_invoke_tool_json|> ... <|end_message|>`)
//! per serving lane and masks out any vocabulary token whose UTF-8 bytes would make the partial JSON
//! syntactically or schema-structurally invalid, or that would emit `<|end_message|>` before the root
//! JSON object `{...}` is balanced and complete.

use crate::tokenizer::Tokenizer;
use serde_json::Value;
use std::sync::Arc;

const MAX_DEPTH_CAP: usize = 32;
/// Compiled object schemas per request: each tool takes a wrapper, its arguments and one per nested
/// object property, so an agent's 40-odd tools need well over 64. Indices are `u16`.
const MAX_SCHEMAS: usize = 4096;
/// One fixed string per tool name.
const MAX_FIXED_STRINGS: usize = 1024;
const MAX_SCHEMA_PROPS: usize = 64;
const NO_SCHEMA: u16 = u16::MAX;
const NO_FIXED_STR: u16 = u16::MAX;

/// Configurable structural bounds so adversarial logit distributions cannot hold open
/// unbounded containers, strings, or structural whitespace runs indefinitely while real
/// tool calls retain generous limits (including multi-space pretty-printed JSON).
#[derive(Clone, Copy, Debug)]
pub struct GrammarLimits {
    pub max_depth: u8,
    pub max_container_items: u16,
    pub max_string_bytes: u32,
    pub max_ws_run: u8,
}

impl GrammarLimits {
    pub const DEFAULT: Self = Self {
        max_depth: 28,
        max_container_items: 1024,
        max_string_bytes: 256 * 1024,
        max_ws_run: 64,
    };

    #[cfg(test)]
    pub const fn adversarial_test() -> Self {
        Self {
            max_depth: 8,
            max_container_items: 8,
            max_string_bytes: 48,
            max_ws_run: 4,
        }
    }
}

impl Default for GrammarLimits {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Contiguous precomputed vocabulary byte lookup table (zero per-step heap allocations),
/// plus startup token-class bitsets that resolve common JSON grammar states in O(1).
pub struct VocabBytes {
    data: Vec<u8>,
    offsets: Vec<u32>,
    special_bits: Vec<u64>,
    /// Non-special, non-empty tokens whose bytes are all RFC 8259 JSON whitespace.
    json_ws_bits: Vec<u64>,
    /// Non-special, non-empty tokens for which every byte returns `StrStep::Continue`
    /// starting from `StrSubState::new()` (no closing `"`, no unescaped control byte,
    /// no invalid UTF-8 or escape sequence).
    str_interior_bits: Vec<u64>,
    /// Non-special, non-empty tokens that hit `StrStep::Invalid` before `StrStep::Closed`
    /// starting from `StrSubState::new()`.
    str_invalid_fresh_bits: Vec<u64>,
    vocab_len: usize,
}

impl VocabBytes {
    pub fn from_tokenizer(tk: &Tokenizer) -> Self {
        let n = tk.vocab_len();
        let mut total_bytes = 0usize;
        for id in 0..n {
            if !tk.is_special(id as u32) {
                total_bytes += tk.decode_bytes(id as u32).len();
            }
        }
        Self::build_from_iter(n, total_bytes, |id| {
            if tk.is_special(id as u32) {
                None
            } else {
                Some(tk.decode_bytes(id as u32))
            }
        })
    }

    fn build_from_iter<F>(n: usize, total_bytes: usize, mut get_bytes: F) -> Self
    where
        F: FnMut(usize) -> Option<Vec<u8>>,
    {
        let words = n.div_ceil(64);
        let mut data = Vec::with_capacity(total_bytes);
        let mut offsets = Vec::with_capacity(n + 1);
        let mut special_bits = vec![0u64; words];
        let mut json_ws_bits = vec![0u64; words];
        let mut str_interior_bits = vec![0u64; words];
        let mut str_invalid_fresh_bits = vec![0u64; words];
        for id in 0..n {
            offsets.push(data.len() as u32);
            let word = id / 64;
            let bit = 1u64 << (id % 64);
            match get_bytes(id) {
                None => {
                    special_bits[word] |= bit;
                }
                Some(bytes) => {
                    if !bytes.is_empty() {
                        if bytes.iter().all(|&b| is_json_ws(b)) {
                            json_ws_bits[word] |= bit;
                        }
                        let mut ss = StrSubState::new();
                        let mut all_continue = true;
                        let mut invalid_before_close = false;
                        for &b in &bytes {
                            match ss.step(b, u32::MAX) {
                                StrStep::Continue => {}
                                StrStep::Closed => {
                                    all_continue = false;
                                    break;
                                }
                                StrStep::Invalid => {
                                    all_continue = false;
                                    invalid_before_close = true;
                                    break;
                                }
                            }
                        }
                        if all_continue {
                            str_interior_bits[word] |= bit;
                        } else if invalid_before_close {
                            str_invalid_fresh_bits[word] |= bit;
                        }
                    }
                    data.extend_from_slice(&bytes);
                }
            }
        }
        offsets.push(data.len() as u32);
        Self {
            data,
            offsets,
            special_bits,
            json_ws_bits,
            str_interior_bits,
            str_invalid_fresh_bits,
            vocab_len: n,
        }
    }

    #[cfg(test)]
    pub(crate) fn from_test_entries(entries: &[Option<&[u8]>]) -> Self {
        let total_bytes: usize = entries.iter().filter_map(|e| e.map(|b| b.len())).sum();
        Self::build_from_iter(entries.len(), total_bytes, |id| {
            entries[id].map(|b| b.to_vec())
        })
    }

    #[inline]
    pub fn is_special(&self, id: u32) -> bool {
        let idx = id as usize;
        if idx >= self.vocab_len {
            return true;
        }
        (self.special_bits[idx / 64] & (1u64 << (idx % 64))) != 0
    }

    #[inline]
    fn bit_set(bits: &[u64], id: u32, vocab_len: usize) -> bool {
        let idx = id as usize;
        idx < vocab_len && (bits[idx / 64] & (1u64 << (idx % 64))) != 0
    }

    /// True iff `id` is a non-special, non-empty token consisting solely of JSON whitespace.
    #[inline]
    pub fn is_json_ws_token(&self, id: u32) -> bool {
        Self::bit_set(&self.json_ws_bits, id, self.vocab_len)
    }

    /// True iff `id` is a non-special, non-empty token that stays inside a free JSON string
    /// (never closing or erroring) when started at a clean byte/escape boundary.
    #[inline]
    pub fn is_str_interior(&self, id: u32) -> bool {
        Self::bit_set(&self.str_interior_bits, id, self.vocab_len)
    }

    /// True iff `id` is a non-special, non-empty token that always fails free-string validation
    /// before closing when started at a clean byte/escape boundary.
    #[inline]
    pub fn is_str_invalid_fresh(&self, id: u32) -> bool {
        Self::bit_set(&self.str_invalid_fresh_bits, id, self.vocab_len)
    }

    /// Non-special vocabulary token bytes, or `None` for special / out-of-range IDs.
    #[inline]
    pub fn non_special_bytes(&self, id: u32) -> Option<&[u8]> {
        let idx = id as usize;
        if idx >= self.vocab_len || self.is_special(id) {
            return None;
        }
        let s = self.offsets[idx] as usize;
        let e = self.offsets[idx + 1] as usize;
        Some(&self.data[s..e])
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TypeMask(u8);

impl TypeMask {
    const OBJ: Self = Self(1 << 0);
    const ARR: Self = Self(1 << 1);
    const STR: Self = Self(1 << 2);
    const NUM: Self = Self(1 << 3);
    const INT: Self = Self(1 << 4);
    const BOOL: Self = Self(1 << 5);
    const NULL: Self = Self(1 << 6);
    const CONTAINERS: Self = Self((1 << 0) | (1 << 1));
    const ANY: Self = Self((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 5) | (1 << 6));

    #[inline]
    const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) != 0
    }

    #[inline]
    const fn bitor(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    #[inline]
    const fn without_containers_if_possible(self) -> Self {
        let prims = self.0 & !Self::CONTAINERS.0;
        if prims != 0 {
            Self(prims)
        } else {
            self
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PropValueSpec {
    mask: TypeMask,
    nested_schema: u16,
    fixed_str: u16,
}

impl PropValueSpec {
    const fn any() -> Self {
        Self {
            mask: TypeMask::ANY,
            nested_schema: NO_SCHEMA,
            fixed_str: NO_FIXED_STR,
        }
    }

    const fn object(nested_schema: u16) -> Self {
        Self {
            mask: TypeMask::OBJ,
            nested_schema,
            fixed_str: NO_FIXED_STR,
        }
    }

    const fn fixed_string(fixed_str: u16) -> Self {
        Self {
            mask: TypeMask::STR,
            nested_schema: NO_SCHEMA,
            fixed_str,
        }
    }
}

#[derive(Clone, Debug)]
struct PropSpec {
    escaped: Vec<u8>,
    spec: PropValueSpec,
}

#[derive(Clone, Debug)]
struct ObjectSchema {
    props: Vec<PropSpec>,
    required_mask: u64,
    allow_additional: bool,
}

impl ObjectSchema {
    #[inline]
    fn all_props_mask(&self) -> u64 {
        let n = self.props.len().min(MAX_SCHEMA_PROPS);
        if n == 64 {
            u64::MAX
        } else {
            (1u64 << n) - 1
        }
    }

    #[inline]
    fn required_satisfied(&self, seen_mask: u64) -> bool {
        (seen_mask & self.required_mask) == self.required_mask
    }

    #[inline]
    fn unseen_mask(&self, seen_mask: u64) -> u64 {
        self.all_props_mask() & !seen_mask
    }

    #[inline]
    fn can_add_more_keys(&self, seen_mask: u64) -> bool {
        self.allow_additional || self.unseen_mask(seen_mask) != 0
    }
}

/// Immutable arena of compiled object schemas and fixed string literals for a request.
#[derive(Clone, Debug, Default)]
pub struct SchemaArena {
    schemas: Vec<ObjectSchema>,
    fixed_strings: Vec<Vec<u8>>,
    /// The first bound the request's tools went past. Past a bound the arena stops compiling, so the serve
    /// routes refuse such a request with a 400 rather than leave its tools unchecked.
    over_limit: Option<String>,
}

fn json_escaped_inner(s: &str) -> Vec<u8> {
    let quoted = serde_json::to_string(s).expect("JSON string serialization");
    quoted.as_bytes()[1..quoted.len() - 1].to_vec()
}

impl SchemaArena {
    fn note_over_limit(&mut self, what: String) {
        self.over_limit.get_or_insert(what);
    }

    fn intern_fixed_str(&mut self, s: &str) -> u16 {
        if self.fixed_strings.len() >= MAX_FIXED_STRINGS {
            self.note_over_limit(format!("more than {MAX_FIXED_STRINGS} tool names"));
            return NO_FIXED_STR;
        }
        let esc = json_escaped_inner(s);
        if let Some(pos) = self.fixed_strings.iter().position(|x| x == &esc) {
            return pos as u16;
        }
        let idx = self.fixed_strings.len() as u16;
        self.fixed_strings.push(esc);
        idx
    }

    fn compile_prop_value(&mut self, schema: &Value, depth: usize) -> PropValueSpec {
        let Some(obj) = schema.as_object() else {
            return PropValueSpec::any();
        };
        // Schemas using combinators (`anyOf`, `oneOf`, `allOf`, `$ref`, untyped `enum`) remain permissive
        // unless an explicit JSON `"type"` is declared.
        let Some(ty_val) = obj.get("type") else {
            if obj.contains_key("properties") || obj.contains_key("required") {
                let nested = if depth < 6 {
                    self.compile_object_schema(schema, depth + 1)
                } else {
                    NO_SCHEMA
                };
                return PropValueSpec::object(nested);
            }
            return PropValueSpec::any();
        };
        let parse_one = |name: &str| -> Option<TypeMask> {
            match name {
                "object" => Some(TypeMask::OBJ),
                "array" => Some(TypeMask::ARR),
                "string" => Some(TypeMask::STR),
                "number" => Some(TypeMask::NUM),
                "integer" => Some(TypeMask::INT),
                "boolean" => Some(TypeMask::BOOL),
                "null" => Some(TypeMask::NULL),
                _ => None,
            }
        };
        let mut mask = TypeMask(0);
        match ty_val {
            Value::String(s) => {
                let Some(m) = parse_one(s) else {
                    return PropValueSpec::any();
                };
                mask = m;
            }
            Value::Array(items) => {
                for item in items {
                    let Some(s) = item.as_str().and_then(parse_one) else {
                        return PropValueSpec::any();
                    };
                    mask = mask.bitor(s);
                }
                if mask.0 == 0 {
                    return PropValueSpec::any();
                }
            }
            _ => return PropValueSpec::any(),
        }
        let nested_schema = if mask.contains(TypeMask::OBJ) && depth < 6 {
            self.compile_object_schema(schema, depth + 1)
        } else {
            NO_SCHEMA
        };
        PropValueSpec {
            mask,
            nested_schema,
            fixed_str: NO_FIXED_STR,
        }
    }

    pub fn compile_object_schema(&mut self, schema: &Value, depth: usize) -> u16 {
        if self.schemas.len() >= MAX_SCHEMAS {
            self.note_over_limit(schemas_over_limit());
            return NO_SCHEMA;
        }
        let Some(obj) = schema.as_object() else {
            return NO_SCHEMA;
        };
        let allow_additional = !matches!(obj.get("additionalProperties"), Some(Value::Bool(false)));
        let mut prop_names: Vec<String> = Vec::new();
        let mut required_names: Vec<String> = Vec::new();
        if let Some(req_arr) = obj.get("required").and_then(Value::as_array) {
            for r in req_arr {
                if let Some(name) = r.as_str() {
                    if !required_names.iter().any(|x| x == name) && required_names.len() < MAX_SCHEMA_PROPS {
                        required_names.push(name.to_owned());
                    }
                    if !prop_names.iter().any(|x| x == name) && prop_names.len() < MAX_SCHEMA_PROPS {
                        prop_names.push(name.to_owned());
                    }
                }
            }
        }
        let props_map = obj.get("properties").and_then(Value::as_object);
        if let Some(pm) = props_map {
            for k in pm.keys() {
                if !prop_names.iter().any(|x| x == k) && prop_names.len() < MAX_SCHEMA_PROPS {
                    prop_names.push(k.clone());
                }
            }
        }
        // `prop_names` keeps the first MAX_SCHEMA_PROPS names; one more distinct name would go unchecked.
        let required = obj.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
        let keys = props_map.into_iter().flat_map(|pm| pm.keys().map(String::as_str));
        if prop_names.len() == MAX_SCHEMA_PROPS && required.chain(keys).any(|n| !prop_names.iter().any(|p| p == n)) {
            self.note_over_limit(format!("an object schema with more than {MAX_SCHEMA_PROPS} properties"));
        }
        if prop_names.is_empty() && allow_additional {
            return NO_SCHEMA;
        }
        let mut props = Vec::with_capacity(prop_names.len());
        let mut required_mask = 0u64;
        for (idx, name) in prop_names.iter().enumerate() {
            let spec = props_map
                .and_then(|pm| pm.get(name))
                .map(|sub| self.compile_prop_value(sub, depth))
                .unwrap_or_else(PropValueSpec::any);
            if required_names.iter().any(|r| r == name) {
                required_mask |= 1u64 << idx;
            }
            props.push(PropSpec {
                escaped: json_escaped_inner(name),
                spec,
            });
        }
        if self.schemas.len() >= MAX_SCHEMAS {
            self.note_over_limit(schemas_over_limit());
            return NO_SCHEMA;
        }
        let id = self.schemas.len() as u16;
        self.schemas.push(ObjectSchema {
            props,
            required_mask,
            allow_additional,
        });
        id
    }

    fn build_tool_wrapper_schema(&mut self, fixed_tool_name: Option<&str>, args_schema: u16) -> u16 {
        let name_spec = match fixed_tool_name.filter(|s| !s.is_empty()) {
            Some(name) => {
                let fs = self.intern_fixed_str(name);
                if fs != NO_FIXED_STR {
                    PropValueSpec::fixed_string(fs)
                } else {
                    PropValueSpec {
                        mask: TypeMask::STR,
                        nested_schema: NO_SCHEMA,
                        fixed_str: NO_FIXED_STR,
                    }
                }
            }
            None => PropValueSpec {
                mask: TypeMask::STR,
                nested_schema: NO_SCHEMA,
                fixed_str: NO_FIXED_STR,
            },
        };
        let args_spec = PropValueSpec::object(args_schema);
        let props = vec![
            PropSpec {
                escaped: b"name".to_vec(),
                spec: name_spec,
            },
            PropSpec {
                escaped: b"args".to_vec(),
                spec: args_spec,
            },
        ];
        // `parse_tool_call` in `src/serve/reply.rs` requires `"args"` to be a JSON object and reads
        // optional `"name"` (falling back to the header name when omitted).
        let id = self.schemas.len() as u16;
        self.schemas.push(ObjectSchema {
            props,
            required_mask: 1u64 << 1,
            allow_additional: false,
        });
        id
    }
}

#[derive(Clone, Debug)]
struct ToolEntry {
    name: String,
    wrapper_schema: u16,
}

/// Pre-compiled request tool catalog shared via `Arc` on `Job`.
#[derive(Clone, Debug)]
pub struct ToolCatalog {
    arena: SchemaArena,
    /// The wrapper for a body that follows no offered header (unmasked catalogs only; see `observe_token`).
    fallback_wrapper_schema: u16,
    /// Every tool name the request offered, sorted and deduplicated, each spelled exactly as the request spells
    /// it and as the template writes it in a header (`<|message_model|>NAME<|content_invoke_tool_json|>`).
    /// Read from the request, not from the schemas that compiled, so a tool whose schema did not fit the arena
    /// is still callable. Sorted so that the names sharing a prefix are one contiguous range: no lookup scans
    /// every name.
    names: Vec<Box<[u8]>>,
    /// Per entry of `names`: that tool's wrapper schema in `arena`, or `NO_SCHEMA` when its schema did not fit.
    name_wrappers: Vec<u16>,
    /// The header and the tool marker are masked to `names`. False for `tool_choice: none`, which leaves both
    /// unconstrained (the routes refuse `none` today; the grammar does not rely on that).
    mask: bool,
    /// Bytes the header may hold: the longest offered name, at least [`UNCONSTRAINED_HEADER_CAP`].
    header_cap: usize,
}

/// Header bytes kept when the header is not masked (a longer header cannot name an offered tool anyway).
const UNCONSTRAINED_HEADER_CAP: usize = 256;

/// A header with its surrounding whitespace removed: the compatibility reading for a header that is not
/// exactly an offered name. An exactly offered name is never trimmed (see [`bind_call`]).
pub fn header_tool_name(header: &[u8]) -> std::borrow::Cow<'_, str> {
    match String::from_utf8_lossy(header) {
        std::borrow::Cow::Borrowed(s) => std::borrow::Cow::Borrowed(s.trim()),
        std::borrow::Cow::Owned(s) => std::borrow::Cow::Owned(s.trim().to_owned()),
    }
}

/// The schema bound as a 400 names it.
fn schemas_over_limit() -> String {
    format!("more than {MAX_SCHEMAS} object schemas (one per tool, per tool's arguments and per nested object)")
}

/// How the wire names a completed tool body (`serve::reply`: chat, chat SSE, Anthropic content and stream).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CallName {
    /// Sent under `name`. `offered`: the request offered that name. `consistent`: the body followed a header
    /// that is exactly `name`, and its own `"name"`, if it has one, agrees.
    Sent { name: String, offered: bool, consistent: bool },
    /// The request offered tools and neither the header nor the body names one of them: the body is not sent.
    Unoffered,
}

/// Binds a completed tool body to an offered tool. `tools` is the request's catalog (`None`: it offered no
/// tools); `header` is the text between `<|message_model|>` and the tool marker, `None` when the marker did not
/// follow a header; `body_name` is the body's `"name"`.
///
/// With tools, in order: the header exactly as offered (never trimmed, so a name offered with surrounding
/// whitespace keeps it), the trimmed header, the body's name. The header outranks the body because the grammar
/// picks the argument schema by header. A request with tools is never sent a name it did not offer. With no
/// tools there is nothing to bind to: the body's name, else the trimmed header, goes out as before.
pub fn bind_call(tools: Option<&ToolCatalog>, header: Option<&[u8]>, body_name: Option<&str>) -> CallName {
    let Some(cat) = tools else {
        let name = match (body_name, header) {
            (Some(b), _) => b.to_owned(),
            (None, Some(h)) => header_tool_name(h).into_owned(),
            (None, None) => String::new(),
        };
        return CallName::Sent { name, offered: false, consistent: true };
    };
    if let Some(h) = header {
        if let (true, Ok(name)) = (cat.offers(h), std::str::from_utf8(h)) {
            let consistent = body_name.is_none_or(|b| b == name);
            return CallName::Sent { name: name.to_owned(), offered: true, consistent };
        }
        let trimmed = header_tool_name(h);
        if cat.offers(trimmed.as_bytes()) {
            return CallName::Sent { name: trimmed.into_owned(), offered: true, consistent: false };
        }
    }
    match body_name {
        Some(b) if cat.offers(b.as_bytes()) => CallName::Sent { name: b.to_owned(), offered: true, consistent: false },
        _ => CallName::Unoffered,
    }
}

#[cfg(test)]
thread_local! {
    /// Name comparisons made by the offered-name lookups on this thread (tests assert none scans the catalog).
    static NAME_PROBES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

#[inline(always)]
fn name_probe() {
    #[cfg(test)]
    NAME_PROBES.with(|c| c.set(c.get() + 1));
}

impl ToolCatalog {
    /// The first bound the tools went past, as a 400's message: past it the grammar would not check them.
    pub fn over_limit(&self) -> Option<String> {
        self.arena
            .over_limit
            .as_ref()
            .map(|what| format!("tools: the request declares {what}; inky's tool-call grammar checks at most that many"))
    }

    /// Extract tool definitions from either OpenAI `/v1/chat/completions` (`tools[].function.{name, parameters}`)
    /// or Anthropic `/v1/messages` (`tools[].{name, input_schema}`). Returns `None` when no tools are present.
    pub fn from_request(req: &Value) -> Option<Arc<Self>> {
        let arr = req.get("tools")?.as_array()?;
        if arr.is_empty() {
            return None;
        }
        let mut arena = SchemaArena::default();
        let mut raw_tools: Vec<(String, Option<&Value>)> = Vec::new();
        for item in arr {
            if let Some(func) = item.get("function").and_then(Value::as_object) {
                if let Some(name) = func.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()) {
                    raw_tools.push((name.to_owned(), func.get("parameters")));
                    continue;
                }
            }
            if let Some(obj) = item.as_object() {
                if let Some(name) = obj.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()) {
                    raw_tools.push((name.to_owned(), obj.get("input_schema").or_else(|| obj.get("parameters"))));
                }
            }
        }
        // `tool_choice: none` (OpenAI `"none"`, Anthropic `{"type":"none"}`): no call is wanted, so nothing is
        // steered toward one.
        let choice = req.get("tool_choice");
        let choice_none = choice.is_some_and(|c| c == "none" || c.get("type").is_some_and(|t| t == "none"));
        let mut names: Vec<Box<[u8]>> = raw_tools.iter().map(|(name, _)| name.as_bytes().into()).collect();
        names.sort_unstable();
        names.dedup();
        let mask = !choice_none && !names.is_empty();
        let header_cap = names.iter().map(|n| n.len()).max().unwrap_or(0).max(UNCONSTRAINED_HEADER_CAP);
        let mut tools = Vec::with_capacity(raw_tools.len());
        for (name, params) in raw_tools {
            if arena.schemas.len() + 2 >= MAX_SCHEMAS {
                arena.note_over_limit(schemas_over_limit());
                break;
            }
            let args_schema = params
                .map(|p| arena.compile_object_schema(p, 0))
                .unwrap_or(NO_SCHEMA);
            let wrapper_schema = arena.build_tool_wrapper_schema(Some(&name), args_schema);
            tools.push(ToolEntry {
                name,
                wrapper_schema,
            });
        }
        let fallback_wrapper_schema = if tools.len() == 1 {
            tools[0].wrapper_schema
        } else {
            arena.build_tool_wrapper_schema(None, NO_SCHEMA)
        };
        // The first declaration of a name keeps its schema, as the header lookup always chose it.
        let mut name_wrappers = vec![NO_SCHEMA; names.len()];
        for entry in &tools {
            if let Ok(i) = names.binary_search_by(|n| (**n).cmp(entry.name.as_bytes())) {
                if name_wrappers[i] == NO_SCHEMA {
                    name_wrappers[i] = entry.wrapper_schema;
                }
            }
        }
        Some(Arc::new(Self {
            arena,
            fallback_wrapper_schema,
            names,
            name_wrappers,
            mask,
            header_cap,
        }))
    }

    /// The position of `name` among the offered names: a binary search.
    fn find(&self, name: &[u8]) -> Option<usize> {
        self.names
            .binary_search_by(|n| {
                name_probe();
                (**n).cmp(name)
            })
            .ok()
    }

    /// Whether the request offered a tool spelled exactly `name`.
    pub fn offers(&self, name: &[u8]) -> bool {
        self.find(name).is_some()
    }

    /// In `names[lo..hi]`, which all share their first `pos` bytes: the first name whose bytes from `pos` are
    /// not below `bytes`. The names that continue with `bytes` start there, if there are any.
    fn lower(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> usize {
        lo + self.names[lo..hi].partition_point(|n| {
            name_probe();
            &n[pos..] < bytes
        })
    }

    /// The part of `names[lo..hi]` (sharing `pos` bytes) whose names continue with `bytes`: two binary searches.
    fn narrow(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> (usize, usize) {
        let start = self.lower(lo, hi, pos, bytes);
        let end = start
            + self.names[start..hi].partition_point(|n| {
                name_probe();
                n[pos..].starts_with(bytes)
            });
        (start, end)
    }

    /// Whether some name in `names[lo..hi]` (sharing `pos` bytes) continues with `bytes`: one binary search.
    fn continues(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> bool {
        let start = self.lower(lo, hi, pos, bytes);
        start < hi && self.names[start][pos..].starts_with(bytes)
    }
}

#[inline]
fn is_json_ws(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

#[inline]
fn hex_nibble(b: u8) -> Option<u16> {
    match b {
        b'0'..=b'9' => Some((b - b'0') as u16),
        b'a'..=b'f' => Some((b - b'a' + 10) as u16),
        b'A'..=b'F' => Some((b - b'A' + 10) as u16),
        _ => None,
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EscState {
    None,
    Backslash,
    Hex { digits: u8, val: u16, after_high: bool },
    NeedLowBackslash,
    NeedLowU,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StrSubState {
    utf8_need: u8,
    utf8_first_min: u8,
    utf8_first_max: u8,
    esc: EscState,
    byte_len: u32,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrStep {
    Continue,
    Closed,
    Invalid,
}

impl StrSubState {
    const fn new() -> Self {
        Self {
            utf8_need: 0,
            utf8_first_min: 0x80,
            utf8_first_max: 0xBF,
            esc: EscState::None,
            byte_len: 0,
        }
    }

    #[inline]
    fn step(&mut self, b: u8, max_bytes: u32) -> StrStep {
        if self.utf8_need > 0 {
            if b < self.utf8_first_min || b > self.utf8_first_max {
                return StrStep::Invalid;
            }
            self.utf8_need -= 1;
            self.utf8_first_min = 0x80;
            self.utf8_first_max = 0xBF;
            self.byte_len = self.byte_len.saturating_add(1);
            return StrStep::Continue;
        }

        match self.esc {
            EscState::None => {
                if b == b'"' {
                    return StrStep::Closed;
                }
                if self.byte_len >= max_bytes {
                    return StrStep::Invalid;
                }
                if b == b'\\' {
                    self.esc = EscState::Backslash;
                    self.byte_len = self.byte_len.saturating_add(1);
                    return StrStep::Continue;
                }
                if b < 0x20 {
                    // Unescaped U+0000..=U+001F control characters are forbidden by RFC 8259 §7.
                    return StrStep::Invalid;
                }
                if b < 0x80 {
                    self.byte_len = self.byte_len.saturating_add(1);
                    return StrStep::Continue;
                }
                // RFC 3629 multi-byte UTF-8 lead byte validation.
                match b {
                    0xC2..=0xDF => {
                        self.utf8_need = 1;
                        self.utf8_first_min = 0x80;
                        self.utf8_first_max = 0xBF;
                    }
                    0xE0 => {
                        self.utf8_need = 2;
                        self.utf8_first_min = 0xA0;
                        self.utf8_first_max = 0xBF;
                    }
                    0xE1..=0xEC | 0xEE..=0xEF => {
                        self.utf8_need = 2;
                        self.utf8_first_min = 0x80;
                        self.utf8_first_max = 0xBF;
                    }
                    0xED => {
                        // Exclude UTF-16 surrogates U+D800..=U+DFFF (ED A0..=BF).
                        self.utf8_need = 2;
                        self.utf8_first_min = 0x80;
                        self.utf8_first_max = 0x9F;
                    }
                    0xF0 => {
                        self.utf8_need = 3;
                        self.utf8_first_min = 0x90;
                        self.utf8_first_max = 0xBF;
                    }
                    0xF1..=0xF3 => {
                        self.utf8_need = 3;
                        self.utf8_first_min = 0x80;
                        self.utf8_first_max = 0xBF;
                    }
                    0xF4 => {
                        // Exclude > U+10FFFF (F4 90..=BF).
                        self.utf8_need = 3;
                        self.utf8_first_min = 0x80;
                        self.utf8_first_max = 0x8F;
                    }
                    _ => return StrStep::Invalid,
                }
                self.byte_len = self.byte_len.saturating_add(1);
                StrStep::Continue
            }
            EscState::Backslash => {
                self.byte_len = self.byte_len.saturating_add(1);
                match b {
                    b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {
                        self.esc = EscState::None;
                        StrStep::Continue
                    }
                    b'u' => {
                        self.esc = EscState::Hex {
                            digits: 0,
                            val: 0,
                            after_high: false,
                        };
                        StrStep::Continue
                    }
                    _ => StrStep::Invalid,
                }
            }
            EscState::Hex {
                digits,
                val,
                after_high,
            } => {
                let Some(nib) = hex_nibble(b) else {
                    return StrStep::Invalid;
                };
                // Reject lone low surrogates (0xDC00..=0xDFFF when !after_high) and non-low
                // surrogates (outside 0xDC00..=0xDFFF when after_high) at the earliest hex digit
                // so no partial prefix ever reaches a dead end.
                if after_high {
                    if digits == 0 && nib != 0xD {
                        return StrStep::Invalid;
                    }
                    if digits == 1 && nib < 0xC {
                        return StrStep::Invalid;
                    }
                } else if digits == 1 && val == 0xD && nib >= 0xC {
                    return StrStep::Invalid;
                }
                let next_val = (val << 4) | nib;
                let next_digits = digits + 1;
                self.byte_len = self.byte_len.saturating_add(1);
                if next_digits == 4 {
                    if !after_high && (0xD800..=0xDBFF).contains(&next_val) {
                        self.esc = EscState::NeedLowBackslash;
                    } else {
                        self.esc = EscState::None;
                    }
                } else {
                    self.esc = EscState::Hex {
                        digits: next_digits,
                        val: next_val,
                        after_high,
                    };
                }
                StrStep::Continue
            }
            EscState::NeedLowBackslash => {
                if b != b'\\' {
                    return StrStep::Invalid;
                }
                self.byte_len = self.byte_len.saturating_add(1);
                self.esc = EscState::NeedLowU;
                StrStep::Continue
            }
            EscState::NeedLowU => {
                if b != b'u' {
                    return StrStep::Invalid;
                }
                self.byte_len = self.byte_len.saturating_add(1);
                self.esc = EscState::Hex {
                    digits: 0,
                    val: 0,
                    after_high: true,
                };
                StrStep::Continue
            }
        }
    }
}

/// The grammar never masks a digit to keep a number small: masking the digit the model wanted makes it write
/// something else, and the number silently becomes a different number. It lets a number run until a part
/// reaches its cap below, and only then makes the number close; [`read_call_body`] refuses every literal that
/// reached a cap (it may have been cut there) and every literal serde_json would not read exactly, so such a
/// call goes out as `{"_unparsed": ...}` and is counted in `tool_call_parse_fallback`.
///
/// Integer-part digits: 21. Every 20-digit integer above `u64::MAX` and every 21-digit one is out of range,
/// so a cut integer is refused by value anyway.
const NUM_INT_DIGITS_CAP: u8 = 21;
/// Fraction digits: a literal with 32 is accepted, one with 33 was possibly cut and is refused.
const NUM_FRAC_DIGITS_CAP: u8 = 33;
/// Exponent digits (leading zeros count): 4 are accepted (`1e-0308`), 5 were possibly cut and are refused.
const NUM_EXP_DIGITS_CAP: u8 = 5;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NumStage {
    Sign,
    Zero,
    Int { digits: u8 },
    FracNeedDigit,
    Frac { digits: u8 },
    ExpSignOrDigit,
    ExpNeedDigit,
    Exp { digits: u8 },
}

impl NumStage {
    #[inline]
    fn is_complete(self) -> bool {
        matches!(
            self,
            Self::Zero | Self::Int { .. } | Self::Frac { .. } | Self::Exp { .. }
        )
    }

    /// An `integer` field takes the same syntax as a `number` field: refusing `.` or `e` there would turn
    /// `1.5e3` into `1`. A non-integer reaches the client as written, where its type check sees it.
    /// At a cap the part takes nothing more, so the number can only close (and is then refused, see above).
    #[inline]
    fn step_digit_or_part(&mut self, b: u8) -> bool {
        let next = match *self {
            Self::Sign => match b {
                // `read_call_body` sends `-0` as `0`: an integer field gets an integer.
                b'0' => Some(Self::Zero),
                b'1'..=b'9' => Some(Self::Int { digits: 1 }),
                _ => None,
            },
            Self::Zero => match b {
                b'.' => Some(Self::FracNeedDigit),
                b'e' | b'E' => Some(Self::ExpSignOrDigit),
                _ => None,
            },
            Self::Int { digits } if digits < NUM_INT_DIGITS_CAP => match b {
                b'0'..=b'9' => Some(Self::Int { digits: digits + 1 }),
                b'.' => Some(Self::FracNeedDigit),
                b'e' | b'E' => Some(Self::ExpSignOrDigit),
                _ => None,
            },
            Self::FracNeedDigit => b.is_ascii_digit().then_some(Self::Frac { digits: 1 }),
            Self::Frac { digits } if digits < NUM_FRAC_DIGITS_CAP => match b {
                b'0'..=b'9' => Some(Self::Frac { digits: digits + 1 }),
                b'e' | b'E' => Some(Self::ExpSignOrDigit),
                _ => None,
            },
            Self::ExpSignOrDigit => match b {
                b'+' | b'-' => Some(Self::ExpNeedDigit),
                b'0'..=b'9' => Some(Self::Exp { digits: 1 }),
                _ => None,
            },
            Self::ExpNeedDigit => b.is_ascii_digit().then_some(Self::Exp { digits: 1 }),
            Self::Exp { digits } if digits < NUM_EXP_DIGITS_CAP => {
                b.is_ascii_digit().then_some(Self::Exp { digits: digits + 1 })
            }
            Self::Int { .. } | Self::Frac { .. } | Self::Exp { .. } => None,
        };
        match next {
            Some(stage) => {
                *self = stage;
                true
            }
            None => false,
        }
    }
}

/// Whether serde_json reads the number literal `lit` exactly as written: an integer (no `.`, `e` or `E`) only
/// when it fits `i64` (negative) or `u64` (otherwise), since serde_json reads a larger one as a rounded `f64`;
/// any other literal only when it is finite, a nonzero literal does not read as `0.0` (underflow), and
/// serde_json's `f64` is the correctly rounded value of the literal (`str::parse`). A literal with a part at its
/// cap is refused too: the grammar may have cut it there. `-0` (integer syntax) is exact: it is sent as `0`.
fn number_reads_exactly(lit: &str) -> bool {
    let b = lit.as_bytes();
    let body = b.strip_prefix(b"-").unwrap_or(b);
    let int_len = body.iter().take_while(|c| c.is_ascii_digit()).count();
    let rest = &body[int_len..];
    let (frac_len, rest) = match rest.strip_prefix(b".") {
        Some(r) => {
            let n = r.iter().take_while(|c| c.is_ascii_digit()).count();
            (Some(n), &r[n..])
        }
        None => (None, rest),
    };
    let exp_len = match rest.first() {
        Some(b'e' | b'E') => {
            let r = rest[1..].strip_prefix(b"+").or_else(|| rest[1..].strip_prefix(b"-")).unwrap_or(&rest[1..]);
            let n = r.iter().take_while(|c| c.is_ascii_digit()).count();
            if n != r.len() {
                return false;
            }
            Some(n)
        }
        Some(_) => return false,
        None => None,
    };
    let well_formed = int_len > 0
        && (int_len == 1 || body[0] != b'0')
        && frac_len != Some(0)
        && exp_len != Some(0);
    if !well_formed
        || int_len >= usize::from(NUM_INT_DIGITS_CAP)
        || frac_len.unwrap_or(0) >= usize::from(NUM_FRAC_DIGITS_CAP)
        || exp_len.unwrap_or(0) >= usize::from(NUM_EXP_DIGITS_CAP)
    {
        return false;
    }
    if frac_len.is_none() && exp_len.is_none() {
        return if b[0] == b'-' { lit == "-0" || lit.parse::<i64>().is_ok() } else { lit.parse::<u64>().is_ok() };
    }
    let Ok(want) = lit.parse::<f64>() else {
        return false;
    };
    let mantissa_nonzero = body.iter().take_while(|c| !matches!(c, b'e' | b'E')).any(|c| matches!(c, b'1'..=b'9'));
    want.is_finite()
        && (want != 0.0 || !mantissa_nonzero)
        && serde_json::from_str::<f64>(lit).is_ok_and(|got| got.to_bits() == want.to_bits())
}

/// Reads a tool body as `serve::reply` sends it: `Value::Null` (the call goes out as `{"_unparsed": ...}` and is
/// counted in `tool_call_parse_fallback`) unless the body is JSON whose every number serde_json reads exactly
/// (see [`number_reads_exactly`]). A number is never sent changed: rounded, cut or rescaled.
pub fn read_call_body(body: &str) -> Value {
    let b = body.as_bytes();
    let mut minus_zero: Vec<usize> = Vec::new();
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'"' => {
                i += 1;
                while i < b.len() && b[i] != b'"' {
                    i += if b[i] == b'\\' { 2 } else { 1 };
                }
                i += 1;
            }
            b'-' | b'0'..=b'9' => {
                let start = i;
                while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
                    i += 1;
                }
                let lit = &body[start..i];
                if !number_reads_exactly(lit) {
                    return Value::Null;
                }
                if lit == "-0" {
                    minus_zero.push(start);
                }
            }
            _ => i += 1,
        }
    }
    let parsed = if minus_zero.is_empty() {
        serde_json::from_str(body)
    } else {
        // serde_json reads `-0` as the float `-0.0`; an integer has no negative zero, so it is sent as `0`.
        let mut fixed = b.to_vec();
        for at in minus_zero {
            fixed[at] = b' ';
        }
        serde_json::from_slice(&fixed)
    };
    parsed.unwrap_or(Value::Null)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Frame {
    Empty,
    Obj {
        schema_idx: u16,
        seen_mask: u64,
        items: u16,
    },
    Arr {
        items: u16,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum KeyMode {
    Restricted {
        schema_idx: u16,
        cand_mask: u64,
        pos: u16,
    },
    Free {
        schema_idx: u16,
        cand_mask: u64,
        pos: u16,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrMode {
    Free,
    Fixed { fixed_str: u16, pos: u16 },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Phase {
    BeforeRoot,
    ObjExpectKeyOrEnd,
    ObjExpectKey,
    InKey(KeyMode),
    ObjExpectColon(PropValueSpec),
    ExpectValue(PropValueSpec),
    ArrExpectValOrEnd,
    ArrExpectVal,
    InString(StrMode),
    InNumber(NumStage),
    InLit { target: [u8; 5], len: u8, pos: u8 },
    AfterValue,
    Complete,
}

#[derive(Clone, Copy, Debug)]
struct AutoState {
    phase: Phase,
    stack: [Frame; MAX_DEPTH_CAP],
    depth: u8,
    str_sub: StrSubState,
    root_schema: u16,
    ws_run: u8,
}

impl AutoState {
    fn new(root_schema: u16) -> Self {
        Self {
            phase: Phase::BeforeRoot,
            stack: [Frame::Empty; MAX_DEPTH_CAP],
            depth: 0,
            str_sub: StrSubState::new(),
            root_schema,
            ws_run: 0,
        }
    }

    #[inline]
    fn accept_ws(&mut self, limits: GrammarLimits) -> bool {
        if self.ws_run >= limits.max_ws_run {
            false
        } else {
            self.ws_run += 1;
            true
        }
    }

    #[inline]
    fn is_complete(&self) -> bool {
        matches!(self.phase, Phase::Complete)
    }

    #[inline]
    fn top(&self) -> Frame {
        self.stack[(self.depth - 1) as usize]
    }

    #[inline]
    fn top_mut(&mut self) -> &mut Frame {
        &mut self.stack[(self.depth - 1) as usize]
    }

    fn push_obj(&mut self, schema_idx: u16, arena: &SchemaArena) -> bool {
        if self.depth as usize >= MAX_DEPTH_CAP {
            return false;
        }
        self.stack[self.depth as usize] = Frame::Obj {
            schema_idx,
            seen_mask: 0,
            items: 0,
        };
        self.depth += 1;
        let has_req = schema_idx != NO_SCHEMA
            && !arena.schemas[schema_idx as usize].required_satisfied(0);
        self.phase = if has_req {
            Phase::ObjExpectKey
        } else {
            Phase::ObjExpectKeyOrEnd
        };
        true
    }

    fn push_arr(&mut self) -> bool {
        if self.depth as usize >= MAX_DEPTH_CAP {
            return false;
        }
        self.stack[self.depth as usize] = Frame::Arr { items: 0 };
        self.depth += 1;
        self.phase = Phase::ArrExpectValOrEnd;
        true
    }

    fn pop_container(&mut self) {
        self.depth -= 1;
        self.stack[self.depth as usize] = Frame::Empty;
        if self.depth == 0 {
            self.phase = Phase::Complete;
        } else {
            self.phase = Phase::AfterValue;
        }
    }

    fn begin_key(&mut self, arena: &SchemaArena) -> bool {
        let Frame::Obj {
            schema_idx,
            seen_mask,
            items,
        } = self.top()
        else {
            return false;
        };
        let next_items = items.saturating_add(1);
        *self.top_mut() = Frame::Obj {
            schema_idx,
            seen_mask,
            items: next_items,
        };
        self.str_sub = StrSubState::new();
        if schema_idx == NO_SCHEMA {
            self.phase = Phase::InKey(KeyMode::Free {
                schema_idx: NO_SCHEMA,
                cand_mask: 0,
                pos: 0,
            });
            return true;
        }
        let schema = &arena.schemas[schema_idx as usize];
        let unseen = schema.unseen_mask(seen_mask);
        if !schema.required_satisfied(seen_mask) || !schema.allow_additional {
            if unseen == 0 {
                return false;
            }
            self.phase = Phase::InKey(KeyMode::Restricted {
                schema_idx,
                cand_mask: unseen,
                pos: 0,
            });
            true
        } else {
            self.phase = Phase::InKey(KeyMode::Free {
                schema_idx,
                cand_mask: unseen,
                pos: 0,
            });
            true
        }
    }

    fn start_value(&mut self, b: u8, mut spec: PropValueSpec, arena: &SchemaArena, limits: GrammarLimits) -> bool {
        if is_json_ws(b) {
            return self.accept_ws(limits);
        }
        self.ws_run = 0;
        if self.depth >= limits.max_depth {
            spec.mask = spec.mask.without_containers_if_possible();
        }
        match b {
            b'{' if spec.mask.contains(TypeMask::OBJ) => self.push_obj(spec.nested_schema, arena),
            b'[' if spec.mask.contains(TypeMask::ARR) => self.push_arr(),
            b'"' if spec.mask.contains(TypeMask::STR) => {
                self.str_sub = StrSubState::new();
                if spec.fixed_str != NO_FIXED_STR {
                    self.phase = Phase::InString(StrMode::Fixed {
                        fixed_str: spec.fixed_str,
                        pos: 0,
                    });
                } else {
                    self.phase = Phase::InString(StrMode::Free);
                }
                true
            }
            b'-' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
                self.phase = Phase::InNumber(NumStage::Sign);
                true
            }
            b'0' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
                self.phase = Phase::InNumber(NumStage::Zero);
                true
            }
            b'1'..=b'9' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
                self.phase = Phase::InNumber(NumStage::Int { digits: 1 });
                true
            }
            b't' if spec.mask.contains(TypeMask::BOOL) => {
                self.phase = Phase::InLit {
                    target: *b"true\0",
                    len: 4,
                    pos: 1,
                };
                true
            }
            b'f' if spec.mask.contains(TypeMask::BOOL) => {
                self.phase = Phase::InLit {
                    target: *b"false",
                    len: 5,
                    pos: 1,
                };
                true
            }
            b'n' if spec.mask.contains(TypeMask::NULL) => {
                self.phase = Phase::InLit {
                    target: *b"null\0",
                    len: 4,
                    pos: 1,
                };
                true
            }
            _ => false,
        }
    }

    fn step_after_value(&mut self, b: u8, arena: &SchemaArena, limits: GrammarLimits) -> bool {
        if is_json_ws(b) {
            return self.accept_ws(limits);
        }
        self.ws_run = 0;
        match self.top() {
            Frame::Obj {
                schema_idx,
                seen_mask,
                items,
            } => {
                let (req_ok, more_ok) = if schema_idx == NO_SCHEMA {
                    (true, items < limits.max_container_items)
                } else {
                    let s = &arena.schemas[schema_idx as usize];
                    let req_sat = s.required_satisfied(seen_mask);
                    let more = if !req_sat {
                        s.unseen_mask(seen_mask) != 0
                    } else {
                        items < limits.max_container_items && s.can_add_more_keys(seen_mask)
                    };
                    (req_sat, more)
                };
                match b {
                    b',' if more_ok => {
                        self.phase = Phase::ObjExpectKey;
                        true
                    }
                    b'}' if req_ok => {
                        self.pop_container();
                        true
                    }
                    _ => false,
                }
            }
            Frame::Arr { items } => match b {
                b',' if items < limits.max_container_items => {
                    self.phase = Phase::ArrExpectVal;
                    true
                }
                b']' => {
                    self.pop_container();
                    true
                }
                _ => false,
            },
            Frame::Empty => false,
        }
    }

    fn step_byte(&mut self, b: u8, arena: &SchemaArena, limits: GrammarLimits) -> bool {
        match self.phase {
            Phase::BeforeRoot => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                if b == b'{' {
                    self.ws_run = 0;
                    return self.push_obj(self.root_schema, arena);
                }
                false
            }
            Phase::ObjExpectKeyOrEnd => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                self.ws_run = 0;
                if b == b'}' {
                    let Frame::Obj {
                        schema_idx,
                        seen_mask,
                        ..
                    } = self.top()
                    else {
                        return false;
                    };
                    if schema_idx != NO_SCHEMA
                        && !arena.schemas[schema_idx as usize].required_satisfied(seen_mask)
                    {
                        return false;
                    }
                    self.pop_container();
                    return true;
                }
                if b == b'"' {
                    let can_key = match self.top() {
                        Frame::Obj {
                            schema_idx,
                            seen_mask,
                            items,
                        } => {
                            items < limits.max_container_items
                                && (schema_idx == NO_SCHEMA
                                    || arena.schemas[schema_idx as usize].can_add_more_keys(seen_mask))
                        }
                        _ => false,
                    };
                    return can_key && self.begin_key(arena);
                }
                false
            }
            Phase::ObjExpectKey => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                if b == b'"' {
                    self.ws_run = 0;
                    return self.begin_key(arena);
                }
                false
            }
            Phase::InKey(mode) => match mode {
                KeyMode::Restricted {
                    schema_idx,
                    cand_mask,
                    pos,
                } => {
                    let schema = &arena.schemas[schema_idx as usize];
                    let pos_usize = pos as usize;
                    if b == b'"' {
                        let mut matched_idx: Option<usize> = None;
                        let mut m = cand_mask;
                        while m != 0 {
                            let j = m.trailing_zeros() as usize;
                            m &= m - 1;
                            if schema.props[j].escaped.len() == pos_usize {
                                matched_idx = Some(j);
                                break;
                            }
                        }
                        if let Some(j) = matched_idx {
                            if let Frame::Obj { seen_mask, .. } = self.top_mut() {
                                *seen_mask |= 1u64 << j;
                            }
                            self.phase = Phase::ObjExpectColon(schema.props[j].spec);
                            return true;
                        }
                    }
                    let mut next_mask = 0u64;
                    let mut m = cand_mask;
                    while m != 0 {
                        let j = m.trailing_zeros() as usize;
                        m &= m - 1;
                        if schema.props[j].escaped.get(pos_usize) == Some(&b) {
                            next_mask |= 1u64 << j;
                        }
                    }
                    if next_mask == 0 || pos == u16::MAX {
                        return false;
                    }
                    self.phase = Phase::InKey(KeyMode::Restricted {
                        schema_idx,
                        cand_mask: next_mask,
                        pos: pos + 1,
                    });
                    true
                }
                KeyMode::Free {
                    schema_idx,
                    cand_mask,
                    pos,
                } => match self.str_sub.step(b, limits.max_string_bytes) {
                    StrStep::Invalid => false,
                    StrStep::Closed => {
                        let mut val_spec = PropValueSpec::any();
                        if schema_idx != NO_SCHEMA && cand_mask != 0 {
                            let schema = &arena.schemas[schema_idx as usize];
                            let pos_usize = pos as usize;
                            let mut m = cand_mask;
                            while m != 0 {
                                let j = m.trailing_zeros() as usize;
                                m &= m - 1;
                                if schema.props[j].escaped.len() == pos_usize {
                                    if let Frame::Obj { seen_mask, .. } = self.top_mut() {
                                        *seen_mask |= 1u64 << j;
                                    }
                                    val_spec = schema.props[j].spec;
                                    break;
                                }
                            }
                        }
                        self.phase = Phase::ObjExpectColon(val_spec);
                        true
                    }
                    StrStep::Continue => {
                        let mut next_mask = 0u64;
                        if schema_idx != NO_SCHEMA && cand_mask != 0 && (pos as usize) < usize::from(u16::MAX) {
                            let schema = &arena.schemas[schema_idx as usize];
                            let pos_usize = pos as usize;
                            let mut m = cand_mask;
                            while m != 0 {
                                let j = m.trailing_zeros() as usize;
                                m &= m - 1;
                                if schema.props[j].escaped.get(pos_usize) == Some(&b) {
                                    next_mask |= 1u64 << j;
                                }
                            }
                        }
                        self.phase = Phase::InKey(KeyMode::Free {
                            schema_idx,
                            cand_mask: next_mask,
                            pos: pos.saturating_add(1),
                        });
                        true
                    }
                },
            },
            Phase::ObjExpectColon(spec) => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                if b == b':' {
                    self.ws_run = 0;
                    self.phase = Phase::ExpectValue(spec);
                    return true;
                }
                false
            }
            Phase::ExpectValue(spec) => self.start_value(b, spec, arena, limits),
            Phase::ArrExpectValOrEnd => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                self.ws_run = 0;
                if b == b']' {
                    self.pop_container();
                    return true;
                }
                if let Frame::Arr { items } = self.top_mut() {
                    if *items >= limits.max_container_items {
                        return false;
                    }
                    *items += 1;
                }
                self.start_value(b, PropValueSpec::any(), arena, limits)
            }
            Phase::ArrExpectVal => {
                if is_json_ws(b) {
                    return self.accept_ws(limits);
                }
                self.ws_run = 0;
                if let Frame::Arr { items } = self.top_mut() {
                    *items = items.saturating_add(1);
                }
                self.start_value(b, PropValueSpec::any(), arena, limits)
            }
            Phase::InString(mode) => match mode {
                StrMode::Free => match self.str_sub.step(b, limits.max_string_bytes) {
                    StrStep::Continue => true,
                    StrStep::Closed => {
                        self.phase = Phase::AfterValue;
                        true
                    }
                    StrStep::Invalid => false,
                },
                StrMode::Fixed { fixed_str, pos } => {
                    let target = &arena.fixed_strings[fixed_str as usize];
                    let pos_usize = pos as usize;
                    if pos_usize == target.len() {
                        if b == b'"' {
                            self.phase = Phase::AfterValue;
                            true
                        } else {
                            false
                        }
                    } else if target[pos_usize] == b {
                        self.phase = Phase::InString(StrMode::Fixed {
                            fixed_str,
                            pos: pos + 1,
                        });
                        true
                    } else {
                        false
                    }
                }
            },
            Phase::InNumber(mut stage) => {
                if stage.step_digit_or_part(b) {
                    self.phase = Phase::InNumber(stage);
                    return true;
                }
                if !stage.is_complete() {
                    return false;
                }
                self.phase = Phase::AfterValue;
                self.step_after_value(b, arena, limits)
            }
            Phase::InLit { target, len, pos } => {
                if target[pos as usize] != b {
                    return false;
                }
                if pos + 1 == len {
                    self.phase = Phase::AfterValue;
                } else {
                    self.phase = Phase::InLit {
                        target,
                        len,
                        pos: pos + 1,
                    };
                }
                true
            }
            Phase::AfterValue => self.step_after_value(b, arena, limits),
            Phase::Complete => {
                if is_json_ws(b) {
                    self.accept_ws(limits)
                } else {
                    false
                }
            }
        }
    }
}

/// Standalone byte-level JSON object pushdown grammar (root `{ ... }` with optional schema).
#[cfg(test)]
#[derive(Clone, Debug)]
pub struct JsonObjectGrammar {
    arena: Arc<SchemaArena>,
    state: AutoState,
    limits: GrammarLimits,
}

#[cfg(test)]
impl JsonObjectGrammar {
    pub fn new() -> Self {
        Self {
            arena: Arc::new(SchemaArena::default()),
            state: AutoState::new(NO_SCHEMA),
            limits: GrammarLimits::DEFAULT,
        }
    }

    pub fn with_schema(schema: &Value) -> Self {
        let mut arena = SchemaArena::default();
        let root = arena.compile_object_schema(schema, 0);
        Self {
            arena: Arc::new(arena),
            state: AutoState::new(root),
            limits: GrammarLimits::DEFAULT,
        }
    }

    pub fn with_limits(mut self, limits: GrammarLimits) -> Self {
        self.limits = limits;
        self
    }

    #[inline]
    pub fn is_complete(&self) -> bool {
        self.state.is_complete()
    }

    #[inline]
    pub fn accepts_bytes(&self, bytes: &[u8]) -> bool {
        let mut next = self.state;
        for &b in bytes {
            if !next.step_byte(b, &self.arena, self.limits) {
                return false;
            }
        }
        true
    }

    #[inline]
    pub fn advance_bytes(&mut self, bytes: &[u8]) -> bool {
        let mut next = self.state;
        for &b in bytes {
            if !next.step_byte(b, &self.arena, self.limits) {
                return false;
            }
        }
        self.state = next;
        true
    }
}

// Inline `Copy` state avoids heap allocation per candidate token during masked sampling.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug)]
enum SpanMode {
    Idle,
    Header,
    Json(AutoState),
}

/// Per-lane tool-call span tracker & JSON pushdown mask.
///
/// Tracks `<|message_model|><tool_name><|content_invoke_tool_json|>` -> activates [`AutoState`]
/// over the JSON body -> permits `<|end_message|>` (`end_tok`) ONLY once the root `{...}` object
/// is balanced and complete -> returns to `Idle` after `<|end_message|>`.
#[derive(Clone, Debug)]
pub struct ToolCallGrammar {
    catalog: Arc<ToolCatalog>,
    header_buf: Vec<u8>,
    dynamic_arena: Option<SchemaArena>,
    mode: SpanMode,
    limits: GrammarLimits,
    /// The special tokens the masks and the marker rewrite need: given at construction (`with_marks`) and by
    /// every `observe_token` call.
    marks: Option<SpanMarks>,
    /// In a masked header: the range of `catalog.names` that `header_buf` is a prefix of (empty once it is no
    /// name's prefix, which only a token forced past the mask can cause).
    hdr: (u32, u32),
    /// Idle inside an open text or thinking message (after its content marker, before its end).
    body_open: bool,
    /// Masked header draws (`note_header_draw`), and those whose unmasked top token the mask refused.
    header_draws: u64,
    header_masked: u64,
    /// Tool markers drawn away from an exactly offered header and rewritten (`committed_token`).
    marker_rewrites: u64,
}

/// The special tokens a tool-call span is made of.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpanMarks {
    pub msg_model: u32,
    pub c_think: u32,
    pub c_text: u32,
    pub c_tool: u32,
    pub end: u32,
}

impl ToolCallGrammar {
    pub fn new(catalog: Arc<ToolCatalog>) -> Self {
        Self {
            catalog,
            header_buf: Vec::with_capacity(64),
            dynamic_arena: None,
            mode: SpanMode::Idle,
            limits: GrammarLimits::DEFAULT,
            marks: None,
            hdr: (0, 0),
            body_open: false,
            header_draws: 0,
            header_masked: 0,
            marker_rewrites: 0,
        }
    }

    /// The span's special tokens, so the tool marker is masked from the first generated token on (before any
    /// `observe_token` call has named them).
    pub fn with_marks(mut self, marks: SpanMarks) -> Self {
        self.marks = Some(marks);
        self
    }

    #[cfg(test)]
    pub fn with_limits(mut self, limits: GrammarLimits) -> Self {
        self.limits = limits;
        self
    }

    /// True while the lane is actively generating tokens inside `<|content_invoke_tool_json|> ... <|end_message|>`.
    #[inline]
    pub fn is_in_json(&self) -> bool {
        matches!(self.mode, SpanMode::Json(_))
    }

    /// True in a masked model message header: between `<|message_model|>` and its content marker, in a request
    /// that offered tools.
    #[inline]
    pub fn is_in_masked_header(&self) -> bool {
        self.catalog.mask && matches!(self.mode, SpanMode::Header)
    }

    /// True while every next token is masked: inside a tool-call JSON body or a masked header. A lane in this
    /// state must sample through `allows_token` (no GPU Gumbel draw, no DSpark draft).
    ///
    /// Elsewhere a request with tools refuses one token, the tool marker. That does not make the lane
    /// constrained: the paths that filter apply it for free, and `committed_token` covers the ones that do not.
    #[inline]
    pub fn is_constrained(&self) -> bool {
        self.is_in_json() || self.is_in_masked_header()
    }

    /// Masked header draws so far: the denominator of [`Self::header_masked`].
    #[inline]
    pub fn header_draws(&self) -> u64 {
        self.header_draws
    }

    /// Header draws so far whose unmasked top token the header mask refused: how often the model reached for a
    /// tool the request never offered (or another header the template does not write).
    #[inline]
    pub fn header_masked(&self) -> u64 {
        self.header_masked
    }

    /// Tool markers so far that a path without a mask drew away from an exactly offered header.
    #[inline]
    pub fn marker_rewrites(&self) -> u64 {
        self.marker_rewrites
    }

    /// Count a masked header draw; `top_refused`: the token the draw would have picked first with no grammar
    /// (the row's argmax among tokens not banned for other reasons) is one the mask refuses. Does nothing
    /// outside a masked header.
    pub fn note_header_draw(&mut self, top_refused: bool) {
        if self.is_in_masked_header() {
            self.header_draws += 1;
            self.header_masked += u64::from(top_refused);
        }
    }

    /// The header so far is exactly an offered name (masked catalogs).
    fn header_is_offered_name(&self) -> bool {
        let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
        lo < hi && self.catalog.names[lo].len() == self.header_buf.len()
    }

    /// The token to commit when a draw produced `tok`: `tok` itself, except a tool marker that does not follow
    /// an exactly offered header in a request with tools. The masks already refuse that marker; this is for the
    /// paths that draw without one (GPU Gumbel, DSpark verify), so the marker cannot be committed by any path.
    ///
    /// The rewrite puts the turn back on the template: inside a text or thinking message the message ends
    /// (`<|end_message|>`); between messages the next one opens (`<|message_model|>`), whose masked header then
    /// names the tool. A header that is not an offered name (unreachable, a header is always masked) becomes a
    /// text message.
    pub fn committed_token(&mut self, tok: u32) -> u32 {
        let Some(m) = self.marks else { return tok };
        if tok != m.c_tool || !self.catalog.mask {
            return tok;
        }
        let to = match self.mode {
            SpanMode::Json(_) => return tok,
            SpanMode::Header if self.header_is_offered_name() => return tok,
            SpanMode::Header => m.c_text,
            SpanMode::Idle if self.body_open => m.end,
            SpanMode::Idle => m.msg_model,
        };
        self.marker_rewrites += 1;
        to
    }

    /// Header mask. After `<|message_model|>` the template writes either a content marker
    /// (`<|content_thinking|>` / `<|content_text|>`) or an offered tool name then `<|content_invoke_tool_json|>`.
    /// So: name bytes only while they stay a prefix of an offered name, the tool marker only on an exact
    /// name, a content marker only before any name byte, and no other special token.
    ///
    /// `hdr` is the range of the sorted names the header is a prefix of, so a candidate costs one binary search
    /// in that range, whatever the size of the catalog.
    fn header_allows(&self, token_id: u32, vocab: &VocabBytes) -> bool {
        let Some(m) = self.marks else { return true };
        let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
        let pos = self.header_buf.len();
        if token_id == m.c_tool {
            return self.header_is_offered_name();
        }
        if token_id == m.c_text || token_id == m.c_think {
            // A header that is no longer any name's prefix can only come from a token forced past the mask;
            // a content marker then keeps the turn alive.
            return pos == 0 || lo == hi;
        }
        let Some(bytes) = vocab.non_special_bytes(token_id) else {
            return false;
        };
        !bytes.is_empty() && lo < hi && self.catalog.continues(lo, hi, pos, bytes)
    }

    /// Outside a header or a JSON body: everything, except the tool marker in a request with tools. The marker
    /// is only reachable from an exactly offered header.
    #[inline]
    fn idle_allows(&self, token_id: u32) -> bool {
        !(self.catalog.mask && self.marks.is_some_and(|m| m.c_tool == token_id))
    }

    #[inline]
    fn active_arena(&self) -> &SchemaArena {
        self.dynamic_arena.as_ref().unwrap_or(&self.catalog.arena)
    }

    /// Whether `token_id` is syntactically/structurally valid at the current position.
    ///
    /// Uses precomputed `VocabBytes` class bitsets and first-byte pre-filters to resolve
    /// common accepts and rejects in O(1) without copying `AutoState` (~260 bytes).
    #[inline]
    pub fn allows_token(&self, token_id: u32, vocab: &VocabBytes, end_tok: u32) -> bool {
        let state = match &self.mode {
            SpanMode::Json(state) => state,
            SpanMode::Header if self.catalog.mask => return self.header_allows(token_id, vocab),
            SpanMode::Header => return true,
            SpanMode::Idle => return self.idle_allows(token_id),
        };
        if token_id == end_tok {
            return state.is_complete();
        }
        let Some(bytes) = vocab.non_special_bytes(token_id) else {
            return false;
        };
        if bytes.is_empty() {
            return false;
        }
        let arena = self.active_arena();
        let b0 = bytes[0];
        match state.phase {
            Phase::Complete => {
                return vocab.is_json_ws_token(token_id)
                    && (state.ws_run as usize) + bytes.len() <= (self.limits.max_ws_run as usize);
            }
            Phase::InString(StrMode::Free) | Phase::InKey(KeyMode::Free { .. }) => {
                if state.str_sub.utf8_need == 0 && state.str_sub.esc == EscState::None {
                    if vocab.is_str_interior(token_id)
                        && u64::from(state.str_sub.byte_len) + bytes.len() as u64
                            <= u64::from(self.limits.max_string_bytes)
                    {
                        return true;
                    }
                    if vocab.is_str_invalid_fresh(token_id) {
                        return false;
                    }
                }
            }
            Phase::BeforeRoot => {
                if !is_json_ws(b0) && b0 != b'{' {
                    return false;
                }
            }
            Phase::ObjExpectKeyOrEnd => {
                if !is_json_ws(b0) && b0 != b'}' && b0 != b'"' {
                    return false;
                }
            }
            Phase::ObjExpectKey => {
                if !is_json_ws(b0) && b0 != b'"' {
                    return false;
                }
            }
            Phase::ObjExpectColon(_) => {
                if !is_json_ws(b0) && b0 != b':' {
                    return false;
                }
            }
            Phase::AfterValue => {
                if !is_json_ws(b0) && !matches!(b0, b',' | b'}' | b']') {
                    return false;
                }
            }
            Phase::ExpectValue(_) | Phase::ArrExpectVal => {
                if !is_json_ws(b0)
                    && !matches!(b0, b'{' | b'[' | b'"' | b'-' | b'0'..=b'9' | b't' | b'f' | b'n')
                {
                    return false;
                }
            }
            Phase::ArrExpectValOrEnd => {
                if !is_json_ws(b0)
                    && !matches!(
                        b0,
                        b']' | b'{' | b'[' | b'"' | b'-' | b'0'..=b'9' | b't' | b'f' | b'n'
                    )
                {
                    return false;
                }
            }
            Phase::InLit { target, pos, .. } => {
                if b0 != target[pos as usize] {
                    return false;
                }
            }
            Phase::InString(StrMode::Fixed { fixed_str, pos }) => {
                let target = &arena.fixed_strings[fixed_str as usize];
                let expected = if (pos as usize) == target.len() {
                    b'"'
                } else {
                    target[pos as usize]
                };
                if b0 != expected {
                    return false;
                }
            }
            Phase::InNumber(stage) => {
                let mut probe = stage;
                if !probe.step_digit_or_part(b0)
                    && !(stage.is_complete()
                        && (is_json_ws(b0) || matches!(b0, b',' | b'}' | b']')))
                {
                    return false;
                }
            }
            Phase::InKey(KeyMode::Restricted {
                schema_idx,
                cand_mask,
                pos,
            }) => {
                if b0 != b'"' {
                    let schema = &arena.schemas[schema_idx as usize];
                    let pos_usize = pos as usize;
                    let mut m = cand_mask;
                    let mut any = false;
                    while m != 0 {
                        let j = m.trailing_zeros() as usize;
                        m &= m - 1;
                        if schema.props[j].escaped.get(pos_usize) == Some(&b0) {
                            any = true;
                            break;
                        }
                    }
                    if !any {
                        return false;
                    }
                }
            }
        }
        let mut next = *state;
        for &b in bytes {
            if !next.step_byte(b, arena, self.limits) {
                return false;
            }
        }
        true
    }

    #[cfg(test)]
    fn allows_token_ref(&self, token_id: u32, vocab: &VocabBytes, end_tok: u32) -> bool {
        let state = match &self.mode {
            SpanMode::Json(state) => state,
            SpanMode::Header if self.catalog.mask => return self.header_allows(token_id, vocab),
            SpanMode::Header => return true,
            SpanMode::Idle => return self.idle_allows(token_id),
        };
        if token_id == end_tok {
            return state.is_complete();
        }
        let Some(bytes) = vocab.non_special_bytes(token_id) else {
            return false;
        };
        if bytes.is_empty() {
            return false;
        }
        let arena = self.active_arena();
        let mut next = *state;
        for &b in bytes {
            if !next.step_byte(b, arena, self.limits) {
                return false;
            }
        }
        true
    }

    /// Advance the lane's span state with the emitted token `tok`.
    #[allow(clippy::too_many_arguments)]
    pub fn observe_token(
        &mut self,
        tok: u32,
        vocab: &VocabBytes,
        msg_model_tok: u32,
        c_think_tok: u32,
        c_text_tok: u32,
        c_tool_tok: u32,
        end_tok: u32,
        end_sampling_tok: u32,
        eos_tok: u32,
    ) {
        self.marks = Some(SpanMarks {
            msg_model: msg_model_tok,
            c_think: c_think_tok,
            c_text: c_text_tok,
            c_tool: c_tool_tok,
            end: end_tok,
        });
        if tok == msg_model_tok {
            self.header_buf.clear();
            self.dynamic_arena = None;
            self.mode = SpanMode::Header;
            self.hdr = (0, self.catalog.names.len() as u32);
            self.body_open = false;
            return;
        }
        if tok == c_think_tok
            || tok == c_text_tok
            || tok == end_tok
            || tok == end_sampling_tok
            || tok == eos_tok
        {
            self.header_buf.clear();
            self.dynamic_arena = None;
            self.mode = SpanMode::Idle;
            self.body_open = tok == c_think_tok || tok == c_text_tok;
            return;
        }
        if tok == c_tool_tok {
            self.dynamic_arena = None;
            self.body_open = false;
            let cat = Arc::clone(&self.catalog);
            // The offered tool the header names. Masked: the header is exactly its name, or names nothing.
            // Unmasked (`tool_choice: none`): the exact spelling first, so a name offered with surrounding
            // whitespace is matched as offered, then the header without its surrounding whitespace.
            let trimmed = std::str::from_utf8(&self.header_buf).map(str::trim).unwrap_or("");
            let named = if cat.mask {
                self.header_is_offered_name().then_some(self.hdr.0 as usize)
            } else {
                cat.find(&self.header_buf).or_else(|| cat.find(trimmed.as_bytes()))
            };
            // The body's `"name"` is fixed to `name`; its arguments are unchecked (no schema in the arena).
            let mut fixed_name_wrapper = |name: &str| {
                let mut dyn_arena = SchemaArena::default();
                let root = dyn_arena.build_tool_wrapper_schema(Some(name), NO_SCHEMA);
                self.dynamic_arena = Some(dyn_arena);
                root
            };
            let root_schema = match named {
                Some(i) if cat.name_wrappers[i] != NO_SCHEMA => cat.name_wrappers[i],
                // Offered, but its schema did not fit the arena.
                Some(i) => fixed_name_wrapper(std::str::from_utf8(&cat.names[i]).unwrap_or("")),
                None if !cat.mask && !trimmed.is_empty() => fixed_name_wrapper(trimmed),
                // No offered header. Masked: `committed_token` never lets the marker get here; were it to, the
                // wire binds the body by its own name or drops it (`bind_call`).
                None => {
                    debug_assert!(!cat.mask, "a tool marker was committed away from an offered header");
                    cat.fallback_wrapper_schema
                }
            };
            self.mode = SpanMode::Json(AutoState::new(root_schema));
            return;
        }
        match &mut self.mode {
            SpanMode::Idle => {}
            SpanMode::Header => {
                if let Some(bytes) = vocab.non_special_bytes(tok) {
                    if self.catalog.mask {
                        let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
                        if lo < hi {
                            let (lo, hi) = self.catalog.narrow(lo, hi, self.header_buf.len(), bytes);
                            self.hdr = (lo as u32, hi as u32);
                        }
                    }
                    if self.header_buf.len() + bytes.len() <= self.catalog.header_cap {
                        self.header_buf.extend_from_slice(bytes);
                    }
                }
            }
            SpanMode::Json(state) => {
                if let Some(bytes) = vocab.non_special_bytes(tok) {
                    let arena_ptr: *const SchemaArena =
                        self.dynamic_arena.as_ref().unwrap_or(&self.catalog.arena);
                    // SAFETY: `arena_ptr` borrows `self.dynamic_arena` or `self.catalog.arena`, neither
                    // of which is mutated while advancing `state` (`Copy`).
                    let arena = unsafe { &*arena_ptr };
                    let mut next = *state;
                    for &b in bytes {
                        let ok = next.step_byte(b, arena, self.limits);
                        debug_assert!(ok, "observed token violated active ToolCallGrammar");
                        if !ok {
                            break;
                        }
                    }
                    *state = next;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sampler::Sampler;
    use serde_json::json;

    #[test]
    fn accepts_valid_nested_json_escapes_surrogates_and_utf8_across_splits() {
        let valid = r#" {
            "str": "hello \"world\" \\ \/ \b\f\n\r\t \u0041 \uD83D\uDE80 café 日本語",
            "nums": [0, -0, 42, -17, 3.14159, -0.001, 1e9, 2.5E-4, -9e+12],
            "lits": [true, false, null],
            "nested": {"empty_obj": {}, "empty_arr": [], "deep": [{"k": "v"}]}
        } "#;
        let bytes = valid.as_bytes();
        // Verify full-slice acceptance AND arbitrary 1..3-byte chunk splits (including mid-UTF-8!).
        for step in [1usize, 2, 3, 5, 7] {
            let mut g = JsonObjectGrammar::new();
            for chunk in bytes.chunks(step) {
                assert!(!g.is_complete() || chunk.iter().all(|&b| is_json_ws(b)));
                assert!(g.advance_bytes(chunk), "rejected valid chunk {chunk:?} (step={step})");
            }
            assert!(g.is_complete(), "expected complete JSON at step={step}");
        }
        let parsed: Value = serde_json::from_str(valid).unwrap();
        assert_eq!(parsed["nested"]["deep"][0]["k"], "v");

        let schema = json!({"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]});
        let schema_g = JsonObjectGrammar::with_schema(&schema).with_limits(GrammarLimits::DEFAULT);
        assert!(schema_g.accepts_bytes(br#"{"a": 1}"#));
        assert!(!schema_g.accepts_bytes(br#"{"a": "bad"}"#));
    }

    #[test]
    fn rejects_malformed_json_and_invalid_utf8_or_surrogates() {
        let invalid_cases: &[(&str, &[u8])] = &[
            ("unquoted key", br#"{foo: 1}"#),
            ("single-quoted string", br#"{"a": 'hi'}"#),
            ("trailing comma in object", br#"{"a": 1,}"#),
            ("trailing comma in array", br#"{"a": [1, 2,]}"#),
            ("double comma", br#"{"a": [1,,2]}"#),
            ("leading zero integer", br#"{"a": 01}"#),
            ("negative leading zero", br#"{"a": -01}"#),
            ("bare decimal point", br#"{"a": .5}"#),
            ("trailing decimal point", br#"{"a": 1.}"#),
            ("incomplete exponent", br#"{"a": 1e}"#),
            ("raw newline in string", b"{\"a\": \"line1\nline2\"}"),
            ("raw nul in string", b"{\"a\": \"bad\x00\"}"),
            ("bad escape", br#"{"a": "\x41"}"#),
            ("lone low surrogate", br#"{"a": "\uDC00"}"#),
            ("high surrogate without low", br#"{"a": "\uD83Dx"}"#),
            ("high surrogate followed by high", br#"{"a": "\uD83D\uD83D"}"#),
            ("overlong utf8 C0", b"{\"a\": \"\xC0\xAF\"}"),
            ("surrogate utf8 ED A0 80", b"{\"a\": \"\xED\xA0\x80\"}"),
            ("out of range utf8 F4 90 80 80", b"{\"a\": \"\xF4\x90\x80\x80\"}"),
            ("root array instead of object", br#"[1, 2, 3]"#),
            ("extra brace after root", br#"{"a": 1}}"#),
            ("concatenated objects", br#"{"a": 1}{"b": 2}"#),
        ];

        for &(label, case) in invalid_cases {
            let mut g = JsonObjectGrammar::new();
            let accepted_all = g.advance_bytes(case);
            assert!(
                !accepted_all || !g.is_complete(),
                "grammar should reject {label}: {:?}",
                String::from_utf8_lossy(case)
            );
        }

        // Unclosed containers and truncated literals/numbers are never `is_complete()`.
        for incomplete in [
            br#"{"#.as_slice(),
            br#"{"a""#.as_slice(),
            br#"{"a":"#.as_slice(),
            br#"{"a": 1"#.as_slice(),
            br#"{"a": [1, 2"#.as_slice(),
            br#"{"a": tru"#.as_slice(),
            br#"{"a": 1."#.as_slice(),
        ] {
            let mut g = JsonObjectGrammar::new();
            assert!(g.advance_bytes(incomplete));
            assert!(!g.is_complete(), "unclosed input marked complete: {:?}", String::from_utf8_lossy(incomplete));
        }
    }

    #[test]
    fn enforces_tool_schema_required_keys_types_and_end_token_boundary() {
        let tk = Tokenizer::for_byte_test();
        let vocab = VocabBytes::from_tokenizer(&tk);
        let msg_model = tk.encode("<|message_model|>", true)[0];
        let c_think = tk.encode("<|content_thinking|>", true)[0];
        let c_text = tk.encode("<|content_text|>", true)[0];
        let c_tool = tk.encode("<|content_invoke_tool_json|>", true)[0];
        let end = tk.encode("<|end_message|>", true)[0];
        let end_sampling = tk.encode("<|content_model_end_sampling|>", true)[0];

        let req = json!({
            "tools": [{
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "city": {"type": "string"},
                            "days": {"type": "integer"}
                        },
                        "required": ["city"],
                        "additionalProperties": false
                    }
                }
            }]
        });
        let catalog = ToolCatalog::from_request(&req).unwrap();
        let mut g = ToolCallGrammar::new(catalog);
        assert!(!g.is_in_json());

        let step = |g: &mut ToolCallGrammar, tok: u32| {
            g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
        };

        step(&mut g, msg_model);
        for tok in tk.encode("get_weather", false) {
            step(&mut g, tok);
        }
        assert!(!g.is_in_json());
        step(&mut g, c_tool);
        assert!(g.is_in_json());
        assert!(!g.allows_token(end, &vocab, end), "premature <|end_message|> before JSON must be blocked");

        // Advance `{"name":"get_weather","args":{` and verify `}` is blocked before required `"city"`.
        for tok in tk.encode(r#"{"name":"get_weather","args":{"#, false) {
            assert!(g.allows_token(tok, &vocab, end));
            step(&mut g, tok);
        }
        let close_brace = tk.encode("}", false)[0];
        assert!(!g.allows_token(close_brace, &vocab, end), "closing args before required 'city' must be rejected");

        // Optional `"days"` must be an integer, not a string or float.
        for tok in tk.encode(r#""days":"#, false) {
            assert!(g.allows_token(tok, &vocab, end));
            step(&mut g, tok);
        }
        let quote_tok = tk.encode("\"", false)[0];
        assert!(!g.allows_token(quote_tok, &vocab, end), "string value for integer property 'days' must be rejected");
        for tok in tk.encode("3", false) {
            assert!(g.allows_token(tok, &vocab, end));
            step(&mut g, tok);
        }
        let dot_tok = tk.encode(".", false)[0];
        // An integer field takes number syntax: refusing `.` would cut `3.5` to `3` (see `NumStage::step_digit_or_part`).
        assert!(g.allows_token(dot_tok, &vocab, end), "decimal point after an integer field's digits stays open");
        assert!(!g.allows_token(close_brace, &vocab, end), "still missing required 'city'");

        // Emit `,"city":"Seattle"}}` and verify `<|end_message|>` unlocks ONLY after root `}` closes.
        for tok in tk.encode(r#","city":"Seattle"}"#, false) {
            assert!(g.allows_token(tok, &vocab, end));
            step(&mut g, tok);
            assert!(!g.allows_token(end, &vocab, end), "<|end_message|> must remain blocked before outer '}}'");
        }
        assert!(g.allows_token(close_brace, &vocab, end));
        step(&mut g, close_brace);
        assert!(g.allows_token(end, &vocab, end), "<|end_message|> must unlock once outer JSON object completes");
        step(&mut g, end);
        assert!(!g.is_in_json(), "grammar must reset to idle after <|end_message|>");
    }

    #[test]
    fn hundred_of_hundred_adversarial_random_logit_tool_calls_parse_valid_json() {
        let tk = Tokenizer::for_byte_test();
        let vocab = VocabBytes::from_tokenizer(&tk);
        let msg_model = tk.encode("<|message_model|>", true)[0];
        let c_think = tk.encode("<|content_thinking|>", true)[0];
        let c_text = tk.encode("<|content_text|>", true)[0];
        let c_tool = tk.encode("<|content_invoke_tool_json|>", true)[0];
        let end = tk.encode("<|end_message|>", true)[0];
        let end_sampling = tk.encode("<|content_model_end_sampling|>", true)[0];

        let req = json!({
            "tools": [{
                "type": "function",
                "function": {
                    "name": "search_repo",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "query": {"type": "string"},
                            "max_results": {"type": "integer"},
                            "case_sensitive": {"type": "boolean"},
                            "filters": {"type": "object"}
                        },
                        "required": ["query", "max_results"]
                    }
                }
            }]
        });
        let catalog = ToolCatalog::from_request(&req).unwrap();
        let vocab_len = tk.vocab_len();
        let mut logits = vec![0.0f32; vocab_len];

        // Tokens that frequently break naive JSON generators: boost them adversarially on odd trials!
        let traps: Vec<u32> = [
            end,
            msg_model,
            c_tool,
            tk.eos,
            tk.encode(",", false)[0],
            tk.encode("}", false)[0],
            tk.encode("]", false)[0],
            tk.encode(":", false)[0],
            tk.encode("\\", false)[0],
            tk.encode("0", false)[0],
            tk.encode(".", false)[0],
            tk.encode("\n", false)[0],
            tk.encode("\x00", false)[0],
        ]
        .into_iter()
        .collect();

        let mut rng_state = 0xD1CE_CAFE_BAAD_F00Du64;
        let mut next_f32 = || -> f32 {
            rng_state ^= rng_state >> 12;
            rng_state ^= rng_state << 25;
            rng_state ^= rng_state >> 27;
            let u = rng_state.wrapping_mul(0x2545F4914F6CDD1D) >> 40;
            (u as f32 / ((1u32 << 24) as f32)) * 8.0 - 4.0
        };

        let mut refused = 0;
        for trial in 0..100u64 {
            let mut g = ToolCallGrammar::new(catalog.clone()).with_limits(GrammarLimits::adversarial_test());
            g.observe_token(msg_model, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
            for tok in tk.encode("search_repo", false) {
                g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
            }
            g.observe_token(c_tool, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);

            let temp = if trial % 5 == 0 { 0.0 } else { 1.1 };
            let mut sampler = Sampler::new(temp, 64, 0.98, 0.0, 10_000 + trial);
            let mut emitted_bytes = Vec::new();
            let mut finished_with_end = false;

            for step_idx in 0..2048usize {
                for x in logits.iter_mut() {
                    *x = next_f32();
                }
                if trial % 2 == 1 {
                    // Actively try to force premature <|end_message|>, trailing commas, unclosed braces,
                    // control chars, leading zeros, and bare backslashes!
                    for &trap in &traps {
                        logits[trap as usize] = 18.0 + (step_idx % 5) as f32;
                    }
                }
                let tok = sampler
                    .sample_next_filtered(&logits, None, 0.0, |id| g.allows_token(id, &vocab, end))
                    .unwrap_or_else(|e| panic!("trial {trial} step {step_idx} failed to sample: {e}"));
                g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
                if tok == end {
                    finished_with_end = true;
                    break;
                }
                emitted_bytes.extend_from_slice(&tk.decode_bytes(tok));
            }

            assert!(finished_with_end, "trial {trial} did not reach <|end_message|>; partial={:?}", String::from_utf8_lossy(&emitted_bytes));
            let body_str = std::str::from_utf8(&emitted_bytes)
                .unwrap_or_else(|e| panic!("trial {trial} emitted invalid UTF-8 {emitted_bytes:?}: {e}"));
            // Syntax first (a number serde_json cannot read exactly is replaced by 0), then what is sent.
            serde_json::from_str::<Value>(&zero_numbers(body_str))
                .unwrap_or_else(|e| panic!("trial {trial} emitted invalid JSON {body_str:?}: {e}"));
            let parsed = read_call_body(body_str);
            if parsed.is_null() {
                // A number the grammar let run to a cap (random logits write long digit runs): refused, visibly.
                refused += 1;
                continue;
            }
            assert_eq!(
                parsed.get("name").and_then(Value::as_str).unwrap_or("search_repo"),
                "search_repo",
                "trial {trial}: unexpected tool name in {parsed}"
            );
            let args = parsed
                .get("args")
                .and_then(Value::as_object)
                .unwrap_or_else(|| panic!("trial {trial}: missing args object in {parsed}"));
            assert!(args.get("query").and_then(Value::as_str).is_some(), "trial {trial}: missing string 'query' in {parsed}");
            assert!(args.get("max_results").is_some_and(Value::is_number), "trial {trial}: missing number 'max_results' in {parsed}");
        }
        assert!(refused <= 20, "{refused} of 100 adversarial calls refused for a number");
    }

    /// `body` with every number literal outside strings replaced by `0`.
    fn zero_numbers(body: &str) -> String {
        let (b, mut out, mut i) = (body.as_bytes(), Vec::new(), 0);
        while i < b.len() {
            if b[i] == b'"' {
                let start = i;
                i += 1;
                while i < b.len() && b[i] != b'"' {
                    i += if b[i] == b'\\' { 2 } else { 1 };
                }
                i = (i + 1).min(b.len());
                out.extend_from_slice(&b[start..i]);
            } else if matches!(b[i], b'-' | b'0'..=b'9') {
                while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
                    i += 1;
                }
                out.push(b'0');
            } else {
                out.push(b[i]);
                i += 1;
            }
        }
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn restricted_key_with_escaped_quote_and_rfc8259_numbers() {
        let accepts_full = |g: &JsonObjectGrammar, s: &str| {
            let mut c = g.clone();
            c.advance_bytes(s.as_bytes()) && c.is_complete()
        };
        // 1. Restricted required property name containing an escaped quote (`a"b`).
        let schema: Value = serde_json::json!({
            "type": "object",
            "properties": {
                "a\"b": { "type": "string" }
            },
            "required": ["a\"b"],
            "additionalProperties": false
        });
        let g = JsonObjectGrammar::with_schema(&schema);
        assert!(accepts_full(&g, r#"{"a\"b":"ok"}"#), "escaped quote inside restricted key must be accepted");
        assert!(!accepts_full(&g, r#"{"a":"ok"}"#), "unmatched prefix must still be rejected");

        // 2. Integer `-0` and 3-digit / 4-digit exponents on number fields.
        let num_schema: Value = serde_json::json!({
            "type": "object",
            "properties": {
                "n": { "type": "integer" },
                "x": { "type": "number" }
            },
            "required": ["n", "x"],
            "additionalProperties": false
        });
        let ng = JsonObjectGrammar::with_schema(&num_schema);
        assert!(accepts_full(&ng, r#"{"n":0,"x":1e100}"#));
        assert!(accepts_full(&ng, r#"{"n":-42,"x":1e-308}"#));
        assert!(accepts_full(&ng, r#"{"n":0,"x":-0}"#), "number fields accept -0");
        assert!(accepts_full(&ng, r#"{"n":-0,"x":1}"#), "integer fields take -0 (read_call_body sends it as 0)");
        assert!(accepts_full(&ng, r#"{"n":-0.0,"x":1}"#), "integer fields take number syntax");
        assert!(!accepts_full(&ng, r#"{"n":-01,"x":1}"#), "integer must still reject leading zero -01");
    }

    #[test]
    fn vocab_bitsets_and_fast_path_match_reference_across_all_phases() {
        const END_TOK: u32 = 0;
        const MSG_MODEL: u32 = 1;
        const C_TOOL: u32 = 2;
        const C_TEXT: u32 = 3;
        const C_THINK: u32 = 4;
        const END_SAMP: u32 = 5;
        const EOS: u32 = 6;

        let entries: Vec<Option<&[u8]>> = vec![
            None,                             // 0: END_TOK
            None,                             // 1: MSG_MODEL
            None,                             // 2: C_TOOL
            None,                             // 3: C_TEXT
            None,                             // 4: C_THINK
            None,                             // 5: END_SAMP
            None,                             // 6: EOS
            Some(b""),                        // 7: empty non-special
            Some(b" "),                       // 8: single ws
            Some(b"  \t\r\n"),                // 9: multi ws (5 bytes > adversarial max_ws_run=4)
            Some(b"  \n"),                    // 10: multi ws (3 bytes)
            Some(b"{"),                       // 11
            Some(b"}"),                       // 12
            Some(b"["),                       // 13
            Some(b"]"),                       // 14
            Some(b":"),                       // 15
            Some(b","),                       // 16
            Some(b"\""),                      // 17
            Some(b"hello"),                   // 18: plain ascii string interior
            Some(b"a\"b"),                    // 19: closes string then extra byte
            Some(b"ok\"}"),                   // 20: closes string then }
            Some(b"ok\","),                   // 21: closes string then ,
            Some(b"ok\":"),                   // 22: closes key then :
            Some(b"\\n"),                     // 23: valid escape
            Some(b"\\\""),                    // 24: valid escaped quote
            Some(b"\\"),                      // 25: trailing backslash (stays in Backslash)
            Some(b"\\x"),                     // 26: invalid escape
            Some(b"\\u"),                     // 27: incomplete unicode escape
            Some(b"\\u0041"),                 // 28: valid unicode escape
            Some(b"\\uD83D"),                 // 29: high surrogate waiting for low
            Some(b"\\uD83D\\uDE80"),          // 30: valid surrogate pair
            Some(b"\\uDC00"),                 // 31: lone low surrogate (invalid)
            Some(b"\\uD83D\\u0041"),          // 32: high surrogate followed by non-low (invalid)
            Some(b"\x00"),                    // 33: NUL control byte (invalid in string)
            Some(b"abc\x1fdef"),              // 34: control byte mid-token (invalid in string)
            Some(b"\"\x00"),                  // 35: closes string BEFORE control byte!
            Some("é".as_bytes()),             // 36: valid 2-byte UTF-8
            Some("🚀".as_bytes()),            // 37: valid 4-byte UTF-8
            Some(&[0xC3]),                    // 38: partial 2-byte UTF-8 lead
            Some(&[0xA9]),                    // 39: lone UTF-8 continuation
            Some(&[0xC0, 0xAF]),              // 40: overlong UTF-8
            Some(&[0xED, 0xA0, 0x80]),        // 41: UTF-8 surrogate (invalid)
            Some(&[0xF4, 0x90, 0x80, 0x80]),  // 42: > U+10FFFF (invalid)
            Some(b"0"),                       // 43
            Some(b"1"),                       // 44
            Some(b"-"),                       // 45
            Some(b"-0"),                      // 46
            Some(b"-42"),                     // 47
            Some(b".5"),                      // 48
            Some(b"e+10"),                    // 49
            Some(b"true"),                    // 50
            Some(b"tr"),                      // 51
            Some(b"ue"),                      // 52
            Some(b"false"),                   // 53
            Some(b"null"),                    // 54
            Some(b"name"),                    // 55
            Some(b"args"),                    // 56
            Some(b"query"),                   // 57
            Some(b"n"),                       // 58
            Some(b"x"),                       // 59
            Some(b"arr"),                     // 60
            Some(b"flag"),                    // 61
            Some(b"extra"),                   // 62
            Some(b"my_tool"),                 // 63
            Some(b"my_"),                     // 64
            Some(b"tool"),                    // 65
            Some(b"\"name\":\"my_tool\""),    // 66
            Some(b"{\"name\":\"my_tool\","),  // 67
            Some(b"  }"),                     // 68
            Some(b"  ]"),                     // 69
            Some(b"123}"),                    // 70
            Some(b"123,"),                    // 71
            Some(b"123 "),                    // 72
            Some(b"123abc"),                  // 73
            Some(b"\"key\":1"),               // 74
            Some(b"0041"),                    // 75
            Some(b"\\uDE80"),                 // 76
        ];
        let vocab = VocabBytes::from_test_entries(&entries);

        // Sanity-check bitset classifications directly.
        assert!(!vocab.is_json_ws_token(0));
        assert!(!vocab.is_json_ws_token(7));
        assert!(vocab.is_json_ws_token(8));
        assert!(vocab.is_json_ws_token(9));
        assert!(vocab.is_json_ws_token(10));
        assert!(!vocab.is_json_ws_token(68));

        assert!(vocab.is_str_interior(18));
        assert!(vocab.is_str_interior(23));
        assert!(vocab.is_str_interior(25));
        assert!(vocab.is_str_interior(29));
        assert!(vocab.is_str_interior(30));
        assert!(vocab.is_str_interior(36));
        assert!(vocab.is_str_interior(37));
        assert!(vocab.is_str_interior(38));
        assert!(!vocab.is_str_interior(17));
        assert!(!vocab.is_str_interior(19));
        assert!(!vocab.is_str_interior(26));
        assert!(!vocab.is_str_interior(35));

        assert!(vocab.is_str_invalid_fresh(26));
        assert!(vocab.is_str_invalid_fresh(31));
        assert!(vocab.is_str_invalid_fresh(32));
        assert!(vocab.is_str_invalid_fresh(33));
        assert!(vocab.is_str_invalid_fresh(34));
        assert!(vocab.is_str_invalid_fresh(39));
        assert!(vocab.is_str_invalid_fresh(40));
        assert!(vocab.is_str_invalid_fresh(41));
        assert!(vocab.is_str_invalid_fresh(42));
        // Token 35 starts with `"` (closes the string before `\x00`) so it MUST NOT be flagged invalid_fresh.
        assert!(!vocab.is_str_invalid_fresh(35));

        let req = serde_json::json!({
            "tools": [{
                "type": "function",
                "function": {
                    "name": "my_tool",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "query": { "type": "string" },
                            "n": { "type": "integer" },
                            "x": { "type": "number" },
                            "arr": { "type": "array" },
                            "flag": { "type": "boolean" },
                            "extra": { "type": "object", "additionalProperties": true }
                        },
                        "required": ["query", "n"]
                    }
                }
            }]
        });
        let catalog = ToolCatalog::from_request(&req).expect("tool catalog");
        let check_all = |g: &ToolCallGrammar, label: &str| {
            for id in 0..=(entries.len() as u32 + 2) {
                let got = g.allows_token(id, &vocab, END_TOK);
                let exp = g.allows_token_ref(id, &vocab, END_TOK);
                assert_eq!(got, exp, "mismatch at state {label:?} for token id={id}");
            }
        };

        let limits = GrammarLimits {
            max_depth: 6,
            max_container_items: 8,
            max_string_bytes: 8,
            max_ws_run: 4,
        };

        // 1. Idle and Header modes.
        let mut g = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
        check_all(&g, "idle");
        g.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
        check_all(&g, "header_empty");
        g.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
        check_all(&g, "header_named");

        // Enter Json mode via C_TOOL and walk prefixes covering every Phase & boundary.
        let prefixes: &[(&str, &[u8])] = &[
            ("before_root", b""),
            ("before_root_ws", b"   "),
            ("before_root_ws_full", b"    "),
            ("obj_expect_key_or_end", b"{"),
            ("in_key_restricted_0", b"{\""),
            ("in_key_restricted_1", b"{\"na"),
            ("in_key_restricted_full", b"{\"name"),
            ("obj_expect_colon", b"{\"name\""),
            ("expect_value_fixed_str", b"{\"name\":"),
            ("in_str_fixed_0", b"{\"name\":\""),
            ("in_str_fixed_mid", b"{\"name\":\"my_"),
            ("in_str_fixed_end", b"{\"name\":\"my_tool"),
            ("after_value_obj", b"{\"name\":\"my_tool\""),
            ("obj_expect_key", b"{\"name\":\"my_tool\","),
            ("args_obj", b"{\"name\":\"my_tool\",\"args\":{"),
            ("in_str_free_fresh", b"{\"name\":\"my_tool\",\"args\":{\"query\":\""),
            ("in_str_free_near_limit_7", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"1234567"),
            ("in_str_free_at_limit_8", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"12345678"),
            ("in_str_free_backslash", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\\"),
            ("in_str_free_hex", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\\u00"),
            ("in_str_free_high_surrogate", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\\uD83D"),
            ("in_str_free_partial_utf8", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\xC3"),
            ("in_num_int_expect", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":"),
            ("in_num_int_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":-"),
            ("in_num_int_zero", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":0"),
            ("in_num_int_digits", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":12"),
            ("in_num_float_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":-"),
            ("in_num_float_zero", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0"),
            ("in_num_float_dot", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0."),
            ("in_num_float_frac", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0.5"),
            ("in_num_float_exp_e", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e"),
            ("in_num_float_exp_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e+"),
            ("in_num_float_exp_dig", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e+2"),
            ("arr_expect_val_or_end", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":["),
            ("arr_after_val", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[1"),
            ("arr_expect_val", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[1,"),
            ("in_lit_true", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"flag\":tr"),
            ("in_lit_false", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"flag\":fa"),
            ("in_lit_null", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[nu"),
            ("in_key_free_fresh", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\""),
            ("in_key_free_near_limit", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\"1234567"),
            ("in_key_free_backslash", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\"a\\"),
            ("complete_ws_0", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}}"),
            ("complete_ws_2", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}}  "),
            ("complete_ws_4", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}}    "),
        ];

        for &(label, prefix) in prefixes {
            let mut st = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
            st.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
            st.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
            st.observe_token(C_TOOL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
            if let SpanMode::Json(ref mut auto) = st.mode {
                let arena = &catalog.arena;
                for &b in prefix {
                    assert!(
                        auto.step_byte(b, arena, limits),
                        "prefix {label:?} failed at byte {b:#x}"
                    );
                }
            } else {
                panic!("expected Json mode for {label}");
            }
            check_all(&st, label);
        }

        // Verify the subtle byte_len == max_string_bytes - 1 boundary directly:
        // `\n` (token 23, 2 bytes) and `é` (token 36, 2 bytes) start at byte_len=7 < 8 and
        // continue via escape/utf8 continuation without hitting the EscState::None check.
        let mut edge = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
        edge.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
        edge.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
        edge.observe_token(C_TOOL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
        if let SpanMode::Json(ref mut auto) = edge.mode {
            for &b in b"{\"name\":\"my_tool\",\"args\":{\"query\":\"1234567" {
                assert!(auto.step_byte(b, &catalog.arena, limits));
            }
        }
        assert!(edge.allows_token(23, &vocab, END_TOK));
        assert!(edge.allows_token(36, &vocab, END_TOK));
        assert!(!edge.allows_token(18, &vocab, END_TOK));
    }

    /// What the client receives when the model writes `lit` into field `field` (`x`: number, `n`: integer): the
    /// grammar takes the literal byte by byte, and where it refuses a byte the model cannot write the rest and
    /// closes the object. `Some(text)`: the field's value as sent; `None`: the call goes out `_unparsed`.
    /// Also returns whether the grammar cut the literal short.
    fn sent_number(field: &str, lit: &str) -> (Option<String>, bool) {
        let g = JsonObjectGrammar::with_schema(&json!({
            "type": "object",
            "properties": {"x": {"type": "number"}, "n": {"type": "integer"}},
            "additionalProperties": false
        }));
        let mut written = format!("{{\"{field}\":");
        let mut c = g.clone();
        assert!(c.advance_bytes(written.as_bytes()));
        for &b in lit.as_bytes() {
            let mut next = c.clone();
            if !next.advance_bytes(&[b]) {
                break;
            }
            c = next;
            written.push(char::from(b));
        }
        let cut = written.len() - field.len() - 4 < lit.len();
        assert!(c.advance_bytes(b"}") && c.is_complete(), "the grammar must let {written:?} close (from {lit:?})");
        written.push('}');
        let v = read_call_body(&written);
        ((!v.is_null()).then(|| serde_json::to_string(&v[field]).unwrap()), cut)
    }

    /// The boundary table: every literal either reaches the client as exactly the value it writes or the call is
    /// visibly refused (`_unparsed`, counted in `tool_call_parse_fallback`). Never cut, rounded or rescaled.
    #[test]
    fn boundary_numbers_reach_the_client_exactly_or_the_call_is_refused() {
        enum Want {
            /// Sent as written.
            Same,
            /// Sent as this text (serde_json's spelling of the same value).
            Text(&'static str),
            /// Refused: the call goes out `_unparsed`.
            Refused,
        }
        use Want::*;
        let table: &[(&str, Want)] = &[
            ("-9223372036854775809", Refused), // i64::MIN - 1: serde_json would round it to an f64
            ("-9223372036854775808", Same),    // i64::MIN
            ("-1", Same),
            ("-0", Text("0")), // an integer has no negative zero
            ("0", Same),
            ("9223372036854775807", Same),  // i64::MAX
            ("9223372036854775808", Same),  // i64::MAX + 1 (u64)
            ("1733100000000000000", Same),  // a nanosecond Unix time
            ("10000000000000000000", Same), // 20 digits within u64
            ("18446744073709551615", Same), // u64::MAX
            ("18446744073709551616", Refused), // u64::MAX + 1
            ("99999999999999999999", Refused), // 20 digits past u64
            ("100000000000000000000", Refused), // 21 digits: the cap
            ("123456789012345678901234", Refused), // 24 digits: cut at 21, refused
            ("1e308", Text("1e+308")),
            ("1.7976931348623157e308", Text("1.7976931348623157e+308")), // f64::MAX
            ("1.7976931348623159e308", Refused), // rounds to infinity
            ("1e309", Refused),
            ("1e400", Refused),
            ("1e+0400", Refused),
            ("1e000400", Refused), // 6 exponent digits: cut at 5, refused
            ("1e-0308", Text("1e-308")),
            ("5e-324", Same), // the smallest subnormal
            ("1e-324", Refused), // a nonzero literal that reads as 0.0
            ("1e-400", Refused),
            ("0e-400", Text("0.0")),
            ("-0.0", Same),
            ("0.1", Same),
            ("0.30000000000000004", Same),
            ("1.5e3", Text("1500.0")),
            ("2.5e-3", Text("0.0025")),
            ("0.12345678901234567890123456789012", Text("0.12345678901234568")), // 32 fraction digits: f64 nearest
            ("0.123456789012345678901234567890123", Refused), // 33: the cap
            ("0.1234567890123456789012345678901234567890", Refused), // 40: cut at 33, refused
        ];
        for (lit, want) in table {
            for field in ["x", "n"] {
                let (got, cut) = sent_number(field, lit);
                match want {
                    Same => assert_eq!(got.as_deref(), Some(*lit), "{field}={lit}"),
                    Text(t) => assert_eq!(got.as_deref(), Some(*t), "{field}={lit}"),
                    Refused => assert_eq!(got, None, "{field}={lit} must be refused, not sent"),
                }
                assert!(!cut || got.is_none(), "{field}={lit}: a literal the grammar cut must never be sent");
            }
        }
    }

    /// Property test against serde_json: for random literals, the call is sent iff the literal is exactly
    /// readable (an oracle on `i128` and `str::parse::<f64>`), and what is sent is serde_json's own reading of
    /// the literal, uncut.
    #[test]
    fn numbers_sent_match_serde_json_exactly_and_are_never_cut() {
        let mut state = 0x9E37_79B9_7F4A_7C15u64;
        let mut rnd = |n: u64| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state % n
        };
        let digits = |rnd: &mut dyn FnMut(u64) -> u64, n: u64, lead: bool| -> String {
            (0..n)
                .map(|i| char::from(b'0' + if i == 0 && lead { 1 + rnd(9) } else { rnd(10) } as u8))
                .collect()
        };
        let edges = ["9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616"];
        let (mut sent, mut refused) = (0, 0);
        for _ in 0..20_000 {
            let mut lit = String::new();
            if rnd(2) == 0 {
                lit.push('-');
            }
            match rnd(8) {
                0 => lit.push('0'),
                1 => {
                    // Near the i64 / u64 edges: change the last digits of an edge value.
                    let e = edges[rnd(4) as usize];
                    let keep = e.len() - 1 - rnd(3) as usize;
                    lit.push_str(&e[..keep]);
                    lit.push_str(&digits(&mut rnd, (e.len() - keep) as u64, false));
                }
                _ => {
                    let n = 1 + rnd(24);
                    lit.push_str(&digits(&mut rnd, n, true));
                }
            }
            if rnd(3) == 0 {
                lit.push('.');
                let n = 1 + rnd(40);
                lit.push_str(&digits(&mut rnd, n, false));
            }
            if rnd(3) == 0 {
                lit.push(['e', 'E'][rnd(2) as usize]);
                lit.push_str(["", "+", "-"][rnd(3) as usize]);
                let n = 1 + rnd(6);
                lit.push_str(&digits(&mut rnd, n, false));
            }
            let field = ["x", "n"][rnd(2) as usize];
            let (got, cut) = sent_number(field, &lit);

            let int_syntax = !lit.contains(['.', 'e', 'E']);
            let unsigned = lit.trim_start_matches('-');
            let int_digits = unsigned.bytes().take_while(u8::is_ascii_digit).count();
            let frac_digits = lit.split_once('.').map_or(0, |(_, f)| f.bytes().take_while(u8::is_ascii_digit).count());
            let exp_digits = lit.split_once(['e', 'E']).map_or(0, |(_, e)| e.trim_start_matches(['+', '-']).len());
            let f = lit.parse::<f64>().unwrap();
            let oracle = if int_syntax {
                lit.parse::<i128>().is_ok_and(|v| (i128::from(i64::MIN)..=i128::from(u64::MAX)).contains(&v))
            } else {
                int_digits <= 20
                    && frac_digits <= 32
                    && exp_digits <= 4
                    && f.is_finite()
                    && (f != 0.0 || !lit.split(['e', 'E']).next().unwrap().contains(|c: char| ('1'..='9').contains(&c)))
            };
            assert_eq!(got.is_some(), oracle, "{field}={lit}: sent {got:?}");
            let Some(text) = got else {
                refused += 1;
                continue;
            };
            sent += 1;
            assert!(!cut, "{field}={lit}: sent although the grammar cut it");
            let serde: Value = serde_json::from_str(&lit).unwrap();
            if lit == "-0" {
                assert_eq!(text, "0");
            } else if int_syntax {
                assert_eq!(text, lit, "an integer is sent as written");
                assert!(serde.is_i64() || serde.is_u64(), "{lit}: serde_json reads it as an integer");
            } else {
                assert_eq!(text, serde.to_string(), "{lit}: sent as serde_json reads it");
                assert_eq!(serde.as_f64().unwrap().to_bits(), f.to_bits(), "{lit}: serde_json's f64 is the nearest");
            }
        }
        assert!(sent > 5_000 && refused > 2_000, "both outcomes exercised: sent {sent}, refused {refused}");
    }

    /// Past a bound the grammar would leave tools unchecked, so the catalog names the bound (the routes refuse
    /// the request with a 400 carrying it) instead of silently stopping.
    #[test]
    fn catalog_past_a_bound_names_it() {
        let tool = |i: usize, params: Value| json!({"type": "function", "function": {"name": format!("t{i}"), "parameters": params}});
        let small = json!({"type": "object", "properties": {"a": {"type": "integer"}}});
        let ok = ToolCatalog::from_request(&json!({"tools": (0..40).map(|i| tool(i, small.clone())).collect::<Vec<_>>()})).unwrap();
        assert_eq!(ok.over_limit(), None);

        let names = ToolCatalog::from_request(&json!({"tools": (0..1025).map(|i| tool(i, json!({}))).collect::<Vec<_>>()})).unwrap();
        assert!(names.over_limit().unwrap().contains("more than 1024 tool names"), "{:?}", names.over_limit());

        let schemas = ToolCatalog::from_request(&json!({"tools": (0..1000).map(|i| tool(i, json!({"type": "object", "properties": {
            "a": {"type": "object", "properties": {"b": {"type": "integer"}}},
            "c": {"type": "object", "properties": {"d": {"type": "integer"}}},
            "e": {"type": "object", "properties": {"f": {"type": "integer"}}}
        }}))).collect::<Vec<_>>()})).unwrap();
        assert!(schemas.over_limit().unwrap().contains("more than 4096 object schemas"), "{:?}", schemas.over_limit());

        let wide: serde_json::Map<String, Value> = (0..65).map(|i| (format!("p{i}"), json!({"type": "integer"}))).collect();
        let props = ToolCatalog::from_request(&json!({"tools": [tool(0, json!({"type": "object", "properties": wide}))]})).unwrap();
        assert!(props.over_limit().unwrap().contains("more than 64 properties"), "{:?}", props.over_limit());
        let at64: serde_json::Map<String, Value> = (0..64).map(|i| (format!("p{i}"), json!({"type": "integer"}))).collect();
        let req = json!({"type": "object", "properties": at64, "required": ["p0", "p63", "p0"]});
        assert_eq!(ToolCatalog::from_request(&json!({"tools": [tool(0, req)]})).unwrap().over_limit(), None);
    }

    /// A request with many tools must keep every tool in the catalog, with its argument schema:
    /// a tool left out gets an unchecked dynamic wrapper, so its arguments are never constrained.
    #[test]
    fn catalog_keeps_every_tool_schema_past_sixty_four_schemas() {
        let tools: Vec<Value> = (0..40)
            .map(|i| {
                json!({"type": "function", "function": {"name": format!("tool{i}"), "parameters": {
                    "type": "object",
                    "properties": {
                        "count": {"type": "integer"},
                        "opts": {"type": "object", "properties": {"deep": {"type": "boolean"}}}
                    },
                    "required": ["count"],
                    "additionalProperties": false
                }}})
            })
            .collect();
        let catalog = ToolCatalog::from_request(&json!({"tools": tools})).unwrap();
        assert_eq!(catalog.names.len(), 40, "every requested tool must be in the catalog");
        assert!(catalog.name_wrappers.iter().all(|&w| w != NO_SCHEMA), "every tool's schema must compile");
        let last = catalog.names.iter().position(|n| &**n == b"tool39").expect("tool39 in the catalog");
        let run = |doc: &str| {
            let mut st = AutoState::new(catalog.name_wrappers[last]);
            doc.bytes().all(|b| st.step_byte(b, &catalog.arena, GrammarLimits::DEFAULT)) && st.is_complete()
        };
        assert!(run(r#"{"name":"tool39","args":{"count":3}}"#));
        assert!(!run(r#"{"name":"tool39","args":{"count":"three"}}"#), "tool39's integer must be enforced");
        assert!(!run(r#"{"name":"tool39","args":{}}"#), "tool39's required key must be enforced");
    }

    /// A small vocabulary for the tool header: specials at 0..=7, then multi-byte name pieces.
    mod header {
        use super::*;

        pub(super) const END: u32 = 0;
        pub(super) const MSG_MODEL: u32 = 1;
        pub(super) const C_THINK: u32 = 2;
        pub(super) const C_TEXT: u32 = 3;
        pub(super) const C_TOOL: u32 = 4;
        pub(super) const END_SAMP: u32 = 5;
        pub(super) const EOS: u32 = 6;
        pub(super) const MSG_USER: u32 = 7;
        pub(super) const PIECES: &[&[u8]] = &[
            b"Read", b"File", b"Bash", b"Bash2", b"2", b" Read", b"R", b"ead", b"Re", b"ad", b"x", b"F", b"ile",
            b"{", b"}", b"\"", b":", b",", b"name", b"args", b"Write", b"", b" ", b"Edit", b"\n", b"\\n",
        ];

        pub(super) fn marks() -> SpanMarks {
            SpanMarks { msg_model: MSG_MODEL, c_think: C_THINK, c_text: C_TEXT, c_tool: C_TOOL, end: END }
        }

        /// `<|message_model|>NAME<|content_invoke_tool_json|>{"args":{}}<|end_message|>` with `name` as one piece each.
        pub(super) fn call(name: &[&[u8]]) -> Vec<u32> {
            let mut toks = vec![MSG_MODEL];
            toks.extend(name.iter().map(|p| id(p)));
            toks.push(C_TOOL);
            toks.extend([b"{" as &[u8], b"\"", b"args", b"\"", b":", b"{", b"}", b"}"].iter().map(|p| id(p)));
            toks.push(END);
            toks
        }

        pub(super) fn vocab() -> VocabBytes {
            let mut entries: Vec<Option<&[u8]>> = vec![None; 8];
            entries.extend(PIECES.iter().map(|p| Some(*p)));
            VocabBytes::from_test_entries(&entries)
        }

        pub(super) fn id(piece: &[u8]) -> u32 {
            8 + PIECES.iter().position(|p| *p == piece).expect("piece in test vocab") as u32
        }

        pub(super) fn n_vocab() -> u32 {
            8 + PIECES.len() as u32
        }

        pub(super) fn step(g: &mut ToolCallGrammar, vocab: &VocabBytes, tok: u32) {
            g.observe_token(tok, vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END, END_SAMP, EOS);
        }

        pub(super) fn catalog(names: &[&str], extra: Value) -> Arc<ToolCatalog> {
            let tools: Vec<Value> = names
                .iter()
                .map(|n| json!({"type": "function", "function": {"name": n, "parameters": {"type": "object"}}}))
                .collect();
            let mut req = json!({ "tools": tools });
            if let (Some(obj), Some(more)) = (req.as_object_mut(), extra.as_object()) {
                for (k, v) in more {
                    obj.insert(k.clone(), v.clone());
                }
            }
            ToolCatalog::from_request(&req).expect("catalog")
        }
    }

    #[test]
    fn tool_header_admits_offered_names_and_their_shared_prefixes_only() {
        use header::*;
        let vocab = vocab();
        let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
        let mut g = ToolCallGrammar::new(cat);
        step(&mut g, &vocab, MSG_MODEL);
        assert!(g.is_constrained() && !g.is_in_json(), "the header of a request with tools is masked");
        let allows = |g: &ToolCallGrammar, t: u32| g.allows_token(t, &vocab, END);

        // Empty header: a name's first piece or a content marker; never the tool marker, never another special.
        for ok in [id(b"Read"), id(b"R"), id(b"Re"), id(b"Bash"), C_TEXT, C_THINK] {
            assert!(allows(&g, ok), "empty header must allow {ok}");
        }
        for bad in [id(b"Bash2"), id(b" Read"), id(b"x"), id(b"File"), id(b"Write"), id(b""), C_TOOL, END, END_SAMP, EOS, MSG_USER, MSG_MODEL] {
            assert!(!allows(&g, bad), "empty header must refuse {bad}");
        }

        // "Read" is a name and a prefix of "ReadFile": both the tool marker and the continuation stay open.
        step(&mut g, &vocab, id(b"Read"));
        assert!(allows(&g, C_TOOL) && allows(&g, id(b"File")) && allows(&g, id(b"F")));
        for bad in [id(b"2"), id(b"Bash"), id(b"ead"), C_TEXT, C_THINK, END] {
            assert!(!allows(&g, bad), "header \"Read\" must refuse {bad}");
        }
        let mut read_file = g.clone();
        step(&mut read_file, &vocab, id(b"F"));
        assert!(!allows(&read_file, C_TOOL), "\"ReadF\" names no tool");
        assert!(allows(&read_file, id(b"ile")));
        step(&mut read_file, &vocab, id(b"ile"));
        assert!(allows(&read_file, C_TOOL));
        step(&mut read_file, &vocab, C_TOOL);
        assert!(read_file.is_in_json());
        // The body is ReadFile's own wrapper: its fixed name is "ReadFile".
        assert!(read_file.allows_token(id(b"{"), &vocab, END));

        step(&mut g, &vocab, C_TOOL);
        assert!(g.is_in_json(), "an exact offered name opens the JSON body");

        // "Bash" is offered, "Bash2" is not: the piece that would make it is refused.
        let mut g = ToolCallGrammar::new(catalog(&["Read", "ReadFile", "Bash"], json!({})));
        step(&mut g, &vocab, MSG_MODEL);
        step(&mut g, &vocab, id(b"Bash"));
        assert!(!g.allows_token(id(b"2"), &vocab, END), "\"Bash2\" was never offered");
        assert!(g.allows_token(C_TOOL, &vocab, END));
    }

    /// Every header the mask lets through, walked exhaustively over the test vocabulary: whenever the tool
    /// marker is allowed the header is exactly an offered name, and every offered name is reachable.
    #[test]
    fn tool_header_mask_reaches_every_offered_name_and_nothing_else() {
        use header::*;
        let vocab = vocab();
        let names = ["Read", "ReadFile", "Bash"];
        let cat = catalog(&names, json!({}));
        let mut start = ToolCallGrammar::new(cat);
        step(&mut start, &vocab, MSG_MODEL);
        let mut frontier = vec![(start, String::new())];
        let mut reached = std::collections::BTreeSet::new();
        for _depth in 0..8 {
            let mut next = Vec::new();
            for (g, text) in frontier {
                for t in 0..n_vocab() {
                    if !g.allows_token(t, &vocab, END) {
                        continue;
                    }
                    if t == C_TOOL {
                        assert!(names.contains(&text.as_str()), "tool marker allowed after {text:?}");
                        reached.insert(text.clone());
                        continue;
                    }
                    if t == C_TEXT || t == C_THINK {
                        assert!(text.is_empty(), "content marker allowed after {text:?}");
                        continue;
                    }
                    let bytes = vocab.non_special_bytes(t).expect("only name pieces remain");
                    let mut g2 = g.clone();
                    step(&mut g2, &vocab, t);
                    let text2 = format!("{text}{}", std::str::from_utf8(bytes).unwrap());
                    assert!(names.iter().any(|n| n.starts_with(&text2)), "header {text2:?} is no offered name's prefix");
                    next.push((g2, text2));
                }
            }
            frontier = next;
        }
        assert_eq!(reached.into_iter().collect::<Vec<_>>(), vec!["Bash", "Read", "ReadFile"]);
    }

    #[test]
    fn tool_header_text_and_thinking_answers_stay_open() {
        use header::*;
        let vocab = vocab();
        let cat = catalog(&["Read"], json!({}));
        for marker in [C_TEXT, C_THINK] {
            let mut g = ToolCallGrammar::new(cat.clone());
            step(&mut g, &vocab, MSG_MODEL);
            assert!(g.allows_token(marker, &vocab, END));
            step(&mut g, &vocab, marker);
            assert!(!g.is_constrained(), "a text or thinking message is not masked");
            // Ordinary text is not constrained: every token but the tool marker.
            for t in 0..n_vocab() {
                assert_eq!(g.allows_token(t, &vocab, END), t != C_TOOL, "message body, token {t}");
            }
        }
    }

    /// Grammar-level only. Both routes answer `tool_choice: none` with HTTP 400 today
    /// (`serve::tests::unsupported_generation_controls_return_400_before_scheduling`), so this does not show that
    /// a route supports `none`: it pins what the catalog does with it, should a route ever admit it. A request
    /// without tools has no catalog, so no grammar at all.
    #[test]
    fn a_tool_choice_none_catalog_masks_nothing_at_the_grammar_level() {
        use header::*;
        let vocab = vocab();
        assert!(ToolCatalog::from_request(&json!({"messages": []})).is_none(), "no tools: no grammar at all");
        assert!(ToolCatalog::from_request(&json!({"tools": []})).is_none());
        for choice in [json!("none"), json!({"type": "none"})] {
            let mut g =
                ToolCallGrammar::new(catalog(&["Read"], json!({ "tool_choice": choice }))).with_marks(marks());
            assert_eq!(g.committed_token(C_TOOL), C_TOOL, "tool_choice {choice}: no rewrite");
            for at in [&[][..], &[MSG_MODEL][..], &[MSG_MODEL, C_TEXT][..]] {
                let mut g = g.clone();
                for &t in at {
                    step(&mut g, &vocab, t);
                }
                assert!(!g.is_constrained(), "tool_choice {choice} leaves the header alone");
                for t in 0..n_vocab() {
                    assert!(g.allows_token(t, &vocab, END), "tool_choice {choice}, after {at:?}: must allow {t}");
                }
            }
        }
        // `auto` (and no `tool_choice`) masks.
        let mut g = ToolCallGrammar::new(catalog(&["Read"], json!({ "tool_choice": "auto" })));
        step(&mut g, &vocab, MSG_MODEL);
        assert!(g.is_constrained());
    }

    /// A thinking cap forces `<|end_message|><|message_model|>`; the header the model then picks is masked.
    #[test]
    fn tool_header_after_a_forced_thinking_close_is_masked() {
        use header::*;
        let vocab = vocab();
        let mut g = ToolCallGrammar::new(catalog(&["Read", "Bash"], json!({})));
        for t in [MSG_MODEL, C_THINK, id(b"x"), id(b"x"), END, MSG_MODEL] {
            step(&mut g, &vocab, t);
        }
        assert!(g.is_constrained());
        assert!(!g.allows_token(id(b"Bash2"), &vocab, END));
        assert!(!g.allows_token(END, &vocab, END), "the turn must not close an empty model message");
        assert!(g.allows_token(id(b"Bash"), &vocab, END) && g.allows_token(C_TEXT, &vocab, END));
    }

    #[test]
    fn tool_header_counts_draws_and_those_whose_top_token_was_refused() {
        use header::*;
        let vocab = vocab();
        let mut g = ToolCallGrammar::new(catalog(&["Read", "Bash"], json!({})));
        g.note_header_draw(true);
        assert_eq!((g.header_draws(), g.header_masked()), (0, 0), "outside a header nothing is counted");
        step(&mut g, &vocab, MSG_MODEL);
        g.note_header_draw(true);
        g.note_header_draw(false);
        g.note_header_draw(false);
        assert_eq!((g.header_draws(), g.header_masked()), (3, 1));
        step(&mut g, &vocab, id(b"Bash"));
        g.note_header_draw(true);
        assert_eq!((g.header_draws(), g.header_masked()), (4, 2));
        step(&mut g, &vocab, C_TOOL);
        g.note_header_draw(true);
        assert_eq!((g.header_draws(), g.header_masked()), (4, 2), "a JSON body is not a header");
    }

    /// The tool marker is only reachable from a header that is exactly an offered name: not at the start of the
    /// reply, not inside a text or thinking message, not between messages, not after a finished call. Nothing
    /// else is refused there.
    #[test]
    fn tool_marker_is_refused_wherever_it_does_not_follow_an_offered_header() {
        use header::*;
        let vocab = vocab();
        let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
        let x = id(b"x");
        let mut after_call = call(&[b"Read"]);
        after_call.extend(call(&[b"Read", b"File"]));
        let states: Vec<(&str, Vec<u32>)> = vec![
            ("the start of the reply", vec![]),
            ("a text message", vec![MSG_MODEL, C_TEXT, x]),
            ("a thinking message", vec![MSG_MODEL, C_THINK, x]),
            ("between messages", vec![MSG_MODEL, C_TEXT, x, END]),
            ("after two calls", after_call),
            ("after the turn's end", vec![MSG_MODEL, C_TEXT, x, END, END_SAMP]),
        ];
        for (label, toks) in &states {
            let mut g = ToolCallGrammar::new(cat.clone()).with_marks(marks());
            for &t in toks {
                assert!(g.allows_token(t, &vocab, END), "{label}: the walk itself must be allowed (token {t})");
                step(&mut g, &vocab, t);
            }
            assert!(!g.is_constrained(), "{label}: not a masked state");
            for t in 0..n_vocab() {
                assert_eq!(g.allows_token(t, &vocab, END), t != C_TOOL, "{label}: token {t}");
            }
        }
        // Without `with_marks` the first `observe_token` call names the marker.
        let mut g = ToolCallGrammar::new(cat);
        step(&mut g, &vocab, x);
        assert!(!g.allows_token(C_TOOL, &vocab, END));
    }

    /// A path that draws without a mask (GPU Gumbel, DSpark verify) can still draw the tool marker anywhere:
    /// `committed_token` puts the turn back on the template, so the marker is never committed away from an
    /// exactly offered header.
    #[test]
    fn a_tool_marker_drawn_away_from_an_offered_header_is_rewritten() {
        use header::*;
        let vocab = vocab();
        let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
        let x = id(b"x");
        // The last flag: a maskless path can be in this state. It never is in a header, which is always masked;
        // the two header rewrites only keep the function total.
        let cases: Vec<(&str, Vec<u32>, u32, bool)> = vec![
            ("the start of the reply opens a message", vec![], MSG_MODEL, true),
            ("a text message ends", vec![MSG_MODEL, C_TEXT, x], END, true),
            ("an empty text message ends", vec![MSG_MODEL, C_TEXT], END, true),
            ("a thinking message ends", vec![MSG_MODEL, C_THINK, x], END, true),
            ("between messages the next one opens", vec![MSG_MODEL, C_TEXT, x, END], MSG_MODEL, true),
            ("after a call the next message opens", call(&[b"Read"]), MSG_MODEL, true),
            ("an empty header becomes a text message", vec![MSG_MODEL], C_TEXT, false),
            ("a partial name becomes a text message", vec![MSG_MODEL, id(b"Re")], C_TEXT, false),
            ("an offered name keeps the marker", vec![MSG_MODEL, id(b"Read")], C_TOOL, false),
            ("a longer offered name keeps the marker", vec![MSG_MODEL, id(b"Read"), id(b"File")], C_TOOL, false),
        ];
        for (label, toks, want, maskless) in &cases {
            let mut g = ToolCallGrammar::new(cat.clone()).with_marks(marks());
            for &t in toks {
                step(&mut g, &vocab, t);
            }
            assert_eq!(g.committed_token(C_TOOL), *want, "{label}");
            assert_eq!(g.marker_rewrites(), u64::from(*want != C_TOOL), "{label}: counted");
            // Every other token is committed as drawn.
            for t in (0..n_vocab()).filter(|&t| t != C_TOOL) {
                assert_eq!(g.committed_token(t), t, "{label}: token {t}");
            }
            assert_eq!(g.is_constrained(), !*maskless, "{label}");
            // What a maskless path commits is something the mask allows, and no tool body opens unnamed.
            let committed = g.committed_token(C_TOOL);
            if *maskless {
                assert!(g.allows_token(committed, &vocab, END), "{label}: the rewrite obeys the mask");
            }
            step(&mut g, &vocab, committed);
            assert_eq!(g.is_in_json(), *want == C_TOOL, "{label}");
        }
    }

    /// The wire's naming rule (`bind_call`): a request with tools is only ever sent a name it offered.
    #[test]
    fn a_completed_call_is_bound_to_an_offered_name_or_not_sent() {
        use header::*;
        let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
        let tools = Some(&*cat);
        let sent = |name: &str, consistent: bool| CallName::Sent { name: name.into(), offered: true, consistent };
        // The template's call: an offered header, the body agreeing or silent.
        assert_eq!(bind_call(tools, Some(b"Read"), Some("Read")), sent("Read", true));
        assert_eq!(bind_call(tools, Some(b"ReadFile"), None), sent("ReadFile", true));
        // The header picks the schema, so it outranks a body that disagrees, offered or not.
        assert_eq!(bind_call(tools, Some(b"Read"), Some("Evil")), sent("Read", false));
        assert_eq!(bind_call(tools, Some(b"Read"), Some("Bash")), sent("Read", false));
        // No header (the marker followed none): the body's name, when it is offered.
        assert_eq!(bind_call(tools, None, Some("Bash")), sent("Bash", false));
        assert_eq!(bind_call(tools, Some(b""), Some("Bash")), sent("Bash", false));
        assert_eq!(bind_call(tools, Some(b"Bash2"), Some("Bash")), sent("Bash", false));
        // Nothing offered to bind to: not sent.
        for (header, body) in [
            (None, Some("Evil")),
            (None, None),
            (Some(&b""[..]), None),
            (Some(&b"Bash2"[..]), Some("Bash2")),
            (Some(&b"Rea"[..]), Some("read")),
        ] {
            assert_eq!(bind_call(tools, header, body), CallName::Unoffered, "{header:?} {body:?}");
        }
        // A request with no tools has nothing to bind to: the name goes out as before, marked unoffered.
        assert_eq!(
            bind_call(None, Some(b" Read"), None),
            CallName::Sent { name: "Read".into(), offered: false, consistent: true }
        );
        assert_eq!(
            bind_call(None, Some(b"Read"), Some("Evil")),
            CallName::Sent { name: "Evil".into(), offered: false, consistent: true }
        );
    }

    /// A name offered with surrounding whitespace is a name like any other: the header matches it byte for byte,
    /// the body's name is fixed to it, and the wire sends it as offered. Trimming is only the fallback for a
    /// header that is not exactly an offered name.
    #[test]
    fn a_name_offered_with_surrounding_whitespace_is_matched_and_sent_as_offered() {
        use header::*;
        let vocab = vocab();
        let names = [" Read", "Read", "Edit\n"];
        let quote = id(b"\"");
        let name_value_open = |g: &mut ToolCallGrammar| {
            for p in [b"{" as &[u8], b"\"", b"name", b"\"", b":", b"\""] {
                assert!(g.allows_token(id(p), &vocab, END), "body prefix {p:?}");
                step(g, &vocab, id(p));
            }
        };
        for extra in [json!({}), json!({"tool_choice": "none"})] {
            let cat = catalog(&names, extra.clone());
            // ` Read` and `Read` are different tools: each header opens its own body.
            let mut padded = ToolCallGrammar::new(cat.clone());
            for t in [MSG_MODEL, id(b" Read"), C_TOOL] {
                assert!(padded.allows_token(t, &vocab, END), "{extra}: header token {t}");
                step(&mut padded, &vocab, t);
            }
            name_value_open(&mut padded);
            assert!(padded.allows_token(id(b" Read"), &vocab, END), "{extra}: the body names ` Read`");
            assert!(!padded.allows_token(id(b"Read"), &vocab, END), "{extra}: not the trimmed `Read`");

            let mut plain = ToolCallGrammar::new(cat.clone());
            for t in [MSG_MODEL, id(b"Read"), C_TOOL] {
                step(&mut plain, &vocab, t);
            }
            name_value_open(&mut plain);
            assert!(plain.allows_token(id(b"Read"), &vocab, END) && !plain.allows_token(id(b" Read"), &vocab, END));

            // A trailing newline is part of `Edit\n`'s name (escaped in the JSON body).
            let mut newline = ToolCallGrammar::new(cat.clone());
            for t in [MSG_MODEL, id(b"Edit"), id(b"\n"), C_TOOL] {
                assert!(newline.allows_token(t, &vocab, END), "{extra}: header token {t}");
                step(&mut newline, &vocab, t);
            }
            name_value_open(&mut newline);
            for p in [b"Edit" as &[u8], b"\\n"] {
                assert!(newline.allows_token(id(p), &vocab, END), "{extra}: body name piece {p:?}");
                step(&mut newline, &vocab, id(p));
            }
            assert!(newline.allows_token(quote, &vocab, END));

            let tools = Some(&*cat);
            let sent = |name: &str, consistent: bool| CallName::Sent { name: name.into(), offered: true, consistent };
            assert_eq!(bind_call(tools, Some(b" Read"), None), sent(" Read", true));
            assert_eq!(bind_call(tools, Some(b" Read"), Some(" Read")), sent(" Read", true));
            assert_eq!(bind_call(tools, Some(b"Read"), None), sent("Read", true));
            assert_eq!(bind_call(tools, Some(b"Edit\n"), None), sent("Edit\n", true));
            // Not exactly offered: the trimmed header, as before.
            assert_eq!(bind_call(tools, Some(b"Read "), None), sent("Read", false));
            assert_eq!(bind_call(tools, Some(b"\tRead"), None), sent("Read", false));
            assert_eq!(bind_call(tools, Some(b"Edit"), None), CallName::Unoffered, "`Edit` was not offered");
        }
        // In a masked header the padded spelling that was not offered cannot be written at all.
        let mut g = ToolCallGrammar::new(catalog(&["Read"], json!({})));
        step(&mut g, &vocab, MSG_MODEL);
        assert!(!g.allows_token(id(b" Read"), &vocab, END) && !g.allows_token(id(b" "), &vocab, END));
    }

    /// 256 tools whose names differ only in their last bytes: no lookup scans them. Every header candidate costs
    /// one binary search (9 comparisons at most), whatever the catalog holds, and gives the answer a scan gives.
    #[test]
    fn offered_name_lookups_never_scan_the_catalog() {
        const MSG_MODEL: u32 = 1;
        const C_TOOL: u32 = 4;
        let names: Vec<String> = (0..256).map(|i| format!("mcp__workspace__tool_{i:03}")).collect();
        let mut tools: Vec<Value> = names
            .iter()
            .map(|n| json!({"type": "function", "function": {"name": n, "parameters": {"type": "object"}}}))
            .collect();
        // Declared twice and out of order: the catalog still holds each name once.
        tools.extend(tools.clone());
        tools.reverse();
        let cat = ToolCatalog::from_request(&json!({ "tools": tools })).unwrap();
        assert_eq!(cat.names.len(), 256);
        assert!(cat.names.windows(2).all(|w| w[0] < w[1]), "sorted, no duplicates");

        let digits: Vec<String> = (0..10).map(|d| d.to_string()).chain((0..100).map(|d| format!("{d:02}"))).collect();
        let fillers: Vec<String> = (0..2000u32).map(|i| format!("{}{}", ["m", "mc", "t", "w", "_"][i as usize % 5], i)).collect();
        let mut pieces: Vec<&[u8]> = vec![b"mcp__workspace__tool_", b"mcp", b"__", b"workspace", b"tool", b"_", b"m", b"mcp__", b"x"];
        pieces.extend(digits.iter().map(|d| d.as_bytes()));
        pieces.extend(fillers.iter().map(|f| f.as_bytes()));
        pieces.extend(names.iter().map(|n| n.as_bytes()));
        let mut entries: Vec<Option<&[u8]>> = vec![None; 8];
        entries.extend(pieces.iter().map(|p| Some(*p)));
        let vocab = VocabBytes::from_test_entries(&entries);
        let tok = |piece: &[u8]| 8 + pieces.iter().position(|p| *p == piece).unwrap() as u32;
        let step = |g: &mut ToolCallGrammar, t: u32| g.observe_token(t, &vocab, MSG_MODEL, 2, 3, C_TOOL, 0, 5, 6);
        let probes = || NAME_PROBES.with(|c| c.replace(0));

        let walks: [&[&[u8]]; 5] = [
            &[],
            &[b"mcp"],
            &[b"mcp__workspace__tool_"],
            &[b"mcp__workspace__tool_", b"1"],
            &[b"mcp__workspace__tool_", b"12", b"7"],
        ];
        for walk in walks {
            let mut g = ToolCallGrammar::new(cat.clone());
            probes();
            step(&mut g, MSG_MODEL);
            for piece in walk {
                step(&mut g, tok(piece));
                let narrowed = probes();
                assert!(narrowed <= 18, "narrowing by {piece:?} made {narrowed} comparisons");
            }
            let header: Vec<u8> = walk.concat();
            let mut allowed = 0;
            for t in 0..entries.len() as u32 {
                let got = g.allows_token(t, &vocab, 0);
                let made = probes();
                assert!(made <= 9, "token {t} after {walk:?} made {made} comparisons");
                let scan = match vocab.non_special_bytes(t) {
                    Some(bytes) => {
                        let text = [header.as_slice(), bytes].concat();
                        !bytes.is_empty() && names.iter().any(|n| n.as_bytes().starts_with(&text))
                    }
                    None if t == C_TOOL => names.iter().any(|n| n.as_bytes() == header),
                    None => header.is_empty() && (t == 2 || t == 3),
                };
                assert_eq!(got, scan, "token {t} after {walk:?}");
                allowed += usize::from(got);
            }
            assert!(allowed > 0, "after {walk:?} something is allowed");
        }

        // Opening the body looks nothing up: the range already names the tool. A tool past the arena's schema
        // cap is still callable, its body name fixed to it.
        let mut g = ToolCallGrammar::new(cat.clone());
        for t in [MSG_MODEL, tok(b"mcp__workspace__tool_255")] {
            step(&mut g, t);
        }
        probes();
        assert!(g.allows_token(C_TOOL, &vocab, 0));
        step(&mut g, C_TOOL);
        assert_eq!(probes(), 0, "the marker and the body's schema cost no comparison");
        assert!(g.is_in_json());
        // The wire's check is a binary search too.
        assert!(cat.offers(b"mcp__workspace__tool_128") && !cat.offers(b"mcp__workspace__tool_256"));
        assert!(probes() <= 18);
    }
}