Sub topic 3
Tracking data, code, and model lineage
Prerequisites and scope
This chapter assumes you know the basic ML lifecycle (training, evaluation, deployment, monitoring) and can use Git and CI/CD. You should also be able to read short Python programs and know what a model registry or experiment tracker does. It builds on the audit-trail chapter, because lineage records are the part of an audit event that says what a model was made from.
This chapter is engineering guidance, not legal advice.
What lineage is and why governance needs it
Lineage is the recorded chain of inputs and steps that produced an artifact. For a model version, it answers one question: what exactly was this built from?
Provenance is closely related. Lineage describes the chain of artifacts and steps. Provenance adds who and what environment produced each step, and when. In practice teams store both in one record and call it lineage.
Ordinary software has one main input, the source code, and a commit hash identifies it. An ML model has at least three:
- The training data, which changes over time and is often too large to put in Git.
- The code, including the training script, feature logic, and configuration.
- The environment, including library versions, hardware, and random seeds.
A change to any of these can change the model's behavior, so a model version is only explainable if all of them are pinned. Without lineage you cannot answer an auditor or incident reviewer who asks which data a deployed model saw. You also cannot reproduce a result or find every model affected when a dataset turns out to be flawed.
The lineage graph
Lineage is a directed graph. Nodes are artifacts (datasets, code revisions, models, reports). Edges say "was produced from."
Two properties make this graph useful:
- Immutable nodes. Each node is identified by a content hash or an immutable version, never by a mutable name like
latest. - Queryable in both directions. Forward: which models used this dataset? Backward: what produced this model?
The forward query is the one teams forget. When you discover that a data source was mislabeled, you need to list every model trained from it, including models derived from those models.
What to record
A lineage record for one model version should contain the following.
| Item | What to store | Why it matters |
|---|---|---|
| Training data | Snapshot ID and content hash, source systems, extraction date | Reproduces the exact rows used |
| Data preparation | Code revision and parameters for cleaning and feature steps | Explains how raw data became features |
| Training code | Git commit SHA, plus a flag for uncommitted changes | Identifies the exact logic |
| Configuration | Hyperparameters and config file hash | Distinguishes runs on the same code |
| Environment | Dependency lock file hash, container image digest, seeds | Allows rebuilds |
| Evaluation | Evaluation dataset ID and the report's hash | Links claims about quality to evidence |
| Parent models | Base model or checkpoint version when fine-tuning | Carries lineage across generations |
Capturing lineage in code
The most reliable approach captures lineage automatically in the training job, so engineers do not fill it in by hand. The example below hashes a dataset file, reads the Git state, and builds a lineage record.
import hashlib
import json
import subprocess
from pathlib import Path
def file_sha256(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def git_state() -> dict:
commit = subprocess.run(
["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True
).stdout.strip()
dirty = bool(
subprocess.run(
["git", "status", "--porcelain"], capture_output=True, text=True, check=True
).stdout.strip()
)
return {"commit": commit, "dirty": dirty}
def build_lineage(model: str, version: str, data_path: str, params: dict) -> dict:
return {
"model": model,
"version": version,
"data": {"path": data_path, "sha256": file_sha256(data_path)},
"code": git_state(),
"params": params,
}
if __name__ == "__main__":
Path("train.csv").write_text("age,income,label\n41,52000,1\n29,31000,0\n")
record = build_lineage("credit-scoring", "2.4.0", "train.csv", {"lr": 0.05, "seed": 7})
print(json.dumps(record, indent=2))Run it inside a Git repository that has at least one commit. If it runs outside a repository, git rev-parse fails and the script raises an error, which is the right behavior: a training run that cannot name its code revision should not produce a governed model.
The dirty flag matters. If the working tree has uncommitted changes, the commit SHA does not describe the code that ran. A release gate can reject any record where dirty is true.
Linking lineage to the audit trail
Lineage and audit events serve different purposes, and they work together.
- The lineage record describes what a model version is made of. It is written once when the model is created.
- Audit events describe what people and systems did to it: registered, approved, promoted, rolled back.
Do not copy the whole lineage into every event. Store the lineage record under its own ID, then reference that ID or its hash from the audit events. This keeps events small. It also means a tampered lineage record no longer matches the hash in the tamper-evident log.
import hashlib
import json
def lineage_id(record: dict) -> str:
payload = json.dumps(record, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
record = {
"model": "credit-scoring",
"version": "2.4.0",
"data": {"sha256": "ab12"},
"code": {"commit": "3f9c0de", "dirty": False},
}
details = {"lineage_id": lineage_id(record)}
print(details)The details dictionary can be passed as the details argument when you append a "model registered" event to the hash-chained log from the previous chapter.
Where lineage is stored
| Approach | Strength | Weakness |
|---|---|---|
| Experiment tracker or registry metadata | Easy to adopt, tied to runs | Weak guarantees if records can be edited |
| Data versioning tools (snapshots, content-addressed storage) | Pins large datasets without Git | Needs discipline to snapshot before each run |
| Dedicated lineage service (graph store) | Fast forward and backward queries | More infrastructure to run |
| Records in the release record file | Reviewable in pull requests | Not queryable across many models |
Many teams combine them: content-addressed data snapshots, tracker metadata for runs, and a hashed reference in the audit log.
Common errors and edge cases
- Mutable references. Recording
s3://bucket/train/latest.csvinstead of a snapshot ID or hash. The file changes and the record becomes false. - Hashing paths, not content. A path proves nothing about what was in the file.
- Missing preprocessing. Recording the raw data but not the code that filtered or joined it.
- Lost parents. Fine-tuned models that do not record the base model, so a flaw in the base cannot be traced forward.
- Untracked data from outside. Third-party or purchased data with no source, license, or collection date recorded.
- Personal data and retention. Snapshots may contain personal data. Keep a hash and metadata long term, and apply your data-protection retention rules to the snapshot itself. If a snapshot is deleted, record that fact and keep the hash so the record still shows what was used.
- Non-determinism. Recording seeds does not guarantee bit-identical retraining on GPUs. Lineage tells you what went in. It does not promise the same weights come out.
Checklist
- Every training run records dataset hash, code commit, config, and environment automatically.
- Releases are blocked when the code state is dirty or a data reference is mutable.
- Fine-tuned models store their parent model version.
- You can list all models derived from a given dataset.
- Audit events reference lineage by ID or hash.
Exercise
A team records data_path: s3://ml/train/latest.csv and the Git commit in the lineage record of model 3.1.0. Name two ways this record fails as evidence, and one change that fixes each.
Show answer
First, latest.csv is a mutable reference, so the file may change after training and the record no longer identifies the data used. Fix it by recording a content hash or an immutable snapshot ID. Second, the record does not say whether the working tree was clean, so the commit SHA may not match the code that ran. Fix it by capturing a dirty flag (or refusing to train on a dirty tree). Missing environment details such as the image digest and seed would be a further gap.
Exercise
A labeling vendor reports that one batch in dataset snapshot S-12 was mislabeled. Which lineage query do you need, and what does it return?
Show answer
A forward query from S-12. It returns every training run and model version built from that snapshot, plus models fine-tuned from those models. You then decide which deployed versions need review, retraining, or incident handling.