"""Exact count-compressed controls for demerit and fixed-percentile error.""" import argparse from datetime import datetime, timezone from fractions import Fraction import hashlib import json from pathlib import Path import platform from numeric import sqrt_rational def exact(value): if isinstance(value, bool) or not isinstance(value, (int, Fraction)): raise TypeError("Use int or Fraction, not floating point or booleans") return Fraction(value) def histogram(bins): """Combine equal values without expanding positive integer multiplicities.""" counts = {} for value, count in bins: value = exact(value) if value < 0: raise ValueError("Latency must be nonnegative") if isinstance(count, bool) or not isinstance(count, int): raise TypeError("Multiplicity must be an integer") if count <= 0: raise ValueError("Multiplicity must be positive") counts[value] = counts.get(value, 0) + count if not counts: raise ValueError("Histogram must be nonempty") return tuple(sorted(counts.items())) def quantile(bins, probability): """Inverse ECDF for 0 < p <= 1: first value whose cumulative mass reaches p.""" bins = histogram(bins) p = exact(probability) if not 0 < p <= 1: raise ValueError("Probability must satisfy 0 < p <= 1") target = p * sum(count for _, count in bins) cumulative = 0 for value, count in bins: cumulative += count if cumulative >= target: return value raise RuntimeError("Quantile mass not covered") def intervals(reference, modeled): """Merge distinct-value CDF endpoints using exact probability mass.""" left, right = histogram(reference), histogram(modeled) n, m = sum(c for _, c in left), sum(c for _, c in right) i = j = 0 lc, rc = left[0][1], right[0][1] previous = Fraction(0) while i < len(left) and j < len(right): le, re = Fraction(lc, n), Fraction(rc, m) end = min(le, re) yield end - previous, left[i][0] - right[j][0] previous = end if le == end: i += 1 if i < len(left): lc += left[i][1] if re == end: j += 1 if j < len(right): rc += right[j][1] if previous != 1: raise RuntimeError("Probability mass not fully covered") def distance_squared(reference, modeled): return sum((mass * error ** 2 for mass, error in intervals(reference, modeled)), Fraction(0)) def error_mass(reference, modeled, threshold): """Probability mass of quantile positions with absolute error >= threshold.""" threshold = exact(threshold) if threshold <= 0: raise ValueError("Error threshold must be positive") return sum((mass for mass, error in intervals(reference, modeled) if abs(error) >= threshold), Fraction(0)) def exceedance(bins, threshold): bins, threshold = histogram(bins), exact(threshold) return Fraction(sum(c for value, c in bins if value > threshold), sum(c for _, c in bins)) def summarize(n): if isinstance(n, bool) or not isinstance(n, int): raise TypeError("Count must be an integer") if n < 100 or n % 100: raise ValueError("Count must be a positive multiple of 100") fast = 99 * n // 100 reference = ((1, fast), (101, n - fast)) modeled = ((1, fast - 1), (101, n - fast + 1)) squared = distance_squared(reference, modeled) mean = sum(value * count for value, count in reference) / Fraction(n) return { "count_per_sample": n, "reference_histogram": [{"latency_ms": v, "count": c} for v, c in reference], "modeled_histogram": [{"latency_ms": v, "count": c} for v, c in modeled], "reference_mean_ms_exact": str(mean), "distribution_mse_ms2_exact": str(squared), "distribution_rms_ms": sqrt_rational(squared), "relative_demerit_percent": sqrt_rational(10000 * squared / mean ** 2), "reference_p99_ms_exact": str(quantile(reference, Fraction(99, 100))), "modeled_p99_ms_exact": str(quantile(modeled, Fraction(99, 100))), "reference_exceeds_50ms_fraction_exact": str(exceedance(reference, 50)), "modeled_exceeds_50ms_fraction_exact": str(exceedance(modeled, 50)), "quantile_mass_error_at_least_100ms_exact": str(error_mass(reference, modeled, 100)), "merged_intervals": len(list(intervals(reference, modeled))), } def payload(): return { "schema_version": 1, "kind": "constructed-exact-calculation", "quantile_convention": "inverse empirical CDF (type 1); 0 < p <= 1", "percentile_probability_exact": "99/100", "latency_unit": "ms", "representation": "exact values with integer multiplicities, not latency buckets", "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "numeric_sha256": hashlib.sha256(Path(__file__).with_name("numeric.py").read_bytes()).hexdigest(), "limits": [ "Constructed finite populations, not measured requests or independent samples.", "The fixed percentile lies at a jump; this is not a claim about smooth latency densities.", "No confidence intervals, hardware accuracy or historical simulator results are inferred.", "Error mass refers to quantile positions, not to paired request identities.", ], "cases": [summarize(n) for n in (100, 10000, 1000000, 10000000000)], } def main(): parser = argparse.ArgumentParser() actions = parser.add_mutually_exclusive_group(required=True) actions.add_argument("--write", type=Path) actions.add_argument("--check", type=Path) args = parser.parse_args() result = payload() if args.check: existing = json.loads(args.check.read_text()) expected = {k: v for k, v in existing.items() if k not in ("generated_at", "runtime")} if result != expected: raise SystemExit("Tail replay mismatch") print("PASS: four count-compressed cases and source hash") else: result["generated_at"] = datetime.now(timezone.utc).isoformat() result["runtime"] = {"python": platform.python_version()} args.write.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") if __name__ == "__main__": main()