Sub topic 1
Why rollback starts with immutable, versioned artifacts
A rollback is only as reliable as the thing you roll back to. If last week's model cannot be found, or has been overwritten, or loads but behaves differently than it did last week, you have no rollback. You have a second incident. This chapter covers the foundation that every later step depends on: each deployable model is an immutable, versioned artifact with recorded metadata.
Prerequisites
This chapter assumes you already have the following:
- You know how a trained model is packaged and loaded for inference, for example a pickled scikit-learn pipeline, a PyTorch checkpoint, or an ONNX file behind an HTTP server.
- You can work with containers and have seen a Kubernetes Deployment.
- You can read and run basic Python and shell commands.
- You know common model metrics such as accuracy, latency, and error rate.
You do not need to have used a model registry yet. The next chapter introduces one.
What rollback needs
Rolling back means returning production to a model version that worked before. That sentence contains three requirements:
- A version must exist. You can name it, and you can fetch it.
- It must be the same thing it was. Fetching version 3 today returns exactly the bytes that served traffic when version 3 was healthy.
- It must be runnable. You know which code, features, and dependencies it needs.
Immutability covers the second requirement. Metadata and bundling cover the third. Teams that skip these steps usually find out during an outage.
What counts as the artifact
The weights file is rarely the whole model. A prediction comes from a chain of pieces, and changing any one of them changes the output. The deployable unit is a bundle.
| Piece | Example | What goes wrong if it is not versioned with the model |
|---|---|---|
| Model weights | `model.pkl`, `model.onnx` | The old file is overwritten and cannot be restored |
| Preprocessing | Fitted scaler, encoder vocabulary, tokenizer | The old weights receive inputs scaled differently than in training |
| Feature schema | Column names, types, order | A renamed feature makes the old model fail or silently mis-predict |
| Inference code | Handler, post-processing, thresholds | A new threshold changes decisions even though the weights are the same |
| Environment | Python and library versions, base image digest | The same weights load but produce different numbers, or fail to load |
| Metadata | Training data version, code commit, metrics | You cannot tell whether the old version is a safe target |
A common mistake is to version the weights and leave the fitted preprocessing in a shared location. When someone refits the encoder for the new model, the old model's rollback target is broken even though its file never changed. The simplest fix is to package the fitted preprocessing inside the artifact, for example as one scikit-learn Pipeline, or to store it next to the weights under the same version.
What immutable means
An immutable artifact never changes after it is published. Version 3 is version 3 forever. If you find a bug, you publish version 4. You do not edit version 3.
This is easy to say and easy to break. These are the usual ways immutability is lost:
- Overwriting a path. The training job writes to
s3://models/fraud/latest/model.pklevery night. Yesterday's model is gone the moment tonight's job finishes. - Reusing a version tag. A container image tagged
fraud:v3is pushed again after a "small fix". Nodes that pulled the image earlier run different code from nodes that pull it now. - Mutable tags in deployment specs. A Deployment that references
fraud:latestcan change behavior on any pod restart, with no deploy event to point at. - Unpinned dependencies. The artifact is unchanged, but
pip install scikit-learnresolves to a newer release at build time. The bundle is no longer the same thing. - Retraining under the same name. A retrained model gets the same registry name and version as the previous one because the pipeline reuses a run label.
The defenses are mechanical:
- Write each version to a unique path that includes the version number or a content hash.
- Refuse to write to a path that already exists.
- Make stored objects read-only where the storage supports it. Examples are object lock or versioning on a bucket, and permissions that deny overwrite and delete to the training job's role.
- Reference container images by digest (
fraud@sha256:...) in the deployment spec. Use a version tag only as a readable label. - Pin dependency versions and record the base image digest.
Recording metadata
Metadata answers the question you ask at 3 a.m.: is version 3 safe to go back to? Record these fields at publish time, from the training pipeline, not by hand afterwards:
- Version number and creation time
- Code commit of the training and inference code
- Identifier or snapshot of the training data
- Evaluation metrics on a held-out set, with the dataset they were measured on
- Input and output schema (the model signature)
- Environment: Python version, key library versions, base image digest
- Content hashes of each file
- Who or what published it (user, pipeline run ID)
Later chapters use these fields directly. The schema tells you whether an old model still fits the current features. The evaluation metrics give you a baseline to compare against after rollback. The training data identifier tells you whether the old model was trained on data that is still valid.
A minimal publish-and-verify example
A model registry does all of this for you, but the mechanics are small enough to write out. The script below publishes a version to a local directory store. It refuses to overwrite an existing version, records hashes and metadata in a manifest, makes the files read-only, and verifies the hashes on load. It uses only the Python standard library, so it runs as shown.
import hashlib
import json
import shutil
import stat
import tempfile
from datetime import datetime, timezone
from pathlib import Path
def sha256_of(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def publish(store: Path, name: str, version: int, files: list, metadata: dict) -> Path:
target = store / name / f"v{version}"
if target.exists():
raise FileExistsError(f"{name} v{version} already exists and is immutable")
target.mkdir(parents=True)
hashes = {}
for src in files:
dest = target / Path(src).name
shutil.copy2(src, dest)
hashes[dest.name] = sha256_of(dest)
dest.chmod(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) # read-only
manifest = {
"name": name,
"version": version,
"created_at": datetime.now(timezone.utc).isoformat(),
"files": hashes,
**metadata,
}
manifest_path = target / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True))
manifest_path.chmod(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
return target
def load_verified(store: Path, name: str, version: int) -> dict:
target = store / name / f"v{version}"
manifest = json.loads((target / "manifest.json").read_text())
for filename, expected in manifest["files"].items():
actual = sha256_of(target / filename)
if actual != expected:
raise ValueError(f"{filename} does not match its recorded hash")
return manifest
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
weights = tmp / "model.bin"
weights.write_bytes(b"weights-for-version-3")
store = tmp / "store"
metadata = {
"git_commit": "a1b2c3d",
"training_data": "transactions-2026-10-01",
"metrics": {"auc": 0.93},
"schema": ["amount", "country", "hour"],
}
publish(store, "fraud-detector", 3, [weights], metadata)
print("Verified:", load_verified(store, "fraud-detector", 3)["version"])
try:
publish(store, "fraud-detector", 3, [weights], metadata)
except FileExistsError as err:
print("Blocked overwrite:", err)Running it prints Verified: 3, then Blocked overwrite: fraud-detector v3 already exists and is immutable. The read-only permission is a guard against mistakes, not a security boundary. Anyone with write access to the directory can still change the permissions. In production, enforce immutability in the storage layer (bucket versioning, object lock, or deny policies) and in the registry.
How artifacts flow to a rollback
The diagram shows where immutable artifacts sit between training and serving. Training produces a new bundle each time and never edits an old one. The deployment pointer, covered in a later chapter, decides which bundle serves traffic. Because every earlier bundle is still intact, moving the pointer back is a safe operation.
Failure modes to watch for
These are the situations where a team believes it has a rollback target and does not.
- The target was never retained. A cleanup job deletes versions older than 30 days. The last good version was 45 days old. Set retention so that the previous known-good version is never deleted automatically.
- The target depends on something that moved. The old model expects a feature that has since been renamed or removed. The artifact is intact, but the system around it changed. A later chapter covers compatibility checks.
- The metadata is missing or untrusted. If no one recorded which training data produced version 2, you cannot judge whether it is safe to return to.
- A hash exists but is never checked. Recording hashes without verifying them at load time catches nothing.
- The old image cannot be pulled. The registry that hosted the image was pruned, or the base image tag now points elsewhere. Pinning by digest and retaining images prevents this.
- Silent numeric differences. The same weights loaded under a different library version can produce slightly different outputs. Recording the environment lets you reproduce the original behavior.
Summary of the working model
- The deployable unit is a bundle: weights, fitted preprocessing, schema, inference code, and environment.
- Each bundle is published once under a unique version and never modified.
- Hashes detect change, and storage controls prevent it.
- Metadata recorded at publish time lets you judge a rollback target without guessing.
- Retention rules keep at least the last known-good version available.
With these in place, the next chapter adds a model registry on top. It tracks versions and their metadata in one place, so that "which version is production?" has a single answer.
Exercise
A training job writes its output to s3://models/fraud/latest/model.pkl every night and deploys from that path. The nightly model degrades accuracy on Tuesday. Name two reasons rollback is not possible with this setup, and give one change for each.
Show answer
First, the path is overwritten each night, so Monday's model no longer exists after Tuesday's job runs. Change: write each run to a unique versioned path such as s3://models/fraud/v42/ and deny overwrite and delete to the training role, or enable bucket versioning and object lock. Second, there is no record of which version served traffic or what it needed. Deploying from latest means no deploy event, no metadata, and no pointer to move back. Change: publish each model with a manifest of hashes, code commit, training data identifier, metrics, and schema, and deploy by referencing an explicit version or registry alias.
Exercise
A container image fraud:v3 was rebuilt and pushed again under the same tag after a "small fix". Why does this break rollback, and how should the Deployment reference the image instead?
Show answer
The tag v3 no longer identifies one fixed set of bytes. Nodes that pulled it before the push and nodes that pull it after run different code, and rolling back to "v3" does not return to the version that was healthy. Reference the image by digest (fraud@sha256:<digest>) in the deployment spec, publish fixes under a new tag such as v4, and treat the tag only as a readable label.