exatok 0.1.1

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

use std::cell::RefCell;

use vyre::MemoryOrdering;
use vyre::ir::{BufferAccess, BufferDecl, DataType, Expr, Node, Program};
use vyre_driver::{DispatchConfig, Resource, VyreBackend};
use vyre_driver::grid_sync::contains_grid_sync;
use vyre_primitives::fixpoint::persistent_fixpoint::{
    PERSISTENT_FIXPOINT_WORKGROUP_SIZE, persistent_fixpoint, persistent_fixpoint_grid,
};
use vyre_primitives::wire::{pack_u32_slice_into, unpack_u32_slice_into};

use crate::{ExatokError, trap_program};

/// Canonical op id of the single-dispatch loop.
///
/// `exatok::` is the Tier 4 prefix. A `vyre-libs::` or `vyre-intrinsics::`
/// prefix would falsely claim a Tier 3 or Tier 2 stability and review tier, and
/// the tier audit greps exactly this string.
pub const OP_ID: &str = "exatok::gpu_loop::persistent_merge";

/// Canonical op id of the one-pass program a host-driven loop dispatches.
pub const OP_ID_SINGLE_PASS: &str = "exatok::gpu_loop::merge_pass";

/// Live loop state. Ping-pong front buffer, and where the final state is read
/// back from.
pub const NAME_STATE_CURRENT: &str = "wt_loop_current";

/// Ping-pong back buffer the pass body writes into.
pub const NAME_STATE_NEXT: &str = "wt_loop_next";

/// One-word batch convergence flag owned by `persistent_fixpoint`. Non-zero
/// after the dispatch means the loop ran out of passes.
pub const NAME_CHANGED: &str = "wt_loop_changed";

/// One-word counter incremented once per iteration the kernel enters.
pub const NAME_PASSES: &str = "wt_loop_passes";

/// Per-segment flag, rewritten every pass: non-zero when that segment's state
/// changed during the most recent pass.
pub const NAME_SEGMENT_CHANGED: &str = "wt_loop_segment_changed";

/// Per-segment tally of passes in which that segment changed. Its convergence
/// depth is this plus the one pass that observed no change.
pub const NAME_SEGMENT_PASSES: &str = "wt_loop_segment_passes";

/// Binding of [`NAME_STATE_CURRENT`].
pub const BINDING_STATE_CURRENT: u32 = 0;

/// Binding of [`NAME_STATE_NEXT`].
pub const BINDING_STATE_NEXT: u32 = 1;

/// Binding of [`NAME_CHANGED`].
pub const BINDING_CHANGED: u32 = 2;

/// Binding of [`NAME_PASSES`].
pub const BINDING_PASSES: u32 = 3;

/// Binding of [`NAME_SEGMENT_CHANGED`].
pub const BINDING_SEGMENT_CHANGED: u32 = 4;

/// Binding of [`NAME_SEGMENT_PASSES`].
pub const BINDING_SEGMENT_PASSES: u32 = 5;

/// First binding a pass body may claim for its own buffers, such as a rank
/// table or a per-segment selection scratch. Everything below belongs to the
/// loop harness.
pub const FIRST_CALLER_BINDING: u32 = 6;

/// Harness buffers the loop returns, in binding order.
const HARNESS_BUFFERS: usize = 6;

/// Whether the kernel reads what each harness binding arrives HOLDING, in
/// binding order.
///
/// `false` is a proof obligation discharged in the IR, not a guess. Two of the
/// six buffers are overwritten in full before the dispatch reads them, so
/// staging host bytes into them moves bytes no kernel can observe, and the
/// resident path skips those uploads. On a prose encode that is 2,023,908 of
/// the 4,507,896 bytes the host used to push per encode.
///
/// - [`NAME_STATE_NEXT`]: every live slot is written by the pass body, which
///   the module contract requires, and every padding word is written by
///   `close_pass` before the barrier that precedes the primitive's compare.
///   Nothing loads `next` earlier than that compare.
/// - [`NAME_SEGMENT_CHANGED`]: `open_pass` stores zero into every segment's
///   flag from that segment's own slot-0 lane, then barriers, before any lane
///   reads it or `atomic_or`s it. That phase belongs to this harness, so it
///   holds whatever the caller's pass body does.
///
/// The other four are read. [`NAME_STATE_CURRENT`] carries the tokens.
/// [`NAME_PASSES`] and [`NAME_SEGMENT_PASSES`] are accumulated with
/// `atomic_add`, so the arriving value is part of the answer.
/// [`NAME_CHANGED`] MUST arrive zeroed: the grid form never clears a word, so a
/// stale set would decode a converged run as budget-exhausted.
///
/// An unobservable-content claim nobody can re-verify mechanically is one
/// refactor away from being false, and the failure mode is a wrong token id
/// with nothing hanging. `poison_seed_does_not_reach_a_contract_abiding_body`
/// and `poison_seed_is_visible_to_a_body_that_skips_a_live_slot` pin it: the
/// first proves a complete body is immune to the staged bytes, the second
/// proves that immunity is not vacuous by showing an incomplete body is not.
const HARNESS_SEED_IS_READ: [bool; HARNESS_BUFFERS] = [
    true,  // wt_loop_current
    false, // wt_loop_next
    true,  // wt_loop_changed
    true,  // wt_loop_passes
    false, // wt_loop_segment_changed
    true,  // wt_loop_segment_passes
];

/// Slot holding a segment's live token count, relative to the segment base.
pub const SLOT_LIVE_LEN: u32 = 0;

/// Slot holding a segment's token 0, relative to the segment base. Token `j`
/// lives at `SLOT_FIRST_TOKEN + j`.
pub const SLOT_FIRST_TOKEN: u32 = 1;

/// Canonical fill for a state slot past a segment's live length.
///
/// Every pass body must write this into dead slots so a pass that merges
/// nothing leaves the array bit-identical. It shares the value of
/// [`crate::Rank::ABSENT`] on purpose: `u32::MAX` is this crate's single
/// "nothing here" marker. It is a FILL, not an end marker; slot 0 remains the
/// authority on liveness, so a real token id of `u32::MAX` stays unambiguous.
pub const DEAD_SLOT: u32 = u32::MAX;

/// Workgroup width of the convergence kernel, fixed by `persistent_fixpoint`.
///
/// This is the width of ONE group, not a batch limit. The state array is padded
/// to a whole number of these, and a batch spanning several of them is the
/// normal case rather than the exception.
///
/// Taken from the primitive's own exported constant rather than restated, so a
/// change to the workgroup size cannot leave this layout math describing a
/// kernel that no longer exists.
pub const LOOP_WORKGROUP_WIDTH: u32 = PERSISTENT_FIXPOINT_WORKGROUP_SIZE[0];

/// Sound pass budget for a batch whose LONGEST pretoken holds `longest` tokens.
///
/// Every merge removes exactly one token, so a pretoken of length n needs at
/// most n-1 merges, and one further pass to observe that nothing changed.
/// Because merging never crosses a pretoken boundary, the bound is the longest
/// segment in the batch, not the length of the input. On a gigabyte corpus the
/// input-length bound would be about a billion and useless as a bug detector;
/// the per-pretoken bound is roughly 32 for real text and actually catches
/// bugs, which is why a cap hit at this bound is a defect rather than a tuning
/// problem.
///
/// Do NOT bound the loop by the number of distinct merge ranks. In real
/// `cl100k_base` a merge can create a pair ranked strictly lower than the rank
/// just consumed: `' ' + '  '` yields `'   '` at rank 262, and `'   ' + ' '`
/// then yields `'    '` at rank 257. The minimum live rank can fall between
/// passes, so a rank-derived bound would cut a correct tokenization short.
#[must_use]
pub const fn merge_pass_bound(longest: u32) -> u32 {
    if longest < 1 { 1 } else { longest }
}

/// Longest pretoken in a batch, in tokens.
#[must_use]
pub fn longest_segment<S: AsRef<[u32]>>(pretokens: &[S]) -> u32 {
    let mut longest = 0usize;
    for pretoken in pretokens {
        let len = pretoken.as_ref().len();
        if len > longest {
            longest = len;
        }
    }
    longest as u32
}

/// Dimensions of one convergence loop.
///
/// Deliberately unvalidated. Every builder in this crate is infallible and
/// lowers an impossible shape to an IR trap instead, so a bad shape surfaces at
/// dispatch with a named parameter rather than as a host-side `Result` the
/// caller may discard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LoopShape {
    segments: u32,
    segment_capacity: u32,
    max_passes: u32,
}

impl LoopShape {
    /// Describe a batch of `segments` pretokens, each holding up to
    /// `segment_capacity` tokens, converging within `max_passes` iterations.
    #[must_use]
    pub const fn new(segments: u32, segment_capacity: u32, max_passes: u32) -> Self {
        Self {
            segments,
            segment_capacity,
            max_passes,
        }
    }

    /// Pretokens in the batch.
    #[must_use]
    pub const fn segments(self) -> u32 {
        self.segments
    }

    /// Token slots each pretoken owns.
    #[must_use]
    pub const fn segment_capacity(self) -> u32 {
        self.segment_capacity
    }

    /// Hard cap on iterations the kernel will run.
    #[must_use]
    pub const fn max_passes(self) -> u32 {
        self.max_passes
    }

    /// State words per segment: the live length slot plus the token slots.
    #[must_use]
    pub const fn stride(self) -> u32 {
        self.segment_capacity + 1
    }

    /// Segments one workgroup holds.
    ///
    /// A segment MUST NOT straddle a workgroup boundary. The pass body
    /// synchronizes its phases with barriers, and a barrier orders writes only
    /// within a workgroup, so two lanes cooperating on one segment must sit in
    /// the same group. Whole segments per group is what enforces that.
    #[must_use]
    pub const fn segments_per_group(self) -> u32 {
        let per = LOOP_WORKGROUP_WIDTH / self.stride();
        if per == 0 { 1 } else { per }
    }

    /// Workgroups this batch dispatches.
    #[must_use]
    pub const fn groups(self) -> u32 {
        let per = self.segments_per_group();
        (self.segments + per - 1) / per
    }

    /// Words each group owns, always a whole number of workgroup widths.
    ///
    /// For any dispatchable shape this is exactly [`LOOP_WORKGROUP_WIDTH`],
    /// because `segments_per_group * stride` cannot exceed the width. It rounds
    /// up only for an over-long segment, whose stride alone exceeds the width.
    /// Such a shape traps rather than dispatching, but it must still be sized
    /// honestly: reporting one width for a segment needing more would hand out a
    /// buffer shorter than [`segment_base`] indexes, and the write past the end
    /// would land in whatever follows rather than being caught.
    ///
    /// [`segment_base`]: LoopShape::segment_base
    #[must_use]
    pub const fn words_per_group(self) -> u32 {
        let used = self.segments_per_group() * self.stride();
        used.div_ceil(LOOP_WORKGROUP_WIDTH) * LOOP_WORKGROUP_WIDTH
    }

    /// Total state words across the batch, including per-group padding.
    ///
    /// Each group owns exactly [`words_per_group`] words and uses the first
    /// `segments_per_group * stride` of them, so the layout is padded rather than
    /// densely packed. The waste is bounded by `stride - 1` words per group and
    /// buys an unbounded number of pretokens per dispatch: segments are
    /// independent, because a merge never crosses a pretoken boundary, so groups
    /// need no ordering between them at all.
    ///
    /// [`words_per_group`]: LoopShape::words_per_group
    #[must_use]
    pub const fn state_words(self) -> u32 {
        self.groups() * self.words_per_group()
    }

    /// First state word belonging to `segment`.
    #[must_use]
    pub const fn segment_base(self, segment: u32) -> u32 {
        let per = self.segments_per_group();
        (segment / per) * self.words_per_group() + (segment % per) * self.stride()
    }

    /// Replace the pass budget, keeping the layout.
    #[must_use]
    pub const fn with_max_passes(self, max_passes: u32) -> Self {
        Self { max_passes, ..self }
    }
}

/// A seeded batch: a shape and the state array that matches it.
///
/// Constructing the two together is what keeps them consistent. The capacity is
/// derived from the pretokens, so no token can be dropped and this is total.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoopBatch {
    shape: LoopShape,
    state: Vec<u32>,
}

impl LoopBatch {
    /// Lay out `pretokens` into one state array.
    ///
    /// Every segment is padded to the longest pretoken so the stride is
    /// uniform, and every slot past a segment's live length is filled with
    /// [`DEAD_SLOT`].
    #[must_use]
    pub fn new<S: AsRef<[u32]>>(pretokens: &[S], max_passes: u32) -> Self {
        // The placeholder shape sizes an empty state, which `reseed` then
        // replaces wholesale, so one layout implementation serves both
        // construction and reuse.
        let mut batch = Self {
            shape: LoopShape::new(0, 1, max_passes),
            state: Vec::new(),
        };
        batch.reseed(pretokens, max_passes);
        batch
    }

    /// Lay out `pretokens` into this batch's state array, keeping its
    /// allocation.
    ///
    /// `crate::device` dispatches one batch per band of an encode, and `new`
    /// plus a drop hands the state array back to the allocator on every
    /// dispatch: thousands of words churned per dispatch for bytes a kept
    /// buffer holds exactly as well. Reseeding is reuse-with-resize, the
    /// pattern [`STAGING_POOL`] applies to its word buffers: `clear` keeps
    /// the capacity, `resize` with [`DEAD_SLOT`] rewrites every word, and
    /// each segment's live prefix is then copied in exactly as [`Self::new`]
    /// writes it, so no word from the previous layout is observable and the
    /// bytes handed to the backend are identical.
    pub(crate) fn reseed<S: AsRef<[u32]>>(&mut self, pretokens: &[S], max_passes: u32) {
        // A zero-token segment still needs its length slot, and a stride of one
        // keeps the layout arithmetic uniform for an all-empty batch.
        let segment_capacity = longest_segment(pretokens).max(1);
        self.shape = LoopShape::new(pretokens.len() as u32, segment_capacity, max_passes);
        self.state.clear();
        self.state.resize(self.shape.state_words() as usize, DEAD_SLOT);
        for (index, pretoken) in pretokens.iter().enumerate() {
            let tokens = pretoken.as_ref();
            let base = self.shape.segment_base(index as u32) as usize;
            self.state[base + SLOT_LIVE_LEN as usize] = tokens.len() as u32;
            let first = base + SLOT_FIRST_TOKEN as usize;
            self.state[first..first + tokens.len()].copy_from_slice(tokens);
        }
    }

    /// Lay out `pretokens` with the pass budget [`merge_pass_bound`] derives
    /// from the longest one.
    #[must_use]
    pub fn with_sound_bound<S: AsRef<[u32]>>(pretokens: &[S]) -> Self {
        Self::new(pretokens, merge_pass_bound(longest_segment(pretokens)))
    }

    /// Shape this batch was laid out with.
    #[must_use]
    pub const fn shape(&self) -> LoopShape {
        self.shape
    }

    /// Seed state array.
    #[must_use]
    pub fn state(&self) -> &[u32] {
        &self.state
    }
}

/// Why the loop stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Termination {
    /// A whole pass changed no segment. The batch is a true fixed point.
    Converged,
    /// The pass budget ran out with at least one segment still changing. Those
    /// segments hold a partial merge, not a tokenization.
    CapReached,
}

impl Termination {
    /// True only for a genuine fixed point.
    #[must_use]
    pub const fn is_converged(self) -> bool {
        matches!(self, Self::Converged)
    }
}

/// Result of running a convergence loop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoopOutcome {
    shape: LoopShape,
    state: Vec<u32>,
    passes: u32,
    segment_passes: Vec<u32>,
    segment_changed: Vec<u32>,
    termination: Termination,
}

impl LoopOutcome {
    /// An outcome assembled from its parts.
    ///
    /// Exists for tests and harness fixtures. Production outcomes come only
    /// from a dispatch a backend actually ran, through
    /// `PassWindow::into_outcome`, and a fixture needs states no real run
    /// produces: a capped loop whose every segment held still is unreachable
    /// from the loop itself, since such a run reports converged, but it is
    /// exactly the state that drives the per-segment fallback the assembly
    /// path must keep byte-identical.
    #[must_use]
    pub fn from_parts(
        shape: LoopShape,
        state: Vec<u32>,
        passes: u32,
        segment_passes: Vec<u32>,
        segment_changed: Vec<u32>,
        termination: Termination,
    ) -> Self {
        Self {
            shape,
            state,
            passes,
            segment_passes,
            segment_changed,
            termination,
        }
    }

    /// Full state array as read back, including every length slot and
    /// [`DEAD_SLOT`] tail. This is what an equivalence check compares.
    #[must_use]
    pub fn state(&self) -> &[u32] {
        &self.state
    }

    /// Shape the loop ran with.
    #[must_use]
    pub const fn shape(&self) -> LoopShape {
        self.shape
    }

    /// Live token count of `segment`, clamped to the segment capacity.
    #[must_use]
    pub fn live_len(&self, segment: u32) -> u32 {
        let base = self.shape.segment_base(segment) as usize;
        self.state
            .get(base + SLOT_LIVE_LEN as usize)
            .copied()
            .unwrap_or(0)
            .min(self.shape.segment_capacity())
    }

    /// Live tokens of `segment`, regardless of how the loop stopped.
    ///
    /// Prefer [`Self::converged_tokens`] on any path that feeds a model.
    #[must_use]
    pub fn tokens(&self, segment: u32) -> &[u32] {
        let base = self.shape.segment_base(segment) as usize;
        let start = base + SLOT_FIRST_TOKEN as usize;
        let end = start + self.live_len(segment) as usize;
        self.state.get(start..end).unwrap_or(&[])
    }

    /// Live tokens of `segment`, but only from a segment that reached a fixed
    /// point.
    ///
    /// A segment that changed nothing during the final pass IS converged, even
    /// when a sibling exhausted the budget, because segments are independent
    /// and a fixed point cannot move again.
    ///
    /// # Errors
    ///
    /// Returns [`ExatokError`] when the budget ran out while this segment was
    /// still changing. Such a segment still yields a well-formed token array,
    /// so accepting it silently would ship a truncated tokenization.
    pub fn converged_tokens(&self, segment: u32) -> Result<&[u32], ExatokError> {
        if self.termination.is_converged() || self.segment_changed(segment) == 0 {
            return Ok(self.tokens(segment));
        }
        Err(ExatokError::Divergence {
            byte_offset: segment as usize,
            host: None,
            device: self.tokens(segment).first().copied().map(crate::TokenId),
            fix: format!(
                "segment {segment} was still merging after {} pass(es) of a {} pass budget, so \
                 its {} live token(s) are a partial merge. Every merge drops one token, so \
                 merge_pass_bound(longest pretoken) always suffices: a cap hit at that bound is \
                 a pass-body bug, not a budget to raise. This dispatch used {} workgroup(s) over \
                 {} segment(s); ONE workgroup rules out every cross-group cause, so a failure \
                 here is intra-workgroup. Both defects that produced this exact message were \
                 intra-workgroup ordering bugs that needed no concurrency and no second \
                 dispatch: a missing barrier on `persistent_fixpoint`'s loop back edge, and a \
                 `_vyre_grid_barrier` counter left unzeroed between grid-sync launches of one \
                 module. Check the pass body and the primitive's barriers before suspecting \
                 anything above them.",
                self.passes,
                self.shape.max_passes(),
                self.live_len(segment),
                self.shape.groups(),
                self.shape.segments()
            ),
        })
    }

    /// Live tokens of every segment in order, from a fully converged run only.
    ///
    /// One termination check for the whole batch, where [`Self::converged_tokens`]
    /// pays one per segment. A converged run has nothing per segment left to
    /// guard, so this walks the state array group by group with the layout
    /// arithmetic done once and hands out each segment's live tokens without a
    /// `Result`, a `segment_changed` load, or the repeated bounds checks the
    /// per-segment path pays. The slices are exactly what `converged_tokens`
    /// returns for the same segments; only the per-segment machinery is gone.
    ///
    /// Returns `None` when the budget ran out. A capped batch must take the
    /// per-segment path, because WHICH segments refuse is per-segment
    /// information this batch-level view deliberately does not carry.
    ///
    /// The walk leans on the layout: `used` words per group is
    /// `segments_per_group * stride`, never past `words_per_group` by that
    /// field's own definition, and a segment chunk is `stride` words, so
    /// `SLOT_FIRST_TOKEN + live.min(capacity)` can never index past it. The
    /// `take` drops the padding segments of a partial last group, whose live
    /// length slots hold [`DEAD_SLOT`] and must not be read as counts.
    pub fn converged_segments(&self) -> Option<impl Iterator<Item = &[u32]> + '_> {
        if !self.termination.is_converged() {
            return None;
        }
        let stride = self.shape.stride() as usize;
        let used = self.shape.segments_per_group() as usize * stride;
        let capacity = self.shape.segment_capacity();
        let segments = self.shape.segments() as usize;
        Some(
            self.state
                .chunks_exact(self.shape.words_per_group() as usize)
                .flat_map(move |group| group[..used].chunks_exact(stride))
                .take(segments)
                .map(move |segment| {
                    let live = segment[SLOT_LIVE_LEN as usize].min(capacity) as usize;
                    &segment[SLOT_FIRST_TOKEN as usize..SLOT_FIRST_TOKEN as usize + live]
                }),
        )
    }

    /// Iterations the kernel entered, including the final unchanged pass.
    #[must_use]
    pub const fn passes(&self) -> u32 {
        self.passes
    }

    /// Passes in which `segment` changed. Its convergence depth is this plus
    /// the one pass that observed no change.
    #[must_use]
    pub fn segment_passes(&self, segment: u32) -> u32 {
        self.segment_passes
            .get(segment as usize)
            .copied()
            .unwrap_or(0)
    }

    /// Non-zero when `segment` was still changing on the final pass.
    #[must_use]
    pub fn segment_changed(&self, segment: u32) -> u32 {
        self.segment_changed
            .get(segment as usize)
            .copied()
            .unwrap_or(0)
    }

    /// Segments that had not reached a fixed point when the loop stopped.
    /// Empty for a converged run, and the localized diagnosis for a capped one.
    #[must_use]
    pub fn unconverged_segments(&self) -> Vec<u32> {
        self.segment_changed
            .iter()
            .enumerate()
            .filter(|(_, changed)| **changed != 0)
            .map(|(index, _)| index as u32)
            .collect()
    }

    /// Why the loop stopped.
    #[must_use]
    pub const fn termination(&self) -> Termination {
        self.termination
    }
}

impl Drop for LoopOutcome {
    /// Hand the outcome's buffers back to this thread's staging pool.
    ///
    /// The state array and the two per-segment tallies are the three largest
    /// buffers a dispatch produces, and the caller drops the outcome before
    /// the next dispatch is seeded, so parking them here is what lets the
    /// next [`PassWindow::seed`] reuse them instead of allocating at state
    /// size again. A caller that keeps an outcome alive simply keeps its
    /// buffers out of the pool that long; correctness never depends on the
    /// park happening.
    fn drop(&mut self) {
        let _ = STAGING_POOL.try_with(|pool| {
            let pool = &mut *pool.borrow_mut();
            park(&mut pool.current, std::mem::take(&mut self.state));
            park(
                &mut pool.segment_passes,
                std::mem::take(&mut self.segment_passes),
            );
            park(
                &mut pool.segment_changed,
                std::mem::take(&mut self.segment_changed),
            );
        });
    }
}

/// Build the single-dispatch convergence program.
///
/// `pass_body` performs ONE pass over every segment; see the module contract.
/// `caller_buffers` declares the bindings that body reads, numbered from
/// [`FIRST_CALLER_BINDING`].
///
/// Infallible by design: an impossible shape lowers to an IR trap naming the
/// offending parameter.
#[must_use]
pub fn device_loop_program(
    shape: LoopShape,
    pass_body: Vec<Node>,
    caller_buffers: Vec<BufferDecl>,
) -> Program {
    build_loop_program(
        OP_ID,
        shape,
        shape.max_passes(),
        pass_body,
        caller_buffers,
        StateReadback::Discarded,
    )
}

/// Build the same program capped at one pass, for a host-driven loop.
///
/// This is the honest comparison for [`device_loop_program`]: identical pass
/// body, identical compare, identical ping-pong, identical buffers. Only the
/// loop driver moves from the kernel to the host, so any difference in the
/// final state is attributable to device-side convergence alone.
#[must_use]
pub fn single_pass_program(
    shape: LoopShape,
    pass_body: Vec<Node>,
    caller_buffers: Vec<BufferDecl>,
) -> Program {
    build_loop_program(
        OP_ID_SINGLE_PASS,
        shape,
        1,
        pass_body,
        caller_buffers,
        StateReadback::Discarded,
    )
}

/// [`single_pass_program`] with [`NAME_STATE_NEXT`] returned at full width.
///
/// For asserting on the state the pass body WROTE, which the shipped narrowing
/// makes invisible. [`LoopOutcome`] is no substitute: it rewrites every unowned
/// word to [`DEAD_SLOT`] on readback, so a padding assertion taken from an
/// outcome cannot fail. The scale-boundary suite needs the raw buffer to check
/// that unowned words really are [`DEAD_SLOT`] and that no OWNED word came back
/// unwritten, the second being a direct witness for a stale value folded into
/// state with convergence reported over it.
///
/// Identical to [`single_pass_program`] in every other respect: same op id, same
/// body, same bindings, same counts. Only the declared readback window of the
/// back buffer differs, so a test using this observes the same kernel the
/// shipped path runs.
#[must_use]
pub fn single_pass_program_returning_state(
    shape: LoopShape,
    pass_body: Vec<Node>,
    caller_buffers: Vec<BufferDecl>,
) -> Program {
    build_loop_program(
        OP_ID_SINGLE_PASS,
        shape,
        1,
        pass_body,
        caller_buffers,
        StateReadback::Full,
    )
}

/// Run the whole loop in one dispatch.
///
/// # Errors
///
/// Returns [`ExatokError::Backend`] when the dispatch fails or returns fewer
/// buffers than the harness declares.
pub fn run_device_loop(
    backend: &dyn VyreBackend,
    program: &Program,
    batch: &LoopBatch,
    caller_inputs: &[Vec<u8>],
) -> Result<LoopOutcome, ExatokError> {
    let borrowed: Vec<&[u8]> = caller_inputs.iter().map(Vec::as_slice).collect();
    run_device_loop_borrowed(backend, program, batch, &host_inputs(&borrowed))
}

/// [`run_device_loop`] over caller buffers this call does not own.
///
/// The whole dispatch path holds its caller buffers as slices, so a caller that
/// keeps a packed buffer alive across dispatches hands out a borrow instead of a
/// copy. `crate::device` uploads one 16 MiB merge table per dispatch and holds
/// the packed bytes for the tokenizer's lifetime, so an owned parameter here
/// would memcpy that table on every dispatch for no gain.
///
/// Internal, and the owned form above delegates to it, so there is still ONE
/// dispatch path rather than two that can drift.
///
/// # Errors
///
/// Same as [`run_device_loop`].
pub(crate) fn run_device_loop_borrowed(
    backend: &dyn VyreBackend,
    program: &Program,
    batch: &LoopBatch,
    caller_inputs: &[CallerInput<'_>],
) -> Result<LoopOutcome, ExatokError> {
    let mut window = PassWindow::seed(batch);
    dispatch_window(backend, program, batch.shape(), &mut window, caller_inputs)?;
    Ok(window.into_outcome(batch.shape()))
}

/// Run the loop from the host, dispatching `one_pass` once per iteration.
///
/// `one_pass` must come from [`single_pass_program`]. The host takes the role
/// the kernel plays in [`run_device_loop`]: resubmit the ping-pong buffers,
/// read the convergence flag, stop on a clean pass or on the shape's budget.
///
/// # Errors
///
/// Same as [`run_device_loop`].
pub fn run_host_driven_loop(
    backend: &dyn VyreBackend,
    one_pass: &Program,
    batch: &LoopBatch,
    caller_inputs: &[Vec<u8>],
) -> Result<LoopOutcome, ExatokError> {
    let shape = batch.shape();
    // Borrowed once rather than per pass. The caller's buffers do not change
    // between iterations, so re-borrowing them inside the loop would put back a
    // per-dispatch cost for nothing.
    let borrowed: Vec<&[u8]> = caller_inputs.iter().map(Vec::as_slice).collect();
    let inputs = host_inputs(&borrowed);
    let mut window = PassWindow::seed(batch);
    for _ in 0..shape.max_passes() {
        dispatch_window(backend, one_pass, shape, &mut window, &inputs)?;
        if !window.any_segment_moved() {
            break;
        }
    }
    Ok(window.into_outcome(shape))
}

/// Live state plus the report words, carried between dispatches.
///
/// The ping-pong BACK buffer is deliberately not mirrored here. Every pass
/// writes `next` whole, tokens by the pass body and the padding tail by
/// `close_pass`, before anything reads it, and the primitive copies it into
/// `current` at the end of the pass. So no value the host puts in it is ever
/// observed and no value it returns is ever used: it needs a device allocation
/// and a staged byte LENGTH, never a host copy of its contents.
///
/// Every heap buffer lives in [`Staging`], which outlives one window: a window
/// is seeded per dispatch on the encode path, so per-window buffers would be
/// per-dispatch allocations, and those are the cost [`STAGING_POOL`] exists to
/// remove.
struct PassWindow {
    staging: Staging,
    passes: u32,
}

/// Every heap buffer a dispatch stages or lands, owned by one thread across
/// the whole encode rather than by one window.
///
/// The encode path seeds a fresh [`PassWindow`] per dispatch, so any buffer
/// the window OWNS is allocated once per dispatch: the state array is
/// thousands of words, and the copy chain the recon measured (a `to_vec` of
/// the seed state, a [`DEAD_SLOT`] fill plus its packed bytes, and a re-pack
/// of `current` before every dispatch) was three state-sized allocations per
/// dispatch whose bytes either never changed or never reached the device at
/// all. Keeping the buffers here and parking them in [`STAGING_POOL`] when a
/// dispatch finishes turns that into reuse-with-resize: after the first
/// dispatch of an encode, staging allocates nothing at state size.
///
/// The stable lifetimes are also the prerequisite the graph-replay note on
/// [`dispatch_resident`] names. Replay needs the same program AND the same
/// pointers across an encode's dispatches; the host side of that is exactly
/// these buffers, so they are laid out as one struct a later arena or graph
/// cache can take over wholesale.
///
/// Reuse-with-resize is only sound because every buffer is rewritten whole
/// before any read: `seed` clears and refills the word buffers and repacks
/// `current`, `dispatch_window` repacks the four wire buffers in place before
/// binding them, `next_filler` is validated by LENGTH before it is uploaded,
/// and `changed_filler` is zero from construction to drop. A stale word from
/// the previous dispatch is therefore never observable, which is the same
/// argument [`HARNESS_SEED_IS_READ`] makes for the device side.
#[derive(Debug, Default)]
struct Staging {
    /// Canonical state words: seeded from the batch, read back into after
    /// every dispatch, and moved into the [`LoopOutcome`] at the end.
    current: Vec<u32>,
    /// Per-segment count of passes in which the segment changed.
    segment_passes: Vec<u32>,
    /// Per-segment verdict of the most recent pass; the termination signal.
    segment_changed: Vec<u32>,
    /// Landing buffer for the primitive's own `changed` words. Never consulted
    /// for the verdict, kept so the readback can validate the width instead of
    /// allocating one per dispatch.
    changed: Vec<u32>,
    /// `current` in wire format, repacked in place before every dispatch.
    ///
    /// Seeded straight from the batch by [`pack_u32_slice_into`], which is
    /// what removes the old `to_vec` plus re-pack pair: the seed state crosses
    /// into wire bytes exactly once, and later dispatches repack the readback
    /// into this same allocation.
    current_bytes: Vec<u8>,
    /// The one-word pass counter in wire format, repacked in place.
    passes_bytes: Vec<u8>,
    /// `segment_changed` in wire format, repacked in place. The borrowed path
    /// uploads it; the resident path consults only its length, because
    /// `open_pass` zeroes every flag on device before any read.
    segment_changed_bytes: Vec<u8>,
    /// `segment_passes` in wire format, repacked in place.
    segment_passes_bytes: Vec<u8>,
    /// Bytes staged for [`NAME_STATE_NEXT`], built lazily and only for the
    /// borrowed path.
    ///
    /// The resident path never uploads these bytes, so on the encode path the
    /// buffer is never built: the binding carries a length instead (see
    /// [`ResidentBinding::Overwritten`]). A backend without resident buffers
    /// still needs one slice per input binding, and it gets a [`DEAD_SLOT`]
    /// fill rather than zeros so a pass body that skips a live slot surfaces
    /// there as a marker instead of as a plausible token id of zero.
    next_filler: Vec<u8>,
    /// Zero bytes staged for [`NAME_CHANGED`], sized once per declared width.
    ///
    /// `changed` MUST arrive zeroed on every dispatch: the grid form never
    /// clears a word, so a stale set would decode a converged run as
    /// budget-exhausted. Reusing one buffer keeps that guarantee because
    /// nothing ever writes it. The readback lands in `changed` above, so
    /// these bytes are zero from construction to drop, which the old
    /// `pack_u32_slice(&vec![0; changed])` site achieved by allocating twice
    /// per dispatch instead.
    changed_filler: Vec<u8>,
}

thread_local! {
    /// Staging one thread has finished with, waiting for its next dispatch.
    ///
    /// Thread-local because the pool needs no synchronization: an encode's
    /// dispatches run sequentially on the caller's thread, so a per-thread
    /// stash is never contended, and two threads encoding concurrently get one
    /// stash each, which is exactly the working set they would allocate
    /// anyway. Buffers are parked with their capacity intact, so a steady
    /// caller reaches a fixed point where a dispatch allocates nothing here.
    static STAGING_POOL: RefCell<Staging> = RefCell::new(Staging::default());
}

/// Largest capacity the pool keeps, in bytes.
///
/// Parking is bounded so one outsized batch does not pin its buffers for the
/// life of the thread: anything larger is handed back to the allocator, and a
/// later dispatch of that size pays for it again.
const MAX_PARKED_CAPACITY: usize = 64 << 20;

/// Take the staging this thread parked, or empty buffers if none is waiting.
///
/// `try_with` rather than `with` so a call landing during thread-local
/// teardown gets empty staging instead of a panic.
fn take_staging() -> Staging {
    STAGING_POOL
        .try_with(|pool| std::mem::take(&mut *pool.borrow_mut()))
        .unwrap_or_default()
}

/// Park `buffer` in `slot`, keeping whichever has the larger capacity.
///
/// Keep-larger rather than last-wins so an outsized dispatch followed by a
/// small one does not shrink the pool and force the next large dispatch to
/// allocate again. Past [`MAX_PARKED_CAPACITY`] the buffer is dropped instead,
/// bounding what an idle thread can pin.
fn park<T>(slot: &mut Vec<T>, buffer: Vec<T>) {
    if buffer.capacity() > slot.capacity() && buffer.capacity() <= MAX_PARKED_CAPACITY {
        *slot = buffer;
    }
}

/// Return every buffer a finished window can offer the next dispatch.
///
/// The three buffers [`PassWindow::into_outcome`] moves into the
/// [`LoopOutcome`] arrive empty here, and `park` ignores an empty buffer, so
/// one function serves both parking sites.
fn park_staging(staging: Staging) {
    let _ = STAGING_POOL.try_with(|pool| {
        let pool = &mut *pool.borrow_mut();
        park(&mut pool.current, staging.current);
        park(&mut pool.segment_passes, staging.segment_passes);
        park(&mut pool.segment_changed, staging.segment_changed);
        park(&mut pool.changed, staging.changed);
        park(&mut pool.current_bytes, staging.current_bytes);
        park(&mut pool.passes_bytes, staging.passes_bytes);
        park(&mut pool.segment_changed_bytes, staging.segment_changed_bytes);
        park(&mut pool.segment_passes_bytes, staging.segment_passes_bytes);
        park(&mut pool.next_filler, staging.next_filler);
        park(&mut pool.changed_filler, staging.changed_filler);
    });
}

impl PassWindow {
    fn seed(batch: &LoopBatch) -> Self {
        let shape = batch.shape();
        let segments = shape.segments() as usize;
        let mut staging = take_staging();
        // Reuse-with-resize: every word buffer keeps its allocation from the
        // previous dispatch and is rewritten whole here, so no stale word is
        // observable and no allocation repeats once the pool holds the
        // shape's high-water sizes.
        staging.current.clear();
        staging.current.extend_from_slice(batch.state());
        // The seed state crosses into wire format exactly once, straight into
        // the reused buffer: no `to_vec` to re-pack later.
        pack_u32_slice_into(batch.state(), &mut staging.current_bytes);
        staging.segment_passes.clear();
        staging.segment_passes.resize(segments, 0);
        staging.segment_changed.clear();
        staging.segment_changed.resize(segments, 0);
        staging.changed.clear();
        // `next_filler` is deliberately NOT reset or built here: the resident
        // path never reads it, and the borrowed path builds it on first use.
        Self { staging, passes: 0 }
    }

    /// Size the `changed` staging bytes to the width the program declares.
    ///
    /// Reallocates only when the width changes, which for one window means the
    /// first dispatch only: a window is threaded through dispatches of a
    /// single program, so the declared width is constant after that.
    fn size_changed_filler(&mut self, words: u32) {
        let bytes = words as usize * 4;
        if self.staging.changed_filler.len() != bytes {
            self.staging.changed_filler = vec![0; bytes];
        }
    }

    /// True while any segment moved on the most recent pass.
    ///
    /// This, and never the global `changed` word, is the termination signal.
    /// That word is cleared by a plain store from lane 0 ordered only by a
    /// workgroup barrier, so once a batch spans more than one group nothing
    /// orders one group's clear against another group's set and the word stops
    /// describing the run. Each segment's flag is cleared by that segment's own
    /// slot-0 lane and set by `atomic_or` from lanes of the same segment, all
    /// inside one group and ordered by that group's barriers, so it is race-free
    /// by construction.
    ///
    /// Reading it here also fails closed. A group that exits early under the
    /// race leaves its segments non-zero, so the caller gets a refusal from
    /// [`LoopOutcome::converged_tokens`] rather than a silently truncated
    /// tokenization.
    fn any_segment_moved(&self) -> bool {
        self.staging
            .segment_changed
            .iter()
            .any(|changed| *changed != 0)
    }

    fn into_outcome(mut self, shape: LoopShape) -> LoopOutcome {
        normalize_padding(shape, &mut self.staging.current);
        let converged = !self.any_segment_moved();
        let mut staging = self.staging;
        let outcome = LoopOutcome {
            shape,
            state: std::mem::take(&mut staging.current),
            passes: self.passes,
            segment_passes: std::mem::take(&mut staging.segment_passes),
            segment_changed: std::mem::take(&mut staging.segment_changed),
            termination: if converged {
                Termination::Converged
            } else {
                Termination::CapReached
            },
        };
        // What remains is pure staging: offer it to the next dispatch. The
        // three buffers the outcome took come back through `LoopOutcome`'s
        // own drop, so the pool is whole again once the caller is done.
        park_staging(staging);
        outcome
    }
}

/// Overwrite every state word no segment owns with [`DEAD_SLOT`].
///
/// The padded layout leaves gaps: the tail of a group when `stride` does not
/// divide the width, and the whole remainder of the final group when `segments`
/// does not fill it. Nothing reads those words, so a pass body is free to leave
/// anything in them, and what it leaves depends on how many lanes the backend
/// launched. The reference interpreter plans its grid from `dispatch_elements`
/// and the CUDA driver from `grid_override`, so the two genuinely disagree there.
///
/// That would make [`LoopOutcome::state`] backend-dependent in words that carry
/// no meaning, and a differential test comparing whole state arrays would fail on
/// garbage rather than on tokenization. Normalizing here keeps that comparison
/// honest: every word is either a segment's or the canonical dead marker.
fn normalize_padding(shape: LoopShape, state: &mut [u32]) {
    let owned = shape.segments_per_group() * shape.stride();
    let width = shape.words_per_group() as usize;
    for (index, word) in state.iter_mut().enumerate() {
        let offset = index % width;
        let group = index / width;
        let segment = group as u32 * shape.segments_per_group() + offset as u32 / shape.stride();
        if offset as u32 >= owned || segment >= shape.segments() {
            *word = DEAD_SLOT;
        }
    }
}

/// Decide whether a grid-synchronized dispatch may proceed.
///
/// `GridSync` lowers to a native cooperative launch on CUDA, and a cooperative
/// launch requires every block co-resident. Past that ceiling a backend has two
/// escapes and both are silent failures at this layer: a host kernel split turns
/// the single dispatch this module exists for into a launch per wave, and
/// shrinking the grid leaves segments without lanes, returning a truncated
/// tokenization. Both would still report success, so this refuses and names the
/// numbers instead.
///
/// A backend that permits the host split (the reference interpreter, whose
/// default is `true`) attempts no cooperative launch and so has no residency to
/// exceed, and is left alone. CUDA sets it `false` precisely so the split cannot
/// happen behind the caller's back.
///
/// `limit` is a thunk because recovering the number costs a bisection over the
/// backend's fit predicate, and neither accepting path needs it.
fn cooperative_gate(
    fits: bool,
    allows_split: bool,
    blocks: u32,
    limit: impl FnOnce() -> u32,
) -> Result<(), ExatokError> {
    if fits || allows_split {
        return Ok(());
    }
    let limit = limit();
    if limit == 0 {
        return Err(ExatokError::Backend(format!(
            "gpu_loop needs {blocks} co-resident block(s) to grid-synchronize this batch, \
             but this backend admits no cooperative launch of this program at any grid \
             size and refuses a host kernel split. \
             Fix: run a single-group batch, which needs no grid synchronization at all"
        )));
    }
    Err(ExatokError::Backend(format!(
        "gpu_loop needs {blocks} co-resident block(s) to grid-synchronize this batch, \
         but this device admits at most {limit}. \
         Fix: dispatch fewer pretokens per batch so the grid fits in {limit} block(s). \
         Lowering the group count instead would leave segments without lanes"
    )))
}

/// Largest block count under `ceiling` for which `fits_at` answers yes.
///
/// [`VyreBackend::cooperative_grid_sync_fits`] answers yes or no for one
/// geometry and never reports the device's limit, but that limit is exactly the
/// number a caller needs in order to split the batch. Bisecting the predicate
/// recovers it.
///
/// `fits_at` returns `None` when the geometry query itself failed. Further
/// probes are then untrustworthy, so the search stops and reports the largest
/// count already proven to fit, which is always a safe under-estimate.
fn probe_block_limit(ceiling: u32, mut fits_at: impl FnMut(u32) -> Option<bool>) -> u32 {
    // Invariant: `low` fits or is zero, `high` is known not to fit. The caller
    // reaches here only once `ceiling` itself has failed, which establishes it.
    let mut low = 0;
    let mut high = ceiling;
    while high - low > 1 {
        let mid = low + (high - low) / 2;
        match fits_at(mid) {
            Some(true) => low = mid,
            Some(false) => high = mid,
            None => return low,
        }
    }
    low
}

/// Ask the backend whether this cooperative launch fits, and refuse if not.
///
/// Thin adapter over [`cooperative_gate`]: everything decidable without a
/// backend lives there so it can be tested directly, because [`VyreBackend`] is
/// sealed and cannot be doubled from this crate.
fn check_cooperative_residency(
    backend: &dyn VyreBackend,
    program: &Program,
    inputs: &[&[u8]],
    config: &DispatchConfig,
    blocks: u32,
) -> Result<(), ExatokError> {
    let fits = backend
        .cooperative_grid_sync_fits(program, inputs, config)
        .map_err(|error| {
            ExatokError::Backend(format!(
                "gpu_loop could not compute the cooperative launch geometry: {error}. \
                 Fix: rebuild the backend and retry, because the geometry predicate answering \
                 at all is a driver-level property no batch shape can repair"
            ))
        })?;
    cooperative_gate(fits, backend.allows_host_grid_sync_split(), blocks, || {
        probe_block_limit(blocks, |candidate| {
            let mut probe = config.clone();
            probe.grid_override = Some([candidate, 1, 1]);
            backend
                .cooperative_grid_sync_fits(program, inputs, &probe)
                .ok()
        })
    })
}

/// Words the program declares for [`NAME_CHANGED`].
///
/// One for the in-kernel form, one per pass for the grid form, which never
/// clears a word and so needs a fresh one each wave. Read off the program's own
/// buffer table rather than recomputed from the shape, so the host buffer is by
/// construction the width the kernel was built for: recomputing it would put
/// the same rule in two places and let them drift.
fn changed_words(program: &Program) -> u32 {
    program
        .buffers()
        .iter()
        .find(|buffer| buffer.name.as_ref() == NAME_CHANGED)
        .map_or(1, |buffer| buffer.count.max(1))
}

/// The dispatch geometry for one loop launch, and the block count it implies.
///
/// Shared by the dispatch path and by [`cooperative_block_ceiling`] so the
/// residency a caller measures is the residency the dispatch will actually ask
/// for. Measuring one geometry and launching another would report a ceiling
/// that does not hold.
fn launch_geometry(program: &Program, shape: LoopShape) -> (DispatchConfig, u32) {
    let mut config = DispatchConfig::default();
    // The reference interpreter infers its grid from buffer shapes, so state the
    // element count outright: one lane per state word.
    config.dispatch_elements = Some(shape.state_words());
    // The CUDA driver never consults `dispatch_elements`. It plans through
    // `infer_dispatch_grid`, which honours `grid_override` and otherwise infers
    // a grid from the widest non-shared binding. That inference happens to equal
    // the lane count here only because the state array is the widest buffer this
    // harness binds; a caller that binds a rank table (233,378 words for cl100k,
    // 446,189 for o200k) against a state array in the hundreds would over-dispatch
    // by three orders of magnitude and run live lanes past the end of its state.
    // So the grid is specified rather than inferred, with `workgroup_override`
    // carried alongside per `grid_override`'s contract.
    let workgroup = program.workgroup_size();
    let lanes_per_group = workgroup[0].max(1) * workgroup[1].max(1) * workgroup[2].max(1);
    let groups = shape.state_words().div_ceil(lanes_per_group);
    config.grid_override = Some([groups.max(1), 1, 1]);
    config.workgroup_override = Some(workgroup);
    config.label = Some(OP_ID.to_owned());
    (config, groups.max(1))
}

/// Zero-filled buffers matching every binding `program` declares.
///
/// A residency query plans launch geometry from the bindings and never reads
/// the contents, so the sizes are the only part that has to be right. Every
/// buffer this module binds is `U32`, hence four bytes per element.
fn probe_inputs(program: &Program) -> Vec<Vec<u8>> {
    program
        .buffers()
        .iter()
        .map(|buffer| vec![0u8; buffer.count.max(1) as usize * 4])
        .collect()
}

/// Largest workgroup count this backend admits for one grid-synchronized
/// dispatch of `program`.
///
/// Multiply by [`LoopShape::segments_per_group`] for the ceiling in pretokens
/// per dispatch, which is what a caller sizing a batch actually needs. At a
/// four-token pretoken the stride is five, so a 256-word group holds 51 whole
/// segments and not 64: the length word occupies one slot per segment.
///
/// Returns zero when the backend admits no cooperative launch of this program
/// at any size. That is the correct answer, not a failure, for a single-group
/// program: it carries no `GridSync` barrier and needs none, so there is
/// nothing to launch cooperatively.
///
/// The search doubles until the backend refuses, then bisects, so the answer is
/// the device's ceiling rather than a verdict on the batch in hand.
///
/// This is an upper bound on an upper bound. The preflight it queries bounds
/// THREAD residency, `(max_threads_per_sm / workgroup) * sm_count`, which is
/// 1020 for a 256-wide block on an RTX 5090. Register and shared-memory
/// pressure from the pass body tighten it further, and that stricter per-kernel
/// occupancy bound is only enforced at launch. So a batch under this ceiling
/// can still be refused by the device, with the numbers named; treat the value
/// as a ceiling to stay well under, never as a capacity to fill.
#[must_use]
pub fn cooperative_block_ceiling(
    backend: &dyn VyreBackend,
    program: &Program,
    shape: LoopShape,
) -> u32 {
    if !contains_grid_sync(program) {
        return 0;
    }
    let inputs = probe_inputs(program);
    let borrowed: Vec<&[u8]> = inputs.iter().map(Vec::as_slice).collect();
    let (config, _) = launch_geometry(program, shape);
    let fits_at = |blocks: u32| {
        let mut probe = config.clone();
        probe.grid_override = Some([blocks, 1, 1]);
        backend
            .cooperative_grid_sync_fits(program, &borrowed, &probe)
            .ok()
    };

    if fits_at(1) != Some(true) {
        return 0;
    }
    // Double until refusal to bracket the ceiling from above, since the caller's
    // own block count says nothing about where the device stops.
    let mut ceiling = 2;
    while fits_at(ceiling) == Some(true) {
        match ceiling.checked_mul(2) {
            Some(doubled) => ceiling = doubled,
            // Every block count representable in the grid fits.
            None => return u32::MAX,
        }
    }
    probe_block_limit(ceiling, fits_at)
}

/// One caller buffer, either host bytes or a buffer already on the device.
///
/// Exists because the merge table is 16 MiB of immutable bytes that vyre
/// re-uploaded on EVERY dispatch: prose moved four identical copies per encode,
/// which measured as 88 to 96 percent of the per-dispatch fixed cost. Uploading
/// it once and binding the handle afterwards is the whole point.
///
/// [`Self::Resident`] keeps `bytes` alongside the handle. That is not
/// redundancy: the cooperative-residency query is a function of the binding
/// SIZES, so it still needs to see how wide every buffer is, and it is a pure
/// query that uploads nothing. Dropping `bytes` would mean either re-deriving
/// the width from the program or skipping the check, and skipping it turns a
/// clean refusal into a failed cooperative launch.
/// `Copy` because both variants hold only shared references, so a caller that
/// threads one table binding through several dispatches passes it by value
/// instead of re-matching on it at each call.
#[derive(Clone, Copy)]
pub(crate) enum CallerInput<'a> {
    /// Uploaded as part of this dispatch, as every buffer used to be.
    Host(&'a [u8]),
    /// Already uploaded. Bound by handle, and NOT transferred again.
    Resident {
        /// Handle from [`VyreBackend::allocate_resident`], owned by the caller.
        resource: &'a Resource,
        /// The same bytes the handle holds, for geometry queries only.
        bytes: &'a [u8],
    },
}

impl<'a> CallerInput<'a> {
    /// The buffer's bytes, wherever it currently lives.
    const fn bytes(&self) -> &'a [u8] {
        match self {
            Self::Host(bytes) | Self::Resident { bytes, .. } => bytes,
        }
    }

    /// The handle, when this buffer is already on the device.
    const fn resident(&self) -> Option<&'a Resource> {
        match self {
            Self::Host(_) => None,
            Self::Resident { resource, .. } => Some(resource),
        }
    }
}

/// Wrap host slices as caller inputs, uploading all of them per dispatch.
///
/// The pre-residency behaviour, kept for the paths that have no resident buffer
/// to bind and for backends that do not implement residency at all.
fn host_inputs<'a>(caller_inputs: &[&'a [u8]]) -> Vec<CallerInput<'a>> {
    caller_inputs
        .iter()
        .map(|bytes| CallerInput::Host(bytes))
        .collect()
}

/// What one binding hands the resident dispatch.
///
/// The two cases are exactly the two rows of [`HARNESS_SEED_IS_READ`]. A
/// binding the kernel reads arrives with its host bytes, which are uploaded
/// after the device allocation. A binding the kernel provably overwrites
/// before any read arrives as a bare LENGTH: no host buffer is ever built for
/// it, because allocating without a following [`VyreBackend::upload_resident`]
/// IS a device buffer with no host-to-device leg, which is a different thing
/// from a zero-length binding (refused below) or from a backend-allocated
/// output (which would drop the buffer out of the input list and renumber
/// every binding after it).
enum ResidentBinding<'a> {
    /// Host bytes to upload; the kernel reads what the buffer arrives holding.
    Staged(&'a [u8]),
    /// A device allocation of this many bytes and no upload. The bytes the
    /// borrowed path would have staged are never built on this path, which is
    /// the state-sized allocation per dispatch the encode no longer pays.
    Overwritten(usize),
}

impl ResidentBinding<'_> {
    /// Bytes of device memory this binding needs.
    const fn len(&self) -> usize {
        match self {
            Self::Staged(bytes) => bytes.len(),
            Self::Overwritten(len) => *len,
        }
    }
}

/// Dispatch with every binding resident, reusing the handles the caller supplied.
///
/// vyre's resident entry point takes ONE kind of resource: a `Borrowed` resource
/// in the list is refused outright, so making the table resident means making
/// every binding resident. The harness buffers are therefore allocated here per
/// dispatch and freed before returning so a long encode does not accumulate
/// device memory.
///
/// `seed_is_read` has already been folded into [`ResidentBinding`] by the
/// caller: `Staged` is uploaded, `Overwritten` is only allocated. See
/// [`HARNESS_SEED_IS_READ`] for the proof that the `Overwritten` set is
/// complete.
///
/// Freshly allocating the DEVICE buffers per dispatch is also the one
/// remaining reason CUDA graph replay cannot amortize this loop: replay needs
/// the same program AND the same device pointers, and an encode's dispatches
/// are several distinct shapes over device buffers that do not outlive one
/// dispatch. The host side of that prerequisite is now met: [`Staging`] gives
/// every HOST buffer a lifetime longer than the encode through
/// [`STAGING_POOL`], laid out as one struct so a later arena or graph cache
/// can take it over wholesale. If the device buffers ever gain the same
/// stability from an arena, revisit replay.
///
/// Returns the dispatch outputs in binding order, exactly as the host path does.
fn dispatch_resident(
    backend: &dyn VyreBackend,
    program: &Program,
    bindings: &[ResidentBinding<'_>],
    resident: &[Option<&Resource>],
    config: &DispatchConfig,
) -> Result<Vec<Vec<u8>>, ExatokError> {
    debug_assert_eq!(
        bindings.len(),
        resident.len(),
        "every binding must say whether it is already resident"
    );
    // Allocated for this dispatch only, and freed on every exit path below. The
    // caller's resident handles are NOT in here; freeing one would invalidate the
    // table for every later dispatch.
    let mut owned: Vec<Resource> = Vec::with_capacity(bindings.len());
    let mut resources: Vec<Resource> = Vec::with_capacity(bindings.len());
    let mut staging = Ok(());

    for (binding, already) in bindings.iter().zip(resident) {
        if let Some(resource) = already {
            resources.push((*resource).clone());
            continue;
        }
        // A zero-length binding cannot be allocated resident, and vyre refuses
        // it explicitly rather than returning a handle to nothing. No buffer the
        // loop declares is ever empty, so this is a defect check.
        if binding.len() == 0 {
            staging = Err(ExatokError::Backend(
                "gpu_loop resident dispatch cannot bind a zero-length buffer. \
                 Fix: every harness buffer must carry at least one word"
                    .to_string(),
            ));
            break;
        }
        match backend.allocate_resident(binding.len()) {
            Ok(resource) => {
                // Skipped, not shortened, for `Overwritten`. The buffer is
                // allocated at its full width and the kernel writes every word
                // of it before reading any, so pushing host bytes in first
                // would move bytes the dispatch cannot observe.
                if let ResidentBinding::Staged(bytes) = binding {
                    if let Err(error) = backend.upload_resident(&resource, bytes) {
                        owned.push(resource);
                        staging = Err(ExatokError::Backend(format!(
                            "gpu_loop resident upload failed: {error}. \
                             Fix: drop the session and bind a fresh one, since a buffer the \
                             backend just allocated refusing its upload marks the device \
                             context as suspect"
                        )));
                        break;
                    }
                }
                owned.push(resource.clone());
                resources.push(resource);
            }
            Err(error) => {
                staging = Err(ExatokError::Backend(format!(
                    "gpu_loop resident allocation of {} byte(s) failed: {error}. \
                     Fix: free device memory and retry, or encode without a resident session \
                     so buffers are bound from host memory per call",
                    binding.len()
                )));
                break;
            }
        }
    }

    let dispatched = staging.and_then(|()| {
        backend
            .dispatch_resident_timed(program, &resources, config)
            .map(|timed| timed.outputs)
            .map_err(|error| {
                ExatokError::Backend(format!(
                    "gpu_loop resident dispatch failed: {error}. \
                     Fix: re-run the encode; if it repeats, re-create the backend to rule \
                     out a stale device context before suspecting the program"
                ))
            })
    });

    // Freed whether the dispatch succeeded or not, and BEFORE the result is
    // propagated. An early `?` above would leak one device buffer per failed
    // dispatch, which on a retrying caller is a slow device-memory exhaustion
    // that surfaces far from its cause.
    for resource in owned {
        backend.free_resident(resource).map_err(|error| {
            ExatokError::Backend(format!("gpu_loop resident free failed: {error}"))
        })?;
    }
    dispatched
}

/// Dispatch once and fold the outputs back into `window`.
fn dispatch_window(
    backend: &dyn VyreBackend,
    program: &Program,
    shape: LoopShape,
    window: &mut PassWindow,
    caller_inputs: &[CallerInput<'_>],
) -> Result<(), ExatokError> {
    let words = window.staging.current.len();
    let segments = window.staging.segment_passes.len();
    // The grid form gives every wave its own `changed` word and never clears
    // one, so this buffer is as wide as the pass budget there and a single word
    // for the in-kernel form. Taking the width off the program's own
    // declaration keeps host and kernel from drifting apart silently.
    let changed = changed_words(program);
    window.size_changed_filler(changed);

    // Resident only when the caller actually handed over a device buffer. A
    // dispatch whose every binding is host bytes gains nothing from the
    // resident entry point and would pay an allocate and free per harness
    // buffer for it, so that case keeps the borrowed path unchanged. Decided
    // BEFORE staging, because the borrowed path needs bytes the resident path
    // provably never reads.
    let use_resident = caller_inputs
        .iter()
        .any(|input| input.resident().is_some());

    // Repacked IN PLACE where the contents differ per dispatch: the tokens,
    // the pass counter, and the two per-segment tallies. The buffers come from
    // the window's [`Staging`], so after the first dispatch of an encode this
    // is a rewrite of existing allocations, not new ones.
    // [`NAME_STATE_NEXT`] and [`NAME_CHANGED`] come from fillers, because
    // neither ever carries a value this dispatch computed.
    pack_u32_slice_into(
        &window.staging.current,
        &mut window.staging.current_bytes,
    );
    pack_u32_slice_into(&[window.passes], &mut window.staging.passes_bytes);
    pack_u32_slice_into(
        &window.staging.segment_changed,
        &mut window.staging.segment_changed_bytes,
    );
    pack_u32_slice_into(
        &window.staging.segment_passes,
        &mut window.staging.segment_passes_bytes,
    );
    // The borrowed path UPLOADS the [`NAME_STATE_NEXT`] fill, so it must
    // exist there: one [`DEAD_SLOT`] per word, whose little-endian wire bytes
    // are `0xFF` four times over on any host, so the fill is one `vec!` with
    // no word buffer and no pack. The resident path never reads those bytes
    // (see [`HARNESS_SEED_IS_READ`]), so the buffer is never built for it and
    // the binding below carries a length instead.
    if !use_resident && window.staging.next_filler.len() != words * 4 {
        window.staging.next_filler = vec![0xFF; words * 4];
    }
    // What the binding list holds for [`NAME_STATE_NEXT`]. On the borrowed
    // path, the fill itself. On the resident path the slice is only consulted
    // for its LENGTH, by the cooperative residency probe below, and the state
    // bytes stand in at the identical length so no fill is ever materialized.
    let next_binding: &[u8] = if use_resident {
        &window.staging.current_bytes
    } else {
        &window.staging.next_filler
    };
    // The six harness buffers, BORROWED so the binding list can carry them
    // alongside the caller's. Pushing them into an owned list and appending the
    // caller's buffers CLONES those, and one of them is a 16 MiB merge table the
    // caller already holds packed.
    //
    // Typed at [`HARNESS_BUFFERS`] so the count the loop declares and the count
    // it stages are checked against each other by the compiler rather than by a
    // reader counting entries.
    let harness: [&[u8]; HARNESS_BUFFERS] = [
        &window.staging.current_bytes,
        next_binding,
        &window.staging.changed_filler,
        &window.staging.passes_bytes,
        &window.staging.segment_changed_bytes,
        &window.staging.segment_passes_bytes,
    ];
    let mut inputs: Vec<&[u8]> = Vec::with_capacity(HARNESS_BUFFERS + caller_inputs.len());
    inputs.extend_from_slice(&harness);
    inputs.extend(caller_inputs.iter().map(CallerInput::bytes));
    // Parallel to `inputs`: the harness buffers are rebuilt every dispatch and so
    // are never resident, and each caller buffer answers for itself.
    let mut resident: Vec<Option<&Resource>> = Vec::with_capacity(inputs.len());
    resident.extend(std::iter::repeat_n(None, HARNESS_BUFFERS));
    resident.extend(caller_inputs.iter().map(CallerInput::resident));
    // Also parallel to `inputs`. A caller buffer always carries data its pass
    // body reads, so only the harness has entries a dispatch may leave unstaged.
    let mut seed_is_read: Vec<bool> = Vec::with_capacity(inputs.len());
    seed_is_read.extend_from_slice(&HARNESS_SEED_IS_READ);
    seed_is_read.extend(std::iter::repeat_n(true, caller_inputs.len()));

    let (config, groups) = launch_geometry(program, shape);

    // Check residency BEFORE the allocate and upload a failed cooperative
    // launch would otherwise waste.
    //
    // The gate keys on the program actually carrying a `GridSync` barrier, not
    // on the group count. Only the grid form emits one, and asking the backend
    // about a program without one is actively wrong: `cooperative_grid_sync_fits`
    // answers `Ok(false)` when there is no barrier to launch cooperatively, so a
    // gate keyed on `groups()` would refuse every ordinary multi-group dispatch
    // on any backend that declines the host split, CUDA included.
    if contains_grid_sync(program) {
        check_cooperative_residency(backend, program, &inputs, &config, groups.max(1))?;
    }

    // `dispatch_borrowed` and not `dispatch`, because `dispatch` takes one owned
    // `Vec<u8>` per binding and would stage every borrow above into a fresh
    // allocation, table included. CUDA overrides it and uploads the borrows
    // directly; a backend that does not gets the trait default, which stages
    // them into owned buffers and calls `dispatch`, so the bytes and the result
    // are the same and the cost is exactly what this module paid before.
    //
    // Equivalent here and not merely cheaper. CUDA's owned entry point checks
    // cooperative residency and host-splits a grid that exceeds it; that branch
    // is unreachable from this module, because the gate above refuses any
    // grid-sync dispatch `cooperative_grid_sync_fits` declines (CUDA reports
    // `allows_host_grid_sync_split` false) and that query consults the very
    // residency bound the split decision does.
    let outputs = if use_resident {
        // `seed_is_read` folded into the binding: a buffer the kernel reads
        // arrives with its bytes, a buffer it overwrites before any read
        // arrives as a length and its fill is never built.
        let bindings: Vec<ResidentBinding<'_>> = inputs
            .iter()
            .zip(&seed_is_read)
            .map(|(bytes, seeded)| {
                if *seeded {
                    ResidentBinding::Staged(bytes)
                } else {
                    ResidentBinding::Overwritten(bytes.len())
                }
            })
            .collect();
        dispatch_resident(backend, program, &bindings, &resident, &config)?
    } else {
        backend
            .dispatch_borrowed(program, &inputs, &config)
            .map_err(|error| {
                ExatokError::Backend(format!(
                    "gpu_loop dispatch failed: {error}. \
                     Fix: retry on a freshly created backend, because a launch with buffers \
                     bound per call fails for driver reasons the input cannot cause"
                ))
            })?
    };
    if outputs.len() < HARNESS_BUFFERS {
        return Err(ExatokError::Backend(format!(
            "gpu_loop dispatch returned {} output buffer(s), needs {HARNESS_BUFFERS}. \
             Fix: keep the six harness buffers declared ReadWrite so the backend returns them",
            outputs.len()
        )));
    }

    read_words(
        &outputs[0],
        words,
        NAME_STATE_CURRENT,
        &mut window.staging.current,
    )?;
    // Whatever the program DECLARED for the back buffer is what the backend must
    // return. Shipped programs declare `0..0`, so a backend that ships the whole
    // array home is moving 1.79 MB per prose encode this module asked it not to,
    // and this is the only place that is visible. A
    // [`single_pass_program_returning_state`] program declares the full width
    // instead, and then a SHORT buffer is the defect worth catching, because the
    // suite reading it would otherwise index off the end.
    let declared_next_bytes = declared_readback_bytes(program, BINDING_STATE_NEXT, words);
    if outputs[1].len() != declared_next_bytes {
        return Err(ExatokError::Backend(format!(
            "gpu_loop read {} byte(s) back from `{NAME_STATE_NEXT}`, which declares {} byte(s). \
             Fix: honour BufferDecl::output_byte_range on this backend",
            outputs[1].len(),
            declared_next_bytes
        )));
    }
    // Read but deliberately discarded. The global word is not the termination
    // signal (see `any_segment_moved`), yet it stays in the buffer list and is
    // validated at its full declared width here, so a backend that returns it
    // short or drops it is caught rather than silently shifting every later
    // output index by one.
    read_words(
        &outputs[2],
        changed as usize,
        NAME_CHANGED,
        &mut window.staging.changed,
    )?;
    window.passes = read_word(&outputs[3], NAME_PASSES)?;
    read_words(
        &outputs[4],
        segments,
        NAME_SEGMENT_CHANGED,
        &mut window.staging.segment_changed,
    )?;
    read_words(
        &outputs[5],
        segments,
        NAME_SEGMENT_PASSES,
        &mut window.staging.segment_passes,
    )?;
    Ok(())
}

fn read_words(
    bytes: &[u8],
    count: usize,
    label: &str,
    out: &mut Vec<u32>,
) -> Result<(), ExatokError> {
    unpack_u32_slice_into(bytes, count, label, out).map_err(ExatokError::Backend)
}

fn read_word(bytes: &[u8], label: &str) -> Result<u32, ExatokError> {
    let mut word = Vec::new();
    read_words(bytes, 1, label, &mut word)?;
    word.first().copied().ok_or_else(|| {
        ExatokError::Backend(format!(
            "gpu_loop read no word from `{label}`. Fix: declare it with a one-word count"
        ))
    })
}

/// Whether the back buffer comes home.
///
/// Every shipped path uses [`StateReadback::Discarded`]: the primitive copies
/// `next` into `current` at the end of every pass, so the answer is in
/// `current` and returning `next` moved 1,794,048 bytes per prose encode
/// straight into a drop.
///
/// [`StateReadback::Full`] exists because "the kernel overwrites every slot" and
/// "the kernel writes the RIGHT value into every slot" are different claims. The
/// first is an IR property; the second is only observable by reading the buffer
/// the pass wrote, INCLUDING its padding, which no transfer analysis can
/// establish. The scale-boundary suite asserts the padding and ownership
/// contract that way, so the narrowing may not be allowed to blind it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateReadback {
    /// Declare a zero-length readback window on [`NAME_STATE_NEXT`].
    Discarded,
    /// Return [`NAME_STATE_NEXT`] at its full width, for state inspection.
    Full,
}

fn build_loop_program(
    op_id: &str,
    shape: LoopShape,
    max_passes: u32,
    pass_body: Vec<Node>,
    caller_buffers: Vec<BufferDecl>,
    state_readback: StateReadback,
) -> Program {
    if let Some(message) = shape_rejection(shape, max_passes, &pass_body, &caller_buffers) {
        return trap_program(op_id, NAME_STATE_CURRENT, DataType::U32, message);
    }

    let state_words = shape.state_words();
    let mut body = Vec::with_capacity(pass_body.len() + 8);
    body.extend(open_pass(shape));
    body.extend(pass_body);
    // The primitive puts NO barrier between the pass body and its compare and
    // copy step, and that step writes `current` while other lanes may still be
    // reading it. This barrier is required by the memory model. Note that no
    // test here fails without it: the reference interpreter sequences lanes per
    // node, and 64 full-width CUDA runs stayed correct, so the ordering it
    // buys is currently unproven by experiment rather than demonstrated.
    body.push(barrier());
    body.extend(close_pass(shape));

    // Above one workgroup the single-word form is unsound: it clears `changed`
    // with a plain store from lane 0 while every group sets it, so a set can be
    // lost and a group can return with its segments still moving. The grid form
    // gives each wave its own never-cleared word behind a `GridSync` barrier, so
    // every group reads the same verdict and the early exit stays collective.
    // Below that width one workgroup's barriers are incidentally grid-wide and
    // the original is correct, so it is kept rather than paying grid sync.
    let primitive = if shape.groups() > 1 {
        persistent_fixpoint_grid(
            body,
            NAME_STATE_CURRENT,
            NAME_STATE_NEXT,
            NAME_CHANGED,
            state_words,
            max_passes,
        )
    } else {
        persistent_fixpoint(
            body,
            NAME_STATE_CURRENT,
            NAME_STATE_NEXT,
            NAME_CHANGED,
            state_words,
            max_passes,
        )
    };
    // The body came from another registered op's builder, so the region chain
    // has to record that. `tag_program` stamps this op as the parent and sets
    // `source_region` on the primitive's own region, which is what
    // `cargo xtask print-composition` walks. Wrapping it anonymously instead
    // would leave a None root and silently break the audit trail.
    let program = vyre_libs::region::tag_program(op_id, primitive);

    let segments = shape.segments();
    let mut buffers = program.buffers().to_vec();
    if state_readback == StateReadback::Discarded {
        narrow_readback_to_nothing(&mut buffers, NAME_STATE_NEXT);
    }
    buffers.push(word_buffer(NAME_PASSES, BINDING_PASSES, 1));
    buffers.push(word_buffer(
        NAME_SEGMENT_CHANGED,
        BINDING_SEGMENT_CHANGED,
        segments,
    ));
    buffers.push(word_buffer(
        NAME_SEGMENT_PASSES,
        BINDING_SEGMENT_PASSES,
        segments,
    ));
    buffers.extend(caller_buffers);
    program.with_rewritten_buffers(buffers)
}

/// Declare `name` as returning no bytes, keeping its full device allocation.
///
/// Applied to [`NAME_STATE_NEXT`], which the host never consults. The primitive
/// copies `next` into `current` at the end of every pass, so the answer is in
/// `current` and `next` came home only to be dropped: on a prose encode that was
/// 1,794,048 of the 4,507,752 bytes read back, half the padded state traffic in
/// that direction.
///
/// `output_byte_range` is the declared readback window, not the allocation, so
/// the kernel still owns every word and [`LoopShape::segment_base`] still
/// indexes inside the buffer. `require_static_readback_size` accepts an explicit
/// range, which is what makes an empty declaration legal rather than
/// indistinguishable from a mis-declared buffer.
fn narrow_readback_to_nothing(buffers: &mut [BufferDecl], name: &str) {
    for buffer in buffers.iter_mut() {
        if buffer.name() == name {
            *buffer = buffer.clone().with_output_byte_range(0..0);
        }
    }
}

/// Bytes the program declares for the buffer at `binding`.
///
/// `output_byte_range` is optional: absent means "the whole buffer", so the
/// fallback is `words` at four bytes each rather than zero. Reading the
/// declaration is what lets one dispatch path serve both [`StateReadback`]
/// modes without a second code path that can drift.
fn declared_readback_bytes(program: &Program, binding: u32, words: usize) -> usize {
    program
        .buffers()
        .iter()
        .find(|buffer| buffer.binding == binding)
        .and_then(BufferDecl::output_byte_range)
        .map_or(words * 4, |range| range.len())
}

/// Count this iteration and clear the per-segment change flags it will set.
fn open_pass(shape: LoopShape) -> Vec<Node> {
    vec![
        // Counted at the top of the wrapped body so the tally includes the final
        // pass that observes no change. Convergence depth is otherwise invisible
        // to the host without a second dispatch.
        Node::if_then(
            Expr::eq(lane(), Expr::u32(0)),
            vec![Node::let_bind(
                "wt_tick",
                Expr::atomic_add(NAME_PASSES, Expr::u32(0), Expr::u32(1)),
            )],
        ),
        Node::if_then(
            lane_live(shape),
            vec![Node::if_then(
                Expr::eq(slot(shape), Expr::u32(0)),
                vec![Node::store(NAME_SEGMENT_CHANGED, segment(shape), Expr::u32(0))],
            )],
        ),
        barrier(),
    ]
}

/// Per-segment convergence: flag the segments this pass moved, then tally them.
///
/// This mirrors what `persistent_fixpoint` does with its single global word,
/// at the granularity the batch actually converges at.
fn close_pass(shape: LoopShape) -> Vec<Node> {
    vec![
        // Pin the padding before the compare. Nothing owns these words, so no
        // pass body writes them, yet the fixpoint primitive's compare-and-copy
        // spans the whole state array: an unwritten `next` word would differ
        // from its `current` dead marker on every pass and the batch would run
        // to the cap without ever reporting convergence. Writing the marker
        // here makes padding compare equal, so `changed` reflects tokens only.
        Node::if_then(
            lane_dead(shape),
            vec![Node::store(NAME_STATE_NEXT, lane(), Expr::u32(DEAD_SLOT))],
        ),
        Node::if_then(
            lane_live(shape),
            vec![
                Node::let_bind("wt_cur", Expr::load(NAME_STATE_CURRENT, lane())),
                Node::let_bind("wt_nxt", Expr::load(NAME_STATE_NEXT, lane())),
                Node::if_then(
                    Expr::ne(Expr::var("wt_cur"), Expr::var("wt_nxt")),
                    vec![Node::let_bind(
                        "wt_mark",
                        Expr::atomic_or(NAME_SEGMENT_CHANGED, segment(shape), Expr::u32(1)),
                    )],
                ),
            ],
        ),
        barrier(),
        Node::if_then(
            lane_live(shape),
            vec![Node::if_then(
                Expr::eq(slot(shape), Expr::u32(0)),
                vec![Node::if_then(
                    Expr::ne(Expr::load(NAME_SEGMENT_CHANGED, segment(shape)), Expr::u32(0)),
                    vec![Node::let_bind(
                        "wt_seg_tick",
                        Expr::atomic_add(NAME_SEGMENT_PASSES, segment(shape), Expr::u32(1)),
                    )],
                )],
            )],
        ),
        barrier(),
    ]
}

/// Bind the segment-local coordinates a pass body indexes state with.
///
/// Binds exactly four names, and they are RESERVED inside a pass body: `seg` is
/// the global segment index, `slot` is the word offset within that segment where
/// 0 is the live-length word, `base` is that segment's first state word, and
/// `len` is its current live token count.
///
/// This exists so the padded layout is stated once, by the module that owns it.
/// A pass body that re-derived `seg = lane / stride` and `base = seg * stride`
/// would be silently wrong under padding, and the two copies would drift.
/// Call it inside a guard of [`lane_is_live`]: `len` loads through `base`, and a
/// lane in a group's unused tail has no segment to load.
#[must_use]
pub fn segment_coordinates(shape: LoopShape) -> Vec<Node> {
    vec![
        Node::let_bind("seg", segment(shape)),
        Node::let_bind("slot", slot(shape)),
        Node::let_bind(
            "base",
            Expr::add(
                Expr::mul(group_index(), Expr::u32(LOOP_WORKGROUP_WIDTH)),
                Expr::mul(
                    Expr::div(group_offset(), Expr::u32(shape.stride())),
                    Expr::u32(shape.stride()),
                ),
            ),
        ),
        Node::let_bind(
            "len",
            Expr::load(
                NAME_STATE_CURRENT,
                Expr::add(Expr::var("base"), Expr::u32(SLOT_LIVE_LEN)),
            ),
        ),
    ]
}

fn lane() -> Expr {
    Expr::gid_x()
}

/// This lane's offset within its own workgroup's region.
fn group_offset() -> Expr {
    Expr::rem(lane(), Expr::u32(LOOP_WORKGROUP_WIDTH))
}

/// The workgroup this lane belongs to.
fn group_index() -> Expr {
    Expr::div(lane(), Expr::u32(LOOP_WORKGROUP_WIDTH))
}

/// Segment this lane's state word belongs to, under the padded layout.
///
/// Not `lane / stride`. Each workgroup owns a fixed [`LOOP_WORKGROUP_WIDTH`]
/// words and holds whole segments only, so the segment index is the group's
/// first segment plus the offset within that group. Using the dense form here
/// would attribute a lane in one group to a segment owned by another.
fn segment(shape: LoopShape) -> Expr {
    Expr::add(
        Expr::mul(group_index(), Expr::u32(shape.segments_per_group())),
        Expr::div(group_offset(), Expr::u32(shape.stride())),
    )
}

fn slot(shape: LoopShape) -> Expr {
    Expr::rem(group_offset(), Expr::u32(shape.stride()))
}

/// True when this lane maps to a real slot of a real segment.
///
/// Two ways a lane can be idle under the padded layout, and both must be
/// excluded or a lane corrupts a neighbour. It can sit in the unused tail of its
/// own group, when `stride` does not divide the width, or it can sit in a group
/// past the last real segment, when `segments` does not fill the final group. A
/// bare `lane < state_words` catches neither, because padding is inside the
/// state array rather than past its end.
fn lane_live(shape: LoopShape) -> Expr {
    Expr::and(
        Expr::lt(
            group_offset(),
            Expr::u32(shape.segments_per_group() * shape.stride()),
        ),
        Expr::lt(segment(shape), Expr::u32(shape.segments())),
    )
}

/// The exact negation of [`lane_live`], for the phase that has to touch padding.
///
/// The IR has no `not`, so this restates the complement rather than wrapping the
/// positive form. Keep the two in step: a lane must satisfy exactly one.
fn lane_dead(shape: LoopShape) -> Expr {
    Expr::or(
        Expr::ge(
            group_offset(),
            Expr::u32(shape.segments_per_group() * shape.stride()),
        ),
        Expr::ge(segment(shape), Expr::u32(shape.segments())),
    )
}

/// The liveness predicate a pass body MUST guard every phase with.
///
/// Exposed because a composed pass body indexes the same padded state array and
/// cannot re-derive this correctly from `state_words` alone. See [`lane_live`].
#[must_use]
pub fn lane_is_live(shape: LoopShape) -> Expr {
    lane_live(shape)
}

fn barrier() -> Node {
    Node::Barrier {
        ordering: MemoryOrdering::SeqCst,
    }
}

fn word_buffer(name: &str, binding: u32, count: u32) -> BufferDecl {
    BufferDecl::storage(name, binding, BufferAccess::ReadWrite, DataType::U32).with_count(count)
}

/// The complete set of shapes this harness cannot build, each naming its
/// parameter and carrying an actionable fix.
fn shape_rejection(
    shape: LoopShape,
    max_passes: u32,
    pass_body: &[Node],
    caller_buffers: &[BufferDecl],
) -> Option<String> {
    if shape.segments() == 0 {
        return Some(
            "segments is 0: an empty batch has no pretoken to converge. \
             Fix: build the LoopShape from the pretokens in this dispatch"
                .to_owned(),
        );
    }
    if shape.segment_capacity() == 0 {
        return Some(
            "segment_capacity is 0: a segment with no token slots holds only its length word. \
             Fix: size the capacity from the longest pretoken in the batch, which is at least 1"
                .to_owned(),
        );
    }
    let stride = shape.stride();
    if stride > LOOP_WORKGROUP_WIDTH {
        return Some(format!(
            "segment_capacity {} needs a stride of {stride} words, past the \
             {LOOP_WORKGROUP_WIDTH} one workgroup covers: a segment cannot straddle a workgroup \
             boundary, because the pass body's barriers order writes only within a group. \
             Fix: cap a single pretoken at {} tokens. The number of pretokens per dispatch is \
             unbounded, only one pretoken's own length is limited",
            shape.segment_capacity(),
            LOOP_WORKGROUP_WIDTH - 1
        ));
    }
    if max_passes == 0 {
        return Some(
            "max_passes is 0: the loop would never run the pass body and would report the \
             untouched seed as a converged tokenization. \
             Fix: use merge_pass_bound(longest pretoken in the batch)"
                .to_owned(),
        );
    }
    if pass_body.is_empty() {
        return Some(
            "pass_body is empty: it would leave the next buffer untouched, so the loop would \
             converge on whatever that scratch already held. \
             Fix: emit a body that writes every slot of the next state, including the length \
             word and the DEAD_SLOT tail"
                .to_owned(),
        );
    }
    caller_buffer_rejection(caller_buffers)
}

fn caller_buffer_rejection(caller_buffers: &[BufferDecl]) -> Option<String> {
    const RESERVED: [&str; HARNESS_BUFFERS] = [
        NAME_STATE_CURRENT,
        NAME_STATE_NEXT,
        NAME_CHANGED,
        NAME_PASSES,
        NAME_SEGMENT_CHANGED,
        NAME_SEGMENT_PASSES,
    ];
    let mut seen: Vec<u32> = Vec::with_capacity(caller_buffers.len());
    for buffer in caller_buffers {
        if buffer.binding() < FIRST_CALLER_BINDING {
            return Some(format!(
                "caller_buffers declares `{}` at binding {}, which the loop harness owns: it \
                 would alias the ping-pong or a convergence flag and read as a mysterious \
                 non-convergence. \
                 Fix: number pass-body buffers from {FIRST_CALLER_BINDING} upward",
                buffer.name(),
                buffer.binding()
            ));
        }
        if RESERVED.contains(&buffer.name()) {
            return Some(format!(
                "caller_buffers reuses the harness buffer name `{}`, which would shadow it in \
                 the IR name space even on a free binding. \
                 Fix: rename the pass-body buffer",
                buffer.name()
            ));
        }
        if seen.contains(&buffer.binding()) {
            return Some(format!(
                "caller_buffers declares binding {} twice, so one of the two would be dropped at \
                 bind time and the pass body would read whichever bound last. \
                 Fix: give every pass-body buffer its own binding",
                buffer.binding()
            ));
        }
        seen.push(buffer.binding());
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    use vyre_primitives::wire::pack_u32_slice;

    /// A pass body that is valid enough to get past the emptiness check.
    fn stub_body() -> Vec<Node> {
        vec![Node::store(NAME_STATE_NEXT, Expr::u32(0), Expr::u32(0))]
    }
    /// Count `Barrier` nodes sitting at the top level of `nodes`.
    ///
    /// Barriers nested inside divergent control flow are deliberately excluded,
    /// because the module contract requires pass barriers at the top level.
    fn top_level_barriers(nodes: &[Node]) -> usize {
        nodes
            .iter()
            .filter(|node| matches!(node, Node::Barrier { .. }))
            .count()
    }

    /// Descend to the node list holding the pass body.
    ///
    /// `persistent_fixpoint` nests it as Region -> Region -> `Node::Loop`, so
    /// the loop body has to be entered too. Divergent control flow is NOT
    /// entered, which is what keeps the barrier count a top-level count.
    fn innermost_body(nodes: &[Node]) -> &[Node] {
        for node in nodes {
            match node {
                Node::Region { body, .. } => return innermost_body(body),
                Node::Block(inner) => return innermost_body(inner),
                Node::Loop { body, .. } => return innermost_body(body),
                _ => {}
            }
        }
        nodes
    }

    /// Locks in that the barrier between the pass body and the compare and copy
    /// step is still emitted.
    ///
    /// This test exists because that barrier is the one piece of this module no
    /// behavioral test can defend, which makes it the piece most likely to be
    /// deleted. `persistent_fixpoint` emits no barrier of its own there, and its
    /// compare and copy step writes `current[i]` while other lanes may still be
    /// reading `current[j]`, so the memory model requires one.
    ///
    /// Deleting it was tried and every other test stayed green: the reference
    /// interpreter sequences lanes per node and cannot expose the race, and 64
    /// full-width dispatches on an RTX 5090 stayed correct as well. A future
    /// maintainer who repeats that experiment will conclude the barrier is dead
    /// code. This test is the tripwire that tells them otherwise, so it asserts
    /// a count rather than behavior on purpose, and the count is exact so that
    /// losing a barrier cannot be masked by gaining one elsewhere.
    ///
    /// Seven is a measured value, not a derived one. Four come from this module:
    /// one closing `open_pass`, this one after the pass body, and two in
    /// `close_pass` around its guarded copy. The other three come from
    /// `persistent_fixpoint`'s own compare and copy step, which lands in the
    /// same loop body. That split is why the assertion is on the total: this
    /// module cannot tell the primitive's barriers from its own by position, but
    /// it can tell that one went missing.
    #[test]
    fn the_pass_body_barrier_is_still_emitted() {
        let program = device_loop_program(LoopShape::new(2, 4, 4), stub_body(), Vec::new());
        let body = innermost_body(program.entry());

        assert_eq!(
            top_level_barriers(body),
            7,
            "expected 7 top-level barriers in the fixpoint loop body. A count of 6 \
             means the barrier between the pass body and the compare and copy step \
             was removed, which is a real race on hardware that no other test in this \
             crate detects. \
             Fix: restore `body.push(barrier())` after `body.extend(pass_body)`. \
             A count of 8 or more means the primitive changed its own barrier \
             placement: re-derive the split before editing this number."
        );
    }

    fn caller_buffer(name: &str, binding: u32) -> BufferDecl {
        BufferDecl::storage(name, binding, BufferAccess::ReadOnly, DataType::U32).with_count(8)
    }

    /// Depth-first search for a trap message, so the assertion does not depend
    /// on how many Region or Block scopes wrap the trap.
    fn trap_message(nodes: &[Node]) -> Option<String> {
        for node in nodes {
            let found = match node {
                Node::Trap { tag, .. } => Some(tag.as_str().to_owned()),
                Node::Region { body, .. } => trap_message(body),
                Node::Block(inner) => trap_message(inner),
                Node::If { then, otherwise, .. } => {
                    trap_message(then).or_else(|| trap_message(otherwise))
                }
                Node::Loop { body, .. } => trap_message(body),
                _ => None,
            };
            if found.is_some() {
                return found;
            }
        }
        None
    }

    fn trap_for(shape: LoopShape) -> Option<String> {
        trap_message(device_loop_program(shape, stub_body(), Vec::new()).entry())
    }

    /// Locks the batch layout: one length slot plus the token slots, repeated
    /// per segment. If the stride ever drops the length slot, every pass body's
    /// slot indexing shifts by one and the loop compares the wrong words.
    #[test]
    fn stride_reserves_one_slot_per_segment_for_the_live_length() {
        let shape = LoopShape::new(3, 4, 4);
        assert_eq!(shape.stride(), 5);
        // Whole segments per group: 256 / 5 is 51, with 1 word of tail per group.
        assert_eq!(shape.segments_per_group(), 51);
        assert_eq!(shape.groups(), 1);
        // Padded to the full group width, not the 15 words the tokens occupy.
        assert_eq!(shape.state_words(), LOOP_WORKGROUP_WIDTH);
        assert_eq!(shape.segment_base(0), 0);
        assert_eq!(shape.segment_base(1), 5);
        assert_eq!(shape.segment_base(2), 10);
    }

    /// A segment must never straddle a workgroup boundary.
    ///
    /// The pass body synchronizes its phases with barriers, and a barrier orders
    /// writes only within one workgroup, so two lanes cooperating on one segment
    /// have to sit in the same group. This is the invariant that lets the batch
    /// span unlimited workgroups at all, so it is pinned directly: for a spread
    /// of strides, every segment's first and last word land in the same group.
    #[test]
    fn no_segment_straddles_a_workgroup_boundary() {
        for capacity in [1_u32, 2, 3, 4, 7, 15, 16, 31, 63, 127, 254] {
            let shape = LoopShape::new(1000, capacity, 4);
            let stride = shape.stride();
            for segment in 0..shape.segments() {
                let base = shape.segment_base(segment);
                let last = base + stride - 1;
                assert_eq!(
                    base / LOOP_WORKGROUP_WIDTH,
                    last / LOOP_WORKGROUP_WIDTH,
                    "capacity {capacity}: segment {segment} spans words {base}..={last}, \
                     which crosses a group boundary"
                );
                assert!(
                    last < shape.state_words(),
                    "capacity {capacity}: segment {segment} ends at {last}, past the {} allocated",
                    shape.state_words()
                );
            }
        }
    }

    /// Distinct segments must never share a state word.
    ///
    /// Padding introduces gaps, and a base formula that mixed up group stride and
    /// segment stride could alias two segments onto the same words while still
    /// looking plausible in a spot check. Aliasing would make one pretoken
    /// overwrite another's tokens, so enumerate every word every segment owns and
    /// assert the ownership is unique.
    #[test]
    fn distinct_segments_never_share_a_state_word() {
        for capacity in [1_u32, 3, 4, 5, 16, 51, 127] {
            let shape = LoopShape::new(500, capacity, 4);
            let mut owner = vec![u32::MAX; shape.state_words() as usize];
            for segment in 0..shape.segments() {
                let base = shape.segment_base(segment) as usize;
                for word in base..base + shape.stride() as usize {
                    assert_eq!(
                        owner[word],
                        u32::MAX,
                        "capacity {capacity}: word {word} claimed by both segment {} and {segment}",
                        owner[word]
                    );
                    owner[word] = segment;
                }
            }
        }
    }

    /// The pass bound is the longest PRETOKEN, not the input length and not the
    /// rank count. Bounding by input length gives about a billion on a gigabyte
    /// corpus, useless as a bug detector; bounding by rank count is unsound
    /// because a merge can create a lower-ranked pair (rank 262 then rank 257).
    #[test]
    fn merge_pass_bound_is_the_longest_segment_length() {
        assert_eq!(merge_pass_bound(0), 1);
        assert_eq!(merge_pass_bound(1), 1);
        assert_eq!(merge_pass_bound(2), 2);
        assert_eq!(merge_pass_bound(16), 16);
        assert_eq!(merge_pass_bound(506), 506);

        let batch: Vec<Vec<u32>> = vec![vec![1, 2, 3], vec![4], vec![5, 6, 7, 8, 9]];
        assert_eq!(longest_segment(&batch), 5);
        assert_eq!(merge_pass_bound(longest_segment(&batch)), 5);
    }

    /// An empty batch has no longest pretoken. Returning 0 here would make the
    /// bound 1 and hide the real problem, which the builder must trap on.
    #[test]
    fn longest_segment_of_an_empty_batch_is_zero() {
        let empty: Vec<Vec<u32>> = Vec::new();
        assert_eq!(longest_segment(&empty), 0);
    }

    /// The words one segment owns, under whatever layout is current.
    ///
    /// Layout assertions go through this rather than comparing the whole state
    /// array, because the array is padded to a multiple of the workgroup width
    /// and a full-array literal would encode the padding as if it were meaning.
    fn segment_window(batch: &LoopBatch, segment: u32) -> &[u32] {
        let shape = batch.shape();
        let base = shape.segment_base(segment) as usize;
        &batch.state()[base..base + shape.stride() as usize]
    }
    /// `state_words` must cover every word `segment_base` hands out, for every
    /// shape, not just the dispatchable ones.
    ///
    /// This locks out a live bug. `segments_per_group` clamps a zero to one so a
    /// stride wider than the workgroup still names a group, but `state_words` then
    /// multiplied that single group by the workgroup WIDTH rather than by the words
    /// the group needs. A 256-token pretoken therefore reported 256 words for a
    /// segment spanning 257, so the final slot addressed one word past the buffer.
    /// Such a shape traps before dispatch, which is exactly what made the sizing
    /// error invisible: nothing read the number on the path that rejected it, and a
    /// later caller sizing a real allocation from it would have overflowed silently.
    #[test]
    fn state_words_never_under_allocates_any_segment_it_sizes() {
        for capacity in 0u32..=300 {
            for segments in 0u32..=9 {
                let shape = LoopShape::new(segments, capacity, 1);
                assert_eq!(
                    shape.words_per_group() % LOOP_WORKGROUP_WIDTH,
                    0,
                    "a group must stay a whole number of workgroup widths, else \
                     lane / width no longer names the group: capacity {capacity}"
                );
                for segment in 0..segments {
                    let end = shape.segment_base(segment) + shape.stride();
                    assert!(
                        end <= shape.state_words(),
                        "segment {segment} of {segments} at capacity {capacity} ends \
                         at word {end} but the batch only sizes {} words",
                        shape.state_words()
                    );
                }
            }
        }
    }

    /// Two segments must never overlap, at any capacity, including the strides
    /// that divide the workgroup width exactly and the ones that leave a tail.
    ///
    /// The padded layout computes a base from a group index and an offset within
    /// the group. An off-by-one in either factor aliases two segments onto shared
    /// words, and aliasing corrupts tokens rather than crashing, so it would
    /// surface as a rare wrong id long after this code was trusted.
    #[test]
    fn no_two_segments_share_a_word_at_any_capacity() {
        for capacity in 0u32..=64 {
            let shape = LoopShape::new(9, capacity, 1);
            let stride = shape.stride() as usize;
            let mut owner = vec![u32::MAX; shape.state_words() as usize];
            for segment in 0..shape.segments() {
                let base = shape.segment_base(segment) as usize;
                for word in &mut owner[base..base + stride] {
                    assert_eq!(
                        *word,
                        u32::MAX,
                        "capacity {capacity}: segment {segment} claims a word already \
                         owned by segment {word}"
                    );
                    *word = segment;
                }
            }
        }
    }

    /// Segments are padded to a uniform stride and every dead slot carries the
    /// canonical marker. A seed that left the tail zeroed would make token id 0
    /// and "no token" the same word, and the first pass would compare against a
    /// tail it never wrote.
    #[test]
    fn batch_layout_pads_every_segment_to_a_uniform_stride() {
        let batch = LoopBatch::new(&[vec![11, 22, 33], vec![44]], 3);
        assert_eq!(batch.shape().segments(), 2);
        assert_eq!(batch.shape().segment_capacity(), 3);
        assert_eq!(batch.shape().max_passes(), 3);
        assert_eq!(segment_window(&batch, 0), &[3, 11, 22, 33]);
        assert_eq!(segment_window(&batch, 1), &[1, 44, DEAD_SLOT, DEAD_SLOT]);
        // The array is padded to whole workgroups, so it is wider than the eight
        // words the two segments occupy.
        assert_eq!(batch.state().len(), LOOP_WORKGROUP_WIDTH as usize);
    }

    /// An empty pretoken is a real input. It must seed a zero live length so the
    /// first pass converges without mutating anything, and the all-empty batch
    /// must still produce a usable stride rather than a zero-width layout.
    #[test]
    fn batch_layout_handles_empty_pretokens() {
        let batch = LoopBatch::new(&[vec![7, 8], Vec::new()], 2);
        assert_eq!(segment_window(&batch, 0), &[2, 7, 8]);
        assert_eq!(segment_window(&batch, 1), &[0, DEAD_SLOT, DEAD_SLOT]);

        let all_empty = LoopBatch::new(&[Vec::<u32>::new(), Vec::new()], 1);
        assert_eq!(all_empty.shape().segment_capacity(), 1);
        assert_eq!(all_empty.shape().stride(), 2);
        assert_eq!(segment_window(&all_empty, 0), &[0, DEAD_SLOT]);
        assert_eq!(segment_window(&all_empty, 1), &[0, DEAD_SLOT]);
    }

    /// A token id equal to the dead marker must stay a live token, because slot
    /// 0 is the authority on liveness. Treating the marker as an end sentinel
    /// here would silently truncate the segment.
    #[test]
    fn a_token_equal_to_the_dead_marker_stays_live() {
        let batch = LoopBatch::new(&[vec![DEAD_SLOT, 5]], 2);
        assert_eq!(segment_window(&batch, 0), &[2, DEAD_SLOT, 5]);
        let outcome = LoopOutcome {
            shape: batch.shape(),
            state: batch.state().to_vec(),
            passes: 1,
            segment_passes: vec![0],
            segment_changed: vec![0],
            termination: Termination::Converged,
        };
        assert_eq!(outcome.tokens(0), &[DEAD_SLOT, 5]);
    }

    /// `with_sound_bound` must derive the budget from the longest pretoken. A
    /// budget taken from the first or the shortest one would cap a longer
    /// sibling mid-merge.
    #[test]
    fn sound_bound_comes_from_the_longest_pretoken() {
        let batch = LoopBatch::with_sound_bound(&[vec![1], vec![1, 2, 3, 4]]);
        assert_eq!(batch.shape().max_passes(), 4);
        assert_eq!(batch.shape().segment_capacity(), 4);
    }

    /// One PRETOKEN past a workgroup traps, but a WIDE BATCH must not.
    ///
    /// This replaces a test that asserted the opposite, and the change is the
    /// point. A segment still cannot straddle a workgroup boundary, because the
    /// pass body's phase barriers order writes only within a group, so a single
    /// pretoken is capped. But segments are independent, since a merge never
    /// crosses a pretoken boundary, so groups need no ordering between them and
    /// the number of pretokens per dispatch is unbounded. The old rejection of
    /// `segments * stride > 256` was the throughput ceiling on the whole product,
    /// and it was stricter than the hardware requires.
    #[test]
    fn an_over_long_pretoken_traps_but_a_wide_batch_does_not() {
        assert_eq!(trap_for(LoopShape::new(1, 255, 4)), None);
        let message = trap_for(LoopShape::new(1, 256, 4)).unwrap_or_default();
        assert!(
            message.contains("257") && message.contains("256") && message.contains("Fix:"),
            "trap must name the stride, the limit, and a fix, got: {message}"
        );
        assert!(
            message.contains("255"),
            "trap must name the per-pretoken token cap, got: {message}"
        );

        // Each of these would have been rejected by the old batch-wide rule.
        for (segments, capacity) in [(16_u32, 16_u32), (1000, 3), (100_000, 1), (60, 254)] {
            assert_eq!(
                trap_for(LoopShape::new(segments, capacity, 4)),
                None,
                "a batch of {segments} pretokens of capacity {capacity} must dispatch, \
                 because pretokens per dispatch is unbounded"
            );
        }
    }

    /// A zero-segment batch and a zero-capacity segment are both unbuildable,
    /// and each must say which parameter is wrong rather than share one message.
    #[test]
    fn degenerate_layouts_trap_with_distinct_messages() {
        let no_segments = trap_for(LoopShape::new(0, 4, 4)).unwrap_or_default();
        assert!(
            no_segments.contains("segments is 0"),
            "trap must name segments, got: {no_segments}"
        );

        let no_capacity = trap_for(LoopShape::new(2, 0, 4)).unwrap_or_default();
        assert!(
            no_capacity.contains("segment_capacity is 0"),
            "trap must name segment_capacity, got: {no_capacity}"
        );
    }

    /// A zero budget never runs the body, so the loop would hand back the seed
    /// and call it converged. That is the exact failure the cap signal exists to
    /// prevent, so it must not be buildable.
    #[test]
    fn a_zero_pass_budget_traps() {
        let message = trap_for(LoopShape::new(2, 4, 0)).unwrap_or_default();
        assert!(
            message.contains("max_passes is 0") && message.contains("merge_pass_bound"),
            "trap must name max_passes and point at the sound bound, got: {message}"
        );
    }

    /// An empty body never writes `next`, so the primitive would compare against
    /// stale scratch and report convergence after wiping the state.
    #[test]
    fn an_empty_pass_body_traps() {
        let program = device_loop_program(LoopShape::new(2, 4, 4), Vec::new(), Vec::new());
        let message = trap_message(program.entry()).unwrap_or_default();
        assert!(
            message.contains("pass_body is empty"),
            "trap must name pass_body, got: {message}"
        );
    }

    /// The harness owns bindings 0 through 5. A pass-body buffer landing on one
    /// would alias the ping-pong or a convergence flag.
    #[test]
    fn a_caller_buffer_on_a_harness_binding_traps() {
        let shape = LoopShape::new(2, 4, 4);
        for binding in 0..FIRST_CALLER_BINDING {
            let program =
                device_loop_program(shape, stub_body(), vec![caller_buffer("ranks", binding)]);
            let message = trap_message(program.entry()).unwrap_or_default();
            assert!(
                message.contains("caller_buffers") && message.contains(&binding.to_string()),
                "binding {binding} must trap and be named, got: {message}"
            );
        }
        let ok = device_loop_program(
            shape,
            stub_body(),
            vec![caller_buffer("ranks", FIRST_CALLER_BINDING)],
        );
        assert_eq!(trap_message(ok.entry()), None);
    }

    /// A pass-body buffer reusing a harness NAME would shadow it in the IR name
    /// space even on a free binding, letting the body overwrite the flag the
    /// primitive uses to decide convergence.
    #[test]
    fn a_caller_buffer_reusing_a_harness_name_traps() {
        for name in [
            NAME_STATE_CURRENT,
            NAME_STATE_NEXT,
            NAME_CHANGED,
            NAME_PASSES,
            NAME_SEGMENT_CHANGED,
            NAME_SEGMENT_PASSES,
        ] {
            let program = device_loop_program(
                LoopShape::new(2, 4, 4),
                stub_body(),
                vec![caller_buffer(name, FIRST_CALLER_BINDING)],
            );
            let message = trap_message(program.entry()).unwrap_or_default();
            assert!(
                message.contains(name),
                "reusing `{name}` must trap and name it, got: {message}"
            );
        }
    }

    /// Two pass-body buffers on one binding silently drop one at bind time, so
    /// the body would read whichever the backend bound last.
    #[test]
    fn duplicate_caller_bindings_trap() {
        let program = device_loop_program(
            LoopShape::new(2, 4, 4),
            stub_body(),
            vec![
                caller_buffer("ranks", FIRST_CALLER_BINDING),
                caller_buffer("ids", FIRST_CALLER_BINDING),
            ],
        );
        let message = trap_message(program.entry()).unwrap_or_default();
        assert!(
            message.contains("twice"),
            "trap must report the duplicate binding, got: {message}"
        );
    }

    /// The six harness buffers must be declared in binding order with the right
    /// widths. A shifted order silently remaps every input the dispatch helper
    /// packs, and a wrong width truncates a readback.
    #[test]
    fn the_program_declares_the_harness_buffers_in_binding_order() {
        let shape = LoopShape::new(3, 4, 4);
        let program = device_loop_program(
            shape,
            stub_body(),
            vec![caller_buffer("ranks", FIRST_CALLER_BINDING)],
        );
        let names: Vec<&str> = program.buffers().iter().map(BufferDecl::name).collect();
        assert_eq!(
            names,
            vec![
                NAME_STATE_CURRENT,
                NAME_STATE_NEXT,
                NAME_CHANGED,
                NAME_PASSES,
                NAME_SEGMENT_CHANGED,
                NAME_SEGMENT_PASSES,
                "ranks",
            ]
        );
        let bindings: Vec<u32> = program.buffers().iter().map(BufferDecl::binding).collect();
        assert_eq!(bindings, vec![0, 1, 2, 3, 4, 5, 6]);
        let counts: Vec<u32> = program.buffers().iter().map(BufferDecl::count).collect();
        // The two state buffers are padded to whole workgroups, so they are the
        // group width rather than the 15 words three segments of stride 5 occupy.
        assert_eq!(
            counts,
            vec![
                LOOP_WORKGROUP_WIDTH,
                LOOP_WORKGROUP_WIDTH,
                1,
                1,
                3,
                3,
                8
            ]
        );
    }

    /// `live_len` must never index past a segment even if the device reported a
    /// nonsense length, or `tokens` would read a neighbouring segment's slots.
    #[test]
    fn live_len_is_clamped_to_the_segment_capacity() {
        let outcome = LoopOutcome {
            shape: LoopShape::new(2, 2, 2),
            state: vec![99, 5, 6, 1, 7, DEAD_SLOT],
            passes: 1,
            segment_passes: vec![0, 0],
            segment_changed: vec![0, 0],
            termination: Termination::Converged,
        };
        assert_eq!(outcome.live_len(0), 2);
        assert_eq!(outcome.tokens(0), &[5, 6]);
        assert_eq!(outcome.tokens(1), &[7]);
    }

    /// The whole point of the termination signal: a capped run yields tokens
    /// that look fine. `converged_tokens` must refuse the segments that were
    /// still moving, and must still trust the siblings that reached a fixed
    /// point, because an independent segment cannot move again once settled.
    #[test]
    fn converged_tokens_refuses_only_the_segments_still_moving() {
        let capped = LoopOutcome {
            shape: LoopShape::new(2, 2, 2),
            state: vec![2, 40, 41, 1, 42, DEAD_SLOT],
            passes: 2,
            segment_passes: vec![2, 1],
            segment_changed: vec![1, 0],
            termination: Termination::CapReached,
        };
        assert_eq!(capped.tokens(0), &[40, 41]);
        assert!(capped.converged_tokens(0).is_err());
        assert_eq!(capped.converged_tokens(1).ok(), Some(&[42][..]));
        assert_eq!(capped.unconverged_segments(), vec![0]);
        assert!(!capped.termination().is_converged());

        // A full literal rather than a `..capped` update: `LoopOutcome` owns
        // its buffers and returns them to the staging pool on drop, so its
        // fields cannot be moved out.
        let converged = LoopOutcome {
            shape: capped.shape(),
            state: capped.state().to_vec(),
            passes: capped.passes(),
            segment_passes: vec![2, 1],
            segment_changed: vec![0, 0],
            termination: Termination::Converged,
        };
        assert_eq!(converged.converged_tokens(0).ok(), Some(&[40, 41][..]));
        assert!(converged.unconverged_segments().is_empty());
        assert!(converged.termination().is_converged());
    }

    /// The refusal message has to localize the failure. A cap hit at a bound
    /// derived from the longest pretoken is a bug, so the operator needs the
    /// segment index and the pass count, not just "it did not converge".
    #[test]
    fn the_refusal_names_the_segment_and_the_pass_count() {
        let capped = LoopOutcome {
            shape: LoopShape::new(2, 2, 3),
            state: vec![2, 40, 41, 1, 42, DEAD_SLOT],
            passes: 3,
            segment_passes: vec![3, 1],
            segment_changed: vec![0, 1],
            termination: Termination::CapReached,
        };
        let message = capped
            .converged_tokens(1)
            .err()
            .map(|error| error.to_string())
            .unwrap_or_default();
        assert!(
            message.contains("segment 1") && message.contains("3 pass"),
            "refusal must name the segment and the pass count, got: {message}"
        );
    }

    /// Walk the nested region generators, outermost first, paired with the
    /// `source_region` back-reference each one carries.
    fn region_chain(nodes: &[Node]) -> Vec<(String, Option<String>)> {
        let mut chain = Vec::new();
        let mut level = nodes;
        loop {
            let mut descend = None;
            for node in level {
                if let Node::Region {
                    generator,
                    source_region,
                    body,
                } = node
                {
                    chain.push((
                        generator.as_str().to_owned(),
                        source_region.as_ref().map(|parent| parent.name.clone()),
                    ));
                    descend = Some(body.as_slice());
                    break;
                }
            }
            match descend {
                Some(inner) => level = inner,
                None => return chain,
            }
        }
    }

    /// The region chain is what `cargo xtask print-composition` walks. This body
    /// is built by calling another registered op's builder, so the composed
    /// region MUST carry a back-reference to this op; a None there leaves the
    /// primitive looking like an unattributed root and silently breaks the
    /// composition audit.
    #[test]
    fn the_region_chain_attributes_the_composed_primitive() {
        let program = device_loop_program(LoopShape::new(2, 4, 4), stub_body(), Vec::new());
        let chain = region_chain(program.entry());
        assert_eq!(
            chain.first().map(|entry| entry.0.as_str()),
            Some(OP_ID),
            "the outermost region must be this op, got: {chain:?}"
        );
        assert_eq!(
            chain.get(1).map(|entry| entry.0.as_str()),
            Some(vyre_primitives::fixpoint::persistent_fixpoint::OP_ID),
            "the composed primitive must keep its own generator, got: {chain:?}"
        );
        assert_eq!(
            chain.get(1).and_then(|entry| entry.1.as_deref()),
            Some(OP_ID),
            "the composed primitive must point back at this op, got: {chain:?}"
        );
    }

    /// The one-pass program is a separate registered shape and must not borrow
    /// the loop's op id, or a composition trace would attribute host-driven
    /// dispatches to the single-dispatch op.
    #[test]
    fn the_single_pass_program_carries_its_own_op_id() {
        let program = single_pass_program(LoopShape::new(2, 4, 4), stub_body(), Vec::new());
        let chain = region_chain(program.entry());
        assert_eq!(
            chain.first().map(|entry| entry.0.as_str()),
            Some(OP_ID_SINGLE_PASS)
        );
        assert_eq!(
            chain.get(1).and_then(|entry| entry.1.as_deref()),
            Some(OP_ID_SINGLE_PASS)
        );
        assert_ne!(OP_ID, OP_ID_SINGLE_PASS);
    }

    /// Op ids carry the tier. A `vyre-libs::` or `vyre-intrinsics::` prefix on a
    /// Tier 4 op would falsely claim that review tier, and the audit is a grep
    /// on exactly this string.
    #[test]
    fn op_ids_declare_the_tier_four_prefix() {
        for op_id in [OP_ID, OP_ID_SINGLE_PASS] {
            assert!(
                op_id.starts_with("exatok::gpu_loop::"),
                "`{op_id}` must be namespaced under this crate and module"
            );
        }
    }

    /// Render a gate refusal, naming the admit case so a wrong `Ok` reads
    /// clearly in the failure output instead of as an empty string.
    fn refusal(fits: bool, allows_split: bool, blocks: u32, limit: u32) -> String {
        match cooperative_gate(fits, allows_split, blocks, || limit) {
            Ok(()) => "<gate admitted the dispatch>".to_owned(),
            Err(error) => format!("{error}"),
        }
    }

    /// Locks out: refusing a launch the device can run, or admitting one it
    /// cannot.
    ///
    /// The full truth table, because the two accepting reasons are independent:
    /// a launch that fits needs no escape route, and a backend that permits the
    /// host split never attempts a cooperative launch to begin with. Collapsing
    /// them to a single condition would either refuse the reference interpreter
    /// or admit an over-residency grid on CUDA.
    #[test]
    fn the_gate_admits_exactly_the_launches_that_can_run() {
        assert!(cooperative_gate(true, true, 4, || 0).is_ok());
        assert!(cooperative_gate(true, false, 4, || 0).is_ok());
        assert!(cooperative_gate(false, true, 4, || 0).is_ok());
        assert!(cooperative_gate(false, false, 4, || 2).is_err());
    }

    /// Locks out: probing for a limit the gate does not need.
    ///
    /// Recovering the limit costs a bisection over `cooperative_grid_sync_fits`,
    /// so computing it eagerly would pay a run of geometry queries on every
    /// accepted dispatch, to build a message that is then discarded.
    #[test]
    fn an_admitted_dispatch_never_pays_for_the_limit() {
        for (fits, allows_split) in [(true, false), (false, true), (true, true)] {
            let probes = Cell::new(0u32);
            let result = cooperative_gate(fits, allows_split, 4, || {
                probes.set(probes.get() + 1);
                0
            });
            assert!(result.is_ok(), "fits={fits} allows_split={allows_split}");
            assert_eq!(
                probes.get(),
                0,
                "admitted dispatch probed for a limit it never reports"
            );
        }
    }

    /// Locks out: a refusal that fails to name both numbers.
    ///
    /// "Too big" without the required count and the device ceiling leaves the
    /// caller no way to pick a batch size, and picking one is the whole
    /// remediation.
    #[test]
    fn a_refusal_names_the_required_blocks_and_the_device_limit() {
        let text = refusal(false, false, 9, 5);
        assert!(text.contains("needs 9 co-resident block(s)"), "got: {text}");
        assert!(text.contains("at most 5"), "got: {text}");
        assert!(text.contains("Fix: "), "got: {text}");
    }

    /// Locks out: advising the caller to fit inside zero blocks.
    ///
    /// A backend that cannot launch cooperatively at any size is a different
    /// failure from one whose limit was merely exceeded, and the remedy differs:
    /// there is no smaller batch that helps.
    #[test]
    fn a_backend_with_no_cooperative_launch_says_so_instead_of_naming_zero() {
        let text = refusal(false, false, 9, 0);
        assert!(text.contains("no cooperative launch"), "got: {text}");
        assert!(!text.contains("at most 0"), "got: {text}");
    }

    /// Locks out: reporting a limit adjacent to the request, the request echoed
    /// back, or any off-by-one in either bisection bound.
    ///
    /// Exhaustive over every limit and ceiling pair in range rather than one
    /// example, because a bisection can be correct on a power of two and wrong
    /// everywhere else.
    #[test]
    fn the_probe_recovers_the_exact_largest_admitted_grid() {
        for limit in 0u32..24 {
            for ceiling in (limit + 1)..40 {
                let found = probe_block_limit(ceiling, |candidate| Some(candidate <= limit));
                assert_eq!(found, limit, "ceiling {ceiling}, true limit {limit}");
            }
        }
    }

    /// Locks out: returning the ceiling itself, which the caller has already
    /// proven does not fit.
    ///
    /// An all-admitting predicate is the adversarial case: the search must still
    /// respect that its upper bound failed for real, or the refusal would advise
    /// a batch size identical to the one being refused.
    #[test]
    fn the_probe_never_reports_the_ceiling_it_was_given() {
        for ceiling in 1u32..40 {
            let found = probe_block_limit(ceiling, |_| Some(true));
            assert_eq!(found, ceiling - 1, "ceiling {ceiling}");
        }
    }

    /// Locks out: over-reporting the limit once a geometry query fails.
    ///
    /// A failed probe makes every later answer untrustworthy, so the search must
    /// fall back to a count it actually proved rather than the midpoint it was
    /// about to test. Over-reporting sends the caller back with a batch that
    /// fails again for the same reason.
    #[test]
    fn a_failed_probe_falls_back_to_the_last_proven_fit() {
        let seen = Cell::new(0u32);
        let found = probe_block_limit(16, |candidate| {
            seen.set(seen.get() + 1);
            if seen.get() == 1 {
                Some(candidate <= 8)
            } else {
                None
            }
        });
        // The first probe is the midpoint 8, which fits and is therefore proven.
        // The second query fails, so the search stops at 8 rather than climbing.
        assert_eq!(found, 8);
        assert_eq!(seen.get(), 2, "the search must stop at the failed query");
    }

    /// Locks out: inventing a limit when nothing was ever proven to fit.
    #[test]
    fn a_probe_that_fails_immediately_reports_nothing_proven() {
        assert_eq!(probe_block_limit(16, |_| None), 0);
    }

    /// Locks out: routing a batch wider than one workgroup through the
    /// single-word form, which is the unsound configuration this selection
    /// exists to prevent.
    ///
    /// Nothing in the output catches it: the lost-set race depends on scheduler
    /// timing, so the wrong form produces correct tokens on every run where the
    /// race does not fire. Only the emitted program can be asserted on.
    #[test]
    fn a_batch_wider_than_one_workgroup_selects_the_grid_form() {
        let shape = LoopShape::new(40, 15, 15);
        assert_eq!(shape.groups(), 3, "40 segments of stride 16");

        let program = device_loop_program(shape, stub_body(), Vec::new());
        assert!(
            contains_grid_sync(&program),
            "a multi-group batch must separate its waves with GridSync"
        );
        let chain = region_chain(program.entry());
        assert_eq!(
            chain.get(1).map(|entry| entry.0.as_str()),
            Some(vyre_primitives::fixpoint::persistent_fixpoint::OP_ID_GRID),
            "got: {chain:?}"
        );
    }

    /// Locks out: paying grid synchronization on a batch that fits one
    /// workgroup, where the in-kernel loop is already sound because that single
    /// group's barriers are incidentally grid-wide.
    #[test]
    fn a_batch_inside_one_workgroup_keeps_the_in_kernel_form() {
        let shape = LoopShape::new(2, 4, 4);
        assert_eq!(shape.groups(), 1);

        let program = device_loop_program(shape, stub_body(), Vec::new());
        assert!(
            !contains_grid_sync(&program),
            "one workgroup needs no grid barrier"
        );
        let chain = region_chain(program.entry());
        assert_eq!(
            chain.get(1).map(|entry| entry.0.as_str()),
            Some(vyre_primitives::fixpoint::persistent_fixpoint::OP_ID),
            "got: {chain:?}"
        );
    }

    /// Locks out: uploading a one-word `changed` buffer to a kernel that indexes
    /// one word per wave.
    ///
    /// Never clearing the word is exactly what removes the lost-set race, so the
    /// grid form needs a fresh word per pass. A host that still sends one word
    /// leaves the kernel addressing past the end of the binding, and the width
    /// is read off the program precisely so the two cannot disagree.
    #[test]
    fn the_changed_buffer_widens_to_the_pass_budget_only_for_the_grid_form() {
        let single = device_loop_program(LoopShape::new(2, 4, 9), stub_body(), Vec::new());
        assert_eq!(changed_words(&single), 1);

        let grid = device_loop_program(LoopShape::new(40, 15, 9), stub_body(), Vec::new());
        assert_eq!(changed_words(&grid), 9, "one word per pass of the budget");
    }

    /// Decode the pass count from the grid form's own per-wave flags.
    ///
    /// The primitive gives each wave a word, never clears one, and exits at the
    /// first zero, so the array is a run of ones followed by zeros and the count
    /// is the index of the first zero plus one. No zero means the budget ran out.
    fn decode_waves(changed: &[u32]) -> u32 {
        changed
            .iter()
            .position(|word| *word == 0)
            .map_or(changed.len() as u32, |index| index as u32 + 1)
    }

    /// Run one dispatch of `body` over `batch` on the reference backend.
    fn dispatch_once(batch: &LoopBatch, body: Vec<Node>) -> PassWindow {
        let program = device_loop_program(batch.shape(), body, Vec::new());
        let mut window = PassWindow::seed(batch);
        let dispatched = dispatch_window(
            &vyre_driver_reference::CpuRefBackend,
            &program,
            batch.shape(),
            &mut window,
            &[],
        );
        assert!(dispatched.is_ok(), "reference dispatch must succeed");
        window
    }

    /// A batch of `segments` four-token pretokens.
    fn wide_batch(segments: u32) -> LoopBatch {
        let pretokens: Vec<Vec<u32>> = (0..segments).map(|_| vec![1u32, 2, 3, 4]).collect();
        LoopBatch::with_sound_bound(&pretokens)
    }

    /// Locks out: this module's pass counter drifting from the primitive's own
    /// per-wave flags.
    ///
    /// The two numbers come from genuinely different mechanisms. `passes` is a
    /// word this harness increments in `open_pass`; the `changed` array is
    /// written by the primitive, one word per wave, never cleared. They measure
    /// the same loop and must agree. If they ever stop agreeing, one of them is
    /// miscounting and every convergence depth this module reports, including
    /// the per-segment ones an operator uses to localize a cap hit, is suspect.
    ///
    /// Covered on a run that converges early, where the array carries a real
    /// zero, and on one that exhausts the budget, where it does not: those are
    /// the two decode branches and a decoder can be wrong on either alone.
    #[test]
    fn the_harness_pass_count_agrees_with_the_primitives_own_wave_flags() {
        let batch = wide_batch(200);
        assert!(
            batch.shape().groups() > 1,
            "must span several groups, or this exercises the single-word form \
             whose one flag carries no per-wave history"
        );

        // Copying state through unchanged is a fixed point, so the first wave
        // moves nothing and the loop exits having entered exactly one.
        let settled = dispatch_once(
            &batch,
            vec![Node::store(
                NAME_STATE_NEXT,
                lane(),
                Expr::load(NAME_STATE_CURRENT, lane()),
            )],
        );
        assert_eq!(settled.passes, 1, "a fixed point settles in one wave");
        assert_eq!(decode_waves(&settled.staging.changed), settled.passes);
        assert_eq!(
            settled.staging.changed.first().copied(),
            Some(0),
            "the first wave moved nothing, so its flag must be clear"
        );

        // Incrementing every word changes state on every wave, so no flag is
        // ever clear and the loop runs the whole budget.
        let capped = dispatch_once(
            &batch,
            vec![Node::store(
                NAME_STATE_NEXT,
                lane(),
                Expr::add(Expr::load(NAME_STATE_CURRENT, lane()), Expr::u32(1)),
            )],
        );
        let budget = batch.shape().max_passes();
        assert_eq!(capped.passes, budget, "a body that never settles runs out");
        assert_eq!(decode_waves(&capped.staging.changed), capped.passes);
        assert!(
            capped.staging.changed.iter().all(|word| *word != 0),
            "every wave moved state, so no flag may be clear"
        );
    }

    /// Locks out: the grid form's `changed` array coming back the wrong width.
    ///
    /// The host uploads it zero-filled at the width the program declares, and
    /// the kernel indexes one word per wave. A short readback would leave the
    /// decode above reading past the end of what the device actually wrote,
    /// which would make the agreement check pass on stale host zeros.
    #[test]
    fn the_wave_flag_array_returns_at_its_declared_width() {
        let batch = wide_batch(200);
        let window = dispatch_once(
            &batch,
            vec![Node::store(
                NAME_STATE_NEXT,
                lane(),
                Expr::load(NAME_STATE_CURRENT, lane()),
            )],
        );
        assert_eq!(window.staging.changed.len() as u32, batch.shape().max_passes());
    }

    /// A contract-abiding pass body: carry every live slot through unchanged.
    ///
    /// Writes EVERY slot of `next` that its segment owns, length word included,
    /// which is what the module contract requires and what makes the un-uploaded
    /// back buffer sound. The seed is therefore the fixed point, so the tokens
    /// this returns must be the tokens that went in, at their own slots.
    fn carry_through_body(shape: LoopShape) -> Vec<Node> {
        let mut inner = segment_coordinates(shape);
        inner.push(Node::store(
            NAME_STATE_NEXT,
            lane(),
            Expr::load(NAME_STATE_CURRENT, lane()),
        ));
        vec![Node::if_then(lane_is_live(shape), inner)]
    }

    /// A pass body that drops each segment's last token, settling at length 0.
    ///
    /// Also contract-abiding: slot 0 gets the new length, every token slot at or
    /// past it gets [`DEAD_SLOT`], and every slot before it carries through. It
    /// takes several passes to settle, so staged bytes get several chances to
    /// leak into the answer rather than only one.
    fn shrink_body(shape: LoopShape) -> Vec<Node> {
        let mut inner = segment_coordinates(shape);
        inner.push(Node::if_then_else(
            Expr::eq(Expr::var("slot"), Expr::u32(0)),
            vec![Node::if_then_else(
                Expr::eq(Expr::var("len"), Expr::u32(0)),
                vec![Node::store(NAME_STATE_NEXT, lane(), Expr::u32(0))],
                vec![Node::store(
                    NAME_STATE_NEXT,
                    lane(),
                    Expr::sub(Expr::var("len"), Expr::u32(1)),
                )],
            )],
            vec![
                Node::let_bind("token", Expr::sub(Expr::var("slot"), Expr::u32(1))),
                Node::if_then_else(
                    Expr::ge(
                        Expr::add(Expr::var("token"), Expr::u32(1)),
                        Expr::var("len"),
                    ),
                    vec![Node::store(NAME_STATE_NEXT, lane(), Expr::u32(DEAD_SLOT))],
                    vec![Node::store(
                        NAME_STATE_NEXT,
                        lane(),
                        Expr::load(NAME_STATE_CURRENT, lane()),
                    )],
                ),
            ],
        ));
        vec![Node::if_then(lane_is_live(shape), inner)]
    }

    /// A pass body that writes ONLY each segment's length word.
    ///
    /// Deliberately in VIOLATION of the module contract: every token slot of
    /// `next` is left untouched, so whatever the staging put there survives into
    /// `current`. It exists to give the poison check teeth.
    fn length_only_body(shape: LoopShape) -> Vec<Node> {
        let mut inner = segment_coordinates(shape);
        inner.push(Node::if_then(
            Expr::eq(Expr::var("slot"), Expr::u32(0)),
            vec![Node::store(NAME_STATE_NEXT, lane(), Expr::var("len"))],
        ));
        vec![Node::if_then(lane_is_live(shape), inner)]
    }

    /// Run one dispatch, optionally replacing the staged bytes of the two
    /// buffers the kernel is supposed to overwrite before reading.
    ///
    /// `None` runs the harness exactly as production does. `Some(word)` fills
    /// [`NAME_STATE_NEXT`] and [`NAME_SEGMENT_CHANGED`] with `word` instead,
    /// which is what the resident path effectively hands the device when it skips
    /// those uploads and the allocator returns whatever it had.
    fn dispatch_seeded(batch: &LoopBatch, body: Vec<Node>, poison: Option<u32>) -> PassWindow {
        let program = device_loop_program(batch.shape(), body, Vec::new());
        let mut window = PassWindow::seed(batch);
        if let Some(word) = poison {
            window.staging.next_filler = pack_u32_slice(&vec![word; batch.state().len()]);
            window.staging.segment_changed = vec![word; batch.shape().segments() as usize];
        }
        let dispatched = dispatch_window(
            &vyre_driver_reference::CpuRefBackend,
            &program,
            batch.shape(),
            &mut window,
            &[],
        );
        assert!(dispatched.is_ok(), "reference dispatch must succeed");
        if poison.is_some() {
            // The filler's bytes are staged for the NEXT window only by length,
            // so a poisoned one parked in the thread's staging pool would leak
            // the poison into a later clean run on this thread. Drop it instead:
            // the pool keeps the allocation-free guarantee for canonical bytes
            // only, which is all production ever stages.
            window.staging.next_filler = Vec::new();
        }
        window
    }

    /// Assert `body` gives the same answer whatever the un-uploaded buffers hold.
    fn assert_seed_independent(batch: &LoopBatch, body: impl Fn(LoopShape) -> Vec<Node>) {
        let clean = dispatch_seeded(batch, body(batch.shape()), None);
        // Two poisons, not one. A single pattern that happened to equal what the
        // clean run staged would make this vacuous, and a run that agreed with
        // DEAD_SLOT by coincidence would not agree with zero as well.
        for poison in [0u32, 0xdead_beef, DEAD_SLOT ^ 1] {
            let dirty = dispatch_seeded(batch, body(batch.shape()), Some(poison));
            assert_eq!(
                clean.staging.current, dirty.staging.current,
                "state must not depend on what {poison:#x} staged into the buffers the kernel \
                 overwrites"
            );
            assert_eq!(clean.passes, dirty.passes, "pass count must not depend on it");
            assert_eq!(
                clean.staging.segment_passes, dirty.staging.segment_passes,
                "per-segment depths must not depend on it"
            );
            assert_eq!(
                clean.staging.segment_changed, dirty.staging.segment_changed,
                "the verdict must not depend on it"
            );
        }
    }

    /// A batch pairing one-token segments with `longest`-token segments.
    ///
    /// This is the maximum-padding arrangement: a one-token segment occupies two
    /// of the `longest + 1` words its stride reserves and the rest ships as dead
    /// padding. `groups` sets how many workgroups it spans, because the group
    /// tail is the second padding kind and only appears past one group.
    fn mixed_batch(longest: u32, groups: u32, max_passes: u32) -> LoopBatch {
        let per_group = LOOP_WORKGROUP_WIDTH / (longest + 1);
        let segments = (per_group * groups).max(2);
        let pretokens: Vec<Vec<u32>> = (0..segments)
            .map(|index| {
                let len = if index % 2 == 0 { 1 } else { longest };
                (0..len).map(|slot| index * 1000 + slot + 1).collect()
            })
            .collect();
        LoopBatch::new(&pretokens, max_passes)
    }

    /// Locks out: [`HARNESS_SEED_IS_READ`] drifting out of binding order.
    ///
    /// The array is consumed positionally against the binding list, so an entry
    /// in the wrong slot would skip the upload of a buffer whose arriving value
    /// IS part of the answer. `passes` and `segment_passes` are accumulated with
    /// `atomic_add` and `changed` must arrive zeroed, so getting any of those
    /// three wrong is a silent wrong answer rather than a failure.
    #[test]
    fn the_seed_read_table_lines_up_with_the_binding_numbering() {
        let read = |binding: u32| HARNESS_SEED_IS_READ[binding as usize];
        assert!(read(BINDING_STATE_CURRENT), "the tokens themselves");
        assert!(!read(BINDING_STATE_NEXT), "overwritten whole every pass");
        assert!(read(BINDING_CHANGED), "must arrive zeroed");
        assert!(read(BINDING_PASSES), "accumulated with atomic_add");
        assert!(!read(BINDING_SEGMENT_CHANGED), "cleared by open_pass");
        assert!(read(BINDING_SEGMENT_PASSES), "accumulated with atomic_add");
        assert_eq!(
            HARNESS_SEED_IS_READ.iter().filter(|read| !**read).count(),
            2,
            "exactly two harness buffers are derivable on device; a third would need its own \
             proof in the IR before it may be added here"
        );
    }

    /// Locks out: the back buffer's readback silently widening back to full.
    ///
    /// `output_byte_range` narrows the READBACK, not the allocation, and the two
    /// have to stay that way: the kernel indexes every word of `next` through
    /// [`LoopShape::segment_base`], so a narrowed COUNT would put a write past
    /// the end of the buffer. This checks both halves, because a change that
    /// shrank the count instead would still remove the bytes and would look like
    /// it worked.
    #[test]
    fn the_back_buffer_declares_a_zero_length_readback_at_its_full_allocation() {
        let batch = wide_batch(200);
        let shape = batch.shape();
        let program = device_loop_program(shape, carry_through_body(shape), Vec::new());
        let next = program
            .buffers()
            .iter()
            .find(|buffer| buffer.name() == NAME_STATE_NEXT);
        assert_eq!(
            next.and_then(BufferDecl::output_byte_range),
            Some(0..0),
            "the host consults nothing in the back buffer, so it must come home empty"
        );
        assert_eq!(
            next.map(BufferDecl::count),
            Some(shape.state_words()),
            "the allocation must still cover every word the kernel writes"
        );
        // The front buffer is the control: it carries the answer, so narrowing it
        // would be the same edit applied to the wrong binding.
        let current = program
            .buffers()
            .iter()
            .find(|buffer| buffer.name() == NAME_STATE_CURRENT);
        assert_eq!(
            current.and_then(BufferDecl::output_byte_range),
            None,
            "the front buffer carries the tokens home and must not be narrowed"
        );
    }

    /// Locks out: the narrowing spreading to the inspection constructor and
    /// blinding the padding and ownership assertions that depend on it.
    ///
    /// The scale-boundary suite reads the back buffer to check that unowned words
    /// really are [`DEAD_SLOT`] and that no owned word came back unwritten. When
    /// the narrowing first landed it was applied to every program, those three
    /// assertions started indexing an empty vector, and a genuine coverage hole
    /// shipped looking like a clean result. The two programs must therefore
    /// disagree on this one declaration and on NOTHING else.
    #[test]
    fn the_inspection_program_returns_the_back_buffer_and_is_otherwise_identical() {
        let batch = wide_batch(200);
        let shape = batch.shape();
        let shipped = single_pass_program(shape, carry_through_body(shape), Vec::new());
        let inspecting =
            single_pass_program_returning_state(shape, carry_through_body(shape), Vec::new());

        let next_range = |program: &Program| {
            program
                .buffers()
                .iter()
                .find(|buffer| buffer.name() == NAME_STATE_NEXT)
                .and_then(BufferDecl::output_byte_range)
        };
        assert_eq!(
            next_range(&shipped),
            Some(0..0),
            "the shipped single-pass program must keep the narrow window"
        );
        assert_eq!(
            next_range(&inspecting),
            None,
            "the inspection program must leave the window open, or a suite reading \
             the back buffer indexes an empty vector instead of failing on contents"
        );

        // Everything else has to match, otherwise a test using the inspection
        // program is no longer observing the kernel production runs.
        let shape_of = |program: &Program| {
            program
                .buffers()
                .iter()
                .map(|buffer| (buffer.name().to_owned(), buffer.binding, buffer.count))
                .collect::<Vec<_>>()
        };
        assert_eq!(
            shape_of(&shipped),
            shape_of(&inspecting),
            "the two programs must declare the same bindings at the same widths"
        );
        assert_eq!(
            shipped.workgroup_size(),
            inspecting.workgroup_size(),
            "the two programs must launch at the same width"
        );
    }

    /// Locks out: an un-uploaded harness buffer becoming an observable read.
    ///
    /// This is the invariant [`HARNESS_SEED_IS_READ`] rests on, and it is checked
    /// rather than remembered. If a future pass body leaves one word of `next`
    /// untouched on some shape, or a future `open_pass` stops clearing every
    /// segment flag, the skipped upload turns into an uninitialized read and the
    /// failure is a wrong token id with nothing hanging, which is exactly the
    /// defect class that cost this project a full day.
    ///
    /// Covered on three shapes and three poison patterns. The mixed shapes are
    /// the ones that matter: they pair a one-token segment with a long one, so a
    /// leak through the padding tail lands where a uniform batch has nothing.
    #[test]
    fn poison_seed_does_not_reach_a_contract_abiding_body() {
        for body in [
            carry_through_body as fn(LoopShape) -> Vec<Node>,
            shrink_body as fn(LoopShape) -> Vec<Node>,
        ] {
            // Uniform, several groups.
            assert_seed_independent(&wide_batch(200), body);
            // Stride 256: exactly one segment per group and no group tail, so all
            // the padding is inside the long stride. The budget is deliberately
            // small: several passes is what the invariance needs, and unrolling
            // 256 grid waves of a 255-token body would cost minutes for nothing.
            let widest = mixed_batch(LOOP_WORKGROUP_WIDTH - 1, 3, 6);
            assert_eq!(widest.shape().segments_per_group(), 1);
            assert_seed_independent(&widest, body);
            // Stride 101: two segments per group and 54 words of group tail, so
            // both padding kinds are live at once.
            let tailed = mixed_batch(100, 4, 6);
            assert_eq!(tailed.shape().segments_per_group(), 2);
            assert!(tailed.shape().groups() > 1);
            assert_seed_independent(&tailed, body);
        }
    }

    /// Locks out: the poison check above passing vacuously.
    ///
    /// A test that a staged value cannot be observed is worthless unless the
    /// same mechanism CAN observe one when the contract is broken. This runs a
    /// body that writes only each segment's length word, leaving every token
    /// slot of `next` to the staging, and requires the two runs to disagree. If
    /// this ever starts passing by agreement, the poison above stopped reaching
    /// the device and proves nothing.
    #[test]
    fn poison_seed_is_visible_to_a_body_that_skips_a_live_slot() {
        let batch = mixed_batch(100, 4, 6);
        let clean = dispatch_seeded(&batch, length_only_body(batch.shape()), None);
        let dirty = dispatch_seeded(&batch, length_only_body(batch.shape()), Some(0xdead_beef));
        assert_ne!(
            clean.staging.current, dirty.staging.current,
            "a body that leaves live slots of `{NAME_STATE_NEXT}` unwritten must expose the \
             staged bytes, or the poison never reached the device and the invariance check \
             above is vacuous"
        );
    }

    /// Locks out: padding shifting a token out of its own slot.
    ///
    /// The shortest and the longest admissible pretoken in one batch is the
    /// worst case the layout allows: one segment uses 2 of its 256 words and its
    /// neighbour uses all of them. A `segment_base` off by one, or a lane
    /// liveness predicate that admitted a padding lane, moves tokens between
    /// segments while every length word still looks right. Comparing the whole
    /// per-segment vector against the seed is what catches that, since a
    /// carry-through body makes the seed the exact expected answer.
    #[test]
    fn a_batch_mixing_the_shortest_and_longest_admissible_pretoken_converges_exactly() {
        let longest = LOOP_WORKGROUP_WIDTH - 1;
        let batch = mixed_batch(longest, 3, 4);
        let shape = batch.shape();
        assert_eq!(shape.segment_capacity(), longest, "the admissible maximum");
        assert!(shape.groups() > 1, "must span groups");

        for poison in [None, Some(0u32), Some(0xdead_beef)] {
            let window = dispatch_seeded(&batch, carry_through_body(shape), poison);
            let outcome = window.into_outcome(shape);
            assert_eq!(outcome.termination(), Termination::Converged);
            for segment in 0..shape.segments() {
                let expected_len = if segment % 2 == 0 { 1 } else { longest };
                let expected: Vec<u32> = (0..expected_len)
                    .map(|slot| segment * 1000 + slot + 1)
                    .collect();
                assert_eq!(
                    outcome.converged_tokens(segment).ok(),
                    Some(expected.as_slice()),
                    "segment {segment} under poison {poison:?} must converge with its own tokens"
                );
            }
        }
    }
}