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
//! Vocabulary and merge-table loading. OWNER: VocabLoad.
//!
//! Loads `.tiktoken` (base64 token, rank per line) and HuggingFace
//! `vocab.json` + `merges.txt` into a rank table keyed by
//! [`crate::PairKey`]. Owns special-token registration.
//!
//! Acceptance: `cl100k_base` and `gpt2` load with exact vocabulary sizes and
//! known id lookups asserted against published values.
//!
//! # The two formats are structurally different, not just spelled differently
//!
//! A `.tiktoken` file holds `token_bytes -> rank` and no pairs at all, so the
//! pair table must be **derived**. A HuggingFace `merges.txt` states the pair
//! outright and its line order *is* the rank, with the id coming from
//! `vocab.json` independently. The two loaders therefore do genuinely different
//! work and are deliberately not forced through one code path.
//!
//! Because tiktoken conflates rank and id into one column while HuggingFace
//! keeps them apart, [`crate::reference::MergeEntry`] carries `id` and `rank`
//! as separate fields even where a format happens to make them equal. That
//! stops the tiktoken path teaching the HuggingFace path a false identity.
//!
//! # Deriving pairs from a `.tiktoken` file
//!
//! At runtime tiktoken merges two adjacent pieces by looking up the *bytes of
//! their concatenation*. Adjacent pieces are always themselves vocabulary
//! tokens, so a pair `(a, b)` is mergeable exactly when `a + b` is in the
//! vocabulary. The derivation must therefore enumerate **every** split
//! `t = a + b` with both halves in the vocabulary and emit
//! `(id(a), id(b)) -> (id(t), rank(t))`.
//!
//! Recording only the one canonical split that BPE would have used to build `t`
//! is the tempting shortcut and it is wrong. Real example from `cl100k_base`:
//! token `ing` has id 287 and two valid splits, `i`(72) + `ng`(983) and
//! `in`(258) + `g`(70). Canonical derivation keeps only `in` + `g`, so a
//! sequence that ever holds `i` next to `ng` would fail to merge and diverge
//! from the reference ids. `merges.txt` lists only the canonical pair, which is
//! why the HuggingFace table is legitimately smaller than the tiktoken one for
//! the same vocabulary.
//!
//! # What these files do and do not contain
//!
//! Verified against the real `cl100k_base`, `o200k_base`, `p50k_base` and
//! `r50k_base` rank files:
//!
//! - The 256 raw single-byte tokens **are** present as ordinary lines, at ranks
//!   0..=255. They must not be synthesized, or every rank above them shifts.
//! - Special tokens are **not** in the file. They are registered separately.
//! - Ranks are not necessarily contiguous: `p50k_base` has 50280 entries whose
//!   maximum rank is 50280, because 50256 is reserved for `<|endoftext|>`.
//!   Nothing here may index an array by raw token id without tolerating holes.
//! - `n_vocab` is not entries plus specials: `cl100k_base` leaves 16 reserved
//!   ids unused between the two.

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fs;
use std::path::{Path, PathBuf};

use crate::byte_encoder;
use crate::pretokenize::SplitPattern;
use crate::reference::{HostMergeTable, MergeEntry, MergeTable};
use crate::{PairKey, Rank, TokenId, ExatokError};

/// Highest token id a vocabulary may declare.
///
/// `vyre_primitives::hash::table` reserves `u32::MAX` as `EMPTY_KEY` and
/// `u32::MAX - 1` as `RESERVED_KEY`, and [`Rank::ABSENT`] is `u32::MAX`. A
/// token id at or above this bound could not be distinguished from a table
/// sentinel once uploaded to the device.
pub const MAX_TOKEN_ID: u32 = u32::MAX - 2;

/// Slack allowed between the entry count and the highest token id.
///
/// Real vocabularies are dense, give or take a reserved hole. A file claiming
/// id four billion for its second token would otherwise make the reverse
/// lookup table allocate until the process dies, so an implausibly sparse id
/// space is reported as a malformed artifact instead.
const MAX_ID_SPARSITY: usize = 4;

/// Extra headroom added to the sparsity bound for small vocabularies.
const SPARSITY_FLOOR: usize = 1024;

/// A named artifact and its text, so every parse error can cite its source.
#[derive(Debug, Clone, Copy)]
pub struct Source<'a> {
    /// Artifact name reported in errors, for example `cl100k_base.tiktoken`.
    pub name: &'a str,
    /// Full artifact contents.
    pub text: &'a str,
}

impl<'a> Source<'a> {
    /// Name `text` so parse failures can point at it.
    #[must_use]
    pub const fn new(name: &'a str, text: &'a str) -> Self {
        Self { name, text }
    }
}

/// A loaded vocabulary and its derived pair table.
///
/// Implements [`MergeTable`] so a loaded vocabulary drives
/// [`crate::reference::encode`] directly.
#[derive(Debug, Clone, Default)]
pub struct Vocabulary {
    /// Ordinary tokens by id. An empty slot is an id the vocabulary skips;
    /// a zero-length token is never legal, so empty is an unambiguous hole.
    by_id: Vec<Vec<u8>>,
    /// Ordinary tokens by bytes.
    by_bytes: HashMap<Vec<u8>, TokenId>,
    /// Derived pair table, owned by `reference` so there is one table type.
    merges: HostMergeTable,
    /// Special tokens, kept out of `by_id` and `by_bytes` on purpose.
    specials: Vec<(String, TokenId)>,
}

fn artifact_error(artifact: &str, location: String, detail: String, fix: &str) -> ExatokError {
    ExatokError::Artifact {
        artifact: artifact.to_owned(),
        location,
        detail,
        fix: fix.to_owned(),
    }
}

fn line_error(artifact: &str, line: usize, detail: String, fix: &str) -> ExatokError {
    artifact_error(artifact, format!("line {line}"), detail, fix)
}

/// Insert one merge, adding the artifact line to whatever the table reports.
///
/// [`HostMergeTable::insert`] already rejects duplicate pairs and the
/// [`Rank::ABSENT`] sentinel, and it names the pair. Loading additionally knows
/// which line the pair came from, which is the part a person needs to fix the
/// file, so the location is prefixed rather than a second check being written.
fn insert_merge(
    table: &mut HostMergeTable,
    artifact: &str,
    line: usize,
    pair: PairKey,
    merged: TokenId,
    rank: Rank,
) -> Result<(), ExatokError> {
    table
        .insert(artifact, pair, merged, rank)
        .map_err(|error| match error {
            ExatokError::Artifact {
                artifact,
                location,
                detail,
                fix,
            } => ExatokError::Artifact {
                artifact,
                location: format!("line {line}, {location}"),
                detail,
                fix,
            },
            other => other,
        })
}

/// Resolve both halves of a stated merge to their token ids.
fn resolve_halves(
    by_bytes: &HashMap<Vec<u8>, TokenId>,
    artifact: &str,
    line: usize,
    left: &[u8],
    right: &[u8],
) -> Result<PairKey, ExatokError> {
    let lookup = |half: &[u8], side: &str| -> Result<TokenId, ExatokError> {
        by_bytes.get(half).copied().ok_or_else(|| {
            line_error(
                artifact,
                line,
                format!(
                    "{side} half {:?} is not in the vocabulary",
                    byte_encoder::encode(half)
                ),
                "every merge half must itself be a vocabulary token; the \
                 vocabulary and the merge list are out of sync",
            )
        })
    };
    Ok(PairKey::new(lookup(left, "left")?, lookup(right, "right")?))
}

/// Build the id and byte indexes, rejecting duplicates and absurd id spaces.
fn index_tokens(
    artifact: &str,
    tokens: &[(TokenId, Vec<u8>)],
) -> Result<(Vec<Vec<u8>>, HashMap<Vec<u8>, TokenId>), ExatokError> {
    let highest = tokens.iter().map(|(id, _)| id.0).max().unwrap_or(0);
    let needed = highest as usize + 1;
    let allowed = tokens
        .len()
        .saturating_mul(MAX_ID_SPARSITY)
        .saturating_add(SPARSITY_FLOOR);
    if needed > allowed {
        return Err(artifact_error(
            artifact,
            format!("token id {highest}"),
            format!(
                "{} tokens span {needed} ids, more than the {allowed} an id space \
                 this dense may occupy",
                tokens.len()
            ),
            "check the id column: real vocabularies are dense apart from a few \
             reserved holes",
        ));
    }

    let mut by_id: Vec<Vec<u8>> = vec![Vec::new(); needed];
    let mut by_bytes: HashMap<Vec<u8>, TokenId> = HashMap::with_capacity(tokens.len());
    for (id, bytes) in tokens {
        match by_bytes.entry(bytes.clone()) {
            Entry::Occupied(occupied) => {
                return Err(artifact_error(
                    artifact,
                    format!("token id {}", id.0),
                    format!(
                        "token {:?} is already defined with id {}",
                        byte_encoder::encode(bytes),
                        occupied.get().0
                    ),
                    "each token may appear once; drop the duplicate entry",
                ));
            }
            Entry::Vacant(vacant) => {
                vacant.insert(*id);
            }
        }
        by_id[id.0 as usize] = bytes.clone();
    }
    Ok((by_id, by_bytes))
}

impl Vocabulary {
    /// Load a `.tiktoken` rank file.
    ///
    /// Each line is `base64(token_bytes) rank`, where the rank column is both
    /// the token id and the merge rank. Pairs are derived by enumerating every
    /// split of every token whose halves are both in the vocabulary.
    pub fn load_tiktoken(source: Source<'_>) -> Result<Self, ExatokError> {
        let mut tokens: Vec<(TokenId, Vec<u8>)> = Vec::new();
        let mut rank_lines: HashMap<u32, usize> = HashMap::new();
        let mut token_lines: HashMap<Vec<u8>, usize> = HashMap::new();

        for (index, line) in source.text.lines().enumerate() {
            let number = index + 1;

            if line.is_empty() {
                return Err(line_error(
                    source.name,
                    number,
                    "line is empty".to_owned(),
                    "delete the blank line; every line must be `base64(token) rank`",
                ));
            }

            let Some((encoded, rank_text)) = line.split_once(' ') else {
                return Err(line_error(
                    source.name,
                    number,
                    format!("no space separator in {line:?}, so the rank column is missing"),
                    "write the line as `base64(token) rank` with exactly one space",
                ));
            };

            if rank_text.contains(' ') {
                return Err(line_error(
                    source.name,
                    number,
                    format!("more than two columns: rank field is {rank_text:?}"),
                    "a token line has exactly two space separated columns",
                ));
            }

            let token = decode_base64(encoded).map_err(|detail| {
                line_error(
                    source.name,
                    number,
                    detail,
                    "re-export the artifact; the token column must be standard padded base64",
                )
            })?;

            if token.is_empty() {
                return Err(line_error(
                    source.name,
                    number,
                    "token decodes to zero bytes".to_owned(),
                    "remove the entry; a vocabulary token must have at least one byte",
                ));
            }

            let rank: u32 = rank_text.parse().map_err(|_| {
                line_error(
                    source.name,
                    number,
                    format!("rank {rank_text:?} is not a 32-bit unsigned integer"),
                    "the rank column must be a plain non-negative decimal integer",
                )
            })?;

            if rank > MAX_TOKEN_ID {
                return Err(line_error(
                    source.name,
                    number,
                    format!("rank {rank} exceeds the maximum token id {MAX_TOKEN_ID}"),
                    "token ids must stay below the reserved device hash-table sentinels",
                ));
            }

            if let Some(previous) = rank_lines.insert(rank, number) {
                return Err(line_error(
                    source.name,
                    number,
                    format!("rank {rank} was already used on line {previous}"),
                    "ranks are token ids and must be unique; drop the duplicate entry",
                ));
            }

            if let Some(previous) = token_lines.insert(token.clone(), number) {
                return Err(line_error(
                    source.name,
                    number,
                    format!(
                        "token {:?} was already defined on line {previous}",
                        byte_encoder::encode(&token)
                    ),
                    "each token may appear once; drop the duplicate entry",
                ));
            }

            tokens.push((TokenId(rank), token));
        }

        if tokens.is_empty() {
            return Err(artifact_error(
                source.name,
                "whole file".to_owned(),
                "no token lines found".to_owned(),
                "supply a rank file with at least one `base64(token) rank` line",
            ));
        }

        let (by_id, by_bytes) = index_tokens(source.name, &tokens)?;

        // Ascending id order makes error reporting deterministic. The table
        // itself is key-ordered, so insertion order never reaches the device.
        tokens.sort_unstable_by_key(|(id, _)| id.0);

        let mut merges = HostMergeTable::new();
        for (id, token) in &tokens {
            if token.len() < 2 {
                continue;
            }
            let line = token_lines.get(token).copied().unwrap_or(0);
            let mut splits = 0usize;
            for cut in 1..token.len() {
                let (left, right) = token.split_at(cut);
                let (Some(&left_id), Some(&right_id)) =
                    (by_bytes.get(left), by_bytes.get(right))
                else {
                    continue;
                };
                insert_merge(
                    &mut merges,
                    source.name,
                    line,
                    PairKey::new(left_id, right_id),
                    *id,
                    Rank(id.0),
                )?;
                splits += 1;
            }
            if splits == 0 {
                return Err(line_error(
                    source.name,
                    line,
                    format!(
                        "token {:?} has no split whose halves are both in the vocabulary",
                        byte_encoder::encode(token)
                    ),
                    "the file is incomplete: a multi-byte token BPE can never build is \
                     unreachable, so a cheaper token it needs is missing",
                ));
            }
        }

        Ok(Self {
            by_id,
            by_bytes,
            merges,
            specials: Vec::new(),
        })
    }

    /// Load a `.tiktoken` rank file from disk.
    pub fn load_tiktoken_path(path: &Path) -> Result<Self, ExatokError> {
        let name = path.display().to_string();
        let text = read_artifact(&name, path)?;
        Self::load_tiktoken(Source::new(&name, &text))
    }

    /// Load a HuggingFace `vocab.json` plus `merges.txt`.
    ///
    /// `specials` names the entries in `vocab.json` that are special tokens.
    /// They are registered separately and excluded from merge resolution.
    pub fn load_huggingface(
        vocab: Source<'_>,
        merges: Source<'_>,
        specials: &[&str],
    ) -> Result<Self, ExatokError> {
        let parsed = parse_vocab_json(vocab)?;
        let merge_lines = split_merges_txt(merges)?;
        // No declared ids in this format: each special's id comes from
        // `vocab.json`, so it must be named there.
        let specials: Vec<(String, Option<TokenId>)> = specials
            .iter()
            .map(|name| ((*name).to_owned(), None))
            .collect();
        Self::from_huggingface_parts(vocab.name, &parsed, merges.name, &merge_lines, &specials)
    }

    /// Load a HuggingFace `tokenizer.json` bundle.
    ///
    /// `model.vocab` and `model.merges` carry exactly the `vocab.json` and
    /// `merges.txt` content, so this delegates to the same builder rather than
    /// duplicating it.
    ///
    /// `model.merges` is accepted in both published shapes: the older
    /// `"left right"` strings and the `["left", "right"]` arrays that
    /// `tokenizers` 0.20 and later emit. Array halves are joined with a space,
    /// which is lossless because a byte-encoded half can never contain one: a
    /// literal space is written `Ä `.
    ///
    /// `added_tokens` is authoritative for special-token ids. Added tokens are
    /// normally added ON TOP of `model.vocab`, so a real file may list a special
    /// only there; registering only the ones that also appear in `model.vocab`
    /// would drop those silently. Specials register in `added_tokens` order.
    pub fn load_tokenizer_json(source: Source<'_>) -> Result<Self, ExatokError> {
        let root: serde_json::Value = serde_json::from_str(source.text).map_err(|error| {
            artifact_error(
                source.name,
                format!("line {}, column {}", error.line(), error.column()),
                format!("invalid JSON: {error}"),
                "repair the JSON; tokenizer.json must be a single JSON object",
            )
        })?;

        let missing = |field: &str| {
            artifact_error(
                source.name,
                format!("field {field}"),
                format!("{field} is missing or has the wrong type"),
                "supply a BPE tokenizer.json with model.vocab and model.merges",
            )
        };

        let model = root.get("model").ok_or_else(|| missing("model"))?;
        let vocab_object = model
            .get("vocab")
            .and_then(serde_json::Value::as_object)
            .ok_or_else(|| missing("model.vocab"))?;
        let merge_array = model
            .get("merges")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| missing("model.merges"))?;

        let mut parsed = Vec::with_capacity(vocab_object.len());
        for (token, id) in vocab_object {
            parsed.push((token.clone(), vocab_id(source.name, token, id)?));
        }

        let mut merge_lines = Vec::with_capacity(merge_array.len());
        for (index, entry) in merge_array.iter().enumerate() {
            let number = index + 1;
            let line = match entry {
                serde_json::Value::String(text) => text.clone(),
                serde_json::Value::Array(halves) => {
                    let [left, right] = halves.as_slice() else {
                        return Err(line_error(
                            source.name,
                            number,
                            format!(
                                "model.merges entry {index} is an array of {} elements, \
                                 expected exactly 2",
                                halves.len()
                            ),
                            "an array-form merge must be [\"left\", \"right\"]",
                        ));
                    };
                    let (Some(left), Some(right)) = (left.as_str(), right.as_str()) else {
                        return Err(line_error(
                            source.name,
                            number,
                            format!(
                                "model.merges entry {index} has a non-string half: \
                                 [{left}, {right}]"
                            ),
                            "both halves of an array-form merge must be strings",
                        ));
                    };
                    format!("{left} {right}")
                }
                other => {
                    return Err(line_error(
                        source.name,
                        number,
                        format!(
                            "model.merges entry {index} is {other}, expected \
                             \"left right\" or [\"left\", \"right\"]"
                        ),
                        "each merge must be a space separated string or a two element array",
                    ));
                }
            };
            merge_lines.push((number, line));
        }

        let mut specials: Vec<(String, Option<TokenId>)> = Vec::new();
        if let Some(added) = root.get("added_tokens").and_then(serde_json::Value::as_array) {
            for entry in added {
                let Some(content) = entry.get("content").and_then(serde_json::Value::as_str)
                else {
                    continue;
                };
                let declared = match entry.get("id") {
                    Some(value) => Some(TokenId(vocab_id(source.name, content, value)?)),
                    None => None,
                };
                specials.push((content.to_owned(), declared));
            }
        }

        Self::from_huggingface_parts(
            source.name,
            &parsed,
            source.name,
            &merge_lines,
            &specials,
        )
    }

    fn from_huggingface_parts(
        vocab_name: &str,
        parsed: &[(String, u32)],
        merges_name: &str,
        merge_lines: &[(usize, String)],
        specials: &[(String, Option<TokenId>)],
    ) -> Result<Self, ExatokError> {
        let mut tokens: Vec<(TokenId, Vec<u8>)> = Vec::with_capacity(parsed.len());
        let mut special_vocab_ids: Vec<(String, TokenId)> = Vec::new();

        for (token, id) in parsed {
            if *id > MAX_TOKEN_ID {
                return Err(artifact_error(
                    vocab_name,
                    format!("token {token:?}"),
                    format!("id {id} exceeds the maximum token id {MAX_TOKEN_ID}"),
                    "token ids must stay below the reserved device hash-table sentinels",
                ));
            }
            if specials.iter().any(|(name, _)| name == token) {
                special_vocab_ids.push((token.clone(), TokenId(*id)));
                continue;
            }
            let bytes = byte_encoder::decode(token).map_err(|bad| {
                artifact_error(
                    vocab_name,
                    format!("token {token:?}, character {}", bad.char_index),
                    format!(
                        "character {:?} is not in the GPT-2 byte alphabet",
                        bad.character
                    ),
                    "token strings must be byte-encoded, so a literal space is `Ä `; \
                     list a genuine special token in the specials argument instead",
                )
            })?;
            if bytes.is_empty() {
                return Err(artifact_error(
                    vocab_name,
                    format!("token {token:?}"),
                    "token decodes to zero bytes".to_owned(),
                    "remove the entry; a vocabulary token must have at least one byte",
                ));
            }
            tokens.push((TokenId(*id), bytes));
        }

        if tokens.is_empty() {
            return Err(artifact_error(
                vocab_name,
                "whole file".to_owned(),
                "no ordinary tokens found".to_owned(),
                "vocab.json must map at least one token string to an id",
            ));
        }

        let (by_id, by_bytes) = index_tokens(vocab_name, &tokens)?;

        let mut merges = HostMergeTable::new();
        for (rank, (number, line)) in merge_lines.iter().enumerate() {
            let Some((left_text, right_text)) = line.split_once(' ') else {
                return Err(line_error(
                    merges_name,
                    *number,
                    format!("no space separator in {line:?}, so the pair is incomplete"),
                    "write the line as `left right` with exactly one space",
                ));
            };
            if right_text.contains(' ') {
                return Err(line_error(
                    merges_name,
                    *number,
                    format!("more than two columns: right half is {right_text:?}"),
                    "a merge line has exactly two space separated halves; \
                     a literal space inside a half must be written `Ä `",
                ));
            }

            let decode_half = |text: &str| -> Result<Vec<u8>, ExatokError> {
                byte_encoder::decode(text).map_err(|bad| {
                    line_error(
                        merges_name,
                        *number,
                        format!(
                            "character {:?} at position {} of {text:?} is not in the \
                             GPT-2 byte alphabet",
                            bad.character, bad.char_index
                        ),
                        "merge halves must be byte-encoded token strings",
                    )
                })
            };
            let left = decode_half(left_text)?;
            let right = decode_half(right_text)?;

            let pair = resolve_halves(&by_bytes, merges_name, *number, &left, &right)?;

            let mut merged_bytes = Vec::with_capacity(left.len() + right.len());
            merged_bytes.extend_from_slice(&left);
            merged_bytes.extend_from_slice(&right);
            let Some(&merged) = by_bytes.get(merged_bytes.as_slice()) else {
                return Err(line_error(
                    merges_name,
                    *number,
                    format!(
                        "merge result {:?} is not in the vocabulary",
                        byte_encoder::encode(&merged_bytes)
                    ),
                    "vocab.json and merges.txt are out of sync: every merge must \
                     produce a token that vocab.json defines",
                ));
            };

            let rank = u32::try_from(rank).map_err(|_| {
                line_error(
                    merges_name,
                    *number,
                    "more merges than a 32-bit rank can number".to_owned(),
                    "ranks must fit in u32 to reach the device",
                )
            })?;

            // Line order is the rank, 0-based from the first real merge line.
            insert_merge(
                &mut merges,
                merges_name,
                *number,
                pair,
                merged,
                Rank(rank),
            )?;
        }

        let mut vocabulary = Self {
            by_id,
            by_bytes,
            merges,
            specials: Vec::new(),
        };
        for (name, declared) in specials {
            let from_vocab = special_vocab_ids
                .iter()
                .find(|(other, _)| other == name)
                .map(|(_, id)| *id);
            let resolved = match (*declared, from_vocab) {
                (Some(added), Some(in_vocab)) if added != in_vocab => {
                    return Err(artifact_error(
                        vocab_name,
                        format!("special token {name:?}"),
                        format!(
                            "added_tokens gives id {} but the vocabulary gives id {}",
                            added.0, in_vocab.0
                        ),
                        "make the two ids agree; a special token has exactly one id",
                    ));
                }
                (Some(id), _) | (None, Some(id)) => id,
                (None, None) => {
                    return Err(artifact_error(
                        vocab_name,
                        format!("special token {name:?}"),
                        "has no id: absent from the vocabulary and no added_tokens id"
                            .to_owned(),
                        "give the special token an id in added_tokens, or name only \
                         specials that the vocabulary defines",
                    ));
                }
            };
            vocabulary.register_special(name, resolved)?;
        }
        Ok(vocabulary)
    }

    /// Load a HuggingFace `tokenizer.json` bundle from disk.
    pub fn load_tokenizer_json_path(path: &Path) -> Result<Self, ExatokError> {
        let name = path.display().to_string();
        let text = read_artifact(&name, path)?;
        Self::load_tokenizer_json(Source::new(&name, &text))
    }

    /// Register a special token, which lives outside the ordinary vocabulary.
    pub fn register_special(&mut self, text: &str, id: TokenId) -> Result<(), ExatokError> {
        let location = || format!("special token {text:?}");
        if id.0 > MAX_TOKEN_ID {
            return Err(artifact_error(
                "special tokens",
                location(),
                format!("id {} exceeds the maximum token id {MAX_TOKEN_ID}", id.0),
                "token ids must stay below the reserved device hash-table sentinels",
            ));
        }
        if let Some((existing, _)) = self.specials.iter().find(|(name, _)| name == text) {
            return Err(artifact_error(
                "special tokens",
                location(),
                format!("{existing:?} is already registered"),
                "register each special token once",
            ));
        }
        if let Some((name, _)) = self.specials.iter().find(|(_, other)| *other == id) {
            return Err(artifact_error(
                "special tokens",
                location(),
                format!("id {} is already held by special token {name:?}", id.0),
                "give each special token a distinct id",
            ));
        }
        if let Some(bytes) = self.bytes_of(id) {
            return Err(artifact_error(
                "special tokens",
                location(),
                format!(
                    "id {} is already held by ordinary token {:?}",
                    id.0,
                    byte_encoder::encode(bytes)
                ),
                "special token ids must not collide with the ordinary vocabulary",
            ));
        }
        self.specials.push((text.to_owned(), id));
        Ok(())
    }

    /// Number of ordinary tokens.
    #[must_use]
    pub fn len(&self) -> usize {
        self.by_bytes.len()
    }

    /// True when no ordinary token is loaded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.by_bytes.is_empty()
    }

    /// Number of registered special tokens.
    #[must_use]
    pub fn special_len(&self) -> usize {
        self.specials.len()
    }

    /// Highest id in use plus one, across ordinary and special tokens.
    ///
    /// This is not `len() + special_len()`: real vocabularies leave reserved
    /// ids unused between the two.
    #[must_use]
    pub fn n_vocab(&self) -> usize {
        let highest_special = self.specials.iter().map(|(_, id)| id.0 as usize + 1).max();
        self.by_id.len().max(highest_special.unwrap_or(0))
    }

    /// Id of an ordinary token, by its raw bytes.
    #[must_use]
    pub fn id_of(&self, bytes: &[u8]) -> Option<TokenId> {
        self.by_bytes.get(bytes).copied()
    }

    /// Raw bytes of an ordinary token, by id.
    #[must_use]
    pub fn bytes_of(&self, id: TokenId) -> Option<&[u8]> {
        self.by_id
            .get(id.0 as usize)
            .filter(|bytes| !bytes.is_empty())
            .map(Vec::as_slice)
    }

    /// Id of a registered special token.
    #[must_use]
    pub fn special_id(&self, text: &str) -> Option<TokenId> {
        self.specials
            .iter()
            .find(|(name, _)| name == text)
            .map(|(_, id)| *id)
    }

    /// Registered special tokens, in registration order.
    pub fn specials(&self) -> impl Iterator<Item = (&str, TokenId)> {
        self.specials.iter().map(|(name, id)| (name.as_str(), *id))
    }

    /// The derived pair table.
    #[must_use]
    pub const fn merge_table(&self) -> &HostMergeTable {
        &self.merges
    }

    /// Number of derived merges.
    #[must_use]
    pub fn merge_count(&self) -> usize {
        self.merges.len()
    }

    /// Highest ordinary token id in use.
    #[must_use]
    pub fn max_token_id(&self) -> Option<TokenId> {
        self.by_id
            .iter()
            .enumerate()
            .rev()
            .find(|(_, bytes)| !bytes.is_empty())
            .and_then(|(index, _)| u32::try_from(index).ok())
            .map(TokenId)
    }
}

impl MergeTable for Vocabulary {
    fn lookup(&self, pair: PairKey) -> Option<MergeEntry> {
        self.merges.lookup(pair)
    }
}

/// Sentinel for a byte that is not a base64 alphabet character.
const BASE64_INVALID: u8 = 0xFF;

const fn build_base64_reverse() -> [u8; 256] {
    let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut table = [BASE64_INVALID; 256];
    let mut index = 0usize;
    while index < alphabet.len() {
        table[alphabet[index] as usize] = index as u8;
        index += 1;
    }
    table
}

const BASE64_REVERSE: [u8; 256] = build_base64_reverse();

/// Decode standard padded base64, rejecting anything malformed.
///
/// Hand-rolled rather than pulled in as a dependency: the alphabet is 64
/// characters wide and the function is total, so it can be tested exhaustively
/// over all 256 byte values. Errors carry the offending index so an artifact
/// loader can name the line.
fn decode_base64(text: &str) -> Result<Vec<u8>, String> {
    let bytes = text.as_bytes();
    if bytes.is_empty() {
        return Err("token column is empty".to_owned());
    }
    if bytes.len() % 4 != 0 {
        return Err(format!(
            "base64 length {} is not a multiple of 4",
            bytes.len()
        ));
    }

    let blocks = bytes.len() / 4;
    let mut out = Vec::with_capacity(blocks * 3);

    for block in 0..blocks {
        let start = block * 4;
        let is_last = block + 1 == blocks;
        let mut sextets = [0u8; 4];
        let mut padding = 0usize;

        for slot in 0..4 {
            let at = start + slot;
            let character = bytes[at];

            if character == b'=' {
                if !is_last {
                    return Err(format!(
                        "base64 padding '=' at index {at} is not in the final block"
                    ));
                }
                if slot < 2 {
                    return Err(format!(
                        "base64 padding '=' at index {at} would leave no data byte"
                    ));
                }
                padding += 1;
                continue;
            }

            if padding > 0 {
                return Err(format!(
                    "base64 byte 0x{character:02x} at index {at} follows padding"
                ));
            }

            let value = BASE64_REVERSE[character as usize];
            if value == BASE64_INVALID {
                return Err(format!(
                    "invalid base64 byte 0x{character:02x} at index {at}"
                ));
            }
            sextets[slot] = value;
        }

        let triple = (u32::from(sextets[0]) << 18)
            | (u32::from(sextets[1]) << 12)
            | (u32::from(sextets[2]) << 6)
            | u32::from(sextets[3]);

        out.push((triple >> 16) as u8);
        if padding < 2 {
            out.push((triple >> 8) as u8);
        }
        if padding < 1 {
            out.push(triple as u8);
        }
    }

    Ok(out)
}

fn vocab_id(artifact: &str, token: &str, value: &serde_json::Value) -> Result<u32, ExatokError> {
    let Some(number) = value.as_u64() else {
        return Err(artifact_error(
            artifact,
            format!("token {token:?}"),
            format!("id {value} is not a non-negative integer"),
            "vocab.json must map every token string to a non-negative integer id",
        ));
    };
    u32::try_from(number).map_err(|_| {
        artifact_error(
            artifact,
            format!("token {token:?}"),
            format!("id {number} does not fit in 32 bits"),
            "token ids must fit in u32 to reach the device",
        )
    })
}

/// Parse a `vocab.json` object into token/id pairs.
///
/// `serde_json` does the string decoding on purpose. `vocab.json` escapes
/// exactly the codepoints the GPT-2 byte alphabet uses, `\u0120` for a leading
/// space among them, and a hand-rolled parser that mishandled a surrogate pair
/// would produce a wrong token string, hence a wrong id, silently.
///
/// Locations name the token rather than a line: a real `vocab.json` is a single
/// line, so a line number would identify nothing.
fn parse_vocab_json(source: Source<'_>) -> Result<Vec<(String, u32)>, ExatokError> {
    let root: serde_json::Value = serde_json::from_str(source.text).map_err(|error| {
        artifact_error(
            source.name,
            format!("line {}, column {}", error.line(), error.column()),
            format!("invalid JSON: {error}"),
            "repair the JSON; vocab.json must be one object mapping token strings to ids",
        )
    })?;

    let Some(object) = root.as_object() else {
        return Err(artifact_error(
            source.name,
            "document root".to_owned(),
            "top level value is not a JSON object".to_owned(),
            "vocab.json must be a single object mapping token strings to integer ids",
        ));
    };

    let mut out = Vec::with_capacity(object.len());
    for (token, value) in object {
        out.push((token.clone(), vocab_id(source.name, token, value)?));
    }
    Ok(out)
}

/// Split `merges.txt` into numbered lines, dropping only the version header.
///
/// The header is recognized as the literal `#version` prefix on line 1 and
/// nothing else, because `#` is a self-mapping byte and a genuine merge line
/// may legitimately begin with it.
fn split_merges_txt(source: Source<'_>) -> Result<Vec<(usize, String)>, ExatokError> {
    let mut out = Vec::new();
    for (index, line) in source.text.lines().enumerate() {
        let number = index + 1;
        if number == 1 && line.starts_with("#version") {
            continue;
        }
        if line.is_empty() {
            return Err(line_error(
                source.name,
                number,
                "line is empty".to_owned(),
                "delete the blank line; every line must be `left right`",
            ));
        }
        out.push((number, line.to_owned()));
    }
    Ok(out)
}

fn read_artifact(name: &str, path: &Path) -> Result<String, ExatokError> {
    fs::read_to_string(path).map_err(|error| {
        artifact_error(
            name,
            "file read".to_owned(),
            format!("could not read the artifact: {error}"),
            "check the path and read permissions",
        )
    })
}

/// Environment variable that relocates the rank-artifact directory.
///
/// One name shared by the library, the CLI and every artifact-dependent test,
/// so a single export points all of them at the same directory.
pub const ARTIFACT_DIR_ENV: &str = "EXATOK_VOCAB_DIR";

/// Rank-artifact directory relative to `$HOME` when the override is unset.
pub const ARTIFACT_DIR_DEFAULT: &str = ".cache/exatok-vocab";

/// Directory the rank artifacts are read from.
#[must_use]
pub fn artifact_dir() -> PathBuf {
    match std::env::var_os(ARTIFACT_DIR_ENV) {
        Some(dir) => PathBuf::from(dir),
        None => {
            let home = std::env::var_os("HOME").map_or_else(PathBuf::new, PathBuf::from);
            home.join(ARTIFACT_DIR_DEFAULT)
        }
    }
}

/// One vocabulary this crate ships by name, with its pinned counts.
///
/// `tokens` and `pairs` are pinned counts, not hints. A loader that dropped
/// non-canonical splits still produces a table that encodes most inputs
/// correctly, so the entry count is the only cheap check that catches a
/// silently incomplete derivation before an id comparison does.
///
/// This is a product type, not a test fixture descriptor: `exatok --vocab
/// cl100k_base` resolves through it. The fixture file that holds a vocabulary's
/// expected ids is the parity gate's concern and lives there, in
/// [`crate::parity::fixture_name`], so the shipping path carries no knowledge of
/// the test corpus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NamedVocabulary {
    /// Artifact stem, for example `cl100k_base`.
    pub name: &'static str,
    /// Split pattern this vocabulary is used with.
    pub pattern: SplitPattern,
    /// Exact number of ordinary tokens in the artifact.
    pub tokens: usize,
    /// Exact number of derived pair entries.
    pub pairs: usize,
    /// Exact number of reference ids the 42 text cases encode to.
    ///
    /// Text cases only. The 8 byte cases add their own ids and are pinned
    /// separately, so this is not the whole fixture's id count.
    pub text_ids: usize,
}

impl NamedVocabulary {
    /// Where this vocabulary's rank artifact is expected on disk.
    #[must_use]
    pub fn artifact_path(self) -> PathBuf {
        artifact_dir().join(format!("{}.tiktoken", self.name))
    }
}

/// `cl100k_base`: GPT-4 era, its own split pattern, three-digit number cap.
pub const CL100K_BASE: NamedVocabulary = NamedVocabulary {
    name: "cl100k_base",
    pattern: SplitPattern::Cl100kBase,
    tokens: 100_256,
    pairs: 233_378,
    text_ids: 1_211,
};

/// `r50k_base`: GPT-2 era, the `gpt2` pattern, a densely numbered id space.
pub const R50K_BASE: NamedVocabulary = NamedVocabulary {
    name: "r50k_base",
    pattern: SplitPattern::Gpt2,
    tokens: 50_256,
    pairs: 108_299,
    text_ids: 1_500,
};

/// `p50k_base`: the same pattern as `r50k_base` over a *sparse* id space.
///
/// Rank 50256 is reserved for `<|endoftext|>` and absent from the file, so this
/// is the vocabulary where treating a token id as a dense array index silently
/// shifts every entry above the hole.
pub const P50K_BASE: NamedVocabulary = NamedVocabulary {
    name: "p50k_base",
    pattern: SplitPattern::Gpt2,
    tokens: 50_280,
    pairs: 108_599,
    text_ids: 1_331,
};

/// `o200k_base`: GPT-4o era, the third split pattern, four times the pairs.
pub const O200K_BASE: NamedVocabulary = NamedVocabulary {
    name: "o200k_base",
    pattern: SplitPattern::O200kBase,
    tokens: 199_998,
    pairs: 446_189,
    text_ids: 1_015,
};

/// Every vocabulary this crate ships by name, one per split pattern plus the
/// sparse case.
pub const NAMED_VOCABULARIES: [NamedVocabulary; 4] =
    [CL100K_BASE, R50K_BASE, P50K_BASE, O200K_BASE];

/// Result of looking for a rank artifact.
///
/// The three cases are distinguished so a caller can tell an unprovisioned
/// machine from a *broken* cache. Half a cache means an interrupted download or a
/// stale directory, and collapsing it into "absent" is how a test stops testing
/// and a CLI reports the wrong fix.
///
/// The line between them is drawn across the WHOLE directory, not one file. A
/// directory that holds no rank table at all was never provisioned, however it
/// came to exist, and calling that state incomplete sends an operator to repair
/// a machine that is merely fresh. A directory that holds one rank table and
/// not another is genuinely partial, and so is one holding a zero-length file
/// where a table belongs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Artifact {
    /// A usable rank file: it exists and is not empty.
    Present(PathBuf),
    /// No rank table at all was found, so nothing is provisioned.
    ///
    /// The directory may be absent or may exist holding none of them; the
    /// remedy is the same either way, which is why one state covers both.
    NoCache {
        /// Directory that was searched.
        dir: PathBuf,
        /// File that was expected inside it.
        path: PathBuf,
    },
    /// The cache holds a rank table, but not a usable one for this vocabulary.
    ///
    /// Either this file is absent while a sibling is there, or it is present
    /// and empty, which is what an interrupted download leaves behind. Both are
    /// a broken cache rather than an unprovisioned machine, and both are fixed
    /// by fetching this one artifact again.
    Incomplete {
        /// Directory that was searched.
        dir: PathBuf,
        /// File that was expected inside it.
        path: PathBuf,
    },
}

impl Artifact {
    /// Human-readable account of what was looked for and where.
    ///
    /// Always names the full path and the override variable, because a message
    /// that does not say which path it wanted is indistinguishable from a pass.
    ///
    /// Describes the artifact and says nothing about what the caller will do
    /// about it. The wording used to announce a SKIPPED parity gate, which was
    /// true of the gate and false of the CLI that also reads this type: a tool
    /// that refused to run did not skip anything. A message that reports someone
    /// else's subject sends the reader after the wrong problem.
    #[must_use]
    pub fn report(&self) -> String {
        match self {
            Self::Present(path) => format!("rank artifact present: {}", path.display()),
            // Verdict first, path as detail. These strings reach an operator
            // through both the CLI and every suite's skip reason, and a message
            // that restates the filesystem predicate behind a verdict goes
            // false as soon as the classifier gains a second route into the
            // same arm, which is exactly what happened to "the directory does
            // not exist" and to "{path} is absent while {dir} exists".
            Self::NoCache { dir, path } => format!(
                "nothing is provisioned: {} holds no tiktoken rank table at all, and none is at \
                 {}. Populate that directory, creating it if it is absent, or set \
                 {ARTIFACT_DIR_ENV} to a directory that already holds the tiktoken rank tables.",
                dir.display(),
                path.display()
            ),
            Self::Incomplete { dir, path } => format!(
                "the vocabulary cache is incomplete rather than absent: there is no usable rank \
                 artifact at {}, where a zero-length file counts as none. Fix: re-fetch that one \
                 artifact into {}, or point {ARTIFACT_DIR_ENV} at a complete directory.",
                path.display(),
                dir.display()
            ),
        }
    }
}

/// Whether `path` is a rank file this crate could actually load.
///
/// Existence is not enough, and the difference is not pedantic: a zero-length
/// file under the right name is what an interrupted download leaves behind, and
/// calling it present hands the failure to the loader, which reports "malformed
/// at whole file" from a place that no longer knows the cache was half written.
/// One stat answers both questions, so the accurate diagnosis is free.
///
/// Length is the whole check on purpose. Anything past it is parsing, which
/// belongs to [`load_tiktoken_path`] and its pinned counts, and a second parser
/// here would be a second answer to the same question.
fn usable_artifact(path: &Path) -> bool {
    std::fs::metadata(path).is_ok_and(|found| found.is_file() && found.len() > 0)
}

/// Look for `vocabulary`'s rank artifact under `dir`.
///
/// Takes the directory so the classification can be tested against a temporary
/// tree instead of mutating a process-wide environment variable, which would
/// race every other test in the same binary.
///
/// "Incomplete" is a claim about the CACHE and not about one file, so it is
/// decided by looking at every name the cache can hold. Deciding it from the
/// directory's existence alone, which is what this did, reported a fresh empty
/// directory as a half-populated one: the CLI then told the operator to repair
/// a cache that had never been written, and `tests/cli.rs` aborted its whole
/// suite as if the machine were broken.
///
/// # Empty must not mean absent
///
/// The three states are not three shades of the same answer, because their
/// CONSUMERS act differently: every parity suite SKIPS on [`Artifact::NoCache`]
/// and HALTS on [`Artifact::Incomplete`]. So a zero-length rank file, which is
/// what an interrupted download leaves behind, must never classify as absent.
/// Simplifying this function to "no usable file anywhere means nothing is
/// provisioned" reads as a tidy-up and silently converts a truncated artifact
/// into a skipped exactness gate, which is worse than the misrouting this
/// function was fixed for: that sent an operator to the wrong remedy, this
/// would send the suite proving the crate's one claim to no remedy at all.
/// Absent stays absent, and a broken cache stays loud.
#[must_use]
pub fn locate_in(dir: &Path, vocabulary: NamedVocabulary) -> Artifact {
    let path = dir.join(format!("{}.tiktoken", vocabulary.name));
    if usable_artifact(&path) {
        return Artifact::Present(path);
    }
    // A name that merely EXISTS counts as populating the cache, empty or not.
    // A zero-length table is a broken download rather than an absent one, and
    // every parity suite skips on `NoCache` while halting on `Incomplete`, so
    // letting an empty file fall through to "nothing is provisioned" would turn
    // a truncated artifact into a silently skipped exactness gate.
    let populated = NAMED_VOCABULARIES
        .iter()
        .any(|named| dir.join(format!("{}.tiktoken", named.name)).exists());
    let dir = dir.to_path_buf();
    if populated {
        Artifact::Incomplete { dir, path }
    } else {
        Artifact::NoCache { dir, path }
    }
}

/// Look for `vocabulary`'s rank artifact in [`artifact_dir`].
#[must_use]
pub fn locate(vocabulary: NamedVocabulary) -> Artifact {
    locate_in(&artifact_dir(), vocabulary)
}

/// Load `path` as a `.tiktoken` rank file and check its pinned entry counts.
///
/// The counts are checked here rather than in each caller so everything that
/// loads a named vocabulary gets the same incomplete-derivation guard.
///
/// # Errors
///
/// [`ExatokError::Artifact`] when the file will not parse, or when the token or
/// pair count differs from [`NamedVocabulary`].
pub fn load(vocabulary: NamedVocabulary, path: &Path) -> Result<Vocabulary, ExatokError> {
    let loaded = Vocabulary::load_tiktoken_path(path)?;
    let mismatch = |location: &str, detail: String| ExatokError::Artifact {
        artifact: vocabulary.name.to_owned(),
        location: location.to_owned(),
        detail,
        fix: "load the published rank file for this vocabulary, and derive a pair for EVERY \
              split whose halves are both in the vocabulary, not only the canonical one"
            .to_owned(),
    };
    if loaded.len() != vocabulary.tokens {
        return Err(mismatch(
            "token count",
            format!("expected {}, loaded {}", vocabulary.tokens, loaded.len()),
        ));
    }
    if loaded.merge_count() != vocabulary.pairs {
        return Err(mismatch(
            "derived pair count",
            format!(
                "expected {}, derived {}",
                vocabulary.pairs,
                loaded.merge_count()
            ),
        ));
    }
    Ok(loaded)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    /// Pins base64 decoding against vectors computed by hand.
    ///
    /// These exact strings appear in the synthetic fixtures and, for `IQ==`, at
    /// the head of every real `.tiktoken` file. A decoder that dropped or
    /// misplaced the final sextet would still return plausible bytes, so only
    /// known vectors catch it.
    #[test]
    fn base64_decodes_known_vectors() {
        assert_eq!(decode_base64("IQ=="), Ok(b"!".to_vec()));
        assert_eq!(decode_base64("YQ=="), Ok(b"a".to_vec()));
        assert_eq!(decode_base64("Yg=="), Ok(b"b".to_vec()));
        assert_eq!(decode_base64("Yw=="), Ok(b"c".to_vec()));
        assert_eq!(decode_base64("IA=="), Ok(b" ".to_vec()));
        assert_eq!(decode_base64("YWI="), Ok(b"ab".to_vec()));
        assert_eq!(decode_base64("IGE="), Ok(b" a".to_vec()));
        assert_eq!(decode_base64("IGFi"), Ok(b" ab".to_vec()));
        assert_eq!(decode_base64("IENvbnZleW9y"), Ok(b" Conveyor".to_vec()));
    }

    /// Proves the decoder is total and exact over every single byte value.
    ///
    /// Single-byte tokens are ranks 0..=255 of every real vocabulary, so a
    /// decoder that mangled one byte would corrupt one base token and every
    /// merge built on it.
    #[test]
    fn base64_round_trips_all_256_single_byte_tokens() {
        const ALPHABET: &[u8; 64] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        for byte in 0..=u8::MAX {
            let encoded = format!(
                "{}{}==",
                ALPHABET[(byte >> 2) as usize] as char,
                ALPHABET[((byte & 0b11) << 4) as usize] as char,
            );
            assert_eq!(
                decode_base64(&encoded),
                Ok(vec![byte]),
                "byte 0x{byte:02x} encoded as {encoded}"
            );
        }
    }

    /// Rejects every malformed base64 shape instead of guessing.
    ///
    /// A lenient decoder would turn a truncated artifact into short tokens that
    /// still load, producing a vocabulary that is wrong rather than absent.
    #[test]
    fn base64_rejects_malformed_input() {
        assert!(decode_base64("").is_err(), "empty");
        assert!(decode_base64("YQ=").is_err(), "length 3");
        assert!(decode_base64("YQ").is_err(), "length 2");
        assert!(decode_base64("YQ===").is_err(), "length 5");
        assert!(decode_base64("Y!==").is_err(), "invalid character");
        assert!(decode_base64("YQ==YQ==").is_err(), "padding mid stream");
        assert!(decode_base64("====").is_err(), "padding in slot 0");
        assert!(decode_base64("Y===").is_err(), "padding in slot 1");
        assert!(decode_base64("YQ=A").is_err(), "data after padding");

        let message = decode_base64("Y!==").unwrap_err();
        assert!(
            message.contains("index 1"),
            "error must locate the bad byte, got {message:?}"
        );
    }

    /// Locks the `#version` header rule to a literal line-1 prefix.
    ///
    /// `#` is a self-mapping byte, so `#` is a legal merge half. Skipping every
    /// line that starts with `#` would silently delete a real merge and shift
    /// every rank after it.
    #[test]
    fn merges_header_is_only_skipped_on_line_one() {
        let parsed =
            split_merges_txt(Source::new("merges.txt", "#version: 0.2\na b\n# Ä \n")).unwrap();
        assert_eq!(
            parsed,
            vec![(2, "a b".to_owned()), (3, "# Ä ".to_owned())],
            "only line 1 is a header; line 3 is a merge whose left half is '#'"
        );

        let no_header = split_merges_txt(Source::new("merges.txt", "a b\n")).unwrap();
        assert_eq!(no_header, vec![(1, "a b".to_owned())]);

        let later_version =
            split_merges_txt(Source::new("m.txt", "a b\n#version: 0.2\n")).unwrap();
        assert_eq!(
            later_version.len(),
            2,
            "a #version line below line 1 is data, not a header"
        );
    }

    /// A blank line in `merges.txt` is an error, never a skipped line.
    ///
    /// Silently skipping it would renumber every subsequent rank, changing
    /// merge precedence without any visible failure.
    #[test]
    fn blank_merge_line_is_reported_with_its_number() {
        let error = split_merges_txt(Source::new("merges.txt", "a b\n\nc d\n")).unwrap_err();
        let ExatokError::Artifact { location, .. } = &error else {
            panic!("expected an Artifact error, got {error:?}");
        };
        assert_eq!(location, "line 2");
    }

    /// The three artifact states must be told apart, not collapsed.
    ///
    /// Five situations, three states, and two of the boundaries between them
    /// were wrong. An absent directory and a directory holding nothing are both
    /// UNPROVISIONED: the second used to classify as incomplete, which told an
    /// operator to repair a cache that had never been written and, through
    /// `tests/cli.rs`, aborted the CLI suite on a machine that was merely fresh.
    /// A directory holding a sibling rank table IS partial, and that is the one
    /// case where "re-fetch this artifact" is the right instruction. A
    /// zero-length file is partial too, and deliberately not absent: it is what
    /// an interrupted download leaves, and every parity suite skips on absent
    /// while halting on partial, so classifying it as absent would turn a
    /// truncated table into a skipped exactness gate. Driven against a real
    /// temporary directory because the classification is stat against stat and a
    /// mock would assert its own behavior.
    #[test]
    fn artifact_states_distinguish_absent_incomplete_and_present() {
        let dir = std::env::temp_dir().join("exatok-vocab-artifact-states");
        let _ = std::fs::remove_dir_all(&dir);
        let file = dir.join("cl100k_base.tiktoken");
        let sibling = dir.join("r50k_base.tiktoken");

        let no_directory = locate_in(&dir, CL100K_BASE);
        std::fs::create_dir_all(&dir).unwrap();
        let empty_directory = locate_in(&dir, CL100K_BASE);
        std::fs::write(&sibling, "YQ== 0\n").unwrap();
        let sibling_only = locate_in(&dir, CL100K_BASE);
        std::fs::write(&file, "").unwrap();
        let zero_length = locate_in(&dir, CL100K_BASE);
        std::fs::write(&file, "YQ== 0\n").unwrap();
        let present = locate_in(&dir, CL100K_BASE);
        let _ = std::fs::remove_dir_all(&dir);

        let absent = Artifact::NoCache {
            dir: dir.clone(),
            path: file.clone(),
        };
        let partial = Artifact::Incomplete {
            dir: dir.clone(),
            path: file.clone(),
        };
        assert_eq!(no_directory, absent);
        assert_eq!(
            empty_directory, absent,
            "a directory that holds no rank table was never provisioned, so it is not partial"
        );
        assert_eq!(
            sibling_only, partial,
            "a directory holding one rank table and not this one is partial"
        );
        assert_eq!(
            zero_length, partial,
            "an empty rank file is a broken cache, not an absent one"
        );
        assert_eq!(present, Artifact::Present(file));
        for report in [absent.report(), partial.report()] {
            assert!(
                report.contains("cl100k_base.tiktoken") && report.contains(ARTIFACT_DIR_ENV),
                "a report must name the path and the override, got {report}"
            );
        }
    }

    /// No artifact report may describe itself as a test harness.
    ///
    /// These messages reach the CLI, and a CLI that refused to run did not
    /// "skip a gate". The wording used to say exactly that, and main.rs carried a
    /// workaround composing its own message instead of forwarding this one, which
    /// is what a message written for the wrong audience costs. Asserted on the
    /// words rather than the whole string so a rewording that stays honest passes.
    #[test]
    fn artifact_reports_describe_the_artifact_and_not_a_gate() {
        let dir = std::env::temp_dir().join("exatok-vocab-report-wording");
        let _ = std::fs::remove_dir_all(&dir);
        let absent = locate_in(&dir, CL100K_BASE).report();
        std::fs::create_dir_all(&dir).unwrap();
        // A sibling rank table is what makes this cache partial rather than
        // unprovisioned, which is the state whose wording is under test.
        std::fs::write(dir.join("r50k_base.tiktoken"), "YQ== 0\n").unwrap();
        let broken = locate_in(&dir, CL100K_BASE).report();
        let _ = std::fs::remove_dir_all(&dir);

        for report in [&absent, &broken] {
            for forbidden in ["SKIPPED", "skipped", "gate", "parity"] {
                assert!(
                    !report.contains(forbidden),
                    "an artifact report must not speak as a test harness, found {forbidden:?} \
                     in: {report}"
                );
            }
            assert!(
                report.contains("Fix:") || report.contains("Populate"),
                "a report must say what to do about it, got: {report}"
            );
        }
    }

    /// The named vocabularies are distinct and their pinned counts are exact.
    ///
    /// `tokens` and `pairs` are the cheap guard against a silently incomplete
    /// pair derivation, so they are ground truth rather than documentation: a
    /// loader that dropped non-canonical splits still encodes most inputs
    /// correctly and only the count catches it. Two descriptors sharing a name
    /// would also make [`locate`] resolve two vocabularies to one file.
    #[test]
    fn named_vocabularies_are_distinct_and_their_counts_are_pinned() {
        let mut names: Vec<&str> = NAMED_VOCABULARIES.iter().map(|v| v.name).collect();
        names.sort_unstable();
        let count = names.len();
        names.dedup();
        assert_eq!(names.len(), count, "two descriptors share a name: {names:?}");
        assert_eq!(
            names,
            vec!["cl100k_base", "o200k_base", "p50k_base", "r50k_base"],
            "the shipped set changed"
        );

        assert_eq!(CL100K_BASE.tokens, 100_256);
        assert_eq!(CL100K_BASE.pairs, 233_378);
        assert_eq!(CL100K_BASE.text_ids, 1_211);
        assert_eq!(R50K_BASE.tokens, 50_256);
        assert_eq!(R50K_BASE.pairs, 108_299);
        assert_eq!(P50K_BASE.tokens, 50_280);
        assert_eq!(P50K_BASE.pairs, 108_599);
        assert_eq!(O200K_BASE.tokens, 199_998);
        assert_eq!(O200K_BASE.pairs, 446_189);
        assert!(
            CL100K_BASE.artifact_path().ends_with("cl100k_base.tiktoken"),
            "the artifact path must name the stem"
        );
    }

    /// The override wins over `$HOME`, and its absence falls back to the cache.
    ///
    /// `artifact_dir` is the single place the whole crate agrees on where rank
    /// files live, so a precedence defect points the CLI at one directory and the
    /// tests at another. Asserted through the real environment rather than a
    /// parameter, because the precedence IS the environment read.
    #[test]
    fn the_artifact_dir_override_takes_precedence_over_home() {
        assert_eq!(ARTIFACT_DIR_ENV, "EXATOK_VOCAB_DIR");
        assert_eq!(ARTIFACT_DIR_DEFAULT, ".cache/exatok-vocab");
        let dir = artifact_dir();
        match std::env::var_os(ARTIFACT_DIR_ENV) {
            Some(override_dir) => assert_eq!(
                dir,
                PathBuf::from(override_dir),
                "the override must be used verbatim"
            ),
            None => assert!(
                dir.ends_with(ARTIFACT_DIR_DEFAULT),
                "without the override the path must end with the default cache, got {}",
                dir.display()
            ),
        }
    }
}