decision-cert 0.6.0

Verify and apply decision-certificate.v1: signed records of how a model's decisions were measured
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
//! Load, verify and apply decision certificates: `decision-certificate.v1`
//! (spec/decision-certificate.v1.md), `decision-certificate.v1.1` (spec/decision-certificate.v1.1.md)
//! `decision-certificate.v1.2` (spec/decision-certificate.v1.2.md), `decision-certificate.v1.3`
//! (spec/decision-certificate.v1.3.md), `decision-certificate.v1.4` (spec/decision-certificate.v1.4.md)
//! and `decision-certificate.v1.5` (spec/decision-certificate.v1.5.md).
//!
//! Verification canonicalises the JSON value exactly as received (RFC 8785, JCS), never a
//! re-serialised struct, so number formatting can't drift from the issuer's. The typed
//! [`Certificate`] is read from the same value afterwards, rejecting unknown fields.
//!
//! A v1.2 certificate also stores the confidence histogram of its threshold split, so a consumer can
//! monitor without labels: [`Histogram::of`] bins a window of use-time confidences and
//! [`shift_score`] compares it with the stored one. The score is descriptive, a prompt to measure
//! again; it never shows that the bound holds or has failed.
//!
//! [`probabilities`] applies a certificate's calibration map to a case's raw scores, for the map
//! kinds v1.2 defines (`temperature` and `dr`, [`MAP_KINDS`]).
//!
//! A v1.3 certificate also names the options a consumer automates (`automate_options`) and reports,
//! per test, the share and error of the answered cases whose answer is one of them ([`Automated`]).
//!
//! A v1.5 certificate also names its `tenant` and who signed it ([`Signer`]: the tenant as operator,
//! or a hosting service for the tenant), and its signature covers the tenant. It is verified with
//! the tenant the consumer expects and that tenant's moded keys: [`verify_for_tenant`]. [`verify`]
//! keeps its meaning for v1 to v1.4 and refuses a v1.5 certificate.

mod map;
mod monitor;

pub use map::{confidence, probabilities, MAP_KINDS};
pub use monitor::{bin_of, chi2_sf, shift_score, ShiftScore};

use std::collections::BTreeMap;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use chrono::{DateTime, Utc};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::Deserialize;
use sha2::{Digest, Sha256};

/// The `spec` of a certificate produced by the v1 procedure.
pub const SPEC: &str = "decision-certificate.v1";
/// The `spec` of a certificate produced by the v1.1 procedure (the per-test grid start).
pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
/// The `spec` of a v1.2 certificate: v1.1's procedure, plus the stored confidence histogram.
pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
/// The `spec` of a v1.3 certificate: v1.2, plus the automated options and their answered share and
/// error per test.
pub const SPEC_V1_3: &str = "decision-certificate.v1.3";
/// The `spec` of a v1.4 certificate: v1.3, plus the cost risk `selective_cost`.
pub const SPEC_V1_4: &str = "decision-certificate.v1.4";
/// The `spec` of a v1.5 certificate: v1.4, plus `tenant` and `signer`, signed over bytes that bind
/// the tenant.
pub const SPEC_V1_5: &str = "decision-certificate.v1.5";
/// Every `spec` this verifier accepts. v1 and v1.1 have the same fields; v1.2 adds some, v1.3 more,
/// v1.4 more again, v1.5 more again.
pub const SPECS: [&str; 6] = [SPEC, SPEC_V1_1, SPEC_V1_2, SPEC_V1_3, SPEC_V1_4, SPEC_V1_5];
/// The context string a v1.5 signature's bytes start with (spec v1.5 §3).
pub const CONTEXT_V1_5: &str = "decision-cert/certificate.v1.5";
/// The longest `tenant` (spec v1.5 §2).
pub const MAX_TENANT: usize = 128;
/// Most bins a `confidence_bins` may define.
pub const MAX_BINS: usize = 100;
/// `abstain_below` that abstains on every case (as `dk calibrate` writes it).
pub const ABSTAIN_ALL: f64 = 1.01;

#[derive(Debug, thiserror::Error)]
pub enum CertError {
    #[error("certificate is not a valid decision certificate: {0}")]
    Invalid(String),
    #[error("certificate signed by {0}, which is not a trusted key")]
    UntrustedKey(String),
    #[error("trusted key {0} is malformed or does not hash to its id")]
    BadKey(String),
    #[error("certificate signature does not verify")]
    BadSignature,
    /// v1.5 check 1: the certificate's `tenant` is not the tenant the verifier expects.
    #[error("certificate is for tenant {0}, not the expected tenant")]
    WrongTenant(String),
    /// v1.5 check 3 (and an earlier certificate under a hosted key): the key's entry does not allow
    /// the certificate's signer mode, or its `host` is not the certificate's.
    #[error("trusted key {0} may not sign in this mode")]
    KeyMode(String),
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Band {
    pub level: f64,
    pub low: f64,
    pub high: f64,
}

/// A test's threshold-split cases per bin of `confidence_bins`, and the cases the rule abstains on
/// whatever the threshold (unscored, or above the `cannot_tell` cut). v1.2.
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Histogram {
    pub counts: Vec<u64>,
    pub unscored: u64,
}

/// A test's answered cases whose answer is one of `automate_options` (v1.3): their share of the
/// test's `n` cases, and `ucb` and `realized_band` of their error, as the test's own (descriptive,
/// spec v1.2 §1.2). Null exactly where the test's are.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Automated {
    pub coverage: f64,
    #[serde(deserialize_with = "nullable")]
    pub ucb: Option<f64>,
    #[serde(deserialize_with = "nullable")]
    pub realized_band: Option<Band>,
    /// v1.4 only (absent before v1.4): the automated cases' exact sum of whole costs under
    /// `selective_cost`; present and null otherwise.
    #[serde(default, deserialize_with = "present")]
    pub loss_sum: Option<Option<u64>>,
    /// v1.4 only (absent before v1.4): the automated cases' mean normalised cost under
    /// `selective_cost`, `loss_sum / (c_max * answered)`; present and null otherwise.
    #[serde(default, deserialize_with = "present")]
    pub realized_cost: Option<Option<f64>>,
}

/// A v1.4 `selective_cost` certificate's costs: `matrix[label][answered option]`, in the options'
/// order, whole numbers in the consumer's `unit` (informational), and its largest entry `c_max`.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Cost {
    pub matrix: Vec<Vec<u64>>,
    pub c_max: u64,
    #[serde(deserialize_with = "nullable")]
    pub unit: Option<String>,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Segment {
    pub field: String,
    pub value: String,
    pub n: u64,
    pub abstain_below: f64,
    pub coverage: f64,
    #[serde(deserialize_with = "nullable")]
    pub ucb: Option<f64>,
    #[serde(deserialize_with = "nullable")]
    pub realized_band: Option<Band>,
    pub inherited: bool,
    /// v1.2 only: absent (None) before v1.2; present and null (Some(None)) when withheld.
    #[serde(default, deserialize_with = "present")]
    pub confidence_histogram: Option<Option<Histogram>>,
    /// v1.3 only: absent (None) before v1.3.
    #[serde(default, deserialize_with = "present")]
    pub automated: Option<Automated>,
    /// v1.4 only: absent (None) before v1.4.
    #[serde(default, deserialize_with = "present")]
    pub loss_sum: Option<Option<u64>>,
    /// v1.4 only: absent (None) before v1.4.
    #[serde(default, deserialize_with = "present")]
    pub realized_cost: Option<Option<f64>>,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Split {
    pub method: String,
    #[serde(deserialize_with = "nullable")]
    pub seed: Option<i64>,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CalibrationMap {
    pub kind: String,
    pub params: BTreeMap<String, f64>,
    #[serde(deserialize_with = "nullable")]
    pub label_budget: Option<u64>,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Rule {
    #[serde(deserialize_with = "nullable")]
    pub cannot_tell_above: Option<f64>,
    pub unscored: String,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Window {
    pub start: String,
    pub end: String,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Audit {
    pub mode: String,
    pub rate: f64,
    pub n: u64,
    pub propensity_logged: bool,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Issuer {
    pub tool: String,
    pub version: String,
}

/// Who signed a v1.5 certificate: `mode` `operator` (the tenant, with its own key; no `host`), or
/// `hosted` (a hosting service for the tenant; `host` is the hosting service's own key id,
/// `ed25519:<16 lowercase hex>`).
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Signer {
    pub mode: String,
    #[serde(default, deserialize_with = "present")]
    pub host: Option<String>,
}

/// Every field is required; `Option` fields must be present (as null): a missing field is an error.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Certificate {
    pub spec: String,
    pub domain: String,
    pub decision: String,
    pub options: Vec<String>,
    pub model_id: String,
    #[serde(deserialize_with = "nullable")]
    pub manifest_hash: Option<String>,
    pub data_hash: String,
    pub n_cal: u64,
    pub n_temperature: u64,
    pub split: Split,
    pub calibration_map: CalibrationMap,
    pub rule: Rule,
    pub alpha: f64,
    #[serde(deserialize_with = "nullable")]
    pub delta: Option<f64>,
    pub method: String,
    pub risk: String,
    pub n: u64,
    pub abstain_below: f64,
    pub coverage: f64,
    #[serde(deserialize_with = "nullable")]
    pub ucb: Option<f64>,
    pub realized_band: Band,
    pub segments: Vec<Segment>,
    #[serde(deserialize_with = "nullable")]
    pub window: Option<Window>,
    pub fitted_at: String,
    pub expires_at: String,
    pub audit: Audit,
    pub issuer: Issuer,
    pub signer_key_id: String,
    pub signature: String,
    /// v1.2 only (absent, so None, before v1.2): the histogram bin edges, rising from 0 to 1.
    #[serde(default, deserialize_with = "present")]
    pub confidence_bins: Option<Vec<f64>>,
    /// v1.2 only: the remainder's histogram; present and null (Some(None)) when withheld.
    #[serde(default, deserialize_with = "present")]
    pub confidence_histogram: Option<Option<Histogram>>,
    /// v1.3 only (absent before v1.3): the options a consumer decides automatically; a case answered
    /// with another option goes to a person.
    #[serde(default, deserialize_with = "present")]
    pub automate_options: Option<Vec<String>>,
    /// v1.3 only: the remainder's automated cases.
    #[serde(default, deserialize_with = "present")]
    pub automated: Option<Automated>,
    /// v1.4 only (absent before v1.4): the costs of a `selective_cost` certificate; present and null
    /// for the error risks.
    #[serde(default, deserialize_with = "present")]
    pub cost: Option<Option<Cost>>,
    /// v1.4 only: the `ltt` p-value, `binomial` or `hoeffding_bentkus`; null for `crc`.
    #[serde(default, deserialize_with = "present")]
    pub pvalue: Option<Option<String>>,
    /// v1.4 only: the remainder's exact sum of whole costs over its answered cases.
    #[serde(default, deserialize_with = "present")]
    pub loss_sum: Option<Option<u64>>,
    /// v1.4 only: the remainder's mean normalised cost of its answered cases (descriptive).
    #[serde(default, deserialize_with = "present")]
    pub realized_cost: Option<Option<f64>>,
    /// v1.5 only (absent before v1.5): the tenant the certificate is issued for.
    #[serde(default, deserialize_with = "present")]
    pub tenant: Option<String>,
    /// v1.5 only: who signed, the tenant as operator or a hosting service for it.
    #[serde(default, deserialize_with = "present")]
    pub signer: Option<Signer>,
}

/// A field that may be absent (with `default`, as None) but, when present, is read as `T`: so a
/// present null reads as `Some(None)` for `T = Option<_>`, and is an error for any other `T`.
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    d: D,
) -> Result<Option<T>, D::Error> {
    T::deserialize(d).map(Some)
}

/// A present field that may be null. serde reads a missing `Option` as null, the spec does not:
/// with `deserialize_with` and no `default`, a missing field is an error at every level.
fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
    d: D,
) -> Result<Option<T>, D::Error> {
    Option::deserialize(d)
}

/// A certificate whose signature verified against a trusted key.
#[derive(Clone, Debug, PartialEq)]
pub struct Verified {
    /// `sha256:<hex>` of the signed certificate's JCS bytes.
    pub id: String,
    pub cert: Certificate,
    pub expires_at: DateTime<Utc>,
}

impl Verified {
    /// The threshold for a case in `segment`: a certified segment's own, else the top-level one.
    pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
        segment
            .and_then(|v| {
                self.cert
                    .segments
                    .iter()
                    .find(|s| !s.inherited && s.value == v)
            })
            .map_or(self.cert.abstain_below, |s| s.abstain_below)
    }

    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
        now >= self.expires_at
    }

    /// The bin edges of a v1.2 certificate's confidence histograms; None before v1.2.
    pub fn confidence_bins(&self) -> Option<&[f64]> {
        self.cert.confidence_bins.as_deref()
    }

    /// The stored confidence histogram of the cases decided by the same threshold as a case in
    /// `segment`: a certified segment's own, else the top level's. None before v1.2, or when the
    /// issuer withheld it.
    pub fn histogram_for(&self, segment: Option<&str>) -> Option<&Histogram> {
        let own = segment.and_then(|v| {
            self.cert
                .segments
                .iter()
                .find(|s| !s.inherited && s.value == v)
        });
        match own {
            Some(s) => s.confidence_histogram.as_ref()?.as_ref(),
            None => self.cert.confidence_histogram.as_ref()?.as_ref(),
        }
    }

    /// The options a v1.3 certificate's consumer automates; None before v1.3. A consumer refuses a
    /// certificate whose list differs from the options it automates (spec v1.3 §4).
    pub fn automate_options(&self) -> Option<&[String]> {
        self.cert.automate_options.as_deref()
    }

    /// The automated cases of the test that decides a case in `segment` (a certified segment's own,
    /// else the top level's): their share and error. None before v1.3.
    pub fn automated_for(&self, segment: Option<&str>) -> Option<&Automated> {
        let own = segment.and_then(|v| {
            self.cert
                .segments
                .iter()
                .find(|s| !s.inherited && s.value == v)
        });
        match own {
            Some(s) => s.automated.as_ref(),
            None => self.cert.automated.as_ref(),
        }
    }

    /// A v1.4 `selective_cost` certificate's costs; None otherwise. A consumer refuses a certificate
    /// whose matrix differs from the costs it is configured with (spec v1.4 §4), and reports the
    /// bound as `alpha * c_max` in `unit`.
    pub fn cost(&self) -> Option<&Cost> {
        self.cert.cost.as_ref().and_then(|c| c.as_ref())
    }

    /// A v1.5 certificate's tenant (equal to the expected tenant it was verified with); None before
    /// v1.5.
    pub fn tenant(&self) -> Option<&str> {
        self.cert.tenant.as_deref()
    }

    /// Who signed a v1.5 certificate; None before v1.5.
    pub fn signer(&self) -> Option<&Signer> {
        self.cert.signer.as_ref()
    }

    /// The probabilities the certificate's calibration map gives a case's raw scores, one per
    /// option (spec v1.2 §1, [`probabilities`]). None when the map's kind is not one this crate
    /// applies ([`MAP_KINDS`]), its params do not fit that kind, or `scores` does not have one score
    /// per option, or the map is `dr` in a certificate before v1.2, which did not define it. A
    /// consumer refuses a certificate whose map it does not apply (spec v1.2 §4).
    pub fn probabilities(&self, scores: &[f64]) -> Option<Vec<f64>> {
        let defined = self.cert.calibration_map.kind == "temperature"
            || self.cert.spec == SPEC_V1_2
            || self.cert.spec == SPEC_V1_3
            || self.cert.spec == SPEC_V1_4
            || self.cert.spec == SPEC_V1_5;
        (defined && scores.len() == self.cert.options.len())
            .then(|| probabilities(&self.cert.calibration_map, scores))
            .flatten()
    }

    /// A case's confidence: the largest of its [`Verified::probabilities`]. A case is answered when
    /// this is at least [`Verified::threshold_for`] its segment (and the rule does not abstain on it).
    pub fn confidence(&self, scores: &[f64]) -> Option<f64> {
        self.probabilities(scores)
            .map(|p| p.into_iter().fold(f64::NEG_INFINITY, f64::max))
    }

    /// The temperature of a `kind: temperature` calibration map; None for other kinds.
    pub fn temperature(&self) -> Option<f64> {
        (self.cert.calibration_map.kind == "temperature")
            .then(|| self.cert.calibration_map.params.get("temperature").copied())
            .flatten()
    }
}

/// The JCS bytes of a JSON value.
pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
    serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
}

pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
    Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
}

/// `ed25519:` + the first 16 hex chars of SHA-256 of the raw public key.
pub fn key_id(key: &VerifyingKey) -> String {
    format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
}

/// Verify `v` against `keys` (key id → base64url raw public key) and read it.
///
/// For v1 to v1.4. A v1.5 certificate binds a tenant, so it is refused here; verify it with the
/// tenant the consumer expects, [`verify_for_tenant`].
pub fn verify(
    v: &serde_json::Value,
    keys: &BTreeMap<String, String>,
) -> Result<Verified, CertError> {
    let (obj, cert) = read(v)?;
    if cert.spec == SPEC_V1_5 {
        return Err(CertError::Invalid(
            "a v1.5 certificate is verified with its expected tenant (verify_for_tenant)".into(),
        ));
    }
    let raw = keys
        .get(&cert.signer_key_id)
        .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
    let key = public_key(raw, &cert.signer_key_id)?;
    check_signature(&key, &cert, &bare_body(obj)?)?;
    verified(v, cert)
}

/// The mode a trusted key may sign in (spec v1.5 §4): `Operator` (the tenant's own key, as every key
/// in v1 to v1.4), or `Hosted` by the hosting service whose own key id is `host`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeyMode {
    Operator,
    Hosted { host: String },
}

/// A trusted certificate-signing key of one tenant: the base64url raw Ed25519 public key, and the
/// mode it may sign in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrustedKey {
    pub key: String,
    pub mode: KeyMode,
}

/// One tenant's trusted keys: key id → [`TrustedKey`].
pub type TenantKeys = BTreeMap<String, TrustedKey>;

/// Read a tenant's trusted keys from a JSON object of key id → entry. An entry is a bare base64url
/// string (an `operator` key, as in a v1 to v1.4 key map), `{"key": ..., "mode": "operator"}`, or
/// `{"key": ..., "mode": "hosted", "host": "ed25519:<16 lowercase hex>"}` (spec v1.5 §4). Any
/// other entry, an unknown field, or a `host` not in that form is refused as [`CertError::BadKey`].
/// The key is checked against its id when a certificate is verified, as in [`verify`].
pub fn tenant_keys_from_json(v: &serde_json::Value) -> Result<TenantKeys, CertError> {
    let obj = v.as_object().ok_or_else(|| {
        CertError::Invalid("trusted keys are not a JSON object of key id -> key entry".into())
    })?;
    let mut out = TenantKeys::new();
    for (kid, entry) in obj {
        let bad = || CertError::BadKey(kid.clone());
        let trusted = match entry {
            serde_json::Value::String(key) => TrustedKey {
                key: key.clone(),
                mode: KeyMode::Operator,
            },
            serde_json::Value::Object(e) => {
                if e.keys()
                    .any(|k| !matches!(k.as_str(), "key" | "mode" | "host"))
                {
                    return Err(bad());
                }
                let key = e.get("key").and_then(|k| k.as_str()).ok_or_else(bad)?;
                let host = e.get("host");
                let mode = match (e.get("mode").and_then(|m| m.as_str()), host) {
                    (Some("operator"), None) => KeyMode::Operator,
                    (Some("hosted"), Some(serde_json::Value::String(h))) if key_id_form(h) => {
                        KeyMode::Hosted { host: h.clone() }
                    }
                    _ => return Err(bad()),
                };
                TrustedKey {
                    key: key.to_string(),
                    mode,
                }
            }
            _ => return Err(bad()),
        };
        out.insert(kid.clone(), trusted);
    }
    Ok(out)
}

/// Verify `v` for the tenant the consumer expects, against that tenant's moded keys, and read it
/// (spec v1.5 §4).
///
/// A v1.5 certificate: its `tenant` equals `tenant` (check 1, [`CertError::WrongTenant`]); its key
/// is in `keys` and hashes to its id (check 2); the key's entry allows the certificate's signer mode,
/// a hosted entry with the certificate's `host` (check 3, [`CertError::KeyMode`]); and the signature
/// verifies strictly over `"decision-cert/certificate.v1.5" 0x0A tenant 0x0A JCS(body)`, built with
/// the expected `tenant` (check 4). A v1 to v1.4 certificate binds no tenant: it verifies as with
/// [`verify`], and only under an `operator` entry.
pub fn verify_for_tenant(
    v: &serde_json::Value,
    tenant: &str,
    keys: &TenantKeys,
) -> Result<Verified, CertError> {
    if !tenant_ok(tenant) {
        return Err(CertError::Invalid(format!(
            "the expected tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
        )));
    }
    let (obj, cert) = read(v)?;
    let kid = &cert.signer_key_id;
    if cert.spec != SPEC_V1_5 {
        let entry = keys
            .get(kid)
            .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
        let key = public_key(&entry.key, kid)?;
        if entry.mode != KeyMode::Operator {
            return Err(CertError::KeyMode(kid.clone()));
        }
        check_signature(&key, &cert, &bare_body(obj)?)?;
        return verified(v, cert);
    }
    // check() has made both present, the tenant well-formed and the signer one of the two modes
    let (Some(own), Some(signer)) = (&cert.tenant, &cert.signer) else {
        return Err(CertError::Invalid(
            "a v1.5 certificate needs tenant and signer".into(),
        ));
    };
    if own != tenant {
        return Err(CertError::WrongTenant(own.clone()));
    }
    let entry = keys
        .get(kid)
        .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
    let key = public_key(&entry.key, kid)?;
    let allowed = match (&entry.mode, signer.mode.as_str()) {
        (KeyMode::Operator, "operator") => true,
        (KeyMode::Hosted { host }, "hosted") => signer.host.as_deref() == Some(host.as_str()),
        _ => false,
    };
    if !allowed {
        return Err(CertError::KeyMode(kid.clone()));
    }
    let mut msg = format!("{CONTEXT_V1_5}\n{tenant}\n").into_bytes();
    msg.extend(bare_body(obj)?);
    check_signature(&key, &cert, &msg)?;
    verified(v, cert)
}

/// The value as a JSON object and its typed, checked certificate.
fn read(
    v: &serde_json::Value,
) -> Result<(&serde_json::Map<String, serde_json::Value>, Certificate), CertError> {
    let obj = v
        .as_object()
        .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
    let cert: Certificate =
        serde_json::from_value(v.clone()).map_err(|e| CertError::Invalid(e.to_string()))?;
    check(&cert)?;
    Ok((obj, cert))
}

/// A trusted key's base64url raw public key, which must hash to `kid`.
fn public_key(raw: &str, kid: &str) -> Result<VerifyingKey, CertError> {
    URL_SAFE_NO_PAD
        .decode(raw)
        .ok()
        .and_then(|b| <[u8; 32]>::try_from(b).ok())
        .and_then(|b| VerifyingKey::from_bytes(&b).ok())
        .filter(|k| key_id(k) == kid)
        .ok_or_else(|| CertError::BadKey(kid.to_string()))
}

/// The JCS bytes of the certificate without `signature`.
fn bare_body(obj: &serde_json::Map<String, serde_json::Value>) -> Result<Vec<u8>, CertError> {
    let mut body = obj.clone();
    body.remove("signature");
    canonical(&serde_json::Value::Object(body))
}

/// `verify_strict` of the certificate's signature over `msg`.
fn check_signature(key: &VerifyingKey, cert: &Certificate, msg: &[u8]) -> Result<(), CertError> {
    let sig = URL_SAFE_NO_PAD
        .decode(&cert.signature)
        .ok()
        .and_then(|b| Signature::from_slice(&b).ok())
        .ok_or(CertError::BadSignature)?;
    key.verify_strict(msg, &sig)
        .map_err(|_| CertError::BadSignature)
}

fn verified(v: &serde_json::Value, cert: Certificate) -> Result<Verified, CertError> {
    Ok(Verified {
        id: certificate_id(v)?,
        expires_at: timestamp(&cert.expires_at)?,
        cert,
    })
}

/// 1 to 128 characters of `A-Z a-z 0-9 . _ : -` (spec v1.5 §2).
fn tenant_ok(t: &str) -> bool {
    (1..=MAX_TENANT).contains(&t.len())
        && t.bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'))
}

/// `ed25519:` and 16 lowercase hex characters: a key id's form.
fn key_id_form(s: &str) -> bool {
    s.strip_prefix("ed25519:")
        .is_some_and(|h| h.len() == 16 && lower_hex(h))
}

/// The schema's constraints (spec/decision-certificate.v1.schema.json, the v1.1 schema, which
/// differs only in `spec`, and the v1.2 schema) that a typed read doesn't already enforce, so this
/// verifier accepts exactly what the schemas accept; and for v1.2, the histogram and calibration map
/// checks the schema cannot express (spec v1.2 §2).
fn check(c: &Certificate) -> Result<(), CertError> {
    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
    let unit = |x: f64| (0.0..=1.0).contains(&x);
    let open = |x: f64| x > 0.0 && x < 1.0;
    let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
    if !SPECS.contains(&c.spec.as_str()) {
        return bad("spec is not decision-certificate.v1, decision-certificate.v1.1, decision-certificate.v1.2, decision-certificate.v1.3, decision-certificate.v1.4 or decision-certificate.v1.5");
    }
    fields_for_spec(c)?;
    let mut seen = std::collections::BTreeSet::new();
    if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
        return bad("options needs at least 2 distinct non-empty ids");
    }
    if [
        &c.domain,
        &c.decision,
        &c.calibration_map.kind,
        &c.issuer.tool,
        &c.issuer.version,
    ]
    .iter()
    .any(|s| s.is_empty())
    {
        return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
    }
    let v15 = c.spec == SPEC_V1_5;
    let v14 = c.spec == SPEC_V1_4 || v15;
    match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
        ("ltt", "selective_error", Some(d), _) if open(d) => {}
        ("ltt", "selective_cost", Some(d), _) if v14 && open(d) => {}
        ("crc", "joint_error", None, None) => {}
        _ => return bad("method, risk, delta and ucb disagree"),
    }
    if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
        return bad("alpha, abstain_below or coverage out of range");
    }
    if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
        return bad("ucb or realized_band out of range");
    }
    for s in &c.segments {
        if s.field.is_empty()
            || !threshold(s.abstain_below)
            || !unit(s.coverage)
            || s.ucb.is_some_and(|u| !unit(u))
            || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
        {
            return bad("a segment is out of range");
        }
    }
    if !matches!(
        (c.split.method.as_str(), c.split.seed),
        ("time", None) | ("seeded", Some(_))
    ) {
        return bad("split.method and split.seed disagree");
    }
    if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
        return bad("rule out of range");
    }
    if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
        || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
    {
        return bad("audit out of range");
    }
    if !model_id_ok(&c.model_id) {
        return bad("model_id must be <backend>/<model>@<version>");
    }
    if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
        return bad("data_hash and manifest_hash must be sha256:<64 hex>");
    }
    if !key_id_form(&c.signer_key_id) {
        return bad("signer_key_id must be ed25519:<16 hex>");
    }
    if c.signature.len() != 86
        || !c
            .signature
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    {
        return bad("signature must be 86 base64url characters");
    }
    timestamp(&c.fitted_at)?;
    timestamp(&c.expires_at)?;
    if let Some(w) = &c.window {
        timestamp(&w.start)?;
        timestamp(&w.end)?;
    }
    if c.spec == SPEC_V1_2 || c.spec == SPEC_V1_3 || v14 {
        histograms(c)?;
        map::check(&c.calibration_map, c.options.len())?;
    }
    if c.spec == SPEC_V1_3 || v14 {
        automated(c)?;
    }
    if v14 {
        cost(c)?;
    }
    if v15 {
        if !c.tenant.as_deref().is_some_and(tenant_ok) {
            return Err(CertError::Invalid(format!(
                "tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
            )));
        }
        let signer_ok =
            c.signer
                .as_ref()
                .is_some_and(|s| match (s.mode.as_str(), s.host.as_deref()) {
                    ("operator", None) => true,
                    ("hosted", Some(h)) => key_id_form(h),
                    _ => false,
                });
        if !signer_ok {
            return bad("signer must be {\"mode\": \"operator\"} or {\"mode\": \"hosted\", \"host\": \"ed25519:<16 hex>\"}");
        }
    }
    Ok(())
}

/// A v1.2 certificate has every v1.2 field, a v1.3 certificate every v1.2 and v1.3 field, and an
/// earlier certificate none of them, at the top level and in every segment. A certificate whose
/// fields belong to another spec is refused as a spec it is not, so a v1.1-shaped certificate naming
/// v1.2, or a v1.2-shaped one naming v1.3, is still refused as an unknown spec.
fn fields_for_spec(c: &Certificate) -> Result<(), CertError> {
    let v15 = c.spec == SPEC_V1_5;
    let v14 = c.spec == SPEC_V1_4 || v15;
    let v13 = c.spec == SPEC_V1_3 || v14;
    let v12 = c.spec == SPEC_V1_2 || v13;
    // (name, present, required by this spec): the v1.2 fields first, then the v1.3 ones.
    let mut present = vec![
        ("confidence_bins", c.confidence_bins.is_some(), v12),
        (
            "confidence_histogram",
            c.confidence_histogram.is_some(),
            v12,
        ),
        ("automate_options", c.automate_options.is_some(), v13),
        ("automated", c.automated.is_some(), v13),
        ("cost", c.cost.is_some(), v14),
        ("pvalue", c.pvalue.is_some(), v14),
        ("loss_sum", c.loss_sum.is_some(), v14),
        ("realized_cost", c.realized_cost.is_some(), v14),
        ("tenant", c.tenant.is_some(), v15),
        ("signer", c.signer.is_some(), v15),
    ];
    for s in &c.segments {
        present.push((
            "segments[].confidence_histogram",
            s.confidence_histogram.is_some(),
            v12,
        ));
        present.push(("segments[].automated", s.automated.is_some(), v13));
        present.push(("segments[].loss_sum", s.loss_sum.is_some(), v14));
        present.push(("segments[].realized_cost", s.realized_cost.is_some(), v14));
    }
    if let Some(a) = &c.automated {
        present.push(("automated.loss_sum", a.loss_sum.is_some(), v14));
        present.push(("automated.realized_cost", a.realized_cost.is_some(), v14));
    }
    for s in &c.segments {
        if let Some(a) = &s.automated {
            present.push(("segments[].automated.loss_sum", a.loss_sum.is_some(), v14));
            present.push((
                "segments[].automated.realized_cost",
                a.realized_cost.is_some(),
                v14,
            ));
        }
    }
    for (name, here, required) in present {
        if required && !here {
            return Err(CertError::Invalid(format!(
                "spec is not consistent with the fields: {} requires `{name}`",
                c.spec
            )));
        }
        if !required && here {
            return Err(CertError::Invalid(format!(
                "unknown field `{name}` in a {} certificate",
                c.spec
            )));
        }
    }
    Ok(())
}

/// v1.2's checks beyond the schema: the bins rise strictly from 0 to 1, and each histogram has one
/// count per bin and counts exactly its test's `n` cases.
fn histograms(c: &Certificate) -> Result<(), CertError> {
    let bins = c.confidence_bins.as_deref().unwrap_or_default();
    let rising = bins.windows(2).all(|w| w[0] < w[1]);
    if !(2..=MAX_BINS + 1).contains(&bins.len())
        || bins[0] != 0.0
        || bins[bins.len() - 1] != 1.0
        || !rising
    {
        return Err(CertError::Invalid(format!(
            "confidence_bins must rise strictly from 0 to 1, with 1 to {MAX_BINS} bins"
        )));
    }
    let tests = std::iter::once((&c.confidence_histogram, c.n))
        .chain(c.segments.iter().map(|s| (&s.confidence_histogram, s.n)));
    for (h, n) in tests {
        if let Some(Some(h)) = h {
            let total: u128 =
                h.counts.iter().map(|&x| u128::from(x)).sum::<u128>() + u128::from(h.unscored);
            if h.counts.len() != bins.len() - 1 || total != u128::from(n) {
                return Err(CertError::Invalid(
                    "a confidence_histogram needs one count per bin, and its counts and unscored must sum to n".into(),
                ));
            }
        }
    }
    Ok(())
}

/// v1.3's checks beyond the schema: `automate_options` names options of the certificate, once each
/// and in their order; each test's `automated` share is at most its `coverage`, its numbers are in
/// range, and its `ucb` and `realized_band` are null exactly where the test's are.
fn automated(c: &Certificate) -> Result<(), CertError> {
    let auto = c.automate_options.as_deref().unwrap_or_default();
    let mut at = c.options.iter();
    if auto.is_empty() || !auto.iter().all(|o| at.any(|x| x == o)) {
        return Err(CertError::Invalid(
            "automate_options must name one or more of the options, once each and in their order"
                .into(),
        ));
    }
    let unit = |x: f64| (0.0..=1.0).contains(&x);
    let tests = std::iter::once((
        &c.automated,
        c.coverage,
        c.ucb.is_some(),
        true, // the top level's realized_band is never null
    ))
    .chain(c.segments.iter().map(|s| {
        (
            &s.automated,
            s.coverage,
            s.ucb.is_some(),
            s.realized_band.is_some(),
        )
    }));
    for (a, coverage, ucb, band) in tests {
        let Some(a) = a else { continue };
        if !unit(a.coverage)
            || a.coverage > coverage
            || a.ucb.is_some_and(|u| !unit(u))
            || a.realized_band.as_ref().is_some_and(|b| !band_ok(b))
            || a.ucb.is_some() != ucb
            || a.realized_band.is_some() != band
        {
            return Err(CertError::Invalid(
                "automated must agree with its test: coverage at most the test's, and ucb and realized_band null exactly where the test's are".into(),
            ));
        }
    }
    // Every option automated: the automated cases are the answered cases, so each block is its
    // test's own numbers.
    if auto.len() == c.options.len() {
        let same = |a: &Option<Automated>, coverage: f64, ucb: Option<f64>, band: Option<&Band>| {
            a.as_ref().is_none_or(|a| {
                a.coverage == coverage && a.ucb == ucb && a.realized_band.as_ref() == band
            })
        };
        // v1.4: the loss sums (whole numbers, compared exactly) and realized costs agree too (both
        // absent before v1.4)
        let same_cost =
            |a: &Option<Automated>, ls: Option<Option<u64>>, rc: Option<Option<f64>>| {
                a.as_ref()
                    .is_none_or(|a| a.loss_sum == ls && a.realized_cost == rc)
            };
        if !same(&c.automated, c.coverage, c.ucb, Some(&c.realized_band))
            || !same_cost(&c.automated, c.loss_sum, c.realized_cost)
            || !c
                .segments
                .iter()
                .all(|s| same(&s.automated, s.coverage, s.ucb, s.realized_band.as_ref()))
            || !c
                .segments
                .iter()
                .all(|s| same_cost(&s.automated, s.loss_sum, s.realized_cost))
        {
            return Err(CertError::Invalid(
                "automated must equal its test's coverage, ucb and realized_band when every option is automated".into(),
            ));
        }
    }
    Ok(())
}

/// v1.4's checks beyond the schema (spec v1.4 §2): `cost` and `pvalue` pair with `risk`; the cost
/// matrix is options x options with a zero diagonal, whole-number entries in [0, c_max], `c_max` its
/// largest entry, above 0 and at most 10^6, and its off-diagonal entries not all equal; `loss_sum`
/// and `realized_cost` are null for the error risks, for an inherited segment and wherever their test
/// answered no case, and otherwise `loss_sum` is at most c_max * k and `realized_cost` is exactly
/// `loss_sum / (c_max * k)`, k = floor(coverage * n + 1/2) the answered cases.
/// v1.4: the largest `c_max`.
pub const MAX_C: u64 = 1_000_000;
/// v1.4: the largest `c_max * answered`, 2^53, so that it and every `loss_sum` are exact in an f64.
const SAFE_SCALE: f64 = 9_007_199_254_740_992.0;

fn cost(c: &Certificate) -> Result<(), CertError> {
    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
    let cost = c.cost.clone().flatten();
    let pvalue = c.pvalue.clone().flatten();
    let want = match c.risk.as_str() {
        "selective_error" => Some("binomial"),
        "selective_cost" => Some("hoeffding_bentkus"),
        _ => None,
    };
    if cost.is_some() != (c.risk == "selective_cost") || pvalue.as_deref() != want {
        return bad("cost, pvalue and risk disagree");
    }
    if let Some(k) = &cost {
        let n = c.options.len();
        let m = &k.matrix;
        let all = || m.iter().flatten().copied();
        let ok = m.len() == n
            && m.iter().all(|r| r.len() == n)
            && (0..n).all(|i| m[i][i] == 0)
            && all().all(|x| x <= k.c_max)
            && (1..=MAX_C).contains(&k.c_max)
            && all().max() == Some(k.c_max)
            && k.unit.as_deref() != Some("");
        if !ok {
            return bad("cost.matrix must be options x options with a zero diagonal and entries in [0, c_max], c_max its largest entry, above 0 and at most 10^6");
        }
        let off: Vec<u64> = (0..n)
            .flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j)))
            .map(|(i, j)| m[i][j])
            .collect();
        if off.iter().all(|&x| x == off[0]) {
            return bad("a cost risk needs unequal off-diagonal costs; with equal costs it is selective_error");
        }
    }
    let unit = |x: f64| (0.0..=1.0).contains(&x);
    // (realized_cost, loss_sum, coverage, its test's n, own test): each test, and each test's automated
    // cases, whose coverage is a share of the test's n
    type Row = (Option<f64>, Option<u64>, f64, u64, bool);
    let auto = |a: &Option<Automated>, n: u64, own: bool| -> Row {
        a.as_ref().map_or((None, None, 0.0, n, own), |a| {
            (
                a.realized_cost.flatten(),
                a.loss_sum.flatten(),
                a.coverage,
                n,
                own,
            )
        })
    };
    let mut tests: Vec<Row> = vec![(
        c.realized_cost.flatten(),
        c.loss_sum.flatten(),
        c.coverage,
        c.n,
        true,
    )];
    tests.extend(c.segments.iter().map(|s| {
        (
            s.realized_cost.flatten(),
            s.loss_sum.flatten(),
            s.coverage,
            s.n,
            !s.inherited,
        )
    }));
    tests.push(auto(&c.automated, c.n, true));
    tests.extend(
        c.segments
            .iter()
            .map(|s| auto(&s.automated, s.n, !s.inherited)),
    );
    for (rc, ls, coverage, n, own) in tests {
        let expect = cost.is_some() && own && coverage > 0.0;
        if rc.is_some() != expect || ls.is_some() != expect || rc.is_some_and(|x| !unit(x)) {
            return bad("realized_cost and loss_sum must be null for the error risks, an inherited segment and a test that answered no case, and only there");
        }
        if let (Some(rc), Some(ls), Some(k)) = (rc, ls, &cost) {
            // whole costs: one exact division, so every verifier, in any language, gets the same
            // number. Both operands are exact in f64 (at most 2^53).
            let answered = (coverage * n as f64 + 0.5).floor();
            // k can't be fudged by rounding: coverage is exactly k / n, one correctly rounded division
            // of two exact integers, as the issuer writes it
            if !(1..=1u64 << 53).contains(&n) || coverage != answered / n as f64 {
                return bad(
                    "coverage must be exactly answered / n, a whole number of answered cases",
                );
            }
            let ok = (1.0..=SAFE_SCALE).contains(&answered) && {
                let scale = u128::from(k.c_max) * answered as u128;
                scale <= SAFE_SCALE as u128
                    && u128::from(ls) <= scale
                    && rc == ls as f64 / scale as f64
            };
            if !ok {
                return bad("realized_cost must be loss_sum / (c_max * answered), with loss_sum at most c_max * answered");
            }
        }
    }
    Ok(())
}

/// `^[^/]+/.+@.+$`, and not ending in `@?` (an unknown version).
fn model_id_ok(m: &str) -> bool {
    // The pattern's `.` matches no line terminator.
    if m.chars()
        .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
    {
        return false;
    }
    let Some((backend, rest)) = m.split_once('/') else {
        return false;
    };
    let at = rest
        .char_indices()
        .skip(1)
        .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
    !backend.is_empty() && at && !m.ends_with("@?")
}

fn sha256_ok(h: &str) -> bool {
    h.strip_prefix("sha256:")
        .is_some_and(|x| x.len() == 64 && lower_hex(x))
}

fn lower_hex(s: &str) -> bool {
    s.bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn band_ok(b: &Band) -> bool {
    b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
}

/// Parse the spec's timestamp form, `YYYY-MM-DDTHH:MM:SSZ`, and nothing else.
pub fn timestamp(s: &str) -> Result<DateTime<Utc>, CertError> {
    // The schema's `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$` exactly: chrono also takes `t` or a space.
    let b = s.as_bytes();
    let ok = b.len() == 20
        && b.iter().enumerate().all(|(i, &c)| match i {
            4 | 7 => c == b'-',
            10 => c == b'T',
            13 | 16 => c == b':',
            19 => c == b'Z',
            _ => c.is_ascii_digit(),
        });
    DateTime::parse_from_rfc3339(s)
        .ok()
        .filter(|_| ok)
        .map(|t| t.with_timezone(&Utc))
        .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
}

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

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

    fn valid() -> serde_json::Value {
        let f: serde_json::Value =
            serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
                .unwrap();
        f["certificate"].clone()
    }

    /// v1 and v1.1 define only `temperature`, so a `dr` map in one of them gives no probabilities,
    /// though the certificate verifies as it always did.
    #[test]
    fn dr_maps_are_applied_in_v1_2_certificates_only() {
        let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
        cert.calibration_map = CalibrationMap {
            kind: "dr".into(),
            params: [("a", 1.0), ("b0", 0.0), ("b1", 0.0)]
                .iter()
                .map(|(k, v)| (k.to_string(), *v))
                .collect(),
            label_budget: None,
        };
        let v = Verified {
            id: String::new(),
            cert,
            expires_at: Utc::now(),
        };
        assert!(v.probabilities(&[1.0, 0.0]).is_none() && v.confidence(&[1.0, 0.0]).is_none());
        let mut v12 = v.clone();
        v12.cert.spec = SPEC_V1_2.into();
        assert!(v12.confidence(&[1.0, 0.0]).unwrap() > 0.73);
    }

    #[test]
    fn check_rejects_what_the_schema_rejects() {
        let typed =
            |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
        assert!(check(&typed(&valid())).is_ok());
        let edits: [(&str, serde_json::Value); 15] = [
            ("data_hash", serde_json::json!("sha256:XYZ")),
            ("manifest_hash", serde_json::json!("md5:00")),
            ("signer_key_id", serde_json::json!("ed25519:short")),
            ("model_id", serde_json::json!("/x@y")),
            ("model_id", serde_json::json!("b/m@?")),
            (
                "window",
                serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
            ),
            ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
            ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
            ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
            ("domain", serde_json::json!("")),
            ("options", serde_json::json!(["yes", "yes"])),
            ("split", serde_json::json!({"method": "time", "seed": 3})),
            ("alpha", serde_json::json!(1.0)),
            ("signature", serde_json::json!("abc")),
            ("model_id", serde_json::json!("a/b\n@c")),
        ];
        for (field, value) in edits {
            let mut v = valid();
            v[field] = value.clone();
            assert!(check(&typed(&v)).is_err(), "{field} = {value}");
        }
    }

    #[test]
    fn nested_nullable_fields_must_be_present() {
        let paths: [(&str, &str); 5] = [
            ("segments", "ucb"),
            ("segments", "realized_band"),
            ("split", "seed"),
            ("calibration_map", "label_budget"),
            ("rule", "cannot_tell_above"),
        ];
        for (outer, inner) in paths {
            let mut v = valid();
            let o = if outer == "segments" {
                &mut v[outer][0]
            } else {
                &mut v[outer]
            };
            o.as_object_mut().unwrap().remove(inner);
            let e = serde_json::from_value::<Certificate>(v).err();
            assert!(
                e.is_some_and(|e| e.to_string().contains(inner)),
                "{outer}.{inner}"
            );
        }
    }

    /// The same table as python/tests/test_ed25519.py: every small-order encoding is a key
    /// `verify_strict` refuses (the Python verifier must refuse the same ones).
    #[test]
    fn small_order_keys_are_weak() {
        let table = [
            "0100000000000000000000000000000000000000000000000000000000000000",
            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
            "0000000000000000000000000000000000000000000000000000000000000000",
            "0000000000000000000000000000000000000000000000000000000000000080",
            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
            "0100000000000000000000000000000000000000000000000000000000000080",
            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        ];
        for h in table {
            let b: [u8; 32] = (0..32)
                .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
                .collect::<Vec<_>>()
                .try_into()
                .unwrap();
            let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
            assert!(k.is_weak(), "{h}");
        }
    }

    #[test]
    fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
        let cert: Certificate = serde_json::from_value(valid()).unwrap();
        let v = Verified {
            id: String::new(),
            expires_at: timestamp(&cert.expires_at).unwrap(),
            cert,
        };
        assert_eq!(v.threshold_for(Some("east")), 0.9);
        assert_eq!(
            v.threshold_for(Some("z\u{fc}rich \u{2603}")),
            v.cert.abstain_below
        );
        assert_eq!(v.threshold_for(None), v.cert.abstain_below);
        assert!(
            v.is_expired(v.expires_at)
                && !v.is_expired(v.expires_at - chrono::Duration::seconds(1))
        );
    }
}