AI Hallucinations in Developer Tools: The 'Why vs What' Problem and the Counterfactual Fix
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 co

Posted on Nov 24 • Originally published at 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.
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:
Let's formalize the distinction that drives this article.
The model produces an output that is factually incorrect or non-functional. Examples:
Type A errors are relatively easy to catch with compilation, static analysis, or unit tests. They're the ones that get caught in CI.
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:
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.
To fix the "why vs what" problem, we need to understand its etiology. There are four primary contributors.
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.
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.
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.
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.
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.
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)) Enter fullscreen mode Exit fullscreen mode 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:
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. Enter fullscreen mode Exit fullscreen mode The model generates:
from datetime import datetime def parse_date ( s: str ) -> datetime: return datetime. fromisoformat ( s ) Enter fullscreen mode Exit fullscreen mode 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.
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 Enter fullscreen mode Exit fullscreen mode 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}" ) Enter fullscreen mode Exit fullscreen mode 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.
A realistic integration would look like this:
User Prompt → LLM Generation → [Syntax Check] → [Unit Test] → [Counterfactual Verifier] → [Accept/Reject] Enter fullscreen mode Exit fullscreen mode 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:
Counterfactual consistency is a powerful idea, but it's not a silver bullet. Here are the key limitations you need to account for.
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.
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:
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.
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.
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.
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.
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.