use std::collections::BTreeMap;
use std::path::Path;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use crate::{CodeLoreError, Result};
pub const CALIBRATION_FORMAT_VERSION: u32 = 1;
pub const MIN_LANG_SAMPLE: u64 = 500;
pub const QUANTILE_POINTS: usize = 1001;
const TRIVIALITY_THRESHOLD: f64 = 0.0;
const PLACEHOLDER_VINTAGE_PREFIX: &str = "placeholder-";
const EMBEDDED_WORLD_BYTES: &[u8] = include_bytes!("calibration/world.calib.json");
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepoMetrics {
pub values: std::collections::BTreeMap<String, Vec<f64>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CalibrationArtifact {
pub format_version: u32,
pub corpus_vintage: String,
pub generated_at: String,
pub repos_included: u32,
pub repos_attempted: u32,
pub languages: Vec<LanguageTable>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repo_metrics: Option<RepoMetrics>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageTable {
pub language: String,
pub sample_functions: u64,
pub strata: Vec<Stratum>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Stratum {
pub sloc_min: u64,
pub sloc_max: u64,
pub metrics: Vec<MetricQuantiles>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricQuantiles {
pub metric: String,
pub quantiles: Vec<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CorpusPercentile {
pub p: f64,
pub beyond_corpus: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CorpusManifest {
#[serde(default)]
pub repos: Vec<CorpusRepo>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CorpusRepo {
pub source: String,
pub sha: String,
#[serde(default)]
pub languages: Vec<String>,
}
pub fn load_manifest(path: &Path) -> Result<CorpusManifest> {
let raw = std::fs::read_to_string(path).map_err(|e| {
CodeLoreError::RepoIo(std::io::Error::new(
e.kind(),
format!("read corpus manifest {}: {e}", path.display()),
))
})?;
toml::from_str(&raw).map_err(|e| {
CodeLoreError::Analysis(format!("parse corpus manifest {}: {e}", path.display()))
})
}
impl CalibrationArtifact {
fn from_slice(bytes: &[u8]) -> std::result::Result<Self, String> {
let art: Self = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
art.validate()?;
Ok(art)
}
fn validate(&self) -> std::result::Result<(), String> {
if self.format_version != CALIBRATION_FORMAT_VERSION {
return Err(format!(
"unknown calibration format_version {} (this build supports {CALIBRATION_FORMAT_VERSION})",
self.format_version
));
}
for lang in &self.languages {
for stratum in &lang.strata {
for mq in &stratum.metrics {
if mq.quantiles.len() != QUANTILE_POINTS {
return Err(format!(
"{} metric {:?}: quantile vector length {} (expected {QUANTILE_POINTS})",
lang.language,
mq.metric,
mq.quantiles.len()
));
}
for pair in mq.quantiles.windows(2) {
if pair[1] < pair[0] {
return Err(format!(
"{} metric {:?}: non-monotonic quantiles ({} then {})",
lang.language, mq.metric, pair[0], pair[1]
));
}
}
}
}
}
Ok(())
}
}
pub fn load(path: &Path) -> Result<CalibrationArtifact> {
let bytes = std::fs::read(path).map_err(|e| {
CodeLoreError::RepoIo(std::io::Error::new(
e.kind(),
format!("read calibration {}: {e}", path.display()),
))
})?;
CalibrationArtifact::from_slice(&bytes)
.map_err(|e| CodeLoreError::Analysis(format!("parse calibration {}: {e}", path.display())))
}
#[must_use]
pub fn embedded_world() -> Option<&'static CalibrationArtifact> {
static WORLD: OnceLock<Option<CalibrationArtifact>> = OnceLock::new();
WORLD
.get_or_init(|| {
CalibrationArtifact::from_slice(EMBEDDED_WORLD_BYTES)
.ok()
.filter(|art| !art.corpus_vintage.starts_with(PLACEHOLDER_VINTAGE_PREFIX))
})
.as_ref()
}
pub fn load_active_artifact(
opts: &crate::Options,
) -> Result<Option<std::borrow::Cow<'static, CalibrationArtifact>>> {
use std::borrow::Cow;
if let Some(path) = &opts.calibration {
return Ok(Some(Cow::Owned(load(path)?)));
}
Ok(embedded_world().map(Cow::Borrowed))
}
pub fn active_vintage(opts: &crate::Options) -> Result<Option<String>> {
Ok(load_active_artifact(opts)?.map(|art| art.corpus_vintage.clone()))
}
fn metric_breakpoints<'a>(
art: &'a CalibrationArtifact,
language: &str,
metric: &str,
) -> Option<&'a [f64]> {
let lang = art.languages.iter().find(|l| l.language == language)?;
if lang.sample_functions < MIN_LANG_SAMPLE {
return None;
}
lang.strata
.iter()
.flat_map(|s| &s.metrics)
.find(|m| m.metric == metric)
.map(|m| m.quantiles.as_slice())
}
#[must_use]
pub fn percentile(
art: &CalibrationArtifact,
language: &str,
metric: &str,
value: f64,
) -> Option<CorpusPercentile> {
Some(interpolate_percentile(
metric_breakpoints(art, language, metric)?,
value,
))
}
#[must_use]
pub fn conditional_tail_percentile(
art: &CalibrationArtifact,
language: &str,
metric: &str,
value: f64,
) -> Option<f64> {
let quantiles = metric_breakpoints(art, language, metric)?;
let p0 = trivial_share(quantiles);
let span = 1.0 - p0;
if span <= 0.0 {
return None; }
if value <= TRIVIALITY_THRESHOLD {
return Some(0.0); }
let cp = interpolate_percentile(quantiles, value).p;
Some(((cp - p0) / span).clamp(0.0, 1.0))
}
fn trivial_share(q: &[f64]) -> f64 {
let trivial_count = q.partition_point(|&b| b <= TRIVIALITY_THRESHOLD);
if trivial_count == 0 {
return 0.0; }
count_to_f64(trivial_count - 1) / count_to_f64(q.len() - 1)
}
#[must_use]
pub fn language_sample_functions(art: &CalibrationArtifact, language: &str) -> Option<u64> {
art.languages
.iter()
.find(|l| l.language == language)
.filter(|l| l.sample_functions >= MIN_LANG_SAMPLE)
.map(|l| l.sample_functions)
}
#[allow(clippy::cast_precision_loss)]
fn count_to_f64(n: usize) -> f64 {
n as f64
}
fn interpolate_percentile(q: &[f64], value: f64) -> CorpusPercentile {
let last = q.len() - 1;
let denom = count_to_f64(last);
if value <= q[0] {
return CorpusPercentile {
p: 0.0,
beyond_corpus: false,
};
}
if value >= q[last] {
return CorpusPercentile {
p: 1.0,
beyond_corpus: value > q[last],
};
}
let hi = q.partition_point(|&b| b <= value);
let lo = hi - 1;
let (blo, bhi) = (q[lo], q[hi]);
let frac = if bhi > blo {
(value - blo) / (bhi - blo)
} else {
0.0
};
let p = (count_to_f64(lo) + frac) / denom;
CorpusPercentile {
p,
beyond_corpus: false,
}
}
#[must_use]
#[allow(clippy::cast_precision_loss)]
pub fn raw_percentile(sorted: &[f64], value: f64) -> Option<f64> {
let n = sorted.len();
if n == 0 {
return None;
}
let count_less = sorted.partition_point(|&x| x < value);
let count_less_or_equal = sorted.partition_point(|&x| x <= value);
let count_equal = count_less_or_equal - count_less;
Some((count_less as f64 + 0.5 * count_equal as f64) / n as f64)
}
pub fn attach_repo_metrics(artifact: &mut CalibrationArtifact, mut pools: RepoMetrics) {
if pools.values.is_empty() {
artifact.repo_metrics = None;
return;
}
for vec in pools.values.values_mut() {
vec.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
}
artifact.repo_metrics = Some(pools);
}
#[derive(Debug, Clone, Default)]
pub struct LangObservations {
per_lang: BTreeMap<String, BTreeMap<String, Vec<f64>>>,
}
impl LangObservations {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn observe(&mut self, language: &str, metric: &str, value: f64) {
self.per_lang
.entry(language.to_string())
.or_default()
.entry(metric.to_string())
.or_default()
.push(value);
}
fn sample_functions(metrics: &BTreeMap<String, Vec<f64>>) -> u64 {
metrics.values().map(|v| v.len() as u64).max().unwrap_or(0)
}
}
#[must_use]
pub fn build_from_observations(
vintage: &str,
generated_at: &str,
obs: &LangObservations,
) -> CalibrationArtifact {
let languages = obs
.per_lang
.iter()
.map(|(language, metrics)| {
let sample_functions = LangObservations::sample_functions(metrics);
let metric_quantiles = metrics
.iter()
.map(|(metric, values)| {
let mut sorted = values.clone();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
MetricQuantiles {
metric: metric.clone(),
quantiles: quantile_breakpoints(&sorted),
}
})
.collect();
LanguageTable {
language: language.clone(),
sample_functions,
strata: vec![Stratum {
sloc_min: 0,
sloc_max: u64::MAX,
metrics: metric_quantiles,
}],
}
})
.collect();
CalibrationArtifact {
format_version: CALIBRATION_FORMAT_VERSION,
corpus_vintage: vintage.to_string(),
generated_at: generated_at.to_string(),
repos_included: 0,
repos_attempted: 0,
languages,
repo_metrics: None,
}
}
fn quantile_breakpoints(sorted: &[f64]) -> Vec<f64> {
let last_idx = QUANTILE_POINTS - 1;
if sorted.is_empty() {
return vec![0.0; QUANTILE_POINTS];
}
let n = sorted.len();
if n == 1 {
return vec![sorted[0]; QUANTILE_POINTS];
}
(0..QUANTILE_POINTS)
.map(|i| {
let q = count_to_f64(i) / count_to_f64(last_idx);
let rank = q * count_to_f64(n - 1);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let (lo, hi) = (rank.floor() as usize, rank.ceil() as usize);
if lo == hi {
sorted[lo]
} else {
let frac = rank - count_to_f64(lo);
sorted[lo] + (sorted[hi] - sorted[lo]) * frac
}
})
.collect()
}
#[must_use]
pub fn merge(base: CalibrationArtifact, additional: CalibrationArtifact) -> CalibrationArtifact {
let mut add_by_lang: BTreeMap<String, LanguageTable> = additional
.languages
.into_iter()
.map(|l| (l.language.clone(), l))
.collect();
let mut merged_languages = Vec::new();
for base_lang in base.languages {
match add_by_lang.remove(&base_lang.language) {
Some(add_lang) => merged_languages.push(blend_language(base_lang, add_lang)),
None => merged_languages.push(base_lang),
}
}
merged_languages.extend(add_by_lang.into_values());
let repo_metrics = merge_repo_metrics(base.repo_metrics, additional.repo_metrics);
CalibrationArtifact {
format_version: CALIBRATION_FORMAT_VERSION,
corpus_vintage: base.corpus_vintage,
generated_at: base.generated_at,
repos_included: base
.repos_included
.saturating_add(additional.repos_included),
repos_attempted: base
.repos_attempted
.saturating_add(additional.repos_attempted),
languages: merged_languages,
repo_metrics,
}
}
fn merge_repo_metrics(
base: Option<RepoMetrics>,
additional: Option<RepoMetrics>,
) -> Option<RepoMetrics> {
match (base, additional) {
(None, None) => None,
(Some(b), None) => Some(b),
(None, Some(a)) => Some(a),
(Some(mut b), Some(a)) => {
for (metric, mut add_vals) in a.values {
b.values
.entry(metric)
.and_modify(|base_vals| {
base_vals.append(&mut add_vals);
base_vals
.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
})
.or_insert_with(|| {
add_vals
.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
add_vals
});
}
Some(b)
}
}
}
fn blend_language(base: LanguageTable, add: LanguageTable) -> LanguageTable {
let wb = base.sample_functions;
let wa = add.sample_functions;
let base_metrics = single_stratum_metrics(base.strata);
let add_metrics = single_stratum_metrics(add.strata);
let mut add_by_metric: BTreeMap<String, Vec<f64>> = add_metrics
.into_iter()
.map(|m| (m.metric, m.quantiles))
.collect();
let mut blended = Vec::new();
for m in base_metrics {
match add_by_metric.remove(&m.metric) {
Some(add_q) => blended.push(MetricQuantiles {
metric: m.metric,
quantiles: blend_quantiles(&m.quantiles, wb, &add_q, wa),
}),
None => blended.push(m),
}
}
for (metric, quantiles) in add_by_metric {
blended.push(MetricQuantiles { metric, quantiles });
}
LanguageTable {
language: base.language,
sample_functions: wb.saturating_add(wa),
strata: vec![Stratum {
sloc_min: 0,
sloc_max: u64::MAX,
metrics: blended,
}],
}
}
fn single_stratum_metrics(strata: Vec<Stratum>) -> Vec<MetricQuantiles> {
strata.into_iter().flat_map(|s| s.metrics).collect()
}
fn blend_quantiles(base: &[f64], wb: u64, add: &[f64], wa: u64) -> Vec<f64> {
let total = wb.saturating_add(wa);
if total == 0 || base.len() != add.len() {
return base.to_vec();
}
let (wb, wa, total) = (weight_to_f64(wb), weight_to_f64(wa), weight_to_f64(total));
base.iter()
.zip(add.iter())
.map(|(b, a)| (b * wb + a * wa) / total)
.collect()
}
#[allow(clippy::cast_precision_loss)]
fn weight_to_f64(n: u64) -> f64 {
n as f64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_world_is_present_and_real() {
let art =
embedded_world().expect("the embedded world corpus must resolve to Some once built");
assert!(
!art.corpus_vintage.starts_with(PLACEHOLDER_VINTAGE_PREFIX),
"the embedded corpus vintage must be a real build, not a placeholder"
);
}
#[test]
fn embedded_world_bytes_parse_and_validate() {
let art = CalibrationArtifact::from_slice(EMBEDDED_WORLD_BYTES)
.expect("embedded world corpus must be a valid artifact");
assert!(!art.corpus_vintage.starts_with(PLACEHOLDER_VINTAGE_PREFIX));
assert_eq!(art.format_version, CALIBRATION_FORMAT_VERSION);
for lang in &art.languages {
assert!(
lang.sample_functions >= MIN_LANG_SAMPLE,
"embedded language {:?} pooled {} functions, below the {MIN_LANG_SAMPLE} floor",
lang.language,
lang.sample_functions,
);
}
}
#[test]
fn manifest_parses_repos_and_pins() {
let toml = r#"
[[repos]]
source = "https://github.com/example/one"
sha = "abc123"
languages = ["rust", "python"]
[[repos]]
source = "/local/path/to/two"
sha = "def456"
"#;
let manifest: CorpusManifest = toml::from_str(toml).expect("parse manifest");
assert_eq!(manifest.repos.len(), 2);
assert_eq!(manifest.repos[0].source, "https://github.com/example/one");
assert_eq!(manifest.repos[0].sha, "abc123");
assert_eq!(manifest.repos[0].languages, ["rust", "python"]);
assert_eq!(manifest.repos[1].source, "/local/path/to/two");
assert!(manifest.repos[1].languages.is_empty());
}
#[test]
fn manifest_without_repos_is_empty() {
let manifest: CorpusManifest = toml::from_str("").expect("parse empty manifest");
assert!(manifest.repos.is_empty());
}
#[test]
fn from_slice_accepts_a_real_vintage() {
let obs = LangObservations::new();
let art = build_from_observations("world-2026-07", "2026-07-01T00:00:00Z", &obs);
assert!(!art.corpus_vintage.starts_with(PLACEHOLDER_VINTAGE_PREFIX));
let bytes = serde_json::to_vec(&art).expect("serialize");
let back = CalibrationArtifact::from_slice(&bytes).expect("valid real-vintage artifact");
assert_eq!(back.corpus_vintage, "world-2026-07");
}
fn cognitive_artifact(
language: &str,
sample_functions: u64,
q: Vec<f64>,
) -> CalibrationArtifact {
CalibrationArtifact {
format_version: CALIBRATION_FORMAT_VERSION,
corpus_vintage: "test-fixture".into(),
generated_at: "2026-01-01T00:00:00Z".into(),
repos_included: 1,
repos_attempted: 1,
languages: vec![LanguageTable {
language: language.into(),
sample_functions,
strata: vec![Stratum {
sloc_min: 0,
sloc_max: u64::MAX,
metrics: vec![MetricQuantiles {
metric: "cognitive".into(),
quantiles: q,
}],
}],
}],
repo_metrics: None,
}
}
fn zeros_prefix_breakpoints(zeros: usize) -> Vec<f64> {
(0..QUANTILE_POINTS)
.map(|i| {
if i <= zeros {
0.0
} else {
count_to_f64(i - zeros)
}
})
.collect()
}
#[test]
fn trivial_share_matches_controlled_zeros_prefix() {
assert!((trivial_share(&zeros_prefix_breakpoints(300)) - 0.30).abs() < 1e-12);
assert!((trivial_share(&zeros_prefix_breakpoints(500)) - 0.50).abs() < 1e-12);
let all_positive: Vec<f64> = (0..QUANTILE_POINTS).map(|i| count_to_f64(i + 1)).collect();
assert!(trivial_share(&all_positive).abs() < 1e-12);
assert!((trivial_share(&vec![0.0; QUANTILE_POINTS]) - 1.0).abs() < 1e-12);
}
#[test]
fn conditional_tail_percentile_spreads_the_tail() {
let art = cognitive_artifact("rust", 1000, zeros_prefix_breakpoints(300));
let ct = |v: f64| conditional_tail_percentile(&art, "rust", "cognitive", v).unwrap();
assert!((ct(350.0) - 0.50).abs() < 1e-9, "mid-tail value halves");
assert!(ct(0.5) < 1e-3, "just above the plateau ⇒ ~0");
assert!((ct(700.0) - 1.0).abs() < 1e-12, "corpus max ⇒ 1");
assert!((ct(10_000.0) - 1.0).abs() < 1e-12);
}
#[test]
fn conditional_tail_percentile_edges_and_omissions() {
let art = cognitive_artifact("rust", 1000, zeros_prefix_breakpoints(300));
assert_eq!(
conditional_tail_percentile(&art, "rust", "cognitive", 0.0),
Some(0.0)
);
let all_trivial = cognitive_artifact("rust", 1000, vec![0.0; QUANTILE_POINTS]);
assert_eq!(
conditional_tail_percentile(&all_trivial, "rust", "cognitive", 5.0),
None
);
let thin = cognitive_artifact("rust", MIN_LANG_SAMPLE - 1, zeros_prefix_breakpoints(300));
assert_eq!(
conditional_tail_percentile(&thin, "rust", "cognitive", 350.0),
None
);
assert_eq!(
conditional_tail_percentile(&art, "cobol", "cognitive", 350.0),
None
);
assert_eq!(
conditional_tail_percentile(&art, "rust", "cyclomatic", 350.0),
None
);
}
#[test]
fn conditional_tail_percentile_is_identity_without_trivial_mass() {
let q: Vec<f64> = (0..QUANTILE_POINTS).map(|i| count_to_f64(i + 1)).collect();
let art = cognitive_artifact("rust", 1000, q);
let raw = percentile(&art, "rust", "cognitive", 501.0).unwrap().p;
let tail = conditional_tail_percentile(&art, "rust", "cognitive", 501.0).unwrap();
assert!((raw - 0.5).abs() < 1e-12);
assert!((tail - raw).abs() < 1e-12);
}
}