Minor Model Version Upgrades: Evaluation, Canary Rollouts, and Rollback Readiness
Learn how to evaluate a candidate model version against a baseline, automate release checks with a Python script, and gradually increase production traffic. This guide covers evaluation metrics, release thresholds, stable traffic routing, and configuration controls that support rollback readiness.
1. Evaluation Metrics and Comparison Script
Before switching model versions, run both the baseline and the candidate against a fixed evaluation dataset and compare the results. Version the dataset, use the same inputs for both versions, and keep sampling parameters identical—for example, set temperature to 0 for both runs or use the production setting.
Include at least 300 samples per category, with at least 1,000 samples overall recommended.
Use the following metric definitions:
- Time to first token (TTFT): Time from the client sending a request to receiving the first output token, measured in milliseconds. Collect this metric through streaming calls and report P50, P95, and P99.
- End-to-end latency: Time from sending a request to receiving the complete response. Report P95 and compare it with the configured timeout.
- Truncation rate: Requests with
finish_reasonset tolength, divided by total requests. This measures the proportion of responses cut short by the generation length limit. - Parse success rate: Samples whose output can be parsed as JSON and includes all required fields, divided by total samples.
- Task pass rate: Samples marked as passing by the evaluator, divided by total samples. Also report this metric by category.
- Cost per task:
(average input tokens × input price + average output tokens × output price) ÷ 1,000,000, where prices are per million tokens. Estimate the monthly budget by multiplying this cost by monthly task volume.
Write one JSONL record per call using the following fields:
{"id": "t-0001", "category": "ticket_classification", "prompt_tokens": 812, "completion_tokens": 96, "ttft_ms": 420, "total_ms": 1830, "finish_reason": "stop", "passed": true, "parse_ok": true}
The following script reads baseline and candidate result files, calculates these metrics, and produces a release verdict. It uses only the Python standard library and requires Python 3.9 or later.
#!/usr/bin/env python3"""Compare baseline and candidate evaluation results and report a verdict."""import argparseimport jsonimport mathimport sysfrom collections import defaultdictdef load_jsonl(path):rows = []with open(path, encoding="utf-8") as f:for lineno, line in enumerate(f, 1):line = line.strip()if not line:continuetry:rows.append(json.loads(line))except json.JSONDecodeError as e:sys.exit(f"{path}:{lineno} Invalid JSON: {e}")return rowsdef percentile(values, p):if not values:return Nones = sorted(values)k = (len(s) - 1) * p / 100lo, hi = math.floor(k), math.ceil(k)return s[lo] + (s[hi] - s[lo]) * (k - lo)def summarize(rows, price_in, price_out):n = len(rows)ttft = [r["ttft_ms"] for r in rows if r.get("ttft_ms") is not None]total = [r["total_ms"] for r in rows]cat_total = defaultdict(int)cat_pass = defaultdict(int)for r in rows:cat_total[r["category"]] += 1cat_pass[r["category"]] += bool(r["passed"])cost = sum(r["prompt_tokens"] * price_in + r["completion_tokens"] * price_outfor r in rows) / 1_000_000return {"n": n,"ttft_p50_ms": percentile(ttft, 50),"ttft_p95_ms": percentile(ttft, 95),"ttft_p99_ms": percentile(ttft, 99),"total_p95_ms": percentile(total, 95),"truncation_rate": sum(r["finish_reason"] == "length" for r in rows) / n,"parse_rate": sum(bool(r["parse_ok"]) for r in rows) / n,"pass_rate": sum(bool(r["passed"]) for r in rows) / n,"cost_per_task": cost / n,"category_pass_rate": {c: cat_pass[c] / cat_total[c] for c in cat_total},}def judge(base, cand, a):fails, warns = [], []if cand["n"] < a.min_samples:fails.append(f"Sample count {cand['n']} is below the minimum of {a.min_samples}")if cand["ttft_p95_ms"] is None:fails.append("Missing ttft_ms data; use streaming calls to collect time to first token")elif cand["ttft_p95_ms"] > a.max_ttft_p95_ms:fails.append(f"TTFT P95 is {cand['ttft_p95_ms']:.0f} ms, "f"exceeding {a.max_ttft_p95_ms:.0f} ms")if cand["truncation_rate"] > a.max_truncation:fails.append(f"Truncation rate is {cand['truncation_rate']:.2%}, "f"exceeding {a.max_truncation:.2%}")if cand["parse_rate"] < a.min_parse_rate:fails.append(f"Parse success rate is {cand['parse_rate']:.2%}, "f"below {a.min_parse_rate:.2%}")if cand["cost_per_task"] > base["cost_per_task"] * a.max_cost_ratio:fails.append(f"Cost per task is {cand['cost_per_task']:.6f}, "f"exceeding {a.max_cost_ratio:.2f} times the baseline")drop = base["pass_rate"] - cand["pass_rate"]if drop > a.max_pass_drop:fails.append(f"Task pass rate dropped by {drop:.2%}, "f"exceeding {a.max_pass_drop:.2%}")for cat, rate in cand["category_pass_rate"].items():ref = base["category_pass_rate"].get(cat)if ref is not None and ref - rate > a.max_category_drop:warns.append(f"Pass rate for category {cat} dropped by {ref - rate:.2%}; ""investigation required")if fails:return "FAIL", fails + warnsif warns:return "CONDITIONAL_PASS", warnsreturn "PASS", []def main():p = argparse.ArgumentParser(description="Evaluate a minor model version upgrade")p.add_argument("--baseline", required=True, help="Baseline results JSONL")p.add_argument("--candidate", required=True, help="Candidate results JSONL")p.add_argument("--price-in", type=float, default=0.0,help="Input price per 1M tokens")p.add_argument("--price-out", type=float, default=0.0,help="Output price per 1M tokens")p.add_argument("--min-samples", type=int, default=1000)p.add_argument("--max-ttft-p95-ms", type=float, default=1500)p.add_argument("--max-truncation", type=float, default=0.02)p.add_argument("--min-parse-rate", type=float, default=0.99)p.add_argument("--max-cost-ratio", type=float, default=1.10)p.add_argument("--max-pass-drop", type=float, default=0.02)p.add_argument("--max-category-drop", type=float, default=0.05)a = p.parse_args()base_rows = load_jsonl(a.baseline)cand_rows = load_jsonl(a.candidate)if not base_rows or not cand_rows:sys.exit("Baseline or candidate results are empty")base = summarize(base_rows, a.price_in, a.price_out)cand = summarize(cand_rows, a.price_in, a.price_out)verdict, reasons = judge(base, cand, a)print(json.dumps({"verdict": verdict, "reasons": reasons,"baseline": base, "candidate": cand},ensure_ascii=False, indent=2))return {"PASS": 0, "CONDITIONAL_PASS": 1, "FAIL": 2}[verdict]if __name__ == "__main__":sys.exit(main())
Example command:
python3 compare_models.py \--baseline runs/base.jsonl --candidate runs/cand.jsonl \--price-in 0.5 --price-out 1.5 --max-ttft-p95-ms 1500
Exit code 0 means pass, 1 means conditional pass, and 2 means fail. A CI or release pipeline can use these exit codes to determine whether the candidate can proceed to a canary rollout.
The verdict has three levels:
- Pass: All hard requirements are met, with no category-level regression beyond the configured threshold.
- Conditional pass: All hard requirements are met, but at least one category’s pass rate has dropped beyond its threshold. Investigate the cause before proceeding.
- Fail: At least one hard requirement is not met. Postpone the switch.
Sampling noise can affect pass-rate comparisons. With 1,000 samples and a pass rate near 50%, the approximate 95% confidence interval is ±3 percentage points. A 2-percentage-point decline is therefore better treated as a signal for review. Before blocking the switch, increase the sample size or run the same dataset three times and use the median result.
All thresholds above are examples. Adjust them to match your business risk tolerance.
2. Staged Canary Rollout
Passing the evaluation does not mean the candidate should immediately receive all production traffic. Increase exposure in stages, as shown below. Each stage must remain within monitoring thresholds and complete its minimum observation window before advancing. Do not skip stages.
| Stage | Candidate traffic share | Minimum observation window | Entry requirement |
|---|---|---|---|
| 0: Shadow traffic | 0% user-facing traffic; run both versions without returning candidate results to users | 24 hours and at least 3,000 requests | Evaluation script returns PASS |
| 1: Initial canary | 1% | 24 hours | No blocking alerts in Stage 0 |
| 2: Expanded canary | 5% | 24 hours | No blocking alerts in Stage 1 |
| 3: Intermediate rollout | 20% | 48 hours | No blocking alerts in Stage 2 |
| 4: Majority rollout | 50% | 48 hours | No blocking alerts in Stage 3 |
| 5: Full rollout | 100% | Keep the previous version on standby for 7 days | No blocking alerts in Stage 4 |
Traffic assignment must be stable: the same user should consistently reach the same version within a given stage. Otherwise, both the user experience and the metrics can be distorted.
One approach is to assign users to buckets by hashing their user IDs:
import hashlibdef use_candidate(user_id: str, percent: int) -> bool:digest = hashlib.sha256(user_id.encode("utf-8")).hexdigest()return int(digest[:8], 16) % 100 < percent
Manage the traffic percentage through centralized configuration rather than hard-coding it. This lets you adjust exposure without redeploying the service and provides a control point for rollback.
