Sub topic 8
Tracking Data Sources and Verifying Integrity
This chapter assumes you can run a notebook, use the command line, and know basic Python file handling. The previous chapters covered environments and seeds. Here we cover the third input to an analysis, the data.
Why data needs tracking
A notebook can have pinned packages and fixed seeds and still give different answers. The usual cause is that the input file changed. Someone re-exported a CSV, a download URL started serving a newer version, or a cleanup script overwrote the original. Nothing in the notebook shows this. The numbers just move.
Two practices address it:
- Provenance records where the data came from and when.
- Integrity checking confirms that the file you have is the file you recorded.
Keep raw data raw
Put original files in data/raw/ and never edit them. Write anything derived from them to data/processed/, produced by code. If raw files are never modified, a hash recorded once stays valid. Treat the folder as read-only, and on Unix you can enforce it with chmod -R a-w data/raw.
Record provenance
For each input file, write down at least:
- the source (URL, database query, or the person who sent it)
- the date you retrieved it
- the version or release name, if the source has one
- the license or usage terms
- the SHA-256 hash of the file
A SHA-256 hash is a 64-character fingerprint computed from a file's bytes. Changing even one byte gives a completely different hash. Store these records in a small file committed to Git, such as data/MANIFEST.json.
Record and verify hashes
The first script computes the hash and writes a manifest entry. Run it once, when you first obtain the file.
import hashlib
import json
from datetime import date
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 record(path, source):
manifest_path = Path("data/MANIFEST.json")
manifest = {}
if manifest_path.exists():
manifest = json.loads(manifest_path.read_text())
manifest[str(path)] = {
"source": source,
"retrieved": date.today().isoformat(),
"sha256": sha256_of(path),
}
manifest_path.write_text(json.dumps(manifest, indent=2))
record("data/raw/measurements.csv", "https://example.org/measurements.csv")The check goes in the first cells of the notebook. It reads the manifest and stops the run if any file differs.
import hashlib
import json
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()
manifest = json.loads(Path("data/MANIFEST.json").read_text())
for name, info in manifest.items():
actual = sha256_of(name)
assert actual == info["sha256"], f"Input data changed: {name} is now {actual}"
print("All input files match the manifest.")Reading the file in 1 MiB chunks keeps memory use low, so the same code works on large files.
Common errors
- Hashing a re-saved file. Opening a CSV in a spreadsheet and saving it can change line endings or number formats, so the hash changes even when the values look the same.
- Pointing at a live URL. A URL that serves "latest" data cannot be reproduced. Download a copy, hash it, and record the release date.
- Large data in Git. Commit the manifest, not multi-gigabyte files. Keep the data in shared storage and let the hash tell people they fetched the right one.
- Silent edits. If you must correct raw data, save the corrected file under a new name and record a new manifest entry.
Exercise
A colleague reruns your notebook and the assertion fails with "Input data changed". The package versions and seed are identical. What are two likely causes, and what should you do first?
Show answer
Likely causes are that the colleague's copy of the file was re-downloaded, re-saved, or edited, or that the source now serves a newer version. First compare the file's retrieval date and source with the manifest, and recompute its hash. If the file differs, get the original from the recorded source or shared storage. Update the manifest only if you intentionally switch to the new data.