When a language model writes code against a library, a common fix for invented functions is retrieval-augmented generation: look up the relevant documentation and paste it into the prompt. High scores on API-calling benchmarks are then read as evidence that the model understood the retrieved documentation. For popular libraries and web APIs, that reading is unsafe. The model has almost certainly seen the same functions thousands of times during pretraining, so it may simply be recalling them while ignoring the documents in front of it. This is benchmark contamination at the level of the interface rather than the test question. It produces domain-specific hallucination whenever the real interface differs from the memorized one: a library version changes, an enterprise fork renames something, or a hospital's schema departs from the textbook.
We propose to separate the two explanations by changing the interface itself. We take existing executable code-generation tasks and apply deterministic, semantics-preserving mutations to the APIs they use. These mutations rename functions, reorder or rename arguments, change units or defaults, restructure return values, or remove an endpoint entirely. Each mutated library is backed by a working wrapper, and its documentation is rewritten to match. The model receives only the mutated documentation through retrieval. Because the reference solution can be rewritten by the same transformation, the correct answer is known by construction. When a model fails, we can rerun its program against the original, unmutated library. If it succeeds there, the failure is a measured reversion to memory, not an inferred one.
Core Claim
Our central claim is that, for widely used APIs, current code-generation accuracy under retrieval mostly reflects parametric recall rather than reading of the retrieved documentation. We predict that the gap between accuracy on faithful and counterfactual documentation grows with how often the API appears in public code. Prior contamination work found that memorization grows with model size, so we expect the gap to grow with model size as well. We also expect the existing mitigations to split cleanly by mutation type. Constrained decoding over valid symbol names should repair renaming but not argument reordering or unit changes. Prompted verification should help with removed endpoints but not with silent semantic changes.
What would be new is a matched-pair, execution-verified measurement of documentation reliance in code. It needs no frontier-model oracle and no access to training data, so it works on closed models.
Grounding in Prior Work
Three papers motivate the gap. Quantifying Contamination in Evaluating Code Generation Capabilities of Language Models audits open code corpora against HumanEval and MBPP. It finds exact matches for 20.8% of MBPP in StarCoderData, and it shows StarCoderBase-15.5B scoring 72% on the most-leaked tenth of problems versus 22% on the least. That work is limited to static, closed-book puzzles and needs the pretraining corpus. We instead target retrieval-augmented API use and infer reliance from behavior. DyCodeEval rewrites the story of a problem while keeping its algorithm fixed. A Llama-3.2-1B model fine-tuned on leaked seeds falls from about 80% to about 13% under rewriting. DyCodeEval mutates the question and leaves the interface untouched, and it relies on Claude-3.5-Sonnet agents with human checks for validity. Our mutations act on the interface and are valid by construction through program rewriting. Code Hallucination shows GPT-4 ignoring a modified constraint and reproducing a memorized LeetCode solution, which is a qualitative case of the reversion we want to count systematically.
Three other papers supply methods we test as mitigations and also constrain our predictions. MARIN feeds repository skeletons into the prompt and masks next-token probabilities with a prefix tree of valid API symbols. It cuts macro hallucination rate on APIHulBench by 73.56%. Because it relies on fresh repositories created in 2023–2024 to avoid contamination, the protection fades as models retrain. Name masking also cannot detect a call whose name is valid but whose arguments follow the old order. Parameters vs. Context (CK-PLUG) detects conflicts between memory and context by comparing prediction entropy with and without the context, then blends the two sets of logits. It was only evaluated on natural-language counterfactual QA, so our benchmark is its first executable test. Can Tool-augmented LLMs be Aware of Incomplete Conditions? documents "action bias," the tendency to call tools even when information is missing, on static perturbations of APIBank and ToolBench. It also introduces a five-step verification prompt. We reuse that prompt for our endpoint-removal mutations.
Research Program
We build two executable testbeds.
The first uses pandas through the tasks in DataFrame QA. These are UCI-DataFrameQA, 547 question–query pairs over 11 datasets, and its modified WikiSQL split. The reference programs are short pandas expressions, so syntax-tree rewriting maps each reference program to the mutated API exactly. A thin Python wrapper module exposes the mutated interface over real pandas and serves as the counterfactual library. Its documentation is generated from pandas docstrings with the same rename and reshape map applied.
The second uses REST calls from API Pack. API Pack is built from OpenAPI specifications, the machine-readable descriptions of web endpoints. We mutate the specifications, stand up mock servers from them, and grade a generated request by whether the mock server accepts it and returns the expected response.
Mutations come in five families of increasing subtlety. Renaming changes only the symbol. Reordering swaps positional arguments of the same type. Relabeling renames keyword arguments. Semantic shifts change units, defaults, or index conventions. Removal deletes the endpoint, and the documentation says so, so the correct behavior is to abstain.
For each task we measure three quantities. Accuracy under faithful documentation and accuracy under mutated documentation, both with identical retrieval, give the documentation reliance gap. The reversion rate is the fraction of mutated-condition failures that execute correctly against the original API. For removal mutations, we measure abstention quality in the F1 style used by the incomplete-conditions benchmark. We estimate API popularity from occurrence counts of each function or endpoint name in the StarCoderData Python split and The PILE GitHub split. We then regress the reliance gap on popularity and model size. The model pool spans 1B to 34B open code models plus closed models accessed only through their APIs.
Baselines
The naive reference point is closed-book generation with no documentation, run on both faithful and mutated tasks. On mutated tasks this should approach zero except through lucky guesses, which lets us calibrate the reversion detector.
The standard competitor is retrieval with few-shot examples in the style of API Pack. That paper reports CodeLlama-13B fine-tuned on 20,000 Python instances reaching 49.5% on entirely unseen APIs under 3-shot retrieval, against 44.3% for GPT-4. This is the strongest reported number in the file for retrieval-augmented API calling. We rerun that recipe with our retriever and documentation on both conditions. No reported result was found on Lacuna for any model on counterfactually mutated API documentation.
The strongest name-level competitor is MARIN-style constrained decoding. We build a prefix tree over the mutated symbol set, which is language-agnostic for a fixed symbol list, and we also inject skeleton context. Its reported 73.56% reduction in macro hallucination rate on Java sets the bar for renaming mutations.
The strongest conflict-level competitor is CK-PLUG in its adaptive mode. On counterfactual QA it moved memory recall on LLaMA3-8B between 9.9% and 71.9%, against a fixed 42.1% for standard retrieval. It costs two forward passes per token, and we report that cost.
The prompting competitor is Structured Verification. It raised Gemma-3-4B from 20.90% to 68.57% F1 on ToolBench API replacement.
We also run an execution-feedback loop that retries after interpreter errors, following AILS-NTUA. This loop can catch renaming but not silent semantic shifts, which still execute and simply return the wrong answer.
All methods share the same retriever, documentation, base models, decoding temperature, and a fixed budget of prompt variants tuned on a held-out mutation seed. We call a mitigation successful if it cuts the reliance gap and the reversion rate on the semantic-shift family without lowering faithful-condition accuracy. This is the family where no current method has a mechanism.
The key ablation crosses each mitigation with each mutation family. It isolates whether a gain comes from blocking invalid names or from reading the documentation.
Why not just…?
Why not just evaluate on APIs released after the training cutoff, as APIHulBench does? Temporal filtering protects a benchmark only until the next model is trained, and it gives no matched comparison. A new API differs from an old one in difficulty, documentation quality, and domain, so a lower score cannot be attributed to missing memorization. Our mutated tasks are the same task with the same computation, and the mutation can be regenerated with a new seed whenever we suspect leakage. We will still report post-cutoff APIHulBench numbers alongside ours, to check whether the two methods rank models the same way.
Why not just use API Pack's unseen-API split? It measures generalization to APIs the fine-tuning data lacked, not APIs absent from pretraining. Many Level 3 APIs are public and likely memorized from the web. Crucially, it cannot say why a model fails. Our reversion check can, because a failing program that succeeds on the original library is direct evidence of reliance on memory.
Why not just apply prefix-tree constrained decoding and declare the problem solved? For pure renaming, this is a real threat, and we expect it to close most of the gap. That is why the benchmark weights reordering, relabeling, and semantic shifts, where every emitted symbol is valid and only the meaning has changed. If constrained decoding also closes the gap on those families, our central claim that current mitigations miss semantic conflicts is wrong, and the experiment will show it.
Why not just tell the model to follow the documentation? Prior evidence suggests instructions lose to memory. Code Hallucination shows GPT-4 overriding an explicit constraint, and DataFrame QA reports pretraining habits overriding schema instructions. We nonetheless include an explicit "the API has changed; trust only the docs" prompt and Structured Verification as baselines. If either closes the gap, it is the cheapest fix and we will say so.
Proposed Experiments
The first decisive check is validity. On faithful documentation, the wrapper and mock servers must reproduce reference outputs on every task. On mutated documentation, rewritten references must produce identical outputs. Any mismatch is a bug in the benchmark, not a model failure.
The second check tests the central claim. We expect a positive slope of the reliance gap against log popularity across APIs within each model, and a reversion rate that dominates the mutated-condition failures for popular pandas functions. If the gap is flat in popularity, or if failures are mostly novel errors rather than reversions, memorization is not the main driver, and the framing should shift toward plain documentation-reading difficulty.
The third check covers model size. Following the contamination audit's finding that memorization grows with scale, we predict larger open models show a larger reversion rate on semantic shifts even when their faithful accuracy is higher. A 7B model beating a 34B model on mutated tasks would echo the scaling inversion DataFrame QA reported.
The fourth check is the mitigation matrix described under Baselines, with compute cost per generation reported for each cell.
Finally, as a transfer test, we apply field-renaming and nesting mutations to FHIR resources on the FHIR-AgentBench validation set. That set has 424 questions, and the GRPO-trained FHIR agent reports Qwen3-8B reaching 77.1% on it. The test asks whether that agent's gains survive a schema that looks like another hospital's. This is cross-site variation that its authors left untested.
References
- Quantifying Contamination in Evaluating Code Generation Capabilities of Language Models
- DyCodeEval: Dynamic Benchmarking of Reasoning Capabilities in Code Large Language Models Under Data Contamination
- Code Hallucination
- Towards Mitigating API Hallucination in Code Generated by LLMs with Hierarchical Dependency Aware
- Parameters vs. Context: Fine-Grained Control of Knowledge Reliance in Language Models
- Can Tool-augmented Large Language Models be Aware of Incomplete Conditions?
- DataFrame QA: A Universal LLM Framework on DataFrame Question Answering Without Data Exposure
- API Pack: A Massive Multi-Programming Language Dataset for API Call Generation
- AILS-NTUA at SemEval-2025 Task 8: Language-to-Code prompting and Error Fixing for Tabular Question Answering
- Reinforcement Learning for Tool-Calling Agents in Fast Healthcare Interoperability Resources (FHIR)