Why LLMs Keep Failing at Code Review: Hallucination Causes and Engineering Mitigations
Large language models can produce plausible but incorrect code review comments, cite nonexistent methods, point to unrelated line numbers, and then fabricate explanations when challenged. This article examines these failure modes and their technical causes—attention dilution in long contexts, task-induced fabrication, insufficient metacognition, and version or time-anchor confusion. It then presents engineering mitigations: explicitly constructed inputs, scoped review tasks, structured and verifiable outputs, a machine-first and human-final review pipeline, and multi-model cross-validation. The goal is to help teams use LLMs as constrained first-pass reviewers rather than authoritative judges.
1. A Typical Failure Case
Many developers have encountered a similar situation when using large language models for code review: they pass a diff or several files to the model and ask it to find issues and make suggestions. The resulting review comments look plausible at first glance, but upon checking them one by one, they do not match the code at all. The suggested method names do not exist, the cited line numbers point to unrelated code, and the model may even criticize logic that is not present in the code.
The follow-up exchange is often more confusing. When you question the source of these comments, the model tends to invent a self-consistent explanation—for example, claiming that it only saw the commit message and did not receive the actual code. But if you keep asking, the details it provides clearly come from the real code: specific method names, implementation paths, and variable names that could not have been invented unless it had actually “seen” them.
This chain of hallucinations—a wrong answer, a fabricated explanation, and a fabricated explanation of the explanation—is one of the most typical and alarming failure modes for large language models in code review today.
2. Technical Causes of Hallucination
2.1 Attention Dilution in Long Contexts
Code review tasks often involve a large amount of context: diffs, complete files, related modules, and historical commit messages. When the input context is too long, the model’s attention to the middle portion drops significantly, a widely recognized limitation of long-context processing. The result is that the model remembers the beginning and the end but has a fuzzy memory of code snippets in the middle, and then fills in nonexistent line numbers or logic.
2.2 Task Objective Induces Fabrication
Code review naturally asks the model to “find problems.” If the code itself is reasonably good, the model may still generate suggestions that sound reasonable but do not hold up, simply to complete the task. This is similar to the psychology of a human reviewer who raises formatting comments just to fill a quota. When the model lacks certain evidence, it fills the gap with high-probability language patterns. That is the essence of hallucination: generating content that “sounds right” rather than content that has been “verified as right.”
2.3 Insufficient Metacognition
The most difficult problem is not hallucination itself, but the model’s inability to reliably report the source of its information. When asked “what did you base your review on?”, the model does not actually go back through its context window to verify. Instead, it generates a statistically plausible answer. As a result, repeated questioning produces repeated fabrication, and each explanation may contradict the facts. Developers who hope that “a few more rounds will make it admit the mistake” often end up more confused.
2.4 Version and Time-Anchor Confusion
Code repositories evolve continuously, and there is a strict temporal order among diffs, commits, and branch states. The model lacks reliable anchoring for “which commit, which version,” and can easily mix code information from different versions, producing errors such as reviewing new code based on an old version.
3. Engineering Mitigation Strategies
3.1 Construct Input Explicitly Instead of Relying on the Model to “Look”
Do not expect the model to automatically retrieve and understand the repository. The recommended approach is for the caller to construct the input precisely, including explicit file paths, line ranges, and diff format, and to state in the prompt: “The following is the only basis for review; do not cite information that is not provided.” An illustrative prompt structure is:
Role: Senior code reviewerInput contract:- Base comments only on content inside <diff> tags- Each comment must include the exact file path and line number- If evidence is insufficient, reply "Insufficient evidence; cannot determine"Prohibited:- Citing any file, method, or variable not present in the input- Speculating about the code's historical versions or evolution
The “allowed to refuse” clause is critical: giving the model a legitimate exit significantly reduces its tendency to force out comments.
3.2 Break Tasks Down and Control Context Size
Split broad reviews into single-file or single-module granularity, and pass only the necessary context each time. The more focused the context, the lower the hallucination rate. For cross-file dependencies, the caller should explicitly provide the related code snippets rather than letting the model infer from incomplete memory.
3.3 Require Structured Output and Verifiable Anchors
Require the model to output in a structured format, with each comment carrying fields that can be machine-checked:
{"file": "service/order.go","line": 42,"issue": "Shared map read without a lock in a concurrent scenario","severity": "high","evidence": "Quote the original code snippet from the input"}
After receiving the output, use a script to automatically validate it: does the line number actually exist, and does the evidence field match the input code verbatim? Comments that fail validation should be discarded directly or downgraded to “pending manual confirmation.” This step can filter out most hallucinated comments before they reach human review.
3.4 Build a “Machine First Pass + Human Final Review” Pipeline
The correct role of AI review is an initial filtering funnel, not a final judge. A reasonable process is:
- Static analysis tools perform deterministic checks (style, known defect patterns).
- The large language model performs a semantic first pass and outputs structured comments.
- Automated validation checks consistency between comments and code.
- Comments that pass validation enter the human review queue for final judgment.
In this way, even if the model’s hallucination rate is not low, the engineering process provides a backstop.
3.5 Multi-Model Cross-Validation and Confidence Assessment
For high-risk changes, multiple models can review independently, and only issues flagged consistently by multiple models are retained. At the same time, record the historical adoption rate for each type of comment, gradually building a data-driven understanding of “which issue types should be trusted to AI and which must be reviewed by humans.”
4. Several Rational Perspectives
- Most failures of large language models in code review are not a complete lack of capability, but the result of “unconstrained open-ended tasks + very long context + lack of validation.” The same model can perform much better in a carefully designed workflow.
- Do not trust the model’s self-report about its own behavioral boundaries. Questions such as “what did you see?” and “what did you base your conclusion on?” may themselves produce hallucinations, and must be verified through external means.
- To evaluate whether a model is suitable for your code review scenario, use a fixed test set for systematic evaluation: prepare a batch of code snippets with known defects and known clean code, and measure accuracy, false positive rate, and line-number hit rate. Do not draw conclusions from one or two bad experiences.
- The trade-off between cost and effectiveness always exists. Some models follow a lower-cost, large-context route and are suitable for initial screening; for high-quality review scenarios, the budget should be spent on more precise input construction and human review rather than simply stacking model capability.
5. Conclusion
AI-assisted code review is still at the stage of “improving efficiency but not providing the safety net.” Rather than arguing about whether a particular model “works,” it is better to focus on process design: precise input construction, mandatory verifiable output formats, and two-layer machine and human review. Manage the model as a junior reviewer that requires strict acceptance testing, and the efficiency gains it brings can be real and reusable. Treat it as an authoritative judge, and what you get will be repeated and frustrating hallucinations.
