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_reason set to length, 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:

    1. {"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.

    1. #!/usr/bin/env python3
    2. """Compare baseline and candidate evaluation results and report a verdict."""
    3. import argparse
    4. import json
    5. import math
    6. import sys
    7. from collections import defaultdict
    8. def load_jsonl(path):
    9. rows = []
    10. with open(path, encoding="utf-8") as f:
    11. for lineno, line in enumerate(f, 1):
    12. line = line.strip()
    13. if not line:
    14. continue
    15. try:
    16. rows.append(json.loads(line))
    17. except json.JSONDecodeError as e:
    18. sys.exit(f"{path}:{lineno} Invalid JSON: {e}")
    19. return rows
    20. def percentile(values, p):
    21. if not values:
    22. return None
    23. s = sorted(values)
    24. k = (len(s) - 1) * p / 100
    25. lo, hi = math.floor(k), math.ceil(k)
    26. return s[lo] + (s[hi] - s[lo]) * (k - lo)
    27. def summarize(rows, price_in, price_out):
    28. n = len(rows)
    29. ttft = [r["ttft_ms"] for r in rows if r.get("ttft_ms") is not None]
    30. total = [r["total_ms"] for r in rows]
    31. cat_total = defaultdict(int)
    32. cat_pass = defaultdict(int)
    33. for r in rows:
    34. cat_total[r["category"]] += 1
    35. cat_pass[r["category"]] += bool(r["passed"])
    36. cost = sum(
    37. r["prompt_tokens"] * price_in + r["completion_tokens"] * price_out
    38. for r in rows
    39. ) / 1_000_000
    40. return {
    41. "n": n,
    42. "ttft_p50_ms": percentile(ttft, 50),
    43. "ttft_p95_ms": percentile(ttft, 95),
    44. "ttft_p99_ms": percentile(ttft, 99),
    45. "total_p95_ms": percentile(total, 95),
    46. "truncation_rate": sum(r["finish_reason"] == "length" for r in rows) / n,
    47. "parse_rate": sum(bool(r["parse_ok"]) for r in rows) / n,
    48. "pass_rate": sum(bool(r["passed"]) for r in rows) / n,
    49. "cost_per_task": cost / n,
    50. "category_pass_rate": {c: cat_pass[c] / cat_total[c] for c in cat_total},
    51. }
    52. def judge(base, cand, a):
    53. fails, warns = [], []
    54. if cand["n"] < a.min_samples:
    55. fails.append(
    56. f"Sample count {cand['n']} is below the minimum of {a.min_samples}"
    57. )
    58. if cand["ttft_p95_ms"] is None:
    59. fails.append(
    60. "Missing ttft_ms data; use streaming calls to collect time to first token"
    61. )
    62. elif cand["ttft_p95_ms"] > a.max_ttft_p95_ms:
    63. fails.append(
    64. f"TTFT P95 is {cand['ttft_p95_ms']:.0f} ms, "
    65. f"exceeding {a.max_ttft_p95_ms:.0f} ms"
    66. )
    67. if cand["truncation_rate"] > a.max_truncation:
    68. fails.append(
    69. f"Truncation rate is {cand['truncation_rate']:.2%}, "
    70. f"exceeding {a.max_truncation:.2%}"
    71. )
    72. if cand["parse_rate"] < a.min_parse_rate:
    73. fails.append(
    74. f"Parse success rate is {cand['parse_rate']:.2%}, "
    75. f"below {a.min_parse_rate:.2%}"
    76. )
    77. if cand["cost_per_task"] > base["cost_per_task"] * a.max_cost_ratio:
    78. fails.append(
    79. f"Cost per task is {cand['cost_per_task']:.6f}, "
    80. f"exceeding {a.max_cost_ratio:.2f} times the baseline"
    81. )
    82. drop = base["pass_rate"] - cand["pass_rate"]
    83. if drop > a.max_pass_drop:
    84. fails.append(
    85. f"Task pass rate dropped by {drop:.2%}, "
    86. f"exceeding {a.max_pass_drop:.2%}"
    87. )
    88. for cat, rate in cand["category_pass_rate"].items():
    89. ref = base["category_pass_rate"].get(cat)
    90. if ref is not None and ref - rate > a.max_category_drop:
    91. warns.append(
    92. f"Pass rate for category {cat} dropped by {ref - rate:.2%}; "
    93. "investigation required"
    94. )
    95. if fails:
    96. return "FAIL", fails + warns
    97. if warns:
    98. return "CONDITIONAL_PASS", warns
    99. return "PASS", []
    100. def main():
    101. p = argparse.ArgumentParser(
    102. description="Evaluate a minor model version upgrade"
    103. )
    104. p.add_argument("--baseline", required=True, help="Baseline results JSONL")
    105. p.add_argument("--candidate", required=True, help="Candidate results JSONL")
    106. p.add_argument(
    107. "--price-in", type=float, default=0.0,
    108. help="Input price per 1M tokens"
    109. )
    110. p.add_argument(
    111. "--price-out", type=float, default=0.0,
    112. help="Output price per 1M tokens"
    113. )
    114. p.add_argument("--min-samples", type=int, default=1000)
    115. p.add_argument("--max-ttft-p95-ms", type=float, default=1500)
    116. p.add_argument("--max-truncation", type=float, default=0.02)
    117. p.add_argument("--min-parse-rate", type=float, default=0.99)
    118. p.add_argument("--max-cost-ratio", type=float, default=1.10)
    119. p.add_argument("--max-pass-drop", type=float, default=0.02)
    120. p.add_argument("--max-category-drop", type=float, default=0.05)
    121. a = p.parse_args()
    122. base_rows = load_jsonl(a.baseline)
    123. cand_rows = load_jsonl(a.candidate)
    124. if not base_rows or not cand_rows:
    125. sys.exit("Baseline or candidate results are empty")
    126. base = summarize(base_rows, a.price_in, a.price_out)
    127. cand = summarize(cand_rows, a.price_in, a.price_out)
    128. verdict, reasons = judge(base, cand, a)
    129. print(json.dumps({"verdict": verdict, "reasons": reasons,
    130. "baseline": base, "candidate": cand},
    131. ensure_ascii=False, indent=2))
    132. return {"PASS": 0, "CONDITIONAL_PASS": 1, "FAIL": 2}[verdict]
    133. if __name__ == "__main__":
    134. sys.exit(main())

    Example command:

    1. python3 compare_models.py \
    2. --baseline runs/base.jsonl --candidate runs/cand.jsonl \
    3. --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:

    1. import hashlib
    2. def use_candidate(user_id: str, percent: int) -> bool:
    3. digest = hashlib.sha256(user_id.encode("utf-8")).hexdigest()
    4. 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.