Data Audits and Release Governance › Worked Example
Language AI HandbookAll chapters We will build a miniature governance stack for a synthetic corpus of 50,000 documents. The scenario has three phases.
Phase 1, measurement. We plant known sensitive content so that we have ground truth, then evaluate two detectors against it. The first is a naive regex stack. The second adds a Luhn checksum validation to the card-number matcher. We will see the precision difference that a ten-line validator buys.
Phase 2, sampling. We draw a simple random sample, compute a Wilson interval, and compare it against a detector-stratified design at the same human review budget.
Phase 3, governance. We hash the corpus and toy token shards, assemble a manifest, evaluate a policy against a computed sensitive-content bound and three supplied example gate values, and identify candidate releases for a reported document by matching run configurations to one indexed source snapshot. Use loader records to check whether the run consumed the document.
We can enumerate this synthetic corpus and compare the estimates against the true prevalence. For an audit whose budget only covers a sample, the sampling design determines which population conclusions the reviewed cases support.
Sampling arithmetic
We start with the formulas, so the sample sizes in the rest of the example are derived rather than asserted.
PythonIn [5]Expand
from math import ceil, sqrt
import pandas as pd
Z = {0.90: 1.6449, 0.95: 1.9600, 0.99: 2.5758}
def n_for_proportion(p, margin, confidence=0.95, population=None):
"""Documents needed to estimate a proportion within +/- margin."""
z = Z[confidence]
n0 = z**2 * p * (1 - p) / margin**2
if population is None:
return n0
return n0 / (1 + (n0 - 1) / population)
def wilson_interval(k, n, confidence=0.95):
"""Score interval for a binomial proportion; behaves at small k."""
z = Z[confidence]
phat = k / n
denom = 1 + z**2 / n
centre = (phat + z**2 / (2 * n)) / denom
half = z * sqrt(phat * (1 - phat) / n + z**2 / (4 * n**2)) / denom
return max(0.0, centre - half), min(1.0, centre + half)
N_CORPUS = 50_000Now the table. We vary the assumed prevalence and the target margin, and report how much of the corpus would need human review.
PythonIn [6]Expand
rows = []
for p in [0.5, 0.05, 0.01, 0.0075, 0.001]:
for margin in [0.02, 0.005, 0.001]:
n = ceil(n_for_proportion(p, margin, population=N_CORPUS))
rows.append(
{
"prevalence": p,
"margin": margin,
"n_required": n,
"share_of_corpus": n / N_CORPUS,
}
)
sample_size_table = pd.DataFrame(rows)| margin | 0.001 | 0.005 | 0.020 |
|---|---|---|---|
| prevalence | |||
| 0.0010 | 3565 | 154 | 10 |
| 0.0075 | 18192 | 1119 | 72 |
| 0.0100 | 21602 | 1477 | 95 |
| 0.0500 | 39247 | 6370 | 453 |
| 0.5000 | 47526 | 21725 | 2292 |
For the table row with prevalence 0.1%, the normal planning formula gives 10 documents at a two-percentage-point margin after rounding up, and 3,565 documents at a 0.1-percentage-point margin. The first number is a planning calculation with an absolute margin much larger than the assumed rate. It is not a reliable normal-coverage guarantee for rare events.
That asymmetry is the whole story of rare-content auditing. The margin you can afford determines whether the answer is informative at all.
ConsoleOut [8]Expand
Corpus size: 50,000 documents prevalence 0.0500 -> 39,247 documents (78.5% of corpus) prevalence 0.0100 -> 21,602 documents (43.2% of corpus) prevalence 0.0010 -> 3,565 documents (7.1% of corpus)
The figure below makes the scaling visible across a continuous range of margins.
PythonIn [9]Expand
margin_grid = np.logspace(-3.3, -1.3, 60)
prevalence_levels = [0.5, 0.05, 0.01, 0.0075]
sample_size_curves = {
p: np.array(
[n_for_proportion(p, m, population=N_CORPUS) for m in margin_grid]
)
for p in prevalence_levels
}VisualizationOut [10]Expand

The dashed line is the corpus size. No sampling plan can cross it, and any plan that approaches it is really a census with extra steps.
Building a corpus with known ground truth
Now we plant content so that we can measure detector behaviour exactly.
PythonIn [11]Expand
import re
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PHONE_RE = re.compile(r"\(\d{3}\)\s?\d{3}-\d{4}")
CARD_RE = re.compile(r"\b\d{16}\b")
def luhn_ok(number):
"""Check the Luhn checksum of a matched string of 16 decimal digits."""
if len(number) != 16 or not number.isdecimal():
return False
digits = [int(c) for c in number]
total = 0
for i, d in enumerate(reversed(digits)):
if i % 2 == 1: # every second digit from the right
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def luhn_check_digit(payload):
"""Given 15 payload digits, compute the 16th so that luhn_ok() passes."""
total = 0
for i, d in enumerate(reversed(payload)):
if i % 2 == 0:
d *= 2
if d > 9:
d -= 9
total += d
return (10 - total % 10) % 10A sanity check on the checksum, using a well-known test card number and a number that fails.
ConsoleOut [12]Expand
4111111111111111 valid? True 1234567812345678 valid? False
The first passes, the second fails. That single bit of validation is what separates a precision of 0.47 from a precision of 1.00 in a moment.
Now the generator. Each document is assigned a kind, and the kind determines the text and the ground-truth label.
PythonIn [13]Expand
rng = np.random.default_rng(SEED)
FIRST = ["ada", "grace", "alan", "katherine", "linus", "barbara"]
LAST = ["lovelace", "hopper", "turing", "johnson", "torvalds", "liskov"]
DOMAINS = ["example.org", "example.com", "mail.example.net"]
BENIGN = [
"The committee met on Tuesday to review the quarterly budget.",
"She published a short note about soil chemistry in the newsletter.",
"The bridge reopened after two weeks of structural repairs.",
"Attendance at the evening lecture was higher than expected.",
"The archive holds forty years of municipal planning records.",
"Their recipe for rye bread calls for a long, slow ferment.",
"The museum extended the exhibition through the end of March.",
"Local rainfall in April was well above the ten-year average.",
]
KIND_PROBS = {
"email": 0.0015, # plain email address, sensitive
"email_masked": 0.0040, # obfuscated email, sensitive but undetectable by regex
"phone": 0.0010, # phone number, sensitive
"card_valid": 0.0010, # Luhn-valid card number, sensitive
"card_invalid": 0.0040, # 16-digit order id that fails Luhn, NOT sensitive
}
KINDS = list(KIND_PROBS) + ["clean"]
PROBS = list(KIND_PROBS.values()) + [1 - sum(KIND_PROBS.values())]
def make_doc(kind):
base = " ".join(rng.choice(BENIGN, size=int(rng.integers(1, 3))))
if kind == "email":
user = f"{rng.choice(FIRST)}.{rng.choice(LAST)}{rng.integers(1, 999)}"
return base + f" Write to {user}@{rng.choice(DOMAINS)} for access."
if kind == "email_masked":
domain = str(rng.choice(DOMAINS)).replace(".", " [dot] ")
return base + f" Write to {rng.choice(FIRST)} [at] {domain} for access."
if kind == "phone":
return base + (
f" Call ({rng.integers(200, 999)}) "
f"{rng.integers(100, 999)}-{rng.integers(1000, 9999)}."
)
if kind == "card_valid":
payload = [
int(d) for d in "".join(str(rng.integers(0, 10)) for _ in range(15))
]
num = "".join(map(str, payload)) + str(luhn_check_digit(payload))
return base + f" Card on file: {num}. Renewal due."
if kind == "card_invalid":
num = "".join(str(rng.integers(0, 10)) for _ in range(16))
while luhn_ok(num):
num = num[:-1] + str((int(num[-1]) + 1) % 10)
return base + f" Order reference {num} was archived."
return base
kinds = rng.choice(KINDS, size=N_CORPUS, p=PROBS)
documents = [
{"doc_id": f"d{i:06d}", "kind": str(k), "text": make_doc(str(k))}
for i, k in enumerate(kinds)
]
SENSITIVE_KINDS = {"email", "email_masked", "phone", "card_valid"}
for d in documents:
d["sensitive_true"] = d["kind"] in SENSITIVE_KINDS| kind | documents | sensitive | share | |
|---|---|---|---|---|
| 0 | card_invalid | 193 | False | 0.3860% |
| 1 | card_valid | 52 | True | 0.1040% |
| 2 | clean | 49435 | False | 98.8700% |
| 3 | 78 | True | 0.1560% | |
| 4 | email_masked | 198 | True | 0.3960% |
| 5 | phone | 44 | True | 0.0880% |
In the synthetic corpus, 0.744% of documents are labeled sensitive. More than half of those contain the planted obfuscated email form, which the pattern used below misses. This setup leaves much of the sensitive material in the unflagged stratum.
Two detectors, one checksum apart
PythonIn [15]Expand
def detect_naive(text):
"""Regex only: any 16-digit run counts as a card number."""
return bool(
EMAIL_RE.search(text) or PHONE_RE.search(text) or CARD_RE.search(text)
)
def detect_validated(text):
"""Regex plus checksum: only Luhn-valid 16-digit runs count."""
if EMAIL_RE.search(text) or PHONE_RE.search(text):
return True
for m in CARD_RE.finditer(text):
if luhn_ok(m.group()):
return True
return False
def confusion(y_true, y_pred):
y_true = np.asarray(y_true, dtype=bool)
y_pred = np.asarray(y_pred, dtype=bool)
return (
int((y_true & y_pred).sum()), # tp
int((~y_true & y_pred).sum()), # fp
int((y_true & ~y_pred).sum()), # fn
int((~y_true & ~y_pred).sum()),
) # tnPythonIn [16]Expand
true_labels = [d["sensitive_true"] for d in documents]
detector_stats = {}
detector_rows = []
for name, fn in [
("naive regex", detect_naive),
("Luhn-validated", detect_validated),
]:
preds = [fn(d["text"]) for d in documents]
tp, fp, fn_ct, tn = confusion(true_labels, preds)
tpr = tp / (tp + fn_ct) if (tp + fn_ct) else np.nan
fpr = fp / (fp + tn) if (fp + tn) else np.nan
precision = tp / (tp + fp) if (tp + fp) else np.nan
detector_stats[name] = {
"tp": tp,
"fp": fp,
"fn": fn_ct,
"tn": tn,
"tpr": tpr,
"fpr": fpr,
"precision": precision,
}
detector_rows.append(
{
"detector": name,
"tp": tp,
"fp": fp,
"fn": fn_ct,
"precision": round(precision, 3),
"recall": round(tpr, 3),
"f1": round(2 * precision * tpr / (precision + tpr), 3)
if precision + tpr
else 0.0,
}
)
detector_table = pd.DataFrame(detector_rows)| detector | tp | fp | fn | precision | recall | f1 | |
|---|---|---|---|---|---|---|---|
| 0 | naive regex | 174 | 193 | 198 | 0.474 | 0.468 | 0.471 |
| 1 | Luhn-validated | 174 | 0 | 198 | 1.000 | 0.468 | 0.637 |
Two things are worth pausing on.
First, recall is identical for both detectors. Both detectors catch the same 174 of the 372 planted positives, including all 52 valid card-number examples. The generated card numbers pass the checksum, and the planted order references fail it, so the validator removes only false positive flags in this fixture.
Second, precision moves from about 0.47 to 1.00. The naive detector flags every 16-digit order reference in the corpus. The naive detector flags 193 benign documents in this fixture. The checksum rejects all 193 planted order-ID flags.
The figure below isolates what the checksum changes: the split between true and false positives for each detector.
PythonIn [18]Expand
detector_names = ["naive regex", "Luhn-validated"]
tp_counts = [detector_stats[name]["tp"] for name in detector_names]
fp_counts = [detector_stats[name]["fp"] for name in detector_names]
group_x = np.arange(len(detector_names))
bar_width = 0.36VisualizationOut [19]Expand

In this simulation the validated detector makes true-positive flags and no false-positive flags, so its observed precision is 1.0. This result describes the seeded corpus and the specified detector. An observed zero on a sample by itself does not establish a zero population error rate.
The base-rate collapse
The seeded corpus has 0.744% sensitive documents. The next calculation holds detector rates fixed and varies prevalence to show what happens as positives become rarer.
PythonIn [20]Expand
prevalence_grid = np.logspace(-5.5, -1.0, 200)
precision_curves = {}
for name, s in detector_stats.items():
num = s["tpr"] * prevalence_grid
den = num + s["fpr"] * (1 - prevalence_grid)
precision_curves[name] = np.divide(
num, den, out=np.full_like(den, np.nan), where=den > 0
)VisualizationOut [21]Expand

Holding the fixture's measured rates fixed, the naive detector's precision falls below 50% at about 0.82% prevalence. At 0.01% prevalence, about 1.19% of its flags are positives. The validated detector's measured false-positive rate is zero, so its curve stays at 1.0 wherever it makes positive flags. Treat both curves as conditional on rates that must be checked for the population where the detector is used.
Simple random sampling and the Wilson interval
Now we shift from evaluating a detector to estimating prevalence. We draw 2,000 documents and use their known synthetic labels as a stand-in for human review. A real audit would apply its review protocol to the sampled documents.
PythonIn [22]Expand
n_sample = 2000
sample_idx = rng.choice(N_CORPUS, size=n_sample, replace=False)
sample = [documents[i] for i in sample_idx]
k_sample = int(sum(d["sensitive_true"] for d in sample))
p_hat = k_sample / n_sample
ci_lo, ci_hi = wilson_interval(k_sample, n_sample)
p_true = float(np.mean(true_labels))ConsoleOut [23]Expand
Sample size: 2,000 Positives in sample: 14 Point estimate: 0.7000% 95% Wilson interval: [0.4174%, 1.1716%] True corpus prevalence: 0.7440% Interval contains truth: True Interval width: 0.75 percentage points
The binomial Wilson approximation for this sample without replacement runs from about 0.42% to 1.17%. The interval crosses 1.0%, so it does not support a requirement that prevalence be below that threshold.
Choose the release criterion first. Plan the sample for the precision needed to tell whether the estimated rate is below the threshold.
Stratified review at the same budget
Suppose the same 2,000 human reviews are available, but instead of sampling uniformly we first run the validated detector over all 50,000 documents and split into a flagged stratum and an unflagged stratum. This allocation assumes a nonempty flagged stratum small enough to census while leaving at least two unflagged reviews. With a different detector or budget, choose a design that leaves enough observations in every sampled stratum.
PythonIn [24]Expand
flagged = [d for d in documents if detect_validated(d["text"])]
unflagged = [d for d in documents if not detect_validated(d["text"])]
N1, N0 = len(flagged), len(unflagged)
W1, W0 = N1 / N_CORPUS, N0 / N_CORPUS
n1 = N1 # census of the flagged stratum
n0 = min(n_sample - n1, N0) # remainder to the unflagged stratum
if not 0 < n1 < n_sample or n0 < 2:
raise ValueError(
"This allocation needs a flagged census and two unflagged reviews"
)
p1 = float(np.mean([d["sensitive_true"] for d in flagged]))
s0 = rng.choice(N0, size=n0, replace=False)
p0 = float(np.mean([unflagged[i]["sensitive_true"] for i in s0]))
p_strat = W1 * p1 + W0 * p0
# The flagged stratum is censused and adds no sampling variance.
var_strat = W0**2 * (1 - n0 / N0) * p0 * (1 - p0) / (n0 - 1)
se_strat = sqrt(var_strat)ConsoleOut [25]Expand
Flagged stratum: N=174 reviewed=174 p1=1.0000 Unflagged stratum: N=49,826 reviewed=1,826 p0=0.004929 Stratified estimate: 0.8392% (true: 0.7440%) Normal 95% half-width approximation: 0.314 pp
The validated detector misses the planted obfuscated email form. In this allocation, all sampling variance comes from the unflagged stratum. The displayed half-width uses a normal approximation to illustrate the estimated sampling variance. The release rule below uses a finite-population bound.
Use the known synthetic labels to compare both designs at an equal budget. This comparison uses population rates on both sides, so it does not depend on which positives a particular sample happened to contain.
PythonIn [26]Expand
n_review = n_sample
p0_true = float(np.mean([d["sensitive_true"] for d in unflagged]))
srs_pop_var = N_CORPUS / (N_CORPUS - 1) * p_true * (1 - p_true)
unflagged_pop_var = N0 / (N0 - 1) * p0_true * (1 - p0_true)
design_var_srs = srs_pop_var * (1 / n_review - 1 / N_CORPUS)
design_var_strat = W0**2 * unflagged_pop_var * (1 / n0 - 1 / N0)
half_srs = 1.96 * sqrt(design_var_srs)
half_strat = 1.96 * sqrt(design_var_strat)
# Solve the finite-population SRS variance identity for the review count.
effective_n = 1 / (design_var_strat / srs_pop_var + 1 / N_CORPUS)ConsoleOut [27]Expand
Simple random sampling (n=2,000): half-width 0.369 pp Detector-stratified (n=2,000): half-width 0.282 pp Smallest SRS sample with at least this precision: 3,325
VisualizationOut [28]Expand

Both bars use the true finite-population variances of their estimators for this fixture. Multiplying each design standard error by 1.96 puts the comparison on the same reference scale. The unflagged stratum contributes all of the stratified design's sampling variance because only that stratum was sampled.
Changing detector coverage can alter stratum sizes and outcome rates. Recalculate the comparison at the same review budget when the partition changes. Report the stratum results together with the weighted population estimate.
From audit to manifest
The fixed in-memory fixture yields source-document and toy token-shard hashes. The manifest's crawler, extractor, normalization, deduplication, and production-style filter entries are illustrative metadata. The provenance, licensing, and contamination audit references and values are supplied to demonstrate the release workflow. The sensitive-content estimate and bound come from the fixture reviews.
PythonIn [29]Expand
import hashlib
import json
def sha256_hex(data):
"""SHA-256 hex digest of a string or bytes."""
if isinstance(data, str):
data = data.encode("utf-8")
return hashlib.sha256(data).hexdigest()
MERKLE_SCHEMA = "sorted-digest-multiset-sha256-v1"
def merkle_root(leaves):
"""Commit to a sorted multiset of fixed-size input digests."""
digests = sorted(bytes.fromhex(leaf) for leaf in leaves)
if any(len(digest) != 32 for digest in digests):
raise ValueError("leaves must be SHA-256 digests")
layer = [hashlib.sha256(b"leaf:" + digest).digest() for digest in digests]
while len(layer) > 1:
if len(layer) % 2:
layer.append(layer[-1])
layer = [
hashlib.sha256(b"node:" + layer[i] + layer[i + 1]).digest()
for i in range(0, len(layer), 2)
]
tree_digest = layer[0] if layer else b""
return sha256_hex(
MERKLE_SCHEMA.encode()
+ b":"
+ len(digests).to_bytes(8, "big")
+ tree_digest
)
example_leaves = [sha256_hex(name) for name in ("A", "B", "C")]
assert merkle_root(example_leaves) == merkle_root(reversed(example_leaves))
assert merkle_root(example_leaves) != merkle_root(
example_leaves + [max(example_leaves)]
)PythonIn [30]Expand
SHARD_SIZE = 1000
doc_hashes = {}
doc_shard = {}
shard_hashes = []
tokenized_shard_hashes = []
for start in range(0, N_CORPUS, SHARD_SIZE):
shard = documents[start : start + SHARD_SIZE]
leaves = []
for d in shard:
h = sha256_hex(d["text"])
doc_hashes[d["doc_id"]] = h
doc_shard[d["doc_id"]] = start // SHARD_SIZE
leaves.append(h)
shard_hashes.append(merkle_root(leaves))
# Serialize the toy whitespace tokens as ordered UTF-8 JSON Lines.
token_bytes = "".join(
json.dumps(d["text"].split(), ensure_ascii=False) + "\n" for d in shard
).encode("utf-8")
tokenized_shard_hashes.append(sha256_hex(token_bytes))
source_root = merkle_root(shard_hashes)
tokenized_root = merkle_root(tokenized_shard_hashes)PythonIn [31]Expand
manifest = {
"dataset_id": "ds-2025.06",
"created_utc": "2025-06-11T09:14:00Z",
"document_count": N_CORPUS,
"shard_count": len(shard_hashes),
"shard_size": SHARD_SIZE,
"merkle_schema": MERKLE_SCHEMA,
"source_root": source_root,
"tokenized_root": tokenized_root,
"tokenized_shard_digests_in_index_order": tokenized_shard_hashes,
"pipeline": {
"crawler": "cc-snapshot-2025-04",
"extractor": "trafilatura-1.12",
"dedup": "minhash-lsh-threshold-0.85",
"normalization": "unicode-nfkc-whitespace-collapse",
"filters": ["quality-ppl-120", "toxicity-0.82", "pii-regex-luhn-v3"],
"tokenizer": "toy-whitespace-jsonl-utf8-v1",
},
"audit_refs": [
"audit:sensitive/2025-06-11T09:14Z",
"audit:provenance/2025-06-10T17:02Z",
"audit:licensing/2025-06-09T11:40Z",
],
}ConsoleOut [32]Expand
Dataset: ds-2025.06 Documents: 50,000 Shards: 50 Source Merkle root: 0d7ce7a257686626ac507167... Tokenized root: 32db9876dd1e1caf368302fc... Root schema: sorted-digest-multiset-sha256-v1
The source root commits to the synthetic documents grouped into shards. The derived root commits to serialized whitespace-token shards in this example. The manifest also records the derived shard digests in index order. In a real pipeline, verify the exact derived bytes and shard sequence against their own trusted manifest, and record which manifest the training run consumed. Comparing the two roots to each other does not validate the transformation.
Evaluating the gates
The audit record feeds a policy. For sensitive content, require a one-sided 95% upper bound at or below 1%. The flagged census gives its exact count. In the unflagged stratum, find the largest population count for which observing no more positives than we saw would still have probability at least 5%. Sampling without replacement makes that tail hypergeometric.
PythonIn [33]Expand
from scipy.stats import hypergeom
def finite_population_upper(population, reviewed, positives, alpha=0.05):
"""Largest positive population count consistent with a one-sided exact test."""
low, high = positives, population - reviewed + positives
while low < high:
mid = (low + high + 1) // 2
if hypergeom.cdf(positives, population, mid, reviewed) >= alpha:
low = mid
else:
high = mid - 1
return low
k0 = sum(unflagged[i]["sensitive_true"] for i in s0)
k1 = sum(d["sensitive_true"] for d in flagged)
upper_prevalence = (k1 + finite_population_upper(N0, n0, k0)) / N_CORPUS
POLICY = {
"sensitive_prevalence_upper_95_max": 0.010,
"sensitive_bound_method": "one-sided hypergeometric inversion, census of flagged stratum",
"provenance_coverage_min": 0.98,
"license_resolved_min": 0.95,
"contamination_flagged_docs_max": 0,
}
def digest_json(record):
"""Hash this fixture's stable JSON serialization."""
return sha256_hex(json.dumps(record, sort_keys=True, separators=(",", ":")))
def artifact_identity(m):
return {
"dataset_id": m["dataset_id"],
"merkle_schema": m["merkle_schema"],
"source_root": m["source_root"],
"tokenized_root": m["tokenized_root"],
"tokenizer": m["pipeline"]["tokenizer"],
"document_count": m["document_count"],
"shard_count": m["shard_count"],
"ordered_derived_shard_digests_sha256": digest_json(
m["tokenized_shard_digests_in_index_order"]
),
}
audit_report = {
"artifact": artifact_identity(manifest),
"pii_prevalence": p_strat,
"pii_upper_95": upper_prevalence,
"pii_bound_method": "one-sided hypergeometric inversion, census of flagged stratum",
"provenance_coverage": 0.994,
"license_resolved_share": 0.962,
"contamination_flagged_docs": 0,
"review_design": "detector-stratified, census of flagged stratum",
"reviewed_count": int(n1 + n0),
}
def evaluate_gates(report, policy):
if report["pii_bound_method"] != policy["sensitive_bound_method"]:
raise ValueError(
"sensitive-content upper bound uses a different method"
)
rows = [
{
"gate": "sensitive-content prevalence, 95% upper bound",
"observed": report["pii_upper_95"],
"operator": "<=",
"threshold": policy["sensitive_prevalence_upper_95_max"],
"pass": report["pii_upper_95"]
<= policy["sensitive_prevalence_upper_95_max"],
"evidence": "audit:sensitive/2025-06-11T09:14Z",
},
{
"gate": "provenance coverage",
"observed": report["provenance_coverage"],
"operator": ">=",
"threshold": policy["provenance_coverage_min"],
"pass": report["provenance_coverage"]
>= policy["provenance_coverage_min"],
"evidence": "audit:provenance/2025-06-10T17:02Z",
},
{
"gate": "resolved license share",
"observed": report["license_resolved_share"],
"operator": ">=",
"threshold": policy["license_resolved_min"],
"pass": report["license_resolved_share"]
>= policy["license_resolved_min"],
"evidence": "audit:licensing/2025-06-09T11:40Z",
},
{
"gate": "benchmark contamination",
"observed": report["contamination_flagged_docs"],
"operator": "<=",
"threshold": policy["contamination_flagged_docs_max"],
"pass": report["contamination_flagged_docs"]
<= policy["contamination_flagged_docs_max"],
"evidence": "audit:contamination/2025-06-08",
},
]
return pd.DataFrame(rows)
gate_table = evaluate_gates(audit_report, POLICY)| gate | observed | operator | threshold | pass | evidence | value_origin | |
|---|---|---|---|---|---|---|---|
| 0 | sensitive-content prevalence, 95% upper bound | 0.01196 | <= | 0.01 | False | audit:sensitive/2025-06-11T09:14Z | Computed bound |
| 1 | provenance coverage | 0.99400 | >= | 0.98 | True | audit:provenance/2025-06-10T17:02Z | Example input |
| 2 | resolved license share | 0.96200 | >= | 0.95 | True | audit:licensing/2025-06-09T11:40Z | Example input |
| 3 | benchmark contamination | 0.00000 | <= | 0.00 | True | audit:contamination/2025-06-08 | Example input |
ConsoleOut [35]Expand
Overall gate status: BLOCKED FAILED: sensitive-content prevalence, 95% upper bound (observed 0.01196, criterion <= 0.01)
The sensitive-content gate blocks this fixture because its upper bound exceeds 1%, even though the point estimate is below 1%. If an applicable policy permits a waiver, it must cover the failed gate before release. The waiver is a row in the same store, with an approver, a justification, an expiry, and the compensating control.
PythonIn [36]Expand
WAIVER_SCHEMA = {
"waiver_id": "wv-2025-014",
"gate": "internal provenance coverage",
"corpus_version": "ds-waiver-example",
"requested_by": "data-owner-role",
"approved_by": "counsel-role",
"justification": "One permitted source lacks a backfilled extraction timestamp.",
"compensating_control": "retain source receipts and reconcile recorded dates",
"expires_utc": "2025-09-30",
"status": "illustrative only",
}
print(json.dumps(WAIVER_SCHEMA, indent=2))The example shows a record format for a different snapshot. It does not waive the sensitive-content failure. Keep the approval and expiration date with the exact gate and artifact they cover.
Attaching gate outcomes to the manifest
Bind the decision to the artifact identity, policy, outcome, and the digests of the reviewed measurements. This fixture hashes a deterministic record and shows consistency checks. In production, have authorized decision-makers sign the record and verify those signatures using trusted identities.
PythonIn [37]Expand
fixture_decisions = [
{
"role": "data owner",
"decision": "refer for review",
"recorded_utc": "2025-06-11T10:20:00Z",
},
{
"role": "safety review",
"decision": "accept" if all_pass else "hold",
"recorded_utc": "2025-06-11T13:05:00Z",
},
{
"role": "counsel",
"decision": "legal review recorded",
"recorded_utc": "2025-06-11T15:41:00Z",
},
{
"role": "accountable executive",
"decision": "approve" if all_pass else "hold",
"recorded_utc": "2025-06-12T08:30:00Z",
},
]
manifest["gate_record"] = {
"artifact": audit_report["artifact"],
"policy": POLICY,
"gate_table_sha256": sha256_hex(gate_table.to_csv(index=False)),
"audit_report_sha256": digest_json(audit_report),
"overall": "pass" if all_pass else "blocked",
"evaluated_at_utc": "2025-06-11T10:02:00Z",
"fixture_decisions": fixture_decisions,
}
fixture_decision_digest = digest_json(manifest["gate_record"])ConsoleOut [38]Expand
Decision record digest: 648fa783b37b9c02b2d31fc8... Audit record digest: a07382bb66b6e5ceace19918... Overall: blocked data owner refer for review 2025-06-11T10:20:00Z safety review hold 2025-06-11T13:05:00Z counsel legal review recorded 2025-06-11T15:41:00Z accountable executive hold 2025-06-12T08:30:00Z
These role decisions and timestamps are synthetic. Separate the data owner's recommendation, safety and legal review, and the final decision so a reader can see who made each judgment. The accountable executive holds this fixture because its gate failed.
Post-release traceability
A separate toy incident record shows how to use the lineage from a reported document to potentially affected model releases. The run records below are illustrative historical records, not releases approved by the gate evaluated above.
PythonIn [39]Expand
# The earlier snapshot is represented by a placeholder root for this example.
DATA_ROOTS = {
"ds-2025.06": source_root,
"ds-2025.02": sha256_hex("ds-2025.02-placeholder-root"),
}
TRAINING_RUNS = [
{
"run_id": "run-0114",
"dataset": "ds-2025.06",
"checkpoint": "ckpt-0001200",
"release": "model-1.2",
"released_utc": "2025-06-20",
},
{
"run_id": "run-0127",
"dataset": "ds-2025.06",
"checkpoint": "ckpt-0002400",
"release": "model-1.3",
"released_utc": "2025-08-04",
},
{
"run_id": "run-0091",
"dataset": "ds-2025.02",
"checkpoint": "ckpt-0000900",
"release": "model-1.1",
"released_utc": "2025-03-02",
},
]
def blast_radius(doc_id):
if doc_id not in doc_shard:
return {
"doc_id": doc_id,
"searched_snapshot": "ds-2025.06",
"status": "not indexed",
}
shard_idx = doc_shard[doc_id]
shard_root = shard_hashes[shard_idx]
affected = [
r for r in TRAINING_RUNS if DATA_ROOTS[r["dataset"]] == source_root
]
return {
"doc_id": doc_id,
"doc_sha256": doc_hashes[doc_id],
"shard_index": shard_idx,
"shard_root": shard_root,
"dataset_id": "ds-2025.06",
"matching_configured_runs": [r["run_id"] for r in affected],
"candidate_releases": [r["release"] for r in affected],
}ConsoleOut [40]Expand
{
"doc_id": "d031337",
"doc_sha256": "cca2bb482bab2c360984ad870ad07c6ec43a0a73f5c4ab581a2defb270b6246d",
"shard_index": 31,
"shard_root": "567095e2af9134c9118527093deb290586fe88621d6f7cd0ff8c8249e5850a48",
"dataset_id": "ds-2025.06",
"matching_configured_runs": [
"run-0114",
"run-0127"
],
"candidate_releases": [
"model-1.2",
"model-1.3"
]
}The lookup covers one indexed source snapshot and returns runs associated with it. In the fixture, investigate model-1.2 and model-1.3 on that basis. model-1.1 uses another snapshot and remains unexamined. A root match identifies an intended input; use loader records to check selection.
In production, bind the documents and shards to an authenticated source manifest, join the source manifest to the derived one, then check the training run's recorded inputs. Consult the consumption records before stating that a run read a shard or specific sample.
PythonIn [41]Expand
def datasheet_card(manifest, report, gate_df, expected_decision_digest):
"""Check that this fixture's audit and gate data match the supplied decision."""
decision = manifest["gate_record"]
if digest_json(decision) != expected_decision_digest:
raise ValueError("unexpected decision record")
if (
artifact_identity(manifest) != decision["artifact"]
or report["artifact"] != decision["artifact"]
):
raise ValueError("audit refers to a different artifact")
if digest_json(report) != decision["audit_report_sha256"]:
raise ValueError("audit report does not match the decision")
if sha256_hex(gate_df.to_csv(index=False)) != decision["gate_table_sha256"]:
raise ValueError("gate table does not match the decision")
passed = int(gate_df["pass"].sum())
return "\n".join(
[
f"### Dataset card: {manifest['dataset_id']}",
"",
f"- **Content address (Merkle root):** `{manifest['source_root'][:32]}...`",
f"- **Toy tokenized artifact root:** `{manifest['tokenized_root'][:32]}...`",
f"- **Documents / shards:** {manifest['document_count']:,} / {manifest['shard_count']}",
f"- **Sensitive-content prevalence:** {report['pii_prevalence']:.2%} "
f"(one-sided 95% upper bound {report['pii_upper_95']:.2%})",
f"- **Review design:** {report['review_design']}, n = {report['reviewed_count']:,}",
f"- **Example provenance coverage:** {report['provenance_coverage']:.1%}",
f"- **Example resolved license share:** {report['license_resolved_share']:.1%}",
f"- **Fixture gate decision:** {decision['overall'].upper()} ({passed}/{len(gate_df)} gates passed)",
f"- **Example contamination findings:** {report['contamination_flagged_docs']} documents",
"- **Illustrative metadata:** crawler, extractor, normalization, "
"deduplication, production filter names, and non-sensitive audit references.",
]
)
card = datasheet_card(
manifest, audit_report, gate_table, fixture_decision_digest
)ConsoleOut [42]Expand
<IPython.core.display.Markdown object>
The card reads the sensitive-content measurement, supplied example values, and evaluated gate outcome from the bound records. For a release, regenerate it from current evidence, with a build check that rejects missing evidence or mismatched snapshot identifiers.
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!