toktier 0.3.2

Rust API preview for TokTier's exact, stateful tokenization runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use sha2::{Digest, Sha256};
use toktier_routing_core::{FastCpuEngine, FastRepairSpec, NativeRouter, ReferenceEngine};

use crate::artifact::{ArtifactManager, Revision};
use crate::diagnostics::{
    Backend, Certification, CudaFacts, DoctorFacts, ExecutionFacts, ReasonCode, RoutePlan,
    RuntimeBuildFacts, StoreStats,
};
use crate::manifest::{LocalArtifact, Registry};
use crate::session::{SessionStoreState, TokenizerInner};
#[cfg(feature = "jit")]
use crate::JitCompiler;
use crate::{
    Device, Encoding, Error, ErrorCode, GpuDelivery, Policy, RaggedEncoding, Result, Session,
    TokenBuffer,
};

/// Options for a one-shot encode. Both fields default to `false`.
///
/// A single encode with both `offsets` and `add_special_tokens` enabled
/// returns [`ErrorCode::InvalidArgument`]. Batch encodes do not support
/// `offsets`; requesting them also returns [`ErrorCode::InvalidArgument`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EncodeOptions {
    /// Request post-processor special tokens.
    pub add_special_tokens: bool,
    /// Request offsets for a single encode.
    pub offsets: bool,
}

/// Options for decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeOptions {
    pub skip_special_tokens: bool,
}

impl Default for DecodeOptions {
    fn default() -> Self {
        Self {
            skip_special_tokens: true,
        }
    }
}

#[derive(Debug, Clone)]
struct RuntimeConfig {
    home: Option<PathBuf>,
    artifact_cache: PathBuf,
    artifact_manager: Option<ArtifactManager>,
    explicit_artifacts: HashMap<String, PathBuf>,
    policy: Policy,
    device: Device,
    gpu_delivery: GpuDelivery,
    gpu_min_bytes: u64,
    diagnostics: bool,
    persistent_sessions: bool,
    seed_digest_overlap: bool,
    #[cfg(feature = "jit")]
    jit_compiler: Option<JitCompiler>,
}

/// Builder for the immutable Rust runtime.
#[derive(Debug, Clone)]
pub struct RuntimeBuilder {
    config: RuntimeConfig,
}

impl Default for RuntimeBuilder {
    fn default() -> Self {
        let artifact_cache =
            crate::fsutil::default_cache_directory("TOKTIER_ARTIFACT_CACHE", "artifacts");
        Self {
            config: RuntimeConfig {
                home: None,
                artifact_cache,
                artifact_manager: None,
                explicit_artifacts: HashMap::new(),
                policy: Policy::default(),
                device: Device::Auto,
                gpu_delivery: GpuDelivery::Auto,
                gpu_min_bytes: 64 * 1024,
                diagnostics: false,
                persistent_sessions: false,
                seed_digest_overlap: false,
                #[cfg(feature = "jit")]
                jit_compiler: None,
            },
        }
    }
}

impl RuntimeBuilder {
    /// Set the runtime home directory: session state lives under
    /// `<home>/sessions`.
    ///
    /// This implicitly enables persistent sessions; see
    /// [`Self::persistent_sessions`]. Left unset, persistent sessions
    /// resolve a home from `TOKTIER_HOME`, `XDG_STATE_HOME`, or `HOME`,
    /// the way the Python product resolves its state directory.
    pub fn home(mut self, path: impl Into<PathBuf>) -> Self {
        self.config.home = Some(path.into());
        self.config.persistent_sessions = true;
        self
    }

    pub fn artifact_cache(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        self.config.artifact_cache = path.clone();
        if let Some(manager) = &self.config.artifact_manager {
            self.config.artifact_manager = Some(manager.with_cache(path));
        }
        self
    }

    /// Install a shareable Rust-native artifact acquisition policy.
    pub fn artifacts(mut self, manager: ArtifactManager) -> Self {
        self.config.artifact_cache = manager.cache_root().to_path_buf();
        self.config.artifact_manager = Some(manager);
        self
    }

    /// Bind one family to an explicitly supplied local artifact directory.
    pub fn artifact_directory(
        mut self,
        family: impl Into<String>,
        path: impl Into<PathBuf>,
    ) -> Self {
        self.config
            .explicit_artifacts
            .insert(family.into(), path.into());
        self
    }

    pub fn policy(mut self, policy: Policy) -> Self {
        self.config.policy = policy;
        self
    }

    pub fn device(mut self, device: Device) -> Self {
        self.config.device = device;
        self
    }

    pub fn gpu_delivery(mut self, delivery: GpuDelivery) -> Self {
        self.config.gpu_delivery = delivery;
        self
    }

    pub fn gpu_min_bytes(mut self, bytes: u64) -> Self {
        self.config.gpu_min_bytes = bytes;
        self
    }

    pub fn diagnostics(mut self, enabled: bool) -> Self {
        self.config.diagnostics = enabled;
        self
    }

    pub fn persistent_sessions(mut self, enabled: bool) -> Self {
        self.config.persistent_sessions = enabled;
        self
    }

    /// Overlap the session-seed content-digest scan with the seed encode
    /// on the process-wide bounded worker pool (PLAN/162 WP5/WP6). The
    /// digest bytes, validation ordering, and failure behavior are
    /// identical in both modes; overlap changes only wall-clock
    /// scheduling, hiding the scan under the encode when a worker is
    /// free. Defaults to off, which keeps the fully serial seed path.
    pub fn seed_digest_overlap(mut self, enabled: bool) -> Self {
        self.config.seed_digest_overlap = enabled;
        self
    }

    /// Select a direct-NVCC compiler/cache policy for `GpuDelivery::Jit`.
    #[cfg(feature = "jit")]
    pub fn jit_compiler(mut self, compiler: JitCompiler) -> Self {
        self.config.jit_compiler = Some(compiler);
        self
    }

    /// Conspicuous one-runtime opt-in for an unregistered direct JIT tuple.
    /// It does not persist permission and does not make the result certified.
    #[cfg(feature = "jit")]
    pub fn accept_uncertified_jit(mut self, accept: bool) -> Result<Self> {
        let compiler = JitCompiler::builder()
            .accept_uncertified_jit(accept)
            .build()?;
        self.config.jit_compiler = Some(compiler);
        Ok(self)
    }

    pub fn build(mut self) -> Result<Runtime> {
        if self.config.artifact_cache.as_os_str().is_empty() {
            return Err(Error::new(
                ErrorCode::ConfigInvalid,
                "artifact_cache must not be empty",
            ));
        }
        if self.config.persistent_sessions && self.config.home.is_none() {
            // An unnamed home falls back to the same state root the
            // Python product uses. A host with none of those variables
            // set gets no implicit location: session state is not
            // rebuildable, so it is not placed by guesswork.
            self.config.home = crate::fsutil::default_state_directory();
            if self.config.home.is_none() {
                return Err(Error::new(
                    ErrorCode::ConfigInvalid,
                    "persistent sessions require RuntimeBuilder::home, TOKTIER_HOME, \
                     XDG_STATE_HOME, or HOME",
                ));
            }
        }
        if matches!(self.config.device, Device::Cpu)
            && !matches!(
                self.config.gpu_delivery,
                GpuDelivery::Auto | GpuDelivery::Disabled
            )
        {
            return Err(Error::new(
                ErrorCode::ConfigInvalid,
                "a CPU device cannot request GPU kernel delivery",
            ));
        }
        let registry = Registry::load()?;
        let artifacts = match &self.config.artifact_manager {
            Some(manager) => manager.with_cache(self.config.artifact_cache.clone()),
            None => ArtifactManager::builder()
                .cache(self.config.artifact_cache.clone())
                .build()?,
        };
        Ok(Runtime {
            inner: Arc::new(RuntimeInner {
                registry,
                artifacts,
                config: self.config,
            }),
        })
    }
}

#[derive(Debug)]
struct RuntimeInner {
    registry: Arc<Registry>,
    artifacts: ArtifactManager,
    config: RuntimeConfig,
}

/// Immutable root object. Clone is cheap and thread-safe.
#[derive(Debug, Clone)]
pub struct Runtime {
    inner: Arc<RuntimeInner>,
}

impl Runtime {
    pub fn builder() -> RuntimeBuilder {
        RuntimeBuilder::default()
    }

    /// Deterministically release this root handle. Tokenizers cloned from it
    /// retain their own resources until they are dropped or shut down.
    pub fn shutdown(self) {}

    /// Return machine-readable build and non-invasive device facts. This does
    /// not load a tokenizer or CUDA kernel and never widens routing policy.
    pub fn doctor(&self) -> DoctorFacts {
        let standing = self.inner.registry.rust_api_build_standing();
        let runtime_build = RuntimeBuildFacts {
            source_digest: env!("TOKTIER_RUST_API_SOURCE_SHA256").to_owned(),
            fast_cpu_source_digest: env!("TOKTIER_RUST_API_FAST_CPU_SOURCE_SHA256").to_owned(),
            native_host_source_digest: env!("TOKTIER_RUST_API_NATIVE_HOST_SOURCE_SHA256")
                .to_owned(),
            toolchain: env!("TOKTIER_RUST_API_TOOLCHAIN").to_owned(),
            build_flags: env!("TOKTIER_RUST_API_BUILD_FLAGS")
                .split('\x1f')
                .map(str::to_owned)
                .collect(),
            dependency_closure: crate::DEPENDENCY_CLOSURE.to_owned(),
            build_flag_divergence: self.inner.registry.rust_api_build_flag_divergence(),
            certified: self.inner.registry.rust_api_build_certified(),
            source_identity_judged: standing.source_identity_judged,
            recipe_judged: standing.recipe_judged,
            toolchain_divergence: self.inner.registry.rust_api_toolchain_divergence(),
            core_closure: crate::behavior_version::core_closure().to_owned(),
            dependency_advisory: crate::behavior_version::dependency_advisory().map(str::to_owned),
            behavior_versions: crate::behavior_version::facts(),
            reference_versions: crate::behavior_version::reference_facts(),
            reference_certification_reason:
                crate::behavior_version::reference_certification_reason().map(str::to_owned),
        };
        let ordinal = match self.inner.config.device {
            Device::Cuda(ordinal) => ordinal,
            Device::Auto => 0,
            Device::Cpu => {
                return DoctorFacts {
                    crate_version: env!("CARGO_PKG_VERSION").to_owned(),
                    oracle: crate::ORACLE.to_owned(),
                    registry_verified: true,
                    python_required: false,
                    sqlite_compiled: cfg!(feature = "sqlite"),
                    prebuilt_gpu_compiled: cfg!(feature = "prebuilt-gpu"),
                    jit_compiled: cfg!(feature = "jit"),
                    network_compiled: cfg!(feature = "network"),
                    runtime_build,
                    cuda: None,
                };
            }
        };
        let cuda = cuda_facts(ordinal);
        DoctorFacts {
            crate_version: env!("CARGO_PKG_VERSION").to_owned(),
            oracle: crate::ORACLE.to_owned(),
            registry_verified: true,
            python_required: false,
            sqlite_compiled: cfg!(feature = "sqlite"),
            prebuilt_gpu_compiled: cfg!(feature = "prebuilt-gpu"),
            jit_compiled: cfg!(feature = "jit"),
            network_compiled: cfg!(feature = "network"),
            runtime_build,
            cuda: Some(cuda),
        }
    }

    /// Load a canonical family from the verified local cache.
    pub fn load(&self, family: &str) -> Result<Tokenizer> {
        let explicit = self.inner.config.explicit_artifacts.get(family);
        if explicit.is_none() {
            self.inner.artifacts.ensure(family, &self.inner.registry)?;
        }
        let artifact = self.inner.registry.verify_local(
            family,
            &self.inner.config.artifact_cache,
            explicit.map(PathBuf::as_path),
        )?;
        self.build_tokenizer(artifact)
    }

    /// Verify and load a canonical family from one explicit local directory.
    pub fn load_local(&self, family: &str, directory: impl AsRef<Path>) -> Result<Tokenizer> {
        let artifact = self.inner.registry.verify_local(
            family,
            &self.inner.config.artifact_cache,
            Some(directory.as_ref()),
        )?;
        self.build_tokenizer(artifact)
    }

    /// The canonical family whose packaged `tokenizer.json` has the SHA-256
    /// `sha256_hex` (lowercase), when this crate ships one. A host that
    /// already holds a tokenizer file can ask whether it is one this crate
    /// admits before calling [`Runtime::load_local`] on its directory; a
    /// `None` means the file is outside the shipped families and the host
    /// keeps whatever engine it would otherwise use. The lookup reads the
    /// shipped artifact manifest and touches no file.
    pub fn family_for_sha256(&self, sha256_hex: &str) -> Option<String> {
        self.inner
            .registry
            .family_for_tokenizer_sha256(sha256_hex)
            .map(str::to_owned)
    }

    /// Resolve a frozen repository/revision through the shipped verified
    /// sibling table, then execute its canonical digest-identical or proven
    /// equivalent tokenizer artifact.
    pub fn load_repository(&self, repo_id: &str, revision: &str) -> Result<Tokenizer> {
        let family = self.family_for_repo(repo_id, revision)?;
        self.load(&family)
    }

    /// Resolve an immutable repository commit, acquire its canonical artifact,
    /// and return a verified tokenizer handle.
    pub fn from_pretrained(&self, repo_id: &str, revision: Revision) -> Result<Tokenizer> {
        self.load_repository(repo_id, revision.as_str())
    }

    /// Clone the runtime's artifact lifecycle manager.
    pub fn artifacts(&self) -> ArtifactManager {
        self.inner.artifacts.clone()
    }

    pub(crate) fn family_for_repo(&self, repo_id: &str, revision: &str) -> Result<String> {
        self.inner.registry.resolve_repo(repo_id, revision)
    }

    fn build_tokenizer(&self, artifact: LocalArtifact) -> Result<Tokenizer> {
        let bytes = artifact.bytes();
        // The bytes already passed content-hash verification against the
        // shipped manifest, so a reference-engine load failure is not a
        // hash mismatch: it means the shipped tables admit an artifact the
        // frozen oracle cannot execute, which is an internal inconsistency.
        let reference = Arc::new(ReferenceEngine::from_bytes(&bytes).map_err(|error| {
            Error::new(ErrorCode::Internal, error.to_string())
                .with_path(artifact.tokenizer_json())
                .with_family(&artifact.identity().family)
        })?);
        let family = artifact.identity().family.clone();
        let mut reasons = Vec::new();
        let policy = self.inner.config.policy;
        // Two premises, read against the shipped register. The judged
        // recipe -- judged sources, judged toolchain, judged flags, the
        // workspace members as the judged copies, every reference library
        // at a certified version -- admits every accelerated route the
        // way it always has. The judged sources alone admit the fast CPU
        // engine under every policy but `Reference` (since 0.3.0; user
        // rule of 2026-10-14): the engine is the judged one by source
        // identity, and the compiler, the feature recipe and the versions
        // of the reference libraries it was built with are coverage gaps
        // the label and the doctor facts carry, never a reason to run
        // full encodes on the reference engine. The reference route is
        // for builds whose own sources do not verify. The GPU route keeps
        // the first premise: a prebuilt fatbin is paired with a judged
        // host build.
        let runtime_build_certified = self.inner.registry.rust_api_build_certified();
        let accelerated_build_allowed = runtime_build_certified || policy == Policy::Experimental;
        let fast_cpu_build_allowed =
            accelerated_build_allowed || self.inner.registry.rust_api_sources_judged();
        if !fast_cpu_build_allowed && policy != Policy::Reference {
            reasons.push(ReasonCode::RuntimeBuildUncertified);
        }
        let fast_cpu_route = if policy == Policy::Reference {
            reasons.push(ReasonCode::ReferenceRequested);
            None
        } else if !fast_cpu_build_allowed {
            None
        } else {
            self.build_fast_cpu(&artifact, Arc::clone(&reference), &mut reasons)?
        };
        // What the fast CPU route can be called. The judged recipe on the
        // judged compiler is certified by source; anything else that was
        // admitted is supported, or locally verified when a check this
        // machine ran compared the two engines and they agreed.
        let fast_cpu_certification = fast_cpu_route.as_ref().map(|route| {
            if runtime_build_certified && route.toolchain_judged {
                Certification::CertifiedSource
            } else if crate::verify_local::is_locally_verified(&crate::verify_local::cpu_key(
                &family,
                &artifact.identity().tokenizer_sha256,
            )) {
                Certification::LocallyVerified
            } else {
                Certification::Supported
            }
        });
        let fast_cpu = fast_cpu_route.map(|route| route.engine);

        #[allow(unused_mut)]
        let mut gpu = None;
        #[allow(unused_mut)]
        let mut gpu_detail = None;
        #[allow(unused_mut)]
        let mut gpu_assurance = None;
        #[allow(unused_mut)]
        let mut gpu_verification_key = None;
        #[cfg(feature = "jit")]
        let mut jit_detail = None;
        let wants_gpu = !matches!(self.inner.config.device, Device::Cpu)
            && !matches!(self.inner.config.gpu_delivery, GpuDelivery::Disabled)
            && self.inner.config.policy != Policy::Reference;
        // The GPU route by build standing (`gpu_build_decision`): the
        // judged recipe as before, and since 0.3.2 the judged sources on
        // a toolchain or flags no campaign used, under the policies that
        // admit an unjudged device, labelled at most `Supported`.
        let gpu_build = gpu_build_decision(
            classify_build(&BuildReading::of(&self.inner.registry)),
            policy,
        );
        #[allow(unused_variables)]
        let cap_gpu_label = matches!(gpu_build, GpuBuildDecision::Admit { cap_label: true });
        if let (
            true,
            GpuBuildDecision::Refuse {
                reasons: why,
                message,
            },
        ) = (wants_gpu, &gpu_build)
        {
            if matches!(self.inner.config.device, Device::Cuda(_)) {
                return Err(Error::new(ErrorCode::UncertifiedRuntime, message.clone()));
            }
            reasons.extend(why.iter().cloned());
        } else if wants_gpu {
            #[cfg(feature = "prebuilt-gpu")]
            {
                let ordinal = match self.inner.config.device {
                    Device::Cuda(value) => i32::try_from(value).map_err(|_| {
                        Error::new(ErrorCode::InvalidArgument, "CUDA ordinal exceeds i32")
                    })?,
                    Device::Auto => 0,
                    Device::Cpu => unreachable!(),
                };
                let built = if self.inner.config.gpu_delivery == GpuDelivery::Jit {
                    #[cfg(feature = "jit")]
                    {
                        let compiler = match &self.inner.config.jit_compiler {
                            Some(compiler) => compiler.clone(),
                            None => JitCompiler::builder().build()?,
                        };
                        compiler
                            .compile_product(
                                &family,
                                &self.inner.registry,
                                ordinal,
                                self.inner.config.policy,
                            )
                            .and_then(|product| {
                                let facts = product.facts.clone();
                                crate::gpu_data::build_jit(
                                    &self.inner.registry,
                                    &artifact,
                                    Arc::clone(&reference),
                                    ordinal,
                                    self.inner.config.policy,
                                    &product,
                                )
                                .map(|built| (built, Some(facts)))
                            })
                    }
                    #[cfg(not(feature = "jit"))]
                    {
                        Err(Error::new(
                            ErrorCode::KernelIncompatible,
                            "GpuDelivery::Jit requires the crate's `jit` feature",
                        ))
                    }
                } else {
                    let prebuilt = crate::gpu_data::build_prebuilt(
                        &self.inner.registry,
                        &artifact,
                        Arc::clone(&reference),
                        ordinal,
                        self.inner.config.policy,
                    );
                    #[cfg(feature = "jit")]
                    {
                        prebuilt.map(|built| (built, None))
                    }
                    #[cfg(not(feature = "jit"))]
                    {
                        prebuilt.map(|built| (built, ()))
                    }
                };
                match built {
                    Ok((built, _maybe_facts)) => {
                        // What this route can be called. A judged device
                        // on the judged recipe is certified as before; an
                        // unjudged device, or any device on a build whose
                        // toolchain or flags no campaign judged, is
                        // supported, and locally verified when a check
                        // this machine ran with this build says the two
                        // engines agreed (the key carries the host
                        // toolchain and flags).
                        let locally_verified =
                            if gpu_label_reads_local_record(built.assurance, cap_gpu_label) {
                                let key = crate::verify_local::gpu_key(
                                    &built,
                                    &family,
                                    &artifact.identity().tokenizer_sha256,
                                );
                                let verified = crate::verify_local::is_locally_verified(&key);
                                gpu_verification_key = Some(key);
                                verified
                            } else {
                                false
                            };
                        gpu_assurance =
                            Some(gpu_label(built.assurance, cap_gpu_label, locally_verified));
                        gpu_detail = Some((built.architecture, built.driver_api_version));
                        gpu = Some(built.engine);
                        #[cfg(feature = "jit")]
                        {
                            jit_detail = _maybe_facts;
                        }
                    }
                    Err(error) if matches!(self.inner.config.device, Device::Auto) => {
                        reasons.push(
                            if matches!(
                                error.code(),
                                ErrorCode::UncertifiedTokenizer | ErrorCode::UncertifiedRuntime
                            ) {
                                ReasonCode::GpuUncertified
                            } else {
                                ReasonCode::GpuUnavailable
                            },
                        );
                    }
                    Err(error) => return Err(error),
                }
            }
            #[cfg(not(feature = "prebuilt-gpu"))]
            {
                if matches!(self.inner.config.device, Device::Cuda(_)) {
                    return Err(Error::new(
                        ErrorCode::KernelIncompatible,
                        "the crate was built without the prebuilt-gpu feature",
                    ));
                }
                reasons.push(ReasonCode::GpuUnavailable);
            }
        }

        let mut chain = Vec::new();
        let mut thresholds = Vec::new();
        let mut backends = Vec::new();
        if gpu.is_some() {
            chain.push("gpu".to_owned());
            thresholds.push(self.inner.config.gpu_min_bytes);
            backends.push(Backend::Gpu);
        }
        if fast_cpu.is_some() {
            chain.push("fast_cpu".to_owned());
            thresholds.push(0);
            backends.push(Backend::FastCpu);
        }
        chain.push("hf".to_owned());
        thresholds.push(0);
        backends.push(Backend::HuggingFace);
        if self.inner.config.policy == Policy::RequireAccelerated
            && fast_cpu.is_none()
            && gpu.is_none()
        {
            return Err(Error::new(
                ErrorCode::UncertifiedTokenizer,
                format!("family {family} has no certified accelerated route on this runtime"),
            ));
        }
        // How a request with special tokens is served (`RoutePlan::
        // postprocessor_class`). The router keeps its one constructor
        // flag: it is set for every class but `identity`, so a `prefix`
        // artifact asked for special tokens through the router directly
        // still gets the reference's answer rather than a bare core
        // stream; the facade sends the flag only for `reference`.
        let special_tokens = special_token_plan(&bytes, &reference);
        let postprocessor_adds_tokens = special_tokens.kind != PostprocessorKind::Identity;
        let repair_fast_cpu = fast_cpu.is_some();
        let router = Arc::new(
            NativeRouter::new(
                chain,
                thresholds,
                Arc::clone(&reference),
                fast_cpu.clone(),
                repair_fast_cpu,
                // The Rust API reads device facts (architecture, driver
                // version) into its route plan at build time, so its engine
                // is already open here; the deferred source is the Python
                // facade's construction path.
                gpu.map(toktier_routing_core::NativeGpuSource::Open),
                postprocessor_adds_tokens,
                self.inner.config.diagnostics,
            )
            .map_err(|error| Error::new(ErrorCode::ConfigInvalid, error.to_string()))?,
        );
        let fingerprint = semantic_fingerprint(
            artifact.identity().tokenizer_sha256.as_bytes(),
            repair_fast_cpu,
        );
        let literal_guard = reference
            .added_tokens()
            .iter()
            .map(|(_, content, _)| content.chars().count())
            .max()
            .unwrap_or(0);
        let fast_guard = fast_cpu
            .as_ref()
            .map(|engine| engine.minimum_seal_tail_chars())
            .unwrap_or(0);
        let seal_guard = u64::try_from(literal_guard.max(fast_guard))
            .map_err(|_| Error::new(ErrorCode::ConfigInvalid, "session seal guard exceeds u64"))?;
        let store_path = if self.inner.config.persistent_sessions {
            let home = self
                .inner
                .config
                .home
                .as_ref()
                .expect("builder validated persistent home");
            Some(home.join("sessions").join(format!("{family}.sqlite3")))
        } else {
            None
        };
        let store = SessionStoreState::new(
            Arc::clone(&router),
            fingerprint,
            seal_guard,
            store_path.as_deref(),
            self.inner.config.seed_digest_overlap,
        )?;
        let plan = RoutePlan {
            family: family.clone(),
            artifact_sha256: artifact.identity().tokenizer_sha256.clone(),
            backends,
            gpu_min_bytes: self.inner.config.gpu_min_bytes,
            certification: if self.inner.config.policy == Policy::Experimental {
                Certification::Experimental
            } else if self.inner.config.policy == Policy::Reference {
                Certification::Reference
            } else {
                // A routed result can be produced by either accelerated
                // engine, so the plan carries the weaker of the two
                // labels; between equals the GPU's is kept.
                match (gpu_assurance, fast_cpu_certification) {
                    (Some(gpu), Some(cpu)) if label_rank(cpu) < label_rank(gpu) => cpu,
                    (Some(gpu), _) => gpu,
                    (None, Some(cpu)) => cpu,
                    (None, None) => Certification::Reference,
                }
            },
            reasons,
            postprocessor_class: special_tokens.kind.word().to_owned(),
            special_token_prefix: special_tokens.kind.prefix().to_vec(),
            postprocessor_self_check: special_tokens.self_check,
            literal_segmentation: {
                let facts = router.literal_segmentation();
                (facts["served"] != true).then(|| {
                    facts["reason"]
                        .as_str()
                        .unwrap_or("the artifact is outside the served class")
                        .to_owned()
                })
            },
        };
        Ok(Tokenizer {
            inner: Arc::new(TokenizerInner {
                artifact,
                reference,
                router,
                plan,
                policy: self.inner.config.policy,
                registry: Arc::clone(&self.inner.registry),
                chunked: crate::chunked::State::default(),
                store: std::sync::Mutex::new(store),
                gpu_detail,
                gpu_verification_key,
                #[cfg(feature = "jit")]
                jit_detail,
            }),
        })
    }

    fn build_fast_cpu(
        &self,
        artifact: &LocalArtifact,
        reference: Arc<ReferenceEngine>,
        reasons: &mut Vec<ReasonCode>,
    ) -> Result<Option<FastCpuRoute>> {
        let family = &artifact.identity().family;
        if let Some(examined) = self.inner.registry.examined(family) {
            return self.build_examined_fast_cpu(artifact, reference, reasons, examined);
        }
        let Some(repair) = self.inner.registry.repair(family) else {
            reasons.push(ReasonCode::CpuUncertified);
            return Ok(None);
        };
        let support = self.inner.registry.support(family).ok_or_else(|| {
            Error::new(
                ErrorCode::RegistryInvalid,
                format!("repair family {family} has no support-registry row"),
            )
        })?;
        let fast_support = support.backends.get("fast_cpu");
        let fast_status = fast_support
            .and_then(|value| value.get("status"))
            .and_then(serde_json::Value::as_str);
        let fast_source = fast_support
            .and_then(|value| value.get("source_digest"))
            .and_then(serde_json::Value::as_str);
        // The toolchain the campaign built this engine with is recorded
        // on the row and read for the label, not for admission: since
        // 0.3.0 the engine is admitted by its source identity, and a
        // compiler no campaign used makes the route supported rather
        // than refused (`Certification::Supported`).
        let fast_toolchain = fast_support
            .and_then(|value| value.get("toolchain"))
            .and_then(serde_json::Value::as_str);
        // The engine's source binding is the one premise
        // `Policy::Experimental` waives, the way the Python facade's
        // experimental policy waives `R_ENGINE_BINDING_MISMATCH`: a build
        // whose engine sources the registry does not record may run the
        // engine, and the route is labelled experimental. The status and
        // the artifact bindings are not waived.
        let source_bound = fast_source == Some(env!("TOKTIER_RUST_API_FAST_CPU_SOURCE_SHA256"))
            || self.inner.config.policy == Policy::Experimental;
        if !matches!(fast_status, Some("certified") | Some("certified_source"))
            || support.artifact_sha256 != artifact.identity().tokenizer_sha256
            || repair.artifact_sha256 != artifact.identity().tokenizer_sha256
            || !source_bound
        {
            reasons.push(ReasonCode::CpuUncertified);
            return Ok(None);
        }
        let toolchain_judged = fast_toolchain == Some(env!("TOKTIER_RUST_API_TOOLCHAIN"));
        let spec = FastRepairSpec::new(
            family.clone(),
            repair.artifact_sha256.clone(),
            repair.margin,
            repair.effective_l_max,
            repair.has_normalizer,
        );
        let engine = FastCpuEngine::from_reference(
            &artifact.bytes(),
            reference,
            spec,
            self.inner.registry.pclass(),
        )
        .map_err(|error| {
            Error::new(
                ErrorCode::BackendExecutionFault,
                format!("certified corrected-CPU construction failed: {error}"),
            )
        })?;
        Ok(Some(FastCpuRoute {
            engine: Arc::new(engine),
            toolchain_judged,
        }))
    }
}

impl Runtime {
    /// The fast CPU route of an examined (not certified) artifact.
    ///
    /// The engine binding it is admitted against is the fast CPU entry of
    /// a certified support row holding the same pipeline capability: the
    /// entry's status and source digest have to verify exactly as they do
    /// for that family. What no campaign has judged is this artifact's
    /// added-token table, so the route is labelled
    /// [`Certification::Supported`] whatever the build, and
    /// `Policy::Certified` refuses it.
    fn build_examined_fast_cpu(
        &self,
        artifact: &LocalArtifact,
        reference: Arc<ReferenceEngine>,
        reasons: &mut Vec<ReasonCode>,
        examined: &crate::manifest::ExaminedRow,
    ) -> Result<Option<FastCpuRoute>> {
        let family = &artifact.identity().family;
        reasons.push(ReasonCode::ExaminedArtifact);
        if self.inner.config.policy == Policy::Certified
            || examined.artifact_sha256 != artifact.identity().tokenizer_sha256
        {
            reasons.push(ReasonCode::CpuUncertified);
            return Ok(None);
        }
        let bound = self
            .inner
            .registry
            .pipeline_peers(&examined.pipeline_id)
            .into_iter()
            .any(|peer| {
                let fast = peer.backends.get("fast_cpu");
                let status = fast
                    .and_then(|value| value.get("status"))
                    .and_then(serde_json::Value::as_str);
                let source = fast
                    .and_then(|value| value.get("source_digest"))
                    .and_then(serde_json::Value::as_str);
                matches!(status, Some("certified") | Some("certified_source"))
                    && (source == Some(env!("TOKTIER_RUST_API_FAST_CPU_SOURCE_SHA256"))
                        || self.inner.config.policy == Policy::Experimental)
            });
        if !bound {
            reasons.push(ReasonCode::CpuUncertified);
            return Ok(None);
        }
        let spec = FastRepairSpec::new(
            family.clone(),
            examined.artifact_sha256.clone(),
            examined.repair.margin,
            examined.repair.effective_l_max,
            examined.repair.has_normalizer,
        );
        let engine = FastCpuEngine::from_reference(
            &artifact.bytes(),
            reference,
            spec,
            self.inner.registry.pclass(),
        )
        .map_err(|error| {
            Error::new(
                ErrorCode::BackendExecutionFault,
                format!("corrected-CPU construction failed for an examined artifact: {error}"),
            )
        })?;
        Ok(Some(FastCpuRoute {
            engine: Arc::new(engine),
            // Never certified by source: no reading covers this artifact,
            // so the label stays `Supported` even on the judged compiler.
            toolchain_judged: false,
        }))
    }
}

/// An admitted fast CPU engine, with the one fact about its row that
/// decides its label rather than its admission.
struct FastCpuRoute {
    engine: Arc<FastCpuEngine>,
    /// Whether the compiler of this build is the one the registry row
    /// records for the engine.
    toolchain_judged: bool,
}

#[cfg(feature = "prebuilt-gpu")]
fn cuda_facts(ordinal: u32) -> CudaFacts {
    match i32::try_from(ordinal) {
        Ok(ordinal_i32) => match toktier_cuda_driver::CudaContext::new(ordinal_i32) {
            Ok(context) => {
                let (major, minor) = context.architecture();
                CudaFacts {
                    device_ordinal: ordinal,
                    available: true,
                    architecture: Some(format!("sm_{major}{minor}")),
                    driver_api_version: Some(context.driver_version()),
                    error: None,
                }
            }
            Err(error) => CudaFacts {
                device_ordinal: ordinal,
                available: false,
                architecture: None,
                driver_api_version: None,
                error: Some(error.to_string()),
            },
        },
        Err(_) => CudaFacts {
            device_ordinal: ordinal,
            available: false,
            architecture: None,
            driver_api_version: None,
            error: Some("CUDA ordinal exceeds i32".to_owned()),
        },
    }
}

#[cfg(not(feature = "prebuilt-gpu"))]
fn cuda_facts(ordinal: u32) -> CudaFacts {
    CudaFacts {
        device_ordinal: ordinal,
        available: false,
        architecture: None,
        driver_api_version: None,
        error: Some("CUDA support was not compiled into this feature set".to_owned()),
    }
}

/// A verified tokenizer and immutable route. Clone is cheap; sessions retain
/// their own single-writer handles.
#[derive(Debug, Clone)]
pub struct Tokenizer {
    pub(crate) inner: Arc<TokenizerInner>,
}

impl Tokenizer {
    /// What a local verification of this tokenizer's GPU route would be
    /// filed under, when that route is one no campaign has judged.
    pub(crate) fn verification_key(&self) -> Option<&crate::verify_local::VerificationKey> {
        self.inner.gpu_verification_key.as_ref()
    }

    pub fn family(&self) -> &str {
        &self.inner.artifact.identity().family
    }

    pub fn artifact(&self) -> &LocalArtifact {
        &self.inner.artifact
    }

    pub fn plan(&self) -> &RoutePlan {
        &self.inner.plan
    }

    /// The chunk-parallel encode of one long request on this tokenizer's
    /// CPU route: admission, cut plans, the encode itself, the worker
    /// pool and the counters ([`crate::chunked`]).
    pub fn chunked(&self) -> crate::chunked::Chunked<'_> {
        crate::chunked::Chunked::new(&self.inner)
    }

    /// Snapshot native store counters without exposing implementation-crate
    /// types or locks.
    pub fn store_stats(&self) -> StoreStats {
        self.inner
            .store
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .store
            .stats()
            .into()
    }

    pub fn gpu_facts(&self) -> Option<(&str, i32)> {
        self.inner
            .gpu_detail
            .as_ref()
            .map(|(architecture, version)| (architecture.as_str(), *version))
    }

    /// Exact direct-JIT compiler/cache binding, when that delivery was loaded.
    #[cfg(feature = "jit")]
    pub fn jit_facts(&self) -> Option<&crate::JitArtifact> {
        self.inner.jit_detail.as_ref()
    }

    pub fn encode(&self, text: &str) -> Result<Encoding> {
        self.encode_with(text, EncodeOptions::default())
    }

    pub fn encode_with(&self, text: &str, options: EncodeOptions) -> Result<Encoding> {
        if options.offsets && options.add_special_tokens {
            return Err(Error::new(
                ErrorCode::InvalidArgument,
                "offsets with post-processor special tokens are not exposed by Rust API v1",
            ));
        }
        let (router_flag, prefix) = self.special_token_service(options.add_special_tokens);
        let mut routed = self
            .inner
            .router
            .encode_ids(text, router_flag)
            .map_err(|error| Error::new(ErrorCode::BackendExecutionFault, error.to_string()))?;
        if let Some(prefix) = prefix {
            routed.ids = prepend(prefix, routed.ids);
        }
        // Explicitly requested offsets are reconstructed through the
        // one-pass structure-of-arrays bridge and materialized as the
        // public pair layout; values and failure behavior match the
        // retained pair bridge exactly. The bridge places tokens by their
        // raw byte lengths, which locates characters only on text the
        // face's normalizer leaves unchanged; other text is refused even
        // when its length changes cancel in bytes.
        let offsets = options
            .offsets
            .then(|| {
                self.inner
                    .reference
                    .spans_soa_for_ids(text, &routed.ids)
                    .and_then(|spans| {
                        self.inner
                            .reference
                            .require_normalization_stable(text)
                            .map(|()| spans)
                    })
                    .map(|(starts, ends)| starts.into_iter().zip(ends).collect::<Vec<_>>())
            })
            .transpose()
            .map_err(|error| Error::new(ErrorCode::BackendExecutionFault, error.to_string()))?;
        let facts = facts_from_routed(
            &routed.backend,
            routed.path.as_deref(),
            routed.source,
            text.len(),
            self.inner.plan.certification,
            routed.reason,
        );
        Ok(Encoding::new(routed.ids, offsets, facts))
    }

    pub fn encode_batch<S: AsRef<str>>(&self, documents: &[S]) -> Result<RaggedEncoding> {
        self.encode_batch_with(documents, EncodeOptions::default())
    }

    pub fn encode_batch_with<S: AsRef<str>>(
        &self,
        documents: &[S],
        options: EncodeOptions,
    ) -> Result<RaggedEncoding> {
        if options.offsets {
            return Err(Error::new(
                ErrorCode::InvalidArgument,
                "batch offsets are not part of the ragged ID-only API",
            ));
        }
        let texts = documents.iter().map(AsRef::as_ref).collect::<Vec<_>>();
        let (router_flag, prefix) = self.special_token_service(options.add_special_tokens);
        let routed = self
            .inner
            .router
            .encode_batch_ids(&texts, router_flag)
            .map_err(|error| Error::new(ErrorCode::BackendExecutionFault, error.to_string()))?;
        let rows = routed
            .into_iter()
            .zip(texts)
            .map(|(row, text)| {
                let facts = facts_from_routed(
                    &row.backend,
                    row.path.as_deref(),
                    row.source,
                    text.len(),
                    self.inner.plan.certification,
                    row.reason,
                );
                let ids = match prefix {
                    Some(prefix) => prepend(prefix, row.ids),
                    None => row.ids,
                };
                (ids, facts)
            })
            .collect();
        RaggedEncoding::from_rows(rows)
    }

    /// How one request's `add_special_tokens` is served: the flag the
    /// router is called with, and the ids placed before the stream it
    /// returns. Only the `reference` class sends the flag on; the other
    /// two take the plain route's core stream, which with the class's
    /// prefix (empty for `identity`) is the reference's answer
    /// (`RoutePlan::postprocessor_class`).
    fn special_token_service(&self, add_special_tokens: bool) -> (bool, Option<&[u32]>) {
        if !add_special_tokens {
            return (false, None);
        }
        match self.inner.plan.postprocessor_class.as_str() {
            CLASS_IDENTITY => (false, None),
            CLASS_PREFIX => (false, Some(self.inner.plan.special_token_prefix.as_slice())),
            _ => (true, None),
        }
    }

    pub fn decode(&self, ids: impl AsRef<[u32]>, options: DecodeOptions) -> Result<String> {
        self.inner
            .reference
            .decode(ids.as_ref(), options.skip_special_tokens)
            .map_err(|error| Error::new(ErrorCode::BackendExecutionFault, error.to_string()))
    }

    pub fn open_session(&self, name: impl Into<String>) -> Result<Session> {
        Session::open(Arc::clone(&self.inner), name.into())
    }

    /// Content-prefix lookup without Python. A hit returns its exact current
    /// token stream; a miss does not tokenize or mutate the store.
    pub fn lookup(&self, text: &str) -> Result<Option<Encoding>> {
        let mut state = self
            .inner
            .store
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.ensure_healthy()?;
        if !state.lookup_has_a_slot() {
            // Every slot of a durable store is taken by a named session (a
            // file written before the named-session bound kept one free). A
            // hit would make the core drop one of them, so this lookup
            // answers as a miss until a session is deleted.
            return Ok(None);
        }
        let key = state.key;
        let Some(hit) = state.store.lookup(key, text, self.inner.router.as_ref())? else {
            return Ok(None);
        };
        let matched_chars = usize::try_from(hit.matched_chars).map_err(|_| {
            Error::new(
                ErrorCode::Internal,
                "content-prefix length does not fit this platform",
            )
        })?;
        let total_chars = text.chars().count();
        if matched_chars > total_chars {
            return Err(Error::new(
                ErrorCode::StoreCorrupt,
                "content-prefix lookup returned a length beyond the query",
            ));
        }
        let suffix_byte = if matched_chars == total_chars {
            text.len()
        } else {
            text.char_indices()
                .nth(matched_chars)
                .map(|(offset, _)| offset)
                .ok_or_else(|| {
                    Error::new(
                        ErrorCode::StoreCorrupt,
                        "content-prefix lookup returned a non-existent character boundary",
                    )
                })?
        };
        if suffix_byte < text.len() {
            state.store.append_patch(
                hit.handle,
                &text[suffix_byte..],
                hit.revision,
                self.inner.router.as_ref(),
            )?;
        }
        let ids = state.store.shared_all_ids(hit.handle)?;
        // Lookup materializes a temporary session only to complete the
        // verified prefix. The returned Encoding shares the immutable row
        // (which outlives the evicted session), so retaining the handle
        // would only consume the bounded named-session capacity.
        state.store.evict(hit.handle);
        let facts = ExecutionFacts {
            backend: Backend::FastCpu,
            path: "content_lookup".to_owned(),
            source: Some("native_store".to_owned()),
            input_bytes: text.len() as u64,
            certification: self.inner.plan.certification,
            // The verified store answered the prefix: this is the
            // admitted route, not a decision that moved off it.
            reason: None,
        };
        Ok(Some(Encoding::from_buffer(
            TokenBuffer::from_shared(ids),
            facts,
        )))
    }

    /// Deterministically release this handle. Shared clones and outstanding
    /// sessions continue to own the runtime until they are dropped.
    pub fn shutdown(self) {}
}

pub(crate) fn facts_from_routed(
    backend: &str,
    path: Option<&str>,
    source: Option<String>,
    input_bytes: usize,
    certification: Certification,
    reason: Option<&str>,
) -> ExecutionFacts {
    ExecutionFacts {
        backend: Backend::from_internal(backend),
        path: path.unwrap_or("unknown").to_owned(),
        source,
        input_bytes: input_bytes as u64,
        certification,
        reason: reason.map(ReasonCode::from_ledger_code),
    }
}

/// Strength order of the route labels, for "the weaker of two".
fn label_rank(label: Certification) -> u8 {
    match label {
        Certification::Certified | Certification::CertifiedSource => 4,
        Certification::LocallyVerified => 3,
        Certification::Supported => 2,
        Certification::Experimental => 1,
        _ => 0,
    }
}

/// The facts about this build that decide whether it may run a GPU
/// route, read once from the shipped register and the build script.
#[derive(Debug, Clone, PartialEq, Eq)]
struct BuildReading {
    /// The judged recipe: judged sources, toolchain and flags, closure
    /// verified, reference libraries certified.
    recipe_certified: bool,
    /// The three source identities are those of a judged row.
    sources_judged: bool,
    /// `verified`, `unlocated: ...` or `mismatched: ...`.
    core_closure: String,
    /// `Some("uncertified_reference")` when a reference library is
    /// outside its certified versions.
    reference_reason: Option<String>,
    toolchain_divergence: Option<String>,
    flag_divergence: Option<String>,
}

impl BuildReading {
    fn of(registry: &Registry) -> Self {
        Self {
            recipe_certified: registry.rust_api_build_certified(),
            sources_judged: registry.rust_api_build_standing().source_identity_judged,
            core_closure: crate::behavior_version::core_closure().to_owned(),
            reference_reason: crate::behavior_version::reference_certification_reason()
                .map(str::to_owned),
            toolchain_divergence: registry.rust_api_toolchain_divergence(),
            flag_divergence: registry.rust_api_build_flag_divergence(),
        }
    }
}

/// Where a build stands for the GPU route. The four states between the
/// judged recipe and unjudged sources are named one by one; since 0.3.2
/// the first two of them are admitted under the policies that admit an
/// unjudged device, and the last two are not.
#[derive(Debug, Clone, PartialEq, Eq)]
enum BuildState {
    /// Judged sources, toolchain and flags; closure verified; reference
    /// libraries certified.
    JudgedRecipe,
    /// (a) the judged sources, closure and reference libraries, on a
    /// toolchain no judged row records for them;
    OtherToolchain { divergence: String },
    /// (b) the same with build flags or a feature list no judged row
    /// records (a development profile included), with or without (a).
    OtherFlags { divergence: String },
    /// (c) the judged sources with a reference library outside its
    /// certified versions (`uncertified_reference`);
    UncertifiedReference,
    /// (d) the judged sources with a closure that could not be compared
    /// for want of a governing lockfile (`unlocated`);
    UnlocatedClosure { closure: String },
    /// A sibling crate resolved from another copy or version.
    ClosureMismatched { closure: String },
    /// No judged row records these three source identities.
    SourcesUnjudged,
}

fn classify_build(reading: &BuildReading) -> BuildState {
    if reading.recipe_certified {
        return BuildState::JudgedRecipe;
    }
    if !reading.sources_judged {
        return BuildState::SourcesUnjudged;
    }
    if reading.core_closure.starts_with("unlocated") {
        return BuildState::UnlocatedClosure {
            closure: reading.core_closure.clone(),
        };
    }
    if reading.core_closure != "verified" {
        return BuildState::ClosureMismatched {
            closure: reading.core_closure.clone(),
        };
    }
    if reading.reference_reason.is_some() {
        return BuildState::UncertifiedReference;
    }
    match (&reading.flag_divergence, &reading.toolchain_divergence) {
        (Some(flags), _) => BuildState::OtherFlags {
            divergence: flags.clone(),
        },
        (None, Some(toolchain)) => BuildState::OtherToolchain {
            divergence: toolchain.clone(),
        },
        // Neither axis alone differs, yet no judged row records the pair
        // this build carries: a recipe that is not a judged one.
        (None, None) => BuildState::OtherFlags {
            divergence: format!(
                "no judged row records the toolchain `{}` together with the build flags of \
                 this build",
                env!("TOKTIER_RUST_API_TOOLCHAIN")
            ),
        },
    }
}

/// Whether a built GPU route's label depends on a local verification
/// record: every assurance but a judged device on an uncapped build, and
/// an explicit waiver.
#[cfg(feature = "prebuilt-gpu")]
fn gpu_label_reads_local_record(assurance: crate::gpu_data::Assurance, cap_label: bool) -> bool {
    use crate::gpu_data::Assurance;
    match assurance {
        Assurance::Judged => cap_label,
        Assurance::Unjudged => true,
        Assurance::Experimental => false,
    }
}

/// What a built GPU route can be called (T7). A judged device on a build
/// whose recipe a campaign judged is `Certified`; a capped build (its
/// toolchain or flags were not judged) never labels above `Supported`,
/// on a judged device too, and reads `LocallyVerified` when a check this
/// machine ran with this same build says the two engines agreed; an
/// unjudged device is labelled the same way; an explicit waiver is
/// `Experimental`. Pure: the local record is read by the caller.
#[cfg(feature = "prebuilt-gpu")]
fn gpu_label(
    assurance: crate::gpu_data::Assurance,
    cap_label: bool,
    locally_verified: bool,
) -> Certification {
    use crate::gpu_data::Assurance;
    match assurance {
        Assurance::Judged if !cap_label => Certification::Certified,
        Assurance::Experimental => Certification::Experimental,
        Assurance::Judged | Assurance::Unjudged => {
            if locally_verified {
                Certification::LocallyVerified
            } else {
                Certification::Supported
            }
        }
    }
}

/// The GPU route's build decision.
#[derive(Debug, Clone, PartialEq, Eq)]
enum GpuBuildDecision {
    /// Admitted; `cap_label` holds every GPU label at `Supported` (or
    /// `LocallyVerified` with a local record taken by this build).
    Admit { cap_label: bool },
    /// Refused: the reasons a `Device::Auto` plan records, and the
    /// message a `Device::Cuda` request fails with.
    Refuse {
        reasons: Vec<ReasonCode>,
        message: String,
    },
}

fn gpu_build_decision(state: BuildState, policy: Policy) -> GpuBuildDecision {
    let digests = format!(
        "rust_api {}, fast_cpu {}, native_host {}",
        env!("TOKTIER_RUST_API_SOURCE_SHA256"),
        env!("TOKTIER_RUST_API_FAST_CPU_SOURCE_SHA256"),
        env!("TOKTIER_RUST_API_NATIVE_HOST_SOURCE_SHA256"),
    );
    let refuse = |reasons: Vec<ReasonCode>, why: String| GpuBuildDecision::Refuse {
        reasons,
        message: format!(
            "the GPU route is not admitted for this Rust build: {why}. Runtime::doctor() \
             reports the build's standing; a registered release build, or an explicit \
             Policy::Experimental, runs it"
        ),
    };
    match state {
        BuildState::JudgedRecipe => GpuBuildDecision::Admit { cap_label: false },
        _ if policy == Policy::Experimental => GpuBuildDecision::Admit { cap_label: false },
        BuildState::OtherToolchain { .. } | BuildState::OtherFlags { .. }
            if policy.admits_unjudged_device() =>
        {
            GpuBuildDecision::Admit { cap_label: true }
        }
        BuildState::OtherToolchain { divergence } | BuildState::OtherFlags { divergence } => {
            refuse(
                vec![
                    ReasonCode::GpuUncertified,
                    ReasonCode::GpuBuildRecipeUnjudged,
                ],
                format!(
                    "its sources are judged and its recipe is not ({divergence}); policy \
                     {policy:?} admits the GPU route only on the judged recipe, \
                     Policy::Supported runs it labelled supported"
                ),
            )
        }
        BuildState::UncertifiedReference => refuse(
            vec![ReasonCode::GpuUncertified],
            "a reference library of this build is outside its certified versions \
             (uncertified_reference)"
                .to_owned(),
        ),
        BuildState::UnlocatedClosure { closure } => refuse(
            vec![ReasonCode::GpuUncertified],
            format!("its dependency closure could not be compared ({closure})"),
        ),
        BuildState::ClosureMismatched { closure } => refuse(
            vec![ReasonCode::GpuUncertified],
            format!("a sibling crate is not the judged copy ({closure})"),
        ),
        BuildState::SourcesUnjudged => refuse(
            vec![ReasonCode::GpuUncertified],
            format!(
                "no judged row of the shipped runtime-build registry records its source \
                 identities ({digests})"
            ),
        ),
    }
}

/// The three words of `RoutePlan::postprocessor_class`.
const CLASS_IDENTITY: &str = "identity";
const CLASS_PREFIX: &str = "prefix";
const CLASS_REFERENCE: &str = "reference";

/// What the post-processor of the executed document adds to a single
/// sequence, as far as this facade serves it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum PostprocessorKind {
    /// Nothing: the reference's answer with special tokens is its core
    /// stream.
    Identity,
    /// Exactly these ids before the core stream.
    Prefix(Vec<u32>),
    /// Anything else; the reference engine answers.
    Reference,
}

impl PostprocessorKind {
    fn word(&self) -> &'static str {
        match self {
            Self::Identity => CLASS_IDENTITY,
            Self::Prefix(_) => CLASS_PREFIX,
            Self::Reference => CLASS_REFERENCE,
        }
    }

    fn prefix(&self) -> &[u32] {
        match self {
            Self::Prefix(ids) => ids,
            Self::Identity | Self::Reference => &[],
        }
    }
}

/// The class of one artifact and the outcome of its construction check.
struct SpecialTokenPlan {
    kind: PostprocessorKind,
    self_check: Option<String>,
}

/// Classify the document's post-processor, then check the class on the
/// reference engine itself: for every probe text the answer with special
/// tokens has to be the class's prefix followed by the answer without
/// them. A probe that answers otherwise (or fails) makes the class
/// `reference` and is named in the plan.
fn special_token_plan(bytes: &[u8], reference: &ReferenceEngine) -> SpecialTokenPlan {
    let document = serde_json::from_slice::<serde_json::Value>(bytes).ok();
    let kind = document
        .as_ref()
        .map_or(PostprocessorKind::Reference, classify_postprocessor);
    if kind == PostprocessorKind::Reference {
        return SpecialTokenPlan {
            kind,
            self_check: None,
        };
    }
    let first_added = document.as_ref().and_then(first_added_literal);
    let mut probes = vec![
        String::new(),
        "a".to_owned(),
        "hello world".to_owned(),
        "caf\u{e9} \u{4e2d}\u{6587} \u{1f600} na\u{ef}ve".to_owned(),
    ];
    if let Some(literal) = first_added {
        probes.push(literal.clone());
        probes.push(format!("a {literal} b"));
    }
    for (index, probe) in probes.iter().enumerate() {
        let agrees = match (
            reference.encode_ids(probe, true),
            reference.encode_ids(probe, false),
        ) {
            (Ok(with), Ok(core)) => with == prepend(kind.prefix(), core),
            _ => false,
        };
        if !agrees {
            return SpecialTokenPlan {
                kind: PostprocessorKind::Reference,
                self_check: Some(format!(
                    "probe {index} ({} bytes) answered otherwise than the {} class on the \
                     reference engine",
                    probe.len(),
                    kind.word()
                )),
            };
        }
    }
    SpecialTokenPlan {
        kind,
        self_check: None,
    }
}

/// The face's first added token in document order (the first non-empty
/// `content` of the document's `added_tokens`), the literal the
/// construction check probes alone and inside text. The Python facade
/// takes the same one.
fn first_added_literal(document: &serde_json::Value) -> Option<String> {
    document
        .get("added_tokens")?
        .as_array()?
        .iter()
        .filter_map(|row| row.get("content").and_then(serde_json::Value::as_str))
        .find(|content| !content.is_empty())
        .map(str::to_owned)
}

/// The class of a tokenizer document's post-processor.
///
/// `identity`: no post-processor, `ByteLevel` (it rewrites offsets
/// only), or a template whose single-sequence form is the sequence
/// alone. `prefix`: a template whose single-sequence form is one special
/// token, looked up by the piece's own id, whose entry names that same id
/// and carries exactly one id, followed by the sequence. A `Sequence` of processors is classified
/// only when its members are `ByteLevel` and at most one template, the
/// template deciding. Everything else -- suffix or two-sided templates,
/// more than one special token, other processor types, nested sequences,
/// a document with truncation or padding -- is `reference`.
fn classify_postprocessor(document: &serde_json::Value) -> PostprocessorKind {
    let absent = |key: &str| document.get(key).is_none_or(serde_json::Value::is_null);
    if !absent("truncation") || !absent("padding") {
        return PostprocessorKind::Reference;
    }
    match document.get("post_processor") {
        None | Some(serde_json::Value::Null) => PostprocessorKind::Identity,
        Some(processor) => match processor_type(processor) {
            Some("Sequence") => {
                let Some(members) = processor
                    .get("processors")
                    .and_then(serde_json::Value::as_array)
                else {
                    return PostprocessorKind::Reference;
                };
                let mut template = None;
                for member in members {
                    match processor_type(member) {
                        Some("ByteLevel") => {}
                        Some("TemplateProcessing") if template.is_none() => {
                            template = Some(classify_template(member));
                        }
                        _ => return PostprocessorKind::Reference,
                    }
                }
                template.unwrap_or(PostprocessorKind::Identity)
            }
            Some("ByteLevel") => PostprocessorKind::Identity,
            Some("TemplateProcessing") => classify_template(processor),
            _ => PostprocessorKind::Reference,
        },
    }
}

fn processor_type(processor: &serde_json::Value) -> Option<&str> {
    processor.get("type").and_then(serde_json::Value::as_str)
}

/// The single-sequence form of one `TemplateProcessing`.
fn classify_template(template: &serde_json::Value) -> PostprocessorKind {
    let Some(single) = template.get("single").and_then(serde_json::Value::as_array) else {
        return PostprocessorKind::Reference;
    };
    match single.as_slice() {
        [sequence] if template_piece(sequence, "Sequence") == Some("A") => {
            PostprocessorKind::Identity
        }
        [special, sequence] if template_piece(sequence, "Sequence") == Some("A") => {
            let Some(key) = template_piece(special, "SpecialToken") else {
                return PostprocessorKind::Reference;
            };
            // The entry has to name the piece's own id too (the Python
            // facade reads the same, narrower shape).
            let ids = template
                .get("special_tokens")
                .and_then(|tokens| tokens.get(key))
                .filter(|entry| entry.get("id").and_then(serde_json::Value::as_str) == Some(key))
                .and_then(|entry| entry.get("ids"))
                .and_then(serde_json::Value::as_array);
            match ids.map(Vec::as_slice) {
                Some([id]) => id
                    .as_u64()
                    .and_then(|id| u32::try_from(id).ok())
                    .map_or(PostprocessorKind::Reference, |id| {
                        PostprocessorKind::Prefix(vec![id])
                    }),
                _ => PostprocessorKind::Reference,
            }
        }
        _ => PostprocessorKind::Reference,
    }
}

/// The id of a template piece of the given kind (`{"<kind>": {"id": ...,
/// "type_id": 0}}` and nothing else), or `None`.
fn template_piece<'a>(piece: &'a serde_json::Value, kind: &str) -> Option<&'a str> {
    let object = piece.as_object().filter(|object| object.len() == 1)?;
    let inner = object.get(kind)?;
    if inner.get("type_id").and_then(serde_json::Value::as_u64) != Some(0) {
        return None;
    }
    inner.get("id").and_then(serde_json::Value::as_str)
}

fn prepend(prefix: &[u32], ids: Vec<u32>) -> Vec<u32> {
    if prefix.is_empty() {
        return ids;
    }
    let mut out = Vec::with_capacity(prefix.len() + ids.len());
    out.extend_from_slice(prefix);
    out.extend(ids);
    out
}

/// The key a session store of this crate is written and opened under.
///
/// Besides the artifact, the reference library and the backend, it names
/// the serving generation and this build's source identity
/// (`TOKTIER_RUST_API_SOURCE_SHA256`, the exact digest of the crate and the
/// routing and store sources it compiles, which the build script provides).
/// A store written by any other build -- every earlier release included --
/// therefore carries a different key and is refused with
/// [`ErrorCode::SessionStateMismatch`]: its sealed ids were certified by
/// the code that wrote them, not by this one. Releases 0.2.4 to 0.3.1 wrote
/// the `toktier-rust-serving-v1` key, which had no source component.
pub(crate) fn semantic_fingerprint(artifact_sha256: &[u8], fast_cpu: bool) -> [u8; 32] {
    semantic_fingerprint_for(
        artifact_sha256,
        fast_cpu,
        env!("TOKTIER_RUST_API_SOURCE_SHA256"),
    )
}

/// [`semantic_fingerprint`] for an explicit source identity.
pub(crate) fn semantic_fingerprint_for(
    artifact_sha256: &[u8],
    fast_cpu: bool,
    source_identity: &str,
) -> [u8; 32] {
    let mut digest = Sha256::new();
    digest.update(b"toktier.rust.fingerprint.v1\0");
    for component in [
        artifact_sha256,
        b"tokenizers" as &[u8],
        b"0.22.2",
        b"toktier-rust-serving-v2",
        source_identity.as_bytes(),
        if fast_cpu { b"fast_cpu" } else { b"hf" },
        if fast_cpu {
            b"toktier-fast-repair-v1" as &[u8]
        } else {
            b""
        },
    ] {
        digest.update((component.len() as u32).to_le_bytes());
        digest.update(component);
    }
    digest.finalize().into()
}

#[allow(dead_code)]
fn _assert_send_sync() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Runtime>();
    assert_send_sync::<Tokenizer>();
    assert_send_sync::<TokenBuffer>();
}

#[cfg(test)]
mod tests {
    use super::{
        classify_build, classify_postprocessor, gpu_build_decision, label_rank, special_token_plan,
        BuildReading, BuildState, GpuBuildDecision, PostprocessorKind,
    };
    use crate::{Certification, Policy, ReasonCode};
    use serde_json::json;
    use toktier_routing_core::ReferenceEngine;

    /// T7's label cap, every cell: judged / unjudged device x capped /
    /// uncapped build, with and without a local record, plus the waiver.
    #[cfg(feature = "prebuilt-gpu")]
    #[test]
    fn the_gpu_label_cap_holds_in_every_cell() {
        use super::{gpu_label, gpu_label_reads_local_record};
        use crate::gpu_data::Assurance;
        use Assurance::{Experimental as X, Judged as J, Unjudged as U};
        use Certification::{Certified, Experimental, LocallyVerified as Local, Supported};
        // (assurance, capped, locally verified) -> label, reads a record
        let cases = [
            (J, false, false, Certified, false),
            (J, false, true, Certified, false),
            (J, true, false, Supported, true),
            (J, true, true, Local, true),
            (U, false, false, Supported, true),
            (U, false, true, Local, true),
            (U, true, false, Supported, true),
            (U, true, true, Local, true),
            (X, false, false, Experimental, false),
            (X, true, true, Experimental, false),
        ];
        for (assurance, capped, verified, label, reads) in cases {
            assert_eq!(
                gpu_label(assurance, capped, verified),
                label,
                "{assurance:?} capped={capped} verified={verified}"
            );
            assert_eq!(
                gpu_label_reads_local_record(assurance, capped),
                reads,
                "{assurance:?} capped={capped}"
            );
        }
        // A capped build never labels a route `Certified`.
        for assurance in [
            Assurance::Judged,
            Assurance::Unjudged,
            Assurance::Experimental,
        ] {
            for verified in [false, true] {
                assert_ne!(
                    gpu_label(assurance, true, verified),
                    Certification::Certified
                );
            }
        }
    }

    const POLICIES: [Policy; 5] = [
        Policy::Supported,
        Policy::Certified,
        Policy::Reference,
        Policy::RequireAccelerated,
        Policy::Experimental,
    ];

    /// The judged recipe: every axis the register binds agrees.
    fn judged() -> BuildReading {
        BuildReading {
            recipe_certified: true,
            sources_judged: true,
            core_closure: "verified".to_owned(),
            reference_reason: None,
            toolchain_divergence: None,
            flag_divergence: None,
        }
    }

    /// The judged sources, with one axis moved by `change`.
    fn moved(change: impl FnOnce(&mut BuildReading)) -> BuildReading {
        let mut reading = judged();
        reading.recipe_certified = false;
        change(&mut reading);
        reading
    }

    fn admitted(decision: &GpuBuildDecision) -> Option<bool> {
        match decision {
            GpuBuildDecision::Admit { cap_label } => Some(*cap_label),
            GpuBuildDecision::Refuse { .. } => None,
        }
    }

    /// The judged recipe runs the GPU route under every policy (the
    /// device rules then apply as before), uncapped.
    #[test]
    fn the_judged_recipe_admits_the_gpu_route_as_before() {
        assert_eq!(classify_build(&judged()), BuildState::JudgedRecipe);
        for policy in POLICIES {
            assert_eq!(
                admitted(&gpu_build_decision(BuildState::JudgedRecipe, policy)),
                Some(false),
                "{policy:?}"
            );
        }
    }

    /// One widened state's decision under each policy: admitted and
    /// capped under the two policies that admit an unjudged device,
    /// refused under `Certified` with the named reason, uncapped under
    /// `Experimental` (which labels the whole plan experimental).
    fn assert_widened(state: BuildState) {
        for policy in POLICIES {
            let decision = gpu_build_decision(state.clone(), policy);
            match policy {
                Policy::Supported | Policy::RequireAccelerated => {
                    assert_eq!(admitted(&decision), Some(true), "{state:?} {policy:?}");
                }
                Policy::Experimental => {
                    assert_eq!(admitted(&decision), Some(false), "{state:?} {policy:?}");
                }
                _ => {
                    let GpuBuildDecision::Refuse { reasons, message } = decision else {
                        panic!("{state:?} admitted under {policy:?}");
                    };
                    assert_eq!(
                        reasons,
                        vec![
                            ReasonCode::GpuUncertified,
                            ReasonCode::GpuBuildRecipeUnjudged
                        ]
                    );
                    assert!(message.contains("recipe is not"), "{message}");
                    assert!(message.contains("doctor()"), "{message}");
                }
            }
        }
    }

    /// One state that is not widened: refused under every policy but
    /// `Experimental`, the message naming the axis.
    fn assert_not_widened(state: BuildState, axis: &str) {
        for policy in POLICIES {
            let decision = gpu_build_decision(state.clone(), policy);
            if policy == Policy::Experimental {
                assert_eq!(admitted(&decision), Some(false), "{state:?}");
                continue;
            }
            let GpuBuildDecision::Refuse { reasons, message } = decision else {
                panic!("{state:?} admitted under {policy:?}");
            };
            assert_eq!(reasons, vec![ReasonCode::GpuUncertified], "{state:?}");
            assert!(message.contains(axis), "{state:?}: {message}");
            assert!(message.contains("doctor()"), "{message}");
        }
    }

    /// (a) another Rust compiler.
    #[test]
    fn state_a_another_toolchain_is_admitted_capped_outside_certified() {
        let reading = moved(|reading| {
            reading.toolchain_divergence = Some("rustc 1.94.0 is not judged".to_owned());
        });
        let state = classify_build(&reading);
        assert!(
            matches!(state, BuildState::OtherToolchain { .. }),
            "{state:?}"
        );
        assert_widened(state);
    }

    /// (b) other build flags or features, a development profile included,
    /// alone or with (a).
    #[test]
    fn state_b_other_flags_are_admitted_capped_outside_certified() {
        for toolchain in [None, Some("rustc 1.94.0 is not judged".to_owned())] {
            let reading = moved(|reading| {
                reading.flag_divergence = Some("profile=dev is not judged".to_owned());
                reading.toolchain_divergence = toolchain;
            });
            let state = classify_build(&reading);
            assert!(matches!(state, BuildState::OtherFlags { .. }), "{state:?}");
            assert_widened(state);
        }
        // Neither axis alone, yet not a judged pair: still a recipe state.
        let state = classify_build(&moved(|_| {}));
        assert!(matches!(state, BuildState::OtherFlags { .. }), "{state:?}");
        assert_widened(state);
    }

    /// (c) a reference library outside its certified versions: not
    /// widened, whatever the recipe.
    #[test]
    fn state_c_uncertified_reference_is_not_widened() {
        for flags in [None, Some("profile=dev".to_owned())] {
            let reading = moved(|reading| {
                reading.reference_reason = Some("uncertified_reference".to_owned());
                reading.flag_divergence = flags;
            });
            let state = classify_build(&reading);
            assert_eq!(state, BuildState::UncertifiedReference);
            assert_not_widened(state, "uncertified_reference");
        }
    }

    /// (d) a closure that could not be compared: not widened, though the
    /// fast CPU route admits it.
    #[test]
    fn state_d_unlocated_closure_is_not_widened() {
        let reading = moved(|reading| {
            reading.core_closure = "unlocated: no governing lockfile".to_owned();
        });
        let state = classify_build(&reading);
        assert!(
            matches!(state, BuildState::UnlocatedClosure { .. }),
            "{state:?}"
        );
        assert_not_widened(state, "could not be compared");
    }

    /// Outside the four states: a mismatched sibling and unjudged sources
    /// stay refused, and the refusal names the digests.
    #[test]
    fn unjudged_sources_and_a_mismatched_closure_stay_refused() {
        let state = classify_build(&moved(|reading| {
            reading.core_closure = "mismatched: toktier-store-core 0.0.1".to_owned();
        }));
        assert!(
            matches!(state, BuildState::ClosureMismatched { .. }),
            "{state:?}"
        );
        assert_not_widened(state, "judged copy");
        let state = classify_build(&moved(|reading| reading.sources_judged = false));
        assert_eq!(state, BuildState::SourcesUnjudged);
        assert_not_widened(state, env!("TOKTIER_RUST_API_SOURCE_SHA256"));
        assert_not_widened(
            BuildState::SourcesUnjudged,
            env!("TOKTIER_RUST_API_NATIVE_HOST_SOURCE_SHA256"),
        );
    }

    /// The plan carries the weaker label of the two engines.
    #[test]
    fn labels_are_ordered_from_certified_to_experimental() {
        let order = [
            Certification::Certified,
            Certification::LocallyVerified,
            Certification::Supported,
            Certification::Experimental,
            Certification::Reference,
        ];
        for pair in order.windows(2) {
            assert!(label_rank(pair[0]) > label_rank(pair[1]), "{pair:?}");
        }
        assert_eq!(
            label_rank(Certification::Certified),
            label_rank(Certification::CertifiedSource)
        );
    }

    fn template(single: serde_json::Value, special: serde_json::Value) -> serde_json::Value {
        json!({"type": "TemplateProcessing", "single": single, "pair": [], "special_tokens": special})
    }

    fn special(id: &str) -> serde_json::Value {
        json!({"SpecialToken": {"id": id, "type_id": 0}})
    }

    fn sequence(id: &str) -> serde_json::Value {
        json!({"Sequence": {"id": id, "type_id": 0}})
    }

    fn entry(key: &str, ids: serde_json::Value) -> serde_json::Value {
        json!({key: {"id": key, "ids": ids, "tokens": [key]}})
    }

    fn classify(post_processor: serde_json::Value) -> PostprocessorKind {
        classify_postprocessor(&json!({"post_processor": post_processor}))
    }

    /// The shapes the shipped artifacts carry, and the boundary of each
    /// class: only a sequence alone or one special token before it is
    /// served on the plain route; every other shape is the reference's.
    #[test]
    fn the_post_processor_classes_follow_the_template_shape() {
        let bos = || entry("<s>", json!([1]));
        assert_eq!(
            classify(serde_json::Value::Null),
            PostprocessorKind::Identity
        );
        assert_eq!(
            classify_postprocessor(&json!({})),
            PostprocessorKind::Identity
        );
        assert_eq!(
            classify(json!({"type": "ByteLevel", "trim_offsets": false})),
            PostprocessorKind::Identity
        );
        assert_eq!(
            classify(template(json!([sequence("A")]), json!({}))),
            PostprocessorKind::Identity
        );
        assert_eq!(
            classify(template(json!([special("<s>"), sequence("A")]), bos())),
            PostprocessorKind::Prefix(vec![1])
        );
        // The llama shape: ByteLevel then the template.
        let llama = json!({"type": "Sequence", "processors": [
            {"type": "ByteLevel"},
            template(json!([special("<s>"), sequence("A")]), bos()),
        ]});
        assert_eq!(classify(llama), PostprocessorKind::Prefix(vec![1]));
        for refused in [
            // A suffix, a two-sided template, two special tokens.
            template(json!([sequence("A"), special("<s>")]), bos()),
            template(
                json!([special("<s>"), sequence("A"), special("<s>")]),
                bos(),
            ),
            template(
                json!([special("<s>"), special("<s>"), sequence("A")]),
                bos(),
            ),
            // The sequence piece repeated, dropped, or another one.
            template(json!([sequence("A"), sequence("A")]), json!({})),
            template(json!([special("<s>")]), bos()),
            template(json!([sequence("B")]), json!({})),
            // A special token carrying two ids, none, or an id beyond u32.
            template(
                json!([special("<s>"), sequence("A")]),
                entry("<s>", json!([1, 2])),
            ),
            template(
                json!([special("<s>"), sequence("A")]),
                entry("<s>", json!([])),
            ),
            template(
                json!([special("<s>"), sequence("A")]),
                entry("<s>", json!([4_294_967_296_u64])),
            ),
            // The entry is looked up by the piece's own id, not searched.
            template(
                json!([special("<s>"), sequence("A")]),
                entry("<bos>", json!([1])),
            ),
            // A piece with another type id or an extra key.
            template(
                json!([{"SpecialToken": {"id": "<s>", "type_id": 1}}, sequence("A")]),
                bos(),
            ),
            template(
                json!([{"SpecialToken": {"id": "<s>", "type_id": 0}, "x": 1}, sequence("A")]),
                bos(),
            ),
            json!({"type": "BertProcessing", "sep": ["[SEP]", 102], "cls": ["[CLS]", 101]}),
            json!({"type": "RobertaProcessing"}),
            json!({"type": "SomethingLater"}),
            json!({"no_type": true}),
            // Sequences: a template after another template, a nested
            // sequence, a member that is not ByteLevel, no member list.
            json!({"type": "Sequence", "processors": [
                template(json!([special("<s>"), sequence("A")]), bos()),
                template(json!([sequence("A")]), json!({})),
            ]}),
            json!({"type": "Sequence", "processors": [
                {"type": "Sequence", "processors": [{"type": "ByteLevel"}]},
            ]}),
            json!({"type": "Sequence", "processors": [{"type": "RobertaProcessing"}]}),
            json!({"type": "Sequence"}),
        ] {
            assert_eq!(
                classify(refused.clone()),
                PostprocessorKind::Reference,
                "{refused}"
            );
        }
        // Truncation or padding in the document: the reference answers.
        for key in ["truncation", "padding"] {
            assert_eq!(
                classify_postprocessor(&json!({"post_processor": null, key: {"max_length": 8}})),
                PostprocessorKind::Reference,
                "{key}"
            );
        }
    }

    /// The entry a special-token piece names has to carry that same id:
    /// `{"<s>": {"id": "<bos>", "ids": [0]}}` behind the piece `<s>` is
    /// read as `reference`, as the Python facade reads it (the reference
    /// library would look the entry up by its key and emit the prefix;
    /// both readings are exact, the narrower one is the shared one).
    #[test]
    fn a_special_token_entry_naming_another_id_is_the_reference_s() {
        let other = json!({"<s>": {"id": "<bos>", "ids": [0], "tokens": ["<s>"]}});
        assert_eq!(
            classify(template(json!([special("<s>"), sequence("A")]), other)),
            PostprocessorKind::Reference
        );
        let same = json!({"<s>": {"id": "<s>", "ids": [0], "tokens": ["<s>"]}});
        assert_eq!(
            classify(template(json!([special("<s>"), sequence("A")]), same)),
            PostprocessorKind::Prefix(vec![0])
        );
        let unnamed = json!({"<s>": {"ids": [0], "tokens": ["<s>"]}});
        assert_eq!(
            classify(template(json!([special("<s>"), sequence("A")]), unnamed)),
            PostprocessorKind::Reference
        );
    }

    /// The construction check probes the first added token in document
    /// order, not the lowest id (the Python facade's choice).
    #[test]
    fn the_probe_literal_is_the_first_added_token_in_document_order() {
        use super::first_added_literal;
        let document = json!({"added_tokens": [
            {"id": 9, "content": ""},
            {"id": 7, "content": "<later_id_first_in_document>"},
            {"id": 1, "content": "<lowest_id>"},
        ]});
        assert_eq!(
            first_added_literal(&document).as_deref(),
            Some("<later_id_first_in_document>")
        );
        assert_eq!(first_added_literal(&json!({"added_tokens": []})), None);
        assert_eq!(first_added_literal(&json!({})), None);
    }

    /// A minimal word-level document with the given post-processor.
    fn word_level(post_processor: serde_json::Value) -> Vec<u8> {
        serde_json::to_vec(&json!({
            "version": "1.0",
            "truncation": null,
            "padding": null,
            "added_tokens": [{"id": 0, "content": "<s>", "single_word": false,
                "lstrip": false, "rstrip": false, "normalized": false, "special": true}],
            "normalizer": null,
            "pre_tokenizer": {"type": "Whitespace"},
            "post_processor": post_processor,
            "decoder": null,
            "model": {"type": "WordLevel", "vocab": {"<s>": 0, "a": 1, "b": 2, "[UNK]": 3},
                "unk_token": "[UNK]"}
        }))
        .unwrap()
    }

    /// The construction check runs the class against the reference engine
    /// itself: a class the engine agrees with is kept, and the check is
    /// what would demote a class whose reading of the document were wrong.
    #[test]
    fn the_construction_check_keeps_a_class_the_reference_agrees_with() {
        let bytes = word_level(template(
            json!([special("<s>"), sequence("A")]),
            entry("<s>", json!([0])),
        ));
        let reference = ReferenceEngine::from_bytes(&bytes).unwrap();
        let plan = special_token_plan(&bytes, &reference);
        assert_eq!(plan.kind, PostprocessorKind::Prefix(vec![0]));
        assert_eq!(plan.self_check, None);

        let bytes = word_level(serde_json::Value::Null);
        let reference = ReferenceEngine::from_bytes(&bytes).unwrap();
        let plan = special_token_plan(&bytes, &reference);
        assert_eq!(plan.kind, PostprocessorKind::Identity);
        assert_eq!(plan.self_check, None);
    }

    /// A document whose reading disagrees with the engine executing it is
    /// demoted, and the plan names the probe. The bytes classified here
    /// say "nothing is added" while the engine adds a token, which no
    /// shipped artifact does; the check is what keeps such a pair exact.
    #[test]
    fn the_construction_check_demotes_a_class_the_reference_contradicts() {
        let executed = word_level(template(
            json!([special("<s>"), sequence("A")]),
            entry("<s>", json!([0])),
        ));
        let reference = ReferenceEngine::from_bytes(&executed).unwrap();
        let described = word_level(serde_json::Value::Null);
        let plan = special_token_plan(&described, &reference);
        assert_eq!(plan.kind, PostprocessorKind::Reference);
        let named = plan.self_check.expect("the failing probe is named");
        assert!(named.starts_with("probe 0 "), "{named}");
        assert!(named.contains("identity class"), "{named}");
    }
}