use serde::{Deserialize, Serialize};
use super::drain::BandInput;
use super::receipt::{ReceiptInput, TokenCountingMethod, Workload};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RatioMethod {
PairedPercentileBootstrap,
ReplicateTLower,
}
impl RatioMethod {
#[must_use]
pub fn wire_token(self) -> &'static str {
match self {
Self::PairedPercentileBootstrap => "paired_percentile_bootstrap",
Self::ReplicateTLower => "replicate_t_lower",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Ratio {
pub point: f64,
pub lcb95: Option<f64>,
pub method: RatioMethod,
pub n: usize,
}
impl Ratio {
#[must_use]
pub fn reporting_only(point: f64, method: RatioMethod, n: usize) -> Self {
Self {
point,
lcb95: None,
method,
n,
}
}
#[must_use]
pub fn passes(&self, delta: f64) -> bool {
self.lcb95.is_some_and(|l| l >= 1.0 - delta)
}
}
pub type RatioBound = Ratio;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BandRatios {
pub agg: Ratio,
pub dec: Option<Ratio>,
pub prefill: Option<Ratio>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JoinKey {
pub host: String,
pub workload: Workload,
pub band: u32,
pub model: String,
pub quant: String,
pub tokenization: TokenCountingMethod,
pub window_ms: u64,
pub replicates: u32,
pub interleaved: bool,
pub n_ctx_slot: Option<u32>,
pub kv_type: Option<String>,
pub fa: Option<bool>,
pub n_batch: Option<u32>,
pub n_predict: u32,
}
impl JoinKey {
#[must_use]
pub fn of(receipt: &ReceiptInput, band: &BandInput) -> Self {
Self {
host: receipt.provenance.host.clone(),
workload: receipt.workload,
band: band.concurrency,
model: receipt.provenance.model.clone(),
quant: receipt.provenance.quantization.clone(),
tokenization: receipt.tokenization.method(),
window_ms: receipt.protocol.window_ms,
replicates: receipt.protocol.replicates,
interleaved: receipt.protocol.interleaved,
n_ctx_slot: band.lane.n_ctx_slot,
kv_type: band.lane.kv_type.clone(),
fa: band.lane.fa,
n_batch: band.lane.n_batch,
n_predict: receipt.protocol.n_predict,
}
}
pub fn refuse_cripple(&self) -> Result<(), String> {
if self.n_batch == Some(1) {
return Err(format!(
"PP-22 join key at c={}: n_batch=1 — §5.3 refuses a `-b 1` comparator as a \
cripple; that configuration manufactured a 2.39x overstatement once \
(llama_pin.toml:129-165) and it is not a lane serving the band",
self.band
));
}
Ok(())
}
pub fn refuse_mismatch(&self, other: &Self) -> Result<(), String> {
self.refuse_cripple()?;
other.refuse_cripple()?;
let mut differing = Vec::new();
let mut note = |name: &str, a: String, b: String| {
if a != b {
differing.push(format!("{name}: {a} != {b}"));
}
};
note("host", self.host.clone(), other.host.clone());
note(
"workload",
self.workload.wire_token().to_string(),
other.workload.wire_token().to_string(),
);
note("band", self.band.to_string(), other.band.to_string());
note("model", self.model.clone(), other.model.clone());
note("quant", self.quant.clone(), other.quant.clone());
note(
"tokenization",
self.tokenization.wire_token().to_string(),
other.tokenization.wire_token().to_string(),
);
note(
"window_ms",
self.window_ms.to_string(),
other.window_ms.to_string(),
);
note(
"replicates",
self.replicates.to_string(),
other.replicates.to_string(),
);
note(
"interleaved",
self.interleaved.to_string(),
other.interleaved.to_string(),
);
note(
"n_ctx_slot",
opt(self.n_ctx_slot.as_ref()),
opt(other.n_ctx_slot.as_ref()),
);
note(
"kv_type",
opt(self.kv_type.as_ref()),
opt(other.kv_type.as_ref()),
);
note("fa", opt(self.fa.as_ref()), opt(other.fa.as_ref()));
note(
"n_batch",
opt(self.n_batch.as_ref()),
opt(other.n_batch.as_ref()),
);
note(
"n_predict",
self.n_predict.to_string(),
other.n_predict.to_string(),
);
if differing.is_empty() {
return Ok(());
}
Err(format!(
"PP-22 join refused: {} — two bands that differ on any join field are not two \
measurements of the same thing, and their quotient is not a ratio",
differing.join("; ")
))
}
}
fn opt<T: std::fmt::Display>(v: Option<&T>) -> String {
v.map_or_else(|| "null".to_string(), std::string::ToString::to_string)
}
#[cfg(test)]
mod tests {
#![allow(non_snake_case)]
use super::*;
fn key(band: u32) -> JoinKey {
JoinKey {
host: "lambda".to_string(),
workload: Workload::W1,
band,
model: "qwen2.5-coder-7b-apache-q4k-v1".to_string(),
quant: "Q4_K_M".to_string(),
tokenization: TokenCountingMethod::ClientTokenizer,
window_ms: 60_000,
replicates: 5,
interleaved: true,
n_ctx_slot: Some(1024),
kv_type: Some("f16".to_string()),
fa: Some(true),
n_batch: Some(2048),
n_predict: 128,
}
}
#[test]
fn join_ok__matching_keys_join() {
assert!(key(4).refuse_mismatch(&key(4)).is_ok());
}
#[test]
fn join_mismatch__c4_against_c16_is_refused() {
let err = key(4).refuse_mismatch(&key(16)).expect_err("c differs");
assert!(err.contains("band: 4 != 16"), "{err}");
assert!(err.contains("PP-22"), "{err}");
}
#[test]
fn joining_a_30s_window_with_a_60s_window_is_refused() {
let short = JoinKey {
window_ms: 30_000,
..key(4)
};
let err = short.refuse_mismatch(&key(4)).expect_err("window differs");
assert!(err.contains("window_ms: 30000 != 60000"), "{err}");
}
#[test]
fn a_b1_comparator_is_refused_as_a_cripple() {
let crippled = JoinKey {
n_batch: Some(1),
..key(4)
};
let err = key(4)
.refuse_mismatch(&crippled)
.expect_err("-b 1 comparator");
assert!(err.contains("cripple"), "{err}");
assert!(crippled.refuse_mismatch(&crippled).is_err());
}
#[test]
fn a_mismatch_names_every_differing_field() {
let other = JoinKey {
host: "gx10".to_string(),
window_ms: 30_000,
interleaved: false,
kv_type: Some("q8_0".to_string()),
fa: None,
..key(16)
};
let err = key(4).refuse_mismatch(&other).expect_err("many differ");
for field in ["host", "band", "window_ms", "interleaved", "kv_type", "fa"] {
assert!(err.contains(field), "{field} missing from: {err}");
}
}
#[test]
fn an_absent_field_does_not_match_a_present_one() {
let unreported = JoinKey {
n_ctx_slot: None,
..key(4)
};
let err = key(4)
.refuse_mismatch(&unreported)
.expect_err("null vs 1024");
assert!(err.contains("n_ctx_slot: 1024 != null"), "{err}");
}
#[test]
fn a_ratio_without_a_bound_never_passes() {
let reporting = Ratio::reporting_only(1.42, RatioMethod::ReplicateTLower, 3);
assert!(!reporting.passes(0.0));
assert!(
!reporting.passes(0.5),
"no bound is not a pass at any delta"
);
let bounded = Ratio {
point: 1.02,
lcb95: Some(1.005),
method: RatioMethod::ReplicateTLower,
n: 5,
};
assert!(bounded.passes(0.0), "lcb95 >= 1 - 0 passes at parity");
let below = Ratio {
lcb95: Some(0.98),
..bounded.clone()
};
assert!(!below.passes(0.0));
assert!(below.passes(0.05), "delta 0.05 admits an lcb95 of 0.98");
}
#[test]
fn ratio_method_wire_tokens_are_the_schema_spelling() {
assert_eq!(
RatioMethod::PairedPercentileBootstrap.wire_token(),
"paired_percentile_bootstrap"
);
assert_eq!(
RatioMethod::ReplicateTLower.wire_token(),
"replicate_t_lower"
);
let j = serde_json::to_string(&RatioMethod::ReplicateTLower).expect("serialises");
assert_eq!(j, "\"replicate_t_lower\"");
}
}