Python Master Course V2 — 186. Safe Rollouts, Shadow Evaluation and Rollback
Lesson 186: Safe Rollouts, Shadow Evaluation and Rollback
A correct model can still be introduced unsafely. A rollout changes which implementation answers a request, so it must control exposure, preserve an escape route and collect evidence that distinguishes technical failures from prediction mistakes. In this lesson the “users” are generated request identifiers, and both versions are ordinary Python functions. The same reasoning later applies to a real service, but the simulation creates no live exposure.
Estimated study time: 70 minutes, including the practical work. Use a local Python 3.11+ environment; no paid service, API key or public deployment is required.
Before you start
- 182: artifact versions
- 184–185: monitoring
Learning objectives
- Separate candidate validation from production activation
- Compare shadow and canary strategies under bounded risk
- Verify rollback compatibility and avoid interpreting biased samples as experiments
Concepts and worked implementation
Choose the comparison before choosing the router
Offline validation evaluates a fixed dataset before activation. Shadow evaluation sends the same eligible input to a candidate while keeping the established version’s response authoritative. A canary lets a bounded subset receive candidate responses. A staged rollout expands that subset only after explicit gates pass. These are different interventions: shadowing can measure disagreements and resource costs, but it cannot directly measure the downstream effects of actions nobody received.
Separate operational gates from quality gates. Exceptions, malformed outputs and deadline violations may be visible immediately; prediction error often needs labels that arrive later. A disagreement is evidence to inspect, not an error label. Set a minimum observation count, evaluation window and stop condition before looking at the run. In this deliberately tiny drill, two failures out of five attempts exceed a 20% tolerance. Such a short window is suitable for demonstrating control flow, not establishing real reliability.
Build a stable, bounded local router
Save the following as rollout.py. The models accept a finite score between zero and one. Version two has a deliberately seeded exception above 0.8. It is a teaching fault, not an improved model. The cohort function uses a repeatable digest rather than Python’s process-randomized hash. It partitions synthetic IDs without storing any personal identifier.
import hashlib
import math
def bucket(request_id):
digest = hashlib.sha256(request_id.encode('utf-8')).digest()
return int.from_bytes(digest[:4], 'big') % 100
def predict(version, score):
if type(score) not in (int, float):
raise ValueError('score must be numeric')
if not 0 <= score <= 1 or not math.isfinite(score):
raise ValueError('score outside schema')
if version == 'v1':
return int(score >= 0.5)
if version == 'v2':
if score > 0.8:
raise RuntimeError('seeded candidate failure')
return int(score >= 0.6)
raise ValueError('unknown version')
def run_shadow(scores):
rows = []
for index, score in enumerate(scores):
live = predict('v1', score)
try:
candidate = predict('v2', score)
rows.append({'id': index, 'live': live,
'candidate': candidate, 'error': False})
except RuntimeError:
rows.append({'id': index, 'live': live,
'candidate': None, 'error': True})
return rows
def should_rollback(rows, minimum=5, tolerance=0.20):
return (len(rows) >= minimum and
sum(row['error'] for row in rows) / len(rows) > tolerance)
if __name__ == '__main__':
rows = run_shadow([0.1, 0.55, 0.7, 0.9, 0.95])
active = 'v2' # A simulated canary activation, never a live service.
if should_rollback(rows):
active = 'v1'
print({'attempts': len(rows),
'candidate_errors': sum(r['error'] for r in rows),
'active_after_drill': active})
assert active == 'v1'
assert predict(active, 0.95) == 1
assert bucket('synthetic-17') == bucket('synthetic-17')
Expected result: attempts is 5, candidate_errors is 2 and active_after_drill is v1. A threshold of exactly 20% does not trigger this policy because the comparison is strictly greater than. That boundary is intentional and must appear in a test. Keeping failures in the denominator prevents an overly optimistic report that counts only successful predictions.
Understand activation and compatibility
A canary selector could choose v2 when bucket(request_id) is below 5. This creates an approximately 5% partition across a sufficiently varied identifier population, not exactly five requests in every hundred. Stable assignment reduces confusing within-user changes, but the hash partition alone does not establish causal randomization. Correlated traffic, missing outcomes and exclusions can bias comparisons. Document assignment and use an appropriately designed experiment before making causal claims.
Rollback must restore more than a model filename. Version the feature schema, preprocessing, label mapping and response contract together. Keep the previous artifact readable and verify it against the current request schema before activation. If a release irreversibly rewrites stored data, switching the pointer cannot undo that migration. Prefer additive schema changes and separately tested recovery plans. Preserve the failed version’s manifest and aggregate evidence so the incident can be explained without retaining raw inputs.
Do not put the candidate on the critical path in a real shadow system without a separate resource budget. A slow or failing shadow call must not consume all workers or delay the authoritative response. A future with a timeout only stops waiting; it does not necessarily stop the running work. This synchronous local example intentionally demonstrates decisions, not process isolation.
Guided lab and evidence
Create a behavior table for zero requests, four failures before the minimum count, one failure in five attempts and two failures in five attempts. Add direct assertions for each row. Then change the candidate threshold from 0.6 to 0.4 while keeping the operational fault and measure disagreements separately from failures. Record attempted comparisons, successful comparisons, error rate and disagreement rate with their respective denominators.
Your deliverable is rollout.py, a short gate specification and a recovery note. The note must state what is activated, who could stop it in a real setting, how compatibility is checked and which downstream effects the simulation cannot measure. A successful drill shows candidate rejection, continued v1 responses and retained evidence. It does not show that v1 is accurate or that a real deployment is safe. Repeat the drill after intentionally changing the response schema; the correct result is a failed compatibility gate before activation.
Questions worth reasoning through
Why is shadow accuracy unavailable without outcome labels?
Shadow execution produces predictions, not truth. Comparing two versions establishes agreement only. Both may make the same mistake, and a candidate may correctly disagree. Attach later labels through an approved, minimized process before computing quality metrics.
Can a 5% canary guarantee only 5% of possible harm?
No. Traffic share is an exposure control, while harm also depends on the selected cases, failure severity and downstream actions. A small cohort can contain unusually consequential requests. Use contextual exclusions, manual review and explicit stopping rules where appropriate.
Why not use hash(request_id) for cohort membership?
Python may randomize string hashes between processes. Membership could change on restart, undermining a stable comparison. A specified digest gives repeatable partitioning, but it is not anonymization and should not justify collecting real identifiers.
Should every shadow disagreement trigger rollback?
Usually not. Operational contract violations may justify an immediate stop, while disagreements need labeled investigation. Define separate policies so a harmless threshold adjustment does not look identical to malformed responses or widespread exceptions.
What must a rollback test actually prove?
It must demonstrate that the previous artifact loads, accepts the current valid input, returns the expected response schema and can be selected by the routing mechanism. It should also show that irreversible writes and already-executed downstream actions need separate recovery.
Exercises and worked answers
Exercise 1
Write an assertion for the exact 20% boundary with five observations.
Worked answer and reasoning
Construct five rows with one error and four successes. The strict comparison means rollback is false; adding a second error makes it true.
from rollout import should_rollback
rows = [{"error": True}] + [{"error": False} for _ in range(4)]
assert should_rollback(rows) is False
rows[1]["error"] = True
assert should_rollback(rows) is TrueExercise 2
A candidate has one error in ten attempts and agrees on eight of its nine successful responses. Report the two rates.
Worked answer and reasoning
The operational error rate is 1/10 = 10%. Conditional disagreement among successful comparisons is 1/9, approximately 11.1%. Report the missing comparison explicitly. Using ten as the disagreement denominator without explaining failures would mix distinct outcomes.
Recap
Safe rollout begins with explicit evidence gates and ends with a tested recovery path. Shadowing, canaries and experiments answer different questions. Keep failed attempts visible, preserve compatible versions and distinguish operational health from prediction quality.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.