Sub topic 8
Tracking data sources and verifying integrity
This chapter assumes you can read and write basic Python, run commands in a terminal, and use Git for simple commits. It also assumes you have already set up a project layout that keeps raw data separate from code and outputs, as covered earlier in this tutorial.
Code and environment are only two of the inputs to an analysis. The third is the data. If the input file changes without you noticing, the same notebook gives different results. If nobody wrote down where the file came from, you cannot get it back. This chapter covers how to record the origin of your data and how to make a notebook stop when its input is not the one you expected.
Why data is a reproducibility problem
Data breaks reproducibility in several quiet ways:
- Silent edits. Someone opens a CSV in a spreadsheet, fixes a typo, and saves it. The file name is the same, but the content is not.
- Moving sources. A download link returns a newer version of the dataset next month. A web API returns today's records, not last year's.
- Unknown origin. The file sits in a shared folder with no note about who produced it, when, or with what query.
- Partial copies. A download is cut off, or a file is copied between machines with different line endings or encodings.
Your notebook will often run without error on altered data. That is the dangerous part. You get a plausible but different answer, and nothing tells you why.
Two practices handle this. Provenance is a written record of where data came from and how it was obtained. Integrity checking is a mechanical test that the file in front of you is the same one you recorded.
Treat raw data as read-only
Keep original files in one place, for example data/raw/, and never edit them. Any cleaning happens in code and writes its result somewhere else, such as data/processed/. This gives you a fixed starting point. If a cleaning step is wrong, you rerun it from the raw file.
On Linux and macOS you can enforce this with file permissions:
chmod -R a-w data/rawThis removes write permission for everyone. It does not stop a determined user, but it prevents accidental saves. If you need to add a new raw file later, restore write permission on the directory, add the file, then remove it again.
Checksums: a fingerprint for a file
A cryptographic hash is a function that reads all the bytes of a file and produces a short fixed-length string. Changing even one byte of the file produces a completely different string. SHA-256 is a common choice, and it produces 64 hexadecimal characters.
The hash is a checksum when you use it to check a file. If today's hash equals the hash you recorded earlier, the file's bytes are the same. If they differ, something changed.
You can compute one from the command line:
sha256sum data/raw/measurements.csvOn macOS the equivalent is shasum -a 256 data/raw/measurements.csv. In a notebook, use Python so the check runs with the analysis:
import hashlib
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()
EXPECTED = "paste-the-recorded-hash-here"
actual = sha256_of("data/raw/measurements.csv")
assert actual == EXPECTED, f"Input data changed: {actual}"Points worth understanding in this function:
- The file is opened in binary mode (
"rb"). The hash is over bytes, not text, so no encoding or newline conversion happens before hashing. - It reads 1 MiB at a time. A large file never has to fit in memory.
iter(callable, sentinel)calls the lambda repeatedly until it returns the sentinelb"", which signals end of file.- The
assertstops the notebook at the first cell that loads data. The error message prints the actual hash, so you can see what you got.
Before you can compare, you need a recorded value. Run sha256_of once on the file you trust, then paste the result into EXPECTED. Do this at the moment you first accept the data, not later.
Where to keep expected hashes
Hard-coding one hash in a cell works for a single file. With several files, a manifest is easier to maintain. A manifest is a small file that lists each data file with its hash and notes about its origin. Keep it in version control next to the code.
A simple JSON manifest, data/manifest.json:
{
"data/raw/measurements.csv": {
"sha256": "paste-the-recorded-hash-here",
"source": "https://example.org/datasets/measurements-v3.csv",
"retrieved": "2026-11-20",
"notes": "Downloaded by hand from the project page. Version 3."
}
}The notebook (or a module it imports) then checks every file in the manifest:
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()
def verify_manifest(manifest_path="data/manifest.json"):
manifest = json.loads(Path(manifest_path).read_text())
problems = []
for name, info in manifest.items():
path = Path(name)
if not path.exists():
problems.append(f"missing: {name}")
elif sha256_of(path) != info["sha256"]:
problems.append(f"changed: {name}")
if problems:
raise RuntimeError("Data check failed:\n" + "\n".join(problems))
print(f"Verified {len(manifest)} file(s).")
verify_manifest()This reports every problem at once instead of stopping at the first one. That saves a round of fix-and-rerun when several files are wrong.
Recording provenance
A hash tells you that a file changed. It does not tell you where the file came from. For that, write down at least:
- Source. A URL, database name, instrument, or person. For a query, record the query text.
- Date retrieved. Sources change over time, so the date matters.
- Version. A dataset version number, a release tag, or an API version, if one exists.
- Processing before you received it. Was it filtered, anonymized, or aggregated?
- License or access terms. Whether others may reuse it, and whether they can get it themselves.
Put this in the manifest, in a data/README.md, or both. The format matters less than the habit. A useful test is whether a colleague with no access to your machine could fetch the same data from your notes.
Data you cannot redistribute
Some data is too large for Git, or cannot be shared. In that case commit the manifest and the instructions, not the file. Another person then downloads the data themselves and the hash check confirms they got the right one. This is a common arrangement, and the hash is what makes it safe.
Data that changes by design
Live APIs and databases return different results over time. A hash of a file does not help if you never saved the file. The fix is to snapshot: fetch the data once, save it to data/raw/, record its hash and retrieval date, and have the analysis read the saved copy. The fetching code can live in a separate script that you run deliberately, not in the analysis notebook.
from datetime import date
from pathlib import Path
from urllib.request import urlopen
URL = "https://example.org/datasets/measurements-v3.csv"
dest = Path("data/raw/measurements.csv")
dest.parent.mkdir(parents=True, exist_ok=True)
with urlopen(URL) as response:
dest.write_bytes(response.read())
print("Saved", dest, "on", date.today().isoformat())After running it, compute the hash and add the entry to the manifest. The URL is a placeholder, so replace it with a real address before you run this.
Checks beyond the hash
A matching hash proves the bytes are identical. It does not prove the data is sensible. Add a few cheap checks after loading, so that a corrupted or wrongly exported file is caught even when you have no hash for it yet:
import pandas as pd
df = pd.read_csv("data/raw/measurements.csv")
expected_columns = {"sample_id", "value", "timestamp"}
assert expected_columns <= set(df.columns), "Missing columns"
assert len(df) > 0, "File is empty"
assert df["sample_id"].is_unique, "Duplicate sample IDs"
assert df["value"].notna().all(), "Missing values in 'value'"Adjust the checks to your data. Keep them in the notebook, or in a function in a module, so that they run every time.
Common errors
| Problem | Cause | What to do |
|---|---|---|
| Hash differs, file looks the same | Line endings or encoding changed, often from a copy between Windows and Linux or an editor save | Re-download the original. Do not just update the expected hash. |
| Hash passes on one machine, fails on another | Git converted line endings in a data file that was committed as text | Mark data files as binary in `.gitattributes`, or keep them out of Git. |
| Hash updated to make the check pass | The check was treated as an obstacle | Update the hash only after you have understood why the data changed, and note it in the manifest. |
| Check never runs | The assertion sits in a cell that is run out of order or skipped | Put the check in the first cell that loads data, and use restart and run all. |
| Same hash, different results | The source was fine but the code, environment, or seed changed | Check the other inputs covered in this tutorial. |
How the pieces fit
The manifest is written once, when you accept the data. After that, every run compares the file against it.
Exercises
Exercise
A teammate says, "The hash check failed, but I opened the CSV and it looks identical, so I just updated EXPECTED to the new hash." What is wrong with this, and what should they do instead?
Show answer
Looking identical does not mean the bytes are identical. Differences such as line endings, encoding, trailing whitespace, or a changed value in a row you did not inspect all change the hash. Updating the hash removes the protection without finding the cause. They should work out what differs (for example by re-downloading the original and comparing it), decide which version is correct, and only then update the manifest with a note about why.
Exercise
Why does sha256of open the file with "rb" and read it in 1 MiB chunks, instead of calling Path(path).readtext() and hashing the string?
Show answer
Binary mode hashes the exact bytes on disk, with no decoding or newline translation, so the result matches what sha256sum reports. Reading in chunks keeps memory use constant, so a file larger than available memory can still be hashed.
Exercise
Your analysis pulls daily figures from a web API. Describe how you would make the analysis reproducible a year from now.
Show answer
Fetch the data in a separate script and save it to data/raw/ as a snapshot. Compute its SHA-256 hash and record the hash, the API address and query, and the retrieval date in the manifest. Have the notebook read only the saved file and verify its hash before analysis. The notebook then no longer depends on what the API returns in the future.