Skip to main content

decision_cert/
challenger.rs

1//! `decision-certificate.v1.7` (spec/decision-certificate.v1.7.md): the attempt's role, the
2//! champion a challenger runs beside and what it changes (§1.1 to §1.4), the delta budget (§1.5),
3//! the checks beyond the schema (§2.5) and promotion (§4.2).
4//!
5//! A v1.7 certificate is a v1.6 certificate with three more fields in `sequential`. They are read
6//! apart from the v1.6 block (when the certificate is read), so a v1.6 certificate parses, and is refused,
7//! exactly as before.
8
9use serde::Deserialize;
10
11use crate::sequential::v16_timestamp;
12use crate::{nullable, CertError, Certificate};
13
14/// The `changes` a challenger may declare (spec v1.7 §1.4), sorted bytewise.
15pub const CHANGES: [&str; 9] = [
16    "abstain_below",
17    "alpha",
18    "automate_options",
19    "calibration_map",
20    "classes",
21    "configuration",
22    "eligibility",
23    "model_release",
24    "rule",
25];
26/// The fields a v1.7 certificate adds to `sequential`, read apart from the v1.6 block.
27pub(crate) const FIELDS: [&str; 3] = ["role", "challenger", "budget"];
28/// The largest amount of the budget, in parts per million (spec v1.7 §2.4).
29pub const MAX_PPM: u32 = 999_999;
30
31/// The three fields a v1.7 certificate adds to `sequential` (spec v1.7 §2.2 to §2.4).
32#[derive(Deserialize, Clone, Debug, PartialEq)]
33#[serde(deny_unknown_fields)]
34pub struct AttemptRole {
35    pub role: String,
36    #[serde(deserialize_with = "nullable")]
37    pub challenger: Option<Challenger>,
38    pub budget: Budget,
39}
40
41/// The champion a challenger runs beside, and what it changes (spec v1.7 §2.3).
42#[derive(Deserialize, Clone, Debug, PartialEq)]
43#[serde(deny_unknown_fields)]
44pub struct Challenger {
45    pub champion: Champion,
46    pub changes: Vec<String>,
47}
48
49/// The champion's certificate, cited by its id and some of its values (spec v1.7 §2.3).
50#[derive(Deserialize, Clone, Debug, PartialEq)]
51#[serde(deny_unknown_fields)]
52pub struct Champion {
53    pub certificate_id: String,
54    pub spec: String,
55    pub attempt: String,
56    pub preregistration_digest: String,
57    #[serde(deserialize_with = "nullable")]
58    pub experiment_id: Option<String>,
59    pub model_id: String,
60    #[serde(deserialize_with = "nullable")]
61    pub manifest_hash: Option<String>,
62    pub expires_at: String,
63}
64
65/// The attempt's debit in the control plane's account across attempts (spec v1.7 §1.5, §2.4).
66#[derive(Deserialize, Clone, Debug, PartialEq)]
67#[serde(deny_unknown_fields)]
68pub struct Budget {
69    pub window_days: u32,
70    pub total_ppm: u32,
71    pub spent_ppm: u32,
72    pub debit_ppm: u32,
73}
74
75/// The checks of spec v1.7 §2.5, after every v1.6 check (which [`crate::check`] runs first).
76pub(crate) fn check(c: &Certificate) -> Result<(), CertError> {
77    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
78    let Some(a) = &c.attempt_role else {
79        return bad("a v1.7 certificate needs role, challenger and budget in sequential");
80    };
81    let Some(s) = &c.sequential else {
82        return bad("a v1.7 certificate needs sequential");
83    };
84    match (a.role.as_str(), &a.challenger) {
85        ("standalone", None) | ("challenger", Some(_)) => {}
86        _ => return bad(
87            "role must be standalone with challenger null, or challenger with a challenger object",
88        ),
89    }
90    let b = &a.budget;
91    if !(1..=3650).contains(&b.window_days)
92        || !(1..=MAX_PPM).contains(&b.total_ppm)
93        || b.spent_ppm > MAX_PPM
94        || !(1..=MAX_PPM).contains(&b.debit_ppm)
95    {
96        return bad("budget: window_days 1 to 3650, total_ppm and debit_ppm 1 to 999999, spent_ppm 0 to 999999");
97    }
98    if c.delta != Some(f64::from(b.debit_ppm) / 1e6)
99        || u64::from(b.spent_ppm) + u64::from(b.debit_ppm) > u64::from(b.total_ppm)
100    {
101        return bad("budget: delta must be debit_ppm / 10^6, and spent_ppm + debit_ppm at most total_ppm (spec v1.7 §2.5)");
102    }
103    let Some(ch) = &a.challenger else {
104        return Ok(());
105    };
106    let known = ch.changes.iter().all(|x| CHANGES.contains(&x.as_str()));
107    if !known || !ch.changes.windows(2).all(|w| w[0] < w[1]) {
108        return bad("challenger changes must be distinct names of spec v1.7 §1.4, sorted bytewise");
109    }
110    let cp = &ch.champion;
111    let forms = crate::sha256_ok(&cp.certificate_id)
112        && crate::sha256_ok(&cp.preregistration_digest)
113        && (cp.spec == crate::SPEC_V1_6 || cp.spec == crate::SPEC_V1_7)
114        && crate::tenant_ok(&cp.attempt)
115        && cp.experiment_id.as_deref().is_none_or(crate::tenant_ok)
116        && crate::model_id_ok(&cp.model_id)
117        && cp.manifest_hash.as_deref().is_none_or(crate::sha256_ok);
118    if !forms {
119        return bad("challenger champion: certificate_id and preregistration_digest sha256:<64 hex>, spec v1.6 or v1.7, attempt and experiment_id 1 to 128 characters of A-Z a-z 0-9 . _ : -, model_id <backend>/<model>@<version>, manifest_hash sha256:<64 hex> or null");
120    }
121    let p = &s.preregistration;
122    if v16_timestamp(&p.sealed_at)? >= v16_timestamp(&cp.expires_at)? {
123        return bad(
124            "a challenger is pre-registered before its champion's expires_at (spec v1.7 §2.5)",
125        );
126    }
127    if s.attempt == cp.attempt || p.digest == cp.preregistration_digest {
128        return bad("a challenger's attempt and pre-registration differ from its champion's");
129    }
130    if let (Some(e), Some(champion_experiment)) = (&p.exploration, &cp.experiment_id) {
131        if &e.experiment_id == champion_experiment {
132            return bad(
133                "a challenger's experiment_id differs from its champion's (spec v1.6 §1.7)",
134            );
135        }
136    }
137    let new_release = c.model_id != cp.model_id || c.manifest_hash != cp.manifest_hash;
138    if new_release != ch.changes.iter().any(|x| x == "model_release") {
139        return bad("challenger changes list model_release exactly when model_id or manifest_hash differs from the champion's");
140    }
141    Ok(())
142}
143
144/// A v1.6 attempt's debit in the account: the least whole number of parts per million whose
145/// binary64 quotient by 10^6 is at least its `delta` (spec v1.7 §1.5).
146pub fn debit_ppm(delta: f64) -> u32 {
147    let mut d = (delta * 1e6).ceil().clamp(0.0, 1e6) as u32;
148    while f64::from(d) / 1e6 < delta && d < 1_000_000 {
149        d += 1;
150    }
151    while d > 0 && f64::from(d - 1) / 1e6 >= delta {
152        d -= 1;
153    }
154    d
155}
156
157/// The two certificates' differences in each named change of spec v1.7 §1.4 but `configuration`,
158/// in [`CHANGES`] order: (name, differs).
159pub(crate) fn differences(
160    challenger: (&Certificate, &serde_json::Value),
161    champion: (&Certificate, &serde_json::Value),
162) -> Result<Vec<(&'static str, bool)>, CertError> {
163    let ((a, av), (b, bv)) = (challenger, champion);
164    let jcs = |v: &serde_json::Value, path: &[&str]| {
165        let mut x = v;
166        for k in path {
167            x = &x[*k];
168        }
169        crate::canonical(x)
170    };
171    let (Some(pa), Some(pb)) = (
172        a.sequential.as_ref().map(|s| &s.preregistration),
173        b.sequential.as_ref().map(|s| &s.preregistration),
174    ) else {
175        return Err(CertError::Invalid(
176            "a sequential certificate needs sequential".into(),
177        ));
178    };
179    let classes = ["sequential", "preregistration", "classes"];
180    Ok(vec![
181        ("abstain_below", a.abstain_below != b.abstain_below),
182        ("alpha", a.alpha != b.alpha),
183        ("automate_options", a.automate_options != b.automate_options),
184        (
185            "calibration_map",
186            jcs(av, &["calibration_map"])? != jcs(bv, &["calibration_map"])?,
187        ),
188        ("classes", jcs(av, &classes)? != jcs(bv, &classes)?),
189        ("eligibility", pa.eligibility != pb.eligibility),
190        (
191            "model_release",
192            a.model_id != b.model_id || a.manifest_hash != b.manifest_hash,
193        ),
194        ("rule", jcs(av, &["rule"])? != jcs(bv, &["rule"])?),
195    ])
196}
197
198#[cfg(test)]
199mod tests {
200    use super::debit_ppm;
201
202    #[test]
203    fn a_v1_6_debit_is_the_least_whole_ppm_at_or_above_delta() {
204        assert_eq!(debit_ppm(0.02), 20_000);
205        assert_eq!(debit_ppm(0.05), 50_000);
206        assert_eq!(debit_ppm(1e-12), 1);
207        assert_eq!(debit_ppm(0.020_000_000_1), 20_001);
208        assert_eq!(debit_ppm(0.999_999), 999_999);
209        assert_eq!(debit_ppm(0.999_999_5), 1_000_000);
210        for d in [1_u32, 7, 19_999, 20_000, 333_333, 999_999] {
211            assert_eq!(debit_ppm(f64::from(d) / 1e6), d);
212        }
213    }
214}