Given component p95 latencies and a product SLO, return whether the
path has budget left and name the largest contributors.
Hidden answer: invariant, tests, and Python solution
Invariant: the sum of component p95 estimates is a planning
approximation for budget ownership, not a true end-to-end percentile,
a guaranteed upper bound, or a replacement for trace percentiles.
Test exact budget, empty components, one dominant component, and a
negative, non-finite, non-numeric, or missing value rejected by
input validation in real code.
def latency_budget_report(components_ms, slo_ms, top_k=3):
import math
from collections.abc import Mapping
if not isinstance(components_ms, Mapping):
raise ValueError("components_ms must be a mapping of component names to latencies")
if isinstance(slo_ms, bool) or not isinstance(slo_ms, (int, float)) or not math.isfinite(slo_ms) or slo_ms < 0:
raise ValueError("slo_ms must be a finite non-negative number")
if isinstance(top_k, bool) or not isinstance(top_k, int) or top_k < 1:
raise ValueError("top_k must be a positive integer")
for name, value in components_ms.items():
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
raise ValueError(f"{name} latency must be a finite non-negative number")
total = sum(components_ms.values())
contributors = sorted(
components_ms.items(),
key=lambda item: item[1],
reverse=True,
)[:top_k]
return {
"total_ms": total,
"slo_ms": slo_ms,
"within_budget": total <= slo_ms,
"remaining_ms": slo_ms - total,
"top_contributors": contributors,
}