---
title: Data quality, leakage and drift
url: https://gurkanozkan.ai/learn/topics/data-quality/
markdown: https://gurkanozkan.ai/learn/topics/data-quality.md
kind: topic
tracks:
  - ML engineering
  - AI leadership
  - Applied LLM
json: https://gurkanozkan.ai/api/learn/topics/data-quality.json
---

# Data quality, leakage and drift

Many production ML failures are data failures: leakage that inflates offline metrics, training–serving skew, silent upstream schema changes, delayed and noisy labels, class imbalance and drift. Interviewers want a systematic approach: validate data at every boundary, build point-in-time-correct training sets, monitor inputs and predictions while labels are still missing, and diagnose an offline–online gap before touching the model. The same discipline applies to LLM fine-tuning data: quality over volume, deduplication, PII removal and an exact match between training and serving templates.

## Key concepts

### Leakage taxonomy

Target leakage uses information only available after the prediction moment (an "account closed" flag in a churn model). Train–test contamination puts duplicates or the same entity on both sides of a split. Preprocessing leakage fits scalers, encoders or oversamplers on all data before splitting. Temporal leakage comes from random splits of time-ordered data; LLM benchmarks suffer contamination from web-scale pretraining. Red flags: AUC near 0.99, one dominant feature, or a jump far beyond a simple baseline.

### Point-in-time correctness

Each training row must use feature values as they were available when the prediction would have been made: an as-of join on the time the value landed in the system, not the event time it describes. Use versioned or snapshot tables, and verify by recomputing features for past requests and comparing them with values logged at serving time.

### Training–serving skew

Causes include duplicated transformation code in two languages, different sources or freshness, time zones and units, default values for missing data, and, for LLMs, a chat template or tool schema at training time that differs from serving. Prevent it with one transformation path and by logging the features actually served and training on those logs; detect it by comparing training and serving distributions and by shadow scoring before launch.

### Data validation at boundaries

Check schema and types, null rates, ranges and allowed values, key uniqueness, row volume, freshness and distribution against a reference. Separate blocking checks from warnings, give every check an owner and an alert route, and quarantine bad partitions so one broken source does not stop every pipeline.

### Types of drift

Covariate shift changes P(x) (a new market); prior or label shift changes P(y) (a fraud wave); concept drift changes P(y | x) (fraudsters adapt, so the same features mean something else). Each needs different detection and response, upstream data bugs often masquerade as drift, and seasonality must be modelled before alarms are trusted.

### Monitoring when labels are late

Watch input distributions (population stability index, Kolmogorov–Smirnov tests), the prediction-score distribution, decision rates (declines, escalations) and data-quality metrics, plus early proxy labels such as disputes or user feedback. A common PSI rule of thumb: below 0.1 stable, 0.1–0.25 moderate, above 0.25 major. Set thresholds from historical week-on-week variability and monitor by segment, not averages alone.

### Labels: delay, noise and imbalance

With delayed labels (chargebacks after 30–90 days) recent data is right-censored, so train and evaluate only on matured windows and never treat "no label yet" as negative. Estimate noise with double labelling and agreement statistics, find suspect labels with confident learning, and spend labelling budget where the model is uncertain. For imbalance, fix metrics first, then use class weights or negative undersampling, and correct or recalibrate the resulting probabilities.

### Feature hygiene

Encode high-cardinality categoricals (merchant IDs) with out-of-fold target encoding, hashing or learned embeddings, because naive target encoding leaks the label. Missingness can be informative, so add indicator features rather than silently imputing. Feature stores give single definitions, offline and online consistency and lineage.

## Worked examples

### Population stability index for a score distribution

A fraud model's score was binned into five bins on the reference month with shares [0.20, 0.30, 0.25, 0.15, 0.10]. This week's shares are [0.10, 0.25, 0.30, 0.20, 0.15]. Historically the 95th percentile of week-on-week PSI is 0.08. Compute PSI and decide what to do.

**Solution**

PSI = Σ (currentᵢ − referenceᵢ) × ln(currentᵢ / referenceᵢ)

| Bin | ref | cur | (cur − ref) × ln(cur/ref) |
|---|---|---|---|
| 1 | 0.20 | 0.10 | (−0.10) × ln 0.5 = 0.0693 |
| 2 | 0.30 | 0.25 | (−0.05) × ln 0.833 = 0.0091 |
| 3 | 0.25 | 0.30 | 0.05 × ln 1.2 = 0.0091 |
| 4 | 0.15 | 0.20 | 0.05 × ln 1.333 = 0.0144 |
| 5 | 0.10 | 0.15 | 0.05 × ln 1.5 = 0.0203 |

**PSI ≈ 0.122**: "moderate" by the rule of thumb and above this model's normal 0.08, so alert, but do
not retrain blindly.

Next steps:
1. Rule out pipeline bugs: a feature suddenly null or defaulted, a unit or currency-code change,
   a new upstream source.
2. Find which input features moved (PSI per feature, by segment) and whether traffic mix changed (a new
   merchant, a marketing campaign).
3. Check decision rates and early proxies (disputes) for real performance impact.

Caveats: PSI depends on the binning (use reference quantiles), is noisy with small samples, and needs a
small epsilon for empty bins.


### Hunting leakage behind a 0.99 AUC

A churn model shows an offline AUC of 0.99 on a random split. Walk through the investigation and show how to rebuild the training set point-in-time correctly.

**Solution**

**1. Compare with a simple baseline.** Logistic regression on three obvious features gives 0.74; a jump
to 0.99 is implausible for churn.

**2. Inspect the top features.** SHAP shows `days_since_last_login` dominates. It was computed from the
warehouse snapshot taken *after* the churn date, so churned customers always have huge values: target
leakage. Removing it drops AUC to 0.86.

**3. Check the split.** 4% of customers appear in both train and test with several monthly rows each.
Switching to GroupKFold by customer gives 0.83.

**4. Test out of time.** Train on January–September, test on November–December (October left as a gap
because churn labels take 30 days to mature): **0.79**. That is the number to report.

**5. Rebuild point-in-time correct features.** Use the time each value became available:

```sql
SELECT l.customer_id, l.prediction_ts, l.churned,
       f.sessions_30d
FROM labels AS l
LEFT JOIN LATERAL (
  SELECT sessions_30d
  FROM feature_history AS f
  WHERE f.customer_id = l.customer_id
    AND f.available_at <= l.prediction_ts      -- not event time
  ORDER BY f.available_at DESC
  LIMIT 1
) AS f ON TRUE;
```

**6. Prevent recurrence.** A unit test that recomputes features for a sample of logged serving requests
and compares them with the logged values, and an alert if any single feature's importance exceeds an
agreed share.


### Correcting probabilities after undersampling negatives

In a 1:1,000 problem you keep all positives and a random β = 1% of negatives for training. The model then outputs p_s = 0.5 for a transaction. What is the probability on the real population, and why does this matter?

**Solution**

Undersampling negatives multiplies the odds by 1/β, so divide them back out:

odds_true = β × p_s / (1 − p_s)  ⇒  p = β p_s / (β p_s − p_s + 1)

With β = 0.01 and p_s = 0.5: p = 0.005 / (0.005 − 0.5 + 1) = 0.005 / 0.505 ≈ **0.0099**.

**Sanity check.** The true base rate is 1/1,001 ≈ 0.001. After undersampling the training base rate is
1 / (1 + 10) ≈ 0.0909. A prediction equal to that training base rate maps back to
0.01 × 0.0909 / (0.000909 − 0.0909 + 1) = 0.000909 / 0.910 ≈ 0.001, the true base rate, as it should.

**Why it matters.** Thresholds set by expected cost (for example "decline when p > 0.06"), expected-loss
reports and calibrated monitoring all assume true-population probabilities. Uncorrected scores from the
sampled model would be about 50 times too high here. After correcting, check calibration on an untouched,
naturally distributed validation set, and only ever resample after splitting the data.


## What changed recently

- **Oct 2026: Pretraining poisoning can plant agent backdoors.** Researchers including Nicholas Carlini pretrained 0.6B–4B models from scratch on web data with planted poison, then post-trained them into command-line agents; a remote-code-execution backdoor reached about 92% success in the 4B model at a 0.1% poison rate and was still measurable at 0.0005%. Poisoned training data is now an agent-security issue, so expect questions on provenance, corpus audits and runtime limits for agents built on third-party models. [Source](https://arxiv.org/abs/2610.37741)
- **Jul 2026: A $1.5bn settlement over how training data was acquired.** A US court gave final approval to a $1.5 billion settlement over books used to train Claude, roughly $3,000 per work for about 500,000 works; the earlier ruling separated lawfully bought and scanned books from copies taken from pirate libraries. Where data came from, and whether you can prove it, is now a material legal and data-quality question. [Source](https://techcrunch.com/2026/07/20/anthropics-landmark-1-5b-copyright-settlement-is-approved/)
- **Oct 2025: About 250 documents can poison a model of any size.** Anthropic, the UK AI Security Institute and the Alan Turing Institute found that around 250 poisoned documents implanted a trigger-to-gibberish backdoor in models from 600M to 13B parameters, so the attacker needs a roughly fixed number of documents rather than a fixed share of the corpus. Within the tested range, scale did not dilute poisoning, so per-source trust and anomaly detection matter more than corpus size; the study notes it is unclear whether the trend holds for larger models or more complex backdoors. [Source](https://www.anthropic.com/research/small-samples-poison)
- **Aug 2025: Mandatory training-data summaries under the EU AI Act.** From 2 August 2025, providers of general-purpose AI models must publish a summary of their training content using the Commission's template (by 2 August 2027 for models already on the market), and the AI Office can take enforcement action from 2 August 2026. Data teams need provenance records good enough to fill it: data-source categories (public, private, scraped, user and synthetic), crawler names and collection periods, and the top scraped domains. [Source](https://digital-strategy.ec.europa.eu/en/faqs/template-general-purpose-ai-model-providers-summarise-their-training-content)
- **Jun 2025: The SWE-Bench Illusion: memorisation inflates scores.** A study found that models could name the buggy file path from the issue text alone with up to 76% accuracy on SWE-bench Verified versus up to 53% on repositories outside it, and reproduced far more verbatim code there, evidence of memorisation. Contamination checks (held-out repositories, n-gram overlap, path-identification probes) are now expected when an eval set is public. [Source](https://arxiv.org/abs/2506.12286)

## Pitfalls

- Oversampling, SMOTE or fitting encoders on the full dataset before the train–validation split.
- Treating unlabelled recent transactions as negatives, or evaluating on windows whose labels have not matured.
- Calling every metric change 'concept drift' without checking upstream data bugs and seasonality.
- Static thresholds on hundreds of features, producing alert fatigue; or monitoring only averages, which hides segment failures.
- Retraining immediately when an A/B test is flat instead of checking leakage, skew, metric alignment and statistical power.
- Hand-building chat templates for fine-tuning data, or training on user turns or bad agent replies copied from logs.

## How interviewers probe it

- 'Offline AUC is 0.99 — walk me through your leakage hunt', then 'what would you have to see to believe it?'
- 'A big offline gain, a flat A/B test': leakage, metric misalignment, shift, power, latency, novelty, feedback loops.
- 'Labels arrive 30–90 days late': censoring, proxies, maturity windows and what you monitor meanwhile.
- 'Which automated checks would you put on the training and serving paths?' — expect follow-ups on ownership and noisy alerts.
- LLM variant: 'You have 20k support conversations to fine-tune on — what decides whether it helps?'
- Lead and regulated variant: how model risk management in a UK bank handles validation, monitoring and data lineage.

## Reading

- [Rules of Machine Learning: Best Practices for ML Engineering](https://developers.google.com/machine-learning/guides/rules-of-ml) (Docs, 45 min, Intro): Practical rules, including logging served features and measuring training–serving skew.
- [Hidden Technical Debt in Machine Learning Systems](https://papers.nips.cc/paper/5656-hidden-technical-debt-in-machine-learning-systems) (Paper, 30 min, Core): Data dependencies, feedback loops and entanglement as the main sources of ML system debt.
- [Leakage and the Reproducibility Crisis in ML-based Science](https://arxiv.org/abs/2207.07048) (Paper, 50 min, Core): A taxonomy of leakage types with evidence of how often it invalidates published results.
- [Data Distribution Shifts and Monitoring](https://huyenchip.com/2022/02/07/data-distribution-shifts-and-monitoring.html) (Blog, 40 min, Core): Clear treatment of covariate, label and concept shift and what to monitor in production.
- [Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift](https://arxiv.org/abs/1810.11953) (Paper, 50 min, Deep): Compares shift-detection methods; two-sample tests on reduced representations work best.
- [Confident Learning: Estimating Uncertainty in Dataset Labels](https://arxiv.org/abs/1911.00068) (Paper, 50 min, Deep): A principled way to find mislabelled examples, the basis of label-noise cleaning tools.
- [Point-in-time joins (Feast documentation)](https://docs.feast.dev/getting-started/concepts/point-in-time-joins) (Docs, 10 min, Core): How feature stores assemble leakage-free training sets with timestamped as-of joins.
- [A small number of samples can poison LLMs of any size](https://www.anthropic.com/research/small-samples-poison) (Blog, 10 min, Intro): Evidence that backdoor poisoning needs a roughly fixed number of documents rather than a fraction of the corpus, with the study's limits.

## Practise this topic

- [Your offline AUC is 0.99 on a churn model. Walk through how you would hunt for leakage.](https://gurkanozkan.ai/learn/questions/mle-spotting-data-leakage-08.md)
- [What causes training–serving skew and how do you prevent and detect it?](https://gurkanozkan.ai/learn/questions/mle-training-serving-skew-34.md)
- [How do you build a training set where every feature value is what was known at the moment of prediction?](https://gurkanozkan.ai/learn/questions/mle-point-in-time-correct-training-data-35.md)
- [What automated checks would you put on data entering a training pipeline and a serving path?](https://gurkanozkan.ai/learn/questions/mle-data-validation-in-pipelines-36.md)
- [Distinguish covariate shift, prior (label) shift and concept drift, with an example of each from payments or delivery.](https://gurkanozkan.ai/learn/questions/mle-types-of-drift-45.md)
- [Labels arrive weeks late. What would you monitor to catch problems early, and how do you set alert thresholds?](https://gurkanozkan.ai/learn/questions/mle-detecting-drift-without-labels-46.md)
- [Chargebacks arrive 30–90 days after a transaction, and some never arrive. How does this affect training, evaluation and monitoring?](https://gurkanozkan.ai/learn/questions/mle-delayed-and-noisy-labels-30.md)
- [List techniques for a 1:1000 imbalanced problem and their side effects.](https://gurkanozkan.ai/learn/questions/mle-handling-severe-class-imbalance-29.md)
- [A model shows a big offline improvement but the A/B test is flat. What might be happening?](https://gurkanozkan.ai/learn/questions/lead-td-09.md)
- [You're assembling 20k conversations to fine-tune a support assistant. What decides whether the fine-tune helps, and what are the technical gotchas?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-03.md)
- [Compare strategies for missing data, and when is "missingness" itself a signal?](https://gurkanozkan.ai/learn/questions/mle-missing-values-38.md)
- [Design a pipeline that turns 50 million PDFs (born-digital reports, scanned forms, papers with tables and equations) into clean text for pretraining and…](https://gurkanozkan.ai/learn/questions/recent-a-datapipe-01.md)
- [A 2025 study found that about 250 poisoned documents could implant a backdoor in language models from 600M to 13B parameters, regardless of how much clean data…](https://gurkanozkan.ai/learn/questions/recent-a-dq-01.md)
- [After fine-tuning, your team reports a large gain on a public coding benchmark. What would you check before believing it?](https://gurkanozkan.ai/learn/questions/recent-a-dq-02.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
