Code models are increasingly evaluated with an external memory attached. That memory might be a retrieved set of similar training examples pasted into the prompt, or a nearest-neighbor table of cached model states consulted at every token. The standard safeguard is to delete benchmark items from that memory by exact or near-exact text matching. We argue this safeguard misses the leak that matters most for code. Consider a datastore entry with the same control flow and the same sequence of grammar rules as a test solution, but with different variable names, an extra decorator, or a flipped if/else. Text matching passes it as clean. A model that retrieves it can still copy its structure. We propose to measure how much of a retrieval-augmented code model's benchmark score comes from these "structural twins." We also test whether a grammar-level detector catches them better than simpler identifier-normalized deduplication does.
The opportunity comes from two findings that have not yet been connected. Work on repetition in code generation showed that the meaningful unit of repetition is the grammar rule, not the token: structural loops are nearly nine times more common than literal ones. That work gave an online way to find repeated rule sequences with suffix arrays. Separately, work on contamination countermeasures showed that models stay robust to syntactic rewrites of memorized code, while perplexity cannot tell memorized code from fresh code. If memorization survives syntactic rewriting inside the weights, it should also survive inside a retrieval memory. A rule-level view of the datastore is the obvious instrument for checking this.
Core Claim
For retrieval-augmented code generation on HumanEval-ET and MBPP-ET, we claim three things. First, a measurable part of the gain from retrieval comes from datastore entries that match a test solution at the level of grammar-rule sequences but would pass lexical decontamination. Second, removing those entries lowers the score by more than removing lexical duplicates alone. Third, the size of this "structural leak" can be estimated per benchmark item by a coverage score computed over grammar-rule sequences.
The contribution is primarily a measurement: an audit protocol and a number. It is secondarily a detector. If a cheaper detector finds the same twins, we will say so and keep the measurement claim alone.
Relation to Prior Work
Three papers motivate the proposal by showing leakage through channels that text matching does not police.
Search-Time Data Contamination shows that web-search agents retrieve benchmark answer keys from public mirrors. A roughly 3% contamination rate lifted Sonar Deep Research on Humanity's Last Exam from 17.4% to 37.5%. That leak is verbatim and comes from the open web. Ours is structural and comes from a curated datastore the evaluator controls.
Retrieval Collapses When AI Pollutes the Web shows that the generator does not reliably filter bad retrieved content: once BM25 admits 19–24% adversarial passages, answer accuracy falls below the clean baseline. This argues against relying on the generator to ignore leaked twins.
Concerned with Data Contamination? Assessing Countermeasures in Code Language Model supplies the key asymmetry, and we reuse its perturbation families. Its findings were as follows:
- Syntactic refactoring did not stop memorized performance and sometimes raised it.
- Semantic changes such as renaming and decorators cut WizardCoder by up to 15.9%.
- Perplexity ranged 3.37–5.17 across years without separating contaminated from clean code.
That study concerns parametric memory only. We ask the same question of an external datastore.
The memory systems we audit come from two lines of work.
- Retrieval into the prompt. Training Data is More Valuable than You Think (REINA) retrieves similar training input–label pairs with BM25 and concatenates them to the input. Its only leakage guard is removing the target instance itself, which is exactly the lexical guard we expect to be insufficient.
- Retrieval into the output distribution. Generalization through Memorization: Nearest Neighbor Language Models (kNN-LM) mixes the model's next-token distribution with one built from nearest neighbors in a cache of hidden states. It has no decontamination step at all, and its neighbors are matched in representation space, where renamed twins may sit close together.
The detector comes from Rethinking Repetition Problems of LLMs in Code Generation (RPG). RPG maps generated tokens to context-free grammar rules with a pushdown automaton, a parser that tracks nested structure. It then finds repeated rule sequences with suffix and longest-common-prefix arrays, and penalizes tokens that would extend a loop. RPG uses this machinery within a single generation to detect self-repetition. We point the same machinery across documents, from benchmark item to datastore entry, to detect structural copying.
Two contamination-proof benchmarks constrain the design but do not compete with it. DyVal generates fresh reasoning tasks from random graphs, and models strong on static benchmarks scored near zero on it. A²RBench shows a 17.7% drop under symbolic remapping. Both sidestep contamination by building new items. Neither tells a practitioner how much of an existing static score with retrieval attached was leaked, and that is the question we answer. We borrow their logic for a clean control set.
Research Program
Building the structural index
We parse every datastore entry and every benchmark reference solution into its sequence of grammar rules. The datastore is a Python corpus drawn from The Stack v2 plus the 2022–2023 GitHub split used by Cao et al. The parser is RPG's pushdown automaton over the Python grammar. Identifiers and literals vanish at this level of abstraction, which is the point.
All rule sequences go into one generalized suffix array. For a benchmark item $q$ and datastore entry $d$, we define structural coverage $c_L(q,d)$ as the fraction of positions in $q$'s rule sequence covered by maximal substrings shared with $d$ of length at least $L$ rules. The threshold $L$ keeps trivial shared fragments, such as a bare return, from counting. A twin is any $d$ with $c_L(q,d) \ge \tau$. Both $L$ and $\tau$ are fixed on a held-out slice of injected twins before any score is measured.
Coverage rather than whole-sequence equality matters because benchmark-like functions often sit inside larger files. A whole-file hash would miss them.
Two retrieval-augmented systems
We use an open code model (StarCoder, as in Cao et al.) in two configurations:
- a REINA-style system that retrieves the top-$k$ datastore entries by BM25 and prepends them to the prompt;
- a kNN-LM over the same datastore, keyed on the model's own hidden states.
The leak estimate
For each detection method $M$, we report:
$$\Delta_M = \text{Pass@1}(\mathcal{D}) - \text{Pass@1}(\mathcal{D} \setminus \text{Twins}_M)$$
Here $\mathcal{D}$ is the lexically decontaminated datastore and $\text{Twins}_M$ is the set of entries flagged by method $M$. All other settings stay fixed. The structural leak is the extra drop beyond what lexical removal already achieved.
Controlled injection for ground truth
Natural twin rates are unknown, so we also inject perturbed copies of HumanEval and MBPP solutions into the datastore at fixed rates. The perturbations follow Cao et al.: branch flips, renaming, and added decorators. This gives detector recall against known twins. It also gives a dose–response curve of Pass@1 against injection rate for each perturbation type.
A secondary repetition measurement
Using RPG's loop detector purely as a measuring device, we test whether retrieving partial structural twins raises the rate of self-reinforcing structural loops in generation. The hypothesis is that the generator copies a twin's control flow past the point where it fits the new problem. This is a secondary result and is reported only if the rate differs from runs without retrieval.
Baselines
Naive reference points. The first is the same model with no retrieval, which shows what the parametric model alone achieves. The second is retrieval over the undecontaminated datastore, which bounds the leak from above. The relevant published number is RPG's 11.3% Pass@1 gain on HumanEval-ET over greedy decoding (Rethinking Repetition Problems). We report it for scale, not as a competitor, because it concerns decoding rather than retrieval.
Lexical decontamination. We remove entries sharing long token n-grams with any benchmark solution, plus REINA's target-instance filter. This is what practitioners actually do, so every $\Delta$ is measured relative to it.
Identifier-normalized deduplication (the strongest competitor). Every identifier and literal is replaced by a placeholder, and long n-gram overlap is computed on the normalized token stream. It is the strongest competitor because it erases exactly the renaming perturbation that hurt WizardCoder in Cao et al., at a fraction of the parsing cost.
Embedding-similarity deduplication. Entries whose code embedding lies within a cosine threshold of a benchmark solution are removed. This also tests whether the kNN-LM's own retrieval space would flag the twins it is about to use.
Perplexity filter. Included for completeness, since it is the membership signal Cao et al. found ineffective.
Fairness and the ablation. All detectors get the same datastore, the same removal budget, and the same tuning protocol: thresholds chosen on the identical held-out injected slice to hit equal false-positive rates on fresh post-cutoff code. The ablation that isolates our key ingredient replaces grammar-rule sequences with normalized token sequences, keeping the suffix-array coverage score unchanged. This separates the value of the rule abstraction from the value of coverage-based partial matching.
What counts as winning. No reported result was found on Lacuna for detection recall or Pass@1 inflation from structural near-duplicates in code retrieval datastores, so there is no published bar. We set our own. The rule-level detector beats identifier-normalized deduplication if, at matched false-positive rate, two conditions both hold:
- its recall on injected branch-flip and decorator twins is higher by a margin outside bootstrap confidence intervals;
- its $\Delta$ on the natural datastore is larger.
Why not just…?
Why not just use exact or n-gram deduplication, as everyone already does? Branch flips and renaming change the token stream while leaving the structure intact. Cao et al. found that branch flips do not stop memorized performance. The injection experiment measures directly how many known twins survive n-gram deduplication and how much Pass@1 they still add. If n-gram deduplication catches nearly all of them, the core claim is false and we will report that.
Why not just normalize identifiers and deduplicate? This is the real threat, and we treat it as possibly sufficient. For whole-function renamed copies, normalized n-grams and rule sequences may flag almost the same sets. Rule sequences should differ in two cases: when twins are embedded in larger files, and when perturbations reorder or reshape syntax, such as flipped branches, added decorators, or rewritten loop headers. In those cases normalized tokens shift while rule subsequences persist. If the two detectors' flagged sets overlap almost entirely and give equal $\Delta$, we drop the grammar component. We then present the audit with normalized deduplication as the recommended tool, because the measured leak is the finding that matters.
Why not just filter by perplexity or another membership signal? Cao et al. found mean perplexity indistinguishable across contaminated and clean years (3.37–5.17). There is no reason to expect better separation on datastore entries scored by the same model. We include the filter only to confirm this in the retrieval setting.
Why not just evaluate on fresh problems and skip auditing? Fresh generation in the style of DyVal or A²RBench is the right long-term fix, and we use post-cutoff problems as our clean control. But static code benchmarks remain the reported numbers for retrieval-augmented systems. Fresh benchmarks cannot say how much of those existing numbers is leak, and the audit can.
Decisive Experiments
The first check is whether the structural leak exists at all. On HumanEval-ET and MBPP-ET, with both the BM25-prompt system and the kNN-LM, we compare $\Delta$ under lexical decontamination alone against $\Delta$ after additionally removing structural twins.
The control is a set of post-cutoff functions from the 2023 split of Cao et al.'s corpus. Removing an equal number of randomly chosen entries there should change Pass@1 negligibly. A structural leak is confirmed only if twin removal lowers benchmark Pass@1 significantly while equal-size random removal does not. It must also lower the fresh-problem control by less than it lowers the benchmark, which rules out removing generally useful code.
The second check is the injection dose–response. If Pass@1 rises with the injection rate of branch-flipped and decorated twins after lexical decontamination, the datastore is a contamination channel that current practice cannot see. Running the same curve under parametric-only evaluation tells us whether retrieval amplifies the effect Cao et al. observed in weights.
The third check is the head-to-head between rule-level coverage and identifier-normalized coverage at matched false-positive rate. It determines whether the grammar machinery from structural repetition work earns its parsing cost or whether the simpler tool should be the published recommendation.
References
- Search-Time Data Contamination
- Retrieval Collapses When AI Pollutes the Web
- Concerned with Data Contamination? Assessing Countermeasures in Code Language Model
- Training Data is More Valuable than You Think: A Simple and Effective Method by Retrieving from Training Data
- Generalization through Memorization: Nearest Neighbor Language Models
- Rethinking Repetition Problems of LLMs in Code Generation
- DyVal: Dynamic Evaluation of Large Language Models for Reasoning Tasks
- A²RBench: An Automatic Paradigm for Formally Verifiable Abstract Reasoning Benchmark Generation