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
//! Device-resident pretokenization boundaries for `cl100k_base`. OWNER: DevicePretok.
//!
//! Op id: `exatok::gpu_pretokenize::boundaries`. Soundness: `Exact` against
//! [`crate::pretokenize`], which is itself the crate's host oracle for the
//! tiktoken split patterns.
//!
//! # What this computes
//!
//! One dispatch turns a byte slice into the same `u32` offset vector that
//! [`crate::pretokenize::segment_starts`] produces: every pretoken start in
//! order, followed by the total length as a sentinel. Nothing about the split
//! is approximated. The device evaluates the same eight `cl100k_base`
//! alternatives, in the same order, with the same possessive semantics, and a
//! disagreement of a single byte is a bug rather than a tolerance.
//!
//! # Why this is NOT wired into the encode path
//!
//! DO NOT WIRE THIS INTO [`crate::device::DeviceTokenizer`]. The module is
//! feature-gated (`gpu-pretokenize`, off by default) precisely so that it does
//! not read as a shipped capability. It is a REPRODUCIBLE NEGATIVE RESULT: the
//! measurement is the asset and this code is what makes the measurement
//! re-runnable on future hardware.
//!
//! There are two reasons, and they are not equally durable. The decisive one is
//! the exactness liability, which no hardware will ever fix. The cost is
//! supporting evidence, and it is the one a future reader could plausibly
//! overturn. They are presented in that order deliberately.
//!
//! # The decisive reason: two boundary producers, forever
//!
//! This pass implements `cl100k_end` ONLY. The crate's four required encodings
//! are served by three patterns ([`SplitPattern::Gpt2`] for `r50k_base` and
//! `p50k_base`, [`SplitPattern::Cl100kBase`], and [`SplitPattern::O200kBase`]),
//! and [`crate::device::DeviceTokenizer`] is built from an [`crate::Encoding`]
//! carrying any of them. Wiring this in therefore forks the encode path BY
//! ENCODING: `cl100k_base` would take device boundaries while the other three
//! keep host boundaries.
//!
//! That leaves two independent boundary producers that must agree byte for byte
//! forever, on the one claim that is the entire product. Boundaries decide which
//! merges are reachable, so they decide token ids; a one-byte disagreement in
//! either producer is a wrong-ids bug, not a performance regression. Every
//! future change to the split rules would then have to land twice, in a
//! sequential scan and in a pointer-doubling GPU pass, and stay provably
//! identical across both.
//!
//! A permanent two-producer exactness liability, taken on for a speculative
//! win, on a component that is not the bottleneck, is a bad trade AT ANY SPEED.
//! That argument does not depend on a benchmark, does not expire when the GPU
//! gets faster, and is why this question is closed rather than deferred.
//!
//! # The supporting reason: measured cost
//!
//! It also loses by a factor of 45, and the loss is in the KERNEL, so no
//! dispatch, transfer, or residency work can reach break-even.
//!
//! Provenance. Measured on an RTX 5090 (170 SMs, `max_threads_per_sm` 1536
//! measured on the real device, compute capability 12.0, CUDA 12.8), host a
//! Ryzen 9 9950X, `cl100k_base`, one text per dispatch. The host arm is
//! [`crate::pretokenize::segment_starts`] over the identical bytes, sustaining
//! 238 to 398 MB/s on ONE core (238 on CJK, 387 prose, 398 code). Kernel time
//! is CUDA event elapsed read from vyre's own counters through
//! `dispatch_borrowed_timed`, not from a timer this module wrote.
//!
//! Method. Eight interleaved rounds with both arms in one process, so box state
//! moves both halves of a pair together. Absolutes are best-of-N because
//! contention is additive to elapsed time; ratios are the median of per-round
//! ratios; timed regions are folded to at least 0.5 s. The box was contended
//! throughout by an unrelated `llama-server` holding about 24 GB of the device,
//! which is why the method is built to survive contention rather than to assume
//! its absence.
//!
//! ```text
//! bytes    host best   kernel best   kernel/host   kernel throughput
//!    256   0.0003 ms      0.0206 ms        74.9x        12.4 MB/s
//!   1024   0.0010 ms      0.0350 ms        33.8x        29.2 MB/s
//!   4096   0.0044 ms      0.2823 ms        63.9x        14.5 MB/s
//!  16384   0.0187 ms      1.4252 ms        76.0x        11.5 MB/s
//!  65536   0.1426 ms      6.8653 ms        48.2x         9.6 MB/s
//! 262144   0.6774 ms     30.4775 ms        45.0x         8.6 MB/s
//! ```
//!
//! The headline cell is the last row, where BOTH arms were clean: host 0.6774 ms
//! at 1.0 percent relative standard deviation, kernel 30.4775 ms at 2.4 percent.
//!
//! What was NOT clean, stated plainly because it changes what the numbers can
//! carry. End to end at 262144 bytes, everything included (program build, input
//! packing, enqueue, kernel, wait, readback, unpack), [`run_boundaries`]
//! measured 41.6 ms against 0.69 ms for the host, but that cell came back at
//! 31.8 percent relative standard deviation and its enqueue sub-cell at 76.4
//! percent, both far outside tolerance, so neither is load-bearing here. The
//! evidence that wall time was the contaminated quantity and kernel time was
//! not: across the same runs the 65536-byte end-to-end figure moved 8.62 ms to
//! 14.82 ms while the kernel figure for that size moved only 6.69 ms to 6.87 ms.
//! CUDA events time the device; wall clock times the device plus whatever else
//! the box was doing. The verdict rests on the kernel column for that reason.
//!
//! Why no dispatch work can rescue it, measured rather than assumed: an empty
//! program round trip costs 0.0232 ms wall (enqueue 0.0096, kernel 0.0043, wait
//! 0.0036), three orders of magnitude below the kernel cost. So the break-even
//! per-dispatch host cost is NEGATIVE, about -29.8 ms: the kernel alone already
//! exceeds the whole host scan by roughly thirty milliseconds. A cheaper
//! dispatch does not help, a resident input buffer does not help, and the host
//! baseline is still falling as its own optimization work lands.
//!
//! # Why chunking across SMs is not the answer either
//!
//! This question is CLOSED WITH A REASON, not unexplored, because the obvious
//! objection to the numbers above is correct as far as it goes.
//!
//! The cost is caused by the workgroup count, not by the algorithm. Pointer
//! doubling is a chain of DEPENDENT global loads, and this pass runs in one
//! workgroup of [`WORKGROUP_WIDTH`] lanes: eight warps on one of 170 SMs, under
//! 0.1 percent of the device's 261,120 resident-thread capacity. Eight warps
//! cannot hide dependent-load latency, which is the whole of the 9 to 12 MB/s
//! ceiling on long inputs. The single-workgroup choice is deliberate and its
//! reasoning is under "Why one workgroup" below.
//!
//! So 169 of 170 SMs are idle, and the theoretical attack is real: cut the
//! input into chunks with enough right-hand overlap to cover the longest run an
//! alternative can depend on, run one workgroup per chunk, and discard the
//! boundaries that fall in the overlap. That could plausibly close a 45x gap.
//!
//! We are declining it anyway, on the decisive reason above rather than on
//! feasibility. Making one of four encodings faster still buys a permanent
//! obligation to keep two boundary producers byte-identical, and pretokenization
//! is a 4.8 percent slice of the encode it sits in. Making a 4.8 percent slice
//! of one encoding faster is not worth a standing risk to the exactness claim.
//! Note also what overlap would cost in exactness terms: the correct overlap is
//! bounded by the longest input-dependent run, and getting that bound wrong is
//! silent, producing valid-looking boundaries at the wrong offsets, which is the
//! failure mode this crate least wants to introduce.
//!
//! The parallelism this formulation already has is across TEXTS, not across
//! bytes within one text, so the cheap version of the attack is one workgroup
//! per text over a batch ([`BoundaryShape`] already carries the shape). On the
//! crate's own batch cells that looks favourable: per-text kernel time is
//! 0.282 ms at `DOC_BYTES` (4096) and about 0.03 ms at `SMALL_DOC_BYTES` (512),
//! and 170 SMs host at least 170 concurrent workgroups, so 64 documents of 4 KiB
//! or 512 documents of 512 B would each clear in one or two waves. Treat that as
//! an EXTRAPOLATION from measured per-text kernel time and the SM count, not as
//! a measurement: the batched pass does not exist, and at that width the pass
//! stops being latency-bound and becomes bandwidth-bound, which the
//! extrapolation does not model. It does not change the verdict; it is recorded
//! so the next reader starts from the measured position rather than redoing it.
//!
//! # Why a pointer-doubling formulation
//!
//! The host splitter is a sequential scan: `at = cl100k_end(at)` until the end
//! of input. That recurrence is a functional graph over byte offsets, so it
//! parallelizes by pointer doubling rather than by cutting the input into
//! independent chunks. Chunking is what a naive port would do and it is wrong
//! here, because a pretoken can span any chunk boundary and the alternative
//! that wins at an offset depends on an unbounded run to its right.
//!
//! The pass runs in five kinds of stage:
//!
//! 1. `decode`: one lane per byte offset decodes the UTF-8 unit that starts
//!    there, recording its length and its `\p{L}` / `\p{N}` / `\s` class. This
//!    mirrors `Cursor::unit`, including the strict table 3-7 bounds that reject
//!    overlongs, surrogates, and scalars past `U+10FFFF`.
//! 2. `chase_init`: seeds six single-step successor planes, one per unbounded
//!    run the pattern can ask for.
//! 3. `chase`: `ceil(log2(n + 1))` doubling rounds turn each single-step plane
//!    into a full run-end plane. After the last round `letter[p]` is
//!    `run_end(p, L)`, `other[p]` is `other_run_end(p)`, and so on.
//! 4. `next`: one lane per offset evaluates `cl100k_end` using those planes,
//!    which makes every alternative a constant number of loads.
//! 5. `chain`: the same doubling applied to `next` itself. Offset `j` of the
//!    result is `next` composed with itself `j` times starting at zero, which
//!    is exactly the `j`th pretoken start. Reading the composition off a
//!    binary decomposition of `j` avoids any scatter and therefore any race.
//!
//! # Why one workgroup
//!
//! Every stage boundary is a grid-wide dependency. A `MemoryOrdering::GridSync`
//! barrier would express that directly, but `vyre-driver-cuda` rejects a
//! grid-sync program outright unless the caller routes it through the registry
//! split wrapper, and the native cooperative path additionally carries a
//! residency ceiling. Running the whole pass inside a single workgroup with
//! ordinary workgroup barriers and a grid-stride loop per stage removes that
//! whole failure surface: the barrier semantics are the ones every backend
//! already implements, and with one block a workgroup barrier IS a grid
//! barrier.
//!
//! The cost is that a single text is limited to [`WORKGROUP_WIDTH`] lanes. That
//! is the right trade for this pass because batch throughput comes from texts,
//! not from bytes within one text: the natural extension is one workgroup per
//! text, where the lane budget is already saturated.
//!
//! # Why no stage body branches
//!
//! Every stage body is a straight-line chain of `let` bindings and
//! `Expr::select`. There is no `Node::if_then` and no `Node::assign` anywhere
//! in this module.
//!
//! The property that makes that sound is that EVERY LOAD IN EVERY STAGE BODY
//! IS IN BOUNDS FOR EVERY LANE, unconditionally. A `select` evaluates both
//! arms, so a load that only a guard kept in range would fault or read
//! garbage; here none of them need the guard. The byte buffer carries
//! [`BYTE_PAD`] zero bytes past the input, which covers the largest read the
//! pass makes: `len + 3` in [`decode_body`], from the fourth byte of a
//! four-byte sequence starting at the end sentinel, and `len + 2` in
//! [`folded_letter`], from the second byte of the `U+017F` fold. Plane
//! indices are byte offsets and never exceed `len`. The range table is padded
//! to `2^levels - 1` slots with an unreachable `u32::MAX` low bound, so the
//! binary lift probes a real slot at every level.
//!
//! That is a precondition, not a happy accident. Anyone reintroducing a branch
//! here, or extending a stage body with a load that is not unconditionally in
//! bounds, has to re-establish it. Adding the load first and the guard second
//! is the failure mode, because a guard is exactly what this form does not
//! have.
//!
//! # Where the character classes come from
//!
//! `crate::pretokenize::unicode_class` is `pub(super)`, so this module cannot
//! read its tables without widening the visibility of a generated file it does
//! not own. Rather than paste a second copy of Unicode 16.0.0 (two tables that
//! can drift is the defect, not the duplication of bytes), the device table is
//! DERIVED from the host splitter's observable behaviour: [`class_table`]
//! probes `pretokens` with three diagnostic inputs per scalar and reads the
//! class back off the split it produces. There is still exactly one source of
//! truth, and a change to the host tables moves the device table with it.

use std::sync::LazyLock;

use vyre::ir::{BufferAccess, BufferDecl, DataType, Expr, Node, Program};
use vyre_driver::{DispatchConfig, VyreBackend};
use vyre_libs::region::wrap_anonymous;
use vyre_primitives::wire::{pack_u32_slice, unpack_u32_slice_into};

use crate::pretokenize::{SplitPattern, pretokens};
use crate::{ExatokError, trap_program};

/// Canonical op id for the boundary pass.
pub const BOUNDARIES_OP_ID: &str = "exatok::gpu_pretokenize::boundaries";

/// Lanes in the single workgroup that runs the pass.
pub const WORKGROUP_WIDTH: u32 = 256;

/// Largest input the builder accepts.
///
/// The chase planes are the binding constraint: two ping-pong buffers of
/// `6 * (len + 1)` words each, so a 1 MiB input already reserves 48 MiB of
/// device scratch. Longer inputs belong in separate dispatches.
pub const MAX_INPUT_BYTES: u32 = 1 << 20;

/// `\p{L}`.
pub const CLASS_LETTER: u32 = 1;
/// `\p{N}`.
pub const CLASS_NUMBER: u32 = 2;
/// `\s`, which the `regex` crate resolves to `\p{White_Space}`.
pub const CLASS_SPACE: u32 = 4;
/// Union of the three classes the `cl100k_base` pattern can name. Its
/// complement is the pattern's `[^\s\p{L}\p{N}]`.
const CLASS_ANY: u32 = CLASS_LETTER | CLASS_NUMBER | CLASS_SPACE;

/// Input bytes, one per `u32` slot, zero padded.
pub const BYTES_BUFFER: &str = "exatok_pretok_bytes";
/// Class bitmask of every ASCII codepoint, indexed directly.
pub const ASCII_CLASS_BUFFER: &str = "exatok_pretok_ascii_class";
/// Flattened `(low, high, class)` triples for scalars at or above `U+0080`.
pub const RANGE_CLASS_BUFFER: &str = "exatok_pretok_range_class";
/// Pretoken start offsets followed by the total length sentinel.
pub const OFFSETS_BUFFER: &str = "exatok_pretok_offsets";

/// Decoded unit length and class, two planes of `len + 1` words.
const UNITS_BUFFER: &str = "exatok_pretok_units";
/// Successor planes, ping-pong half A.
const CHASE_A_BUFFER: &str = "exatok_pretok_chase_a";
/// Successor planes, ping-pong half B.
const CHASE_B_BUFFER: &str = "exatok_pretok_chase_b";
/// Pretoken successor function, ping-pong half A.
const CHAIN_A_BUFFER: &str = "exatok_pretok_chain_a";
/// Pretoken successor function, ping-pong half B.
const CHAIN_B_BUFFER: &str = "exatok_pretok_chain_b";

/// Zero bytes appended past the input.
///
/// A lane at `len - 1` reads as far as `len + 2` when it tests the two-byte
/// fold of `U+017F` after an apostrophe, and as far as `len + 2` again when it
/// validates a four-byte lead's continuations. Padding with zero rather than
/// branching makes both reads in-bounds AND correct: byte zero fails every
/// continuation-range test and every case-folded letter test, which is exactly
/// what the host's `input.get(..)` returning `None` does.
const BYTE_PAD: u32 = 4;

/// Plane index of the decoded unit length.
const UNIT_LEN: u32 = 0;
/// Plane index of the decoded unit class.
const UNIT_CLASS: u32 = 1;
/// Planes in [`UNITS_BUFFER`].
const UNIT_PLANES: u32 = 2;

/// `run_end(p, L)` after doubling.
const PLANE_LETTER: u32 = 0;
/// `other_run_end(p)` after doubling.
const PLANE_OTHER: u32 = 1;
/// `run_end(p, WS)` after doubling.
const PLANE_SPACE: u32 = 2;
/// Start offset of the last whitespace unit in the run at `p`, or `p`.
const PLANE_LAST_SPACE: u32 = 3;
/// `byte_run_end(p, b"\r\n")` after doubling.
const PLANE_BREAK: u32 = 4;
/// One past the last `\r` or `\n` inside the whitespace run at `p`, or zero.
const PLANE_LAST_BREAK: u32 = 5;
/// Planes in each chase buffer.
const CHASE_PLANES: u32 = 6;

/// Byte value of an ASCII apostrophe.
const APOSTROPHE: u32 = 0x27;
/// Byte value of an ASCII space.
const SPACE: u32 = 0x20;
/// Byte value of a carriage return.
const CR: u32 = 0x0D;
/// Byte value of a line feed.
const LF: u32 = 0x0A;

/// What the boundary pass is being built for.
///
/// A shape is just an input length today, but it is a struct so the batch
/// extension (one workgroup per text) can add a text count without breaking
/// every call site.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BoundaryShape {
    input_len: u32,
}

impl BoundaryShape {
    /// Shape for a single text of `input_len` bytes.
    #[must_use]
    pub const fn new(input_len: u32) -> Self {
        Self { input_len }
    }

    /// Input length in bytes.
    #[must_use]
    pub const fn input_len(self) -> u32 {
        self.input_len
    }

    /// Addressable offsets, which is every byte position plus the end.
    #[must_use]
    pub const fn positions(self) -> u32 {
        self.input_len + 1
    }

    /// Doubling rounds needed to close every chase and chain plane.
    ///
    /// A run can be `positions() - 1` units long and a text can hold that many
    /// pretokens, so the reach `2^rounds` has to cover `positions()`.
    #[must_use]
    pub fn rounds(self) -> u32 {
        let target = u64::from(self.positions());
        let mut rounds = 1;
        let mut reach = 2u64;
        while reach < target {
            reach *= 2;
            rounds += 1;
        }
        rounds
    }

    /// Grid-stride iterations each lane performs per stage.
    #[must_use]
    pub fn chunks(self) -> u32 {
        self.positions().div_ceil(WORKGROUP_WIDTH)
    }

    /// Rejection message for a shape the builder cannot lower, or `None`.
    ///
    /// The remedy names the CONDITION on the split, not just the split. A cut
    /// taken anywhere rebases by addition arithmetically and is still wrong,
    /// because the end-of-input alternatives (`\s++$`, the three-unit numeric
    /// cap, and the contraction group needing a letter after the apostrophe)
    /// all fire at the cut and produce a boundary the whole input does not
    /// have. Splitting on a boundary the pass itself reported is what makes the
    /// pieces compose.
    fn rejection(self) -> Option<String> {
        (self.input_len > MAX_INPUT_BYTES).then(|| {
            format!(
                "gpu_pretokenize boundary shape has {} input bytes, past the {MAX_INPUT_BYTES} \
                 byte ceiling. Fix: split the text ON A PRETOKEN BOUNDARY and dispatch each \
                 piece, then rebase each piece's offsets by adding its start. Take the boundary \
                 from a dispatch of the first {MAX_INPUT_BYTES} bytes rather than cutting at a \
                 fixed offset: a cut inside a pretoken makes the end-of-input alternatives fire \
                 there and invents a boundary the whole text does not have.",
                self.input_len
            )
        })
    }
}

/// Unicode classes for the `cl100k_base` pattern, derived from the host oracle.
#[derive(Debug)]
pub struct ClassTable {
    ascii: [u32; 128],
    ranges: Vec<u32>,
}

impl ClassTable {
    /// Class bitmask of every ASCII codepoint, indexed directly.
    #[must_use]
    pub fn ascii(&self) -> &[u32; 128] {
        &self.ascii
    }

    /// Flattened `(low, high, class)` triples, ascending and disjoint.
    #[must_use]
    pub fn ranges(&self) -> &[u32] {
        &self.ranges
    }

    /// Triples in [`ClassTable::ranges`].
    #[must_use]
    pub fn range_count(&self) -> u32 {
        // The builder caps the table far below u32::MAX; the cast cannot wrap.
        (self.ranges.len() / 3) as u32
    }

    /// Class bitmask of one scalar, the host-side counterpart of the device
    /// lookup. Exposed so a test can compare the two without a GPU.
    #[must_use]
    pub fn class_of(&self, scalar: u32) -> u32 {
        if let Some(bits) = usize::try_from(scalar)
            .ok()
            .and_then(|index| self.ascii.get(index))
        {
            return *bits;
        }
        let mut low = 0usize;
        let mut high = self.ranges.len() / 3;
        while low < high {
            let mid = low + (high - low) / 2;
            match self.ranges.get(mid * 3) {
                Some(&start) if start <= scalar => low = mid + 1,
                _ => high = mid,
            }
        }
        if low == 0 {
            return 0;
        }
        match (self.ranges.get((low - 1) * 3 + 1), self.ranges.get((low - 1) * 3 + 2)) {
            (Some(&end), Some(&bits)) if scalar <= end => bits,
            _ => 0,
        }
    }
}

/// Device class table, built once per process from the host splitter.
///
/// Construction walks every scalar value and costs a fraction of a second. It
/// is a `LazyLock` so a caller that never dispatches never pays it.
pub fn class_table() -> &'static ClassTable {
    &CLASS_TABLE
}

static CLASS_TABLE: LazyLock<ClassTable> = LazyLock::new(build_class_table);

/// Class of one scalar, read off what the host splitter does with it.
///
/// Three probes, each of which isolates one class by giving exactly one
/// alternative of `cl100k_end` something to match:
///
/// - `. c .` splits into one span if and only if `c` is `[^\s\p{L}\p{N}]`,
///   because that is the only case where the whole probe is a single
///   punctuation run. A letter ends the run and starts `\p{L}++`, a digit and
///   whitespace both stop `other_run_end` at the first `.`.
/// - `a c` matches `\p{L}++` through `c` if and only if `c` is `\p{L}`, so the
///   first span reaches `1 + len(c)`.
/// - `c c c c` hits `\p{N}{1,3}` if and only if `c` is `\p{N}`, so the first
///   span stops at three copies rather than four.
///
/// Anything that survives all three is whitespace, which is sound because the
/// four cases partition every scalar.
fn derive_class(scalar: u32) -> u32 {
    let Some(character) = char::from_u32(scalar) else {
        // Surrogates. `Cursor::unit` cannot produce one (lead 0xED caps its
        // first continuation at 0x9F), so the class is unreachable.
        return 0;
    };
    let mut encoded = [0u8; 4];
    let bytes = character.encode_utf8(&mut encoded).as_bytes();
    let width = bytes.len();

    let mut wrapped = [0u8; 6];
    wrapped[0] = b'.';
    wrapped[1..=width].copy_from_slice(bytes);
    wrapped[width + 1] = b'.';
    let mut spans = pretokens(SplitPattern::Cl100kBase, &wrapped[..width + 2]);
    spans.next();
    if spans.next().is_none() {
        return 0;
    }

    let mut suffixed = [0u8; 5];
    suffixed[0] = b'a';
    suffixed[1..=width].copy_from_slice(bytes);
    if pretokens(SplitPattern::Cl100kBase, &suffixed[..=width])
        .next()
        .is_some_and(|span| span.end == 1 + width)
    {
        return CLASS_LETTER;
    }

    let mut repeated = [0u8; 16];
    for copy in 0..4 {
        repeated[copy * width..(copy + 1) * width].copy_from_slice(bytes);
    }
    if pretokens(SplitPattern::Cl100kBase, &repeated[..4 * width])
        .next()
        .is_some_and(|span| span.end == 3 * width)
    {
        return CLASS_NUMBER;
    }

    CLASS_SPACE
}

/// Walk every scalar once and coalesce equal-class neighbours into ranges.
fn build_class_table() -> ClassTable {
    let mut ascii = [0u32; 128];
    for (scalar, slot) in ascii.iter_mut().enumerate() {
        // `enumerate` over a 128-element array cannot exceed u32.
        *slot = derive_class(scalar as u32);
    }

    let mut ranges = Vec::new();
    let mut run_start = 0x80u32;
    let mut run_bits = derive_class(0x80);
    for scalar in 0x81..=0x0010_FFFFu32 {
        let bits = derive_class(scalar);
        if bits == run_bits {
            continue;
        }
        if run_bits != 0 {
            ranges.extend_from_slice(&[run_start, scalar - 1, run_bits]);
        }
        run_start = scalar;
        run_bits = bits;
    }
    if run_bits != 0 {
        ranges.extend_from_slice(&[run_start, 0x0010_FFFF, run_bits]);
    }

    ClassTable { ascii, ranges }
}

/// Levels of binary lifting that can address `count` entries.
///
/// The lift accumulates halves, so its largest reachable index is
/// `2^levels - 1`; that has to cover `count`.
fn lift_levels(count: u32) -> u32 {
    let mut levels = 0;
    let mut reach = 1u64;
    while reach - 1 < u64::from(count) {
        reach *= 2;
        levels += 1;
    }
    levels
}

/// Padded triple slots the range buffer declares for `levels` of lifting.
fn range_slots(levels: u32) -> u32 {
    // `levels` is bounded by the scalar space, so the shift cannot overflow.
    ((1u64 << levels) - 1).max(1) as u32
}

/// Build the boundary pass for `shape`.
///
/// Infallible by contract: an unsupported shape lowers to
/// [`crate::trap_program`] rather than returning an error or panicking.
#[must_use]
pub fn boundary_program(shape: BoundaryShape) -> Program {
    if let Some(message) = shape.rejection() {
        return trap_program(BOUNDARIES_OP_ID, OFFSETS_BUFFER, DataType::U32, message);
    }
    if shape.input_len() == 0 {
        return empty_program();
    }

    let table = class_table();
    let levels = lift_levels(table.range_count());
    let slots = range_slots(levels);
    let len = shape.input_len();
    let positions = shape.positions();
    let rounds = shape.rounds();

    let mut body = vec![Node::let_bind("local", Expr::LocalId { axis: 0 })];

    body.push(stage(shape, decode_body(len, positions, levels)));
    body.push(Node::barrier());

    body.push(stage(shape, chase_init_body(positions)));
    body.push(Node::barrier());

    for round in 0..rounds {
        let (source, target) = chase_pair(round);
        body.push(stage(shape, chase_round_body(positions, source, target)));
        body.push(Node::barrier());
    }

    let settled = settled_chase(rounds);
    body.push(stage(shape, next_body(len, positions, settled)));
    body.push(Node::barrier());

    for round in 0..rounds {
        let (source, target) = chain_pair(round);
        let carry = (round + 1 < rounds).then_some(target);
        body.push(stage(shape, chain_round_body(round, source, carry)));
        if round + 1 < rounds {
            body.push(Node::barrier());
        }
    }

    let chase_words = CHASE_PLANES * positions;
    Program::wrapped(
        vec![
            BufferDecl::storage(BYTES_BUFFER, 0, BufferAccess::ReadOnly, DataType::U32)
                .with_count(len + BYTE_PAD),
            BufferDecl::storage(ASCII_CLASS_BUFFER, 1, BufferAccess::ReadOnly, DataType::U32)
                .with_count(128),
            BufferDecl::storage(RANGE_CLASS_BUFFER, 2, BufferAccess::ReadOnly, DataType::U32)
                .with_count(slots * 3),
            BufferDecl::storage(UNITS_BUFFER, 3, BufferAccess::ReadWrite, DataType::U32)
                .with_count(UNIT_PLANES * positions),
            BufferDecl::storage(CHASE_A_BUFFER, 4, BufferAccess::ReadWrite, DataType::U32)
                .with_count(chase_words),
            BufferDecl::storage(CHASE_B_BUFFER, 5, BufferAccess::ReadWrite, DataType::U32)
                .with_count(chase_words),
            BufferDecl::storage(CHAIN_A_BUFFER, 6, BufferAccess::ReadWrite, DataType::U32)
                .with_count(positions),
            BufferDecl::storage(CHAIN_B_BUFFER, 7, BufferAccess::ReadWrite, DataType::U32)
                .with_count(positions),
            BufferDecl::storage(OFFSETS_BUFFER, 8, BufferAccess::ReadWrite, DataType::U32)
                .with_count(positions),
        ],
        [WORKGROUP_WIDTH, 1, 1],
        vec![wrap_anonymous(BOUNDARIES_OP_ID, body)],
    )
}

/// The empty input still dispatches, so the caller has one code path.
///
/// `segment_starts` on an empty input is `[0]`: no pretokens, and the total
/// length sentinel is zero.
fn empty_program() -> Program {
    Program::wrapped(
        vec![
            BufferDecl::storage(OFFSETS_BUFFER, 0, BufferAccess::ReadWrite, DataType::U32)
                .with_count(1),
        ],
        [1, 1, 1],
        vec![wrap_anonymous(
            BOUNDARIES_OP_ID,
            vec![Node::if_then(
                Expr::eq(Expr::gid_x(), Expr::u32(0)),
                vec![Node::store(OFFSETS_BUFFER, Expr::u32(0), Expr::u32(0))],
            )],
        )],
    )
}

/// Wrap a per-offset body in the grid-stride loop that covers every position
/// with [`WORKGROUP_WIDTH`] lanes.
fn stage(shape: BoundaryShape, body: Vec<Node>) -> Node {
    Node::loop_for(
        "chunk",
        Expr::u32(0),
        Expr::u32(shape.chunks()),
        vec![
            Node::let_bind(
                "p",
                Expr::add(
                    Expr::var("local"),
                    Expr::mul(Expr::var("chunk"), Expr::u32(WORKGROUP_WIDTH)),
                ),
            ),
            Node::if_then(
                Expr::lt(Expr::var("p"), Expr::u32(shape.positions())),
                body,
            ),
        ],
    )
}

/// Current offset of the lane running a stage body.
fn at() -> Expr {
    Expr::var("p")
}

/// Index of `plane` at `index` within a `positions`-strided plane array.
fn plane_at(positions: u32, plane: u32, index: Expr) -> Expr {
    Expr::add(Expr::u32(plane * positions), index)
}

/// Load one decoded-unit plane.
fn unit_load(positions: u32, plane: u32, index: Expr) -> Expr {
    Expr::load(UNITS_BUFFER, plane_at(positions, plane, index))
}

/// Load one successor plane.
fn chase_load(buffer: &str, positions: u32, plane: u32, index: Expr) -> Expr {
    Expr::load(buffer, plane_at(positions, plane, index))
}

/// Store one successor plane.
fn chase_store(buffer: &str, positions: u32, plane: u32, index: Expr, value: Expr) -> Node {
    Node::store(buffer, plane_at(positions, plane, index), value)
}

/// Ping-pong halves for chase round `round`.
fn chase_pair(round: u32) -> (&'static str, &'static str) {
    if round % 2 == 0 {
        (CHASE_A_BUFFER, CHASE_B_BUFFER)
    } else {
        (CHASE_B_BUFFER, CHASE_A_BUFFER)
    }
}

/// Half holding the settled planes after `rounds` chase rounds.
fn settled_chase(rounds: u32) -> &'static str {
    if rounds % 2 == 1 {
        CHASE_B_BUFFER
    } else {
        CHASE_A_BUFFER
    }
}

/// Ping-pong halves for chain round `round`.
fn chain_pair(round: u32) -> (&'static str, &'static str) {
    if round % 2 == 0 {
        (CHAIN_A_BUFFER, CHAIN_B_BUFFER)
    } else {
        (CHAIN_B_BUFFER, CHAIN_A_BUFFER)
    }
}

/// Decode the UTF-8 unit that starts at this lane's offset.
///
/// Mirrors `Cursor::unit`. The end sentinel at `len` is the one offset with a
/// zero length, and every rejected sequence resolves to the host's
/// `MALFORMED` values of length one and class zero, so the scan advances by
/// exactly one byte.
///
/// Like every stage body here this is branch free, so both arms of every
/// `select` are evaluated. See the module note on that form. The bound this
/// body owes it is `len + 3`: the lane at the end sentinel reads `byte3` of a
/// would-be four-byte sequence, which lands on the last of the [`BYTE_PAD`]
/// zero bytes. The class loads are in range for a different reason each: the
/// ASCII index is masked to seven bits, and the range table is padded to the
/// full reach of the binary lift.
fn decode_body(len: u32, positions: u32, levels: u32) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    let byte = |offset: u32| Expr::load(BYTES_BUFFER, Expr::add(at(), Expr::u32(offset)));
    let mut nodes = vec![
        Node::let_bind("lead", byte(0)),
        // Table 3-7 lead classes. `0xC0` and `0xC1`, the overlong two-byte
        // leads, and `0xF5` upward, which can only encode past `U+10FFFF`,
        // are in none of them and so decode to zero continuations.
        Node::let_bind(
            "two_byte",
            Expr::and(
                Expr::ge(var("lead"), Expr::u32(0xC2)),
                Expr::le(var("lead"), Expr::u32(0xDF)),
            ),
        ),
        Node::let_bind(
            "three_byte",
            Expr::and(
                Expr::ge(var("lead"), Expr::u32(0xE0)),
                Expr::le(var("lead"), Expr::u32(0xEF)),
            ),
        ),
        Node::let_bind(
            "four_byte",
            Expr::and(
                Expr::ge(var("lead"), Expr::u32(0xF0)),
                Expr::le(var("lead"), Expr::u32(0xF4)),
            ),
        ),
        Node::let_bind(
            "continuations",
            Expr::select(
                var("two_byte"),
                Expr::u32(1),
                Expr::select(
                    var("three_byte"),
                    Expr::u32(2),
                    Expr::select(var("four_byte"), Expr::u32(3), Expr::u32(0)),
                ),
            ),
        ),
        // The bounds on the FIRST continuation byte are what exclude
        // overlongs (0xE0, 0xF0), surrogates (0xED), and scalars past
        // `U+10FFFF` (0xF4).
        Node::let_bind(
            "low",
            Expr::select(
                Expr::eq(var("lead"), Expr::u32(0xE0)),
                Expr::u32(0xA0),
                Expr::select(
                    Expr::eq(var("lead"), Expr::u32(0xF0)),
                    Expr::u32(0x90),
                    Expr::u32(0x80),
                ),
            ),
        ),
        Node::let_bind(
            "high",
            Expr::select(
                Expr::eq(var("lead"), Expr::u32(0xED)),
                Expr::u32(0x9F),
                Expr::select(
                    Expr::eq(var("lead"), Expr::u32(0xF4)),
                    Expr::u32(0x8F),
                    Expr::u32(0xBF),
                ),
            ),
        ),
        Node::let_bind(
            "lead_mask",
            Expr::select(
                var("two_byte"),
                Expr::u32(0x1F),
                Expr::select(var("three_byte"), Expr::u32(0x0F), Expr::u32(0x07)),
            ),
        ),
        Node::let_bind("byte1", byte(1)),
        Node::let_bind("byte2", byte(2)),
        Node::let_bind("byte3", byte(3)),
        Node::let_bind(
            "decoded",
            Expr::and(
                Expr::and(
                    Expr::ne(var("continuations"), Expr::u32(0)),
                    Expr::and(
                        Expr::ge(var("byte1"), var("low")),
                        Expr::le(var("byte1"), var("high")),
                    ),
                ),
                Expr::and(
                    Expr::or(
                        Expr::lt(var("continuations"), Expr::u32(2)),
                        Expr::and(
                            Expr::ge(var("byte2"), Expr::u32(0x80)),
                            Expr::le(var("byte2"), Expr::u32(0xBF)),
                        ),
                    ),
                    Expr::or(
                        Expr::lt(var("continuations"), Expr::u32(3)),
                        Expr::and(
                            Expr::ge(var("byte3"), Expr::u32(0x80)),
                            Expr::le(var("byte3"), Expr::u32(0xBF)),
                        ),
                    ),
                ),
            ),
        ),
        Node::let_bind(
            "scalar1",
            Expr::bitor(
                Expr::shl(Expr::bitand(var("lead"), var("lead_mask")), Expr::u32(6)),
                Expr::bitand(var("byte1"), Expr::u32(0x3F)),
            ),
        ),
        Node::let_bind(
            "scalar2",
            Expr::select(
                Expr::ge(var("continuations"), Expr::u32(2)),
                Expr::bitor(
                    Expr::shl(var("scalar1"), Expr::u32(6)),
                    Expr::bitand(var("byte2"), Expr::u32(0x3F)),
                ),
                var("scalar1"),
            ),
        ),
        Node::let_bind(
            "scalar",
            Expr::select(
                Expr::ge(var("continuations"), Expr::u32(3)),
                Expr::bitor(
                    Expr::shl(var("scalar2"), Expr::u32(6)),
                    Expr::bitand(var("byte3"), Expr::u32(0x3F)),
                ),
                var("scalar2"),
            ),
        ),
    ];
    nodes.extend(range_bits(levels));
    // The ASCII table holds 128 entries and a lead byte names 256 values, so
    // the index is masked rather than guarded. Masking is harmless: the
    // `select` below keeps this load only when the lead really is ASCII.
    nodes.push(Node::let_bind(
        "ascii_bits",
        Expr::load(
            ASCII_CLASS_BUFFER,
            Expr::bitand(var("lead"), Expr::u32(0x7F)),
        ),
    ));
    nodes.push(Node::let_bind(
        "is_ascii",
        Expr::lt(var("lead"), Expr::u32(0x80)),
    ));
    nodes.push(Node::let_bind("at_end", Expr::eq(at(), Expr::u32(len))));
    nodes.push(Node::store(
        UNITS_BUFFER,
        plane_at(positions, UNIT_LEN, at()),
        Expr::select(
            var("at_end"),
            Expr::u32(0),
            Expr::select(
                var("is_ascii"),
                Expr::u32(1),
                Expr::select(
                    var("decoded"),
                    Expr::add(var("continuations"), Expr::u32(1)),
                    Expr::u32(1),
                ),
            ),
        ),
    ));
    nodes.push(Node::store(
        UNITS_BUFFER,
        plane_at(positions, UNIT_CLASS, at()),
        Expr::select(
            var("at_end"),
            Expr::u32(0),
            Expr::select(
                var("is_ascii"),
                var("ascii_bits"),
                Expr::select(var("decoded"), var("range_bits"), Expr::u32(0)),
            ),
        ),
    ));
    nodes
}

/// Bind `range_bits` to the class of `scalar` from the padded range table.
///
/// A binary lift walks to the largest slot whose low bound is at or below the
/// scalar, then the class survives only if the scalar also fits under that
/// slot's high bound. The table is padded to `2^levels - 1` slots with an
/// unreachable low bound of `u32::MAX`, which keeps the low column
/// non-decreasing and every probe in bounds, so the lift needs no guard.
fn range_bits(levels: u32) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    let mut nodes = vec![Node::let_bind("slot0", Expr::u32(0))];
    let mut settled = "slot0".to_owned();
    for (step, level) in (0..levels).rev().enumerate() {
        let probed = format!("slot{}", step + 1);
        let probe = Expr::add(var(&settled), Expr::u32(1u32 << level));
        nodes.push(Node::let_bind(
            probed.clone(),
            Expr::select(
                Expr::le(
                    Expr::load(
                        RANGE_CLASS_BUFFER,
                        Expr::mul(Expr::sub(probe.clone(), Expr::u32(1)), Expr::u32(3)),
                    ),
                    var("scalar"),
                ),
                probe,
                var(&settled),
            ),
        ));
        settled = probed;
    }
    // Slot zero means the scalar sits below every range. Clamping keeps the
    // base index in bounds; the `ne` test below is what discards the load.
    nodes.push(Node::let_bind(
        "range_base",
        Expr::mul(
            Expr::sub(Expr::max(var(&settled), Expr::u32(1)), Expr::u32(1)),
            Expr::u32(3),
        ),
    ));
    nodes.push(Node::let_bind(
        "range_bits",
        Expr::select(
            Expr::and(
                Expr::ne(var(&settled), Expr::u32(0)),
                Expr::le(
                    var("scalar"),
                    Expr::load(
                        RANGE_CLASS_BUFFER,
                        Expr::add(var("range_base"), Expr::u32(1)),
                    ),
                ),
            ),
            Expr::load(
                RANGE_CLASS_BUFFER,
                Expr::add(var("range_base"), Expr::u32(2)),
            ),
            Expr::u32(0),
        ),
    ));
    nodes
}

/// Seed every successor plane with a single step.
fn chase_init_body(positions: u32) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    // Comparison builders yield `bool`, not a zero-or-one `u32`, so a bound
    // predicate stays a `bool` and is used directly. Testing it against
    // `Expr::u32(0)` is a type error the driver rejects at dispatch.
    let mut nodes = vec![
        Node::let_bind("ulen", unit_load(positions, UNIT_LEN, at())),
        Node::let_bind("cls", unit_load(positions, UNIT_CLASS, at())),
        Node::let_bind("live", Expr::ne(var("ulen"), Expr::u32(0))),
        Node::let_bind("step", Expr::add(at(), var("ulen"))),
        Node::let_bind(
            "is_space",
            Expr::and(
                var("live"),
                Expr::ne(
                    Expr::bitand(var("cls"), Expr::u32(CLASS_SPACE)),
                    Expr::u32(0),
                ),
            ),
        ),
        Node::let_bind("next_len", unit_load(positions, UNIT_LEN, var("step"))),
        Node::let_bind("next_cls", unit_load(positions, UNIT_CLASS, var("step"))),
        Node::let_bind(
            "next_space",
            Expr::and(
                Expr::ne(var("next_len"), Expr::u32(0)),
                Expr::ne(
                    Expr::bitand(var("next_cls"), Expr::u32(CLASS_SPACE)),
                    Expr::u32(0),
                ),
            ),
        ),
        Node::let_bind("byte", Expr::load(BYTES_BUFFER, at())),
        Node::let_bind(
            "is_break",
            Expr::or(
                Expr::eq(var("byte"), Expr::u32(CR)),
                Expr::eq(var("byte"), Expr::u32(LF)),
            ),
        ),
    ];

    // `run_end(p, L)`.
    nodes.push(seed_plane(
        positions,
        PLANE_LETTER,
        Expr::and(
            var("live"),
            Expr::ne(
                Expr::bitand(var("cls"), Expr::u32(CLASS_LETTER)),
                Expr::u32(0),
            ),
        ),
        var("step"),
    ));
    // `other_run_end(p)`, which accepts a malformed byte because its class is
    // zero and therefore avoids every bit of `WS | L | N`.
    nodes.push(seed_plane(
        positions,
        PLANE_OTHER,
        Expr::and(
            var("live"),
            Expr::eq(
                Expr::bitand(var("cls"), Expr::u32(CLASS_ANY)),
                Expr::u32(0),
            ),
        ),
        var("step"),
    ));
    // `run_end(p, WS)`.
    nodes.push(seed_plane(
        positions,
        PLANE_SPACE,
        var("is_space"),
        var("step"),
    ));
    // Last whitespace unit of the run: advance only while the NEXT unit is
    // also whitespace, so the fixed point is the final unit's start.
    nodes.push(seed_plane(
        positions,
        PLANE_LAST_SPACE,
        Expr::and(var("is_space"), var("next_space")),
        var("step"),
    ));
    // `byte_run_end(p, b"\r\n")`, a literal byte run rather than a unit run.
    nodes.push(seed_plane(
        positions,
        PLANE_BREAK,
        var("is_break"),
        Expr::add(at(), Expr::u32(1)),
    ));
    // Last line break inside the whitespace run. Zero is the "no break seen"
    // marker, which is unambiguous because a real answer is one PAST a break
    // and therefore at least one.
    nodes.push(chase_store(
        CHASE_A_BUFFER,
        positions,
        PLANE_LAST_BREAK,
        at(),
        Expr::select(
            Expr::and(var("is_space"), var("is_break")),
            Expr::add(at(), Expr::u32(1)),
            Expr::u32(0),
        ),
    ));
    nodes
}

/// Seed one plane with `target` where `taken` holds and a self-loop otherwise.
fn seed_plane(positions: u32, plane: u32, taken: Expr, target: Expr) -> Node {
    chase_store(
        CHASE_A_BUFFER,
        positions,
        plane,
        at(),
        Expr::select(taken, target, at()),
    )
}

/// One doubling round over every successor plane.
fn chase_round_body(positions: u32, source: &str, target: &str) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    let mut nodes = Vec::new();
    for plane in [
        PLANE_LETTER,
        PLANE_OTHER,
        PLANE_SPACE,
        PLANE_LAST_SPACE,
        PLANE_BREAK,
    ] {
        nodes.push(chase_store(
            target,
            positions,
            plane,
            at(),
            chase_load(
                source,
                positions,
                plane,
                chase_load(source, positions, plane, at()),
            ),
        ));
    }
    // The last-break plane is not a pure composition: it doubles alongside the
    // whitespace plane and keeps the RIGHTMOST break of the two halves, which
    // is what `ws_through_last_break` returns.
    nodes.push(Node::let_bind(
        "half",
        chase_load(source, positions, PLANE_SPACE, at()),
    ));
    nodes.push(Node::let_bind(
        "far",
        chase_load(source, positions, PLANE_LAST_BREAK, var("half")),
    ));
    nodes.push(chase_store(
        target,
        positions,
        PLANE_LAST_BREAK,
        at(),
        Expr::select(
            Expr::ne(var("far"), Expr::u32(0)),
            var("far"),
            chase_load(source, positions, PLANE_LAST_BREAK, at()),
        ),
    ));
    nodes
}

/// Evaluate `cl100k_end` at this lane's offset.
///
/// Every alternative is computed into its own candidate, with zero meaning "no
/// match", and the candidates are then folded right to left so the FIRST
/// nonzero one wins. That reproduces the pattern's leftmost-alternative
/// semantics without a branch. Zero is an unambiguous miss marker because
/// every real end offset here is at least one: a match always consumes at
/// least one byte at or after this offset.
fn next_body(len: u32, positions: u32, chase: &str) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    let after = || Expr::add(at(), Expr::u32(1));
    let mut nodes = vec![
        Node::let_bind("ulen", unit_load(positions, UNIT_LEN, at())),
        Node::let_bind("cls", unit_load(positions, UNIT_CLASS, at())),
        Node::let_bind("lead", Expr::load(BYTES_BUFFER, at())),
    ];

    // `'(?i:[sdmt]|ll|ve|re)`. At most one single letter can match, since a
    // byte folds to exactly one lowercase letter, so the four combine with
    // `max` rather than with a priority chain. The same holds for the pairs.
    for letter in [b's', b'd', b'm', b't'] {
        nodes.push(Node::let_bind(
            format!("solo_{}", letter as char),
            folded_letter(after(), letter),
        ));
    }
    nodes.push(Node::let_bind(
        "solo",
        Expr::max(
            Expr::max(var("solo_s"), var("solo_d")),
            Expr::max(var("solo_m"), var("solo_t")),
        ),
    ));
    for [first, second] in [[b'l', b'l'], [b'v', b'e'], [b'r', b'e']] {
        let head = format!("head_{}{}", first as char, second as char);
        let tail = format!("tail_{}{}", first as char, second as char);
        let pair = format!("pair_{}{}", first as char, second as char);
        nodes.push(Node::let_bind(head.clone(), folded_letter(after(), first)));
        nodes.push(Node::let_bind(
            tail.clone(),
            folded_letter(Expr::add(after(), var(&head)), second),
        ));
        nodes.push(Node::let_bind(
            pair,
            Expr::select(
                Expr::and(
                    Expr::ne(var(&head), Expr::u32(0)),
                    Expr::ne(var(&tail), Expr::u32(0)),
                ),
                Expr::add(Expr::add(after(), var(&head)), var(&tail)),
                Expr::u32(0),
            ),
        ));
    }
    nodes.push(Node::let_bind(
        "solo_end",
        Expr::select(
            Expr::ne(var("solo"), Expr::u32(0)),
            Expr::add(after(), var("solo")),
            Expr::u32(0),
        ),
    ));
    nodes.push(Node::let_bind(
        "pairs_end",
        Expr::max(var("pair_ll"), Expr::max(var("pair_ve"), var("pair_re"))),
    ));
    nodes.push(Node::let_bind(
        "alt_contraction",
        Expr::select(
            Expr::eq(var("lead"), Expr::u32(APOSTROPHE)),
            Expr::select(
                Expr::ne(var("solo_end"), Expr::u32(0)),
                var("solo_end"),
                var("pairs_end"),
            ),
            Expr::u32(0),
        ),
    ));

    // `[^\r\n\p{L}\p{N}]?+\p{L}++`. The optional lead is possessive and could
    // not have helped anyway: a unit its class accepts is never `\p{L}`.
    nodes.push(Node::let_bind(
        "lead_ok",
        Expr::and(
            Expr::and(
                Expr::ne(var("ulen"), Expr::u32(0)),
                Expr::eq(
                    Expr::bitand(var("cls"), Expr::u32(CLASS_LETTER | CLASS_NUMBER)),
                    Expr::u32(0),
                ),
            ),
            Expr::and(
                Expr::ne(var("lead"), Expr::u32(CR)),
                Expr::ne(var("lead"), Expr::u32(LF)),
            ),
        ),
    ));
    nodes.push(Node::let_bind(
        "word_start",
        Expr::select(var("lead_ok"), Expr::add(at(), var("ulen")), at()),
    ));
    nodes.push(Node::let_bind(
        "word_end",
        chase_load(chase, positions, PLANE_LETTER, var("word_start")),
    ));
    nodes.push(Node::let_bind(
        "alt_word",
        Expr::select(
            Expr::ne(var("word_end"), var("word_start")),
            var("word_end"),
            Expr::u32(0),
        ),
    ));

    // `\p{N}{1,3}+`, unrolled because the bound is three. Each step's success
    // implies the previous one's, so the walk stalls in place after a miss.
    nodes.push(Node::let_bind("digit_at0", at()));
    for step in 0..3u32 {
        let position = format!("digit_at{step}");
        let advanced = format!("digit_at{}", step + 1);
        let length = format!("digit_len{step}");
        let taken = format!("digit_ok{step}");
        nodes.push(Node::let_bind(
            length.clone(),
            unit_load(positions, UNIT_LEN, var(&position)),
        ));
        let here = Expr::and(
            Expr::ne(var(&length), Expr::u32(0)),
            Expr::ne(
                Expr::bitand(
                    unit_load(positions, UNIT_CLASS, var(&position)),
                    Expr::u32(CLASS_NUMBER),
                ),
                Expr::u32(0),
            ),
        );
        nodes.push(Node::let_bind(
            taken.clone(),
            if step == 0 {
                here
            } else {
                Expr::and(var(&format!("digit_ok{}", step - 1)), here)
            },
        ));
        nodes.push(Node::let_bind(
            advanced,
            Expr::select(
                var(&taken),
                Expr::add(var(&position), var(&length)),
                var(&position),
            ),
        ));
    }
    nodes.push(Node::let_bind(
        "alt_digits",
        Expr::select(var("digit_ok0"), var("digit_at3"), Expr::u32(0)),
    ));

    // ` ?[^\s\p{L}\p{N}]++[\r\n]*+`. The optional space never needs to be
    // given back: it is whitespace, and the run class excludes whitespace.
    nodes.push(Node::let_bind(
        "punct_start",
        Expr::select(Expr::eq(var("lead"), Expr::u32(SPACE)), after(), at()),
    ));
    nodes.push(Node::let_bind(
        "punct_end",
        chase_load(chase, positions, PLANE_OTHER, var("punct_start")),
    ));
    nodes.push(Node::let_bind(
        "alt_punct",
        Expr::select(
            Expr::ne(var("punct_end"), var("punct_start")),
            chase_load(chase, positions, PLANE_BREAK, var("punct_end")),
            Expr::u32(0),
        ),
    ));

    // `\s++$`.
    nodes.push(Node::let_bind(
        "space_end",
        chase_load(chase, positions, PLANE_SPACE, at()),
    ));
    nodes.push(Node::let_bind(
        "alt_space_to_end",
        Expr::select(
            Expr::and(
                Expr::ne(var("space_end"), at()),
                Expr::eq(var("space_end"), Expr::u32(len)),
            ),
            var("space_end"),
            Expr::u32(0),
        ),
    ));

    // `\s*[\r\n]`. The plane already stores zero when the run holds no break.
    nodes.push(Node::let_bind(
        "alt_last_break",
        chase_load(chase, positions, PLANE_LAST_BREAK, at()),
    ));

    // `\s+(?!\S)`. Reaching this candidate means `\s++$` did not take the run,
    // so the run does not end the input, so it gives back exactly one unit and
    // the match ends at the last whitespace unit's start.
    nodes.push(Node::let_bind(
        "last_space",
        chase_load(chase, positions, PLANE_LAST_SPACE, at()),
    ));
    nodes.push(Node::let_bind(
        "alt_space_before",
        Expr::select(
            Expr::and(
                Expr::ne(var("space_end"), at()),
                Expr::ne(var("last_space"), at()),
            ),
            var("last_space"),
            Expr::u32(0),
        ),
    ));

    // `\s`. The `max` keeps the scan monotone by construction.
    nodes.push(Node::let_bind(
        "alt_one_unit",
        Expr::add(at(), Expr::max(var("ulen"), Expr::u32(1))),
    ));

    let pick = |candidate: &str, rest: Expr| {
        Expr::select(
            Expr::ne(Expr::var(candidate), Expr::u32(0)),
            Expr::var(candidate),
            rest,
        )
    };
    let matched = pick(
        "alt_contraction",
        pick(
            "alt_word",
            pick(
                "alt_digits",
                pick(
                    "alt_punct",
                    pick(
                        "alt_space_to_end",
                        pick(
                            "alt_last_break",
                            pick("alt_space_before", var("alt_one_unit")),
                        ),
                    ),
                ),
            ),
        ),
    );
    nodes.push(Node::let_bind(
        "end",
        // The end of input is the chain's fixed point.
        Expr::select(Expr::eq(at(), Expr::u32(len)), Expr::u32(len), matched),
    ));
    nodes.push(Node::store(CHAIN_A_BUFFER, at(), var("end")));
    nodes.push(Node::store(OFFSETS_BUFFER, at(), Expr::u32(0)));
    nodes
}

/// Bytes a case-folded ASCII `letter` matches at `index`, or zero for no match.
///
/// `letter` is always ASCII lowercase, so `byte | 0x20 == letter` accepts the
/// exact byte and its uppercase pair and nothing else. `U+017F` is the only
/// non-ASCII codepoint in any fold class these contractions reach, and it
/// folds to `s`.
fn folded_letter(index: Expr, letter: u8) -> Expr {
    let matched = Expr::eq(
        Expr::bitor(Expr::load(BYTES_BUFFER, index.clone()), Expr::u32(SPACE)),
        Expr::u32(u32::from(letter)),
    );
    if letter == b's' {
        Expr::select(
            matched,
            Expr::u32(1),
            Expr::select(
                Expr::and(
                    Expr::eq(Expr::load(BYTES_BUFFER, index.clone()), Expr::u32(0xC5)),
                    Expr::eq(
                        Expr::load(BYTES_BUFFER, Expr::add(index, Expr::u32(1))),
                        Expr::u32(0xBF),
                    ),
                ),
                Expr::u32(2),
                Expr::u32(0),
            ),
        )
    } else {
        Expr::select(matched, Expr::u32(1), Expr::u32(0))
    }
}

/// One chain round: advance the running offset by `2^round` pretokens when bit
/// `round` of this lane's index is set, then square the successor function.
///
/// This is a gather, never a scatter. Lane `p` writes only `offsets[p]` and
/// `carry[p]`, so no two lanes contend and no atomics are needed.
fn chain_round_body(round: u32, source: &str, carry: Option<&str>) -> Vec<Node> {
    let var = |name: &str| Expr::var(name);
    let mut nodes = vec![
        Node::let_bind("cursor", Expr::load(OFFSETS_BUFFER, at())),
        Node::store(
            OFFSETS_BUFFER,
            at(),
            Expr::select(
                Expr::ne(Expr::bitand(at(), Expr::u32(1u32 << round)), Expr::u32(0)),
                Expr::load(source, var("cursor")),
                var("cursor"),
            ),
        ),
    ];
    if let Some(target) = carry {
        nodes.push(Node::store(
            target,
            at(),
            Expr::load(source, Expr::load(source, at())),
        ));
    }
    nodes
}

/// Does the caller have to supply bytes for this buffer?
///
/// Mirrors `vyre_reference::is_reference_input`. That helper lives in a
/// dev-dependency, so the shipping runner cannot call it; the parity test
/// asserts the two predicates agree on this program's whole buffer table so a
/// drift in the driver ABI fails loudly instead of shifting every binding.
fn supplies_input(decl: &BufferDecl) -> bool {
    decl.access() != BufferAccess::Workgroup && !decl.is_backend_allocated_output()
}

/// Does the backend return this buffer?
///
/// Mirrors `vyre_reference::is_reference_output`, pinned by the same test.
fn returns_output(decl: &BufferDecl) -> bool {
    decl.is_backend_allocated_output() || decl.access() == BufferAccess::ReadWrite
}

/// Position of `name` in the returned output vector.
fn output_slot(program: &Program, name: &str) -> Option<usize> {
    program
        .buffers()
        .iter()
        .filter(|decl| returns_output(decl))
        .position(|decl| decl.name() == name)
}

/// Build the input vector for `program` over `input`.
fn seed_inputs(program: &Program, input: &[u8]) -> Vec<Vec<u8>> {
    let table = class_table();
    program
        .buffers()
        .iter()
        .filter(|decl| supplies_input(decl))
        .map(|decl| {
            let count = decl.count() as usize;
            let mut words = vec![0u32; count];
            match decl.name() {
                BYTES_BUFFER => {
                    for (slot, byte) in words.iter_mut().zip(input) {
                        *slot = u32::from(*byte);
                    }
                }
                ASCII_CLASS_BUFFER => {
                    for (slot, bits) in words.iter_mut().zip(table.ascii()) {
                        *slot = *bits;
                    }
                }
                RANGE_CLASS_BUFFER => {
                    // Pad slots must never win the binary lift, so their low
                    // bound sits above every scalar.
                    for triple in words.chunks_exact_mut(3) {
                        if let Some(low) = triple.first_mut() {
                            *low = u32::MAX;
                        }
                    }
                    for (slot, value) in words.iter_mut().zip(table.ranges()) {
                        *slot = *value;
                    }
                }
                _ => {}
            }
            pack_u32_slice(&words)
        })
        .collect()
}

/// Run the boundary pass on `backend` and return the pretoken start offsets
/// followed by the total length, matching
/// [`crate::pretokenize::segment_starts`] exactly.
///
/// # Errors
/// Returns [`ExatokError::Backend`] when the input exceeds
/// [`MAX_INPUT_BYTES`], when the dispatch fails, or when the returned buffers
/// do not carry the offsets the builder declared.
pub fn run_boundaries(backend: &dyn VyreBackend, input: &[u8]) -> Result<Vec<u32>, ExatokError> {
    let len = u32::try_from(input.len())
        .ok()
        .filter(|len| *len <= MAX_INPUT_BYTES)
        .ok_or_else(|| {
            ExatokError::Backend(format!(
                "gpu_pretokenize input is {} bytes, past the {MAX_INPUT_BYTES} byte ceiling. \
                 Fix: split the text ON A PRETOKEN BOUNDARY, dispatch each piece, and rebase \
                 each piece's offsets by adding its start. Cutting at a fixed offset instead \
                 invents a boundary at the cut, because the end-of-input alternatives fire \
                 there.",
                input.len()
            ))
        })?;
    let shape = BoundaryShape::new(len);
    let program = boundary_program(shape);
    let inputs = seed_inputs(&program, input);

    let workgroup = program.workgroup_size();
    let lanes = workgroup[0].max(1) * workgroup[1].max(1) * workgroup[2].max(1);
    let mut config = DispatchConfig::default();
    // The whole pass lives in one workgroup, so the grid is stated rather than
    // inferred: inference picks the widest binding, which here is a chase
    // buffer six times the input and would launch six blocks that all rerun
    // the same grid-stride loop over the same offsets.
    config.dispatch_elements = Some(lanes);
    config.grid_override = Some([1, 1, 1]);
    config.workgroup_override = Some(workgroup);
    config.label = Some(BOUNDARIES_OP_ID.to_owned());

    let outputs = backend
        .dispatch(&program, &inputs, &config)
        .map_err(|error| {
            ExatokError::Backend(format!("gpu_pretokenize dispatch failed: {error}"))
        })?;

    let slot = output_slot(&program, OFFSETS_BUFFER).ok_or_else(|| {
        ExatokError::Backend(format!(
            "gpu_pretokenize program declares no returned `{OFFSETS_BUFFER}` buffer. \
             Fix: keep it ReadWrite so the backend hands it back."
        ))
    })?;
    let bytes = outputs.get(slot).ok_or_else(|| {
        ExatokError::Backend(format!(
            "gpu_pretokenize dispatch returned {} buffer(s), needs slot {slot} for \
             `{OFFSETS_BUFFER}`. Fix: check the backend honours ReadWrite readback.",
            outputs.len()
        ))
    })?;

    let mut offsets = Vec::new();
    unpack_u32_slice_into(
        bytes,
        shape.positions() as usize,
        OFFSETS_BUFFER,
        &mut offsets,
    )
    .map_err(ExatokError::Backend)?;

    let end = offsets.iter().position(|offset| *offset == len).ok_or_else(|| {
        ExatokError::Backend(format!(
            "gpu_pretokenize produced no {len}-byte terminator in {} offsets. Fix: the chain \
             stage did not converge, check the doubling round count.",
            offsets.len()
        ))
    })?;
    offsets.truncate(end + 1);
    Ok(offsets)
}

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

    /// Locks the oracle-probing class derivation against the host splitter's
    /// own classification, one scalar at a time rather than in aggregate.
    ///
    /// If this regresses, the device table disagrees with `Cursor::unit` on
    /// some codepoint and the GPU splits that codepoint into a different
    /// pretoken than tiktoken does, which changes token ids silently.
    #[test]
    fn derived_classes_match_host_splits() {
        for scalar in [
            u32::from(b'a'),
            u32::from(b'Z'),
            u32::from(b'7'),
            u32::from(b' '),
            u32::from(b'\n'),
            u32::from(b'\r'),
            u32::from(b'\''),
            u32::from(b'.'),
            0x00A0, // NBSP, whitespace but not ASCII.
            0x00B2, // Superscript two, \p{No}.
            0x017F, // Long s, the only non-ASCII fold target.
            0x0301, // Combining acute, \p{M}: neither letter nor number nor space.
            0x2028, // Line separator.
            0x3042, // Hiragana A.
            0x4E2D, // CJK ideograph.
            0x1F600, // Grinning face, four UTF-8 bytes.
            0x1D7CE, // Mathematical bold digit zero, \p{Nd} outside the BMP.
        ] {
            assert_eq!(
                class_table().class_of(scalar),
                derive_class(scalar),
                "class table disagrees with the probe at U+{scalar:04X}"
            );
        }

        assert_eq!(class_table().class_of(u32::from(b'a')), CLASS_LETTER);
        assert_eq!(class_table().class_of(u32::from(b'7')), CLASS_NUMBER);
        assert_eq!(class_table().class_of(u32::from(b' ')), CLASS_SPACE);
        assert_eq!(class_table().class_of(u32::from(b'\'')), 0);
        assert_eq!(class_table().class_of(0x00A0), CLASS_SPACE);
        assert_eq!(class_table().class_of(0x0301), 0);
        assert_eq!(class_table().class_of(0x1F600), 0);
        assert_eq!(class_table().class_of(0x1D7CE), CLASS_NUMBER);
        assert_eq!(class_table().class_of(0x4E2D), CLASS_LETTER);
    }

    /// Locks the range table's shape: ascending, disjoint, non-empty classes
    /// only, and no ASCII entries.
    ///
    /// If this regresses the device binary lift, which requires a sorted low
    /// column, silently returns the wrong class for scalars near the break.
    #[test]
    fn range_table_is_sorted_and_disjoint() {
        let table = class_table();
        let triples = table.ranges().chunks_exact(3);
        assert_eq!(triples.len(), table.range_count() as usize);
        let mut previous_end = 0x7Fu32;
        for triple in triples {
            let (low, high, bits) = (triple[0], triple[1], triple[2]);
            assert!(low > previous_end, "range {low:#X} overlaps {previous_end:#X}");
            assert!(low <= high, "range {low:#X}..{high:#X} is inverted");
            assert_ne!(bits, 0, "range {low:#X}..{high:#X} stores an empty class");
            assert!(bits <= CLASS_ANY, "range {low:#X}..{high:#X} has unknown bits");
            previous_end = high;
        }
        assert!(previous_end <= 0x0010_FFFF);
    }

    /// Locks the doubling round count against the reach it has to cover.
    ///
    /// One round short and a long whitespace run or a long text stops
    /// resolving partway, which shows up as a missing terminator or a
    /// truncated offset vector rather than as a wrong split.
    #[test]
    fn rounds_cover_every_position() {
        for len in [0u32, 1, 2, 3, 255, 256, 257, 1023, 1024, 65_535] {
            let shape = BoundaryShape::new(len);
            let reach = 1u64 << shape.rounds();
            assert!(
                reach >= u64::from(shape.positions()),
                "{} rounds reach {reach}, short of {} positions",
                shape.rounds(),
                shape.positions()
            );
            assert!(
                (1u64 << (shape.rounds() - 1)) < u64::from(shape.positions()).max(2),
                "{} rounds is one more than needed for {len} bytes",
                shape.rounds()
            );
        }
    }

    /// Locks the range buffer padding: every slot the binary lift can probe
    /// must exist, or the device reads past the buffer.
    ///
    /// If this regresses the lift addresses `3 * (2^levels - 2)`, which lands
    /// outside a table sized to the real range count, and CUDA returns
    /// whatever follows in the allocation.
    #[test]
    fn lift_never_probes_past_the_padded_table() {
        for count in [1u32, 2, 3, 7, 8, 9, 1000, 2358] {
            let levels = lift_levels(count);
            let slots = range_slots(levels);
            assert!(slots >= count, "{levels} levels give {slots} slots for {count} ranges");
            let mut highest = 0u32;
            for level in (0..levels).rev() {
                highest += 1u32 << level;
            }
            assert_eq!(highest, slots, "the lift can reach slot {highest} of {slots}");
        }
    }

    /// Locks the over-length rejection onto the trap path rather than a panic
    /// or a silently truncated dispatch.
    ///
    /// If this regresses, an oversized shape builds a program whose chase
    /// buffers overflow `u32` word counts.
    #[test]
    fn oversized_shape_lowers_to_a_trap() {
        let program = boundary_program(BoundaryShape::new(MAX_INPUT_BYTES + 1));
        assert!(
            program.buffers().iter().any(|decl| decl.name() == OFFSETS_BUFFER),
            "the trap must still declare the offsets buffer so callers bind the same slot"
        );
        assert!(
            output_slot(&program, OFFSETS_BUFFER).is_some(),
            "the trap's offsets buffer must be readable back"
        );
    }
}