Worked tutorial · about 45 minutes
Audit a document split for three kinds of leakage
Find document-family overlap, exact-content overlap and a preprocessing leak in ten fictional records, then verify a complete repair plan.
Original editorial exercise · fictional practice data · checked 25 October 2026
Different row IDs do not guarantee independent evaluation data. A revised document can resemble its earlier version, and a copied document can arrive under another family ID. Even after repairing those overlaps, fitting a transformation on the whole collection can expose held-out information to training.
Your deliverable is an audit and a repaired manifest for this stated goal: evaluate on document families unseen during training. All records, family labels, content keys and page counts are invented. You can solve the exercise by hand; the optional checker uses Python 3's standard library and trains no model.
1. State what each identifier means
id identifies a row. family groups revisions of one source document. Equal content_key values mean identical content in this exercise, even if the family IDs differ. The keys are supplied fictional equality markers, not computed cryptographic hashes. A real audit would verify content identity against the actual files and document how fingerprints were computed.
id,family,content_key,page_count,split
D01,F1,C01,10,train
D02,F1,C02,14,test
D03,F2,C03,20,train
D04,F3,C03,20,test
D05,F4,C04,30,train
D06,F4,C05,34,validation
D07,F5,C06,40,validation
D08,F6,C07,50,test
D09,F7,C08,60,test
D10,F8,C09,70,validation
The proposed pipeline also subtracts the average page count from every row. Its author plans to calculate that average using all ten rows before splitting. Treat this as a separate audit finding from any duplicated document.
2. Run three independent checks
- Group the records by family. For each family, list its row IDs and the distinct proposed splits. Flag a family when it appears in more than one split.
- Repeat that process by content key. Do this even if the family check passes: a copied file can have another family ID.
- Inspect which rows are used to fit the mean. For this learned preprocessing value, use only training rows, then apply that same fitted value to validation and test rows.
Try the worksheet before opening the answer. Overlap is about the intended generalization task: a chronological task involving future revisions of known families would need a different design. Here the unseen-family goal makes family overlap unacceptable.
Show the three findings
- F1 crosses train and test: D01 and D02.
- F4 crosses train and validation: D05 and D06.
- C03 crosses train and test: D03 and D04, despite the different F2 and F3 family labels.
- The mean fit includes held-out rows: the original training mean is (10 + 20 + 30) / 3 = 20 pages. The all-row mean is 348 / 10 = 34.8 pages. Using 34.8 would make the training representation depend on held-out data.
The different means make the leak visible, but equal means by coincidence would not make the all-row fitting procedure valid. The audit concerns which data influenced the fitted transformation.
3. Propose a repair without consulting outcomes
Choose a plan from document provenance and the evaluation goal, before seeing model scores. There is more than one possible plan. Our worked plan moves the related revisions into training and retains a single representative of the exact duplicate. It accounts for every original row.
| Destination | IDs | Reason |
|---|---|---|
| Train | D01, D02, D03, D05, D06 | Keep F1 and F4 together; keep D03 as the chosen C03 representative. |
| Validation | D07, D10 | Reserve two separate families for development choices. |
| Test | D08, D09 | Reserve two other families for the frozen final evaluation. |
| Remove from this evaluation manifest | D04 | Redundant exact-content copy of D03 under the exercise's equality rule. |
The retained counts are 5 training, 2 validation and 2 test records, with one removed copy. No retained family or content key crosses splits. The downloadable plan records these decisions; the checker reads the plan and does not move or delete any source file.
For a larger collection, consider connected relationships: if document A shares a family with B and B duplicates C, those links can connect all three even when A and C share no direct key. Review the connected group before assigning a split. Removing a redundant copy is an exercise policy, not an instruction to discard real documents without checking provenance and usage rights.
4. Refit the transformation after the repair
The repaired training total is 10 + 14 + 20 + 30 + 34 = 108 pages. Fit the training mean as 108 / 5 = 21.6 pages. Subtract that same value from each retained record, without fitting again on validation or test data.
D08 becomes 50 − 21.6 = 28.4; D09 becomes 60 − 21.6 = 38.4. These are centered feature values, not predictions or error rates. In the checker's exact fraction output, the mean is 108/5, and those two values are 142/5 and 192/5.
python audit_split.py document_manifest.csv repair_plan.csv Save the downloads in one folder. The checker prints both the original findings and the proposed repair, including the exact IDs used to fit the repaired mean. A result of passes_stated_overlap_checks: true means only that the supplied family and content-key overlap checks pass.
Show the complete audit checker
"""Audit a fictional split and a proposed repair without editing either file."""
import argparse
import csv
import json
from collections import Counter, defaultdict
from fractions import Fraction
from pathlib import Path
SPLITS = {'train', 'validation', 'test'}
def read_csv(path):
with Path(path).open(encoding='utf-8-sig', newline='') as handle:
return list(csv.DictReader(handle))
def conflicts(rows, field):
grouped = defaultdict(list)
for row in rows:
grouped[row[field]].append(row)
return [
{'key': key, 'ids': sorted(row['id'] for row in values),
'splits': sorted({row['split'] for row in values})}
for key, values in sorted(grouped.items())
if len({row['split'] for row in values}) > 1
]
def mean(rows):
if not rows:
raise ValueError('Cannot fit a mean on an empty training set.')
return Fraction(sum(int(row['page_count']) for row in rows), len(rows))
def evaluate(manifest_path, plan_path):
original = read_csv(manifest_path)
ids = [row['id'] for row in original]
if not ids or len(ids) != len(set(ids)):
raise ValueError('Manifest IDs must be nonempty and unique.')
for row in original:
if row['split'] not in SPLITS or not row['family'] or not row['content_key']:
raise ValueError('Each row needs a valid split, family, and content key.')
if int(row['page_count']) <= 0:
raise ValueError('Page counts must be positive integers.')
plan = read_csv(plan_path)
plan_ids = [row['id'] for row in plan]
if len(plan_ids) != len(set(plan_ids)) or set(plan_ids) != set(ids):
raise ValueError('The plan must mention every manifest ID exactly once.')
decisions = {row['id']: row for row in plan}
repaired, removed = [], []
for row in original:
decision = decisions[row['id']]
if decision['action'] == 'drop' and decision['new_split'] == '':
removed.append(row['id'])
elif decision['action'] == 'keep' and decision['new_split'] in SPLITS:
repaired.append({**row, 'split': decision['new_split']})
else:
raise ValueError('Use keep plus a valid split, or drop plus an empty split.')
counts = Counter(row['split'] for row in repaired)
if set(counts) != SPLITS:
raise ValueError('The repaired exercise must retain all three splits.')
train = [row for row in repaired if row['split'] == 'train']
fitted_mean = mean(train)
family_conflicts = conflicts(repaired, 'family')
content_conflicts = conflicts(repaired, 'content_key')
return {
'scope': 'Equality checks on fictional metadata; no model is trained.',
'original': {
'cross_split_families': conflicts(original, 'family'),
'cross_split_content_keys': conflicts(original, 'content_key'),
'train_mean_exact': str(mean([row for row in original if row['split'] == 'train'])),
'incorrect_all_row_fit_mean_exact': str(mean(original)),
'incorrect_fit_ids': sorted(ids),
},
'repaired': {
'ids_by_split': {split: sorted(row['id'] for row in repaired if row['split'] == split)
for split in sorted(SPLITS)},
'counts_by_split': dict(sorted(counts.items())),
'removed_ids': sorted(removed),
'cross_split_families': family_conflicts,
'cross_split_content_keys': content_conflicts,
'fit_ids': sorted(row['id'] for row in train),
'train_mean_exact': str(fitted_mean),
'test_centered_exact': {row['id']: str(Fraction(row['page_count']) - fitted_mean)
for row in repaired if row['split'] == 'test'},
'passes_stated_overlap_checks': not family_conflicts and not content_conflicts,
},
}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('manifest')
parser.add_argument('plan')
args = parser.parse_args()
try:
print(json.dumps(evaluate(args.manifest, args.plan), indent=2))
except (ValueError, KeyError, OSError) as exc:
parser.exit(2, f'Input error: {exc}\n')
5. Record what the audit leaves open
A suitable handoff is: “The original split shares F1, F4 and exact content C03 across subsets, and its preprocessing fit uses held-out rows. The attached plan retains 5/2/2 records with no cross-split family or content-key overlap. Its centering mean is fitted on the five repaired training IDs.”
This ten-record manifest contains no target labels or predictions, so it cannot establish class balance or model performance. Passing equality checks also misses unmarked near-duplicates, shared templates, hidden common sources and incorrect family metadata. A real evaluation needs verified provenance, representative cases, sufficient sample size and a split policy matching deployment. Keep the final test set out of tuning decisions.
For the simpler idea of grouping related rows, start with the customer-split exercise. For a different data-quality problem, try the CSV audit. Once a split is sound, continue to threshold evaluation.
Sources and scope
The scikit-learn data-leakage guidance explains fitting learned transformations only on training data and applying the fitted transformation to other subsets. Google's dataset-splitting lesson discusses train/validation/test roles and duplicate examples. Sources checked 25 October 2026. The manifest, family policy, repair and calculations are our editorial exercise.