Sub topic 13
Recording run metadata with results
This chapter assumes you can run Jupyter notebooks, use the command line, and install packages with pip. It also assumes you have seen seeds, pinned dependencies, and data checksums in earlier chapters. Here you will learn to save that information next to each result, so a number or figure can be traced back to the run that produced it.
Why results need a label
A figure saved as results.png says nothing about its origin. Three weeks later you may not know which data file, package versions, or seed produced it. If two runs give different numbers, you have nothing to compare.
Run metadata is a small record written alongside each result. It answers the question "what exactly produced this?" Earlier chapters gave you the pieces. This chapter collects them into one file per run.
Metadata does not make a run reproducible by itself. It makes a run diagnosable. When a colleague cannot match your numbers, the record shows which input differs.
What to record
Record anything that can change the result or that you will need in order to find the run again.
| Item | Why it matters | Where it comes from |
|---|---|---|
| Run ID and timestamp | Identifies and orders runs | `datetime`, `uuid` |
| Code version | Ties results to exact code | `git rev-parse HEAD` |
| Uncommitted changes flag | Warns that the commit does not match the code | `git status --porcelain` |
| Python and OS version | Behaviour differs across versions | `sys`, `platform` |
| Package versions | The usual cause of drift | `importlib.metadata` |
| Random seed | Repeats random steps | Your own constant |
| Input data hashes | Detects changed inputs | `hashlib` |
| Parameters | Distinguishes runs of one notebook | Your parameter cell |
Choosing a format
Use a plain-text, structured format. JSON is a good default. Python reads and writes it with the standard library, people can read it, and Git diffs it line by line.
Save the metadata file next to the result it describes, with a matching name. For example, outputs/run_20261202T091500Z/ can hold metrics.json, figure.png, and metadata.json. One directory per run avoids overwriting earlier results.
Collecting the pieces
The following helper functions gather the facts. Put them in a module such as src/runmeta.py so every notebook can reuse them. This follows the module approach from earlier chapters.
import hashlib
import json
import platform
import subprocess
import sys
from datetime import datetime, timezone
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
def sha256_of(path):
h = hashlib.sha256()
with Path(path).open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def git_info():
"""Return the current commit and whether the working tree has changes."""
try:
commit = 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()
return {"commit": commit, "dirty": bool(status)}
except (subprocess.CalledProcessError, FileNotFoundError):
return {"commit": None, "dirty": None}
def package_versions(names):
found = {}
for name in names:
try:
found[name] = version(name)
except PackageNotFoundError:
found[name] = None
return found
def collect_metadata(seed, params, data_files, packages):
now = datetime.now(timezone.utc)
return {
"run_id": now.strftime("%Y%m%dT%H%M%SZ"),
"started_at": now.isoformat(),
"python": sys.version,
"platform": platform.platform(),
"git": git_info(),
"packages": package_versions(packages),
"seed": seed,
"params": params,
"data": {str(p): sha256_of(p) for p in data_files},
}
def write_metadata(meta, out_dir):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
path = out_dir / "metadata.json"
path.write_text(json.dumps(meta, indent=2, sort_keys=True))
return pathSome details are worth noting:
git_inforeturnsNonevalues when Git is missing or the folder is not a repository. It does not crash, and theNoneshows the gap in the record.package_versionsrecordsNonefor a package that is not installed, so a typo in the list is visible.sort_keys=Truekeeps the key order stable, which keeps diffs small.- Timestamps use UTC, so runs from different time zones sort correctly.
Using it in a notebook
Call the helper near the top of the notebook, after the parameter cell, so the record reflects the values actually used. Write the file at the end, so a failed run leaves no metadata that looks complete.
import numpy as np
from runmeta import collect_metadata, write_metadata
SEED = 20240601
params = {"alpha": 0.1}
data_files = ["data/raw/measurements.csv"]
meta = collect_metadata(
seed=SEED,
params=params,
data_files=data_files,
packages=["numpy", "pandas", "matplotlib"],
)
rng = np.random.default_rng(SEED)
sample = rng.normal(size=1000)
metrics = {"mean": float(sample.mean()), "std": float(sample.std())}
out_dir = f"outputs/run_{meta['run_id']}"
write_metadata(meta, out_dir)
print("Wrote", out_dir)The example uses a single seeded generator, as in the earlier chapter on randomness. The seed is stored in the metadata, so the record is enough to repeat the random steps.
Quick in-notebook record
For small projects you may only want the environment printed in the notebook output. This is the lightest option, and it still travels with the saved notebook.
import platform
import sys
from importlib.metadata import version
print("Python:", sys.version)
print("Platform:", platform.platform())
for name in ["numpy", "pandas"]:
print(f"{name}:", version(name))Printed output has one weakness. Someone who strips outputs for version control, as with nbstripout, removes this record too. A JSON file saved to outputs/ is not affected, which is why the file is the better choice for results you intend to keep.
Metadata from headless runs
When you execute notebooks from the command line, the same metadata approach works. Papermill also saves the parameters it injected into the executed notebook, so the output copy documents its own inputs.
papermill analysis.ipynb outputs/analysis_alpha_0.1.ipynb -p alpha 0.1Keep the executed notebook and the metadata.json together. The executed notebook shows what ran and what it printed. The JSON file gives a machine-readable summary that scripts can search.
How the pieces fit together
Using the record to debug a mismatch
The payoff comes when two runs disagree. Load both files and compare them.
import json
from pathlib import Path
def flatten(d, prefix=""):
flat = {}
for key, value in d.items():
name = f"{prefix}{key}"
if isinstance(value, dict):
flat.update(flatten(value, name + "."))
else:
flat[name] = value
return flat
def compare_runs(path_a, path_b, ignore=("run_id", "started_at")):
a = flatten(json.loads(Path(path_a).read_text()))
b = flatten(json.loads(Path(path_b).read_text()))
for key in sorted(set(a) | set(b)):
if key in ignore:
continue
if a.get(key) != b.get(key):
print(f"{key}:\n A = {a.get(key)}\n B = {b.get(key)}")
# compare_runs("outputs/run_A/metadata.json", "outputs/run_B/metadata.json")Any line it prints is a candidate cause. A different packages.numpy points to environment drift. A different data.data/raw/measurements.csv means the input changed. A different git.commit means the code changed.
Gotchas
- Recording a dirty tree. If
dirtyistrue, the commit hash does not describe the code that ran. Commit first, or treat that run as exploratory. - Recording what you did not use. Package versions come from the installed environment. If the kernel runs a different environment from your terminal, the record shows the kernel's versions, which is correct. Check that the notebook uses the kernel you expect.
- Metadata written before the work finishes. A file that exists for a crashed run looks like a success. Write it last, or add a
"status"field. - Hashing very large data. Hashing a multi-gigabyte file on every run is slow. Hash once, store the value, and check it, or hash on first load only.
- Floating-point output that differs slightly. Matching metadata does not guarantee identical numbers across different hardware or library builds. Treat tiny differences as a separate question and compare with a tolerance.
- Hand-edited metadata. Always generate it in code. Typed values go stale.
Exercises
Exercise
A colleague reruns your notebook and gets a different mean. Their metadata.json matches yours in every field except packages.pandas. What should you check next, and why?
Show answer
Check whether the pandas version difference changes the computation, for example in default behaviour for parsing, grouping, or missing values. Install the same pandas version from your pinned requirements file and rerun. If the numbers then match, the cause was environment drift, and you should pin the version in requirements.txt.
Exercise
Why does the chapter recommend writing metadata.json at the end of a run, and what could you add if you must write it earlier?
Show answer
A file written at the start exists even if the run crashes, so it looks like a finished run. Writing it last avoids that. If you must write it early, include a "status" field set to "running" and update it to "complete" when the run succeeds.
Exercise
Add the value of the PYTHONHASHSEED environment variable to the metadata, without recording all environment variables. Which function would you change, and what would the new line look like?
Show answer
Change collect_metadata. Import os and add a line such as "pythonhashseed": os.environ.get("PYTHONHASHSEED") to the returned dictionary. Using .get returns None when the variable is unset, and selecting one variable avoids leaking secrets.