# How to detect eval-set contamination (data leakage) in your LLM tests

> Source: <https://dev.to/nikolay_chernev_a67479931/how-to-detect-eval-set-contamination-data-leakage-in-your-llm-tests-10p>
> Published: 2026-11-23 07:00:05+00:00

**Recommendation:** Run an n-gram overlap audit on your eval set against public corpora before trusting pass rates, and replace any example scoring 0.3 or higher at 8-grams.
More in the playbook "Evals and testing for LLM apps": <https://wpnews.pro/playbooks/evals-testing>

**Short answer:** If your eval examples came from public benchmarks, known documentation, or were AI-generated from a dataset the model was fine-tuned on, the model may have seen the answers during training. Detect contamination with n-gram overlap checks and performance comparisons on post-cutoff data; fix it by replacing examples with ones the model genuinely hasn't seen.

The symptoms are almost invisible until production: 94% golden-set pass rate, then users complaining the feature "feels wrong." You investigate and find your eval examples came from the library's README — the same README that's in every web crawl used to train frontier models. You've been measuring recall, not reasoning.

This is eval-set contamination. It's the classic data leakage problem, applied one layer up: not to model training, but to the eval set you built to verify that training didn't regress.

For traditional ML, data leakage means test examples were in the training set. For LLM evals, it's messier, because you don't control what went into pretraining:

**Pretraining contamination** — your eval inputs appeared in the model's web crawl data. GPT-4 and Claude were trained on a significant fraction of the public internet. If your test examples are from GitHub, Stack Overflow, public docs, or any notable benchmark dataset, there's a real chance the model has seen them.

**Fine-tuning contamination** — you used AI-generated expected outputs to build your golden set, and the model provider used similar outputs for RLHF or instruction tuning. The model isn't generalizing — it's pattern-matching on output style it was explicitly trained to produce.

**Benchmark leakage** — you borrowed examples from a published eval suite (MMLU, HumanEval, MT-Bench) for quick coverage. Those datasets are well-documented in papers, so they're almost certainly in the pretraining corpus. Using them measures "did the model study for this test" more than "can the model do this task."

The first and third are the ones that quietly inflate production teams' confidence. Fine-tuning contamination is rarer but nastier because it's invisible in any corpus comparison.

The fastest signal: how many 8-gram sequences from your eval inputs also appear in a reference corpus. If you're testing against a known benchmark dataset, those datasets are public — you can check directly.

``` php
def ngrams(text: str, n: int) -> set[str]:
    tokens = text.lower().split()
    return {" ".join(tokens[i:i+n]) for i in range(len(tokens) - n + 1)}

def contamination_score(eval_input: str, reference_texts: list[str], n: int = 8) -> float:
    """
    Returns fraction of eval_input's n-grams that appear in any reference text.
    > 0.3 on 8-grams is a strong contamination signal for factual evals.
    """
    eval_grams = ngrams(eval_input, n)
    if not eval_grams:
        return 0.0
    reference_grams: set[str] = set()
    for ref in reference_texts:
        reference_grams |= ngrams(ref, n)
    overlap = eval_grams & reference_grams
    return len(overlap) / len(eval_grams)

def audit_eval_set(
    eval_examples: list[dict],
    reference_texts: list[str],
    threshold: float = 0.3,
) -> None:
    flagged = []
    for ex in eval_examples:
        score = contamination_score(ex["input"], reference_texts, n=8)
        if score >= threshold:
            flagged.append({
                "id": ex.get("id", "?"),
                "score": round(score, 2),
                "input_preview": ex["input"][:80],
            })

    print(f"Contamination audit: {len(flagged)}/{len(eval_examples)} flagged (threshold {threshold})")
    for f in flagged:
        print(f"  {f['id']} (overlap {f['score']}): {f['input_preview']}...")
```

The 8-gram threshold isn't arbitrary. 3-grams are too common — you'll flag everything. 8-grams are specific enough: if 30% of an eval input's 8-gram sequences appear verbatim in a reference document, the model almost certainly trained on that text. For coding evals, drop to 6-grams; code has less natural variation and shorter meaningful sequences.

If you don't have a reference corpus handy, skip to the post-cutoff comparison below — it doesn't require corpus access at all.

Every model has a training data cutoff. Performance on content from before the cutoff reflects what the model has absorbed. Performance on genuinely fresh content — events, documents, code written after the cutoff — reflects reasoning rather than recall.

Build two slices of your eval set. One from known pre-cutoff sources. One from post-cutoff sources — recent production logs, GitHub issues filed in the last few months, or dated internal documents from the last quarter. Run both and compare.

``` python
def run_cutoff_comparison(
    model_fn,
    pre_cutoff_examples: list[dict],
    post_cutoff_examples: list[dict],
    judge_fn,
) -> None:
    def score_set(examples: list[dict]) -> float:
        scores = [
            judge_fn(ex["input"], model_fn(ex["input"]), ex.get("expected"))
            for ex in examples
        ]
        return sum(scores) / len(scores)

    pre_score = score_set(pre_cutoff_examples)
    post_score = score_set(post_cutoff_examples)
    gap = pre_score - post_score

    print(f"Pre-cutoff score:  {pre_score:.2%}  ({len(pre_cutoff_examples)} examples)")
    print(f"Post-cutoff score: {post_score:.2%}  ({len(post_cutoff_examples)} examples)")
    print(f"Score gap:         {gap:+.2%}")

    if gap > 0.15:
        print("WARNING: >15pt gap suggests pre-cutoff examples may be contaminated.")
    elif gap > 0.08:
        print("CAUTION: 8-15pt gap — worth investigating on factual tasks.")
    else:
        print("OK: gap within expected variance.")
```

A 15-point gap on a factual task is a red flag. Some gap is normal and expected — the model knows more about things it trained on, by design. But a 20-point swing usually means your pre-cutoff set is measuring memorization, not capability. I've seen teams interpret an 85% eval score as "close to ready for production" when their post-cutoff equivalent was running at 61%.

A canary is a made-up example you fabricate from scratch — it cannot be in any training corpus because it doesn't exist anywhere yet. Test questions about fictional products, code that calls a made-up API, reasoning problems with numbers you invented.

```
CANARY_EXAMPLES = [
    {
        "id": "canary_001",
        "input": "What does the `fetch_zorblex_manifest(format='v3')` function return when called with an empty path argument?",
        "note": "Fictional function. Model must say it doesn't know — not fabricate an answer.",
        "type": "canary_factual",
    },
    {
        "id": "canary_002",
        "input": (
            "Summarize this article about the Vethla Protocol security incident from last week:\n\n"
            "[3-paragraph fictional incident description with specific made-up product names and CVE numbers]"
        ),
        "note": "Fictional event. Model must base summary on the provided text only — not add 'external facts'.",
        "type": "canary_grounding",
    },
]

def run_canary_check(model_fn, canaries: list[dict]) -> None:
    for canary in canaries:
        output = model_fn(canary["input"])
        print(f"\n{canary['id']} ({canary['type']})")
        print(f"Output: {output[:300]}")
        print(f"Note:   {canary['note']}")
        # canaries don't auto-pass/fail — they flag for human inspection
```

Canary examples don't auto-pass or auto-fail — they're for human review. What you're watching for: does the model fabricate plausible-sounding answers to questions with no correct answer? That's the contamination failure mode made visible. A model that genuinely doesn't know will hedge or decline. A model pattern-matching on something from training will state an answer confidently, and it will sound reasonable.

Two or three canaries per eval run costs almost nothing to create and catches the cases where n-gram overlap misses.

Don't delete the contaminated examples. Move them to a `contaminated/` directory with a note explaining why:

```
evals/
  golden.jsonl          # clean examples only
  contaminated/
    golden_flagged.jsonl  # flagged examples, kept for reference
    contamination_audit_2026-11-23.txt
```

Then:

**Measure the inflation first.** Run the full eval both ways — with and without flagged examples. Write the score gap down. Stakeholders need to understand that "88% pass rate" may actually mean "73% on clean examples + inflated to 88% by memorized test data." That's a significant difference in what you're shipping.

**Replace with post-cutoff examples.** Real production logs from the last 90 days are the best source. They're guaranteed post-cutoff and they reflect actual user behavior. Fabricated canaries are second. Public benchmark examples from after the training cutoff are third.

**Tag every example with source and date going forward.** This makes future audits fast:

```
{"id": "g042", "input": "...", "expected": "...", "label": "pass", "source": "prod_logs_2026-11", "added_date": "2026-11-15", "contamination_checked": true}
{"id": "g043", "input": "...", "expected": null, "label": "behavioral", "source": "canary_fabricated", "added_date": "2026-11-23", "contamination_checked": true}
```

The `contamination_checked` flag costs one field and saves you from re-auditing every example after a model upgrade.

N-gram overlap misses semantic contamination — where the model hasn't seen your exact text but has seen thousands of near-identical paraphrases. A paraphrased StackOverflow answer passes the 8-gram check clean and still inflates scores. The post-cutoff comparison is a better signal for semantic contamination because it sidesteps corpus matching entirely.

Canaries don't scale. You can't fabricate 500 examples that provably couldn't be in a training corpus — the effort is too high. They're a spot check, not a systematic defense.

The approach that actually holds for contamination-resistant evals is building the entire eval set from production logs on a rolling basis. Data captured post-deployment is the one class you can prove wasn't in pretraining. That's what the [free test lab](https://github.com/chernevnikolay86-wq/ai-test-verification-lab) uses as the default dataset source. If you want the full picture — how to structure a clean eval pipeline from day one and maintain it across model upgrades — that's the core of [*AI Software Testing in Practice*](https://www.amazon.com/dp/B0HL4SC5PX?tag=aitestingbook-20).

**What is eval-set contamination in LLM testing?**

Eval-set contamination means the examples you're using to test your model were part of its training data. The model has effectively memorized the answers, so its high score reflects recall, not generalization. This inflates benchmark numbers while doing nothing to predict real-world performance.

**How do you detect data leakage in an LLM eval set?**

Three practical checks: run an n-gram overlap comparison between your eval inputs and known training corpora or public benchmarks; test on date-stamped examples from after the model's training cutoff and compare the score gap; and inject canary examples you fabricated yourself that couldn't be in any training corpus.

**What should I do if my eval set is contaminated?**

Replace the contaminated examples with fresh ones drawn from real production logs, fabricated edge cases, or dated content post-training-cutoff. Keep contaminated examples in a separate file so you can track the score gap — the difference between your contaminated and clean scores is a rough measure of how inflated your old benchmarks were.
