use serde::Deserialize;
use crate::sequential::v16_timestamp;
use crate::{nullable, CertError, Certificate};
pub const CHANGES: [&str; 9] = [
"abstain_below",
"alpha",
"automate_options",
"calibration_map",
"classes",
"configuration",
"eligibility",
"model_release",
"rule",
];
pub(crate) const FIELDS: [&str; 3] = ["role", "challenger", "budget"];
pub const MAX_PPM: u32 = 999_999;
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct AttemptRole {
pub role: String,
#[serde(deserialize_with = "nullable")]
pub challenger: Option<Challenger>,
pub budget: Budget,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Challenger {
pub champion: Champion,
pub changes: Vec<String>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Champion {
pub certificate_id: String,
pub spec: String,
pub attempt: String,
pub preregistration_digest: String,
#[serde(deserialize_with = "nullable")]
pub experiment_id: Option<String>,
pub model_id: String,
#[serde(deserialize_with = "nullable")]
pub manifest_hash: Option<String>,
pub expires_at: String,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Budget {
pub window_days: u32,
pub total_ppm: u32,
pub spent_ppm: u32,
pub debit_ppm: u32,
}
pub(crate) fn check(c: &Certificate) -> Result<(), CertError> {
let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
let Some(a) = &c.attempt_role else {
return bad("a v1.7 certificate needs role, challenger and budget in sequential");
};
let Some(s) = &c.sequential else {
return bad("a v1.7 certificate needs sequential");
};
match (a.role.as_str(), &a.challenger) {
("standalone", None) | ("challenger", Some(_)) => {}
_ => return bad(
"role must be standalone with challenger null, or challenger with a challenger object",
),
}
let b = &a.budget;
if !(1..=3650).contains(&b.window_days)
|| !(1..=MAX_PPM).contains(&b.total_ppm)
|| b.spent_ppm > MAX_PPM
|| !(1..=MAX_PPM).contains(&b.debit_ppm)
{
return bad("budget: window_days 1 to 3650, total_ppm and debit_ppm 1 to 999999, spent_ppm 0 to 999999");
}
if c.delta != Some(f64::from(b.debit_ppm) / 1e6)
|| u64::from(b.spent_ppm) + u64::from(b.debit_ppm) > u64::from(b.total_ppm)
{
return bad("budget: delta must be debit_ppm / 10^6, and spent_ppm + debit_ppm at most total_ppm (spec v1.7 §2.5)");
}
let Some(ch) = &a.challenger else {
return Ok(());
};
let known = ch.changes.iter().all(|x| CHANGES.contains(&x.as_str()));
if !known || !ch.changes.windows(2).all(|w| w[0] < w[1]) {
return bad("challenger changes must be distinct names of spec v1.7 §1.4, sorted bytewise");
}
let cp = &ch.champion;
let forms = crate::sha256_ok(&cp.certificate_id)
&& crate::sha256_ok(&cp.preregistration_digest)
&& (cp.spec == crate::SPEC_V1_6 || cp.spec == crate::SPEC_V1_7)
&& crate::tenant_ok(&cp.attempt)
&& cp.experiment_id.as_deref().is_none_or(crate::tenant_ok)
&& crate::model_id_ok(&cp.model_id)
&& cp.manifest_hash.as_deref().is_none_or(crate::sha256_ok);
if !forms {
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");
}
let p = &s.preregistration;
if v16_timestamp(&p.sealed_at)? >= v16_timestamp(&cp.expires_at)? {
return bad(
"a challenger is pre-registered before its champion's expires_at (spec v1.7 §2.5)",
);
}
if s.attempt == cp.attempt || p.digest == cp.preregistration_digest {
return bad("a challenger's attempt and pre-registration differ from its champion's");
}
if let (Some(e), Some(champion_experiment)) = (&p.exploration, &cp.experiment_id) {
if &e.experiment_id == champion_experiment {
return bad(
"a challenger's experiment_id differs from its champion's (spec v1.6 §1.7)",
);
}
}
let new_release = c.model_id != cp.model_id || c.manifest_hash != cp.manifest_hash;
if new_release != ch.changes.iter().any(|x| x == "model_release") {
return bad("challenger changes list model_release exactly when model_id or manifest_hash differs from the champion's");
}
Ok(())
}
pub fn debit_ppm(delta: f64) -> u32 {
let mut d = (delta * 1e6).ceil().clamp(0.0, 1e6) as u32;
while f64::from(d) / 1e6 < delta && d < 1_000_000 {
d += 1;
}
while d > 0 && f64::from(d - 1) / 1e6 >= delta {
d -= 1;
}
d
}
pub(crate) fn differences(
challenger: (&Certificate, &serde_json::Value),
champion: (&Certificate, &serde_json::Value),
) -> Result<Vec<(&'static str, bool)>, CertError> {
let ((a, av), (b, bv)) = (challenger, champion);
let jcs = |v: &serde_json::Value, path: &[&str]| {
let mut x = v;
for k in path {
x = &x[*k];
}
crate::canonical(x)
};
let (Some(pa), Some(pb)) = (
a.sequential.as_ref().map(|s| &s.preregistration),
b.sequential.as_ref().map(|s| &s.preregistration),
) else {
return Err(CertError::Invalid(
"a sequential certificate needs sequential".into(),
));
};
let classes = ["sequential", "preregistration", "classes"];
Ok(vec![
("abstain_below", a.abstain_below != b.abstain_below),
("alpha", a.alpha != b.alpha),
("automate_options", a.automate_options != b.automate_options),
(
"calibration_map",
jcs(av, &["calibration_map"])? != jcs(bv, &["calibration_map"])?,
),
("classes", jcs(av, &classes)? != jcs(bv, &classes)?),
("eligibility", pa.eligibility != pb.eligibility),
(
"model_release",
a.model_id != b.model_id || a.manifest_hash != b.manifest_hash,
),
("rule", jcs(av, &["rule"])? != jcs(bv, &["rule"])?),
])
}
#[cfg(test)]
mod tests {
use super::debit_ppm;
#[test]
fn a_v1_6_debit_is_the_least_whole_ppm_at_or_above_delta() {
assert_eq!(debit_ppm(0.02), 20_000);
assert_eq!(debit_ppm(0.05), 50_000);
assert_eq!(debit_ppm(1e-12), 1);
assert_eq!(debit_ppm(0.020_000_000_1), 20_001);
assert_eq!(debit_ppm(0.999_999), 999_999);
assert_eq!(debit_ppm(0.999_999_5), 1_000_000);
for d in [1_u32, 7, 19_999, 20_000, 333_333, 999_999] {
assert_eq!(debit_ppm(f64::from(d) / 1e6), d);
}
}
}