Dataset Lineage and Provenance
Build a provenance system for language-model pipelines. Learn event logs, hash chains, Merkle roots, span maps, and lineage queries for audits.
Language AI HandbookAll chapters Dataset Lineage and Provenance
When a training-data problem surfaces, the final checkpoint leaves open which sources entered its training corpus and how the pipeline processed them.
- A model can produce a perfect answer for the wrong reason.
- A benchmark score can rise because the benchmark leaked into training.
- A safety filter can fail because a document that should have been removed survived a pipeline branch.
- A license dispute can prompt a request for the source records behind a particular checkpoint.
Dataset lineage and provenance are the practices that let you answer these questions after the fact.
Each failure raises a question the final model cannot answer on its own.
- Did the training corpus contain the benchmark examples?
- Which pipeline branch processed the document, and what did its filter record?
- Which source and license records can the team recover for this release?
A provenance record gives investigators evidence to answer these questions. It can also expose gaps before release.
Provenance is the record of where something came from and what happened to it. Lineage is the graph of derivation relationships among artifacts: this raw crawl produced these extracted documents, these documents were filtered into that corpus, that corpus was mixed into these training shards, those shards trained this checkpoint, and that checkpoint was evaluated on these examples. The two concepts are complementary, and neither is sufficient alone. Provenance without lineage is a pile of metadata: you know facts about individual artifacts, but you cannot follow a path from one to another. Lineage without provenance is a graph with no verifiable content: you know that edges exist, but you cannot check what flowed along them or whether the claims are true.
A simple way to keep the distinction straight is to imagine a laboratory notebook and a citation graph. The notebook records, entry by entry, what was done, when, by whom, and with what materials. That is provenance. The citation graph records which papers build on which other papers. That is lineage. A research field needs both: the notebook to audit a specific experiment, and the citation graph to understand how ideas propagate. Data pipelines are no different.
In this chapter we build a working provenance system for a miniature language-model pipeline. We will trace documents through collection, normalization, filtering, deduplication, PII redaction, mixing, tokenization, sequence packing, training, evaluation, and release. The toy separates the records you would also need to plan for a larger corpus. Along the way we will separate document identity from content identity, event logs from lineage graphs, and tamper evidence from reproducibility. Each distinction sounds academic until you try to answer a real audit question, at which point the missing distinction becomes the reason the question cannot be answered.
The chapter sits at the start of Part XXI: Data Governance, Provenance, and Synthetic Ecosystems. It builds directly on the curation pipeline from Part XX: Data Curation. We will not re-explain deduplication, quality filtering, or PII detection here. Instead, we ask a different question: once those operations have run, how do we prove what happened?
What Lineage and Provenance Mean
In this chapter, provenance means the recorded history of an artifact, and lineage means the paths that link it to other artifacts. The distinction helps us ask two questions: who produced this artifact and under what conditions, and which recorded inputs and outputs are connected to it? Provenance frameworks such as W3C PROV also describe derivation relationships. A document history without downstream links cannot identify which model consumed that document. A derivation graph records license evidence only if the underlying records include it.
Provenance is the recorded history of an entity: its origin, the activities that touched it, the agents responsible, and the parameters of those activities. A provenance record is evidence, not a summary.
Lineage is the directed graph of derivation among entities. If document was used to produce shard , and shard was used to train checkpoint , then there is a lineage path .
A dataset card is documentation. A model card is documentation. Neither is automatically provenance. Documentation tells a reader what the authors believe is important. Provenance gives an auditor recorded observations to check, at the granularity the system captured. A good release package needs both. The card explains the intent and the caveats to a human reader; the provenance record supplies the verifiable detail that backs up, or contradicts, the card's claims.
Three provenance planes matter for language models:
- Data provenance covers source acquisition, extraction, normalization, filtering, deduplication, PII handling, mixing, tokenization, and shard construction.
- Model provenance covers code, configuration, tokenizer, random seeds, training data manifest, optimizer state, checkpoints, and the training run that produced each artifact.
- Evaluation provenance covers benchmark version, split, prompt template, decoding configuration, scoring code, and contamination checks.
These planes are connected. A model artifact is not reproducible from its own hash. You need the manifest that identifies the training data, the code and configuration that consumed it, and the evaluation records that justify the claims made about it. If any of the three planes is missing, the release has a gap that shows up precisely when someone asks a hard question: which data trained this model, which code produced this checkpoint, or which benchmark version produced this score.
Provenance Is Not Just Metadata
In this example, the descriptive metadata fields can be updated in place. Provenance is historical and ideally append-only. Consider a document record with fields source, language, and quality_score. If an engineer edits quality_score in place, the metadata still looks complete, but the history is gone. If the document was filtered out because of the old score, the new score now contradicts the pipeline's actual decision. Anyone reading the record later would see a coherent-looking row that describes a decision the pipeline never made.
A provenance system records events. Each event says what happened, when, to which entity, with which inputs, and with which parameters. The current state of a document is then a projection over its events. This is event sourcing. Retaining one event per update requires more storage than retaining only the latest row. Capture the filter version and threshold in the event to preserve the decision's context. The extra cost buys you the ability to replay history: to ask not only what the corpus looks like now, but how it came to look that way, which threshold rejected a document, and which version of a filter was in force on the day it ran.
The Traceable Unit
Language pipelines contain several different units, and conflating them is a common source of broken lineage:
- Source record: the raw response from a crawler, API, or dataset release.
- Document: the text extracted from a source record after boilerplate removal and normalization.
- Example: a supervised training or evaluation item, often a prompt-response pair or a labeled sentence.
- Sequence: an ordered token input to a model. A packing policy can combine tokens from several documents in one sequence.
- Token: the model's atomic input unit, produced by a tokenizer whose version matters.
- Artifact: a dataset manifest, tokenizer, shard, checkpoint, evaluation report, or release bundle.
Each unit plays a different role in the audit trail. A source record can capture the observed origin and point to any consent record for that source. A document answers questions about content and filtering. An example answers questions about supervision and labels. A packed sequence identifies its input tokens. A consumption record ties that sequence to a run. A document-span map assigns an input position to its source document. An artifact is the bundle that ties a set of units into something you can ship or compare.
A document can generate many examples. A sequence can contain tokens from many documents. One document can appear in multiple epochs, multiple shards, and multiple checkpoints. The relationships are many-to-many, not a simple parent-child tree. This is why a flat table with one row per document is not enough once training begins: the same document fans out across sequences and runs, and each fan-out point needs its own record.
In this chapter, we will use a "document" as the main traceable unit and a "packed sequence" as the training unit. Add example-level or span-level identifiers when the audit question needs that resolution. The same principles apply. The important thing is to choose the unit deliberately and to be explicit about where it stops being the right unit for a given question.
Why Tracing Is Hard
A CSV with a source column and a JSON config preserves the fields you write into those files. To distinguish retries, filter versions and consumed inputs, also record those observations and link them to the artifacts they affected.
First, represent the versioned artifacts and their producing activities as a directed acyclic graph. Give each retry a separate activity and output so branches and merges remain traceable. A document may fail language identification in one run, pass after a model update, and enter a later mixture. A deduplication cluster may split because a threshold changed. A single source may be crawled multiple times with different extraction versions. The provenance graph must represent versions, not just final state. A pipeline that only records the final artifact cannot explain why two runs of the same job produced different corpora.
Second, the operations can lose information. Boilerplate removal can delete text, and normalization can change Unicode and whitespace. The tokenizer determines token boundaries. After packing, recover document boundaries or ownership from adequate separators, masks, spans, or equivalent records. A hash can check a candidate copy of the surviving bytes against the recorded digest. The removal history belongs in separate event records.
Third, some stages can vary across runs. A fixed threshold is deterministic for fixed scores. Sampling, shuffling, and training operations such as dropout can introduce variation. A hash identifies an artifact, but it does not recreate the run. Reproducibility requires seeds, configurations, code versions, and enough environment information to explain divergence. Two runs with the same seed can still diverge under nondeterministic hardware or scheduler timing, so provenance must record not only the inputs but the conditions under which the run executed.
Fourth, provenance records can disclose private document membership, user identifiers, or source URLs. Store sensitive values under access controls. Where appropriate, a shared-key message authentication code (MAC) lets authorized parties check a candidate without publishing its bytes. Holders of the shared key can also create tags, so define who can access the candidates, verify tags, or issue them.
Fifth, check origin assertions. For example, suppose a vendor record and a scraped page label a text as human-written, while the generator log associates the same bytes with a generation request. Preserve the source records and investigate which claim the evidence supports. Checking a digest against a trusted reference can detect a change to the recorded bytes. A signature check links a claim to a signing key under the verifier's trust policy. Confirm facts about origin with independent records.
These constraints shape the design. We want immutable identifiers, append-only events, content-addressed artifacts, and explicit versioning of every transformation. We also want the system to be cheap enough that engineers do not bypass it. Measure capture overhead on each required stage and scan the run records for missing events after deployment.
A Traceable Pipeline
The stages in Table lineage-pipeline can run in different orders. For each stage, the table pairs an artifact with the provenance needed to investigate what would otherwise be missing.
| Stage | Typical artifact | Provenance to record | Failure if missing |
|---|---|---|---|
| Acquisition | Raw crawl or source file | URI, collector, timestamp, robots or license signal, HTTP status, raw hash | Missing evidence of where, when, and under which recorded signals the collector obtained the source |
| Extraction | Extracted document | Parser version, raw-to-text offsets, boilerplate rules, extraction hash | Cannot audit text loss |
| Normalization | Canonical text | Unicode form, whitespace rules, normalizer version | Hashes change silently across versions |
| Language ID | Language label | Model version, confidence, threshold, code-switching policy | Cannot explain language imbalance |
| Quality filtering | Quality score | Scorer version, features, threshold, decision | Cannot reproduce exclusions |
| Toxicity filtering | Toxicity score | Classifier version, threshold, human review | Cannot audit over-filtering |
| PII handling | Redacted text | Detector version, entity types, replacement policy | Cannot prove privacy handling |
| Deduplication | Cluster assignment | Algorithm, threshold, cluster ID, representative | Cannot explain duplicates or attribution |
| Mixing | Mixture manifest | Domain weights, sampling probabilities, epochs, seed | Cannot reproduce data composition |
| Tokenization | Token sequences | Tokenizer version, vocabulary hash, normalization, offsets | Cannot map tokens back to text |
| Packing | Training sequences | Sequence length, packing policy, document spans, attention mask | Cannot attribute tokens to documents |
| Training | Checkpoints | Code commit, config, seed, parallelism, data order, manifest root | Cannot connect model to data |
| Evaluation | Eval report | Benchmark version, split, prompt, decoding, scorer, contamination test | Cannot defend benchmark claims |
| Release | Model bundle | Model card, data card, manifest, license, known limitations | Cannot support audits or incident response |
The table is intentionally broad. A small project may record only a subset. For a regulated release, identify the applicable recordkeeping, signature, and retention requirements before deciding which fields to capture. The right level of detail depends on the questions you expect to be asked, and on the cost of being unable to answer them. A hobby project that ships a demo can reasonably record a fraction of this; a model that informs decisions about people needs the full chain and the ability to defend it.
Represent input and output artifacts separately from the activities that use and produce them. Forward queries find artifacts connected by recorded downstream paths. Backward queries find recorded inputs and transformations to inspect during an investigation. Establishing what caused a model outcome requires evidence beyond the graph.
Identity and Granularity
The first design decision is what identifier to use. Each of these identifiers needs context to stay meaningful across pipeline runs.
- A filename may change when a file moves.
- A row number may refer to a different document after sorting.
- A URL may serve different content over time, and the same content can appear at several URLs.
Choose a source identifier for the occurrence you intend to trace and a separate content digest for comparing canonical bytes.
As a general identity pattern, digest the bytes of a chosen canonical form. Compare the resulting digests under the same normalization and encoding:
where:
- : the encoded bytes of the versioned canonical text
- : a cryptographic hash function such as SHA-256
- : the content hash, a fixed-length hexadecimal digest of the exact byte sequence
The hash is stable for the exact byte sequence. Equal canonical bytes produce equal digests. Different digests establish different bytes. Distinct bytes can in principle have the same digest, so equality is a practical comparison under a collision-resistance assumption. This gives us a compact, comparable identifier without storing the text itself. It also lets two parties compare notes without exchanging the underlying data, which matters when the data is sensitive.
Mirrors can have identical canonical content and different source URLs, crawl times, or license signals. Keep the source-qualified document identifier separate from its content digest:
and separately:
where:
- : a stable identifier for one capture, such as an archive record ID or a URI plus capture-specific metadata
- : the versioned canonical text of the document
- : byte concatenation with an unambiguous separator
- : the source-qualified document identifier
- : a digest of the chosen text bytes, independent of the source ID
The document ID combines a source record and its canonical text. For readability, the fixture prefixes doc- to the first 12 hex characters of the SHA-256 result, retaining 48 bits. At corpus scale, retain the full digest or use a collision-safe identifier scheme. The fixture's content_hash hashes the redacted text with case preserved. Exact deduplication instead compares a separate dedup_key, computed from normalized, case-folded redacted text.
Canonicalization must be versioned. If version 1 collapses whitespace and version 2 applies Unicode NFKC first, a ligature such as fi becomes fi in version 2. The two versions produce different canonical text and different SHA-256 digests for this example. For text that both versions reduce to the same canonical bytes, the digests agree. Record normalizer="unicode-nfkc-whitespace-v2" alongside the hash. Recall from Text Normalization that Unicode normalization is not a cosmetic step; it changes code points and can change byte offsets. That means a hash that looks "wrong" across two runs may be correct for the normalizer versions that produced it, and without the version tag you cannot tell the difference between a bug and a legitimate change.
Two documents can have different hashes but nearly identical meaning. Two documents can have the same hash after aggressive boilerplate removal but come from different pages. Use a digest to compare a specified byte representation with a trusted reference. Keep the source identity, factual claims, and license as separate fields.
A tokenizer maps input text to tokens according to its vocabulary, normalization rules, special tokens, and version. Offsets can map an encoded input token to a span in a specified version of its source text. When packing combines documents, keep a span map from packed input positions to document IDs. The example below uses that map to identify which document supplied each input token. Attributing a model-generated token to training data requires separate evidence.
A Provenance Data Model
The W3C PROV family gives a useful vocabulary. PROV-DM defines entities, activities, and agents. PROV-O expresses the model in OWL. The core relations are:
- An entity is a thing, such as a document, shard, checkpoint, or evaluation report.
- An activity is something that occurs over time, such as extraction, filtering, training, or evaluation.
- An agent is something responsible, such as a person, team, crawler, or service.
usedconnects an activity to an entity it consumed.wasGeneratedByconnects an entity to the activity that produced it.wasDerivedFromconnects one entity to another.wasAttributedToconnects an entity to the agent it is attributed to; activities are tied to agents bywasAssociatedWith.
A training run uses a packed dataset and configuration and produces a checkpoint. The packed dataset derives from the retained documents. A filtering activity can produce a new selection artifact that references the unchanged document entities. When filtering changes a document's bytes, record the new document version as an output.
You do not need to adopt PROV-O literally to benefit from the model. You need the same distinctions. If your schema only has "dataset" and "model" rows, you cannot express which filter version, which tokenizer, or which mixture produced a checkpoint. The result is a graph that looks complete but cannot answer the questions that matter, because the nodes are too coarse and the edges carry no parameters.
Events Versus Snapshots
A snapshot records the state of an artifact at a point in time. An event records a change. Both are useful, and the design question is which one is the source of truth.
- A dataset manifest is a snapshot. A stored projection can answer state queries without replaying every event.
- Events are auditable and explain how the snapshot came to be. An append-only log is a sequence of events.
A robust system keeps both. The event log is the source of truth for history. The manifest is a materialized view optimized for training and release. A manifest root commits to the fields its construction includes. A separate record of consumed inputs can show how a run followed the manifest. If the planned manifest and recorded inputs differ, keep both. Check whether the discrepancy comes from the plan, the delivered data, or missing events before relying on either record.
Hash Chains and Tamper Evidence
An application can call a log append-only even when a database role can update old rows. In the toy chain, each event payload includes a named prev_hash field for the preceding event's digest. The event's own digest is stored separately from the payload it covers:
where:
- : the event payload with the named
prev_hashfield set to , excluding the event's ownevent_hashfield - : the fixture's compact, sorted-key JSON serialization, preserving Unicode characters
- : the encoding used to convert the resulting JSON text to bytes
- : the fixed genesis value of 64 zero characters
- : the resulting hash of the current event
The verifier checks each predecessor field and recomputes each event digest. If an edit leaves the stored digest unchanged, recomputation fails at that event even if the next stored predecessor still matches. Someone who can rewrite and rehash the log can produce a locally consistent chain. Retain a trusted checkpoint with the event position and digest to verify the corresponding prefix. An earlier checkpoint does not authenticate the suffix after it.
A Merkle tree provides a compact commitment to the leaves encoded by the builder. Given a trusted root and an inclusion proof, an auditor can verify a leaf without downloading the rest of the manifest. A leaf that encodes both a configuration digest and its role can commit to the mixture settings as a configuration input. The fixture below sorts content digests and duplicates the final tree node when a level has odd length. Its root leaves source identity and row order open, and padding can make different multiplicities produce the same root. A production manifest can bind the record count and defined leaf encoding in a signed record. Some blockchains use the same tree structure for transaction commitments. For a training audit, the leaf encoding determines whether the proof identifies only content bytes or a specific source occurrence.
Negative Provenance
Record what reached training and why other candidates were excluded. For example, exclusions can help diagnose a drop in performance for one domain. For redaction, keep the detector version and replacement policy. For near-deduplication, keep the representative and any score used in the decision. The exact-dedup fixture instead compares keys from normalized, case-folded text and logs the key prefix and the retained representative on a drop.
Negative provenance is the record of rejected, filtered, redacted, or deduplicated candidates. It is essential for debugging filters, measuring over-filtering, and defending decisions to auditors. It also creates privacy risk, because rejected documents may be more sensitive than accepted ones. Start with a reason code and the minimum supporting fields needed for the audit. Restrict access to source identifiers and digests when they could reveal sensitive content. If the audit requires raw text, keep it under the applicable access and retention controls.
Lineage Queries
Backward lineage here is the set of artifacts with a recorded derivation path of at least one edge into artifact :
where:
- : the artifact whose history we are tracing
- : a candidate ancestor artifact
- : the direct derivation relation, where means was derived from
- : reachability along one or more recorded derivation edges
The forward lineage, or impact set, is the set of descendants:
The equivalent forward query follows paths of at least one edge away from the starting artifact.
These two queries cover many practical tasks:
- Input investigation. Which recorded training inputs are associated with this checkpoint? Walk backward from the checkpoint through the training run and its shards to the documents and sources.
- Impact analysis: Which models were trained on a dataset that we now know was mislabeled? Walk forward from dataset to checkpoints and releases.
- Deletion requests: Which shards, checkpoints, and evaluation reports are affected by a document that must be removed? Walk forward. Then ask whether removal from the log is enough, since a log edit leaves the checkpoint bytes unchanged.
- Contamination checks: Which evaluation examples overlap with training documents? Query the intersection of evaluation n-grams and training document n-grams.
- License propagation. Which releases depend on training inputs carrying a particular license or consent signal? Walk forward from the source record that carries the signal.
Lineage queries are only as good as the graph. A position-to-document query needs a retained span map or a reproducible reconstruction. A consumed-input query needs the input order or a verified replay. Compare benchmark runs with the exact prompts used for each run. The graph is not a nice-to-have visualization; it is the data structure that determines which questions are answerable at all.
Worked Example: From Eight Documents to a Released Model
We now build a miniature pipeline. The corpus is synthetic and deliberately small. The tokenizer is a regular-expression stand-in, not a production tokenizer. The "model" is a bigram counter, not a neural network. These simplifications keep the provenance mechanics visible. A transformer run can use the same entity and activity distinctions, with additional records for its training inputs, code and environment. The point of the toy is not to model scale but to model the shape of the records, because the shape is what transfers.
We start with eight documents across four domains. One document is an exact duplicate from a mirror. One is in Spanish. One is low-quality spam. One contains fake PII. The rest are plausible news, science, code, and legal text. That mix is chosen to trigger each branch of the pipeline, so that every kind of provenance event gets exercised at least once.
PythonIn [3]Expand
raw_docs = [
{
"source_id": "web-001",
"uri": "https://example.org/transit-plan",
"domain": "news",
"lang": "en",
"text": "The city council approved the new transit plan on Tuesday. The plan adds bus lanes and extends service hours across the region.",
},
{
"source_id": "web-002",
"uri": "https://mirror.example.org/transit-plan",
"domain": "news",
"lang": "en",
"text": "The city council approved the new transit plan on Tuesday. The plan adds bus lanes and extends service hours across the region.",
},
{
"source_id": "web-003",
"uri": "https://example.org/air-quality-schools",
"domain": "science",
"lang": "en",
"text": "Researchers measured air quality at twelve schools. They found that tree cover reduced afternoon temperatures by nearly two degrees.",
},
{
"source_id": "code-001",
"uri": "https://example.org/snippets/add",
"domain": "code",
"lang": "en",
"text": "def add(a, b):\n return a + b\n",
},
{
"source_id": "web-004",
"uri": "https://example.org/cheap-watches",
"domain": "news",
"lang": "en",
"text": "buy cheap watches now click here",
},
{
"source_id": "web-005",
"uri": "https://example.org/transporte",
"domain": "news",
"lang": "es",
"text": "El ayuntamiento aprobó el nuevo plan de transporte el martes. El plan añade carriles para autobuses y amplía el horario de servicio.",
},
{
"source_id": "web-006",
"uri": "https://example.org/transit-contact",
"domain": "public",
"lang": "en",
"text": "Contact Jane Doe at jane.doe@example.com or 202-555-0100 to request the updated transit schedule.",
},
{
"source_id": "web-007",
"uri": "https://example.org/records-policy",
"domain": "public",
"lang": "en",
"text": "Section 4.2 requires the agency to publish an annual report. Requests for records must be submitted in writing.",
},
]ConsoleOut [4]Expand
Raw documents: 8
The raw documents are not yet traceable. We need stable IDs, canonical text, and an event log. The helper functions below define content hashing, normalization, PII redaction, a simple quality score, tokenization, and a Merkle root. The quality score is a toy heuristic, but it demonstrates how a filter decision becomes provenance. The helpers are deterministic. The redaction events record the detector version regex-demo-v1, and the model payload records the tokenizer version regex-word-punct-v1. The toy records omit versions for the normalizer, quality scorer, deduplicator, and Merkle construction. Those versions would help reproduce the artifacts after the implementation changes.
PythonIn [5]Expand
from __future__ import annotations
import copy
import hashlib
import json
import re
import unicodedata
from collections import Counter, defaultdict
from typing import Any
import pandas as pd
def canonical_json(value: Any) -> str:
return json.dumps(
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def short_hash(value: str, n: int = 12) -> str:
return value[:n]
def normalize_text(text: str) -> str:
text = unicodedata.normalize("NFKC", text)
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b")
PHONE_RE = re.compile(
r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"
)
def redact_pii(text: str) -> tuple[str, int]:
text, n_email = EMAIL_RE.subn("[EMAIL]", text)
text, n_phone = PHONE_RE.subn("[PHONE]", text)
return text, n_email + n_phone
SPAM_TERMS = {"buy", "cheap", "click", "watches"}
def quality_score(text: str) -> float:
words = re.findall(r"[A-Za-z0-9_]+", text)
if len(words) < 5:
return 0.0
spam_hits = sum(word.casefold() in SPAM_TERMS for word in words)
length_component = min(len(words), 80) / 80
return max(0.0, length_component - 0.2 * spam_hits)
def tokenize(text: str) -> list[str]:
return re.findall(r"[A-Za-z0-9_]+|[^\sA-Za-z0-9_]", text)
def merkle_root(hashes: list[str]) -> str:
if not hashes:
return sha256_text("")
level = [bytes.fromhex(h) for h in sorted(hashes)]
while len(level) > 1:
if len(level) % 2 == 1:
level.append(level[-1])
level = [
hashlib.sha256(level[i] + level[i + 1]).digest()
for i in range(0, len(level), 2)
]
return level[0].hex()Now we define the event log. Each event includes a sequence number, document ID, stage, activity, decision, input hash, output hash, parameters, and the previous event hash. The event hash is computed over the canonical payload. This is a hash chain. The schema is intentionally explicit: a reader can understand it without knowing the code, which matters because provenance records outlive the systems that produced them.
PythonIn [6]Expand
event_log: list[dict[str, Any]] = []
LOGICAL_CLOCK = 0
def log_event(
doc_id: str,
stage: str,
activity: str,
decision: str,
input_hash: str,
output_hash: str | None = None,
**params: Any,
) -> dict[str, Any]:
global LOGICAL_CLOCK
LOGICAL_CLOCK += 1
payload = {
"seq": LOGICAL_CLOCK,
"doc_id": doc_id,
"stage": stage,
"activity": activity,
"decision": decision,
"input_hash": input_hash,
"output_hash": output_hash,
"params": params,
"prev_hash": event_log[-1]["event_hash"] if event_log else "0" * 64,
}
event_hash = sha256_text(canonical_json(payload))
event = {**payload, "event_hash": event_hash}
event_log.append(event)
return event
def verify_chain(log: list[dict[str, Any]]) -> tuple[bool, int | None]:
prev = "0" * 64
for event in log:
payload = {
key: value for key, value in event.items() if key != "event_hash"
}
if payload["prev_hash"] != prev:
return False, payload["seq"]
recomputed = sha256_text(canonical_json(payload))
if recomputed != event["event_hash"]:
return False, payload["seq"]
prev = event["event_hash"]
return True, NoneWe now process the documents. The order is ingestion, normalization, language filtering, quality filtering, PII redaction, and exact deduplication. Every decision, including rejection, is logged. Each kept record carries the digest of its redacted text. The deduplication key hashes the result of normalizing and case-folding that text, so case variants can share a key and still have different content hashes. The first document for each key becomes its representative. Early rejections skip later stages.
PythonIn [7]Expand
kept: list[dict[str, Any]] = []
seen_exact: dict[str, str] = {}
for raw in raw_docs:
raw_text = raw["text"]
raw_hash = sha256_text(raw_text)
doc_id = "doc-" + short_hash(
sha256_text(raw["source_id"] + "\0" + normalize_text(raw_text)), 12
)
log_event(
doc_id,
"ingest",
"collect",
"accept",
raw_hash,
raw_hash,
source_id=raw["source_id"],
uri=raw["uri"],
domain=raw["domain"],
)
normalized = normalize_text(raw_text)
norm_hash = sha256_text(normalized)
log_event(
doc_id,
"normalize",
"unicode_normalize",
"transform",
raw_hash,
norm_hash,
)
if raw["lang"] != "en":
log_event(
doc_id,
"language_id",
"language_filter",
"drop",
norm_hash,
None,
detected_lang=raw["lang"],
policy="english_only",
)
continue
log_event(
doc_id,
"language_id",
"language_filter",
"keep",
norm_hash,
norm_hash,
detected_lang=raw["lang"],
policy="english_only",
)
score = quality_score(normalized)
if score < 0.08:
log_event(
doc_id,
"quality_filter",
"heuristic_quality",
"drop",
norm_hash,
None,
score=round(score, 4),
threshold=0.08,
)
continue
log_event(
doc_id,
"quality_filter",
"heuristic_quality",
"keep",
norm_hash,
norm_hash,
score=round(score, 4),
threshold=0.08,
)
redacted, n_pii = redact_pii(normalized)
pii_hash = sha256_text(redacted)
log_event(
doc_id,
"pii_redaction",
"regex_redaction",
"transform",
norm_hash,
pii_hash,
replacements=n_pii,
detector="regex-demo-v1",
)
dedup_key = sha256_text(normalize_text(redacted).casefold())
if dedup_key in seen_exact:
log_event(
doc_id,
"exact_dedup",
"exact_content_dedup",
"drop",
pii_hash,
None,
duplicate_of=seen_exact[dedup_key],
dedup_key=short_hash(dedup_key),
)
continue
seen_exact[dedup_key] = doc_id
log_event(
doc_id,
"exact_dedup",
"exact_content_dedup",
"keep",
pii_hash,
pii_hash,
dedup_key=short_hash(dedup_key),
)
kept.append(
{
"doc_id": doc_id,
"source_id": raw["source_id"],
"domain": raw["domain"],
"text": redacted,
"content_hash": pii_hash,
}
)ConsoleOut [8]Expand
Events recorded: 43
Documents kept: 5
Kept domains: Counter({'public': 2, 'news': 1, 'science': 1, 'code': 1})The event log records both accepted and rejected decisions from the run.
- The English-only rule dropped the Spanish document before quality scoring.
- The code snippet cleared the quality threshold, and the spam document failed it.
- Exact deduplication dropped the mirror.
- The redactor transformed the document with PII and kept the redacted version.
The shared event schema lets you query these outcomes across stages.
The event log can be projected into a document-by-stage decision matrix, which makes positive and negative provenance visible at a glance. Each row is a document and each column is a pipeline stage.
PythonIn [9]Expand
import numpy as np
stage_order = [
"ingest",
"normalize",
"language_id",
"quality_filter",
"pii_redaction",
"exact_dedup",
]
decision_code = {"drop": 0, "transform": 1, "accept": 2, "keep": 2}
doc_order = []
for event in event_log:
if event["doc_id"] not in doc_order:
doc_order.append(event["doc_id"])
decision_matrix = np.full((len(doc_order), len(stage_order)), np.nan)
for event in event_log:
if event["stage"] in stage_order and event["decision"] in decision_code:
row = doc_order.index(event["doc_id"])
col = stage_order.index(event["stage"])
decision_matrix[row, col] = decision_code[event["decision"]]
decision_matrix_masked = np.ma.masked_invalid(decision_matrix)VisualizationOut [10]Expand

Let's inspect the first few events and verify the hash chain.
PythonIn [11]Expand
events_preview = pd.DataFrame(event_log)[
["seq", "doc_id", "stage", "activity", "decision", "params"]
]
events_preview["params"] = events_preview["params"].astype(str)| seq | doc_id | stage | activity | decision | params | |
|---|---|---|---|---|---|---|
| 0 | 1 | doc-6bd4bf650451 | ingest | collect | accept | {'source_id': 'web-001', 'uri': 'https://examp... |
| 1 | 2 | doc-6bd4bf650451 | normalize | unicode_normalize | transform | {} |
| 2 | 3 | doc-6bd4bf650451 | language_id | language_filter | keep | {'detected_lang': 'en', 'policy': 'english_only'} |
| 3 | 4 | doc-6bd4bf650451 | quality_filter | heuristic_quality | keep | {'score': 0.275, 'threshold': 0.08} |
| 4 | 5 | doc-6bd4bf650451 | pii_redaction | regex_redaction | transform | {'replacements': 0, 'detector': 'regex-demo-v1'} |
| 5 | 6 | doc-6bd4bf650451 | exact_dedup | exact_content_dedup | keep | {'dedup_key': 'dbb04bb66a83'} |
| 6 | 7 | doc-570fe57e3d3a | ingest | collect | accept | {'source_id': 'web-002', 'uri': 'https://mirro... |
| 7 | 8 | doc-570fe57e3d3a | normalize | unicode_normalize | transform | {} |
| 8 | 9 | doc-570fe57e3d3a | language_id | language_filter | keep | {'detected_lang': 'en', 'policy': 'english_only'} |
| 9 | 10 | doc-570fe57e3d3a | quality_filter | heuristic_quality | keep | {'score': 0.275, 'threshold': 0.08} |
The preview shows the sequence of decisions for the first documents. The params column contains hashes, thresholds, and source identifiers. In production, you would store this in a columnar event store or a relational database, not a Python list. The schema, not the storage engine, is the important part. A schema that captures the right distinctions transfers cleanly from a toy list to a distributed warehouse; a schema that does not cannot be rescued by better storage.
PythonIn [13]Expand
ok, bad_seq = verify_chain(event_log)ConsoleOut [14]Expand
Original chain valid: True, first bad event: None
ConsoleOut [15]Expand
Tampered chain valid: False, first bad event: 4
The original chain passes the internal check. A change to event 4's score fails when the verifier recomputes its digest. The next event alone directly carries the old digest. If only event 4's digest is updated, event 5's predecessor check fails. Detecting a consistent replacement or a truncated suffix requires a trusted expected checkpoint for the portion being verified and its expected scope.
The funnel view shows how many unique documents survived each stage. This is not a token count and not a training-example count. It is a document count, which is the right unit for asking whether a filter is removing too much. Counting tokens would mix in document-length effects; counting examples would mix in supervision choices. Document counts isolate the curation question.
PythonIn [16]Expand
funnel_stages = [
"ingest",
"normalize",
"language_id",
"quality_filter",
"pii_redaction",
"exact_dedup",
]
funnel_rows = []
for stage in funnel_stages:
at_stage = {
event["doc_id"] for event in event_log if event["stage"] == stage
}
dropped = {
event["doc_id"]
for event in event_log
if event["stage"] == stage and event["decision"] == "drop"
}
funnel_rows.append({"stage": stage, "documents": len(at_stage - dropped)})
funnel_df = pd.DataFrame(funnel_rows)| stage | documents | |
|---|---|---|
| 0 | ingest | 8 |
| 1 | normalize | 8 |
| 2 | language_id | 7 |
| 3 | quality_filter | 6 |
| 4 | pii_redaction | 6 |
| 5 | exact_dedup | 5 |
Eight documents enter and all eight survive normalization. Seven survive language filtering and six survive quality filtering. All six reach the end of redaction, and five survive exact deduplication. The duplicate is gone, but its source record and rejection event remain. That last point is easy to miss: the funnel counts five survivors, but the log retains the full history of all eight, which is what lets you reconstruct why the other three are missing.
Mixing and Manifest Commitments
A mixture plan records intended token shares, a token budget, and any sampling policy or repetition targets. Changing the mixture the learner consumes can change the trained model. Store both the plan and the consumed-input records so you can investigate whether the planned change reached training.
For this token budget, divide each domain's weight among its retained documents and normalize the row weights. These normalized weights are target token shares, even though the fixture field is named sampling_weight. Multiplying by the token budget and rounding gives each row's target. If you instead sample whole documents by these weights, the expected token shares also depend on document lengths.
PythonIn [18]Expand
TOTAL_TOKENS = 10_000
SEQ_LEN = 8
domain_weights = {"news": 0.40, "science": 0.30, "code": 0.20, "public": 0.10}
doc_tokens = {doc["doc_id"]: tokenize(doc["text"]) for doc in kept}
domain_counts = Counter(doc["domain"] for doc in kept)
mixture_rows = []
for doc in kept:
raw_weight = domain_weights[doc["domain"]] / domain_counts[doc["domain"]]
mixture_rows.append(
{
"doc_id": doc["doc_id"],
"source_id": doc["source_id"],
"domain": doc["domain"],
"doc_token_count": len(doc_tokens[doc["doc_id"]]),
"raw_weight": raw_weight,
"content_hash": doc["content_hash"],
}
)
weight_sum = sum(row["raw_weight"] for row in mixture_rows)
for row in mixture_rows:
row["sampling_weight"] = row["raw_weight"] / weight_sum
row["expected_tokens"] = round(row["sampling_weight"] * TOTAL_TOKENS)
row["epochs"] = row["expected_tokens"] / max(1, row["doc_token_count"])
mix_config = {
"domain_weights": domain_weights,
"total_token_budget": TOTAL_TOKENS,
"sequence_length": SEQ_LEN,
}
config_hash = sha256_text(canonical_json(mix_config))
manifest_root = merkle_root(
[row["content_hash"] for row in mixture_rows] + [config_hash]
)
for row in mixture_rows:
log_event(
row["doc_id"],
"mixture",
"weighted_sampling_manifest",
"include",
row["content_hash"],
row["content_hash"],
sampling_weight=round(row["sampling_weight"], 4),
expected_tokens=row["expected_tokens"],
manifest_root=manifest_root,
)
mixture_df = pd.DataFrame(mixture_rows)[
[
"doc_id",
"domain",
"doc_token_count",
"sampling_weight",
"expected_tokens",
"epochs",
]
]| doc_id | domain | doc_token_count | sampling_weight | expected_tokens | epochs | |
|---|---|---|---|---|---|---|
| 0 | doc-6bd4bf650451 | news | 24 | 0.40 | 4000 | 166.67 |
| 1 | doc-dd10f119f2fb | science | 21 | 0.30 | 3000 | 142.86 |
| 2 | doc-bcb940d2e6f2 | code | 12 | 0.20 | 2000 | 166.67 |
| 3 | doc-90510a22cf34 | public | 18 | 0.05 | 500 | 27.78 |
| 4 | doc-a86ae901cca2 | public | 22 | 0.05 | 500 | 22.73 |
The toy root combines sorted, untagged content and configuration digests. The leaves omit source IDs, row order, leaf roles, and document-level domain and token assignments. Odd-node padding can also hide differences in leaf count. Use typed leaf records and bind their count and fields when the audit needs those distinctions. The hashed training-run record names its configuration digest separately. Record consumed inputs separately from the plan.
The table's sampling_weight, expected_tokens, and epochs fields describe targets and a planned repetition estimate. The bigram demo reads each retained document once in order. Its realized token counts come from the packed positions below. For a distributed job, compare the planned shard IDs with worker consumption records and retain the sampling and exposure counts separately. A finite sample can deviate from its target proportions.
Packing Sequences and Preserving Spans
Sequence length and document-boundary handling depend on the packing and training setup. In this example the packer uses fixed-length windows, combines documents to reduce padding, and retains a map from positions to document owners.
In this example, we read each retained document once and pack its tokens into windows of length eight. Content positions carry a document ID. Padding positions carry no owner. A window can span several documents, and the owner at each position identifies the document that supplied that input token.
PythonIn [20]Expand
packed = []
buffer: list[str] = []
owners: list[str | None] = []
for doc in kept:
for token in doc_tokens[doc["doc_id"]]:
buffer.append(token)
owners.append(doc["doc_id"])
if len(buffer) == SEQ_LEN:
packed.append(
{
"seq_id": f"seq-{len(packed):03d}",
"tokens": tuple(buffer),
"owners": tuple(owners),
}
)
buffer, owners = [], []
if buffer:
while len(buffer) < SEQ_LEN:
buffer.append("<pad>")
owners.append(None)
packed.append(
{
"seq_id": f"seq-{len(packed):03d}",
"tokens": tuple(buffer),
"owners": tuple(owners),
}
)ConsoleOut [21]Expand
Packed sequences: 13
Packed slots: 104
Content tokens: 97
Padding slots: 7
seq-005 ('by', 'nearly', 'two', 'degrees', '.', 'def', 'add', '(')
owners: ('doc-dd10f119f2fb', 'doc-dd10f119f2fb', 'doc-dd10f119f2fb', 'doc-dd10f119f2fb', 'doc-dd10f119f2fb', 'doc-bcb940d2e6f2', 'doc-bcb940d2e6f2', 'doc-bcb940d2e6f2')
seq-007 ('b', 'Contact', 'Jane', 'Doe', 'at', '[', 'EMAIL', ']')
owners: ('doc-bcb940d2e6f2', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34')
seq-009 ('transit', 'schedule', '.', 'Section', '4', '.', '2', 'requires')
owners: ('doc-90510a22cf34', 'doc-90510a22cf34', 'doc-90510a22cf34', 'doc-a86ae901cca2', 'doc-a86ae901cca2', 'doc-a86ae901cca2', 'doc-a86ae901cca2', 'doc-a86ae901cca2')The output lists windows that cross document boundaries. A window can begin at the end of one document and continue into the next. The owners tuple identifies which document contributed each content position. Character offsets can identify the corresponding span when they specify the text version and coordinate system. A training record can also preserve the associated attention masks and position IDs.
The toy assigns sequence IDs by position. Changing the packing policy can change the tokens and source spans under the same label, such as seq-000. Treat that ID as local to the packing run. Keep the packing policy, tokenizer version or digest, and span map with the packed artifact so readers can interpret its input positions.
The packed sequence span map can be visualized as a token-position grid. Each cell identifies the document that owned the token, with padding left blank.
PythonIn [22]Expand
import numpy as np
owner_ids = []
for seq in packed:
for owner in seq["owners"]:
if owner is not None and owner not in owner_ids:
owner_ids.append(owner)
owner_to_code = {owner: index for index, owner in enumerate(owner_ids)}
owner_matrix = np.full((len(packed), SEQ_LEN), np.nan)
for row, seq in enumerate(packed):
for col, owner in enumerate(seq["owners"]):
if owner is not None:
owner_matrix[row, col] = owner_to_code[owner]
owner_matrix_masked = np.ma.masked_invalid(owner_matrix)VisualizationOut [23]Expand

Training and Model Provenance
We now "train" a bigram model from the packed sequences. This is a toy, but it demonstrates the relationship between data lineage and model lineage. The model artifact hash covers the bigram counts, tokenizer name, sequence length, and seed. The training run record ties that model hash to the mixture manifest, configuration hash, code commit, seed, and checkpoint.
PythonIn [24]Expand
bigram_counts = Counter()
bigram_sources = defaultdict(set)
boundary_bigrams = set()
for seq in packed:
for i in range(len(seq["tokens"]) - 1):
left, right = seq["tokens"][i], seq["tokens"][i + 1]
if left == "<pad>" or right == "<pad>":
continue
bigram = (left, right)
left_owner, right_owner = seq["owners"][i : i + 2]
bigram_counts[bigram] += 1
bigram_sources[bigram].update((left_owner, right_owner))
if left_owner != right_owner:
boundary_bigrams.add(bigram)
model_payload = {
"tokenizer": "regex-word-punct-v1",
"sequence_length": SEQ_LEN,
"seed": 13,
"bigrams": sorted(
[[left, right, count] for (left, right), count in bigram_counts.items()]
),
}
model_hash = sha256_text(canonical_json(model_payload))
training_run = {
"run_id": "run-demo-001",
"model_hash": model_hash,
"manifest_root": manifest_root,
"config_hash": config_hash,
"code_commit": "demo-abc123",
"seed": 13,
"checkpoint": "ckpt-demo-0001",
}
training_run_hash = sha256_text(canonical_json(training_run))ConsoleOut [25]Expand
Distinct bigrams: 84 Model artifact hash: 10284620907afae6 Training run hash: fe9194e63363e1ea
The model hash commits to the serialized payload of bigram counts, tokenizer name, sequence length, and seed. The training-run hash commits to the run record, which includes the model hash, manifest root, configuration hash, code commit, seed, checkpoint, and run identifier.
If the code commit or run identifier changes while the model payload stays the same, only the training-run hash changes. A different recorded seed changes both serialized records. Changes to raw inputs can leave the model hash unchanged. For example, inputs with different whitespace can produce the same canonical text and bigram counts. Compare the payloads and the upstream records to find which fields changed.
The owner map lets us inspect where the two tokens of a bigram came from. We show the first five distinct pairs encountered, then any remaining pairs that occur across document boundaries.
ConsoleOut [26]Expand
'The' 'city': count=1, docs=['doc-6bd4bf650451'] 'city' 'council': count=1, docs=['doc-6bd4bf650451'] 'council' 'approved': count=1, docs=['doc-6bd4bf650451'] 'approved' 'the': count=1, docs=['doc-6bd4bf650451'] 'the' 'new': count=1, docs=['doc-6bd4bf650451'] '.' 'Section': count=1, docs=['doc-90510a22cf34', 'doc-a86ae901cca2'] '.' 'def': count=1, docs=['doc-bcb940d2e6f2', 'doc-dd10f119f2fb'] 'b' 'Contact': count=1, docs=['doc-90510a22cf34', 'doc-bcb940d2e6f2']
All 84 distinct bigrams in the toy have count one. The first five shown come from the transit document, and the three boundary examples show two document IDs each. A neural training pipeline can choose to record which shards each step consumed and which checkpoints follow those steps. Such links trace recorded dependencies. Estimating a document's causal influence on a parameter update requires separate evidence.
Evaluation Provenance and Contamination
Record the benchmark edition, split and any sampled subset with the prompt template, decoding configuration and scoring code. This identifies the examples and protocol behind a reported score. Exposure to benchmark content during training can inflate its score. The toy screen below measures literal five-gram overlap before packing.
We construct two positive controls from the retained transit document. The first copies it in full, and the second copies one sentence. The third example uses unrelated text as a negative control. The check compares their five-grams with those in the retained documents before packing.
where:
- : an evaluation example
- : the set of training documents
- : the set of contiguous 5-grams in the evaluation example
- : the set of contiguous 5-grams in training document
- : the union of all 5-grams appearing in any training document
- : the number of elements in a set
The numerator counts the evaluation 5-grams that also appear in training; the denominator is the total number of evaluation 5-grams. The result is a fraction between 0 and 1 for a nonempty evaluation five-gram set. When the set is empty, the fixture uses zero for its report, which indicates no available five-gram comparison. A paraphrase, translation, or code rewrite can evade exact matching when it preserves no five-grams. Common phrases can create matches without demonstrating that evaluation data entered training. Use the result to decide which examples need inspection.
PythonIn [27]Expand
eval_examples = [
{
"eval_id": "eval-001",
"task": "transit",
"text": raw_docs[0]["text"],
},
{
"eval_id": "eval-002",
"task": "transit",
"text": "The plan adds bus lanes and extends service hours across the region.",
},
{
"eval_id": "eval-003",
"task": "cooking",
"text": "A recipe for lentil soup with carrots and thyme.",
},
]
N_EVAL = 5
REVIEW_OVERLAP_THRESHOLD = 0.2
train_ngrams = set()
train_ngram_sources = defaultdict(set)
for doc in kept:
toks = doc_tokens[doc["doc_id"]]
for i in range(len(toks) - N_EVAL + 1):
ngram = tuple(toks[i : i + N_EVAL])
train_ngrams.add(ngram)
train_ngram_sources[ngram].add(doc["doc_id"])
contam_rows = []
for example in eval_examples:
toks = tokenize(example["text"])
eval_ngrams = {
tuple(toks[i : i + N_EVAL])
for i in range(max(0, len(toks) - N_EVAL + 1))
}
hits = eval_ngrams & train_ngrams
overlap = len(hits) / len(eval_ngrams) if eval_ngrams else 0.0
source_docs = set()
for ngram in hits:
source_docs |= train_ngram_sources[ngram]
contam_rows.append(
{
"eval_id": example["eval_id"],
"task": example["task"],
"eval_ngrams": len(eval_ngrams),
"matched_ngrams": len(hits),
"overlap_fraction": overlap,
"source_docs": sorted(source_docs),
"status": "flag_for_review"
if overlap > REVIEW_OVERLAP_THRESHOLD
else "below_threshold",
}
)
contam_df = pd.DataFrame(contam_rows)| eval_id | task | eval_ngrams | matched_ngrams | overlap_fraction | source_docs | status | |
|---|---|---|---|---|---|---|---|
| 0 | eval-001 | transit | 20 | 20 | 1.0 | [doc-6bd4bf650451] | flag_for_review |
| 1 | eval-002 | transit | 9 | 9 | 1.0 | [doc-6bd4bf650451] | flag_for_review |
| 2 | eval-003 | cooking | 6 | 0 | 0.0 | [] | below_threshold |
All five-grams in both constructed positive controls appear in the retained transit document. The unrelated control has zero overlap. The controls exercise the screen without estimating leakage or performance for a benchmark edition or split. For a real benchmark, state which examples were screened and inspect matches across n-gram lengths and at sentence or document granularity where appropriate. Check task-specific artifacts such as answer formatting, prompt overlap, and label leakage separately.
The fixture flags overlap strictly above 0.2 for review and returns the matching document IDs. A low score leaves other forms of leakage open. In an audit, use these IDs to join to ingestion records and look for source, license, or consent evidence. The separate document trace below illustrates the lookup for the redacted web-006 item.
Release Records and Lineage Queries
A release record ties the model, training run, data manifest, evaluation report, and known limitations into one bundle. It should include the model ID, version, checkpoint, training run hash, manifest root, evaluation set version, maximum contamination overlap, license summary, and any known issues. The record is the public face of the provenance graph, and it should be readable by someone who was not on the team.
PythonIn [29]Expand
release = {
"model_id": "tiny-bigram-demo",
"release_version": "0.1.0",
"training_run_hash": training_run_hash,
"manifest_root": manifest_root,
"eval_set": "demo-eval-v1",
"max_eval_overlap": float(contam_df["overlap_fraction"].max()),
}
release_hash = sha256_text(canonical_json(release))ConsoleOut [30]Expand
Release artifact hash: 6fdc9fdf1db6ea02 Maximum evaluation overlap: 1.00
The release digest covers the serialized record shown above. For evaluation this includes the set label and maximum overlap, which leave the item bytes and full report outside the commitment. A graph edge records a dependency. To bind a separate report, model card, or checkpoint file, include its content digest in this record or a referenced record whose digest is itself bound here. The toy run names a checkpoint by identifier. Verify detached files by comparing their computed digests with trusted expected values.
The graph below records artifact inputs. Packing uses the ordered kept rows, tokenizer, and the sequence length in the mix configuration. The overlap screen uses both the evaluation examples and the kept documents. The backward query follows paths from the release through these graph nodes. Verify its run association separately against the run record named by the digest.
PythonIn [31]Expand
lineage_edges = {
"release:tiny-bigram-demo": [
"model:bigram-demo",
"eval:demo-v1",
"manifest:mixture",
],
"model:bigram-demo": ["dataset:packed", "config:training"],
"dataset:packed": [
"corpus:filtered",
"tokenizer:regex-word-punct-v1",
"config:mix",
],
"manifest:mixture": ["corpus:filtered", "config:mix"],
"corpus:filtered": ["corpus:raw"],
"eval:demo-v1": ["corpus:eval-raw", "corpus:filtered"],
}
def ancestors(node: str, edges: dict[str, list[str]]) -> set[str]:
seen: set[str] = set()
stack = list(edges.get(node, []))
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
stack.extend(edges.get(current, []))
return seenConsoleOut [32]Expand
Ancestors of the release: config:mix config:training corpus:eval-raw corpus:filtered corpus:raw dataset:packed eval:demo-v1 manifest:mixture model:bigram-demo tokenizer:regex-word-punct-v1
The query returns the evaluation set node, the model, packed dataset, mixture manifest, filtered corpus, raw corpus, tokenizer, training config, mix config, and evaluation corpus. In a full system, these nodes would carry content hashes, timestamps, owners, and access controls. The graph is the skeleton; the metadata on each node is the evidence.
We can also trace one document. The trace for web-006 follows seven stages from ingestion through mixture inclusion. Its redaction event logs two replacements, one for an email address and one for a phone number. The name stays in the text. Other documents also have a redaction-stage event marked transform, even when the replacement count is zero.
PythonIn [33]Expand
def trace_doc(doc_id: str) -> list[dict[str, Any]]:
return [event for event in event_log if event["doc_id"] == doc_id]
pii_doc_id = next(
event["doc_id"]
for event in event_log
if event["stage"] == "ingest"
and event["params"].get("source_id") == "web-006"
)
pii_trace = pd.DataFrame(trace_doc(pii_doc_id))[
["seq", "stage", "activity", "decision", "params"]
]
pii_trace["params"] = pii_trace["params"].astype(str)| seq | stage | activity | decision | params | |
|---|---|---|---|---|---|
| 0 | 32 | ingest | collect | accept | {'source_id': 'web-006', 'uri': 'https://examp... |
| 1 | 33 | normalize | unicode_normalize | transform | {} |
| 2 | 34 | language_id | language_filter | keep | {'detected_lang': 'en', 'policy': 'english_only'} |
| 3 | 35 | quality_filter | heuristic_quality | keep | {'score': 0.225, 'threshold': 0.08} |
| 4 | 36 | pii_redaction | regex_redaction | transform | {'replacements': 2, 'detector': 'regex-demo-v1'} |
| 5 | 37 | exact_dedup | exact_content_dedup | keep | {'dedup_key': '5a523fbaf685'} |
| 6 | 47 | mixture | weighted_sampling_manifest | include | {'sampling_weight': 0.05, 'expected_tokens': 5... |
The mixture event links the redacted document to the manifest root. The run record references that root and names the checkpoint. To verify the release's link to the run, compare its training-run digest with the hash of the retained run record. The graph above traverses artifact dependencies, and the digest lookup is a separate step. Use the consumption record to see which inputs reached the run. Linking an output to a document's causal effect requires separate attribution evidence.
Visualizing the Funnel and Contamination
The funnel figure summarizes the document counts at each stage. It is a presentation of values computed above, not a new computation. The counts are unique documents, not tokens or examples. The visualization is for humans scanning for anomalies; the underlying tables and logs are for machines and auditors.
VisualizationOut [35]Expand

The drop from eight to five documents is visible. The figure does not show why each document was dropped. The event log does. A reader can use the figure to spot a large drop and then query the log for the reason. That division of labor, visual triage plus machine-readable detail, is how provenance dashboards should work.
The figure shows five-gram overlap against the retained documents. It highlights the full copy and copied sentence. The unrelated control has zero matching five-grams.
VisualizationOut [36]Expand

For the two constructed positive controls, the audit record lists the retained document IDs supplying the matching five-grams. The unrelated control has zero matching five-grams.
Limitations and Impact
Lineage is expensive. Every stage needs an identifier, a schema, storage, and a query path. At web scale, recording an event per document per stage can produce billions of rows. Keep full text out of the event log when access or retention rules require a separate store. The practical compromise is to store hashes, reason codes, model versions, and aggregate counts, then keep raw text in access-controlled storage with retention limits. This means provenance is often partial. A filter event can preserve a recorded decision while the removed text stays outside the event store. Partial provenance is still far better than none, but it must state its limits so that auditors know what they can and cannot conclude.
Source URLs and identifiers can expose sensitive information. Published plain digests can reveal whether a predictable candidate appears in a set. The ICO guidance on pseudonymisation explains how the space of possible inputs affects disclosure risk. Apply access controls and redaction to records that carry sensitive values. A valid signature under the verifier's trust policy checks the integrity of the bytes it covers. A signed origin claim or an observed license signal still needs independent evidence before it can support conclusions about origin, permissions, or quality.
Contamination checks are approximate. Literal n-gram overlap can retrieve near duplicates that preserve enough matching spans. Wording changes, translation, summarization, and code transformations can lower the overlap. A match on a common phrase alone cannot establish leakage. A release decision should combine multiple checks: exact hash matching, n-gram overlap at several lengths, semantic similarity, canary strings, and manual review of high-risk benchmarks. The result should be reported with the method, threshold, and known false-positive rate. Reporting only a pass/fail hides exactly the uncertainty that a careful reader needs.
Reproducibility is not the same as provenance. A hash tells you which artifact you have. It does not recreate the training run. You also need code commits, dependency versions, hardware details, random seeds, data order, and deterministic flags. Even then, distributed training may be nondeterministic. The honest claim is often "we can reproduce the data manifest and the evaluation, and we can explain likely sources of run-to-run variation," not "we can reproduce the weights bit for bit." Provenance supports that honest claim by making the inputs and conditions auditable.
Lineage can shorten an investigation by narrowing the search to the recorded inputs to a checkpoint, the filter decisions, and the released artifacts. Source records help identify contributors and the downstream artifacts a deletion request may affect. Evaluation records let auditors check how a benchmark ran and whether it overlapped with the training corpus. Connecting a particular output to the causal effect of a particular document requires separate evidence.
The impact of bad lineage is equally large. A model can be trained on a benchmark, pass the benchmark, and ship with a false capability claim. A licensed dataset can be mixed into a release with no record of the license. A PII redaction can fail on one branch and leave no trace. A deletion request can be answered by deleting a row while the model still carries the influence. Use these cases to plan the checks. Preserve source-to-run links, verify filter coverage on each branch, and inspect downstream artifacts when a deletion request changes the input set.
These chapters continue the discussion in Data Governance, Provenance, and Synthetic Ecosystems.
- Licensing, Consent, and Data-Use Signals examines how terms and consent signals attach to sources and propagate through the pipeline.
- Attribution and Training-Data Transparency explains the evidence needed to connect training data with model behavior.
- Synthetic Data Pipelines adds generators, prompts, and decoding configurations to the provenance record.
- Recursive Training and Model Collapse examines lineage when models train on generated data.
- Data Audits and Release Governance brings these records into a release audit.
Summary
Dataset lineage and provenance record where a document came from, how it was processed, which mixture included it, which packed sequence carried its tokens, and which runs and releases reference those records. Evaluation provenance records which inputs, settings, and scoring rules produced an evaluation result.
The core design choices are:
- Use source-qualified document IDs and separate content hashes.
- Version every transformation, especially normalization and tokenization.
- Record events, including rejections and redactions, not just final state.
- Chain event hashes for tamper evidence, and use Merkle roots for dataset commitments.
- Preserve document spans through packing so each packed input token can be traced to its recorded source.
- Tie checkpoints to training runs, manifests, code, configuration, and seeds.
- Treat evaluation as a provenance-bearing artifact, with benchmark versions, prompts, decoding settings, and contamination checks.
- Publish release records that connect model cards, data cards, manifests, and known limitations.
Traceable data and run records support reproducibility checks, benchmark audits, and investigations into deletion requests or pipeline failures. Conclusions about reproducibility, legal compliance, and scientific validity also depend on the other evidence each question requires.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about dataset lineage and provenance.
Dataset Lineage and Provenance
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!