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
//! Multi-merge confluence experiment. OWNER: Confluence.
//!
//! # Question
//!
//! Prior GPU BPE work treats a tradeoff as fundamental. GPUTOK fuses exactly
//! one pair per pass to stay exact, paying O(merges) barrier-synchronized
//! passes. BlockBPE fuses multiple local minima across DIFFERENT ranks in one
//! pass and loses exactness. The hypothesis tested here: restricting a pass to
//! a SINGLE rank level recovers exactness. Let `r` be the global minimum rank
//! present. One pass fuses the maximal LEFT-BIASED NON-OVERLAPPING set of
//! rank-`r` occurrences: scan left to right, take an occurrence, skip any
//! occurrence sharing a token index with it.
//!
//! # Verdict
//!
//! REFUTED as stated, including on initial states. Confirmed for the real
//! `cl100k_base` vocabulary only, empirically, and for a reason that does not
//! generalize to vocabularies in general. Three findings, and conflating them
//! is how BlockBPE shipped an approximation.
//!
//! ## 1. Refuted, and the counterexample is an INITIAL state
//!
//! Minimal at one base symbol, four tokens, two entries. Note the input is four
//! copies of base symbol 0, so this is not an exotic intermediate state: it is
//! what raw input looks like.
//!
//! ```text
//! table  (0,0) -> 1 @rank 1     (1,0) -> 2 @rank 0
//! input  [0, 0, 0, 0]
//!   sequential  -> [2, 0]        multi-merge -> [1, 1]
//! ```
//!
//! Fusing index 0 exposes `(1,0)` at rank 0, BELOW the rank-1 level multi-merge
//! already committed to, so sequential takes it and consumes the token the
//! second rank-1 occurrence needed. Length 3 cannot diverge, and no entry can be
//! dropped, so this is minimal. Restricting to initial states therefore does NOT
//! rescue the hypothesis.
//!
//! ## 2. Real `cl100k_base` diverges too, but only on unreachable states
//!
//! 1917 four-token real states diverge. Smallest, ids exactly as shipped:
//!
//! ```text
//! state ['e', 'nc', 'e', 'nc'] = [68, 1031, 68, 1031]
//!   sequential -> [768, 1031]      multi-merge -> [967, 967]
//! ```
//!
//! It turns on a real rank inversion: `'enc'` ranks 967 while `'ence'` ranks
//! 768. None of these states is reachable. Feeding the bytes of all 130 distinct
//! divergent real states back in as single bytes gives agreement on all 130;
//! `"encenc"` yields `[967, 967]` on BOTH paths, because `'en'` ranks 268, below
//! `'nc'` at 1031, so the greedy rule never assembles the dangerous state.
//!
//! The danger hunt was EXHAUSTIVE over the real table, not sampled, so a future
//! reader does not need to redo it. Method: enumerate every `(a, b) -> X @r` in
//! `cl100k_base`, and for every token `c` in the vocabulary test both `(X, c)`
//! and `(c, X)` for a rank below `r`. That is the complete set of local shapes
//! that can lower the minimum rank, since a fusion rewrites only two adjacent
//! positions and can therefore only create the pairs `(prev, X)` and `(X, next)`.
//! Result: 560 danger triples, of which 304 actually diverge when the
//! corresponding four-token state `[a, b, a, b]` is fed in as an arbitrary state,
//! and 0 reachable from raw bytes. Reachability was then checked by re-encoding
//! the bytes of every one of the 130 distinct divergent states from single bytes.
//!
//! ## 3. What actually protects real vocabularies: id order, not reachability
//!
//! Controlled experiment, vocabulary structure held fixed, only id assignment
//! changed (`IdOrder`), swept over initial states only:
//!
//! ```text
//! ids by uniform random permutation : 354276 initial states x 12 vocabs -> 18530 divergences
//! ids by ascending token length     : 354276 initial states x 12 vocabs ->     0 divergences
//! ```
//!
//! So the saving property is that real ids correlate with token length, because
//! `id == rank` and ids follow training frequency while shorter pieces are more
//! frequent. That forces the greedy rule to build bottom-up, and the dangerous
//! configuration is never assembled. Concretely: the danger state for 2-space
//! and 3-space tokens is `[256, 262, 256, 262]`, which needs 3-space tokens to
//! exist while 2-space pairs sit unfused, but rank 256 is below rank 262, so
//! from raw spaces every 1-space pair fuses first.
//!
//! This is a STATISTICAL property, not a checkable invariant. Injecting random
//! id swaps into a length-ordered vocabulary breaks exactness well below real
//! cl100k's own inversion rate:
//!
//! ```text
//! swapped  parent-order violations  divergences
//!    0%            0.0%                    0
//!    2%            0.6%                    0
//!    5%            5.1%                   19
//!   20%           20.1%                  327
//!  100%           48.1%                 2164
//! ```
//!
//! Real cl100k sits at 24.0% parent-order violations (56048 of 233378; the
//! operand-side count documented on `parent_ordered_table` is 18.7%, a different
//! definition, see the provenance note) and is nonetheless clean over ~1.76M
//! reachable states, so the inversion RATE does not decide it either: real
//! inversions are structured, random ones are not. No cheap structural check
//! certifies a vocabulary. A new vocabulary needs its own sweep, and even a
//! clean sweep is not a proof.
//!
//! Nor would it be enough to forbid rank INVERSIONS and allow equality. A tie
//! between a pair and its own parent is fatal on its own, and the strict
//! inequality in parent order below is load bearing:
//!
//! ```text
//! table  (0,0) -> 2 @rank 0     (2,0) -> 3 @rank 0      both at the SAME rank
//! input  [0, 0, 0, 0]
//!   sequential  -> [3, 0]        multi-merge -> [2, 2]
//! ```
//!
//! Ties are also where the harmless cases live, which is why this module reports
//! two separate counts. Over 8190 binary initial states, tying a parent across
//! two DISTINCT symbols gives 10697 pass-shape differences and 0 exactness
//! failures, while tying on a REPEATED symbol gives 11568 differences of which
//! 5710 are exactness failures. Collapsing those counts into one would make a
//! future sweep pass or fail for the wrong reason.
//!
//! # Why there is no theorem for the real case
//!
//! Exactness on ARBITRARY states holds exactly when, for every entry
//! `(a, b) -> X` at rank `r`, every token `c` satisfies both `rank(X, c) > r`
//! and `rank(c, X) > r`. Call that parent order. It is necessary (finding 1
//! violates it) and sufficient:
//!
//! Proof sketch, resting on LOCALITY, not on ranks rising. Fusing at index `i`
//! rewrites only indices `i` and `i + 1`, so every pair at position `<= i - 2`
//! or `>= i + 2` is untouched: a fusion can neither create nor destroy a
//! rank-`r` pair outside `[i - 1, i + 2]`. Let the left-biased set be
//! `i_1 < i_2 < ...` with `i_{t+1} >= i_t + 2`. Sequential fuses `i_1` first,
//! being the leftmost minimum. That destroys only the occurrence at `i_1 + 1`,
//! which the left-biased rule already skipped, and by parent order the two pairs
//! it creates, `(prev, X)` and `(X, next)`, both rank above `r`, so no new
//! minimum undercuts `r` and no new rank-`r` occurrence appears. Hence the
//! leftmost surviving rank-`r` occurrence is the least `j >= i_1 + 2`, which is
//! `i_2`. Induction gives the pass, and since every rank-`r` occurrence is
//! either taken or destroyed by the one it overlaps, the pass consumes the level
//! exactly. QED for parent-ordered tables.
//!
//! Real tables are NOT parent ordered: of 233378 `cl100k_base` adjacent pair
//! combinations, 56048 violate it, 24.0%. The whitespace chain is clearest, and
//! `id == rank` in tiktoken:
//!
//! ```text
//! ' '(220) + '  '(256) -> '   '(262)      then '   '(262) + ' '(220) -> '    '(257)
//! ```
//!
//! 257 is BELOW 262, so the merge consuming token 262 is cheaper than the merge
//! that minted it. That is a property of the TABLE and holds regardless of which
//! states are reachable. The theorem therefore does not cover production, and
//! finding 3 is why no replacement theorem is offered: the real guarantee rests
//! on a frequency correlation, which local commutation cannot express.
//!
//! Be precise about what descends, because the loose version of this claim is
//! wrong and was corrected once already. The minimum rank descending is a
//! property of a TRACE, not of the table, and it appears on states OFF the
//! raw-byte greedy path. From raw spaces the trace ASCENDS: 7 spaces run
//! 256, 256, 256, 257, 262, 286, because rank 256 beats 262 at every step, so
//! `[220, 256, 220]` never forms. Feed that state in directly and the pass ranks
//! are 262 then 257, descending, which `cl100k_minimum_rank_decreases_across_passes`
//! pins on real ranks. Both are real; neither generalizes to the other.
//!
//! The consequence is for the device side. You may NOT infer "the table is parent
//! ordered" or "ranks rise" from having observed a monotonic greedy trace, so no
//! loop bound may be derived from a count of distinct ranks. A kernel that starts
//! mid-input or resumes a partial state is exactly where an off-path state
//! arises.
//!
//! # Pass count is a measurement, not a theorem
//!
//! Since the minimum rank can decrease, the worst-case pass bound is O(merges),
//! the same as sequential. Termination is unconditional regardless: every fusion
//! shortens the sequence by exactly one, so the loop is bounded by the initial
//! length whatever the ranks do. See the `pass_count_*` tests for constructed
//! cases with exact counts, both a cascade where multi-merge takes 4 passes to
//! sequential's 15, and a chain where it saves nothing at all.
//!
//! # Provenance of the numbers above
//!
//! Every figure in this doc falls into one of three tiers. This section exists
//! because a read-only analysis whose OUTPUT becomes a durable claim corrupts the
//! record silently: no file is touched, so no identity assertion, owner-line
//! check, or content compare can catch it. Two claims in this wave were wrong for
//! exactly that reason, and both were caught only by re-deriving them from data
//! on disk. Do not cite a tier-3 figure without re-deriving it.
//!
//! Tier 1, reproducible by running this crate. Every counterexample and every
//! sweep count: the two initial-state refutations, the same-rank tie refutation,
//! parent order being necessary and sufficient over 13980800 arbitrary-state
//! cases, the tie counts (10697 pass-shape with 0 fatal on distinct symbols,
//! 11568 with 5710 fatal on a repeated symbol), the exact pass counts, and the
//! real cl100k ids. `cargo test -p exatok --test confluence_equivalence`.
//!
//! Tier 2, independently confirmed by a second agent or a second implementation.
//! The real cl100k space-run ids and the `encenc` chain (CpuRef reproduced 4
//! spaces to [257], 7 spaces to [286], raw "encenc" to [967, 967], and the
//! descending [262, 257] pass ranks, from a clean namespace against the
//! artifact). The 233378 adjacent pair combinations (AdversarialVocab derived the
//! same count from a standalone script, and Main confirmed it independently).
//! BOTH violation rates, re-derived from the artifact by standalone script with
//! the sha asserted in the same script that read it: 56048 of 233378, 24.0%,
//! under parent order as defined above, and 43674, 18.7%, under the operand-side
//! reading where a merge result ranks below one of its own two operands. The two
//! index the SAME inversions from opposite ends and are NOT interchangeable: one
//! cheaply consumed token is one violation on the consumer side but one per
//! operand split on the other, hence the larger consumer-side figure over an
//! identical denominator. Excluding single-byte operands leaves 43674 unchanged,
//! because a leaf id is below 256 while any token of length two or more ranks at
//! 256 or above, so a result can never rank below a leaf operand.
//!
//! Tier 3, single-sourced from an interactive session and NOT yet re-derived from
//! disk. The 1917 four-token divergent real states and the 130 distinct ones; the
//! 560 danger triples and the 304 that diverge; the 354276-state id-order sweep
//! totalling 18530 divergences against 0; and the injected-swap table above, whose
//! violation column predates the definition split and so is pinned to neither
//! reading. Treat each as indicative. The swap-table COMPARISON survives either
//! reading, since real cl100k is at 18.7% or above on both, well past the 5.1% row
//! where synthetic tables already diverge.
//!
//! Note what tier 3 does NOT undermine. The id-order CONCLUSION is tier 1: the
//! paired tests `permuted_ids_break_exactness_on_initial_states` and
//! `length_ordered_ids_are_exact_on_initial_states` reproduce it in committed code
//! over 1062864 cases per half, same generator and same seeds, differing only in
//! `IdOrder`. So "id order decides exactness" is verified on disk even though the
//! specific count 18530 is not. Likewise the conclusion that real cl100k violates
//! parent order does not depend on the exact rate: `is_parent_ordered` returning
//! false for the real space-run table is asserted directly, and the argument needs
//! only that the rate is far above zero.
//!
//! # Scope
//!
//! This module is the experiment: two independent implementations, adversarial
//! table generators, and the differential harness. It is not the production
//! merge loop, which is exact sequential per pretoken.

use crate::{PairKey, Rank, TokenId, ExatokError};
use core::fmt;

/// A merge-table hit: the id an adjacent pair fuses into, plus its merge rank.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Merge {
    /// Id the pair fuses into.
    pub id: TokenId,
    /// Merge rank. Lower fuses first.
    pub rank: Rank,
}

/// A table entry that breaks parent order.
///
/// Parent order asks that a merge minting token `X` at rank `q` be followed by
/// every merge consuming `X`, so any such merge ranks above `q`. Real
/// vocabularies violate it (56048 of 233378 `cl100k_base` pair combinations,
/// 24.0%), so this is a classifier for which tables the arbitrary-state theorem
/// covers, NOT a validity check on a vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParentOrderViolation {
    /// The offending pair.
    pub pair: PairKey,
    /// Rank of the offending entry.
    pub rank: Rank,
    /// The operand minted at an equal or later rank.
    pub operand: TokenId,
    /// Latest rank that mints `operand`.
    pub minted_at: Rank,
}

/// A dense `(left, right) -> (merged id, rank)` table over a small id universe.
///
/// Dense indexing is deliberate: an exhaustive sweep runs hundreds of millions
/// of lookups, so they must not be the bottleneck. Ranks and merged ids are
/// free u32 values; only OPERAND ids are bounded by the universe. That is what
/// lets a real vocabulary slice be modeled at real ranks with compact operand
/// slots. Production tables are hashed and live in `gpu_rank_table`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeTable {
    universe: u32,
    /// `universe * universe` ranks, [`Rank::ABSENT`] where the pair is absent.
    ranks: Vec<u32>,
    /// Fused ids, meaningful only where the matching rank is present.
    ids: Vec<u32>,
}

impl MergeTable {
    /// An empty table over operand ids `0..universe`.
    #[must_use]
    pub fn new(universe: u32) -> Self {
        let cells = (universe as usize) * (universe as usize);
        Self {
            universe,
            ranks: vec![Rank::ABSENT.0; cells],
            ids: vec![0; cells],
        }
    }

    /// Build from `(left, right, merged, rank)` rows.
    pub fn from_raw(universe: u32, rows: &[(u32, u32, u32, u32)]) -> Result<Self, ExatokError> {
        let mut table = Self::new(universe);
        for &(left, right, merged, rank) in rows {
            table.insert(TokenId(left), TokenId(right), TokenId(merged), Rank(rank))?;
        }
        Ok(table)
    }

    /// Size of the operand id space this table can address.
    #[must_use]
    pub const fn universe(&self) -> u32 {
        self.universe
    }

    fn cell(&self, left: TokenId, right: TokenId) -> Option<usize> {
        if left.0 >= self.universe || right.0 >= self.universe {
            return None;
        }
        Some((left.0 as usize) * (self.universe as usize) + (right.0 as usize))
    }

    /// Record `left right -> merged` at `rank`, overwriting any prior entry.
    pub fn insert(
        &mut self,
        left: TokenId,
        right: TokenId,
        merged: TokenId,
        rank: Rank,
    ) -> Result<(), ExatokError> {
        if !rank.is_present() {
            return Err(ExatokError::Artifact {
                artifact: "confluence merge table".to_owned(),
                location: format!("pair ({}, {})", left.0, right.0),
                detail: "rank equals Rank::ABSENT, which is the miss sentinel".to_owned(),
                fix: "use a rank below u32::MAX so the min reduction can select it".to_owned(),
            });
        }
        if merged.0 >= self.universe {
            return Err(ExatokError::Artifact {
                artifact: "confluence merge table".to_owned(),
                location: format!("pair ({}, {})", left.0, right.0),
                detail: format!(
                    "merged id {} is outside the operand universe 0..{}, so it could never be \
                     fused again",
                    merged.0, self.universe
                ),
                fix: "widen the universe passed to MergeTable::new".to_owned(),
            });
        }
        let Some(cell) = self.cell(left, right) else {
            return Err(ExatokError::Artifact {
                artifact: "confluence merge table".to_owned(),
                location: format!("pair ({}, {})", left.0, right.0),
                detail: format!("operand outside the universe 0..{}", self.universe),
                fix: "widen the universe passed to MergeTable::new".to_owned(),
            });
        };
        self.ranks[cell] = rank.0;
        self.ids[cell] = merged.0;
        Ok(())
    }

    /// Drop any entry for `left right`. Absent pairs are left alone.
    pub fn remove(&mut self, left: TokenId, right: TokenId) {
        if let Some(cell) = self.cell(left, right) {
            self.ranks[cell] = Rank::ABSENT.0;
        }
    }

    /// The merge for `left right`, or `None` when the pair is unmergeable.
    #[must_use]
    pub fn lookup(&self, left: TokenId, right: TokenId) -> Option<Merge> {
        let cell = self.cell(left, right)?;
        let rank = self.ranks[cell];
        if rank == Rank::ABSENT.0 {
            return None;
        }
        Some(Merge {
            id: TokenId(self.ids[cell]),
            rank: Rank(rank),
        })
    }

    /// Rank of `left right`, or [`Rank::ABSENT`].
    #[must_use]
    pub fn rank_of(&self, left: TokenId, right: TokenId) -> Rank {
        match self.lookup(left, right) {
            Some(merge) => merge.rank,
            None => Rank::ABSENT,
        }
    }

    /// Present entries in ascending packed-key order.
    pub fn entries(&self) -> impl Iterator<Item = (PairKey, Merge)> + '_ {
        let stride = (self.universe as usize).max(1);
        self.ranks
            .iter()
            .enumerate()
            .filter_map(move |(cell, &rank)| {
                if rank == Rank::ABSENT.0 {
                    return None;
                }
                let left = TokenId((cell / stride) as u32);
                let right = TokenId((cell % stride) as u32);
                Some((
                    PairKey::new(left, right),
                    Merge {
                        id: TokenId(self.ids[cell]),
                        rank: Rank(rank),
                    },
                ))
            })
    }

    /// Number of present entries.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.ranks.iter().filter(|&&r| r != Rank::ABSENT.0).count()
    }

    /// Entries whose rank does not strictly follow the merge minting an operand.
    #[must_use]
    pub fn parent_order_violations(&self) -> Vec<ParentOrderViolation> {
        let mut minted: Vec<Option<u32>> = vec![None; self.universe as usize];
        for (_, merge) in self.entries() {
            let slot = &mut minted[merge.id.0 as usize];
            *slot = Some(match *slot {
                Some(seen) if seen >= merge.rank.0 => seen,
                _ => merge.rank.0,
            });
        }
        let mut violations = Vec::new();
        for (pair, merge) in self.entries() {
            for operand in [pair.left(), pair.right()] {
                let Some(minted_at) = minted[operand.0 as usize] else {
                    continue;
                };
                if merge.rank.0 <= minted_at {
                    violations.push(ParentOrderViolation {
                        pair,
                        rank: merge.rank,
                        operand,
                        minted_at: Rank(minted_at),
                    });
                }
            }
        }
        violations
    }

    /// True when no entry violates parent order, so the arbitrary-state
    /// exactness theorem applies. Real vocabularies return false.
    #[must_use]
    pub fn is_parent_ordered(&self) -> bool {
        self.parent_order_violations().is_empty()
    }
}

impl fmt::Display for MergeTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "universe {}:", self.universe)?;
        for (pair, merge) in self.entries() {
            write!(
                f,
                " ({},{})->{}@r{}",
                pair.left().0,
                pair.right().0,
                merge.id.0,
                merge.rank.0
            )?;
        }
        Ok(())
    }
}

/// Result of running a merge strategy to completion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeTrace {
    /// Final token sequence.
    pub tokens: Vec<TokenId>,
    /// Barrier-synchronized passes performed.
    pub passes: usize,
    /// Individual pair fusions performed.
    pub merges: usize,
}

/// One sequential phase spent at a single rank level.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RankPhase {
    /// Sequence after the phase.
    pub tokens: Vec<TokenId>,
    /// The rank the phase ran at.
    pub rank: Rank,
    /// Merges the phase performed.
    pub merges: usize,
}

/// Leftmost position holding the lowest-ranked mergeable pair.
fn leftmost_lowest_rank(tokens: &[TokenId], table: &MergeTable) -> Option<(usize, Merge)> {
    let mut best: Option<(usize, Merge)> = None;
    for at in 0..tokens.len().saturating_sub(1) {
        let Some(merge) = table.lookup(tokens[at], tokens[at + 1]) else {
            continue;
        };
        let better = match best {
            Some((_, incumbent)) => merge.rank.0 < incumbent.rank.0,
            None => true,
        };
        if better {
            best = Some((at, merge));
        }
    }
    best
}

/// Reference BPE: fuse one pair per step, lowest rank first, leftmost on ties.
///
/// The exactness oracle. Selection is recomputed from scratch after every
/// fusion, which is required: a fusion can expose a pair ranking below anything
/// in the input, so a pre-sorted rank replay is wrong. One fusion per pass, so
/// `passes == merges`, which is the O(merges) barrier count GPUTOK pays.
#[must_use]
pub fn sequential_leftmost_greedy(input: &[TokenId], table: &MergeTable) -> MergeTrace {
    let mut tokens = input.to_vec();
    let mut merges = 0usize;
    while let Some((at, merge)) = leftmost_lowest_rank(&tokens, table) {
        tokens[at] = merge.id;
        tokens.remove(at + 1);
        merges += 1;
    }
    MergeTrace {
        tokens,
        passes: merges,
        merges,
    }
}

/// Sequential fusions taken while the global minimum rank stays where it began.
///
/// The per-pass half of the hypothesis: what one multi-merge pass claims to
/// reproduce. `None` when nothing is mergeable.
#[must_use]
pub fn sequential_rank_phase(input: &[TokenId], table: &MergeTable) -> Option<RankPhase> {
    let mut tokens = input.to_vec();
    let (mut at, mut merge) = leftmost_lowest_rank(&tokens, table)?;
    let rank = merge.rank;
    let mut merges = 0usize;
    loop {
        if merge.rank != rank {
            break;
        }
        tokens[at] = merge.id;
        tokens.remove(at + 1);
        merges += 1;
        match leftmost_lowest_rank(&tokens, table) {
            Some((next_at, next_merge)) => {
                at = next_at;
                merge = next_merge;
            }
            None => break,
        }
    }
    Some(RankPhase {
        tokens,
        rank,
        merges,
    })
}

/// One device-shaped pass: rank every adjacent pair, reduce to the minimum
/// rank, then fuse the maximal left-biased non-overlapping set at that rank.
///
/// Returns the next sequence and its fusion count, or `None` when no pair is
/// mergeable. A returned pass always performs at least one fusion, so the
/// driving loop always shortens the sequence and always terminates.
#[must_use]
pub fn single_rank_pass(tokens: &[TokenId], table: &MergeTable) -> Option<(Vec<TokenId>, usize)> {
    let width = tokens.len().checked_sub(1)?;
    if width == 0 {
        return None;
    }
    let mut ranks = Vec::with_capacity(width);
    let mut fused = Vec::with_capacity(width);
    for at in 0..width {
        match table.lookup(tokens[at], tokens[at + 1]) {
            Some(merge) => {
                ranks.push(merge.rank.0);
                fused.push(merge.id);
            }
            None => {
                ranks.push(Rank::ABSENT.0);
                fused.push(tokens[at]);
            }
        }
    }

    // Unsigned min reduction. Rank::ABSENT being u32::MAX is what lets an
    // unmergeable pair lose here without a separate presence mask.
    let mut floor = Rank::ABSENT.0;
    for &rank in &ranks {
        if rank < floor {
            floor = rank;
        }
    }
    if floor == Rank::ABSENT.0 {
        return None;
    }

    let mut out = Vec::with_capacity(tokens.len());
    let mut merges = 0usize;
    let mut at = 0usize;
    while at < tokens.len() {
        if at < width && ranks[at] == floor {
            // Taking this occurrence skips the one at `at + 1`, which would
            // share a token index with it. That is the left-biased rule.
            out.push(fused[at]);
            at += 2;
            merges += 1;
        } else {
            out.push(tokens[at]);
            at += 1;
        }
    }
    Some((out, merges))
}

/// Drive [`single_rank_pass`] to a fixpoint.
///
/// `passes` is a measured cost, not a bound: the minimum rank can fall, so this
/// is O(merges) in the worst case.
#[must_use]
pub fn single_rank_multi_merge(input: &[TokenId], table: &MergeTable) -> MergeTrace {
    let mut tokens = input.to_vec();
    let mut passes = 0usize;
    let mut merges = 0usize;
    while let Some((next, pass_merges)) = single_rank_pass(&tokens, table) {
        tokens = next;
        passes += 1;
        merges += pass_merges;
    }
    MergeTrace {
        tokens,
        passes,
        merges,
    }
}

/// How two strategies disagreed on one input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DivergenceKind {
    /// Final token sequences differ. Exactness is lost.
    FinalTokens,
    /// Final tokens agree, but multi-merge pass `n` is not the sequential
    /// same-rank phase taken from the same state.
    Pass(usize),
}

impl fmt::Display for DivergenceKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FinalTokens => write!(f, "final tokens"),
            Self::Pass(index) => write!(f, "pass {index}"),
        }
    }
}

/// True when two kinds describe the same class of failure.
#[must_use]
pub const fn same_class(left: DivergenceKind, right: DivergenceKind) -> bool {
    matches!(
        (left, right),
        (DivergenceKind::FinalTokens, DivergenceKind::FinalTokens)
            | (DivergenceKind::Pass(_), DivergenceKind::Pass(_))
    )
}

/// Compare both strategies on one input.
///
/// Checks the strong claim (identical final tokens) first, then the per-pass
/// claim at every reachable state, so a pass-level disagreement is caught even
/// when the final ids happen to reconverge.
#[must_use]
pub fn classify(input: &[TokenId], table: &MergeTable) -> Option<DivergenceKind> {
    let reference = sequential_leftmost_greedy(input, table);
    let candidate = single_rank_multi_merge(input, table);
    if reference.tokens != candidate.tokens {
        return Some(DivergenceKind::FinalTokens);
    }
    let mut state = input.to_vec();
    let mut index = 0usize;
    loop {
        match (
            single_rank_pass(&state, table),
            sequential_rank_phase(&state, table),
        ) {
            (None, None) => return None,
            (Some((next, _)), Some(phase)) if next == phase.tokens => {
                state = next;
                index += 1;
            }
            _ => return Some(DivergenceKind::Pass(index)),
        }
    }
}

/// A captured disagreement, reproducible on its own.
#[derive(Debug, Clone)]
pub struct Divergence {
    /// What disagreed.
    pub kind: DivergenceKind,
    /// The rank table that produced it.
    pub table: MergeTable,
    /// The input sequence.
    pub input: Vec<TokenId>,
    /// Sequential leftmost-greedy output.
    pub sequential: Vec<TokenId>,
    /// Multi-merge output.
    pub multi: Vec<TokenId>,
    /// Parent-order violations in `table`.
    pub violations: Vec<ParentOrderViolation>,
}

impl Divergence {
    /// Capture a disagreement on `input`, or `None` when the two agree.
    #[must_use]
    pub fn capture(input: &[TokenId], table: &MergeTable) -> Option<Self> {
        let kind = classify(input, table)?;
        Some(Self {
            kind,
            table: table.clone(),
            input: input.to_vec(),
            sequential: sequential_leftmost_greedy(input, table).tokens,
            multi: single_rank_multi_merge(input, table).tokens,
            violations: table.parent_order_violations(),
        })
    }
}

fn render_ids(f: &mut fmt::Formatter<'_>, tokens: &[TokenId]) -> fmt::Result {
    write!(f, "[")?;
    for (position, token) in tokens.iter().enumerate() {
        if position > 0 {
            write!(f, ", ")?;
        }
        write!(f, "{}", token.0)?;
    }
    write!(f, "]")
}

impl fmt::Display for Divergence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} diverged\n  table: {}\n  input: ", self.kind, self.table)?;
        render_ids(f, &self.input)?;
        write!(f, "\n  sequential: ")?;
        render_ids(f, &self.sequential)?;
        write!(f, "\n  multi-merge: ")?;
        render_ids(f, &self.multi)?;
        write!(f, "\n  parent-order violations: {}", self.violations.len())?;
        for violation in &self.violations {
            write!(
                f,
                "\n    ({},{})@r{} consumes {} minted at r{}",
                violation.pair.left().0,
                violation.pair.right().0,
                violation.rank.0,
                violation.operand.0,
                violation.minted_at.0
            )?;
        }
        Ok(())
    }
}

/// Shrink a captured divergence while preserving its failure class.
///
/// Drops tokens, then drops table entries, then compacts ranks to a dense
/// `0..n` range. Rank compaction is order preserving, so it cannot change
/// either algorithm's behavior, and the result is re-verified regardless.
#[must_use]
pub fn minimize(found: Divergence) -> Divergence {
    let mut best = found;
    loop {
        let mut improved = false;
        for cut in (0..best.input.len()).rev() {
            let mut candidate = best.input.clone();
            candidate.remove(cut);
            let Some(shrunk) = Divergence::capture(&candidate, &best.table) else {
                continue;
            };
            if same_class(shrunk.kind, best.kind) {
                best = shrunk;
                improved = true;
                break;
            }
        }
        if improved {
            continue;
        }
        let keys: Vec<PairKey> = best.table.entries().map(|(key, _)| key).collect();
        for key in keys {
            let mut table = best.table.clone();
            table.remove(key.left(), key.right());
            let Some(shrunk) = Divergence::capture(&best.input, &table) else {
                continue;
            };
            if same_class(shrunk.kind, best.kind) {
                best = shrunk;
                improved = true;
                break;
            }
        }
        if !improved {
            break;
        }
    }
    compact_ranks(best)
}

fn compact_ranks(found: Divergence) -> Divergence {
    let rows: Vec<(PairKey, Merge)> = found.table.entries().collect();
    let mut present: Vec<u32> = rows.iter().map(|(_, merge)| merge.rank.0).collect();
    present.sort_unstable();
    present.dedup();
    let mut table = MergeTable::new(found.table.universe());
    for (key, merge) in rows {
        let Ok(index) = present.binary_search(&merge.rank.0) else {
            return found;
        };
        let Ok(rank) = u32::try_from(index) else {
            return found;
        };
        if table
            .insert(key.left(), key.right(), merge.id, Rank(rank))
            .is_err()
        {
            return found;
        }
    }
    match Divergence::capture(&found.input, &table) {
        Some(shrunk) if same_class(shrunk.kind, found.kind) => shrunk,
        _ => found,
    }
}

/// SplitMix64, so the search space is reproducible without a `rand` dependency.
#[derive(Debug, Clone)]
pub struct SplitMix64 {
    state: u64,
}

impl SplitMix64 {
    /// Seed the generator.
    #[must_use]
    pub const fn new(seed: u64) -> Self {
        Self { state: seed }
    }

    /// Next 64-bit output.
    pub fn next_u64(&mut self) -> u64 {
        self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15);
        let mut z = self.state;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }

    /// Uniform-enough value in `0..bound`, or `0` when `bound` is zero.
    pub fn below(&mut self, bound: u32) -> u32 {
        if bound == 0 {
            return 0;
        }
        (self.next_u64() % u64::from(bound)) as u32
    }

    /// Fisher-Yates shuffle.
    pub fn shuffle<T>(&mut self, items: &mut [T]) {
        if items.len() < 2 {
            return;
        }
        for index in (1..items.len()).rev() {
            let Ok(bound) = u32::try_from(index + 1) else {
                continue;
            };
            items.swap(index, self.below(bound) as usize);
        }
    }
}

/// Shape of an unconstrained random table, free to violate parent order.
#[derive(Debug, Clone, Copy)]
pub struct UnconstrainedSpec {
    /// Base ids `0..base`, the only ids an initial state may contain.
    pub base: u32,
    /// Extra ids reserved for merge outputs.
    pub merged: u32,
    /// Ranks are drawn from `0..rank_pool`. A small pool forces heavy ties.
    pub rank_pool: u32,
    /// Percentage of pairs that get an entry.
    pub density_percent: u32,
}

/// A random table with no structural constraints.
///
/// Merge outputs are drawn from the whole universe, so merged ids re-enter as
/// operands and can alias base ids. Widest net, least realistic.
#[must_use]
pub fn unconstrained_table(rng: &mut SplitMix64, spec: UnconstrainedSpec) -> MergeTable {
    let universe = spec.base.saturating_add(spec.merged);
    let mut table = MergeTable::new(universe);
    for left in 0..universe {
        for right in 0..universe {
            if rng.below(100) >= spec.density_percent {
                continue;
            }
            let rank = Rank(rng.below(spec.rank_pool.max(1)));
            let merged = TokenId(rng.below(universe));
            drop(table.insert(TokenId(left), TokenId(right), merged, rank));
        }
    }
    table
}

/// Shape of a table that respects parent order.
#[derive(Debug, Clone, Copy)]
pub struct ParentOrderedSpec {
    /// Base ids `0..base`, present before any merge.
    pub base: u32,
    /// Number of rank levels.
    pub groups: u32,
    /// Entries minted per rank level. Above one, that level has ties.
    pub per_group: u32,
}

impl ParentOrderedSpec {
    /// Id universe a table built from this spec needs.
    #[must_use]
    pub const fn universe(&self) -> u32 {
        self.base
            .saturating_add(self.groups.saturating_mul(self.per_group))
    }
}

/// A random table satisfying parent order by construction.
///
/// Level `g` may only consume ids existing before level `g`: base ids, or ids
/// minted by a strictly earlier level. This is the class the arbitrary-state
/// theorem covers, and it admits ties within a level. Real vocabularies do NOT
/// belong to it.
#[must_use]
pub fn parent_ordered_table(rng: &mut SplitMix64, spec: ParentOrderedSpec) -> MergeTable {
    let mut table = MergeTable::new(spec.universe());
    let mut operands: Vec<TokenId> = (0..spec.base).map(TokenId).collect();
    let mut minted = spec.base;
    for group in 0..spec.groups {
        let mut fresh: Vec<TokenId> = Vec::new();
        for _ in 0..spec.per_group {
            let Ok(pool) = u32::try_from(operands.len()) else {
                break;
            };
            if pool == 0 {
                break;
            }
            let left = operands[rng.below(pool) as usize];
            let right = operands[rng.below(pool) as usize];
            // Keep the earlier entry: overwriting would lower a rank and could
            // break the very invariant this generator exists to hold.
            if table.rank_of(left, right).is_present() {
                continue;
            }
            if table
                .insert(left, right, TokenId(minted), Rank(group))
                .is_err()
            {
                continue;
            }
            fresh.push(TokenId(minted));
            minted += 1;
        }
        operands.extend(fresh);
    }
    table
}

/// Shape of a table generated the way a real vocabulary actually is.
#[derive(Debug, Clone, Copy)]
pub struct StringVocabSpec {
    /// Number of distinct base symbols, the alphabet of an initial state.
    pub alphabet: u32,
    /// Longest token, in symbols.
    pub max_token_len: u32,
    /// Percentage of multi-symbol strings kept as tokens.
    pub keep_percent: u32,
    /// How ids, and therefore ranks, are assigned across tokens.
    pub id_order: IdOrder,
}

/// How token ids are assigned, which in tiktoken semantics IS the rank order.
///
/// The single variable that decides whether multi-merge is exact on initial
/// states. Holding vocabulary structure fixed and flipping only this flips the
/// result, which is the controlled experiment in
/// `tests/confluence_equivalence.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdOrder {
    /// Uniform random permutation. Destroys any correlation between a token's
    /// rank and its length, and multi-merge is NOT exact under it.
    Permuted,
    /// Ascending token length, random within a length. Models real training
    /// order, where ids follow frequency and shorter pieces are more frequent,
    /// so a token always ranks above the pieces it is built from.
    ByLength,
}

/// A table with real vocabulary structure: tokens are strings and a pair's rank
/// is the id of the concatenation, exactly as in tiktoken.
///
/// Random rank tables essentially never mint a result ranking below its own
/// constituents, but real vocabularies do it 18.7% of the time (43674 of 233378
/// combinations, the OPERAND-side count, re-derived from the artifact; the
/// consumer-side parent-order rate is 24.0% and is the one the theorem uses), because
/// `id == rank` and ids follow training frequency rather than merge order:
/// `'enc'` at 967 versus `'ence'` at 768, or 3 spaces at 262 versus 4 at 257.
/// This generator reproduces that, and `spec.id_order` controls whether the
/// resulting rank order still correlates with token length.
///
/// Base symbols take ids `0..alphabet`, so an initial state is any sequence over
/// that range.
#[must_use]
pub fn string_vocab_table(rng: &mut SplitMix64, spec: StringVocabSpec) -> MergeTable {
    let alphabet = spec.alphabet.max(1);
    let max_len = spec.max_token_len.max(1) as usize;
    // Enumerate every string over the alphabet exactly once. Base symbols are
    // always tokens; longer strings are kept at the requested rate.
    let mut kept: Vec<Vec<u32>> = Vec::new();
    for len in 1..=max_len {
        let mut token = vec![0u32; len];
        loop {
            if len == 1 || rng.below(100) < spec.keep_percent {
                kept.push(token.clone());
            }
            let mut position = len;
            let mut carried = true;
            while position > 0 {
                position -= 1;
                if token[position] + 1 < alphabet {
                    token[position] += 1;
                    carried = false;
                    break;
                }
                token[position] = 0;
            }
            if carried {
                break;
            }
        }
    }

    // Base symbols keep their own ids. Longer tokens are shuffled for a random
    // tie-break, then ordered per `id_order`. A stable sort by length keeps that
    // shuffle within each length, so ByLength is "random within length".
    let mut longer: Vec<Vec<u32>> = kept.iter().filter(|t| t.len() > 1).cloned().collect();
    rng.shuffle(&mut longer);
    if spec.id_order == IdOrder::ByLength {
        longer.sort_by_key(Vec::len);
    }
    let mut id_of: Vec<(Vec<u32>, u32)> = (0..alphabet).map(|s| (vec![s], s)).collect();
    for (offset, token) in longer.iter().enumerate() {
        let Ok(offset) = u32::try_from(offset) else {
            continue;
        };
        id_of.push((token.clone(), alphabet + offset));
    }
    id_of.sort();
    let universe = alphabet.saturating_add(u32::try_from(longer.len()).unwrap_or_default());

    let lookup = |token: &[u32]| -> Option<u32> {
        id_of
            .binary_search_by(|(candidate, _)| candidate.as_slice().cmp(token))
            .ok()
            .map(|index| id_of[index].1)
    };

    let mut table = MergeTable::new(universe);
    for (left_token, left_id) in &id_of {
        for (right_token, right_id) in &id_of {
            let mut joined = left_token.clone();
            joined.extend_from_slice(right_token);
            if joined.len() > max_len {
                continue;
            }
            let Some(result) = lookup(&joined) else {
                continue;
            };
            // tiktoken semantics: a pair's rank IS the id of its result.
            drop(table.insert(
                TokenId(*left_id),
                TokenId(*right_id),
                TokenId(result),
                Rank(result),
            ));
        }
    }
    table
}

/// Real `cl100k_base` ids for a run of `n` spaces at `CL100K_SPACE_RUN_IDS[n - 1]`.
///
/// Read directly from the shipped `cl100k_base` artifact. In tiktoken
/// `id == rank`, so these values are simultaneously the token ids and the merge
/// ranks, and they are wildly non-monotonic in run length: 3 spaces is 262 but
/// 4 spaces is 257.
pub const CL100K_SPACE_RUN_IDS: [u32; 32] = [
    220, 256, 262, 257, 415, 996, 286, 260, 692, 1881, 310, 1835, 1078, 2342, 394, 338, 1733, 4391,
    504, 3909, 2611, 5291, 667, 5218, 3586, 6096, 1014, 6663, 4700, 7714, 1408, 792,
];

/// The real `cl100k_base` space-run merge structure.
///
/// Operand ids are relabeled to compact slots, slot `n - 1` being a run of `n`
/// spaces, while RANKS stay the real cl100k ids. That relabeling is exactly
/// behavior preserving: a token id is only ever compared for equality and used
/// as a table key, while every ordering decision reads the rank. It avoids a
/// dense table sized for id 7714. Map a slot back with
/// [`CL100K_SPACE_RUN_IDS`].
pub fn cl100k_space_run_table() -> Result<MergeTable, ExatokError> {
    let runs = CL100K_SPACE_RUN_IDS.len();
    let Ok(universe) = u32::try_from(runs) else {
        return Err(ExatokError::Artifact {
            artifact: "cl100k_base space runs".to_owned(),
            location: "CL100K_SPACE_RUN_IDS".to_owned(),
            detail: "run count does not fit in u32".to_owned(),
            fix: "shorten the embedded run chain".to_owned(),
        });
    };
    let mut table = MergeTable::new(universe);
    for left in 1..=runs {
        for right in 1..=runs {
            let total = left + right;
            if total > runs {
                continue;
            }
            let Ok(left_slot) = u32::try_from(left - 1) else {
                continue;
            };
            let Ok(right_slot) = u32::try_from(right - 1) else {
                continue;
            };
            let Ok(result_slot) = u32::try_from(total - 1) else {
                continue;
            };
            table.insert(
                TokenId(left_slot),
                TokenId(right_slot),
                TokenId(result_slot),
                Rank(CL100K_SPACE_RUN_IDS[total - 1]),
            )?;
        }
    }
    Ok(table)
}

/// Every pair over `0..base` tied at rank zero, each minting a fresh id.
///
/// Adversarial for the tie-break rule: one pass must pick the same occurrences,
/// in the same left-to-right order, that the oracle picks one at a time.
pub fn all_pairs_tie_table(base: u32) -> Result<MergeTable, ExatokError> {
    let universe = base.saturating_add(base.saturating_mul(base));
    let mut table = MergeTable::new(universe);
    let mut next = base;
    for left in 0..base {
        for right in 0..base {
            table.insert(TokenId(left), TokenId(right), TokenId(next), Rank(0))?;
            next += 1;
        }
    }
    Ok(table)
}

/// A cascade where `(i, i) -> i + 1` at rank `i`, for `i` in `0..levels`.
///
/// Every pass changes the minimum rank, and it is the best case for pass count:
/// multi-merge halves the sequence per pass while sequential fuses once.
pub fn cascade_table(levels: u32) -> Result<MergeTable, ExatokError> {
    let mut table = MergeTable::new(levels.saturating_add(1));
    for level in 0..levels {
        table.insert(
            TokenId(level),
            TokenId(level),
            TokenId(level + 1),
            Rank(level),
        )?;
    }
    Ok(table)
}

/// Convenience: raw ids to a token sequence.
#[must_use]
pub fn ids(raw: &[u32]) -> Vec<TokenId> {
    raw.iter().copied().map(TokenId).collect()
}

/// Number of sequences of length `min_len..=max_len` over `alphabet` ids.
#[must_use]
pub fn sequence_count(alphabet: u32, min_len: usize, max_len: usize) -> usize {
    let mut total = 0usize;
    for len in min_len..=max_len {
        let Ok(exp) = u32::try_from(len) else {
            continue;
        };
        let Some(count) = (alphabet as usize).checked_pow(exp) else {
            continue;
        };
        total = total.saturating_add(count);
    }
    total
}

/// Visit every sequence of length `min_len..=max_len` over ids `0..alphabet`.
///
/// With `alphabet` set to a table's base-symbol count, this enumerates exactly
/// the INITIAL states, the ones reachable from raw input. Returns the number
/// visited, which must equal [`sequence_count`] for the same arguments.
pub fn for_each_sequence(
    alphabet: u32,
    min_len: usize,
    max_len: usize,
    visit: &mut impl FnMut(&[TokenId]),
) -> usize {
    if alphabet == 0 {
        return 0;
    }
    let mut visited = 0usize;
    let mut buffer: Vec<TokenId> = Vec::with_capacity(max_len);
    for len in min_len..=max_len {
        if len == 0 {
            continue;
        }
        buffer.clear();
        buffer.resize(len, TokenId(0));
        loop {
            visit(&buffer);
            visited += 1;
            let mut position = len;
            let mut carried = true;
            while position > 0 {
                position -= 1;
                if buffer[position].0 + 1 < alphabet {
                    buffer[position].0 += 1;
                    carried = false;
                    break;
                }
                buffer[position].0 = 0;
            }
            if carried {
                break;
            }
        }
    }
    visited
}

/// Exactly what a sweep covered, so a result can be stated numerically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchSpace {
    /// Sequence alphabet size.
    pub alphabet: u32,
    /// Shortest sequence enumerated.
    pub min_len: usize,
    /// Longest sequence enumerated.
    pub max_len: usize,
    /// Rank tables swept.
    pub tables: usize,
    /// Sequences per table.
    pub sequences: usize,
    /// Total `(table, sequence)` cases.
    pub cases: usize,
}

impl fmt::Display for SearchSpace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "alphabet {}, lengths {}..={}, {} sequences x {} tables = {} cases",
            self.alphabet, self.min_len, self.max_len, self.sequences, self.tables, self.cases
        )
    }
}

/// What a sweep found.
#[derive(Debug, Clone)]
pub struct SearchOutcome {
    /// The space covered.
    pub space: SearchSpace,
    /// Cases where the two strategies disagreed at all.
    pub divergent_cases: usize,
    /// Disagreements on a parent-ordered table. Any nonzero value refutes the
    /// arbitrary-state theorem itself.
    pub parent_ordered_divergent_cases: usize,
    /// Cases whose final token ids differed, the exactness-fatal class.
    pub final_token_cases: usize,
    /// Total sequential fusions over the sweep.
    pub sequential_merges: usize,
    /// Total multi-merge passes over the sweep.
    pub multi_passes: usize,
    /// Captured samples, capped by the requested limit.
    pub samples: Vec<Divergence>,
}

impl SearchOutcome {
    /// Mean sequential fusions per case, times 1000, to keep it integral.
    #[must_use]
    pub const fn mean_sequential_merges_milli(&self) -> usize {
        if self.space.cases == 0 {
            return 0;
        }
        self.sequential_merges.saturating_mul(1000) / self.space.cases
    }

    /// Mean multi-merge passes per case, times 1000.
    #[must_use]
    pub const fn mean_multi_passes_milli(&self) -> usize {
        if self.space.cases == 0 {
            return 0;
        }
        self.multi_passes.saturating_mul(1000) / self.space.cases
    }
}

/// Sweep every sequence against every table and classify each case.
///
/// Set `alphabet` to a table's base-symbol count to sweep INITIAL states only,
/// which is the production-relevant question. A larger alphabet reaches
/// arbitrary intermediate states, most of which no input can produce.
#[must_use]
pub fn search(
    alphabet: u32,
    min_len: usize,
    max_len: usize,
    tables: &[MergeTable],
    sample_limit: usize,
) -> SearchOutcome {
    let sequences = sequence_count(alphabet, min_len, max_len);
    let mut divergent_cases = 0usize;
    let mut parent_ordered_divergent_cases = 0usize;
    let mut final_token_cases = 0usize;
    let mut sequential_merges = 0usize;
    let mut multi_passes = 0usize;
    let mut samples: Vec<Divergence> = Vec::new();
    for table in tables {
        let parent_ordered = table.is_parent_ordered();
        for_each_sequence(alphabet, min_len, max_len, &mut |sequence| {
            let reference = sequential_leftmost_greedy(sequence, table);
            let candidate = single_rank_multi_merge(sequence, table);
            sequential_merges = sequential_merges.saturating_add(reference.merges);
            multi_passes = multi_passes.saturating_add(candidate.passes);
            let Some(kind) = classify(sequence, table) else {
                return;
            };
            divergent_cases += 1;
            if parent_ordered {
                parent_ordered_divergent_cases += 1;
            }
            if kind == DivergenceKind::FinalTokens {
                final_token_cases += 1;
            }
            if samples.len() < sample_limit {
                if let Some(found) = Divergence::capture(sequence, table) {
                    samples.push(found);
                }
            }
        });
    }
    SearchOutcome {
        space: SearchSpace {
            alphabet,
            min_len,
            max_len,
            tables: tables.len(),
            sequences,
            cases: sequences.saturating_mul(tables.len()),
        },
        divergent_cases,
        parent_ordered_divergent_cases,
        final_token_cases,
        sequential_merges,
        multi_passes,
        samples,
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "test code asserts on known-good values"
)]
mod tests {
    use super::*;

    /// Locks the dense table's miss ACCESSOR: an absent pair reports
    /// [`Rank::ABSENT`], not rank zero. Scope is `rank_of` and `lookup` only.
    /// The min-reduction consequence is NOT covered here, because nothing in this
    /// test calls the reduction; the mixed-state test below carries that claim.
    #[test]
    fn absent_pair_reports_the_miss_sentinel() {
        let table = MergeTable::from_raw(4, &[(0, 1, 2, 7)]).unwrap();
        assert_eq!(table.rank_of(TokenId(0), TokenId(1)), Rank(7));
        assert_eq!(table.rank_of(TokenId(1), TokenId(0)), Rank::ABSENT);
        assert_eq!(table.rank_of(TokenId(3), TokenId(3)), Rank::ABSENT);
        assert_eq!(table.lookup(TokenId(1), TokenId(0)), None);
        assert_eq!(
            table.lookup(TokenId(0), TokenId(1)),
            Some(Merge {
                id: TokenId(2),
                rank: Rank(7)
            })
        );
    }

    /// Locks [`Rank::ABSENT`] LOSING the unsigned min reduction inside
    /// [`single_rank_pass`] on a mixed state, which the accessor test above cannot
    /// see. Absent pairs sit on both sides of the only present rank, so a miss
    /// recorded as rank zero would win the floor and fuse index 0, giving [1, 0]
    /// with two merges instead of [1, 2, 1] with one.
    #[test]
    fn an_absent_pair_loses_the_min_reduction_to_a_present_rank() {
        let table = MergeTable::from_raw(4, &[(0, 0, 2, 5)]).unwrap();
        assert_eq!(table.rank_of(TokenId(1), TokenId(0)), Rank::ABSENT);
        assert_eq!(table.rank_of(TokenId(0), TokenId(0)), Rank(5));
        assert_eq!(table.rank_of(TokenId(0), TokenId(1)), Rank::ABSENT);

        // Pair ranks are [ABSENT, 5, ABSENT], so only index 1 may fuse.
        let (next, merges) = single_rank_pass(&ids(&[1, 0, 0, 1]), &table).unwrap();
        assert_eq!(next, ids(&[1, 2, 1]));
        assert_eq!(merges, 1);
    }

    /// Locks the universe bound: an id outside `0..universe` reads as a miss
    /// rather than indexing another pair's cell. A wrapped index would silently
    /// fuse the wrong pair.
    #[test]
    fn out_of_universe_ids_miss_instead_of_aliasing() {
        let table = MergeTable::from_raw(3, &[(0, 1, 2, 0)]).unwrap();
        assert_eq!(table.rank_of(TokenId(3), TokenId(0)), Rank::ABSENT);
        assert_eq!(table.rank_of(TokenId(0), TokenId(9)), Rank::ABSENT);
        assert_eq!(table.entry_count(), 1);
    }

    /// Locks insert validation: [`Rank::ABSENT`] as a rank, or a merged id
    /// outside the operand universe, is rejected instead of stored. Storing
    /// ABSENT would make a present entry invisible to the min reduction forever.
    #[test]
    fn insert_rejects_the_sentinel_rank_and_out_of_range_ids() {
        let mut table = MergeTable::new(3);
        assert!(
            table
                .insert(TokenId(0), TokenId(1), TokenId(2), Rank::ABSENT)
                .is_err()
        );
        assert!(
            table
                .insert(TokenId(0), TokenId(1), TokenId(3), Rank(0))
                .is_err()
        );
        assert!(
            table
                .insert(TokenId(3), TokenId(1), TokenId(2), Rank(0))
                .is_err()
        );
        assert_eq!(table.entry_count(), 0);
        assert!(
            table
                .insert(TokenId(0), TokenId(1), TokenId(2), Rank(0))
                .is_ok()
        );
        assert_eq!(table.entry_count(), 1);
    }

    /// Locks that a rank may exceed the universe while an operand id may not.
    /// The real-vocabulary tables depend on it: slot operands stay small while
    /// ranks carry values like 7714.
    #[test]
    fn ranks_are_unbounded_while_operands_are_not() {
        let mut table = MergeTable::new(2);
        assert!(
            table
                .insert(TokenId(0), TokenId(0), TokenId(1), Rank(7714))
                .is_ok()
        );
        assert_eq!(table.rank_of(TokenId(0), TokenId(0)), Rank(7714));
    }

    /// Locks entry enumeration order and key packing: entries come back in
    /// ascending packed-key order with left and right operands recovered
    /// correctly. A transposed operand would corrupt every audit downstream.
    #[test]
    fn entries_enumerate_in_packed_key_order() {
        let table = MergeTable::from_raw(3, &[(2, 0, 1, 5), (0, 1, 2, 3), (1, 2, 0, 4)]).unwrap();
        let listed: Vec<(u32, u32, u32, u32)> = table
            .entries()
            .map(|(pair, merge)| (pair.left().0, pair.right().0, merge.id.0, merge.rank.0))
            .collect();
        assert_eq!(listed, vec![(0, 1, 2, 3), (1, 2, 0, 4), (2, 0, 1, 5)]);
    }

    /// Locks the parent-order audit: a merge consuming a token minted at an
    /// equal or later rank is reported, with the exact operand and mint rank.
    #[test]
    fn parent_order_audit_reports_the_offending_operand() {
        let table = MergeTable::from_raw(3, &[(0, 0, 1, 1), (1, 0, 2, 0)]).unwrap();
        let violations = table.parent_order_violations();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].pair, PairKey::new(TokenId(1), TokenId(0)));
        assert_eq!(violations[0].rank, Rank(0));
        assert_eq!(violations[0].operand, TokenId(1));
        assert_eq!(violations[0].minted_at, Rank(1));
        assert!(!table.is_parent_ordered());
    }

    /// Locks the equality boundary of the audit: rank strictly greater than the
    /// mint rank passes, rank exactly equal fails. Equal rank is the subtle
    /// case, and it is unsafe because both merges compete within one pass.
    #[test]
    fn parent_order_audit_requires_strictly_later_rank() {
        let strict = MergeTable::from_raw(3, &[(0, 0, 1, 0), (1, 0, 2, 1)]).unwrap();
        assert!(strict.is_parent_ordered());

        let tied = MergeTable::from_raw(3, &[(0, 0, 1, 0), (1, 0, 2, 0)]).unwrap();
        let violations = tied.parent_order_violations();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].rank, Rank(0));
        assert_eq!(violations[0].minted_at, Rank(0));
    }

    /// Locks the audit against a self-consuming merge: an entry whose output
    /// feeds back into itself is a violation on both operands.
    #[test]
    fn parent_order_audit_catches_self_feeding_entries() {
        let table = MergeTable::from_raw(2, &[(0, 0, 0, 3)]).unwrap();
        let violations = table.parent_order_violations();
        assert_eq!(violations.len(), 2);
        for violation in &violations {
            assert_eq!(violation.operand, TokenId(0));
            assert_eq!(violation.rank, Rank(3));
            assert_eq!(violation.minted_at, Rank(3));
        }
    }

    /// Locks sequential rank precedence: the lowest rank wins even when a
    /// higher-ranked pair sits further left. Scanning left to right and taking
    /// the first mergeable pair is the classic BPE bug.
    #[test]
    fn sequential_takes_lowest_rank_before_leftmost() {
        // (0,1) at rank 9 sits left of (1,2) at rank 0.
        let table = MergeTable::from_raw(6, &[(0, 1, 4, 9), (1, 2, 5, 0)]).unwrap();
        let trace = sequential_leftmost_greedy(&ids(&[0, 1, 2]), &table);
        assert_eq!(trace.tokens, ids(&[0, 5]));
        assert_eq!(trace.merges, 1);
    }

    /// Locks the tie-break direction: equal ranks resolve to the leftmost
    /// occurrence. A rightmost tie-break changes ids on real text.
    #[test]
    fn sequential_breaks_rank_ties_leftmost() {
        let table = MergeTable::from_raw(7, &[(0, 1, 5, 4), (2, 3, 6, 4)]).unwrap();
        let trace = sequential_leftmost_greedy(&ids(&[0, 1, 2, 3]), &table);
        assert_eq!(trace.tokens, ids(&[5, 6]));
        assert_eq!(trace.merges, 2);

        let mirrored = sequential_leftmost_greedy(&ids(&[2, 3, 0, 1]), &table);
        assert_eq!(mirrored.tokens, ids(&[6, 5]));
    }

    /// Locks that selection is recomputed after every fusion. A fusion can
    /// expose a pair ranking below anything in the input, so replaying a
    /// pre-sorted rank order is wrong. Here (0,0)->1 ranks 5 but (1,0)->2
    /// ranks 0, so the second fusion must be the newly exposed lower one.
    #[test]
    fn sequential_recomputes_selection_after_each_fusion() {
        let table = MergeTable::from_raw(3, &[(0, 0, 1, 5), (1, 0, 2, 0)]).unwrap();
        let trace = sequential_leftmost_greedy(&ids(&[0, 0, 0]), &table);
        assert_eq!(trace.tokens, ids(&[2]));
        assert_eq!(trace.merges, 2);
    }

    /// Locks the sequential pass accounting: one fusion per pass, so `passes`
    /// equals `merges`. The pass-count comparison is meaningless if this drifts.
    #[test]
    fn sequential_performs_exactly_one_merge_per_pass() {
        let table = cascade_table(3).unwrap();
        let trace = sequential_leftmost_greedy(&ids(&[0, 0, 0, 0]), &table);
        assert_eq!(trace.tokens, ids(&[2]));
        assert_eq!(trace.merges, 3);
        assert_eq!(trace.passes, trace.merges);
    }

    /// Locks the terminal case: with no mergeable pair the input is returned
    /// unchanged and no fusion is counted. Short inputs must not loop or index
    /// out of range.
    #[test]
    fn sequential_leaves_unmergeable_input_alone() {
        let table = MergeTable::from_raw(4, &[(0, 1, 2, 0)]).unwrap();
        for input in [ids(&[]), ids(&[0]), ids(&[1, 0]), ids(&[3, 3, 3])] {
            let trace = sequential_leftmost_greedy(&input, &table);
            assert_eq!(trace.tokens, input);
            assert_eq!(trace.merges, 0);
            assert_eq!(trace.passes, 0);
        }
    }

    /// Locks the left-biased non-overlapping rule: three consecutive equal-rank
    /// occurrences must yield two fusions (positions 0 and 2), not three.
    /// Fusing overlapping occurrences would consume a token twice.
    #[test]
    fn multi_merge_skips_the_overlapping_occurrence() {
        let table = MergeTable::from_raw(2, &[(0, 0, 1, 0)]).unwrap();
        let (next, merges) = single_rank_pass(&ids(&[0, 0, 0, 0]), &table).unwrap();
        assert_eq!(next, ids(&[1, 1]));
        assert_eq!(merges, 2);

        let (odd, odd_merges) = single_rank_pass(&ids(&[0, 0, 0, 0, 0]), &table).unwrap();
        assert_eq!(odd, ids(&[1, 1, 0]));
        assert_eq!(odd_merges, 2);
    }

    /// Locks single-rank restriction: a pass fuses only the minimum rank and
    /// leaves higher-ranked pairs for later. Fusing across ranks in one pass is
    /// exactly the BlockBPE approximation this design rejects.
    #[test]
    fn multi_merge_pass_touches_only_the_minimum_rank() {
        let table = MergeTable::from_raw(7, &[(0, 1, 5, 0), (2, 3, 6, 1)]).unwrap();
        let (next, merges) = single_rank_pass(&ids(&[0, 1, 2, 3]), &table).unwrap();
        assert_eq!(next, ids(&[5, 2, 3]));
        assert_eq!(merges, 1);
    }

    /// Locks pass termination: a pass over an unmergeable or too-short sequence
    /// reports `None` instead of an unchanged sequence, which would spin the
    /// driving loop forever.
    #[test]
    fn multi_merge_pass_reports_none_when_nothing_merges() {
        let table = MergeTable::from_raw(4, &[(0, 1, 2, 0)]).unwrap();
        assert!(single_rank_pass(&ids(&[]), &table).is_none());
        assert!(single_rank_pass(&ids(&[0]), &table).is_none());
        assert!(single_rank_pass(&ids(&[1, 0]), &table).is_none());
        assert!(single_rank_pass(&ids(&[3, 3, 3]), &table).is_none());
    }

    /// Locks every returned pass making progress and shrinking the sequence.
    /// If a pass could return zero fusions, the driver would never terminate.
    /// Termination does not depend on ranks rising, only on this.
    #[test]
    fn every_returned_pass_performs_at_least_one_merge() {
        let mut rng = SplitMix64::new(0x5eed);
        let table = unconstrained_table(
            &mut rng,
            UnconstrainedSpec {
                base: 3,
                merged: 3,
                rank_pool: 2,
                density_percent: 60,
            },
        );
        let mut checked = 0usize;
        for_each_sequence(6, 1, 5, &mut |sequence| {
            let mut state = sequence.to_vec();
            while let Some((next, merges)) = single_rank_pass(&state, &table) {
                assert!(merges >= 1, "pass made no progress on {state:?}");
                assert!(next.len() < state.len(), "pass did not shrink {state:?}");
                state = next;
                checked += 1;
            }
        });
        assert_eq!(checked, 21287);
    }

    /// Locks multi-merge pass accounting on a cascade: 4 tokens collapse in 2
    /// passes using 3 fusions, against sequential's 3 passes for the same 3
    /// fusions. Pass 1 fuses positions 0 and 2 at rank 0, pass 2 fuses the
    /// result at rank 1.
    #[test]
    fn multi_merge_pass_count_tracks_cascade_depth() {
        let table = cascade_table(3).unwrap();
        let trace = single_rank_multi_merge(&ids(&[0, 0, 0, 0]), &table);
        assert_eq!(trace.tokens, ids(&[2]));
        assert_eq!(trace.merges, 3);
        assert_eq!(trace.passes, 2);
    }

    /// Locks the rank-phase oracle: it stops when the minimum rank moves off
    /// where it started, and reports the rank it ran at plus its fusion count.
    /// Without the stop condition it could not test the per-pass claim.
    #[test]
    fn rank_phase_stops_when_the_minimum_rank_moves() {
        let table = cascade_table(3).unwrap();
        let phase = sequential_rank_phase(&ids(&[0, 0, 0, 0]), &table).unwrap();
        assert_eq!(phase.rank, Rank(0));
        assert_eq!(phase.tokens, ids(&[1, 1]));
        assert_eq!(phase.merges, 2);
        assert!(sequential_rank_phase(&ids(&[3, 3]), &table).is_none());
    }

    /// Locks the enumerator against the closed-form count, and locks the
    /// odometer's emissions. An enumerator that skips sequences would silently
    /// shrink every reported search space.
    #[test]
    fn enumerator_visits_every_sequence_exactly_once() {
        let mut seen: Vec<Vec<u32>> = Vec::new();
        let visited = for_each_sequence(2, 1, 3, &mut |sequence| {
            seen.push(sequence.iter().map(|t| t.0).collect());
        });
        assert_eq!(visited, 14);
        assert_eq!(visited, sequence_count(2, 1, 3));
        assert_eq!(seen[0], vec![0]);
        assert_eq!(seen[1], vec![1]);
        assert_eq!(seen[2], vec![0, 0]);
        assert_eq!(seen[5], vec![1, 1]);
        assert_eq!(seen[6], vec![0, 0, 0]);
        assert_eq!(seen[13], vec![1, 1, 1]);
        let mut deduped = seen.clone();
        deduped.sort();
        deduped.dedup();
        assert_eq!(deduped.len(), 14);

        assert_eq!(for_each_sequence(1, 1, 4, &mut |_| {}), 4);
        assert_eq!(for_each_sequence(0, 1, 4, &mut |_| {}), 0);
        assert_eq!(sequence_count(4, 1, 8), 87380);
        assert_eq!(sequence_count(3, 1, 12), 797160);
    }

    /// Locks the generator's exact output stream. The search space is only
    /// reproducible if this is fixed, so a change invalidates every reported
    /// sweep.
    #[test]
    fn splitmix64_stream_is_fixed() {
        let mut rng = SplitMix64::new(0);
        assert_eq!(rng.next_u64(), 0xe220_a839_7b1d_cdaf);
        assert_eq!(rng.next_u64(), 0x6e78_9e6a_a1b9_65f4);
        assert_eq!(rng.next_u64(), 0x06c4_5d18_8009_454f);
        assert_eq!(rng.next_u64(), 0xf88b_b8a8_724c_81ec);

        let mut seeded = SplitMix64::new(0x243f_6a88_85a3_08d3);
        assert_eq!(seeded.next_u64(), 0x2cb0_f69f_4abe_a221);
        assert_eq!(seeded.next_u64(), 0x9417_0347_2314_8989);

        let mut bounded = SplitMix64::new(0);
        assert_eq!(
            (0..4).map(|_| bounded.below(10)).collect::<Vec<_>>(),
            vec![5, 0, 9, 4]
        );
        assert_eq!(bounded.below(0), 0);
        assert_eq!(bounded.below(1), 0);
    }

    /// Locks the shuffle as a permutation: it reorders without losing,
    /// duplicating, or inventing elements. A broken shuffle would silently
    /// collapse the id permutation that makes `string_vocab_table` adversarial.
    #[test]
    fn shuffle_is_a_permutation() {
        let mut rng = SplitMix64::new(7);
        let mut items: Vec<u32> = (0..64).collect();
        rng.shuffle(&mut items);
        assert_ne!(items, (0..64).collect::<Vec<_>>());
        let mut sorted = items.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, (0..64).collect::<Vec<_>>());

        let mut single = vec![9u32];
        rng.shuffle(&mut single);
        assert_eq!(single, vec![9]);
        let mut empty: Vec<u32> = Vec::new();
        rng.shuffle(&mut empty);
        assert!(empty.is_empty());
    }

    /// Locks the parent-ordered generator's invariant across many seeds and
    /// shapes. The arbitrary-state theorem's validation is meaningless if these
    /// tables are not actually parent ordered.
    #[test]
    fn parent_ordered_generator_never_violates_parent_order() {
        let mut nonempty = 0usize;
        for seed in 0..256u64 {
            for spec in [
                ParentOrderedSpec {
                    base: 2,
                    groups: 2,
                    per_group: 1,
                },
                ParentOrderedSpec {
                    base: 2,
                    groups: 1,
                    per_group: 2,
                },
                ParentOrderedSpec {
                    base: 1,
                    groups: 3,
                    per_group: 1,
                },
                ParentOrderedSpec {
                    base: 4,
                    groups: 3,
                    per_group: 3,
                },
            ] {
                let mut rng = SplitMix64::new(seed);
                let table = parent_ordered_table(&mut rng, spec);
                assert_eq!(
                    table.parent_order_violations(),
                    Vec::new(),
                    "seed {seed} spec {spec:?} produced {table}"
                );
                assert_eq!(table.universe(), spec.universe());
                if table.entry_count() > 0 {
                    nonempty += 1;
                }
            }
        }
        assert_eq!(nonempty, 1024);
    }

    /// Locks both id orders of the real-vocabulary generator, since the
    /// difference between them is the entire finding. `Permuted` must mint
    /// results ranking below their own constituents, reproducing the 18.7% operand-side
    /// structure real vocabularies have. `ByLength` must not, because a longer
    /// token always takes a higher id. Same vocabulary, same entry count, only
    /// the rank order differs.
    ///
    /// If `Permuted` ever stopped producing inversions the adversarial sweep
    /// would be toothless, and if `ByLength` ever produced one the controlled
    /// experiment would no longer isolate a single variable.
    #[test]
    fn string_vocab_id_order_controls_rank_inversions() {
        let spec = |id_order| StringVocabSpec {
            alphabet: 2,
            max_token_len: 5,
            keep_percent: 100,
            id_order,
        };

        let mut rng = SplitMix64::new(11);
        let permuted = string_vocab_table(&mut rng, spec(IdOrder::Permuted));
        // All 2+4+8+16+32 = 62 strings kept, so every splittable token has an
        // entry per split point: sum over lengths 2..=5 of (len-1)*count.
        assert_eq!(permuted.entry_count(), 4 + 2 * 8 + 3 * 16 + 4 * 32);
        assert_eq!(permuted.universe(), 62);
        assert!(
            permuted.parent_order_violations().len() > 40,
            "expected many inversions, got {}",
            permuted.parent_order_violations().len()
        );
        assert!(!permuted.is_parent_ordered());

        let mut rng = SplitMix64::new(11);
        let by_length = string_vocab_table(&mut rng, spec(IdOrder::ByLength));
        assert_eq!(by_length.entry_count(), permuted.entry_count());
        assert_eq!(by_length.universe(), permuted.universe());
        assert_eq!(
            by_length.parent_order_violations(),
            Vec::new(),
            "length-ordered ids cannot invert: a concatenation is longer than \
             either half, so it takes a higher id"
        );
        assert!(by_length.is_parent_ordered());

        // Rank equals the merged id in both, exactly like tiktoken.
        for table in [&permuted, &by_length] {
            for (_, merge) in table.entries() {
                assert_eq!(merge.rank.0, merge.id.0);
            }
        }
    }

    /// Locks the real cl100k space-run chain against the shipped artifact. These
    /// are the exact ids in `cl100k_base`, and the non-monotonicity is the whole
    /// reason the arbitrary-state theorem does not reach production. If someone
    /// "fixes" this array into sorted order the adversarial case evaporates.
    #[test]
    fn cl100k_space_run_ids_are_the_real_non_monotonic_chain() {
        assert_eq!(CL100K_SPACE_RUN_IDS[0], 220);
        assert_eq!(CL100K_SPACE_RUN_IDS[1], 256);
        assert_eq!(CL100K_SPACE_RUN_IDS[2], 262);
        assert_eq!(CL100K_SPACE_RUN_IDS[3], 257);
        assert_eq!(CL100K_SPACE_RUN_IDS[4], 415);
        assert_eq!(CL100K_SPACE_RUN_IDS[5], 996);
        assert_eq!(CL100K_SPACE_RUN_IDS[6], 286);
        assert_eq!(CL100K_SPACE_RUN_IDS[7], 260);
        // 4 spaces ranks BELOW 3 spaces, and 8 below 7.
        assert!(CL100K_SPACE_RUN_IDS[3] < CL100K_SPACE_RUN_IDS[2]);
        assert!(CL100K_SPACE_RUN_IDS[7] < CL100K_SPACE_RUN_IDS[6]);
        let mut sorted = CL100K_SPACE_RUN_IDS;
        sorted.sort_unstable();
        assert_ne!(sorted, CL100K_SPACE_RUN_IDS);
    }

    /// Locks the real space-run table's shape and its rank inversions, stated
    /// with real cl100k ids. Slot `n - 1` is a run of `n` spaces.
    #[test]
    fn cl100k_space_run_table_carries_real_ranks() {
        let table = cl100k_space_run_table().unwrap();
        assert_eq!(table.universe(), 32);
        // Pairs (a, b) with a + b <= 32: 31 * 32 / 2 = 496.
        assert_eq!(table.entry_count(), 496);
        // 1 space + 1 space -> 2 spaces, rank 256.
        assert_eq!(table.rank_of(TokenId(0), TokenId(0)), Rank(256));
        // 1 space + 2 spaces -> 3 spaces, rank 262.
        assert_eq!(table.rank_of(TokenId(0), TokenId(1)), Rank(262));
        // 3 spaces + 1 space -> 4 spaces, rank 257, BELOW 262. Main's case.
        assert_eq!(table.rank_of(TokenId(2), TokenId(0)), Rank(257));
        assert!(
            table.rank_of(TokenId(2), TokenId(0)).0 < table.rank_of(TokenId(0), TokenId(1)).0,
            "the 262 -> 257 inversion is the point of this table"
        );
        // 6 spaces + 1 space -> 7 spaces (286), then 7 + 1 -> 8 spaces (260).
        assert_eq!(table.rank_of(TokenId(0), TokenId(5)), Rank(286));
        assert_eq!(table.rank_of(TokenId(6), TokenId(0)), Rank(260));
        assert!(!table.is_parent_ordered());
    }

    /// Locks the adversarial tie table: every ordered pair over the base
    /// alphabet is present, all at rank zero, each minting a distinct id.
    #[test]
    fn all_pairs_tie_table_is_complete() {
        let table = all_pairs_tie_table(3).unwrap();
        assert_eq!(table.entry_count(), 9);
        assert_eq!(table.universe(), 12);
        let mut minted = Vec::new();
        for (pair, merge) in table.entries() {
            assert_eq!(merge.rank, Rank(0));
            assert!(pair.left().0 < 3 && pair.right().0 < 3);
            minted.push(merge.id.0);
        }
        assert_eq!(minted, vec![3, 4, 5, 6, 7, 8, 9, 10, 11]);
        assert!(table.is_parent_ordered());
    }

    /// Locks the cascade table's shape: one entry per level, rank equal to the
    /// level, parent ordered. The pass-count proof reads these numbers directly.
    #[test]
    fn cascade_table_has_one_entry_per_level() {
        let table = cascade_table(4).unwrap();
        assert_eq!(table.entry_count(), 4);
        assert_eq!(table.universe(), 5);
        for level in 0..4 {
            assert_eq!(
                table.lookup(TokenId(level), TokenId(level)),
                Some(Merge {
                    id: TokenId(level + 1),
                    rank: Rank(level)
                })
            );
        }
        assert!(table.is_parent_ordered());
        assert_eq!(cascade_table(0).unwrap().entry_count(), 0);
    }

    /// Locks classification of an agreeing case as `None` and of the known
    /// counterexample as a final-token divergence. A classifier reporting
    /// agreement on the counterexample would hide every real failure.
    #[test]
    fn classify_separates_agreement_from_divergence() {
        let good = cascade_table(3).unwrap();
        assert_eq!(classify(&ids(&[0, 0, 0, 0]), &good), None);

        let bad = MergeTable::from_raw(3, &[(0, 0, 1, 1), (1, 0, 2, 0)]).unwrap();
        assert_eq!(
            classify(&ids(&[0, 0, 0, 0]), &bad),
            Some(DivergenceKind::FinalTokens)
        );
    }

    /// Locks the minimizer: it shrinks a padded, inflated divergence back to the
    /// four-token, two-entry, rank-0-and-1 core without changing the failure
    /// class. A minimizer that loses the divergence or reports a different class
    /// makes counterexample reports untrustworthy.
    #[test]
    fn minimizer_shrinks_to_the_known_core() {
        let padded = MergeTable::from_raw(
            6,
            &[
                (0, 0, 1, 40),
                (1, 0, 2, 10),
                (4, 4, 5, 70),
                (3, 3, 4, 60),
                (2, 2, 3, 50),
            ],
        )
        .unwrap();
        let found = Divergence::capture(&ids(&[0, 0, 0, 0, 0, 0]), &padded).unwrap();
        assert_eq!(found.kind, DivergenceKind::FinalTokens);

        let small = minimize(found);
        assert_eq!(small.kind, DivergenceKind::FinalTokens);
        assert_eq!(small.input, ids(&[0, 0, 0, 0]));
        assert_eq!(small.table.entry_count(), 2);
        assert_eq!(
            small.table.lookup(TokenId(0), TokenId(0)),
            Some(Merge {
                id: TokenId(1),
                rank: Rank(1)
            })
        );
        assert_eq!(
            small.table.lookup(TokenId(1), TokenId(0)),
            Some(Merge {
                id: TokenId(2),
                rank: Rank(0)
            })
        );
        assert_eq!(small.sequential, ids(&[2, 0]));
        assert_eq!(small.multi, ids(&[1, 1]));
        assert_eq!(small.violations.len(), 1);
    }
}