decision-cert 0.10.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
//! `decision-certificate.v1.6` (spec/decision-certificate.v1.6.md): the `sequential` block, the
//! anytime-valid crossing of each class (§1.3), the exploration draw (§1.7) and the checks beyond
//! the schema (§2.7).
//!
//! [`crossed`] is the spec's normative recipe: IEEE-754 binary64 `+ - * /` only, in a fixed order,
//! with exact power-of-two renormalisation, so it gives the same bits in this crate, its WebAssembly
//! build and the Python package. No logarithm or exponential is used: their rounding differs between
//! maths libraries.

use serde::Deserialize;
use sha2::{Digest, Sha256};
use time::Duration;

use crate::{nullable, tenant_ok, timestamp, CertError, Certificate};

/// The grid of §1.3: qⱼ = alpha · j / GRID for j = 1 .. GRID − 1.
pub const GRID: u32 = 20;
/// The largest `n` of one class (spec v1.6 §2.2).
pub const MAX_TESTED: u64 = 1_000_000_000;
/// The largest integer a count may be (2^53 − 1).
const MAX_COUNT: u64 = 9_007_199_254_740_991;
const UP: f64 = 18_446_744_073_709_551_616.0; // 2^64
const DOWN: f64 = 1.0 / 18_446_744_073_709_551_616.0; // 2^-64, exact

/// A record's sealed status (spec v1.6 §1.1), in the order of a status count (§2.2).
pub const STATUSES: [&str; 7] = [
    "answered",
    "score_unavailable",
    "explore_skipped",
    "cap_exhausted",
    "gate_unavailable",
    "explore_refused",
    "explore_prepared",
];

/// The `sequential` block of a v1.6 certificate (spec v1.6 §2.2).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Sequential {
    pub flow: String,
    pub env: String,
    pub attempt: String,
    pub preregistration: Preregistration,
    pub record_range: RecordRange,
    pub labels: Labels,
    pub reconciliation: Reconciliation,
    pub results: Vec<ClassResult>,
}

/// The citation of the sealed pre-registration (spec v1.6 §2.3).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Preregistration {
    pub digest: String,
    pub config_digest: String,
    pub sealed_at: String,
    pub classes: Classes,
    pub basis: String,
    pub exploration_rate: f64,
    #[serde(deserialize_with = "nullable")]
    pub exploration: Option<Exploration>,
    #[serde(deserialize_with = "nullable")]
    pub resolution_window_hours: Option<u32>,
    pub model_verification: String,
    pub eligibility: Vec<String>,
    pub limits: Limits,
    pub fidelity_sample: u64,
    pub interim_rule: String,
    pub label_horizon_days: u32,
    pub adjudication_days: u32,
    #[serde(deserialize_with = "nullable")]
    pub no_news_rule: Option<NoNewsRule>,
    pub min_weekly_cycles: u32,
    pub max_window_days: u32,
    pub pause_budget: Pauses,
    pub tail_level: f64,
    pub ttl_days: u32,
    pub stopping_rule: String,
}

/// The exploration draw (spec v1.6 §1.7): its experiment, bucket version, unit, the salt's
/// commitment sealed before the window and the salt revealed after it.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Exploration {
    pub experiment_id: String,
    pub bucket_version: String,
    pub unit: String,
    pub unit_source: String,
    #[serde(deserialize_with = "nullable")]
    pub unit_key_id: Option<String>,
    pub salt_commitment: String,
    #[serde(deserialize_with = "nullable")]
    pub salt: Option<String>,
}

/// The pre-registered limits an attempt is refused above (spec v1.6 §2.3).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    pub unclassifiable: u64,
    pub lost_draws: u64,
    pub duplicates: u64,
    pub pre_known: u64,
    pub erased: u64,
}

/// A number of pauses and their total seconds (spec v1.6 §2.3 `pause_budget`, §2.6 `pauses`).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Pauses {
    pub count: u64,
    pub seconds: u64,
}

/// How records are put in classes (spec v1.6 §1.5): `none`, `option` or `segment`.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Classes {
    pub by: String,
    #[serde(deserialize_with = "nullable")]
    pub field: Option<String>,
    pub values: Vec<String>,
}

/// The label a record with no outcome by its horizon takes (spec v1.6 §2.3).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NoNewsRule {
    pub label: String,
    pub observable_options: Vec<String>,
}

/// The records the certificate was computed over (spec v1.6 §2.4).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct RecordRange {
    pub cutoff: String,
    pub revision_from: u64,
    pub revision_to: u64,
    pub first: String,
    pub last: String,
    pub decided: u64,
    pub tested: u64,
    #[serde(deserialize_with = "nullable")]
    pub outcome_source: Option<OutcomeSource>,
}

/// Where the outcomes were read (spec v1.6 §2.4): a table and its snapshot.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct OutcomeSource {
    pub table: String,
    pub snapshot_id: String,
}

/// Label counts over the tested units (spec v1.6 §2.5).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Labels {
    pub basis: LabelBasis,
    pub resolution: LabelResolution,
    pub contested: u64,
    pub adjudicated: u64,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct LabelBasis {
    pub ground_truth: u64,
    pub action_conditional: u64,
    pub decider_choice: u64,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct LabelResolution {
    pub observed: u64,
    pub no_news: u64,
    pub missing_as_error: u64,
    pub not_executed: u64,
}

/// The attempt's reconciliation (spec v1.6 §2.6): its health artifact, the draws, the
/// unclassifiable units and the tail after the stop.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Reconciliation {
    pub health_digest: String,
    pub draws: Draws,
    pub unclassifiable: u64,
    pub duplicates: u64,
    pub pre_known: u64,
    pub erased: u64,
    pub rescored_untested: u64,
    pub fidelity_checked: u64,
    pub pauses: Pauses,
    pub tail: Tail,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Draws {
    pub answered: u64,
    pub sealed: u64,
    pub unsealed: u64,
    pub lost: u64,
}

#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Tail {
    pub decided: u64,
    pub selected: u64,
    pub status: StatusCount,
    pub resolved: u64,
    pub errors: u64,
}

/// Units by their first record's sealed status (spec v1.6 §2.2), fields in [`STATUSES`] order.
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct StatusCount {
    pub answered: u64,
    pub score_unavailable: u64,
    pub explore_skipped: u64,
    pub cap_exhausted: u64,
    pub gate_unavailable: u64,
    pub explore_refused: u64,
    pub explore_prepared: u64,
}

impl StatusCount {
    /// The counts in [`STATUSES`] order.
    pub fn counts(&self) -> [u64; 7] {
        [
            self.answered,
            self.score_unavailable,
            self.explore_skipped,
            self.cap_exhausted,
            self.gate_unavailable,
            self.explore_refused,
            self.explore_prepared,
        ]
    }

    fn total(&self) -> u128 {
        self.counts().iter().map(|&x| u128::from(x)).sum()
    }
}

/// One pre-registered class's tested units, errors, level `δ_c`, status count and re-scored units
/// (spec v1.6 §2.2).
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ClassResult {
    #[serde(deserialize_with = "nullable")]
    pub value: Option<String>,
    pub n: u64,
    pub errors: u64,
    pub delta: f64,
    pub status: StatusCount,
    pub unsealed: u64,
    pub rescored: u64,
}

/// A scaled value `m · 2^k`, `1 <= m < 2^64`, `k` a multiple of 64 (spec v1.6 §1.3).
#[derive(Clone, Copy, Debug, PartialEq)]
struct Scaled {
    m: f64,
    k: i64,
}

fn norm(mut m: f64, mut k: i64) -> Scaled {
    while m >= UP {
        m *= DOWN;
        k += 64;
    }
    while m < 1.0 {
        m *= UP;
        k -= 64;
    }
    Scaled { m, k }
}

fn mul(a: Scaled, b: Scaled) -> Scaled {
    norm(a.m * b.m, a.k + b.k)
}

/// `base^exp`, `base > 0`, by squaring from the lowest bit (recipe step 1).
fn pow(base: f64, mut exp: u64) -> Scaled {
    let mut r = Scaled { m: 1.0, k: 0 };
    let mut s = norm(base, 0);
    while exp > 0 {
        if exp & 1 == 1 {
            r = mul(r, s);
        }
        exp >>= 1;
        if exp > 0 {
            s = mul(s, s);
        }
    }
    r
}

/// Recipe step 3: the terms aligned to the largest exponent and added in order.
fn sum(terms: &[Scaled]) -> Scaled {
    let top = terms.iter().map(|t| t.k).max().unwrap_or(0);
    let mut total = 0.0;
    for t in terms {
        let (mut m, mut k) = (t.m, t.k);
        // m is 0 after at most 18 steps and stays 0: stopping there gives the same bits (spec §1.3, step 3)
        while k < top && m != 0.0 {
            m *= DOWN;
            k += 64;
        }
        total += m;
    }
    norm(total, top)
}

/// 19 · E_n, scaled (recipe steps 2 and 3).
fn mixture(n: u64, errors: u64, alpha: f64) -> Scaled {
    let den = 1.0 - alpha;
    let terms: Vec<Scaled> = (1..GRID)
        .map(|j| {
            let j = f64::from(j);
            let r = j / f64::from(GRID);
            let a = (alpha * j) / f64::from(GRID);
            let b = (1.0 - a) / den;
            mul(pow(r, errors), pow(b, n - errors))
        })
        .collect();
    sum(&terms)
}

/// 19 · M, the tail monitor's mixture, scaled: `q'_j = alpha + (1 - alpha) j / 20` (spec v1.6 §1.3).
fn tail_mixture(n: u64, errors: u64, alpha: f64) -> Scaled {
    let terms: Vec<Scaled> = (1..GRID)
        .map(|j| {
            let r = (alpha + ((1.0 - alpha) * f64::from(j)) / f64::from(GRID)) / alpha;
            let b = f64::from(GRID - j) / f64::from(GRID);
            mul(pow(r, errors), pow(b, n - errors))
        })
        .collect();
    sum(&terms)
}

fn at_least(s: Scaled, level: f64) -> bool {
    let t = norm(f64::from(GRID - 1) / level, 0);
    s.k > t.k || (s.k == t.k && s.m >= t.m)
}

/// The least `alpha`, per-class level `delta_c` and `tail_level` a v1.6 certificate may carry (spec v1.6
/// §2.7): below it, `19 / level` or the tail's ratio can leave binary64's range and the recipe is undefined.
pub const MIN_LEVEL: f64 = 1e-12;

fn level_ok(x: f64) -> bool {
    (MIN_LEVEL..1.0).contains(&x)
}

/// Whether a class with `n` tested records and `errors` errors crossed at level `delta_c`: its
/// grid-mixture test supermartingale is at least `1 / delta_c` (spec v1.6 §1.3), by the spec's
/// recipe. None when the inputs are out of range (`errors <= n <= 10^9`, `alpha` and `delta_c` in
/// [`MIN_LEVEL`], 1)).
pub fn crossed(n: u64, errors: u64, alpha: f64, delta_c: f64) -> Option<bool> {
    if errors > n || n > MAX_TESTED || !level_ok(alpha) || !level_ok(delta_c) {
        return None;
    }
    Some(at_least(mixture(n, errors, alpha), delta_c))
}

/// Whether the tail monitor trips on `n` resolved tail units with `errors` errors at `level`: its
/// mirrored grid mixture is at least `1 / level` (spec v1.6 §1.3). None when the inputs are out of
/// range (`errors <= n <= 2^53 - 1`, `alpha` and `level` in [`MIN_LEVEL`], 1)).
pub fn tail_trips(n: u64, errors: u64, alpha: f64, level: f64) -> Option<bool> {
    if errors > n || n > MAX_COUNT || !level_ok(alpha) || !level_ok(level) {
        return None;
    }
    Some(at_least(tail_mixture(n, errors, alpha), level))
}

/// The salt commitment's domain-separation prefix (spec v1.6 §1.7).
pub const EXPLORE_COMMIT_PREFIX: &[u8] = b"seam.gate.explore.v1\n";
/// The draw's message prefix (`bucket_version` bp2, spec v1.6 §1.7).
pub const BUCKET_MSG_PREFIX: &[u8] = b"bp2\n";
/// The number of buckets: a rate is a whole number of basis points.
pub const BUCKETS: u64 = 10_000;

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

fn salt_bytes(salt: &str) -> Option<[u8; 32]> {
    if !hex64(salt) {
        return None;
    }
    let nib = |c: u8| {
        if c.is_ascii_digit() {
            c - b'0'
        } else {
            c - b'a' + 10
        }
    };
    let b = salt.as_bytes();
    let mut out = [0u8; 32];
    for (i, o) in out.iter_mut().enumerate() {
        *o = (nib(b[2 * i]) << 4) | nib(b[2 * i + 1]);
    }
    Some(out)
}

/// `sha256:` + hex SHA-256(`"seam.gate.explore.v1" 0x0A` ‖ the 32 salt bytes): the commitment
/// sealed before the window (spec v1.6 §1.7). None unless `salt` is 64 lowercase hex.
pub fn salt_commitment(salt: &str) -> Option<String> {
    let key = salt_bytes(salt)?;
    let mut h = Sha256::new();
    h.update(EXPLORE_COMMIT_PREFIX);
    h.update(key);
    Some(format!("sha256:{}", crate::hex(&h.finalize())))
}

/// HMAC-SHA-256 (RFC 2104) with a 32-byte key.
fn hmac_sha256(key: &[u8; 32], msg: &[&[u8]]) -> [u8; 32] {
    let mut ipad = [0x36u8; 64];
    let mut opad = [0x5cu8; 64];
    for (i, k) in key.iter().enumerate() {
        ipad[i] ^= k;
        opad[i] ^= k;
    }
    let mut inner = Sha256::new();
    inner.update(ipad);
    for m in msg {
        inner.update(m);
    }
    let mut outer = Sha256::new();
    outer.update(opad);
    outer.update(inner.finalize());
    outer.finalize().into()
}

/// A unit's bp2 bucket (spec v1.6 §1.7): the first eight bytes of HMAC-SHA-256(salt,
/// `"bp2" 0x0A` ‖ experiment_id ‖ `0x0A` ‖ unit), big-endian, modulo 10000. The unit is selected
/// when the bucket is below the rate in basis points. None unless `salt` is 64 lowercase hex.
pub fn explore_bucket(salt: &str, experiment_id: &str, unit: &str) -> Option<u64> {
    let key = salt_bytes(salt)?;
    let d = hmac_sha256(
        &key,
        &[
            BUCKET_MSG_PREFIX,
            experiment_id.as_bytes(),
            b"\n",
            unit.as_bytes(),
        ],
    );
    let mut first = [0u8; 8];
    first.copy_from_slice(&d[..8]);
    Some(u64::from_be_bytes(first) % BUCKETS)
}

/// The whole number of basis points `r` with `rate = r / 10000` (one IEEE division),
/// `1 <= r <= 9999`, or None.
pub fn rate_bp(rate: f64) -> Option<u32> {
    let r = (rate * 10000.0 + 0.5).floor();
    ((1.0..=9999.0).contains(&r) && r / 10000.0 == rate).then_some(r as u32)
}

/// `<source>:sha256:<64 lowercase hex>`, `<source>` 1 to 32 of `a-z 0-9 -` starting with a letter.
fn record_ref_ok(s: &str) -> bool {
    let Some((source, hex)) = s.split_once(":sha256:") else {
        return false;
    };
    let b = source.as_bytes();
    (1..=32).contains(&b.len())
        && b[0].is_ascii_lowercase()
        && b.iter()
            .all(|&c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
        && hex64(hex)
}

/// A table of 1 to 256 of `A-Z a-z 0-9 . _ : / -` and a decimal snapshot id (an optional `-`, 1 to
/// 19 digits).
fn outcome_source_ok(o: Option<&OutcomeSource>) -> bool {
    let Some(o) = o else {
        return true;
    };
    let t = o.table.as_bytes();
    let digits = o.snapshot_id.strip_prefix('-').unwrap_or(&o.snapshot_id);
    (1..=256).contains(&t.len())
        && t.iter()
            .all(|&c| c.is_ascii_alphanumeric() || b"._:/-".contains(&c))
        && (1..=19).contains(&digits.len())
        && digits.bytes().all(|c| c.is_ascii_digit())
}

/// The checks of spec v1.6 §2.7 beyond the schema and beyond v1.5's (which [`crate::check`] runs).
pub(crate) fn check(c: &Certificate) -> Result<(), CertError> {
    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
    let Some(s) = &c.sequential else {
        return bad("a v1.6 certificate needs sequential");
    };
    // §2.1's fixed values
    let automated_ok = c.automated.as_ref().is_some_and(|a| {
        a.ucb.is_none()
            && a.realized_band.as_ref() == Some(&c.realized_band)
            && a.loss_sum == Some(None)
            && a.realized_cost == Some(None)
    });
    if c.n_cal != c.n
        || c.n_temperature != 0
        || c.split.method != "time"
        || c.split.seed.is_some()
        || c.ucb.is_some()
        || !c.segments.is_empty()
        || c.cost != Some(None)
        || c.pvalue != Some(None)
        || c.loss_sum != Some(None)
        || c.realized_cost != Some(None)
        || c.abstain_below > 1.0
        || !automated_ok
    {
        return bad("a v1.6 certificate has n_cal = n, n_temperature 0, split time with no seed, ucb null, no segments, null cost fields, abstain_below at most 1, and automated with ucb null and the top-level realized_band");
    }
    let Some(window) = &c.window else {
        return bad("a v1.6 certificate has a window");
    };
    if ![&s.flow, &s.env, &s.attempt].iter().all(|x| tenant_ok(x)) {
        return bad("flow, env and attempt must be 1 to 128 characters of A-Z a-z 0-9 . _ : -");
    }
    let p = &s.preregistration;
    let rec = &s.reconciliation;
    if ![&p.digest, &p.config_digest, &rec.health_digest]
        .iter()
        .all(|x| crate::sha256_ok(x))
    {
        return bad("preregistration digest and config_digest, and reconciliation health_digest, must be sha256:<64 hex>");
    }
    // classes (§1.5)
    let auto = c.automate_options.as_deref().unwrap_or_default();
    let cl = &p.classes;
    let values: Vec<Option<&str>> = match (cl.by.as_str(), cl.field.as_deref()) {
        ("none", None) if cl.values.is_empty() => vec![None],
        ("option", None) if cl.values.as_slice() == auto => {
            cl.values.iter().map(|v| Some(v.as_str())).collect()
        }
        ("segment", Some(f))
            if !f.is_empty()
                && !cl.values.is_empty()
                && cl.values.iter().all(|v| !v.is_empty())
                && cl.values.windows(2).all(|w| w[0].as_bytes() < w[1].as_bytes()) =>
        {
            cl.values.iter().map(|v| Some(v.as_str())).collect()
        }
        _ => return bad("classes must be none (no field, no values), option (no field, values equal to automate_options) or segment (a field and distinct non-empty values, sorted bytewise)"),
    };
    let rate = p.exploration_rate;
    let exploring = p.basis == "exploration";
    let basis_ok = (exploring && rate > 0.0 && rate < 1.0)
        || (p.basis == "ground_truth" && (0.0..1.0).contains(&rate));
    let lim = &p.limits;
    if !basis_ok
        || !matches!(
            p.interim_rule.as_str(),
            "own_rule" | "follow_model" | "escalate" | "refuse"
        )
        || p.stopping_rule != "every_class_crosses"
        || !matches!(p.model_verification.as_str(), "recompute" | "receipt")
        || !(1..=3650).contains(&p.label_horizon_days)
        || !(1..=3650).contains(&p.ttl_days)
        || !(1..=520).contains(&p.min_weekly_cycles)
        || p.no_news_rule
            .as_ref()
            .is_some_and(|r| !c.options.contains(&r.label))
        || !p.eligibility.iter().all(|x| tenant_ok(x))
        || !p
            .eligibility
            .windows(2)
            .all(|w| w[0].as_bytes() < w[1].as_bytes())
        || lim.unclassifiable > MAX_COUNT
        || lim.lost_draws > MAX_COUNT
    {
        return bad("preregistration out of range: basis and exploration_rate, interim_rule, stopping_rule, model_verification, label_horizon_days, ttl_days, min_weekly_cycles, a no_news_rule label that is not an option, eligibility not distinct reference strings sorted bytewise, or limits above 2^53 - 1");
    }
    let obs: &[String] = p
        .no_news_rule
        .as_ref()
        .map_or(&[], |r| r.observable_options.as_slice());
    let budget = &p.pause_budget;
    let recompute = p.model_verification == "recompute";
    if (p.no_news_rule.is_some() && (obs.is_empty() || !obs.iter().all(|o| c.options.contains(o))))
        || !obs.windows(2).all(|w| w[0].as_bytes() < w[1].as_bytes())
        || p.adjudication_days > 365
        || !(7..=3650).contains(&p.max_window_days)
        || u64::from(p.max_window_days) < 7 * u64::from(p.min_weekly_cycles)
        || [lim.duplicates, lim.pre_known, lim.erased]
            .iter()
            .any(|&x| x > MAX_COUNT)
        || budget.count > MAX_COUNT
        || budget.seconds > MAX_COUNT
        || p.fidelity_sample > MAX_COUNT
        || (recompute && p.fidelity_sample < 1)
        || (!recompute && p.fidelity_sample != 0)
        || !level_ok(p.tail_level)
    {
        return bad("preregistration out of range: no_news_rule observable_options not distinct options sorted bytewise, adjudication_days, max_window_days (7 to 3650 and at least 7 min_weekly_cycles), limits or pause_budget above 2^53 - 1, fidelity_sample (at least 1 under recompute, 0 under receipt) or tail_level");
    }
    // the exploration draw (§1.7)
    let w = p.resolution_window_hours;
    if exploring {
        let ex_ok = match (&p.exploration, w) {
            (Some(ex), Some(w)) => {
                (1..=87_600).contains(&w)
                    && u64::from(w) <= 24 * u64::from(p.label_horizon_days)
                    && rate_bp(rate).is_some()
                    && tenant_ok(&ex.experiment_id)
                    && ex.bucket_version == "bp2"
                    && ex.unit == "decision"
                    && matches!(ex.unit_source.as_str(), "decision_id" | "business_event_id")
                    && ex.unit_key_id.is_none() == (ex.unit_source == "decision_id")
                    && ex.unit_key_id.as_deref().is_none_or(tenant_ok)
                    && crate::sha256_ok(&ex.salt_commitment)
            }
            _ => false,
        };
        if !ex_ok {
            return bad("under exploration: exploration (experiment_id, bucket_version bp2, unit decision, unit_source decision_id with unit_key_id null or business_event_id with unit_key_id a reference, salt_commitment), resolution_window_hours from 1 to 24 times label_horizon_days, and exploration_rate a whole number of basis points");
        }
        let ex = p.exploration.as_ref().expect("checked above");
        let Some(salt) = ex.salt.as_deref().filter(|s| hex64(s)) else {
            return bad("an exploration certificate reveals its salt: 64 lowercase hex");
        };
        if salt_commitment(salt).as_deref() != Some(ex.salt_commitment.as_str()) {
            return bad("the revealed salt does not match salt_commitment (spec v1.6 §1.7)");
        }
    } else if p.exploration.is_some() || w.is_some() {
        return bad("under ground_truth, exploration and resolution_window_hours are null");
    }
    // results: one per class, in order, δ_c = delta / K, and every class crosses
    let delta = c.delta.unwrap_or(0.0);
    let delta_c = delta / values.len() as f64;
    if !level_ok(c.alpha) || !level_ok(delta_c) {
        return bad("alpha and delta / K must each be at least 10^-12 (spec v1.6 §2.7)");
    }
    if s.results.len() != values.len()
        || !s
            .results
            .iter()
            .zip(&values)
            .all(|(r, v)| r.value.as_deref() == *v)
    {
        return bad("results must have one entry per pre-registered class, in order");
    }
    let mut total: u128 = 0;
    for r in &s.results {
        if r.errors > r.n
            || r.n > MAX_TESTED
            || r.delta != delta_c
            || r.unsealed > r.n
            || r.status.total() != u128::from(r.n - r.unsealed.min(r.n))
            || r.rescored > r.n
            || (p.model_verification == "receipt" && r.rescored != 0)
        {
            return bad("each result has errors at most n, n at most 10^9, delta equal to delta / K, a status count summing to n - unsealed, and rescored at most n (0 under a receipt release)");
        }
        total += u128::from(r.n);
    }
    for r in &s.results {
        if crossed(r.n, r.errors, c.alpha, delta_c) != Some(true) {
            return Err(CertError::Invalid(format!(
                "class {} did not cross: its test supermartingale is below 1/delta_c (spec v1.6 §1.3)",
                r.value.as_deref().unwrap_or("(all)")
            )));
        }
    }
    // reconciliation (§2.6)
    let (unclass, draws, tail) = (rec.unclassifiable, &rec.draws, &rec.tail);
    let lost = draws.lost;
    if unclass > lim.unclassifiable
        || s.results
            .iter()
            .any(|r| u128::from(unclass) + u128::from(lost) > u128::from(r.errors))
        || s.results.iter().any(|r| r.unsealed < lost)
        || u128::from(draws.answered) != u128::from(draws.sealed) + u128::from(draws.unsealed)
        || draws.answered > MAX_COUNT
        || lost > lim.lost_draws
        || rec.duplicates > lim.duplicates
        || rec.pre_known > lim.pre_known
        || rec.erased > lim.erased
        || rec.rescored_untested > MAX_COUNT
        || rec.fidelity_checked != p.fidelity_sample
        || rec.fidelity_checked > c.n
        || (!recompute && (rec.rescored_untested != 0 || rec.fidelity_checked != 0))
        || rec.pauses.count > budget.count
        || rec.pauses.seconds > budget.seconds
        || tail.decided > MAX_COUNT
        || tail.selected > MAX_COUNT
        || tail.status.total() > u128::from(tail.selected)
        || tail.errors > tail.resolved
        || tail.resolved > MAX_COUNT
    {
        return bad("reconciliation: unclassifiable, duplicates, pre_known and erased at most their limits, unclassifiable plus lost draws at most every class's errors and lost draws at most every class's unsealed, draws answered = sealed + unsealed, lost draws at most their limit, rescored_untested and fidelity_checked 0 under receipt, fidelity_checked equal to fidelity_sample and at most n, pauses within pause_budget, the tail's status count at most its selected units and its errors at most its resolved units");
    }
    if tail_trips(tail.resolved, tail.errors, c.alpha, p.tail_level) != Some(false) {
        return bad("the tail monitor tripped on the tail's resolved units: issuance is refused (spec v1.6 §1.3, §1.6)");
    }
    // record range, labels, audit
    let rr = &s.record_range;
    if !record_ref_ok(&rr.first) || !record_ref_ok(&rr.last) {
        return bad("record_range first and last must be <source>:sha256:<64 hex>");
    }
    if !outcome_source_ok(rr.outcome_source.as_ref()) {
        return bad("record_range outcome_source must be a table of 1 to 256 of A-Z a-z 0-9 . _ : / - and a decimal snapshot_id");
    }
    let tested = rr.tested;
    let k = values.len() as u128;
    if rr.decided != c.n
        || c.audit.n != tested
        || tested > MAX_COUNT
        || rec.pre_known > tested
        || rec.erased > tested
        || total != u128::from(tested) + (k - 1) * (u128::from(unclass) + u128::from(lost))
        || rr.revision_from > rr.revision_to
        || rr.revision_to > MAX_COUNT
    {
        return bad("record_range: decided equals n, tested equals audit.n and is at least pre_known and erased, the results' n sum to tested plus (K - 1) (unclassifiable + lost draws), and revision_from at most revision_to");
    }
    let lb = &s.labels.basis;
    let lr = &s.labels.resolution;
    let sum = |xs: &[u64]| xs.iter().map(|&x| u128::from(x)).sum::<u128>();
    let t = u128::from(tested);
    if sum(&[lb.ground_truth, lb.action_conditional, lb.decider_choice]) != t
        || sum(&[
            lr.observed,
            lr.no_news,
            lr.missing_as_error,
            lr.not_executed,
        ]) != t
        || lb.decider_choice != 0
        || (!exploring && lb.action_conditional != 0)
        || (p.no_news_rule.is_none() && lr.no_news != 0)
        || s.labels.adjudicated > s.labels.contested
        || s.labels.contested > tested
        || s.labels.contested - s.labels.adjudicated.min(s.labels.contested) > lr.missing_as_error
    {
        return bad("labels: each group sums to tested, decider_choice is 0, no action_conditional under ground_truth, no no_news without a no-news rule, and adjudicated <= contested <= tested with the unadjudicated ones at most missing_as_error");
    }
    if !exploring
        && (lr.not_executed != 0
            || s.results
                .iter()
                .any(|r| r.status.explore_refused != 0 || r.status.explore_prepared != 0)
            || tail.status.explore_refused != 0
            || tail.status.explore_prepared != 0
            || [draws.answered, draws.sealed, draws.unsealed, draws.lost]
                .iter()
                .any(|&x| x != 0)
            || s.results.iter().any(|r| r.unsealed != 0)
            || tail.selected != 0)
    {
        return bad("under ground_truth: no not_executed, no explore_refused or explore_prepared units, no draws, no unsealed units and no selected tail units");
    }
    let audit_ok = if exploring {
        c.audit.mode == "sample" && c.audit.rate == rate && c.audit.propensity_logged
    } else {
        c.audit.mode == "full-label" && c.audit.rate == 1.0 && !c.audit.propensity_logged
    };
    if !audit_ok {
        return bad("audit must be sample at the exploration rate with propensity logged under exploration, full-label at rate 1 without under ground_truth");
    }
    // dates
    let start = v16_timestamp(&window.start)?;
    let end = v16_timestamp(&window.end)?;
    let cutoff = v16_timestamp(&rr.cutoff)?;
    let sealed = v16_timestamp(&p.sealed_at)?;
    let fitted = v16_timestamp(&c.fitted_at)?;
    let expires = v16_timestamp(&c.expires_at)?;
    let wait = Duration::hours(i64::from(w.unwrap_or(0)))
        + Duration::days(i64::from(p.label_horizon_days) + i64::from(p.adjudication_days));
    let span = end - start;
    if sealed > start
        || start > end
        || end.checked_add(wait).is_none_or(|t| t > cutoff)
        || cutoff > fitted
        || span < Duration::days(7 * i64::from(p.min_weekly_cycles))
        || span > Duration::days(i64::from(p.max_window_days))
        || i128::from(rec.pauses.seconds) > i128::from(span.whole_seconds())
    {
        return bad("dates: sealed_at <= window.start <= window.end, window.end + resolution window + label_horizon_days + adjudication_days <= cutoff <= fitted_at, the window spans min_weekly_cycles weeks and at most max_window_days, and the paused seconds fit in it");
    }
    if cutoff.checked_add(Duration::days(i64::from(p.ttl_days))) != Some(expires) {
        return bad("expires_at must be record_range.cutoff + ttl_days days");
    }
    Ok(())
}

/// A v1.6 date (spec v1.6 §2.7): the spec's timestamp form, without a leap second, whose arithmetic
/// the spec leaves to no convention.
fn v16_timestamp(s: &str) -> Result<time::UtcDateTime, CertError> {
    if s.len() == 20 && s.as_bytes()[17..19] == *b"60" {
        return Err(CertError::Invalid(
            "a v1.6 date has no leap second (seconds 60) (spec v1.6 §2.7)".to_string(),
        ));
    }
    timestamp(s)
}

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

    #[test]
    fn zero_errors_cross_where_the_review_simulated() {
        // 90 records at delta 0.05 and 124 at 0.0125, alpha 0.05 (DECISIONS.md V16-3)
        assert_eq!(crossed(89, 0, 0.05, 0.05), Some(false));
        assert_eq!(crossed(90, 0, 0.05, 0.05), Some(true));
        assert_eq!(crossed(123, 0, 0.05, 0.0125), Some(false));
        assert_eq!(crossed(124, 0, 0.05, 0.0125), Some(true));
    }

    #[test]
    fn crossing_is_monotone_in_errors_and_never_at_zero_records() {
        assert_eq!(crossed(0, 0, 0.05, 0.5), Some(false));
        assert_eq!(crossed(276, 5, 0.05, 0.05), Some(true));
        assert_eq!(crossed(275, 5, 0.05, 0.05), Some(false));
        assert_eq!(crossed(276, 6, 0.05, 0.05), Some(false));
        // a rate at alpha never crosses, however many records
        assert_eq!(
            crossed(MAX_TESTED, MAX_TESTED / 20, 0.05, 0.05),
            Some(false)
        );
        assert_eq!(crossed(MAX_TESTED, MAX_TESTED / 25, 0.05, 0.05), Some(true));
    }

    #[test]
    fn the_tail_monitor_trips_where_exact_arithmetic_does() {
        // the least error count that trips at alpha 0.05, level 0.01, from exact rational arithmetic
        for (n, e) in [(20, 6), (50, 10), (120, 17), (500, 47)] {
            assert_eq!(tail_trips(n, e, 0.05, 0.01), Some(true), "{n} {e}");
            assert_eq!(tail_trips(n, e - 1, 0.05, 0.01), Some(false), "{n} {e}");
        }
        // no resolved units never trips; an error rate below alpha never trips
        assert_eq!(tail_trips(0, 0, 0.05, 0.01), Some(false));
        assert_eq!(tail_trips(1_000_000, 40_000, 0.05, 0.01), Some(false));
        assert_eq!(tail_trips(5, 6, 0.05, 0.01), None);
        assert_eq!(tail_trips(5, 0, 0.05, 1.0), None);
    }

    #[test]
    fn out_of_range_inputs_have_no_verdict() {
        assert_eq!(crossed(5, 6, 0.05, 0.05), None);
        assert_eq!(crossed(MAX_TESTED + 1, 0, 0.05, 0.05), None);
        assert_eq!(crossed(5, 0, 0.0, 0.05), None);
        assert_eq!(crossed(5, 0, 0.05, 1.0), None);
    }
}