"""Exact labeled-mixture comparisons; not a workload intervention or simulator.""" import argparse from collections.abc import Mapping from datetime import datetime, timezone from fractions import Fraction import hashlib import json import math from pathlib import Path import platform from numeric import sqrt_rational from tail import distance_squared, exact, histogram def classes(groups): if not isinstance(groups, Mapping): raise TypeError("Classes must be a mapping from labels to histograms") if not groups: raise ValueError("At least one observed class is required") if any(not isinstance(k, str) or not k.strip() for k in groups): raise ValueError("Class labels must be nonempty strings") return {k: histogram(groups[k]) for k in sorted(groups)} def weights_for(groups, weights): if not isinstance(weights, Mapping): raise TypeError("Weights must be an explicit mapping") if set(groups) != set(weights): raise ValueError("Weights must cover exactly the observed classes") result = {k: exact(weights[k]) for k in groups} if any(w <= 0 for w in result.values()) or sum(result.values()) != 1: raise ValueError("All class weights must be positive and sum exactly to one") return result def mixture(groups, weights): """Represent exact class-weighted masses with compact integer multiplicities.""" groups = classes(groups) weights = weights_for(groups, weights) masses = {} for label, bins in groups.items(): count = sum(c for _, c in bins) for value, multiplicity in bins: mass = weights[label] * Fraction(multiplicity, count) masses[value] = masses.get(value, Fraction(0)) + mass denominator = math.lcm(*(mass.denominator for mass in masses.values())) return histogram((value, int(mass * denominator)) for value, mass in masses.items()) def pooled(groups): return histogram(pair for bins in groups.values() for pair in bins) def compare(reference, modeled, weights): reference, modeled = classes(reference), classes(modeled) if set(reference) != set(modeled): raise ValueError("Every comparison class must be observed on both sides") weights = weights_for(reference, weights) class_errors = {k: distance_squared(reference[k], modeled[k]) for k in reference} observed = distance_squared(pooled(reference), pooled(modeled)) standardized = distance_squared(mixture(reference, weights), mixture(modeled, weights)) conditional = sum((weights[k] * class_errors[k] for k in reference), Fraction(0)) return observed, standardized, conditional, class_errors def summarize(label, reference, modeled, weights): reference, modeled = classes(reference), classes(modeled) observed, standardized, conditional, errors = compare(reference, modeled, weights) totals = {side: sum(c for bins in groups.values() for _, c in bins) for side, groups in (("reference", reference), ("modeled", modeled))} rows = [] for k in reference: row = {"label": k, "common_weight_exact": str(Fraction(weights[k])), "distribution_mse_ms2_exact": str(errors[k]), "distribution_rms_ms": sqrt_rational(errors[k])} for side, groups in (("reference", reference), ("modeled", modeled)): count = sum(c for _, c in groups[k]) row[side + "_count"] = count row[side + "_observed_weight_exact"] = str(Fraction(count, totals[side])) row[side + "_histogram"] = [ {"latency_ms_exact": str(v), "count": c} for v, c in groups[k]] rows.append(row) return { "label": label, "classes": rows, "observed_pool_mse_ms2_exact": str(observed), "observed_pool_rms_ms": sqrt_rational(observed), "common_weight_pool_mse_ms2_exact": str(standardized), "common_weight_pool_rms_ms": sqrt_rational(standardized), "weighted_conditional_mse_ms2_exact": str(conditional), "weighted_conditional_rms_ms": sqrt_rational(conditional), } def payload(): equal = {"read": Fraction(1, 2), "write": Fraction(1, 2)} reference = {"read": [(1, 1)], "write": [(9, 1)]} skewed = {"read": [(1, 3)], "write": [(9, 1)]} cases = [ summarize("Matching classes and proportions", reference, reference, equal), summarize("Reversed class predictions", reference, {"read": [(9, 1)], "write": [(1, 1)]}, equal), summarize("Only class proportions change", skewed, reference, equal), summarize("Changed proportions hide reversed classes", skewed, {"read": [(9, 1)], "write": [(1, 3)]}, equal), ] return { "schema_version": 1, "kind": "constructed-exact-calculation", "latency_unit": "ms", "quantile_convention": "inverse empirical CDF (type 1)", "common_weights": "explicit equal read/write weights, not estimated population shares", "source_sha256": {name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() for name in ("mixture.py", "tail.py", "numeric.py")}, "limits": [ "Constructed examples; no measured I/O, population inference or device benchmark.", "Read/write labels are illustrative, not a claim about real read/write speeds.", "Common-weight pooling still discards class labels; retain per-class distances.", "Conditional distance compares distributions within a class, not paired requests.", "Reweighting observed conditional distributions does not predict a workload intervention.", "Missing classes and zero-weight omissions are rejected, not inferred or silently dropped.", "Compact reweighting multiplicities are arithmetic devices, not additional observations.", ], "cases": cases, } def main(): parser = argparse.ArgumentParser() action = parser.add_mutually_exclusive_group(required=True) action.add_argument("--write", type=Path) action.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 expected != result: raise SystemExit("Mixture replay mismatch") print("PASS: four labeled-mixture cases and both source hashes") 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()