#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ParityLevel {
L0Preprocess,
L1PerOp,
L2PerLayer,
L3Logits,
L4Tokens,
L5EndToEnd,
}
impl ParityLevel {
pub const ALL: [Self; 6] = [
Self::L0Preprocess,
Self::L1PerOp,
Self::L2PerLayer,
Self::L3Logits,
Self::L4Tokens,
Self::L5EndToEnd,
];
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::L0Preprocess => "L0_preprocess",
Self::L1PerOp => "L1_per_op",
Self::L2PerLayer => "L2_per_layer",
Self::L3Logits => "L3_logits",
Self::L4Tokens => "L4_tokens",
Self::L5EndToEnd => "L5_end_to_end",
}
}
#[must_use]
pub const fn index(self) -> u8 {
match self {
Self::L0Preprocess => 0,
Self::L1PerOp => 1,
Self::L2PerLayer => 2,
Self::L3Logits => 3,
Self::L4Tokens => 4,
Self::L5EndToEnd => 5,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToleranceKind {
Exact,
Cosine,
Measured,
ExactPrefix,
Budget,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToleranceSource {
StructuralSpec,
TodoDeriveFromOracleFloor,
TodoLedgerBudget,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GateTolerance {
pub level: ParityLevel,
pub kind: ToleranceKind,
pub cosine_min: Option<f64>,
pub max_abs_diff: Option<f64>,
pub logit_tolerance: Option<f64>,
pub argmax_must_match: bool,
pub exact_match: bool,
pub cer_budget: Option<f64>,
pub teds_budget: Option<f64>,
pub formula_cdm_budget: Option<f64>,
pub source: ToleranceSource,
pub note: &'static str,
}
impl GateTolerance {
const fn exact(level: ParityLevel, note: &'static str) -> Self {
Self {
level,
kind: ToleranceKind::Exact,
cosine_min: None,
max_abs_diff: Some(0.0),
logit_tolerance: None,
argmax_must_match: false,
exact_match: true,
cer_budget: None,
teds_budget: None,
formula_cdm_budget: None,
source: ToleranceSource::StructuralSpec,
note,
}
}
const fn cosine(level: ParityLevel, note: &'static str) -> Self {
Self {
level,
kind: ToleranceKind::Cosine,
cosine_min: Some(0.9999),
max_abs_diff: None,
logit_tolerance: None,
argmax_must_match: false,
exact_match: false,
cer_budget: None,
teds_budget: None,
formula_cdm_budget: None,
source: ToleranceSource::StructuralSpec,
note,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Tolerances {
pub l0: GateTolerance,
pub l1: GateTolerance,
pub l2: GateTolerance,
pub l3: GateTolerance,
pub l4: GateTolerance,
pub l5: GateTolerance,
}
impl Tolerances {
pub fn ordered(&self) -> [GateTolerance; 6] {
[self.l0, self.l1, self.l2, self.l3, self.l4, self.l5]
}
}
impl Default for Tolerances {
fn default() -> Self {
default_tolerances()
}
}
#[must_use]
pub fn default_tolerances() -> Tolerances {
Tolerances {
l0: GateTolerance::exact(
ParityLevel::L0Preprocess,
"exact gray pad, [-1,1] normalize, ratio selection, and tile geometry",
),
l1: GateTolerance::cosine(
ParityLevel::L1PerOp,
"cosine >= 0.9999 f32; bridge path applies the per-op ULP table",
),
l2: GateTolerance::cosine(
ParityLevel::L2PerLayer,
"cosine ~= 1.0 with per-layer max-abs-diff ledgered",
),
l3: GateTolerance {
level: ParityLevel::L3Logits,
kind: ToleranceKind::Measured,
cosine_min: None,
max_abs_diff: None,
logit_tolerance: None,
argmax_must_match: true,
exact_match: false,
cer_budget: None,
teds_budget: None,
formula_cdm_budget: None,
source: ToleranceSource::TodoDeriveFromOracleFloor,
note: "TODO derive logit budget from oracle nondeterminism floor before use",
},
l4: GateTolerance {
level: ParityLevel::L4Tokens,
kind: ToleranceKind::ExactPrefix,
cosine_min: None,
max_abs_diff: None,
logit_tolerance: None,
argmax_must_match: false,
exact_match: true,
cer_budget: None,
teds_budget: None,
formula_cdm_budget: None,
source: ToleranceSource::TodoDeriveFromOracleFloor,
note: "TODO set reproducible prefix lengths from oracle nondeterminism floor",
},
l5: GateTolerance {
level: ParityLevel::L5EndToEnd,
kind: ToleranceKind::Budget,
cosine_min: None,
max_abs_diff: None,
logit_tolerance: None,
argmax_must_match: false,
exact_match: false,
cer_budget: None,
teds_budget: None,
formula_cdm_budget: None,
source: ToleranceSource::TodoLedgerBudget,
note: "TODO fill CER/TEDS/Formula-CDM budgets from corpus and release ledger",
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RolloutStage {
Fp32Reference,
Int8FfnExpertsOnly,
Int8Attention,
Int8LmHead,
SimdKernels,
Int4Experts,
}
impl RolloutStage {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Fp32Reference => "P1_fp32_reference",
Self::Int8FfnExpertsOnly => "P2a_int8_ffn_experts",
Self::Int8Attention => "P2b_int8_attention",
Self::Int8LmHead => "P2c_int8_lm_head",
Self::SimdKernels => "P3_simd_kernels",
Self::Int4Experts => "P4_int4_experts",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InvariantKind {
KvCacheBound,
Int8AccumulatorOverflow,
Determinism,
SimdScalarBitIdentical,
}
impl InvariantKind {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::KvCacheBound => "kv_cache_bound",
Self::Int8AccumulatorOverflow => "int8_accumulator_overflow",
Self::Determinism => "determinism",
Self::SimdScalarBitIdentical => "simd_scalar_bit_identical",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct GateResult {
pub name: &'static str,
pub level: Option<ParityLevel>,
pub passed: bool,
pub measured: Option<f64>,
pub tolerance: Option<f64>,
pub message: &'static str,
}
impl GateResult {
#[must_use]
pub const fn pass(
name: &'static str,
level: Option<ParityLevel>,
message: &'static str,
) -> Self {
Self {
name,
level,
passed: true,
measured: None,
tolerance: None,
message,
}
}
#[must_use]
pub const fn fail(
name: &'static str,
level: Option<ParityLevel>,
message: &'static str,
) -> Self {
Self {
name,
level,
passed: false,
measured: None,
tolerance: None,
message,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RequirementLevel {
Must,
Should,
May,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConformanceCategory {
Differential,
Golden,
Metamorphic,
Parity,
Invariant,
}
pub trait ConformanceTest {
fn name(&self) -> &'static str;
fn category(&self) -> ConformanceCategory;
fn requirement_level(&self) -> RequirementLevel;
fn clauses(&self) -> &'static [u32];
fn run(&self) -> GateResult;
}
pub struct RegisteredConformance {
name: &'static str,
category: ConformanceCategory,
level: RequirementLevel,
clauses: &'static [u32],
run: fn() -> GateResult,
}
impl ConformanceTest for RegisteredConformance {
fn name(&self) -> &'static str {
self.name
}
fn category(&self) -> ConformanceCategory {
self.category
}
fn requirement_level(&self) -> RequirementLevel {
self.level
}
fn clauses(&self) -> &'static [u32] {
self.clauses
}
fn run(&self) -> GateResult {
(self.run)()
}
}
fn run_determinism_entry() -> GateResult {
let gate = DeterminismGate;
gate.validate_bytes(b"greedy output", b"greedy output")
}
fn run_input_fault_entry() -> GateResult {
let p = std::env::temp_dir().join(format!(
"focr_conformance_fault_probe_{}.png",
std::process::id()
));
let outcome = std::fs::write(&p, b"not an image")
.map_err(|e| crate::FocrError::Other(anyhow::anyhow!("probe write: {e}")))
.and_then(|()| {
match crate::preprocess::preprocess_image(
&p,
crate::preprocess::PreprocessMode::default(),
) {
Err(crate::FocrError::InputDecode(_)) => Ok(()),
Err(other) => Err(other),
Ok(_) => Err(crate::FocrError::Other(anyhow::anyhow!(
"corrupt probe unexpectedly preprocessed"
))),
}
});
let _ = std::fs::remove_file(&p);
GateResult {
name: "input_fault_typed_errors",
level: None,
passed: outcome.is_ok(),
measured: None,
tolerance: None,
message: if outcome.is_ok() {
"corrupt input surfaced as typed InputDecode (exit 4)"
} else {
"corrupt input did NOT surface as typed InputDecode"
},
}
}
fn run_tolerance_derivation_entry() -> GateResult {
let t = default_tolerances();
let ordered = t.ordered();
let sourced = ordered.iter().all(|g| {
matches!(
g.source,
ToleranceSource::StructuralSpec
| ToleranceSource::TodoDeriveFromOracleFloor
| ToleranceSource::TodoLedgerBudget
)
});
GateResult {
name: "tolerances_carry_declared_provenance",
level: None,
passed: sourced,
measured: None,
tolerance: None,
message: if sourced {
"every gate tolerance declares its provenance"
} else {
"a gate tolerance has undeclared provenance"
},
}
}
#[must_use]
pub fn conformance_registry() -> Vec<RegisteredConformance> {
vec![
RegisteredConformance {
name: "determinism_byte_identity",
category: ConformanceCategory::Invariant,
level: RequirementLevel::Must,
clauses: &[100, 101, 102, 103],
run: run_determinism_entry,
},
RegisteredConformance {
name: "tolerances_carry_declared_provenance",
category: ConformanceCategory::Parity,
level: RequirementLevel::Must,
clauses: &[],
run: run_tolerance_derivation_entry,
},
RegisteredConformance {
name: "input_fault_typed_errors",
category: ConformanceCategory::Invariant,
level: RequirementLevel::Must,
clauses: &[],
run: run_input_fault_entry,
},
]
}
pub trait ParityGate {
fn name(&self) -> &'static str;
fn level(&self) -> ParityLevel;
fn validate(&self, subject: &[u8], oracle: &[u8]) -> GateResult;
}
pub trait Invariant {
fn name(&self) -> &'static str;
fn kind(&self) -> InvariantKind;
fn validate(&self) -> GateResult;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlaceholderParityGate {
name: &'static str,
level: ParityLevel,
}
impl PlaceholderParityGate {
#[must_use]
pub const fn new(name: &'static str, level: ParityLevel) -> Self {
Self { name, level }
}
}
impl ParityGate for PlaceholderParityGate {
fn name(&self) -> &'static str {
self.name
}
fn level(&self) -> ParityLevel {
self.level
}
fn validate(&self, _subject: &[u8], _oracle: &[u8]) -> GateResult {
GateResult::pass(
self.name,
Some(self.level),
"placeholder validator declared",
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlaceholderInvariant {
name: &'static str,
kind: InvariantKind,
}
impl PlaceholderInvariant {
#[must_use]
pub const fn new(name: &'static str, kind: InvariantKind) -> Self {
Self { name, kind }
}
}
impl Invariant for PlaceholderInvariant {
fn name(&self) -> &'static str {
self.name
}
fn kind(&self) -> InvariantKind {
self.kind
}
fn validate(&self) -> GateResult {
GateResult::pass(self.name, None, "placeholder invariant declared")
}
}
pub const RATCHET_ALPHA: f64 = 0.05;
pub const MIN_CALIBRATION_N: u64 = 20;
#[must_use]
pub fn truncate_score(x: f64) -> f64 {
(x * 1e6).floor() / 1e6
}
fn ln_gamma(x: f64) -> f64 {
const COEFFS: [f64; 9] = [
0.999_999_999_999_809_9,
676.520_368_121_885_1,
-1_259.139_216_722_402_8,
771.323_428_777_653_1,
-176.615_029_162_140_6,
12.507_343_278_686_905,
-0.138_571_095_265_720_12,
9.984_369_578_019_572e-6,
1.505_632_735_149_311_6e-7,
];
if x < 0.5 {
return std::f64::consts::PI.ln()
- (std::f64::consts::PI * x).sin().ln()
- ln_gamma(1.0 - x);
}
let x = x - 1.0;
let mut acc = COEFFS[0];
for (i, c) in COEFFS.iter().enumerate().skip(1) {
acc += c / (x + i as f64);
}
let t = x + 7.5;
0.5 * (2.0 * std::f64::consts::PI).ln() + (x + 0.5) * t.ln() - t + acc.ln()
}
fn betacf(a: f64, b: f64, x: f64) -> f64 {
const MAX_ITER: usize = 200;
const EPS: f64 = 3e-16;
const FPMIN: f64 = 1e-300;
let qab = a + b;
let qap = a + 1.0;
let qam = a - 1.0;
let mut c = 1.0;
let mut d = 1.0 - qab * x / qap;
if d.abs() < FPMIN {
d = FPMIN;
}
d = 1.0 / d;
let mut h = d;
for m in 1..=MAX_ITER {
let m = m as f64;
let m2 = 2.0 * m;
let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1.0 + aa * d;
if d.abs() < FPMIN {
d = FPMIN;
}
c = 1.0 + aa / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
h *= d * c;
let aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1.0 + aa * d;
if d.abs() < FPMIN {
d = FPMIN;
}
c = 1.0 + aa / c;
if c.abs() < FPMIN {
c = FPMIN;
}
d = 1.0 / d;
let del = d * c;
h *= del;
if (del - 1.0).abs() < EPS {
break;
}
}
h
}
fn beta_cdf(a: f64, b: f64, x: f64) -> f64 {
if x <= 0.0 {
return 0.0;
}
if x >= 1.0 {
return 1.0;
}
let ln_front = ln_gamma(a + b) - ln_gamma(a) - ln_gamma(b) + a * x.ln() + b * (1.0 - x).ln();
let front = ln_front.exp();
if x < (a + 1.0) / (a + b + 2.0) {
front * betacf(a, b, x) / a
} else {
1.0 - front * betacf(b, a, 1.0 - x) / b
}
}
fn beta_quantile(a: f64, b: f64, p: f64) -> f64 {
let (mut lo, mut hi) = (0.0_f64, 1.0_f64);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if beta_cdf(a, b, mid) < p {
lo = mid;
} else {
hi = mid;
}
}
0.5 * (lo + hi)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CategoryCounts {
pub category: &'static str,
pub passes: u64,
pub failures: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BoundMethod {
Conformal,
DeterministicFallback,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CategoryBound {
pub category: &'static str,
pub n: u64,
pub point: f64,
pub beta_lower: f64,
pub dkw_lower: f64,
pub lower: f64,
pub method: BoundMethod,
}
#[must_use]
pub fn category_bound(counts: CategoryCounts) -> CategoryBound {
let n = counts.passes + counts.failures;
let point = if n == 0 {
0.0
} else {
counts.passes as f64 / n as f64
};
if n < MIN_CALIBRATION_N {
return CategoryBound {
category: counts.category,
n,
point: truncate_score(point),
beta_lower: 0.0,
dkw_lower: 0.0,
lower: truncate_score(point),
method: BoundMethod::DeterministicFallback,
};
}
let beta_lower = beta_quantile(
counts.passes as f64 + 0.5,
counts.failures as f64 + 0.5,
RATCHET_ALPHA,
);
let eps = ((1.0 / RATCHET_ALPHA).ln() / (2.0 * n as f64)).sqrt();
let dkw_lower = (point - eps).max(0.0);
let lower = truncate_score(beta_lower.min(dkw_lower));
CategoryBound {
category: counts.category,
n,
point: truncate_score(point),
beta_lower: truncate_score(beta_lower),
dkw_lower: truncate_score(dkw_lower),
lower,
method: BoundMethod::Conformal,
}
}
#[derive(Clone, Debug)]
pub struct RatchetDecision {
pub allowed: bool,
pub raised: bool,
pub verdicts: Vec<String>,
}
#[must_use]
pub fn ratchet_decide(baseline: &[(&str, f64)], candidate: &[CategoryBound]) -> RatchetDecision {
let mut allowed = true;
let mut raised = false;
let mut verdicts = Vec::new();
for &(name, floor) in baseline {
match candidate.iter().find(|b| b.category == name) {
None => {
allowed = false;
verdicts.push(format!(
"{name}: DROPPED (baseline floor {floor:.6}, no candidate bound) — rejected"
));
}
Some(b) => {
let floor_t = truncate_score(floor);
if b.lower < floor_t {
allowed = false;
verdicts.push(format!(
"{name}: LOWERED {:.6} < floor {floor_t:.6} ({:?}) — rejected",
b.lower, b.method
));
} else {
if b.lower > floor_t {
raised = true;
}
verdicts.push(format!(
"{name}: holds {:.6} >= floor {floor_t:.6} ({:?})",
b.lower, b.method
));
}
}
}
}
for b in candidate {
if !baseline.iter().any(|(name, _)| *name == b.category) {
raised = true;
verdicts.push(format!(
"{}: NEW coverage at {:.6} ({:?}) — admissible, sets the initial floor",
b.category, b.lower, b.method
));
}
}
RatchetDecision {
allowed,
raised,
verdicts,
}
}
#[must_use]
pub fn transparency_card(b: &CategoryBound) -> serde_json::Value {
let (s, f) = (
(b.point * b.n as f64).round() as u64,
b.n - (b.point * b.n as f64).round() as u64,
);
serde_json::json!({
"card": "conformal-ratchet/v1",
"category": b.category,
"equation": "lower = min( BetaQuantile(s+1/2, f+1/2; alpha), p_hat - sqrt(ln(1/alpha)/(2n)) ), truncated to 6dp",
"substituted": {
"s": s, "f": f, "n": b.n, "alpha": RATCHET_ALPHA,
"p_hat": b.point, "beta_lower": b.beta_lower, "dkw_lower": b.dkw_lower,
"lower": b.lower, "method": format!("{:?}", b.method),
},
"intuition": "the release floor is what the data still guarantees after paying for sampling luck: the Jeffreys posterior prices the binomial uncertainty, the Hoeffding band prices distribution-freeness, and the decision takes the stingier of the two",
"validity_assumptions": [
"calibration items are exchangeable (i.i.d.-like) draws from the deployment distribution",
"pass/fail is a Bernoulli outcome per item (no partial credit)",
format!("n >= MIN_CALIBRATION_N ({MIN_CALIBRATION_N}) for the conformal path; below it the deterministic point-estimate fallback is ledgered instead"),
],
"decision_flips_if": [
format!("any per-category lower bound falls below its committed floor (alpha = {RATCHET_ALPHA})"),
"a category present in the baseline disappears from the candidate (dropped coverage)",
],
})
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DeterminismGate;
impl DeterminismGate {
#[must_use]
pub fn validate_bytes(&self, first: &[u8], second: &[u8]) -> GateResult {
if first == second {
GateResult::pass(
"same_input_twice_byte_identical",
None,
"same input produced byte-identical output",
)
} else {
GateResult::fail(
"same_input_twice_byte_identical",
None,
"same input produced divergent output",
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn log_result(check: &str, passed: bool) {
println!(
"{{\"check\":\"{check}\",\"result\":\"{}\"}}",
if passed { "pass" } else { "fail" }
);
}
#[test]
fn tolerances_default_constructs() {
let tolerances = default_tolerances();
let ordered = tolerances.ordered();
let ok = ordered.len() == ParityLevel::ALL.len()
&& tolerances.l0.exact_match
&& tolerances.l1.cosine_min == Some(0.9999)
&& tolerances.l2.cosine_min == Some(0.9999)
&& tolerances.l3.source == ToleranceSource::TodoDeriveFromOracleFloor
&& tolerances.l3.logit_tolerance.is_none()
&& tolerances.l3.argmax_must_match
&& tolerances.l4.source == ToleranceSource::TodoDeriveFromOracleFloor
&& tolerances.l5.source == ToleranceSource::TodoLedgerBudget;
log_result("tolerances_default_constructs", ok);
assert!(ok, "{tolerances:#?}");
}
#[test]
fn parity_levels_span_l0_to_l5() {
let labels: Vec<_> = ParityLevel::ALL
.iter()
.map(|level| (level.index(), level.label()))
.collect();
let ok = labels
== vec![
(0, "L0_preprocess"),
(1, "L1_per_op"),
(2, "L2_per_layer"),
(3, "L3_logits"),
(4, "L4_tokens"),
(5, "L5_end_to_end"),
];
log_result("parity_levels_span_l0_to_l5", ok);
assert!(ok, "{labels:?}");
}
#[test]
fn invariant_trait_object_dispatches() {
let invariants: Vec<Box<dyn Invariant>> = vec![
Box::new(PlaceholderInvariant::new(
"kv_cache_never_exceeds_reference_plus_window",
InvariantKind::KvCacheBound,
)),
Box::new(PlaceholderInvariant::new(
"same_input_twice_byte_identical",
InvariantKind::Determinism,
)),
];
let results: Vec<_> = invariants
.iter()
.map(|invariant| invariant.validate())
.collect();
let ok = results.iter().all(|result| result.passed)
&& invariants[0].kind().label() == "kv_cache_bound"
&& invariants[1].kind().label() == "determinism";
log_result("invariant_trait_object_dispatches", ok);
assert!(ok, "{results:?}");
}
#[test]
fn parity_gate_trait_object_dispatches() {
let gate: Box<dyn ParityGate> = Box::new(PlaceholderParityGate::new(
"l0_preprocess_placeholder",
ParityLevel::L0Preprocess,
));
let result = gate.validate(b"subject", b"oracle");
let ok = result.passed && result.level == Some(ParityLevel::L0Preprocess);
log_result("parity_gate_trait_object_dispatches", ok);
assert!(ok, "{result:?}");
}
#[test]
fn determinism_gate_checks_byte_identity() {
let gate = DeterminismGate;
let same = gate.validate_bytes(b"abc", b"abc");
let different = gate.validate_bytes(b"abc", b"abd");
let ok = same.passed && !different.passed;
log_result("determinism_gate_checks_byte_identity", ok);
assert!(ok, "same={same:?} different={different:?}");
}
#[test]
fn beta_cdf_matches_closed_forms() {
let mut worst = 0.0_f64;
for i in 1..20 {
let x = f64::from(i) / 20.0;
worst = worst.max((beta_cdf(1.0, 1.0, x) - x).abs());
worst = worst.max((beta_cdf(3.0, 1.0, x) - x.powi(3)).abs());
worst = worst.max((beta_cdf(1.0, 4.0, x) - (1.0 - (1.0 - x).powi(4))).abs());
}
worst = worst.max((beta_cdf(2.0, 2.0, 0.5) - 0.5).abs());
let ok = worst < 1e-12;
log_result("beta_cdf_matches_closed_forms", ok);
assert!(ok, "worst closed-form deviation {worst:e}");
}
#[test]
fn beta_quantile_inverts_the_cdf() {
let mut worst = 0.0_f64;
for &(a, b) in &[(0.5, 0.5), (5.5, 0.5), (95.5, 5.5), (20.5, 0.5), (2.0, 8.0)] {
for &p in &[0.01, 0.05, 0.5, 0.95] {
let q = beta_quantile(a, b, p);
worst = worst.max((beta_cdf(a, b, q) - p).abs());
}
}
let uniform = (beta_quantile(1.0, 1.0, 0.05) - 0.05).abs();
let ok = worst < 1e-10 && uniform < 1e-12;
log_result("beta_quantile_inverts_the_cdf", ok);
assert!(ok, "worst inversion error {worst:e}, uniform {uniform:e}");
}
#[test]
fn category_bound_matches_known_posteriors() {
let perfect20 = category_bound(CategoryCounts {
category: "perfect20",
passes: 20,
failures: 0,
});
let mixed100 = category_bound(CategoryCounts {
category: "mixed100",
passes: 95,
failures: 5,
});
let ok = perfect20.method == BoundMethod::Conformal
&& (perfect20.beta_lower - 0.909_523).abs() < 1e-9
&& (mixed100.beta_lower - 0.904_229).abs() < 1e-9
&& (mixed100.dkw_lower - 0.827_612).abs() < 1e-9
&& (mixed100.lower - mixed100.dkw_lower).abs() < 1e-12
&& perfect20.lower <= perfect20.beta_lower;
log_result("category_bound_matches_known_posteriors", ok);
assert!(ok, "perfect20={perfect20:?} mixed100={mixed100:?}");
}
#[test]
fn min_calibration_n_is_the_computed_threshold() {
let at17 = beta_quantile(17.5, 0.5, RATCHET_ALPHA);
let at18 = beta_quantile(18.5, 0.5, RATCHET_ALPHA);
let ok = at17 < 0.9 && at18 >= 0.9 && MIN_CALIBRATION_N >= 18;
log_result("min_calibration_n_is_the_computed_threshold", ok);
assert!(ok, "at17={at17} at18={at18} MIN={MIN_CALIBRATION_N}");
}
#[test]
fn small_corpus_takes_the_deterministic_fallback() {
let b = category_bound(CategoryCounts {
category: "tiny",
passes: 10,
failures: 0,
});
let decision = ratchet_decide(&[("tiny", 0.95)], &[b]);
let ok = b.method == BoundMethod::DeterministicFallback
&& (b.lower - 1.0).abs() < 1e-12
&& decision.allowed;
log_result("small_corpus_takes_the_deterministic_fallback", ok);
assert!(ok, "bound={b:?} decision={decision:?}");
}
#[test]
fn per_category_regression_blocks_even_when_aggregate_improves() {
let a = category_bound(CategoryCounts {
category: "a",
passes: 100,
failures: 0,
});
let b = category_bound(CategoryCounts {
category: "b",
passes: 75,
failures: 25,
});
let baseline = [("a", 0.60), ("b", 0.80)];
let decision = ratchet_decide(&baseline, &[a, b]);
let dropped = ratchet_decide(&baseline, &[a]);
let holds = ratchet_decide(&[("a", 0.60), ("b", b.lower)], &[a, b]);
let ok = !decision.allowed && !dropped.allowed && holds.allowed && holds.raised;
log_result(
"per_category_regression_blocks_even_when_aggregate_improves",
ok,
);
assert!(
ok,
"decision={decision:?}\ndropped={dropped:?}\nholds={holds:?}"
);
}
#[test]
fn transparency_card_is_complete() {
let b = category_bound(CategoryCounts {
category: "parity",
passes: 95,
failures: 5,
});
let card = transparency_card(&b);
let ok = card["card"] == "conformal-ratchet/v1"
&& card["equation"]
.as_str()
.is_some_and(|e| e.contains("BetaQuantile"))
&& card["substituted"]["n"] == 100
&& card["substituted"]["s"] == 95
&& card["intuition"].as_str().is_some_and(|s| !s.is_empty())
&& card["validity_assumptions"]
.as_array()
.is_some_and(|a| a.len() == 3)
&& card["decision_flips_if"]
.as_array()
.is_some_and(|a| a.len() == 2);
println!(
"{{\"check\":\"transparency_card_is_complete\",\"result\":\"{}\",\"card\":{card}}}",
if ok { "pass" } else { "fail" }
);
assert!(ok, "{card}");
}
}