Dataset Lineage and Provenance › Worked Example: From Eight Documents to a Released Model

Michael BrenndoerferNovember 26, 202610 min read
Language AI HandbookAll chapters
Part 21 of 67Data Governance, Provenance, and Synthetic Ecosystems
Chapter 149Dataset Lineage and Provenance › Worked Example: From Eight Documents to a Released Model
Reading section 8 of 17 · Worked Example: From Eight Documents to a Released Model · 10 minSection 8 of 17 · 10 min

Section 8 of 17 · 10 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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, None

We 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Heatmap of per-document provenance decisions across six pipeline stages.
Per-document provenance decisions across pipeline stages. Rows are documents and columns are stages, with colors distinguishing drops from transformations and accepted artifacts. This view reveals at a glance which stage removed each document and where transformations occurred.

Let's inspect the first few events and verify the hash chain.

PythonIn [11]
CollapseExpand
events_preview = pd.DataFrame(event_log)[
    ["seq", "doc_id", "stage", "activity", "decision", "params"]
]
events_preview["params"] = events_preview["params"].astype(str)
Out[12]:
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]
CollapseExpand
ok, bad_seq = verify_chain(event_log)
ConsoleOut [14]
CollapseExpand
Original chain valid: True, first bad event: None
ConsoleOut [15]
CollapseExpand
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]
CollapseExpand
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)
Out[17]:
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.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy