Given aggregate canary metrics by slice, return a sorted list of
failing gates. Lower is better for WER, latency, cost, and unsafe rate;
higher is better for task success and citation support.
Hidden answer: invariant, tests, and Python solution
Invariant: every slice is judged against its own configured budgets,
and severity is normalized so different metric units can be sorted
together, including zero-budget safety gates such as unsafe-rate
ceilings. Validate gate definitions and metric values before
scoring. Keep missing metrics explicit and finite in reports so
launch tooling does not emit non-JSON severity values. Reject
booleans, NaN, and infinity so malformed telemetry cannot silently
pass a launch gate or distort severity sorting. Test missing
metrics, exactly-on-threshold values, lower-is-better metrics,
higher-is-better metrics, zero thresholds, invalid gates, nonnumeric
metrics, non-finite values, and multiple failures in the same slice.
from math import isfinite
def _finite_number(value, label):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value):
raise ValueError(f"{label} must be a finite number")
return value
def rank_canary_risks(slices, gates):
failures = []
for slice_name, metrics in slices.items():
for metric, gate in gates.items():
direction = gate.get("direction")
if direction not in {"max", "min"}:
raise ValueError(f"unknown direction for {metric}: {direction}")
threshold = _finite_number(gate.get("threshold"), f"threshold for {metric}")
if metric not in metrics:
failures.append((1_000_000.0, slice_name, metric, "missing"))
continue
value = _finite_number(metrics[metric], f"value for {slice_name}/{metric}")
scale = max(abs(threshold), 1.0)
if direction == "max":
over = value - threshold
if over > 0:
severity = over / scale
failures.append((severity, slice_name, metric, value))
else:
under = threshold - value
if under > 0:
severity = under / scale
failures.append((severity, slice_name, metric, value))
failures.sort(reverse=True)
return [
{"slice": s, "metric": m, "value": v, "severity": round(sev, 4)}
for sev, s, m, v in failures
]