Originally published on tamiz.pro.
When an AI assistant suggests a code snippet, the worst outcome isn't a compile error — it's a snippet that compiles, passes tests, and is still wrong. That silent failure is the hallucination problem, and it's uniquely dangerous in developer tools because the cost of a wrong answer isn't a bad joke or a misquoted fact; it's a production incident, a security vulnerability, or a subtle bug that ships to thousands of users.
But not all hallucinations are created equal. There's a critical distinction between a model that produces the wrong thing (the "what") and a model that produces the right thing for the wrong reason (the "why"). Most evaluation pipelines and guardrails only check the first. This article explores why the "why vs what" problem is the real blocker for trustworthy AI in software engineering, and how counterfactual reasoning — asking "what would happen if I changed the input?" — offers a practical fix.
- 1. Why Developer Tools Are a Hallucination Magnifier
- 2. The "Why vs What" Distinction
- 3. Root Causes of Hallucination in Code Models
- 4. The Counterfactual Fix: Consistency as a Proxy for Grounding
- 5. A Practical Implementation Sketch
- 6. Limitations and the Road Ahead
- Frequently Asked Questions
1. Why Developer Tools Are a Hallucination Magnifier
General-purpose chatbots can hallucinate and still be useful — a wrong trivia answer is annoying, not catastrophic. Developer tools occupy a different regime. When an LLM generates a function body, a regex pattern, a CI configuration, or a security rule, the output is consumed by a machine, not a human. Machines don't apply common sense; they apply the semantics you wrote. A hallucinated API name might pass a linter, a hallucinated security fix might pass a test suite, and a hallucinated documentation example might be copy-pasted into production code.
Three factors make code generation especially prone to silent hallucination:
- Lack of a single ground truth. For a natural-language question like "What's the capital of France?" there's one correct answer. For "Write a function that parses ISO 8601 dates," there are dozens of correct implementations, and thousands of incorrect ones that are still syntactically valid and semantically plausible. The model can't be trained to maximize exact-match accuracy because there's no exact match to maximize.
- Compilation is not verification. A code snippet that compiles and passes unit tests is not evidence that it does what the user asked. The tests are written by the same model or by a developer who may share the model's misconceptions. In a self-referential loop, a model can generate code, generate tests for that code, and pass those tests — all while being wrong about the original intent.
- Context is compressed and lossy. Code models operate on a window of tokens. The "why" behind a piece of code — the design rationale, the API contract, the edge cases that motivated a branch — is often in a comment, a type signature, or a docstring that gets truncated or semantically flattened. The model is forced to infer intent from a partial view, which is precisely the setup for hallucination.
2. The "Why vs What" Distinction
Let's formalize the distinction that drives this article.
- The "what" is the model's output: the code, the explanation, the command, the configuration. It's observable, testable, and measurable.
- The "why" is the model's internal reasoning or its grounding in the input context: why this particular function signature is correct, why this API is being called, why this branch handles this edge case. It's not directly observable, and it's rarely evaluated.
Hallucinations fall into two buckets:
Type A: Wrong "what"
The model produces an output that is factually incorrect or non-functional. Examples:
- A function that references
np.meanwhennp.averageis intended. - A regex that matches the wrong date format.
- A security rule that blocks
GETrequests instead ofPOST.
Type A errors are relatively easy to catch with compilation, static analysis, or unit tests. They're the ones that get caught in CI.
Type B: Wrong "why"
The model produces an output that looks correct — it compiles, it passes tests, it's syntactically idiomatic — but the reasoning behind it is fabricated or misattributed. Examples:
- The model generates a correct-looking function but cites a non-existent overload of a standard library method.
- The model explains a piece of code by inventing a performance characteristic that doesn't hold.
- The model refactors a function based on a type annotation it hallucinated in a previous turn, leading to a cascade of plausible-but-wrong decisions.
Type B errors are the real threat. They pass every automated check because the checks are designed to verify the "what," not the "why." The model has learned to produce outputs that satisfy the evaluation surface without being grounded in the underlying task. This is the core of the "why vs what" problem: we are training and evaluating models on the wrong axis.
3. Root Causes of Hallucination in Code Models
To fix the "why vs what" problem, we need to understand its etiology. There are four primary contributors.
3.1 Training Data: Code Is a Poor Teacher of Causality
Code datasets (GitHub, Stack Overflow, etc.) are rich in examples but poor in explanations. A function body tells you what the code does, but rarely why the author chose that particular approach. The model learns correlations between tokens, not causal relationships between intent and implementation. When asked to generate code for a novel task, it can't reason about consequences — it can only interpolate from patterns. This is the fundamental limitation of next-token prediction for reasoning tasks.
3.2 Objective Mismatch: Next-Token Prediction ≠ Grounded Reasoning
The training objective is to maximize the likelihood of the next token given the previous ones. This objective rewards fluency and plausibility, not correctness. A model that produces a syntactically perfect but semantically wrong function gets no penalty at training time if that function appears in the training data. In fact, it gets rewarded — the loss is lower for a plausible continuation than for a novel, correct one that doesn't match the training distribution. The model is literally optimized to hallucinate in the Type B sense.
3.3 Decoding Strategies: Sampling Amplifies Plausibility Gaps
Even a well-calibrated model can produce Type B errors through decoding. Greedy decoding tends to produce the most probable sequence, but "most probable" is not "most grounded." Temperature sampling, used to increase diversity, can generate code that is statistically plausible but causally disconnected from the prompt. The model doesn't know it's guessing; it just samples from a distribution that has a long tail of plausible-but-wrong continuations.
3.4 The Absence of a Verifier
Most production systems that use code generation have no verification layer that checks the semantic correctness of the output. They check syntax, they run tests, they may run a linter — but none of these verify that the code does what the user intended. The intent is only in the prompt, and the prompt is only in the model's context. There's no external oracle that says "this function should return the number of days in a month, given a year and month." Without a verifier, the model is the only authority, and the model is hallucinating.
4. The Counterfactual Fix: Consistency as a Proxy for Grounding
If we can't directly observe the model's "why," how can we detect when it's wrong? The answer is to use counterfactual reasoning: instead of asking "is this output correct?" we ask "does this output respond correctly to changes in the input?"
A counterfactual is a hypothetical modification of the input context. For example, if the model is asked to generate a function that parses a date string, a counterfactual might be to change the input type from string to number and see if the model's output (or its reasoning) changes accordingly. If the model's output is invariant to a perturbation that should change the answer, the model is not grounded in the input — it's hallucinating.
This is a powerful idea because it doesn't require an external oracle. It only requires a model of what should change. That model is much easier to construct than a full specification of correctness. You don't need to know the exact correct function; you just need to know that changing the input type should change the function's behavior.
4.1 Formalizing Counterfactual Consistency
Let M be the model, x be the input context, and y = M(x) be the output. Let P be a set of perturbation functions, each of which maps x to a modified context x'. For each perturbation p ∈ P, we have a corresponding expected change Δ_p that describes how the output should change.
A model is counterfactually consistent with respect to p if:
M(p(x)) ≈ Δ_p(M(x))
where ≈ denotes semantic equivalence (not exact token match). If M(p(x)) is not ≈ to Δ_p(M(x)), the model has failed the counterfactual check for perturbation p.
For code generation, we can define perturbations that are cheap to generate and have predictable effects:
- Type perturbation: Change a parameter's type annotation. The output should use different type-specific operations.
-
API perturbation: Replace a function call with a semantically equivalent but syntactically different one (e.g.,
Array.prototype.mapvs. aforloop). The output should still be functionally equivalent. - Context perturbation: Remove a relevant comment or docstring. The model's output should become less confident or change its approach.
- Constraint perturbation: Change a boundary condition (e.g., "return the first element" vs. "return the last element"). The output should change in a predictable way.
4.2 Why This Works
The counterfactual check is a proxy for grounding because a model that has genuinely understood the input will have a causal model of the relationship between input and output. When the input changes, the output must change in a way that reflects that causal model. A model that is merely interpolating from surface patterns will often be invariant to perturbations that don't change the surface statistics — even when they should change the semantics.
Consider a concrete example. Suppose the prompt is:
Write a Python function `parse_date(s: str) -> datetime` that parses an ISO 8601 date string.
The model generates:
from datetime import datetime
def parse_date(s: str) -> datetime:
return datetime.fromisoformat(s)
Now apply a type perturbation: change s: str to s: bytes. A grounded model should produce a function that decodes the bytes first, or uses bytes.fromhex, or raises a clear error. A hallucinating model might produce the exact same function, because it's not actually attending to the type annotation — it's just generating the most likely continuation for the token sequence "parse_date". The counterfactual check catches this: the output didn't change when it should have.
5. A Practical Implementation Sketch
Counterfactual checking can be implemented as a post-generation verification layer. Here's a Python-style pseudo-code outline of the architecture:
from dataclasses import dataclass
from typing import Callable, Any, List
@dataclass
class CounterfactualCheck:
name: str
perturb: Callable[[str], str] # transforms the prompt
should_change: Callable[[Any, Any], bool] # compares old and new outputs
class CounterfactualVerifier:
def __init__(self, model: Callable[[str], str]):
self.model = model
self.checks: List[CounterfactualCheck] = []
def add_check(self, check: CounterfactualCheck) -> None:
self.checks.append(check)
def verify(self, prompt: str, output: str) -> List[str]:
"""Return a list of failed counterfactual checks."""
failures = []
for check in self.checks:
perturbed_prompt = check.perturb(prompt)
perturbed_output = self.model(perturbed_prompt)
if not check.should_change(output, perturbed_output):
failures.append(check.name)
return failures
5.1 A Concrete Example: Type Perturbation for a Date Parser
Here's how you'd wire it up for the parse_date example:
# Define the perturbation: change str to bytes in the signature
perturb_type = lambda prompt: prompt.replace("s: str", "s: bytes")
# Define the expected change: the output must reference decode or bytes
def output_changed(old: str, new: str) -> bool:
# If the output references bytes-related operations, it's a valid change
return "decode" in new or "bytes" in new or "fromhex" in new
check = CounterfactualCheck(
name="type_perturbation_str_to_bytes",
perturb=perturb_type,
should_change=output_changed,
)
verifier = CounterfactualVerifier(model=my_llm)
verifier.add_check(check)
failures = verifier.verify(
prompt="Write a Python function parse_date(s: str) -> datetime...",
output="""from datetime import datetime
def parse_date(s: str) -> datetime:
return datetime.fromisoformat(s)"""
)
if failures:
print(f"Hallucination detected: {failures}")
This is a toy example, but the pattern scales. In a production system, you'd maintain a library of perturbation functions for common code patterns: type annotations, function signatures, imports, control-flow conditions, and docstrings. Each perturbation comes with a predicate that describes the expected semantic change.
5.2 The Verification Pipeline
A realistic integration would look like this:
User Prompt → LLM Generation → [Syntax Check] → [Unit Test] → [Counterfactual Verifier] → [Accept/Reject]
The counterfactual verifier runs after the cheap checks pass. It's expensive — each perturbation requires another LLM call — so you'd only run it on outputs that already pass syntax and tests. This creates a layered defense:
- Layer 1 (cheap): Compilation/linting catches Type A errors.
- Layer 2 (moderate): Unit tests catch behavioral errors in the "what."
- Layer 3 (expensive): Counterfactual checks catch Type B errors in the "why."
6. Limitations and the Road Ahead
Counterfactual consistency is a powerful idea, but it's not a silver bullet. Here are the key limitations you need to account for.
6.1 The Perturbation Generation Problem
The hardest part is designing perturbations that are meaningful. A perturbation that changes the input in a way that doesn't affect the correct output (e.g., changing a variable name) will produce a false positive — the model's output won't change, but it's not hallucinating. Conversely, a perturbation that changes the input in a way that should change the output but doesn't have a clear expected effect (e.g., changing a comment) will produce a false negative. Building a robust perturbation library requires domain expertise and careful curation.
6.2 Computational Cost
Each counterfactual check requires an additional LLM inference call. If you have 10 perturbations per prompt, that's 10x the inference cost. For interactive developer tools, this is prohibitive unless you:
- Run checks asynchronously and only on the final accepted output.
- Use a smaller, cheaper model for the counterfactual runs.
- Cache results by prompt hash.
- Sample a subset of perturbations rather than running all of them.
6.3 Necessity vs. Sufficiency
Counterfactual consistency is a necessary condition for grounding, but not a sufficient one. A model can pass all counterfactual checks and still be wrong in a way that no perturbation catches. For example, if the perturbation space doesn't cover a particular failure mode, the model can hallucinate in that mode undetected. The technique is best used as a filter — it raises the bar for what gets accepted, but it doesn't guarantee correctness.
6.4 The "Why" Remains Unobservable
Even with counterfactual checks, we're still inferring the "why" indirectly. We never actually see the model's reasoning; we only see how its output responds to perturbations. This is a fundamental epistemic limitation of black-box models. The only way to fully observe the "why" is to make the model's reasoning explicit — either through chain-of-thought prompting, or by training models to produce verifiable reasoning traces. Until then, counterfactual consistency is the best proxy we have.
Frequently Asked Questions
Q1: How is a counterfactual check different from a unit test?
A unit test verifies that the output matches an expected behavior for a given input. A counterfactual check verifies that the output changes in the expected way when the input changes. Unit tests are static; counterfactual checks are dynamic. A unit test can pass even if the model is hallucinating, as long as the hallucination happens to produce the tested behavior. A counterfactual check catches cases where the model is invariant to input changes that should matter.
Q2: Can this technique be applied to non-code outputs, like documentation or security analysis?
Yes, with the right perturbations. For documentation, you'd perturb the code being documented and check that the explanation changes. For security analysis, you'd perturb the vulnerability pattern and check that the recommended fix changes. The core principle — "if the input changes, the output should change in a predictable way" — applies to any generation task where there's a causal relationship between input and output.
Q3: What's the biggest practical barrier to adopting this in a production developer tool?
Cost. Running multiple LLM calls per generation is expensive, and the perturbation library requires ongoing maintenance. The most viable path is to run counterfactual checks only on high-risk outputs (e.g., security patches, API migrations) and to use a smaller, cheaper model for the verification runs. As inference costs drop and perturbation libraries mature, this will become a standard layer in AI-assisted development pipelines. For more on practical AI engineering patterns, see Tamiz's Insights.
Top comments (0)