Sub topic 6
Recording what each run did
A training run that leaves no record cannot be trusted later. Suppose someone asks why the model in production scores 0.93 and last week's scored 0.96. Without records you can only guess. This chapter adds a recording layer to the pipeline from earlier chapters, so every run leaves behind what it was given, what it produced, and where it ran.
It assumes you have the TrainConfig, config_fingerprint, load_data, and run_pipeline code from earlier chapters, saved in a module named pipeline.py. It also assumes you know basic file I/O and context managers in Python.
The working model: parameters, metrics, artifacts, context
Every tracking tool, from a folder of JSON files to a hosted service, stores the same four kinds of information about a run.
| Kind | Example | Source | Question it answers |
|---|---|---|---|
| Parameters | `n_estimators=100`, `seed=42` | The resolved configuration | What was this run told to do? |
| Metrics | `accuracy=0.967` | The evaluate stage | How well did it do? |
| Artifacts | `model.joblib` | Files the run wrote | What did it produce? |
| Context | Git commit, library versions, data hash, status | The environment | Where and on what did it run? |
Context is the category people skip, and it matters most. Parameters and metrics tell you that two runs differ. Context tells you why.
A run also needs an identity that links these records. The config fingerprint from the configuration chapter is not enough, because the same configuration can be run twice, and those two runs should have separate records. A good run ID combines three parts: a UTC timestamp so folders sort by time, the fingerprint so you can find all runs of one configuration, and a short random suffix so IDs never collide.
A minimal recorder
You do not need a server to start. A directory per run, holding JSON files, is easy to inspect, diff, and commit-ignore. The recorder below does four things:
- It writes parameters and environment as soon as the run starts, before anything can fail.
- It writes each file through a temporary name and a rename, so a crash never leaves half a JSON file.
- It writes a
run.jsonsummary with statusrunningat the start. If the process is killed, the status staysrunning, which tells you the run died without cleanup. - It is a context manager, so an exception marks the run
failedand keeps the error message.
# tracking.py
import dataclasses
import hashlib
import json
import platform
import subprocess
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
import joblib
import numpy as np
import sklearn
from pipeline import TrainConfig, config_fingerprint, load_data, run_pipeline
def git_commit() -> str:
try:
head = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True, check=True,
).stdout.strip()
status = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True, text=True, check=True,
).stdout.strip()
except (OSError, subprocess.CalledProcessError):
return "unknown"
return head + ("-dirty" if status else "")
def environment() -> dict:
return {
"python": platform.python_version(),
"platform": platform.platform(),
"numpy": np.__version__,
"sklearn": sklearn.__version__,
"git_commit": git_commit(),
}
def data_fingerprint(X, y) -> str:
digest = hashlib.sha256()
for array in (X, y):
digest.update(str(array.dtype).encode())
digest.update(str(array.shape).encode())
digest.update(array.tobytes())
return digest.hexdigest()[:16]
class RunRecorder:
def __init__(self, root, cfg: TrainConfig):
self.fingerprint = config_fingerprint(cfg)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
self.run_id = f"{stamp}-{self.fingerprint}-{uuid.uuid4().hex[:6]}"
self.dir = Path(root) / self.run_id
self.dir.mkdir(parents=True, exist_ok=False)
self._started = time.monotonic()
self.info = {
"run_id": self.run_id,
"config_fingerprint": self.fingerprint,
"started_at": datetime.now(timezone.utc).isoformat(),
"status": "running",
"error": None,
"artifacts": [],
}
self._write("params.json", dataclasses.asdict(cfg))
self._write("environment.json", environment())
self._write("run.json", self.info)
def _write(self, name: str, obj) -> None:
tmp = self.dir / (name + ".tmp")
tmp.write_text(json.dumps(obj, indent=2, sort_keys=True))
tmp.replace(self.dir / name)
def note(self, **fields) -> None:
self.info.update(fields)
self._write("run.json", self.info)
def log_metrics(self, metrics: dict) -> None:
self._write("metrics.json", {k: float(v) for k, v in metrics.items()})
def log_artifact(self, name: str, obj) -> None:
joblib.dump(obj, self.dir / name)
self.note(artifacts=self.info["artifacts"] + [name])
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is None:
self.note(status="succeeded")
else:
self.note(status="failed", error=f"{exc_type.__name__}: {exc}")
self.note(duration_seconds=round(time.monotonic() - self._started, 3))
return False # never swallow the exceptionThe return False in __exit__ matters. The recorder only observes failures. It must not hide them, or CI would report green on a broken run.
Wiring it to the pipeline
tracked_run wraps run_pipeline without changing it. The pipeline stays a plain function that you can call without any tracking, which keeps tests simple.
def tracked_run(cfg: TrainConfig, root="runs") -> str:
with RunRecorder(root, cfg) as rec:
X, y = load_data()
rec.note(data_sha256=data_fingerprint(X, y))
model, metrics = run_pipeline(cfg)
rec.log_metrics(metrics)
rec.log_artifact("model.joblib", model)
return rec.run_id
if __name__ == "__main__":
print(tracked_run(TrainConfig()))After one run, the folder looks like this:
runs/20261130T093246Z-3f9a1c0b27de-a41b9c/
params.json
environment.json
metrics.json
model.joblib
run.jsonHere data_sha256 is a hash of the loaded arrays. For Iris, which ships inside scikit-learn, this only detects a library upgrade that changes the data. With real data, hash the input file or store the version identifier from your data versioning tool in the same field.
Reading records back
Records are only useful if you can query them. Two small functions are enough to answer "which successful run scored best?"
def load_runs(root="runs") -> list[dict]:
runs = []
for run_dir in sorted(Path(root).iterdir()):
summary = run_dir / "run.json"
if not summary.exists():
continue
info = json.loads(summary.read_text())
for name in ("params", "metrics", "environment"):
path = run_dir / f"{name}.json"
info[name] = json.loads(path.read_text()) if path.exists() else {}
runs.append(info)
return runs
def best_run(runs: list[dict], metric: str = "accuracy"):
candidates = [
r for r in runs
if r["status"] == "succeeded" and metric in r["metrics"]
]
return max(candidates, key=lambda r: r["metrics"][metric], default=None)Because run IDs begin with a UTC timestamp, sorted returns runs in chronological order. Local time would break this order whenever daylight saving shifts the clock.
Testing the recorder
Treat the recording layer like any other pipeline code. Use pytest's tmp_path fixture so tests never write into your real runs directory. Test the failure path as well, because that is the path people forget.
import json
import pytest
from pipeline import TrainConfig
from tracking import tracked_run
def test_successful_run_is_recorded(tmp_path):
run_id = tracked_run(TrainConfig(), root=tmp_path)
run_dir = tmp_path / run_id
info = json.loads((run_dir / "run.json").read_text())
params = json.loads((run_dir / "params.json").read_text())
assert info["status"] == "succeeded"
assert params["seed"] == 42
assert (run_dir / "model.joblib").exists()
def test_failed_run_is_recorded(tmp_path):
with pytest.raises(ValueError):
tracked_run(TrainConfig(min_accuracy=1.1), root=tmp_path)
run_dir = next(tmp_path.iterdir())
info = json.loads((run_dir / "run.json").read_text())
assert info["status"] == "failed"
assert "below the gate" in info["error"]Using an existing tracker
A file-based recorder works for one person and one machine. Once several people or machines run experiments, use a shared tracker. MLflow is a common open-source choice. It follows the same model of parameters, metrics, and artifacts, so the hand-written version above maps onto it directly.
import dataclasses
import mlflow
from pipeline import TrainConfig, config_fingerprint, run_pipeline
def tracked_run_mlflow(cfg: TrainConfig) -> None:
with mlflow.start_run(run_name=config_fingerprint(cfg)):
mlflow.log_params(dataclasses.asdict(cfg))
_, metrics = run_pipeline(cfg)
mlflow.log_metrics(metrics)MLflow marks a run as failed when the with block raises, which matches the behavior of RunRecorder. Trackers differ in how much context they capture automatically. Check what yours records. Anything it misses, such as the data hash, you must add yourself as a tag or parameter.
Common errors
- Recording only the final metric. One number hides how training behaved. For iterative models, log a metric per epoch or boosting round with a step index, so you can see overfitting begin.
- Recording the config diff instead of the full config. If you store only "n_estimators changed to 200", the record depends on defaults that may change later. Store the fully resolved configuration, as
dataclasses.asdict(cfg)does. - Run IDs that collide. If the ID is only the fingerprint, a second run with the same configuration overwrites the first. The timestamp and random suffix, plus
exist_ok=False, make a collision an error instead of silent data loss. - Ignoring uncommitted changes. A bare commit hash claims the code matches that commit. The
-dirtysuffix is a warning that it does not. For serious runs, make CI refuse to publish models whose commit ends in-dirty. - Recording only successes. If failed runs vanish, you overestimate how well your experiments work. Failed and aborted runs are data.
- Non-serializable values. NumPy scalars, arrays, and
Pathobjects can crashjson.dumpsor be silently converted in surprising ways. Convert values explicitly, aslog_metricsdoes withfloat. - Secrets in parameters. Parameters are written in plain text and often shared. Keep API keys and database passwords out of the config object, or redact them before logging.
- Selecting on the test metric. If you pick the best of fifty runs by test accuracy, the test score is now optimistic. Compare runs on validation metrics, and report the test metric once for the chosen model.
- Unbounded artifact growth. Saving a model for every run fills the disk. Decide a retention rule, for example keep artifacts only for runs that pass the gate and delete the rest after a fixed number of days, and keep the small JSON records forever.
Summary
Each run should write its parameters, metrics, artifacts, and context under a unique run ID, including runs that fail. Write the files early and atomically, and mark the status at the end. Keep tracking outside run_pipeline so the pipeline stays testable. Whether you use a folder of JSON or a service like MLflow, check that the data version and code version are recorded.
Exercise
A teammate reruns the pipeline with the same TrainConfig twice in one minute. Using the recorder in this chapter, how many run directories exist afterward, and why? What would change if the run ID were just config_fingerprint(cfg)?
Show answer
Two directories exist. Each ID has a UTC timestamp to the second plus a random six-character suffix, so the IDs differ even for the same fingerprint and the same second. With the fingerprint alone, the second run would hit mkdir(..., exist_ok=False) and fail with FileExistsError. If that check were removed, it would overwrite the first run's files.
Exercise
Add a field to run.json that records the number of training rows used. Which function should set it, and why is RunRecorder.note a better place to call than editing RunRecorder.__init__?
Show answer
Call rec.note(n_train_rows=len(X_train)) from the code that knows the value. That is the pipeline wrapper, or the split stage if you pass the recorder into it. The recorder cannot know the row count when it is created, because the data has not been split yet. note merges new fields into the existing summary and rewrites run.json atomically, so the recorder stays generic and any stage can add facts as they become known.