Observe a controlled candidate failure, restore a checked earlier routing generation and confirm predictions use the stable bundle.
Problem
When you need this. A selected candidate can fail after activation because an artifact is unavailable. The operator needs a known compatible bundle and a reliable way to select it again. Rewriting the failed generation would erase how the incident occurred.
The drill renames the candidate directory so prediction cannot find it, observes the failure, restores generation 1 as a new generation and predicts again. The code renames the directory back when the drill ends, so the model files are unchanged.
Concepts
Rollback selects a previous working configuration. It does not reverse training or delete the candidate. This router copies the selected historical configuration into a new generation with an explicit rollback reason.
Before the router changes the head, it loads the historical bundle and checks it again. Its model, feature definition, policy, serving code and release code must still be compatible. An old model is not safe simply because it once worked with different application code.
The expected-generation check also applies to rollback. If another operator changed the head after diagnosis, the router refuses the stale rollback. The operator reloads the current state and issues the rollback again.
Architecture
Working code
Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. Install the pinned platform dependencies for this workshop.
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txtOn PowerShell, activate with .venv\Scripts\Activate.ps1.
Continue from Stage a candidate with an explicit traffic decision; keep the same lab directory and outputs.
Revalidate the target before selecting it
Routing.rollback finds the historical row and passes its paths and percentage to stage, the same checked transaction that staging uses. The rollback adds a new row, so the previous configuration stays in history.
class Routing:
def __init__(self,path):
self.db=sqlite3.connect(path)
self.db.row_factory=sqlite3.Row
self.db.execute('CREATE TABLE IF NOT EXISTS releases (generation INTEGER PRIMARY KEY,stable TEXT NOT NULL,candidate TEXT NOT NULL,percent INTEGER NOT NULL,reason TEXT NOT NULL)')
self.db.execute('CREATE TABLE IF NOT EXISTS head (singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation INTEGER NOT NULL)')
self.db.commit()
def close(self):self.db.close()
def current(self):
row=self.db.execute('SELECT r.* FROM releases r JOIN head h ON r.generation=h.generation').fetchone()
if row is None:raise ValueError('no routing release selected')
return dict(row)
def stage(self,stable,candidate,percent,expected_generation,reason='stage'):
if type(percent) is not int or not 0<=percent<=100:raise ValueError('percent must be an integer from 0 to 100')
for path in [stable,candidate]:
_,_,decision=release.load_bundle(path)
if not decision['passed']:raise ValueError('gate failure prevents routing')
self.db.execute('BEGIN IMMEDIATE')
try:
row=self.db.execute('SELECT generation FROM head WHERE singleton=1').fetchone()
old=row[0] if row else 0
if expected_generation!=old:raise ValueError('routing changed; reload before editing')
generation=old+1
self.db.execute('INSERT INTO releases VALUES (?,?,?,?,?)',(generation,str(Path(stable).resolve()),str(Path(candidate).resolve()),percent,reason))
self.db.execute('INSERT INTO head VALUES (1,?) ON CONFLICT(singleton) DO UPDATE SET generation=excluded.generation',(generation,))
self.db.commit();return self.current()
except Exception:self.db.rollback();raise
def predict(self,value):
# Invalid requests cannot influence routing or create prediction records.
value=serving.request(value);state=self.current()
bucket=int(hashlib.sha256(value['id'].encode()).hexdigest()[:8],16)%100
chosen=state['candidate'] if bucket<state['percent'] else state['stable']
result=serving.Predictor(chosen).predict(value)
return dict(result,generation=state['generation'],route='candidate' if bucket<state['percent'] else 'stable',bucket=bucket)
def rollback(self,target_generation,expected_generation):
row=self.db.execute('SELECT * FROM releases WHERE generation=?',(target_generation,)).fetchone()
if row is None:raise ValueError('unknown rollback generation')
# Revalidate target bytes and code compatibility before changing the head.
return self.stage(row['stable'],row['candidate'],row['percent'],expected_generation,'rollback to '+str(target_generation))The class checks both selected paths before committing. A missing target or incompatible implementation leaves the current head unchanged.
Run the missing-candidate drill
rollback_report renames the selected candidate directory for the drill only. It catches the FileNotFoundError from prediction, rolls back to generation 1 and makes a stable prediction. If prediction does not fail, the drill raises an error instead of rolling back.
def rollback_report(root):
need(root,'routed-predictions.json');routing=rollout.Routing(root/'routing.sqlite')
candidate=root/'bundle-v2';held=root/'bundle-v2-held-during-drill'
try:
current=routing.current();candidate.rename(held)
try:
try:routing.predict(rows(root)[0])
except FileNotFoundError:failure='selected candidate files unavailable in controlled drill'
else:raise ValueError('controlled missing-artifact failure did not occur')
restored=routing.rollback(1,current['generation'])
prediction=routing.predict(rows(root)[0])
finally:held.rename(candidate)
return {'observed_failure':failure,'restored_generation':restored['generation'],
'restored_candidate_percent':restored['percent'],'prediction_route':prediction['route'],
'release_history_rows':routing.db.execute('SELECT count(*) FROM releases').fetchone()[0]}
finally:routing.close()python course.py rollback --workspace work/course{
"observed_failure": "selected candidate files unavailable in controlled drill",
"restored_generation": 4,
"restored_candidate_percent": 0,
"prediction_route": "stable",
"release_history_rows": 4
}The output records the observed failure, restored generation, zero candidate percentage and stable route. In this run, rolling back to generation 1 creates generation 4; it does not reuse number 1. The history includes the original selection and the rollback.
The output above is from a recorded local run in recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt.
Failure cases
The staging/rollback integration test checks the retained generation count and zero candidate percentage. Separate bundle tests check that the loader refuses changed model bytes and incompatible application code.
Rollback cannot repair an old bundle that fails to load. Keep another compatible release available, restore the missing artifacts or follow a reviewed application recovery procedure. Do not remove a lock or edit a manifest just to force a load.
python -m unittest -v test_platform.pyRunning and scaling the workshop
This drill makes local files unavailable and records a real prediction failure and routing change. It does not simulate a production outage or measure recovery time.
In a real release, package the prior application image, dependency set, feature definition and model so they can be retrieved together. The local digests check compatibility; they do not install a different application build.
Key takeaways
- Rollback creates a new selection and preserves history.
- Revalidate the target’s compatibility and bytes.
- A successful prediction after selection is the smoke check.
Best practices
Keep a known compatible release available before rollout.
Use the current generation when issuing a rollback, and retain the incident’s failure record.
Roll back by generation number instead of retyping bundle paths. Routing.rollback then reuses the stored paths and percentage, and stage checks them again.
After a rollback, send one prediction and check its generation and route before you treat the rollback as done.
Check your understanding
Why is the old model alone insufficient for rollback?
Show the explanation
Its inputs, preprocessing, policy and serving implementation must agree. This loader refuses a bundle whose application digests or feature contract differ.
Read the explanation
The router checks the old bundle before updating routing. A compatibility failure leaves the active selection unchanged.