Given speech assistant turn records, return the trace IDs where any
stage exceeds its budget.
Hidden answer: invariant and Python solution
Invariant: each reported trace has at least one named stage whose
observed latency is greater than the allowed budget. Missing stages
are ignored, but each record still needs a trace ID and a mapping
of stage latencies. Reject malformed records, negative or
non-finite latencies, and non-positive or non-finite budgets before
making SLO decisions.
import math
def budget_violations(records, budgets_ms):
if not isinstance(budgets_ms, dict):
raise ValueError("budgets_ms must be a mapping")
for name, limit in budgets_ms.items():
if not isinstance(limit, (int, float)) or not math.isfinite(limit) or limit <= 0:
raise ValueError(f"budget for {name} must be a positive finite number")
violations = []
for record in records:
if not isinstance(record, dict):
raise ValueError("each record must be a mapping")
trace_id = record.get("trace_id")
if not trace_id:
raise ValueError("record is missing trace_id")
stages = record.get("stages_ms", {})
if not isinstance(stages, dict):
raise ValueError(f"stages_ms for {trace_id} must be a mapping")
for name, value in stages.items():
if not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
raise ValueError(f"latency for {name} must be a non-negative finite number")
bad = {
name: value
for name, value in stages.items()
if name in budgets_ms and value > budgets_ms[name]
}
if bad:
violations.append({
"trace_id": trace_id,
"violations": bad,
})
return violations