toktier 0.3.3

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
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

use flate2::read::ZlibDecoder;
use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::{Error, ErrorCode, Result};

pub(crate) const ARTIFACT_MANIFEST_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/artifacts/tables/artifact_manifest.v1.json"
));
pub(crate) const ARTIFACT_CONVERSIONS_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/artifacts/tables/artifact_conversions.v1.json"
));
pub(crate) const SUPPORT_REGISTRY_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/routing/tables/support_registry.v1.json"
));
pub(crate) const CHUNKED_ADMISSION_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/routing/tables/chunked_admission.v1.json"
));
pub(crate) const EXAMINED_ARTIFACTS_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/routing/tables/examined_artifacts.v1.json"
));
pub(crate) const SIBLING_ALIASES_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/artifacts/tables/sibling_aliases.v1.json"
));
pub(crate) const REPAIR_MANIFEST_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/repair/tables/fast_repair_families.v1.json"
));
pub(crate) const REPAIR_PCLASS_COMPRESSED: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/repair/tables/repair_pclass.v1.zlib"
));
pub(crate) const KERNEL_FAMILIES_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/kernel_families.v1.json"
));
pub(crate) const PREBUILT_MANIFEST_BYTES: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/prebuilt/build_manifest.json"
));
#[cfg(feature = "prebuilt-gpu")]
pub(crate) const PREBUILT_FATBIN: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/prebuilt/pretok_kernel.fatbin"
));

const ARTIFACT_MANIFEST_SHA256: &str =
    "9f2e2edbb6220b31c280503f97a1d9d5be0fb0b7070ebe527a729b198dc35776";
const ARTIFACT_CONVERSIONS_SHA256: &str =
    "8fa33251a20e12ab8e35894732e49ea93fc2599f4e3425d1730d81bb1e9f2719";
const SUPPORT_REGISTRY_SHA256: &str = env!("TOKTIER_SUPPORT_REGISTRY_SHA256");
const CHUNKED_ADMISSION_SHA256: &str = env!("TOKTIER_CHUNKED_ADMISSION_SHA256");
const SIBLING_ALIASES_SHA256: &str =
    "f61866d6af8fd5268a7c4304ae3a9db8d8d87dc973c156408ad06a4a58e8893d";
const REPAIR_MANIFEST_SHA256: &str =
    "8801781427f98456a7dfce6d9cc8f8ddd8dd4ec31c1ff37b71913d83182f3853";
const KERNEL_FAMILIES_SHA256: &str =
    "a792fc914e2c8103da0d5e31eb55b4b4cb5163c491924f3c4a648009c41a4628";
const EXAMINED_ARTIFACTS_SHA256: &str =
    "c218cf0e73c67dc02854bd88295acf329d4e7aa5a39d3ba9b0fb211c311892d4";
const PREBUILT_MANIFEST_SHA256: &str =
    "9f193e6b42408a09ee0796cbff525e283836389c40a91d67aa4ec1271db8acbe";

/// Content and provenance identity of a verified tokenizer artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ArtifactIdentity {
    pub family: String,
    pub repo_id: String,
    pub revision: String,
    pub tokenizer_sha256: String,
    pub tokenizer_size: u64,
}

/// A local tokenizer whose required bytes were checked against the shipped
/// manifest during this process.
#[derive(Debug, Clone)]
pub struct LocalArtifact {
    identity: ArtifactIdentity,
    directory: PathBuf,
    tokenizer_json: PathBuf,
    bytes: Arc<[u8]>,
}

impl LocalArtifact {
    pub fn identity(&self) -> &ArtifactIdentity {
        &self.identity
    }

    pub fn directory(&self) -> &Path {
        &self.directory
    }

    pub fn tokenizer_json(&self) -> &Path {
        &self.tokenizer_json
    }

    pub(crate) fn bytes(&self) -> Arc<[u8]> {
        Arc::clone(&self.bytes)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ArtifactFileRow {
    pub(crate) sha256: String,
    pub(crate) size: u64,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ArtifactRow {
    pub(crate) repo_id: String,
    pub(crate) revision: String,
    pub(crate) files: BTreeMap<String, ArtifactFileRow>,
}

/// One family whose certified artifact is produced from pinned upstream
/// inputs rather than downloaded whole.
///
/// The shipped conversion table is the only place a converted family is
/// named; both faces read this same file, so neither can hold an opinion
/// the other does not.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ConversionRow {
    pub(crate) converter: String,
    pub(crate) inputs: Vec<ConversionInputRow>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ConversionInputRow {
    pub(crate) name: String,
}

#[derive(Debug, Deserialize)]
struct ConversionTable {
    conversions: BTreeMap<String, ConversionRow>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RepairRow {
    pub(crate) family: String,
    pub(crate) artifact_sha256: String,
    pub(crate) margin: usize,
    pub(crate) effective_l_max: usize,
    pub(crate) has_normalizer: bool,
}

/// Repair parameters a certified support record holds itself
/// (`backends.fast_cpu.repair`): the record is carried from an anchor by a
/// cross-artifact carry-over (`docs/contracts/evidence-carryover.md`
/// Section 3.1) and is not in the repair roster. The parameters equal the
/// anchor's roster row (condition C6, checked by the release check).
#[derive(Debug, Deserialize)]
struct CarriedRepair {
    margin: usize,
    effective_l_max: usize,
    has_normalizer: bool,
}

#[derive(Debug, Deserialize)]
struct RepairManifest {
    schema: String,
    pclass: PclassRow,
    families: Vec<RepairRow>,
}

#[derive(Debug, Deserialize)]
struct PclassRow {
    raw_sha256: String,
    compressed_sha256: String,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct SupportArtifact {
    pub(crate) family: String,
    pub(crate) artifact_sha256: String,
    pub(crate) pipeline_id: String,
    #[cfg_attr(not(feature = "jit"), allow(dead_code))]
    pub(crate) oracle_id: String,
    #[cfg_attr(not(feature = "jit"), allow(dead_code))]
    pub(crate) evidence_id: String,
    pub(crate) backends: BTreeMap<String, serde_json::Value>,
}

/// One row of the shipped chunked admission table
/// (`src/toktier/routing/tables/chunked_admission.v1.json`): which paths
/// of the chunk-parallel encode have recorded evidence for this artifact.
/// Generated by `tools/update_chunked_admission.py` from the campaign
/// readings. Both faces admit by the row's `status`; the Rust surface
/// reports the `native` levels as a label beside the admission.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ChunkedAdmissionRow {
    pub(crate) family: String,
    pub(crate) artifact_sha256: String,
    /// The loader-face digest the row's readings were taken on; the
    /// artifact file's own digest for a face the loader did not extend.
    #[serde(default)]
    pub(crate) loader_face_sha256: Option<String>,
    /// The row's certification status, the one the Python facade admits
    /// by: `certified` when both evidence levels are recorded for the
    /// Python path, `adversarial_only` or `corpus_only` when one is. The
    /// generator derives it from `evidence.python`, so the two always
    /// spell the same state (a unit test reads every shipped row).
    pub(crate) status: String,
    pub(crate) evidence_id: String,
    #[serde(default)]
    pub(crate) evidence: ChunkedEvidence,
}

/// The evidence levels recorded per chunked path.
#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct ChunkedEvidence {
    /// Read by the unit test that holds `status` and these levels to one
    /// state; the run-time decision reads `status`.
    #[serde(default)]
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) python: Vec<String>,
    #[serde(default)]
    pub(crate) native: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct ChunkedAdmissionTable {
    schema: String,
    schema_version: u64,
    rows: Vec<ChunkedAdmissionRow>,
}

/// One examined artifact: runnable, not certified
/// (`src/toktier/routing/tables/examined_artifacts.v1.json`, generated by
/// `tools/generate_examined_artifacts.py`). Its pipeline capability is the
/// one a certified family holds and its added-token capability no campaign
/// has judged, so the support registry carries no reading for it. Both
/// faces read the same table: the fast CPU engine runs it with the repair
/// parameters below, the route is labelled [`crate::Certification::Supported`],
/// and `Policy::Certified` refuses it.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ExaminedRow {
    pub(crate) family: String,
    pub(crate) artifact_sha256: String,
    pub(crate) pipeline_id: String,
    pub(crate) repair: ExaminedRepair,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ExaminedRepair {
    pub(crate) margin: usize,
    pub(crate) effective_l_max: usize,
    pub(crate) has_normalizer: bool,
}

#[derive(Debug, Deserialize)]
struct ExaminedTable {
    schema_version: u64,
    status: String,
    artifacts: Vec<ExaminedRow>,
}

#[derive(Debug, Deserialize)]
struct SupportRegistry {
    schema_version: u64,
    #[serde(default)]
    runtime_builds: Vec<RuntimeBuildRow>,
    artifacts: Vec<SupportArtifact>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RuntimeBuildRow {
    runtime: String,
    source_digest: String,
    build_flags: Vec<String>,
    toolchain: String,
    fast_cpu_source_digest: String,
    native_host_source_digest: String,
    evidence_id: String,
}

#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) struct KernelFamily {
    pub(crate) band: String,
    pub(crate) ruleset: String,
    pub(crate) digits_max: Option<i32>,
    pub(crate) class_table: String,
    #[serde(default)]
    pub(crate) contractions: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) struct ClassTableRow {
    pub(crate) file: String,
    pub(crate) shape: Vec<usize>,
    pub(crate) dtype: String,
    pub(crate) sha256: String,
    pub(crate) meta_file: Option<String>,
    pub(crate) meta_sha256: Option<String>,
}

#[derive(Debug, Deserialize)]
struct KernelManifest {
    schema: String,
    class_tables: BTreeMap<String, ClassTableRow>,
    bands: BTreeMap<String, KernelBand>,
    families: BTreeMap<String, KernelFamily>,
}

#[derive(Debug, Deserialize)]
struct KernelBand {
    #[serde(default)]
    e2e: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) struct PrebuiltManifest {
    pub(crate) toolchain: String,
    pub(crate) architectures: BTreeMap<String, serde_json::Value>,
    pub(crate) fatbin: PrebuiltFatbin,
    pub(crate) kernels: BTreeMap<String, String>,
}

#[derive(Debug, Clone, Deserialize)]
#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) struct PrebuiltFatbin {
    pub(crate) size: u64,
    pub(crate) digest: String,
}

#[derive(Debug, Deserialize)]
struct AliasManifest {
    schema_version: u64,
    aliases: Vec<AliasRow>,
}

#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AliasRow {
    pub(crate) repo_id: String,
    pub(crate) revision: String,
    pub(crate) source_sha256: String,
    pub(crate) source_size: u64,
    pub(crate) canonical_family: String,
    pub(crate) canonical_anchor_sha256: String,
    pub(crate) basis: String,
    pub(crate) canonical_packaged: bool,
}

/// Sibling-alias bases that admit the canonical execution artifact.
///
/// The list matches the Python-side `ALIAS_BASES` and the schema enum
/// (`schemas/sibling_aliases.schema.json`); a basis outside it is never
/// admitted, so a widened table cannot widen admission silently.
/// `equivalent_loader_face` joined in 0.2.9
/// (`docs/contracts/registry.md` Section 4.1).
pub(crate) fn admitted_alias_basis(basis: &str) -> bool {
    matches!(
        basis,
        "identical"
            | "identical_source"
            | "equivalent_canonicalisation"
            | "equivalent_serialisation"
            | "equivalent_loader_face"
    )
}

/// Where a build stands to the shipped `runtime_builds` register.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct BuildStanding {
    /// The three source identities are those of a judged row.
    pub(crate) source_identity_judged: bool,
    /// A judged row with these sources also records this build's
    /// toolchain and build flags.
    pub(crate) recipe_judged: bool,
}

#[derive(Debug)]
#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) struct Registry {
    artifacts: BTreeMap<String, ArtifactRow>,
    conversions: BTreeMap<String, ConversionRow>,
    repairs: HashMap<String, RepairRow>,
    support: HashMap<String, SupportArtifact>,
    examined: HashMap<String, ExaminedRow>,
    chunked_admission: HashMap<String, ChunkedAdmissionRow>,
    runtime_builds: Vec<RuntimeBuildRow>,
    pub(crate) kernel_families: BTreeMap<String, KernelFamily>,
    pub(crate) class_tables: BTreeMap<String, ClassTableRow>,
    pub(crate) prebuilt: PrebuiltManifest,
    pub(crate) aliases: Vec<AliasRow>,
    pclass: Vec<u8>,
}

/// The build flags of this build set beside the judged ones, as a
/// sentence a reader can act on.
///
/// Per key rather than as two lists: the reader needs the one entry to
/// change, not a diff of nine.
/// The judged row nearest a build, by symmetric difference of build flags.
///
/// Counting only the flags a row shares with the build would reward a row
/// for being long; the distance that matters is how many flags one side
/// has and the other does not. Where two rows are equally far -- which is
/// what happens to a build whose feature list is neither row's, since each
/// row then differs from it in exactly one flag on each side -- the row
/// that adds no optional feature wins, so the reader is shown the plain
/// recipe rather than an optional one.
fn nearest_judged_row<'a>(
    observed: &[&str],
    candidates: &[&'a RuntimeBuildRow],
) -> Option<&'a RuntimeBuildRow> {
    candidates.iter().copied().min_by_key(|row| {
        let missing = row
            .build_flags
            .iter()
            .filter(|flag| !observed.contains(&flag.as_str()))
            .count();
        let extra = observed
            .iter()
            .filter(|flag| !row.build_flags.iter().any(|other| other == *flag))
            .count();
        (missing + extra, usize::from(names_optional_feature(row)))
    })
}

/// Whether a judged row's feature list names an optional build feature.
///
/// The register carries one row per judged recipe, and the recipes differ
/// from the default one by naming an extra feature. When two rows are
/// equally far from the build asking, the one that adds nothing is the
/// one to hold up as the recipe.
fn names_optional_feature(row: &RuntimeBuildRow) -> bool {
    const OPTIONAL: [&str; 2] = ["jit", "network"];
    row.build_flags
        .iter()
        .filter_map(|flag| flag.strip_prefix("features="))
        .any(|features| {
            features
                .split(',')
                .any(|feature| OPTIONAL.contains(&feature.trim()))
        })
}

fn describe_flag_divergence(observed: &[&str], judged: &[String]) -> Option<String> {
    let key = |flag: &str| flag.split_once('=').map(|(key, _)| key.to_owned());
    let value = |flag: &str| flag.split_once('=').map(|(_, value)| value.to_owned());
    let mut differences = Vec::new();
    for flag in observed {
        let Some(name) = key(flag) else { continue };
        match judged
            .iter()
            .find(|other| key(other).as_deref() == Some(name.as_str()))
        {
            Some(other) if other == flag => {}
            Some(other) => differences.push(format!(
                "{name} is {:?} here and {:?} in the judged build",
                value(flag).unwrap_or_default(),
                value(other).unwrap_or_default(),
            )),
            None => differences.push(format!("{name} is not a judged build flag")),
        }
    }
    for other in judged {
        let Some(name) = key(other) else { continue };
        if !observed
            .iter()
            .any(|flag| key(flag).as_deref() == Some(name.as_str()))
        {
            differences.push(format!(
                "{name} is judged but this build does not report it"
            ));
        }
    }
    if differences.is_empty() {
        return None;
    }
    Some(format!(
        "the build flags of this build are not the judged ones: {}. Building with the judged \
         flags brings it back -- `rustflags` is the one a caller usually sets, through RUSTFLAGS \
         or a Cargo configuration file, and the judged builds set none. A build that means to \
         keep them can still take the accelerated route by selecting Policy::Experimental, which \
         labels the result experimental rather than certified",
        differences.join("; ")
    ))
}

impl Registry {
    /// Verify and parse the embedded tables once per process, then share
    /// the result. The embedded bytes are compile-time constants, so the
    /// digest checks, JSON parses, and pclass decompression in
    /// [`Registry::load_embedded`] cannot change between calls; a failure
    /// is replayed with its recorded code and message, matching the
    /// per-call verification behavior this replaces.
    pub(crate) fn load() -> Result<Arc<Self>> {
        static REGISTRY: OnceLock<std::result::Result<Arc<Registry>, (ErrorCode, String)>> =
            OnceLock::new();
        REGISTRY
            .get_or_init(|| {
                Self::load_embedded()
                    .map(Arc::new)
                    .map_err(|error| (error.code(), error.message().to_owned()))
            })
            .clone()
            .map_err(|(code, message)| Error::new(code, message))
    }

    fn load_embedded() -> Result<Self> {
        verify_embedded(
            "artifact manifest",
            ARTIFACT_MANIFEST_BYTES,
            ARTIFACT_MANIFEST_SHA256,
        )?;
        verify_embedded(
            "support registry",
            SUPPORT_REGISTRY_BYTES,
            SUPPORT_REGISTRY_SHA256,
        )?;
        verify_embedded(
            "sibling aliases",
            SIBLING_ALIASES_BYTES,
            SIBLING_ALIASES_SHA256,
        )?;
        verify_embedded(
            "repair manifest",
            REPAIR_MANIFEST_BYTES,
            REPAIR_MANIFEST_SHA256,
        )?;
        verify_embedded(
            "kernel families",
            KERNEL_FAMILIES_BYTES,
            KERNEL_FAMILIES_SHA256,
        )?;
        verify_embedded(
            "prebuilt manifest",
            PREBUILT_MANIFEST_BYTES,
            PREBUILT_MANIFEST_SHA256,
        )?;

        verify_embedded(
            "artifact conversion table",
            ARTIFACT_CONVERSIONS_BYTES,
            ARTIFACT_CONVERSIONS_SHA256,
        )?;
        verify_embedded(
            "chunked admission table",
            CHUNKED_ADMISSION_BYTES,
            CHUNKED_ADMISSION_SHA256,
        )?;
        verify_embedded(
            "examined artifact table",
            EXAMINED_ARTIFACTS_BYTES,
            EXAMINED_ARTIFACTS_SHA256,
        )?;

        let artifacts: BTreeMap<String, ArtifactRow> =
            parse_json("artifact manifest", ARTIFACT_MANIFEST_BYTES)?;
        let conversions: ConversionTable =
            parse_json("artifact conversion table", ARTIFACT_CONVERSIONS_BYTES)?;
        let repair: RepairManifest = parse_json("repair manifest", REPAIR_MANIFEST_BYTES)?;
        if repair.schema != "toktier.fast_repair_families.v1" {
            return Err(registry_error("unexpected repair manifest schema"));
        }
        verify_embedded(
            "compressed repair property table",
            REPAIR_PCLASS_COMPRESSED,
            &repair.pclass.compressed_sha256,
        )?;
        let mut decoder = ZlibDecoder::new(REPAIR_PCLASS_COMPRESSED);
        let mut pclass = Vec::with_capacity(0x11_0000);
        decoder.read_to_end(&mut pclass).map_err(|error| {
            Error::new(
                ErrorCode::RegistryInvalid,
                format!("cannot decompress repair property table: {error}"),
            )
        })?;
        if pclass.len() != 0x11_0000 || sha256_hex(&pclass) != repair.pclass.raw_sha256 {
            return Err(registry_error(
                "decompressed repair property table has the wrong identity",
            ));
        }
        let support: SupportRegistry = parse_json("support registry", SUPPORT_REGISTRY_BYTES)?;
        if support.schema_version != 1 {
            return Err(registry_error("unexpected support registry schema"));
        }
        let kernel: KernelManifest = parse_json("kernel families", KERNEL_FAMILIES_BYTES)?;
        if kernel.schema != "toktier.kernel_families.v1" {
            return Err(registry_error("unexpected kernel-family schema"));
        }
        for (family, row) in &kernel.families {
            let band = kernel.bands.get(&row.band).ok_or_else(|| {
                registry_error(format!("kernel family {family} names an unknown band"))
            })?;
            if !kernel.class_tables.contains_key(&row.class_table) {
                return Err(registry_error(format!(
                    "kernel family {family} names an unknown class table"
                )));
            }
            if !band.e2e {
                return Err(registry_error(format!(
                    "unexpected non-e2e kernel family {family}"
                )));
            }
        }
        let aliases: AliasManifest = parse_json("sibling aliases", SIBLING_ALIASES_BYTES)?;
        if aliases.schema_version != 1 {
            return Err(registry_error("unexpected sibling-alias schema"));
        }
        let prebuilt: PrebuiltManifest = parse_json("prebuilt manifest", PREBUILT_MANIFEST_BYTES)?;
        let chunked: ChunkedAdmissionTable =
            parse_json("chunked admission table", CHUNKED_ADMISSION_BYTES)?;
        if chunked.schema != "toktier.chunked_admission.v1" || chunked.schema_version != 1 {
            return Err(registry_error("unexpected chunked admission table schema"));
        }
        let mut chunked_admission = HashMap::with_capacity(chunked.rows.len());
        for row in chunked.rows {
            if chunked_admission.insert(row.family.clone(), row).is_some() {
                return Err(registry_error(
                    "the chunked admission table repeats an artifact",
                ));
            }
        }

        let examined_table: ExaminedTable =
            parse_json("examined artifact table", EXAMINED_ARTIFACTS_BYTES)?;
        if examined_table.schema_version != 1 || examined_table.status != "examined" {
            return Err(registry_error("unexpected examined artifact table schema"));
        }
        let mut examined = HashMap::with_capacity(examined_table.artifacts.len());
        for row in examined_table.artifacts {
            if repair
                .families
                .iter()
                .any(|certified| certified.artifact_sha256 == row.artifact_sha256)
                || support
                    .artifacts
                    .iter()
                    .any(|certified| certified.artifact_sha256 == row.artifact_sha256)
            {
                return Err(registry_error(format!(
                    "examined artifact {} is also a certified one",
                    row.family
                )));
            }
            if examined.insert(row.family.clone(), row).is_some() {
                return Err(registry_error(
                    "the examined artifact table repeats a family",
                ));
            }
        }

        let mut repairs: HashMap<String, RepairRow> = repair
            .families
            .into_iter()
            .map(|row| (row.family.clone(), row))
            .collect();
        // Carried records hold their own repair parameters; they join the
        // same lookup the roster rows answer, so the fast CPU route and the
        // chunked roster test treat them alike. A family or digest that
        // the roster or the examined table already names is an
        // inconsistent installation and is refused.
        for row in &support.artifacts {
            let Some(raw) = row
                .backends
                .get("fast_cpu")
                .and_then(|entry| entry.get("repair"))
            else {
                continue;
            };
            let carried: CarriedRepair = serde_json::from_value(raw.clone()).map_err(|error| {
                registry_error(format!(
                    "carried repair parameters of {} are malformed: {error}",
                    row.family
                ))
            })?;
            if repairs.contains_key(&row.family)
                || repairs
                    .values()
                    .any(|other| other.artifact_sha256 == row.artifact_sha256)
                || examined.contains_key(&row.family)
                || examined
                    .values()
                    .any(|other| other.artifact_sha256 == row.artifact_sha256)
            {
                return Err(registry_error(format!(
                    "carried repair parameters of {} collide with another repair source",
                    row.family
                )));
            }
            repairs.insert(
                row.family.clone(),
                RepairRow {
                    family: row.family.clone(),
                    artifact_sha256: row.artifact_sha256.clone(),
                    margin: carried.margin,
                    effective_l_max: carried.effective_l_max,
                    has_normalizer: carried.has_normalizer,
                },
            );
        }
        let runtime_builds = support.runtime_builds;
        let support = support
            .artifacts
            .into_iter()
            .map(|row| (row.family.clone(), row))
            .collect();
        Ok(Self {
            artifacts,
            conversions: conversions.conversions,
            repairs,
            support,
            examined,
            chunked_admission,
            runtime_builds,
            kernel_families: kernel.families,
            class_tables: kernel.class_tables,
            prebuilt,
            aliases: aliases.aliases,
            pclass,
        })
    }

    pub(crate) fn artifact(&self, family: &str) -> Result<&ArtifactRow> {
        self.artifacts.get(family).ok_or_else(|| {
            let mut message = format!("unknown tokenizer family {family:?}");
            // The same closest-id hint the Python facade gives, from the
            // same ranking, so a typo is answered identically on either
            // surface. Nothing is suggested when nothing is close.
            let suggestions =
                crate::suggest::close_matches(family, self.artifacts.keys().map(String::as_str));
            if !suggestions.is_empty() {
                let rendered = suggestions
                    .iter()
                    .map(|candidate| format!("{candidate:?}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                message.push_str(&format!("; closest valid family IDs: {rendered}"));
            }
            Error::new(ErrorCode::ArtifactNotFound, message).with_family(family)
        })
    }

    /// The conversion recipe of `family`, when its artifact is derived
    /// locally rather than published.
    pub(crate) fn conversion(&self, family: &str) -> Option<&ConversionRow> {
        self.conversions.get(family)
    }

    pub(crate) fn artifacts(&self) -> impl Iterator<Item = (&str, &ArtifactRow)> {
        self.artifacts
            .iter()
            .map(|(family, row)| (family.as_str(), row))
    }

    /// The canonical family whose shipped `tokenizer.json` carries this
    /// digest, when this build packages one.
    ///
    /// Canonical artifacts only: a sibling repository whose file is
    /// byte-identical to a canonical one carries the canonical digest
    /// and is found here; one admitted as equivalent rather than
    /// identical has another digest and is reached through
    /// `resolve_repo` by its repository and revision instead.
    pub(crate) fn family_for_tokenizer_sha256(&self, sha256: &str) -> Option<&str> {
        self.artifacts
            .iter()
            .find(|(_, row)| {
                row.files
                    .get("tokenizer.json")
                    .is_some_and(|file| file.sha256 == sha256)
            })
            .map(|(family, _)| family.as_str())
    }

    pub(crate) fn repair(&self, family: &str) -> Option<&RepairRow> {
        self.repairs.get(family)
    }

    pub(crate) fn support(&self, family: &str) -> Option<&SupportArtifact> {
        self.support.get(family)
    }

    /// The examined-artifact row of `family`, when it is an examined
    /// (not certified) one.
    pub(crate) fn examined(&self, family: &str) -> Option<&ExaminedRow> {
        self.examined.get(family)
    }

    /// The certified support rows holding `pipeline_id`, in family order:
    /// the records whose fast CPU entry an examined artifact with the same
    /// pipeline capability is planned against.
    pub(crate) fn pipeline_peers(&self, pipeline_id: &str) -> Vec<&SupportArtifact> {
        let mut peers = self
            .support
            .values()
            .filter(|row| row.pipeline_id == pipeline_id)
            .collect::<Vec<_>>();
        peers.sort_by(|left, right| left.family.cmp(&right.family));
        peers
    }

    /// The chunked admission row of `family`, when the shipped table has
    /// one; the caller compares its artifact digest.
    pub(crate) fn chunked_admission(&self, family: &str) -> Option<&ChunkedAdmissionRow> {
        self.chunked_admission.get(family)
    }

    /// Why the build flags of this build are not the judged ones, when
    /// that is what stands between it and certification.
    ///
    /// `certified = false` should never be a verdict without a reason a
    /// reader can act on, and the flags are the axis most likely to be
    /// the reader's own doing. Reported only when a judged row agrees
    /// with this build on every other axis: when the sources or the
    /// toolchain differ, the flags are not the thing to change.
    pub(crate) fn rust_api_build_flag_divergence(&self) -> Option<String> {
        let observed = env!("TOKTIER_RUST_API_BUILD_FLAGS")
            .split('\x1f')
            .collect::<Vec<_>>();
        // Rows built from these sources, whatever compiler built them:
        // since 0.3.0 the toolchain is reported on its own axis
        // (`rust_api_toolchain_divergence`), so a build on another rustc
        // still learns which flag differs.
        let candidates = self.judged_rows_for_these_sources().collect::<Vec<_>>();
        if candidates.is_empty()
            || candidates
                .iter()
                .any(|row| row.build_flags.iter().eq(observed.iter().copied()))
        {
            return None;
        }
        // The row nearest this build, so that naming every difference
        // against every row does not bury the one the reader has to
        // change. Nearest is the smallest symmetric difference: counting
        // only the flags a row shares with this build rewards a row for
        // being long, and the rows this register carries differ by a
        // single feature token. Where that still ties -- it does for a
        // build whose feature list is neither row's -- the plain row wins
        // over an optional-feature one, because the reader building
        // without that option should be told what the plain recipe is.
        let closest = nearest_judged_row(&observed, &candidates).expect("a candidate row");
        describe_flag_divergence(&observed, &closest.build_flags)
    }

    /// The judged rows whose three source identities are this build's.
    /// (Named by their sources, not their recipes: since 0.3.0 the
    /// sources are what admit the fast CPU engine.)
    fn judged_rows_for_these_sources(&self) -> impl Iterator<Item = &RuntimeBuildRow> {
        self.runtime_builds.iter().filter(|row| {
            row.runtime == "rust_api"
                && row.source_digest == env!("TOKTIER_RUST_API_SOURCE_SHA256")
                && row.fast_cpu_source_digest == env!("TOKTIER_RUST_API_FAST_CPU_SOURCE_SHA256")
                && row.native_host_source_digest
                    == env!("TOKTIER_RUST_API_NATIVE_HOST_SOURCE_SHA256")
                && !row.evidence_id.is_empty()
        })
    }

    /// Where this build stands to the judged builds of the register, on
    /// the two axes the register binds besides the compiled closure.
    ///
    /// The rows still describe the judged builds exactly -- sources,
    /// toolchain, flags -- and nothing about them changed. What changed
    /// in 0.3.0 is the rule read against them: the source identities
    /// are what admits the fast CPU engine, and the toolchain and flags
    /// decide the label it is admitted under. A build from the judged
    /// sources on a compiler no campaign used is `supported_untested`
    /// under `Policy::Supported`, the way an unjudged GPU architecture
    /// has been since 0.2.6 -- and, by the user's rule of 2026-10-14,
    /// under every policy but `Reference`: the label carries the recipe,
    /// the reference route is for sources that do not verify.
    pub(crate) fn rust_api_build_standing(&self) -> BuildStanding {
        let observed_flags = env!("TOKTIER_RUST_API_BUILD_FLAGS")
            .split('\x1f')
            .map(str::to_owned)
            .collect::<Vec<_>>();
        let mut rows = self.judged_rows_for_these_sources().peekable();
        let source_identity_judged = rows.peek().is_some();
        let recipe_judged = rows.any(|row| {
            row.build_flags == observed_flags && row.toolchain == env!("TOKTIER_RUST_API_TOOLCHAIN")
        });
        BuildStanding {
            source_identity_judged,
            recipe_judged,
        }
    }

    /// Why the compiler of this build is not a judged one, when the
    /// sources are: the toolchain this build reports beside the ones the
    /// judged rows for these sources record, and what the difference
    /// means for the fast CPU route. `None` when a judged row records
    /// this toolchain, or when the sources themselves are not judged
    /// (the toolchain is then not the thing to change).
    pub(crate) fn rust_api_toolchain_divergence(&self) -> Option<String> {
        let mut judged = self
            .judged_rows_for_these_sources()
            .map(|row| row.toolchain.as_str())
            .collect::<Vec<_>>();
        judged.sort_unstable();
        judged.dedup();
        if judged.is_empty() || judged.contains(&env!("TOKTIER_RUST_API_TOOLCHAIN")) {
            return None;
        }
        Some(format!(
            "this build was compiled by `{}`; the judged builds from these sources were compiled \
             by `{}`. The fast CPU engine is the judged one by source identity, so it is admitted \
             under every policy but Reference and labelled Certification::Supported \
             (supported_untested) rather than CertifiedSource. `toktier-rust verify-local --engine \
             cpu` compares the two engines on this machine",
            env!("TOKTIER_RUST_API_TOOLCHAIN"),
            judged.join("`, `")
        ))
    }

    pub(crate) fn rust_api_build_certified(&self) -> bool {
        // The register binds compile-time facts about this crate's own
        // sources. Those sources are compiled together with whatever
        // versions Cargo resolved for the transitive graph, so the judged
        // recipe is the judged sources, the judged toolchain and flags,
        // the workspace members as the judged copies, and every reference
        // library at a version the certificate speaks for. Anything less
        // is a label, not a refusal (`rust_api_sources_judged`); the
        // implementation libraries and everything else the build compiles
        // are compared and reported (`crate::DEPENDENCY_CLOSURE`).
        if !crate::behavior_version::core_closure_verified()
            || crate::behavior_version::reference_certification_reason().is_some()
        {
            return false;
        }
        let standing = self.rust_api_build_standing();
        standing.source_identity_judged && standing.recipe_judged
    }

    /// Whether the fast CPU engine of this build is the judged one by
    /// source identity: the three digests are those of a judged row, and
    /// the closure says this crate's own siblings are the judged copies
    /// (or could not be compared for want of a lockfile). This is what
    /// admits the fast CPU route under every policy but `Reference`,
    /// since 0.3.0 (user rule of 2026-10-14); the compiler, the flags and
    /// the reference libraries are labels on it.
    pub(crate) fn rust_api_sources_judged(&self) -> bool {
        self.rust_api_build_standing().source_identity_judged
            && crate::behavior_version::sources_closure_admits()
    }

    pub(crate) fn pclass(&self) -> Vec<u8> {
        self.pclass.clone()
    }

    pub(crate) fn resolve_repo(&self, repo_id: &str, revision: &str) -> Result<String> {
        if let Some((family, _)) = self
            .artifacts
            .iter()
            .find(|(_, row)| row.repo_id == repo_id && row.revision == revision)
        {
            return Ok(family.clone());
        }
        let alias = self
            .aliases
            .iter()
            .find(|row| row.repo_id == repo_id && row.revision == revision)
            .ok_or_else(|| {
                Error::new(
                    ErrorCode::UncertifiedTokenizer,
                    format!("{repo_id}@{revision} is not in the shipped verified-repository table"),
                )
            })?;
        if !alias.canonical_packaged
            || alias.source_sha256.len() != 64
            || alias.source_size == 0
            || !admitted_alias_basis(alias.basis.as_str())
        {
            return Err(Error::new(
                ErrorCode::UncertifiedTokenizer,
                format!("{repo_id}@{revision} has no admitted canonical execution artifact"),
            ));
        }
        let canonical = self.artifact(&alias.canonical_family)?;
        let file = canonical
            .files
            .get("tokenizer.json")
            .ok_or_else(|| registry_error("canonical artifact does not bind tokenizer.json"))?;
        if file.sha256 != alias.canonical_anchor_sha256 {
            return Err(registry_error("sibling alias canonical anchor drifted"));
        }
        Ok(alias.canonical_family.clone())
    }

    pub(crate) fn verify_local(
        &self,
        family: &str,
        cache_root: &Path,
        explicit: Option<&Path>,
    ) -> Result<LocalArtifact> {
        let row = self.artifact(family)?;
        let file = row.files.get("tokenizer.json").ok_or_else(|| {
            registry_error(format!("artifact {family} does not bind tokenizer.json"))
        })?;
        let directory = explicit.map_or_else(
            || cache_root.join(format!("{}-{}", family, &row.revision[..12])),
            Path::to_path_buf,
        );
        // An explicit path may be, or lead through, a symbolic link (a hub
        // snapshot directory holds `tokenizer.json` as a link into its blob
        // store). It is resolved once here; the bytes verified below are
        // read from the resolved file and are the ones served. The default
        // cache entry keeps the stricter rule: a regular file, not a link.
        let given_is_link = explicit.is_some()
            && fs::symlink_metadata(&directory)
                .is_ok_and(|metadata| metadata.file_type().is_symlink())
            && !directory.is_dir();
        let tokenizer_json = if directory.is_file() || given_is_link {
            directory.clone()
        } else {
            directory.join("tokenizer.json")
        };
        let resolved = if explicit.is_some() {
            fs::canonicalize(&tokenizer_json).map_err(|error| {
                Error::new(
                    ErrorCode::ArtifactNotFound,
                    format!("verified tokenizer artifact is unavailable: {error}"),
                )
                .with_path(&tokenizer_json)
                .with_family(family)
            })?
        } else {
            tokenizer_json.clone()
        };
        let metadata = fs::symlink_metadata(&resolved).map_err(|error| {
            Error::new(
                ErrorCode::ArtifactNotFound,
                format!("verified tokenizer artifact is unavailable: {error}"),
            )
            .with_path(&tokenizer_json)
            .with_family(family)
        })?;
        if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
            let message = if explicit.is_some() {
                "tokenizer artifact must be a regular file"
            } else {
                "tokenizer artifact must be a regular, non-symlink file"
            };
            return Err(Error::new(ErrorCode::ArtifactNotFound, message)
                .with_path(&tokenizer_json)
                .with_family(family));
        }
        if metadata.len() != file.size {
            return Err(Error::new(
                ErrorCode::ArtifactSizeMismatch,
                format!(
                    "tokenizer.json has {} bytes; manifest requires {}",
                    metadata.len(),
                    file.size
                ),
            )
            .with_path(&tokenizer_json)
            .with_family(family));
        }
        let bytes = fs::read(&resolved).map_err(|error| {
            Error::new(ErrorCode::Io, error.to_string())
                .with_path(&tokenizer_json)
                .with_family(family)
        })?;
        let observed = sha256_hex(&bytes);
        if observed != file.sha256 {
            return Err(Error::new(
                ErrorCode::ArtifactHashMismatch,
                format!(
                    "tokenizer.json digest mismatch: expected {}, observed {observed}",
                    file.sha256
                ),
            )
            .with_path(&tokenizer_json)
            .with_family(family));
        }
        let artifact_directory = tokenizer_json
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .to_path_buf();
        Ok(LocalArtifact {
            identity: ArtifactIdentity {
                family: family.to_owned(),
                repo_id: row.repo_id.clone(),
                revision: row.revision.clone(),
                tokenizer_sha256: file.sha256.clone(),
                tokenizer_size: file.size,
            },
            directory: artifact_directory,
            tokenizer_json,
            bytes: bytes.into(),
        })
    }
}

fn parse_json<T: for<'de> Deserialize<'de>>(name: &str, bytes: &[u8]) -> Result<T> {
    serde_json::from_slice(bytes).map_err(|error| {
        Error::new(
            ErrorCode::RegistryInvalid,
            format!("cannot parse shipped {name}: {error}"),
        )
    })
}

fn verify_embedded(name: &str, bytes: &[u8], expected: &str) -> Result<()> {
    let observed = sha256_hex(bytes);
    if observed == expected.trim_start_matches("sha256:") {
        Ok(())
    } else {
        Err(registry_error(format!(
            "shipped {name} digest mismatch: expected {expected}, observed {observed}"
        )))
    }
}

pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
    crate::fsutil::hex(&Sha256::digest(bytes))
}

#[cfg_attr(not(feature = "prebuilt-gpu"), allow(dead_code))]
pub(crate) fn domain_sha256_hex(domain: &[u8], bytes: &[u8]) -> String {
    let mut digest = Sha256::new();
    digest.update(domain);
    digest.update(bytes);
    crate::fsutil::hex(&digest.finalize())
}

fn registry_error(message: impl Into<String>) -> Error {
    Error::new(ErrorCode::RegistryInvalid, message)
}

#[cfg(test)]
mod tests {
    use super::{
        admitted_alias_basis, describe_flag_divergence, nearest_judged_row, parse_json,
        registry_error, verify_embedded, ArtifactRow, ChunkedAdmissionTable, RuntimeBuildRow,
        CHUNKED_ADMISSION_BYTES, SUPPORT_REGISTRY_BYTES, SUPPORT_REGISTRY_SHA256,
    };
    use crate::ErrorCode;

    /// Every examined artifact the crate ships is fetchable, is not a
    /// certified one, and has a certified support row holding its pipeline
    /// capability with an eligible fast CPU entry -- the binding its route
    /// is admitted against.
    #[test]
    fn every_examined_artifact_has_a_certified_pipeline_peer() {
        let registry = super::Registry::load().expect("embedded tables load");
        for (family, row) in &registry.examined {
            assert!(registry.support(family).is_none(), "{family} is certified");
            assert!(
                registry.repair(family).is_none(),
                "{family} has a roster row"
            );
            let pinned = registry
                .artifact(family)
                .expect("examined family is in the artifact manifest")
                .files
                .get("tokenizer.json")
                .expect("tokenizer.json is pinned")
                .sha256
                .clone();
            assert_eq!(pinned, row.artifact_sha256);
            let peers = registry.pipeline_peers(&row.pipeline_id);
            assert!(
                peers.iter().any(|peer| peer
                    .backends
                    .get("fast_cpu")
                    .and_then(|entry| entry.get("status"))
                    .and_then(serde_json::Value::as_str)
                    == Some("certified_source")),
                "{family} has no certified pipeline peer"
            );
        }
    }

    /// The examined table ships with no row in this release; the embedded
    /// table still parses, and an examined row keeps its shape.
    #[test]
    fn the_shipped_examined_table_is_empty_and_rows_still_parse() {
        let registry = super::Registry::load().expect("embedded tables load");
        assert!(registry.examined.is_empty());
        let table: super::ExaminedTable = serde_json::from_str(
            r#"{"schema_version": 1, "status": "examined", "artifacts": [{
                "family": "examined_fixture",
                "artifact_sha256": "eeee",
                "pipeline_id": "pipeline.9f6d5117c3680d0e",
                "repair": {"margin": 36, "effective_l_max": 128, "has_normalizer": true}
            }]}"#,
        )
        .expect("an examined row parses");
        assert_eq!(table.artifacts.len(), 1);
        assert_eq!(table.artifacts[0].repair.margin, 36);
    }

    /// Carried records join the repair lookup with their own parameters,
    /// equal to their anchors' roster rows.
    #[test]
    fn carried_records_hold_their_anchors_repair_parameters() {
        let registry = super::Registry::load().expect("embedded tables load");
        for (family, anchor) in [
            ("deepseek_v4_1_flash", "deepseek_v4_flash"),
            ("mimo_v2_6", "qwen3_8b"),
        ] {
            let carried = registry.repair(family).expect("carried repair row");
            let support = registry.support(family).expect("certified record");
            assert_eq!(carried.artifact_sha256, support.artifact_sha256);
            let anchor = registry.repair(anchor).expect("anchor roster row");
            assert_eq!(
                (
                    carried.margin,
                    carried.effective_l_max,
                    carried.has_normalizer
                ),
                (anchor.margin, anchor.effective_l_max, anchor.has_normalizer)
            );
        }
    }

    /// Both faces admit by a chunked row's `status`, which the table
    /// generator derives from the Python path's evidence levels: every
    /// shipped row spells the state its own levels spell, so reading the
    /// status and reading the levels are one decision.
    #[test]
    fn every_chunked_row_status_is_the_state_its_python_levels_spell() {
        let table: ChunkedAdmissionTable =
            parse_json("chunked admission table", CHUNKED_ADMISSION_BYTES).unwrap();
        assert!(!table.rows.is_empty());
        for row in &table.rows {
            assert_eq!(
                crate::chunked::levels_status(&row.evidence.python).as_deref(),
                Some(row.status.as_str()),
                "{}",
                row.family
            );
        }
    }

    /// Every recorded sibling basis admits the canonical execution
    /// artifact, the 0.2.9 loader-face basis included: a table row with
    /// any of these values must load and resolve, not be refused as an
    /// unknown basis.
    #[test]
    fn alias_admission_accepts_every_recorded_basis() {
        for basis in [
            "identical",
            "identical_source",
            "equivalent_canonicalisation",
            "equivalent_serialisation",
            "equivalent_loader_face",
        ] {
            assert!(admitted_alias_basis(basis), "{basis} must be admitted");
        }
    }

    /// A basis outside the recorded vocabulary never admits: a widened
    /// or damaged table cannot widen admission silently.
    #[test]
    fn alias_admission_refuses_an_unrecorded_basis() {
        for basis in ["", "equivalent", "loader_face", "equivalent_loader_face2"] {
            assert!(!admitted_alias_basis(basis), "{basis:?} must not admit");
        }
    }

    /// A judged row carrying one feature list, with every other axis
    /// equal to the build under test: the divergence reporter only ever
    /// sees rows that already agree on sources and toolchain.
    fn judged_row(features: &str) -> RuntimeBuildRow {
        RuntimeBuildRow {
            runtime: "rust_api".to_owned(),
            source_digest: "s".to_owned(),
            build_flags: vec![
                "profile=release".to_owned(),
                "opt-level=3".to_owned(),
                "target=x86_64-unknown-linux-gnu".to_owned(),
                "debug=false".to_owned(),
                "target-features=fxsr,sse,sse2".to_owned(),
                "rustflags=".to_owned(),
                format!("features={features}"),
            ],
            toolchain: "t".to_owned(),
            fast_cpu_source_digest: "f".to_owned(),
            native_host_source_digest: "n".to_owned(),
            evidence_id: "e".to_owned(),
        }
    }

    /// The build flags a build with this feature list reports about itself,
    /// in the shape the register records them.
    fn observed_flags(features: &str) -> Vec<String> {
        judged_row(features).build_flags
    }

    /// From 0.2.5 the register carries two rows whose feature lists differ
    /// by one token, and a build with `network` matches neither. It is the
    /// same distance from both, so the tie is what decides which recipe
    /// the reader is shown -- and the recipe to show is the default one,
    /// not the one that also turns on an unrelated optional feature. The
    /// reader is being told which flag to change, and `jit` is not it.
    #[test]
    fn the_divergence_reference_is_the_plain_recipe_not_an_optional_one() {
        let default_row = judged_row("default,prebuilt-gpu,serving,sqlite");
        let jit_row = judged_row("default,jit,prebuilt-gpu,serving,sqlite");
        let flags = observed_flags("default,network,prebuilt-gpu,serving,sqlite");
        let observed = flags.iter().map(String::as_str).collect::<Vec<_>>();

        for candidates in [vec![&default_row, &jit_row], vec![&jit_row, &default_row]] {
            let chosen = nearest_judged_row(&observed, &candidates).expect("a candidate row");
            assert_eq!(
                chosen.build_flags.last().map(String::as_str),
                Some("features=default,prebuilt-gpu,serving,sqlite"),
                "the plain recipe is the reference whatever order the rows arrive in",
            );
            let message = describe_flag_divergence(&observed, &chosen.build_flags)
                .expect("a build with network diverges from the default recipe");
            assert!(
                message.contains("network") && !message.contains("jit"),
                "the reported difference names the feature the reader turned on: {message}",
            );
        }
    }

    /// Distance, not overlap: a row that shares more flags simply because
    /// it carries more of them is not nearer. The exact row still wins
    /// outright, which is the case the caller short-circuits before ever
    /// asking.
    #[test]
    fn the_nearest_row_is_the_one_with_the_smallest_difference() {
        let exact = judged_row("default,prebuilt-gpu,serving,sqlite");
        let far = judged_row("default,jit,network,serde,serving,sqlite");
        let flags = observed_flags("default,prebuilt-gpu,serving,sqlite");
        let observed = flags.iter().map(String::as_str).collect::<Vec<_>>();
        let candidates = vec![&far, &exact];

        let chosen = nearest_judged_row(&observed, &candidates).expect("a candidate row");
        assert_eq!(
            chosen.build_flags.last().map(String::as_str),
            Some("features=default,prebuilt-gpu,serving,sqlite"),
        );
        assert_eq!(
            describe_flag_divergence(&observed, &chosen.build_flags),
            None
        );
    }

    /// Every shipped table is admitted by its digest and then by its
    /// shape, and both refusals are `REGISTRY_INVALID`: a package whose
    /// own records do not hold together is not a caller error. The
    /// product bytes stay untouched here -- these are the two gates
    /// themselves, asked about bytes that are not the shipped ones.
    #[test]
    fn a_shipped_record_that_does_not_hold_together_is_refused() {
        // The shipped bytes pass their own digest.
        verify_embedded(
            "support registry",
            SUPPORT_REGISTRY_BYTES,
            SUPPORT_REGISTRY_SHA256,
        )
        .expect("the shipped registry verifies");

        let error = verify_embedded(
            "support registry",
            b"not the shipped bytes",
            SUPPORT_REGISTRY_SHA256,
        )
        .expect_err("a digest mismatch");
        assert_eq!(error.code(), ErrorCode::RegistryInvalid);
        assert_eq!(error.code().as_str(), "REGISTRY_INVALID");
        assert!(
            error.message().contains("digest mismatch")
                && error.message().contains("support registry"),
            "{}",
            error.message()
        );

        // A digest that verifies over the wrong shape still stops here.
        let error = parse_json::<ArtifactRow>("artifact manifest", b"{\"repo_id\": 7}")
            .expect_err("a shape mismatch");
        assert_eq!(error.code(), ErrorCode::RegistryInvalid);
        assert!(
            error
                .message()
                .starts_with("cannot parse shipped artifact manifest"),
            "{}",
            error.message()
        );

        // And the cross-reference refusals share the code.
        let error = registry_error("kernel family x names an unknown band");
        assert_eq!(error.code(), ErrorCode::RegistryInvalid);
    }

    fn judged() -> Vec<String> {
        [
            "profile=release",
            "opt-level=3",
            "target=x86_64-unknown-linux-gnu",
            "debug=false",
            "target-features=fxsr,sse,sse2",
            "rustflags=",
            "features=default,network,prebuilt-gpu,serving,sqlite",
        ]
        .into_iter()
        .map(str::to_owned)
        .collect()
    }

    #[test]
    fn matching_flags_have_nothing_to_report() {
        let judged = judged();
        let observed = judged.iter().map(String::as_str).collect::<Vec<_>>();
        assert_eq!(describe_flag_divergence(&observed, &judged), None);
    }

    /// The one a caller sets themselves, and the reason this key is
    /// admitted at all: it is the codegen switch a build script can
    /// actually observe.
    #[test]
    fn a_caller_s_rustflags_are_named_with_both_ways_out() {
        let judged = judged();
        let mut observed = judged.clone();
        observed[5] = "rustflags=-C target-cpu=native".to_owned();
        let observed = observed.iter().map(String::as_str).collect::<Vec<_>>();

        let reported = describe_flag_divergence(&observed, &judged).expect("a divergence");

        assert!(
            reported.contains(
                "rustflags is \"-C target-cpu=native\" here and \"\" in the judged build"
            ),
            "{reported}"
        );
        assert!(reported.contains("RUSTFLAGS"), "{reported}");
        assert!(reported.contains("Policy::Experimental"), "{reported}");
        assert!(!reported.contains('\n'), "{reported}");
    }

    #[test]
    fn only_the_keys_that_differ_are_named() {
        let judged = judged();
        let mut observed = judged.clone();
        observed[1] = "opt-level=2".to_owned();
        let observed = observed.iter().map(String::as_str).collect::<Vec<_>>();

        let reported = describe_flag_divergence(&observed, &judged).expect("a divergence");

        assert!(reported.contains("opt-level is \"2\""), "{reported}");
        assert!(!reported.contains("profile is"), "{reported}");
        assert!(!reported.contains("rustflags is"), "{reported}");
    }

    #[test]
    fn a_key_on_only_one_side_is_named_as_such() {
        let judged = judged();
        let observed = ["profile=release", "lto=fat"];
        let reported = describe_flag_divergence(&observed, &judged).expect("a divergence");
        assert!(
            reported.contains("lto is not a judged build flag"),
            "{reported}"
        );
        assert!(
            reported.contains("rustflags is judged but this build does not report it"),
            "{reported}"
        );
    }
}