Skip to main content

decision_cert/
sequential.rs

1//! `decision-certificate.v1.6` (spec/decision-certificate.v1.6.md): the `sequential` block, the
2//! anytime-valid crossing of each class (§1.3), the exploration draw (§1.7) and the checks beyond
3//! the schema (§2.7).
4//!
5//! [`crossed`] is the spec's normative recipe: IEEE-754 binary64 `+ - * /` only, in a fixed order,
6//! with exact power-of-two renormalisation, so it gives the same bits in this crate, its WebAssembly
7//! build and the Python package. No logarithm or exponential is used: their rounding differs between
8//! maths libraries.
9
10use serde::Deserialize;
11use sha2::{Digest, Sha256};
12use time::Duration;
13
14use crate::{nullable, tenant_ok, timestamp, CertError, Certificate};
15
16/// The grid of §1.3: qⱼ = alpha · j / GRID for j = 1 .. GRID − 1.
17pub const GRID: u32 = 20;
18/// The largest `n` of one class (spec v1.6 §2.2).
19pub const MAX_TESTED: u64 = 1_000_000_000;
20/// The largest integer a count may be (2^53 − 1).
21const MAX_COUNT: u64 = 9_007_199_254_740_991;
22const UP: f64 = 18_446_744_073_709_551_616.0; // 2^64
23const DOWN: f64 = 1.0 / 18_446_744_073_709_551_616.0; // 2^-64, exact
24
25/// A record's sealed status (spec v1.6 §1.1), in the order of a status count (§2.2).
26pub const STATUSES: [&str; 7] = [
27    "answered",
28    "score_unavailable",
29    "explore_skipped",
30    "cap_exhausted",
31    "gate_unavailable",
32    "explore_refused",
33    "explore_prepared",
34];
35
36/// The `sequential` block of a v1.6 certificate (spec v1.6 §2.2).
37#[derive(Deserialize, Clone, Debug, PartialEq)]
38#[serde(deny_unknown_fields)]
39pub struct Sequential {
40    pub flow: String,
41    pub env: String,
42    pub attempt: String,
43    pub preregistration: Preregistration,
44    pub record_range: RecordRange,
45    pub labels: Labels,
46    pub reconciliation: Reconciliation,
47    pub results: Vec<ClassResult>,
48}
49
50/// The citation of the sealed pre-registration (spec v1.6 §2.3).
51#[derive(Deserialize, Clone, Debug, PartialEq)]
52#[serde(deny_unknown_fields)]
53pub struct Preregistration {
54    pub digest: String,
55    pub config_digest: String,
56    pub sealed_at: String,
57    pub classes: Classes,
58    pub basis: String,
59    pub exploration_rate: f64,
60    #[serde(deserialize_with = "nullable")]
61    pub exploration: Option<Exploration>,
62    #[serde(deserialize_with = "nullable")]
63    pub resolution_window_hours: Option<u32>,
64    pub model_verification: String,
65    pub eligibility: Vec<String>,
66    pub limits: Limits,
67    pub fidelity_sample: u64,
68    pub interim_rule: String,
69    pub label_horizon_days: u32,
70    pub adjudication_days: u32,
71    #[serde(deserialize_with = "nullable")]
72    pub no_news_rule: Option<NoNewsRule>,
73    pub min_weekly_cycles: u32,
74    pub max_window_days: u32,
75    pub pause_budget: Pauses,
76    pub tail_level: f64,
77    pub ttl_days: u32,
78    pub stopping_rule: String,
79}
80
81/// The exploration draw (spec v1.6 §1.7): its experiment, bucket version, unit, the salt's
82/// commitment sealed before the window and the salt revealed after it.
83#[derive(Deserialize, Clone, Debug, PartialEq)]
84#[serde(deny_unknown_fields)]
85pub struct Exploration {
86    pub experiment_id: String,
87    pub bucket_version: String,
88    pub unit: String,
89    pub unit_source: String,
90    #[serde(deserialize_with = "nullable")]
91    pub unit_key_id: Option<String>,
92    pub salt_commitment: String,
93    #[serde(deserialize_with = "nullable")]
94    pub salt: Option<String>,
95}
96
97/// The pre-registered limits an attempt is refused above (spec v1.6 §2.3).
98#[derive(Deserialize, Clone, Debug, PartialEq)]
99#[serde(deny_unknown_fields)]
100pub struct Limits {
101    pub unclassifiable: u64,
102    pub lost_draws: u64,
103    pub duplicates: u64,
104    pub pre_known: u64,
105    pub erased: u64,
106}
107
108/// A number of pauses and their total seconds (spec v1.6 §2.3 `pause_budget`, §2.6 `pauses`).
109#[derive(Deserialize, Clone, Debug, PartialEq)]
110#[serde(deny_unknown_fields)]
111pub struct Pauses {
112    pub count: u64,
113    pub seconds: u64,
114}
115
116/// How records are put in classes (spec v1.6 §1.5): `none`, `option` or `segment`.
117#[derive(Deserialize, Clone, Debug, PartialEq)]
118#[serde(deny_unknown_fields)]
119pub struct Classes {
120    pub by: String,
121    #[serde(deserialize_with = "nullable")]
122    pub field: Option<String>,
123    pub values: Vec<String>,
124}
125
126/// The label a record with no outcome by its horizon takes (spec v1.6 §2.3).
127#[derive(Deserialize, Clone, Debug, PartialEq)]
128#[serde(deny_unknown_fields)]
129pub struct NoNewsRule {
130    pub label: String,
131    pub observable_options: Vec<String>,
132}
133
134/// The records the certificate was computed over (spec v1.6 §2.4).
135#[derive(Deserialize, Clone, Debug, PartialEq)]
136#[serde(deny_unknown_fields)]
137pub struct RecordRange {
138    pub cutoff: String,
139    pub revision_from: u64,
140    pub revision_to: u64,
141    pub first: String,
142    pub last: String,
143    pub decided: u64,
144    pub tested: u64,
145    #[serde(deserialize_with = "nullable")]
146    pub outcome_source: Option<OutcomeSource>,
147}
148
149/// Where the outcomes were read (spec v1.6 §2.4): a table and its snapshot.
150#[derive(Deserialize, Clone, Debug, PartialEq)]
151#[serde(deny_unknown_fields)]
152pub struct OutcomeSource {
153    pub table: String,
154    pub snapshot_id: String,
155}
156
157/// Label counts over the tested units (spec v1.6 §2.5).
158#[derive(Deserialize, Clone, Debug, PartialEq)]
159#[serde(deny_unknown_fields)]
160pub struct Labels {
161    pub basis: LabelBasis,
162    pub resolution: LabelResolution,
163    pub contested: u64,
164    pub adjudicated: u64,
165}
166
167#[derive(Deserialize, Clone, Debug, PartialEq)]
168#[serde(deny_unknown_fields)]
169pub struct LabelBasis {
170    pub ground_truth: u64,
171    pub action_conditional: u64,
172    pub decider_choice: u64,
173}
174
175#[derive(Deserialize, Clone, Debug, PartialEq)]
176#[serde(deny_unknown_fields)]
177pub struct LabelResolution {
178    pub observed: u64,
179    pub no_news: u64,
180    pub missing_as_error: u64,
181    pub not_executed: u64,
182}
183
184/// The attempt's reconciliation (spec v1.6 §2.6): its health artifact, the draws, the
185/// unclassifiable units and the tail after the stop.
186#[derive(Deserialize, Clone, Debug, PartialEq)]
187#[serde(deny_unknown_fields)]
188pub struct Reconciliation {
189    pub health_digest: String,
190    pub draws: Draws,
191    pub unclassifiable: u64,
192    pub duplicates: u64,
193    pub pre_known: u64,
194    pub erased: u64,
195    pub rescored_untested: u64,
196    pub fidelity_checked: u64,
197    pub pauses: Pauses,
198    pub tail: Tail,
199}
200
201#[derive(Deserialize, Clone, Debug, PartialEq)]
202#[serde(deny_unknown_fields)]
203pub struct Draws {
204    pub answered: u64,
205    pub sealed: u64,
206    pub unsealed: u64,
207    pub lost: u64,
208}
209
210#[derive(Deserialize, Clone, Debug, PartialEq)]
211#[serde(deny_unknown_fields)]
212pub struct Tail {
213    pub decided: u64,
214    pub selected: u64,
215    pub status: StatusCount,
216    pub resolved: u64,
217    pub errors: u64,
218}
219
220/// Units by their first record's sealed status (spec v1.6 §2.2), fields in [`STATUSES`] order.
221#[derive(Deserialize, Clone, Debug, PartialEq)]
222#[serde(deny_unknown_fields)]
223pub struct StatusCount {
224    pub answered: u64,
225    pub score_unavailable: u64,
226    pub explore_skipped: u64,
227    pub cap_exhausted: u64,
228    pub gate_unavailable: u64,
229    pub explore_refused: u64,
230    pub explore_prepared: u64,
231}
232
233impl StatusCount {
234    /// The counts in [`STATUSES`] order.
235    pub fn counts(&self) -> [u64; 7] {
236        [
237            self.answered,
238            self.score_unavailable,
239            self.explore_skipped,
240            self.cap_exhausted,
241            self.gate_unavailable,
242            self.explore_refused,
243            self.explore_prepared,
244        ]
245    }
246
247    fn total(&self) -> u128 {
248        self.counts().iter().map(|&x| u128::from(x)).sum()
249    }
250}
251
252/// One pre-registered class's tested units, errors, level `δ_c`, status count and re-scored units
253/// (spec v1.6 §2.2).
254#[derive(Deserialize, Clone, Debug, PartialEq)]
255#[serde(deny_unknown_fields)]
256pub struct ClassResult {
257    #[serde(deserialize_with = "nullable")]
258    pub value: Option<String>,
259    pub n: u64,
260    pub errors: u64,
261    pub delta: f64,
262    pub status: StatusCount,
263    pub unsealed: u64,
264    pub rescored: u64,
265}
266
267/// A scaled value `m · 2^k`, `1 <= m < 2^64`, `k` a multiple of 64 (spec v1.6 §1.3).
268#[derive(Clone, Copy, Debug, PartialEq)]
269struct Scaled {
270    m: f64,
271    k: i64,
272}
273
274fn norm(mut m: f64, mut k: i64) -> Scaled {
275    while m >= UP {
276        m *= DOWN;
277        k += 64;
278    }
279    while m < 1.0 {
280        m *= UP;
281        k -= 64;
282    }
283    Scaled { m, k }
284}
285
286fn mul(a: Scaled, b: Scaled) -> Scaled {
287    norm(a.m * b.m, a.k + b.k)
288}
289
290/// `base^exp`, `base > 0`, by squaring from the lowest bit (recipe step 1).
291fn pow(base: f64, mut exp: u64) -> Scaled {
292    let mut r = Scaled { m: 1.0, k: 0 };
293    let mut s = norm(base, 0);
294    while exp > 0 {
295        if exp & 1 == 1 {
296            r = mul(r, s);
297        }
298        exp >>= 1;
299        if exp > 0 {
300            s = mul(s, s);
301        }
302    }
303    r
304}
305
306/// Recipe step 3: the terms aligned to the largest exponent and added in order.
307fn sum(terms: &[Scaled]) -> Scaled {
308    let top = terms.iter().map(|t| t.k).max().unwrap_or(0);
309    let mut total = 0.0;
310    for t in terms {
311        let (mut m, mut k) = (t.m, t.k);
312        // m is 0 after at most 18 steps and stays 0: stopping there gives the same bits (spec §1.3, step 3)
313        while k < top && m != 0.0 {
314            m *= DOWN;
315            k += 64;
316        }
317        total += m;
318    }
319    norm(total, top)
320}
321
322/// 19 · E_n, scaled (recipe steps 2 and 3).
323fn mixture(n: u64, errors: u64, alpha: f64) -> Scaled {
324    let den = 1.0 - alpha;
325    let terms: Vec<Scaled> = (1..GRID)
326        .map(|j| {
327            let j = f64::from(j);
328            let r = j / f64::from(GRID);
329            let a = (alpha * j) / f64::from(GRID);
330            let b = (1.0 - a) / den;
331            mul(pow(r, errors), pow(b, n - errors))
332        })
333        .collect();
334    sum(&terms)
335}
336
337/// 19 · M, the tail monitor's mixture, scaled: `q'_j = alpha + (1 - alpha) j / 20` (spec v1.6 §1.3).
338fn tail_mixture(n: u64, errors: u64, alpha: f64) -> Scaled {
339    let terms: Vec<Scaled> = (1..GRID)
340        .map(|j| {
341            let r = (alpha + ((1.0 - alpha) * f64::from(j)) / f64::from(GRID)) / alpha;
342            let b = f64::from(GRID - j) / f64::from(GRID);
343            mul(pow(r, errors), pow(b, n - errors))
344        })
345        .collect();
346    sum(&terms)
347}
348
349fn at_least(s: Scaled, level: f64) -> bool {
350    let t = norm(f64::from(GRID - 1) / level, 0);
351    s.k > t.k || (s.k == t.k && s.m >= t.m)
352}
353
354/// The least `alpha`, per-class level `delta_c` and `tail_level` a v1.6 certificate may carry (spec v1.6
355/// §2.7): below it, `19 / level` or the tail's ratio can leave binary64's range and the recipe is undefined.
356pub const MIN_LEVEL: f64 = 1e-12;
357
358fn level_ok(x: f64) -> bool {
359    (MIN_LEVEL..1.0).contains(&x)
360}
361
362/// Whether a class with `n` tested records and `errors` errors crossed at level `delta_c`: its
363/// grid-mixture test supermartingale is at least `1 / delta_c` (spec v1.6 §1.3), by the spec's
364/// recipe. None when the inputs are out of range (`errors <= n <= 10^9`, `alpha` and `delta_c` in
365/// [`MIN_LEVEL`], 1)).
366pub fn crossed(n: u64, errors: u64, alpha: f64, delta_c: f64) -> Option<bool> {
367    if errors > n || n > MAX_TESTED || !level_ok(alpha) || !level_ok(delta_c) {
368        return None;
369    }
370    Some(at_least(mixture(n, errors, alpha), delta_c))
371}
372
373/// Whether the tail monitor trips on `n` resolved tail units with `errors` errors at `level`: its
374/// mirrored grid mixture is at least `1 / level` (spec v1.6 §1.3). None when the inputs are out of
375/// range (`errors <= n <= 2^53 - 1`, `alpha` and `level` in [`MIN_LEVEL`], 1)).
376pub fn tail_trips(n: u64, errors: u64, alpha: f64, level: f64) -> Option<bool> {
377    if errors > n || n > MAX_COUNT || !level_ok(alpha) || !level_ok(level) {
378        return None;
379    }
380    Some(at_least(tail_mixture(n, errors, alpha), level))
381}
382
383/// The salt commitment's domain-separation prefix (spec v1.6 §1.7).
384pub const EXPLORE_COMMIT_PREFIX: &[u8] = b"seam.gate.explore.v1\n";
385/// The draw's message prefix (`bucket_version` bp2, spec v1.6 §1.7).
386pub const BUCKET_MSG_PREFIX: &[u8] = b"bp2\n";
387/// The number of buckets: a rate is a whole number of basis points.
388pub const BUCKETS: u64 = 10_000;
389
390fn hex64(s: &str) -> bool {
391    s.len() == 64
392        && s.bytes()
393            .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
394}
395
396fn salt_bytes(salt: &str) -> Option<[u8; 32]> {
397    if !hex64(salt) {
398        return None;
399    }
400    let nib = |c: u8| {
401        if c.is_ascii_digit() {
402            c - b'0'
403        } else {
404            c - b'a' + 10
405        }
406    };
407    let b = salt.as_bytes();
408    let mut out = [0u8; 32];
409    for (i, o) in out.iter_mut().enumerate() {
410        *o = (nib(b[2 * i]) << 4) | nib(b[2 * i + 1]);
411    }
412    Some(out)
413}
414
415/// `sha256:` + hex SHA-256(`"seam.gate.explore.v1" 0x0A` ‖ the 32 salt bytes): the commitment
416/// sealed before the window (spec v1.6 §1.7). None unless `salt` is 64 lowercase hex.
417pub fn salt_commitment(salt: &str) -> Option<String> {
418    let key = salt_bytes(salt)?;
419    let mut h = Sha256::new();
420    h.update(EXPLORE_COMMIT_PREFIX);
421    h.update(key);
422    Some(format!("sha256:{}", crate::hex(&h.finalize())))
423}
424
425/// HMAC-SHA-256 (RFC 2104) with a 32-byte key.
426fn hmac_sha256(key: &[u8; 32], msg: &[&[u8]]) -> [u8; 32] {
427    let mut ipad = [0x36u8; 64];
428    let mut opad = [0x5cu8; 64];
429    for (i, k) in key.iter().enumerate() {
430        ipad[i] ^= k;
431        opad[i] ^= k;
432    }
433    let mut inner = Sha256::new();
434    inner.update(ipad);
435    for m in msg {
436        inner.update(m);
437    }
438    let mut outer = Sha256::new();
439    outer.update(opad);
440    outer.update(inner.finalize());
441    outer.finalize().into()
442}
443
444/// A unit's bp2 bucket (spec v1.6 §1.7): the first eight bytes of HMAC-SHA-256(salt,
445/// `"bp2" 0x0A` ‖ experiment_id ‖ `0x0A` ‖ unit), big-endian, modulo 10000. The unit is selected
446/// when the bucket is below the rate in basis points. None unless `salt` is 64 lowercase hex.
447pub fn explore_bucket(salt: &str, experiment_id: &str, unit: &str) -> Option<u64> {
448    let key = salt_bytes(salt)?;
449    let d = hmac_sha256(
450        &key,
451        &[
452            BUCKET_MSG_PREFIX,
453            experiment_id.as_bytes(),
454            b"\n",
455            unit.as_bytes(),
456        ],
457    );
458    let mut first = [0u8; 8];
459    first.copy_from_slice(&d[..8]);
460    Some(u64::from_be_bytes(first) % BUCKETS)
461}
462
463/// The whole number of basis points `r` with `rate = r / 10000` (one IEEE division),
464/// `1 <= r <= 9999`, or None.
465pub fn rate_bp(rate: f64) -> Option<u32> {
466    let r = (rate * 10000.0 + 0.5).floor();
467    ((1.0..=9999.0).contains(&r) && r / 10000.0 == rate).then_some(r as u32)
468}
469
470/// `<source>:sha256:<64 lowercase hex>`, `<source>` 1 to 32 of `a-z 0-9 -` starting with a letter.
471fn record_ref_ok(s: &str) -> bool {
472    let Some((source, hex)) = s.split_once(":sha256:") else {
473        return false;
474    };
475    let b = source.as_bytes();
476    (1..=32).contains(&b.len())
477        && b[0].is_ascii_lowercase()
478        && b.iter()
479            .all(|&c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
480        && hex64(hex)
481}
482
483/// A table of 1 to 256 of `A-Z a-z 0-9 . _ : / -` and a decimal snapshot id (an optional `-`, 1 to
484/// 19 digits).
485fn outcome_source_ok(o: Option<&OutcomeSource>) -> bool {
486    let Some(o) = o else {
487        return true;
488    };
489    let t = o.table.as_bytes();
490    let digits = o.snapshot_id.strip_prefix('-').unwrap_or(&o.snapshot_id);
491    (1..=256).contains(&t.len())
492        && t.iter()
493            .all(|&c| c.is_ascii_alphanumeric() || b"._:/-".contains(&c))
494        && (1..=19).contains(&digits.len())
495        && digits.bytes().all(|c| c.is_ascii_digit())
496}
497
498/// The checks of spec v1.6 §2.7 beyond the schema and beyond v1.5's (which [`crate::check`] runs).
499pub(crate) fn check(c: &Certificate) -> Result<(), CertError> {
500    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
501    let Some(s) = &c.sequential else {
502        return bad("a v1.6 certificate needs sequential");
503    };
504    // §2.1's fixed values
505    let automated_ok = c.automated.as_ref().is_some_and(|a| {
506        a.ucb.is_none()
507            && a.realized_band.as_ref() == Some(&c.realized_band)
508            && a.loss_sum == Some(None)
509            && a.realized_cost == Some(None)
510    });
511    if c.n_cal != c.n
512        || c.n_temperature != 0
513        || c.split.method != "time"
514        || c.split.seed.is_some()
515        || c.ucb.is_some()
516        || !c.segments.is_empty()
517        || c.cost != Some(None)
518        || c.pvalue != Some(None)
519        || c.loss_sum != Some(None)
520        || c.realized_cost != Some(None)
521        || c.abstain_below > 1.0
522        || !automated_ok
523    {
524        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");
525    }
526    let Some(window) = &c.window else {
527        return bad("a v1.6 certificate has a window");
528    };
529    if ![&s.flow, &s.env, &s.attempt].iter().all(|x| tenant_ok(x)) {
530        return bad("flow, env and attempt must be 1 to 128 characters of A-Z a-z 0-9 . _ : -");
531    }
532    let p = &s.preregistration;
533    let rec = &s.reconciliation;
534    if ![&p.digest, &p.config_digest, &rec.health_digest]
535        .iter()
536        .all(|x| crate::sha256_ok(x))
537    {
538        return bad("preregistration digest and config_digest, and reconciliation health_digest, must be sha256:<64 hex>");
539    }
540    // classes (§1.5)
541    let auto = c.automate_options.as_deref().unwrap_or_default();
542    let cl = &p.classes;
543    let values: Vec<Option<&str>> = match (cl.by.as_str(), cl.field.as_deref()) {
544        ("none", None) if cl.values.is_empty() => vec![None],
545        ("option", None) if cl.values.as_slice() == auto => {
546            cl.values.iter().map(|v| Some(v.as_str())).collect()
547        }
548        ("segment", Some(f))
549            if !f.is_empty()
550                && !cl.values.is_empty()
551                && cl.values.iter().all(|v| !v.is_empty())
552                && cl.values.windows(2).all(|w| w[0].as_bytes() < w[1].as_bytes()) =>
553        {
554            cl.values.iter().map(|v| Some(v.as_str())).collect()
555        }
556        _ => 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)"),
557    };
558    let rate = p.exploration_rate;
559    let exploring = p.basis == "exploration";
560    let basis_ok = (exploring && rate > 0.0 && rate < 1.0)
561        || (p.basis == "ground_truth" && (0.0..1.0).contains(&rate));
562    let lim = &p.limits;
563    if !basis_ok
564        || !matches!(
565            p.interim_rule.as_str(),
566            "own_rule" | "follow_model" | "escalate" | "refuse"
567        )
568        || p.stopping_rule != "every_class_crosses"
569        || !matches!(p.model_verification.as_str(), "recompute" | "receipt")
570        || !(1..=3650).contains(&p.label_horizon_days)
571        || !(1..=3650).contains(&p.ttl_days)
572        || !(1..=520).contains(&p.min_weekly_cycles)
573        || p.no_news_rule
574            .as_ref()
575            .is_some_and(|r| !c.options.contains(&r.label))
576        || !p.eligibility.iter().all(|x| tenant_ok(x))
577        || !p
578            .eligibility
579            .windows(2)
580            .all(|w| w[0].as_bytes() < w[1].as_bytes())
581        || lim.unclassifiable > MAX_COUNT
582        || lim.lost_draws > MAX_COUNT
583    {
584        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");
585    }
586    let obs: &[String] = p
587        .no_news_rule
588        .as_ref()
589        .map_or(&[], |r| r.observable_options.as_slice());
590    let budget = &p.pause_budget;
591    let recompute = p.model_verification == "recompute";
592    if (p.no_news_rule.is_some() && (obs.is_empty() || !obs.iter().all(|o| c.options.contains(o))))
593        || !obs.windows(2).all(|w| w[0].as_bytes() < w[1].as_bytes())
594        || p.adjudication_days > 365
595        || !(7..=3650).contains(&p.max_window_days)
596        || u64::from(p.max_window_days) < 7 * u64::from(p.min_weekly_cycles)
597        || [lim.duplicates, lim.pre_known, lim.erased]
598            .iter()
599            .any(|&x| x > MAX_COUNT)
600        || budget.count > MAX_COUNT
601        || budget.seconds > MAX_COUNT
602        || p.fidelity_sample > MAX_COUNT
603        || (recompute && p.fidelity_sample < 1)
604        || (!recompute && p.fidelity_sample != 0)
605        || !level_ok(p.tail_level)
606    {
607        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");
608    }
609    // the exploration draw (§1.7)
610    let w = p.resolution_window_hours;
611    if exploring {
612        let ex_ok = match (&p.exploration, w) {
613            (Some(ex), Some(w)) => {
614                (1..=87_600).contains(&w)
615                    && u64::from(w) <= 24 * u64::from(p.label_horizon_days)
616                    && rate_bp(rate).is_some()
617                    && tenant_ok(&ex.experiment_id)
618                    && ex.bucket_version == "bp2"
619                    && ex.unit == "decision"
620                    && matches!(ex.unit_source.as_str(), "decision_id" | "business_event_id")
621                    && ex.unit_key_id.is_none() == (ex.unit_source == "decision_id")
622                    && ex.unit_key_id.as_deref().is_none_or(tenant_ok)
623                    && crate::sha256_ok(&ex.salt_commitment)
624            }
625            _ => false,
626        };
627        if !ex_ok {
628            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");
629        }
630        let ex = p.exploration.as_ref().expect("checked above");
631        let Some(salt) = ex.salt.as_deref().filter(|s| hex64(s)) else {
632            return bad("an exploration certificate reveals its salt: 64 lowercase hex");
633        };
634        if salt_commitment(salt).as_deref() != Some(ex.salt_commitment.as_str()) {
635            return bad("the revealed salt does not match salt_commitment (spec v1.6 §1.7)");
636        }
637    } else if p.exploration.is_some() || w.is_some() {
638        return bad("under ground_truth, exploration and resolution_window_hours are null");
639    }
640    // results: one per class, in order, δ_c = delta / K, and every class crosses
641    let delta = c.delta.unwrap_or(0.0);
642    let delta_c = delta / values.len() as f64;
643    if !level_ok(c.alpha) || !level_ok(delta_c) {
644        return bad("alpha and delta / K must each be at least 10^-12 (spec v1.6 §2.7)");
645    }
646    if s.results.len() != values.len()
647        || !s
648            .results
649            .iter()
650            .zip(&values)
651            .all(|(r, v)| r.value.as_deref() == *v)
652    {
653        return bad("results must have one entry per pre-registered class, in order");
654    }
655    let mut total: u128 = 0;
656    for r in &s.results {
657        if r.errors > r.n
658            || r.n > MAX_TESTED
659            || r.delta != delta_c
660            || r.unsealed > r.n
661            || r.status.total() != u128::from(r.n - r.unsealed.min(r.n))
662            || r.rescored > r.n
663            || (p.model_verification == "receipt" && r.rescored != 0)
664        {
665            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)");
666        }
667        total += u128::from(r.n);
668    }
669    for r in &s.results {
670        if crossed(r.n, r.errors, c.alpha, delta_c) != Some(true) {
671            return Err(CertError::Invalid(format!(
672                "class {} did not cross: its test supermartingale is below 1/delta_c (spec v1.6 §1.3)",
673                r.value.as_deref().unwrap_or("(all)")
674            )));
675        }
676    }
677    // reconciliation (§2.6)
678    let (unclass, draws, tail) = (rec.unclassifiable, &rec.draws, &rec.tail);
679    let lost = draws.lost;
680    if unclass > lim.unclassifiable
681        || s.results
682            .iter()
683            .any(|r| u128::from(unclass) + u128::from(lost) > u128::from(r.errors))
684        || s.results.iter().any(|r| r.unsealed < lost)
685        || u128::from(draws.answered) != u128::from(draws.sealed) + u128::from(draws.unsealed)
686        || draws.answered > MAX_COUNT
687        || lost > lim.lost_draws
688        || rec.duplicates > lim.duplicates
689        || rec.pre_known > lim.pre_known
690        || rec.erased > lim.erased
691        || rec.rescored_untested > MAX_COUNT
692        || rec.fidelity_checked != p.fidelity_sample
693        || rec.fidelity_checked > c.n
694        || (!recompute && (rec.rescored_untested != 0 || rec.fidelity_checked != 0))
695        || rec.pauses.count > budget.count
696        || rec.pauses.seconds > budget.seconds
697        || tail.decided > MAX_COUNT
698        || tail.selected > MAX_COUNT
699        || tail.status.total() > u128::from(tail.selected)
700        || tail.errors > tail.resolved
701        || tail.resolved > MAX_COUNT
702    {
703        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");
704    }
705    if tail_trips(tail.resolved, tail.errors, c.alpha, p.tail_level) != Some(false) {
706        return bad("the tail monitor tripped on the tail's resolved units: issuance is refused (spec v1.6 §1.3, §1.6)");
707    }
708    // record range, labels, audit
709    let rr = &s.record_range;
710    if !record_ref_ok(&rr.first) || !record_ref_ok(&rr.last) {
711        return bad("record_range first and last must be <source>:sha256:<64 hex>");
712    }
713    if !outcome_source_ok(rr.outcome_source.as_ref()) {
714        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");
715    }
716    let tested = rr.tested;
717    let k = values.len() as u128;
718    if rr.decided != c.n
719        || c.audit.n != tested
720        || tested > MAX_COUNT
721        || rec.pre_known > tested
722        || rec.erased > tested
723        || total != u128::from(tested) + (k - 1) * (u128::from(unclass) + u128::from(lost))
724        || rr.revision_from > rr.revision_to
725        || rr.revision_to > MAX_COUNT
726    {
727        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");
728    }
729    let lb = &s.labels.basis;
730    let lr = &s.labels.resolution;
731    let sum = |xs: &[u64]| xs.iter().map(|&x| u128::from(x)).sum::<u128>();
732    let t = u128::from(tested);
733    if sum(&[lb.ground_truth, lb.action_conditional, lb.decider_choice]) != t
734        || sum(&[
735            lr.observed,
736            lr.no_news,
737            lr.missing_as_error,
738            lr.not_executed,
739        ]) != t
740        || lb.decider_choice != 0
741        || (!exploring && lb.action_conditional != 0)
742        || (p.no_news_rule.is_none() && lr.no_news != 0)
743        || s.labels.adjudicated > s.labels.contested
744        || s.labels.contested > tested
745        || s.labels.contested - s.labels.adjudicated.min(s.labels.contested) > lr.missing_as_error
746    {
747        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");
748    }
749    if !exploring
750        && (lr.not_executed != 0
751            || s.results
752                .iter()
753                .any(|r| r.status.explore_refused != 0 || r.status.explore_prepared != 0)
754            || tail.status.explore_refused != 0
755            || tail.status.explore_prepared != 0
756            || [draws.answered, draws.sealed, draws.unsealed, draws.lost]
757                .iter()
758                .any(|&x| x != 0)
759            || s.results.iter().any(|r| r.unsealed != 0)
760            || tail.selected != 0)
761    {
762        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");
763    }
764    let audit_ok = if exploring {
765        c.audit.mode == "sample" && c.audit.rate == rate && c.audit.propensity_logged
766    } else {
767        c.audit.mode == "full-label" && c.audit.rate == 1.0 && !c.audit.propensity_logged
768    };
769    if !audit_ok {
770        return bad("audit must be sample at the exploration rate with propensity logged under exploration, full-label at rate 1 without under ground_truth");
771    }
772    // dates
773    let start = v16_timestamp(&window.start)?;
774    let end = v16_timestamp(&window.end)?;
775    let cutoff = v16_timestamp(&rr.cutoff)?;
776    let sealed = v16_timestamp(&p.sealed_at)?;
777    let fitted = v16_timestamp(&c.fitted_at)?;
778    let expires = v16_timestamp(&c.expires_at)?;
779    let wait = Duration::hours(i64::from(w.unwrap_or(0)))
780        + Duration::days(i64::from(p.label_horizon_days) + i64::from(p.adjudication_days));
781    let span = end - start;
782    if sealed > start
783        || start > end
784        || end.checked_add(wait).is_none_or(|t| t > cutoff)
785        || cutoff > fitted
786        || span < Duration::days(7 * i64::from(p.min_weekly_cycles))
787        || span > Duration::days(i64::from(p.max_window_days))
788        || i128::from(rec.pauses.seconds) > i128::from(span.whole_seconds())
789    {
790        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");
791    }
792    if cutoff.checked_add(Duration::days(i64::from(p.ttl_days))) != Some(expires) {
793        return bad("expires_at must be record_range.cutoff + ttl_days days");
794    }
795    Ok(())
796}
797
798/// A v1.6 date (spec v1.6 §2.7): the spec's timestamp form, without a leap second, whose arithmetic
799/// the spec leaves to no convention.
800pub(crate) fn v16_timestamp(s: &str) -> Result<time::UtcDateTime, CertError> {
801    if s.len() == 20 && s.as_bytes()[17..19] == *b"60" {
802        return Err(CertError::Invalid(
803            "a v1.6 date has no leap second (seconds 60) (spec v1.6 §2.7)".to_string(),
804        ));
805    }
806    timestamp(s)
807}
808
809#[cfg(test)]
810mod tests {
811    use super::*;
812
813    #[test]
814    fn zero_errors_cross_where_the_review_simulated() {
815        // 90 records at delta 0.05 and 124 at 0.0125, alpha 0.05 (DECISIONS.md V16-3)
816        assert_eq!(crossed(89, 0, 0.05, 0.05), Some(false));
817        assert_eq!(crossed(90, 0, 0.05, 0.05), Some(true));
818        assert_eq!(crossed(123, 0, 0.05, 0.0125), Some(false));
819        assert_eq!(crossed(124, 0, 0.05, 0.0125), Some(true));
820    }
821
822    #[test]
823    fn crossing_is_monotone_in_errors_and_never_at_zero_records() {
824        assert_eq!(crossed(0, 0, 0.05, 0.5), Some(false));
825        assert_eq!(crossed(276, 5, 0.05, 0.05), Some(true));
826        assert_eq!(crossed(275, 5, 0.05, 0.05), Some(false));
827        assert_eq!(crossed(276, 6, 0.05, 0.05), Some(false));
828        // a rate at alpha never crosses, however many records
829        assert_eq!(
830            crossed(MAX_TESTED, MAX_TESTED / 20, 0.05, 0.05),
831            Some(false)
832        );
833        assert_eq!(crossed(MAX_TESTED, MAX_TESTED / 25, 0.05, 0.05), Some(true));
834    }
835
836    #[test]
837    fn the_tail_monitor_trips_where_exact_arithmetic_does() {
838        // the least error count that trips at alpha 0.05, level 0.01, from exact rational arithmetic
839        for (n, e) in [(20, 6), (50, 10), (120, 17), (500, 47)] {
840            assert_eq!(tail_trips(n, e, 0.05, 0.01), Some(true), "{n} {e}");
841            assert_eq!(tail_trips(n, e - 1, 0.05, 0.01), Some(false), "{n} {e}");
842        }
843        // no resolved units never trips; an error rate below alpha never trips
844        assert_eq!(tail_trips(0, 0, 0.05, 0.01), Some(false));
845        assert_eq!(tail_trips(1_000_000, 40_000, 0.05, 0.01), Some(false));
846        assert_eq!(tail_trips(5, 6, 0.05, 0.01), None);
847        assert_eq!(tail_trips(5, 0, 0.05, 1.0), None);
848    }
849
850    #[test]
851    fn out_of_range_inputs_have_no_verdict() {
852        assert_eq!(crossed(5, 6, 0.05, 0.05), None);
853        assert_eq!(crossed(MAX_TESTED + 1, 0, 0.05, 0.05), None);
854        assert_eq!(crossed(5, 0, 0.0, 0.05), None);
855        assert_eq!(crossed(5, 0, 0.05, 1.0), None);
856    }
857}