Sub topic 13
Recording run metadata with results
A result file without context is hard to trust later. If a figure looks different next month, you need to know which code, packages, seed, and data produced the original. This chapter shows how to save that information next to every result.
This chapter assumes you already pin dependencies, seed random generators, and checksum input data, as covered in earlier chapters. Run metadata is where those records come together.
What to record
Run metadata is a small record saved with each run. A useful record answers five questions:
| Question | Example value | Source |
|---|---|---|
| When did it run? | UTC timestamp | `datetime` |
| What code ran? | Git commit hash | `git rev-parse HEAD` |
| What software ran it? | Python and package versions | `importlib.metadata` |
| What randomness was used? | The seed | Your own constant |
| What data went in? | SHA-256 of each input file | `hashlib` |
Also record the parameters of the run, such as alpha. Without them, two runs of the same notebook cannot be told apart.
Writing the metadata file
The script below collects the values and writes them as JSON. JSON is plain text, so it is easy to diff and to read without Python. Put this function in a module such as src/run_info.py and call it at the end of the notebook.
import hashlib
import json
import platform
import subprocess
import sys
from datetime import datetime, timezone
from importlib.metadata import 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_commit():
try:
out = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True, check=True,
)
return out.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def write_run_metadata(out_path, seed, params, input_files, packages):
metadata = {
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"git_commit": git_commit(),
"python": sys.version,
"platform": platform.platform(),
"packages": {name: version(name) for name in packages},
"seed": seed,
"parameters": params,
"inputs": {str(p): sha256_of(p) for p in input_files},
}
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(metadata, indent=2))
return metadataCall it from the last cell of the notebook, after the analysis has finished:
write_run_metadata(
"outputs/run_metadata.json",
seed=20240601,
params={"alpha": 0.1},
input_files=["data/raw/measurements.csv"],
packages=["numpy", "pandas"],
)Writing at the end means the file exists only if the run completed. A leftover file from an earlier run is a risk, so overwrite it every time rather than appending.
Keeping metadata with the results
Metadata is only useful if it stays attached to its results. Two habits help:
- Save each run in its own folder, for example
outputs/2026-12-02_alpha_0.1/, and writerun_metadata.jsoninto that folder. - Never reuse a results file name for a different run. If the folder name includes the parameters, you can see at a glance what differs.
When you run the notebook with Papermill, the executed copy already stores the injected parameters. Still write the JSON file, because it also holds the commit and data hashes.
Common errors
- Dirty working tree. The commit hash is misleading if you edited files after committing. Record
git status --porcelainoutput too, or refuse to run when it is not empty. - Version of the wrong environment.
version("numpy")reports what is installed in the active kernel. Check that the notebook kernel uses your project's.venv. - Recording the seed but not using it. The metadata says
seed: 20240601even if no generator received it. Pass the same constant to both. - Metadata saved from an early cell. If a later cell changes a parameter, the record is wrong. Write it last.
Exercise
A colleague reruns your notebook and gets slightly different numbers. Your metadata file shows the same seed and the same package versions. Which two other fields would you compare first, and why?
Show answer
Compare the input data hashes, because a changed input file gives different results even with identical code and seed. Then compare the Git commit, because a different code version can change the computation. The parameters and the platform string are the next things to check.