Anyone whoâs been confidently burned by an AI knows that moment of total disbelief â it cites an API that doesnât exist, makes up a reference that looks completely legit, and says it like itâs the most natural thing in the world.
If you think this is just the model ânot being smart enough,â youâre underestimating the problem. LLM hallucination isnât some intelligence gap or engineering bug â itâs a systemic risk the architecture carries by design. You canât fix it by tuning model parameters; you need system-level guardrails to set the bottom line. Here, weâll break down how hallucinations actually happen, then look at how guardrails can minimize the damage â and finally, Iâll use two real-world war stories to show why AOSP actually isnât fazed by this side effect and why itâs a safer environment for AI agents.
1. The Architecture: It Optimizes for Probability, Not Truth
At its core, an LLM does next-token prediction â it predicts the next word. What it learns from massive text corpora is the statistical patterns of human language, not a lookup table of facts.
This creates a fundamental problem: high-frequency patterns like spelling and grammar improve reliably as models scale, but low-frequency, arbitrary facts â like someoneâs birthday â canât be derived from language patterns alone. OpenAIâs 2025 paper Why Language Models Hallucinate is blunt about this: when the model hits a knowledge gap, it sacrifices accuracy to keep the sentence fluent, picking the most âcontextually plausibleâ token to fill the slot. Its knowledge isnât stored like a SQL database â itâs distributed across billions of neural weights. When you ask a question, it doesnât look anything up. It reconstructs a probabilistic shadow of a plausible answer through fuzzy association.
The Evaluation Pipeline Rewards Guessing
Thereâs a more critical reason the model wonât say âI donât knowâ: the training and evaluation pipeline itself punishes honesty.
Think of a multiple-choice exam that only counts right vs. wrong â guessing right earns points, leaving blanks earns zero. The rational strategy is obvious: guess even when you donât know. LLMs are trained exactly this way. When scoring only measures correctness, the model learns to fabricate rather than admit uncertainty. OpenAIâs SimpleQA benchmark illustrates this well: an older model that almost never abstained (o4-mini) had a 75% error rate; a model willing to say âI donât knowâ on roughly half the questions dropped to 26%. The difference isnât intelligence â itâs whether the model is allowed to acknowledge its own ignorance (source: OpenAI SimpleQA benchmark; see also Nature 2026).
Training Side Effects: Long-Tail Loss and the People-Pleaser Personality
To compress massive datasets into finite parameters, models automatically trade off: they memorize high-frequency general patterns and drop low-frequency long-tail details. When you push for an obscure specific fact, the model simply doesnât have that memory â it fills in a fake answer from pattern extrapolation.
Another side effect comes from alignment training (RLHF). Anthropicâs research Towards Understanding Sycophancy in Language Models found that reward models and human annotators both tend to score âcompliant, well-formatted, plausible-soundingâ answers higher â while an honest âI donât knowâ actually gets penalized. This effectively gives hallucination a green light, breeding a people-pleaser personality: the model learns to satisfy you rather than be honest with you.
2. Error Amplification: One Wrong Step, Then Doubling Down
An LLMâs decoding is an autoregressive chain that canât stop and restart: each step takes its own previous output as input. This creates exposure bias â if the first step drifts even slightly, errors compound like dominoes. Thatâs why hallucinations tend to cluster in the second half of long outputs â youâve probably heard this called the snowball effect, where errors just keep piling up.
Zhang and Pressâs ICML 2024 paper How Language Model Hallucinations Can Snowball revealed a counterintuitive phenomenon: models will actively generate more wrong supporting arguments to stay âconsistentâ with their initial incorrect answer. But hereâs the thing â when those errors are isolated and asked about separately, ChatGPT recognizes 67% of its own mistakes, and GPT-4 catches 87%. The model isnât lacking knowledge. Itâs held hostage by its own prior context, trapped in a hole it dug itself.
Attention Drift: More Context Isnât Always Better
Thereâs another amplifying factor. Stanfordâs Lost in the Middle found that when critical information is buried in the middle of a long context window, model accuracy drops by over 20 percentage points compared to placing it at the beginning or end. In scenarios with 20-30 documents stuffed into context, performance was actually worse than providing no documents at all.
More context isnât always better. Stuff in too much, and the model actually loses the signal.
3. Engineering Countermeasures
After all of the above, the conclusion should be clear: hallucination canât be solved by trusting the model to self-regulate. It takes deliberately designed system architecture to prevent or correct the problem. The industry has converged on three approaches, all sharing the same principle â donât let the model brute-force it on weights alone.
| Approach | Mechanism | Effect |
|---|---|---|
| RAG (Retrieval-Augmented Generation) | Retrieve hard facts from an external knowledge base before the model answers | Most cost-effective and widely adopted |
| Chain of Thought | Force the model to write out intermediate reasoning steps, inserting checkpoints into the autoregressive chain | Truncates exponential error amplification |
| Uncertainty Detection | Quantify model confidence; refuse or escalate when below threshold | Intercepts low-confidence outputs at the source |
Semantic Entropy: Why Logits Arenât Enough
The third approach deserves a closer look because thereâs a common misconception. Many assume you can use a single tokenâs output probability (logit) as a confidence score and block anything below a threshold. But single-token logit calibration is poor â models are frequently âvery confident and very wrong.â Logits alone canât catch hallucinations.
The more robust approach in current research is Semantic Entropy: sample the same question multiple times and cluster the answers by meaning. If the model says something different each time (semantic divergence), itâs guessing, and the system should raise a red flag. This method was published in Nature and significantly outperforms baselines at detecting hallucination, at the cost of roughly 10x compute.
However, probabilistic detection has an inherent ceiling. What I want to talk about next is a harder-edged approach â deterministic verification.
4. An Engineerâs Perspective: AOSP Is a Built-In Hallucination Safety Net
As someone who has worked on AOSP / Android framework for years, the more I study these mechanisms, the more familiar they feel: the three countermeasures above already have direct counterparts in AOSPâs workflow.
| General Countermeasure | AOSP Counterpart | Difference |
|---|---|---|
| RAG (ground in external knowledge) | Ground in the real AOSP source tree + official docs | The knowledge base is deterministic source code, not approximate vector search results |
| Chain of Thought (insert checkpoints) | Gerrit code review: design first, code second, human +2 to merge | Human reviewers understand semantics, not just tokens |
| Uncertainty detection (confidence threshold) | Compilation / CI / CTS / VTS | Deterministic verification â not âwe estimate you might be wrong,â but âwe have proof youâre wrongâ |
The first line of defense is the RAG counterpart: make the AI agent work against the real source tree â look up APIs by reading the actual code, not guessing from training data. But grounding alone isnât enough. The two cases below show how the other two defenses catch the two types of hallucination AI agents are most prone to.
Case 1: Copying a Pattern, Forgetting the Scope â Caught by Code Review
In a HAL-layer authentication polling service, the outer loop used std::unique_lock + wait_for for periodic status checks. The inner loop needed the same sleep functionality, so someone copied the outer loopâs pattern verbatim:
while (!exit) {
std::unique_lock<std::mutex> autolock(mMutex); // LOCKED
mCv.wait_for(autolock, 200ms);
// when wait_for returns, mutex is re-acquired
if (condition) {
for (int i = 0; i < N; i++) {
std::unique_lock<std::mutex> slock(mMutex); // DEADLOCK
// autolock still holds mMutex
// slock tries to lock the same non-recursive mutex
// â waits for itself to unlock â waits forever
mCv.wait_for(slock, 200ms);
}
}
}
std::mutex is non-recursive. The outer autolock is still holding the mutex when the inner slock tries to lock the same one â deterministic deadlock. The program silently hangs with zero error output.
This bug was caught in the first round of Gerrit code review.
Tell an AI agent to âadd a periodic check to the inner loop,â and the first thing it does is find the closest pattern in context and copy it â thatâs literally how next-token prediction works. The code looks âsymmetricâ and reads âreasonably,â but the semantics are wrong. Gerrit review, acting as a human checkpoint, cut the snowball off before the code ever ran â the AOSP version of a Chain of Thought defense.
Case 2: Updated One Side, Forgot the Other â Caught by Boot-Time Validation
During an update to a system-level privileged app, an engineer modified the privapp-permissions allowlist (removed a permission) but forgot that the prebuilt APKâs manifest still declared it:
privapp-permissions.xml: removed WRITE_SECURE_SETTINGS â updated
prebuilt APK manifest: still has WRITE_SECURE_SETTINGS â not synced
â mismatch â IllegalStateException â boot loop
Androidâs PermissionManagerService performs a strict comparison of these two lists at systemReady(). A mismatch triggers an IllegalStateException â the system wonât boot. Not a warning, not a degradation â a hard block.
When an AI agent modifies permissions, its context window might only contain the allowlist XML â not the prebuilt APK manifest sitting in a different directory. This is what a knowledge gap looks like in practice: the model doesnât have the complete state. But PermissionManagerService doesnât care what you know or donât know â inconsistent means no boot. Semantic entropy can only estimate the model âmight be guessing.â Deterministic verification tells you straight: youâre wrong. Harder than any logit threshold.
Three Defenses, All Essential
| Defense | Corresponding case | What type of hallucination it catches |
|---|---|---|
| RAG â source tree grounding | Prerequisite | Agent reads real code instead of guessing APIs from memory |
| Code review â human checkpoint | Case 1 | Pattern-copy hallucination (syntactically correct, semantically wrong) |
| Compilation / CTS / boot-time â deterministic verification | Case 2 | Knowledge-gap hallucination (incomplete state) |
With these three layers, AI agents can safely handle the work that genuinely should be automated â boilerplate, HAL templates, test generation, log analysis, large-scale refactoring migrations. Even when the agent gets it wrong, the system catches it.
My principle in one line: donât let AI guess â make it tell the truth in front of the compiler and the test suite.
A Word of Honesty
I need to add a boundary so this post doesnât read too optimistic.
Most of the research cited above comes from OpenAI, Anthropic, and top conferences â sources that carry an inherent narrative bias toward âhallucination is manageable and engineering can solve it.â Engineering measures can dramatically reduce hallucination, but they canât eliminate it entirely.
So the real moat isnât âtrusting that AI wonât make mistakes.â Itâs designing a system that catches mistakes when they happen. Every commit we make in AOSP follows the same logic â nobody assumes their code is bug-free, but with the compiler, CI, CTS, and code review all in place, you can enjoy the benefits AI agents bring with a lot more confidence.
References
- OpenAI, Why Language Models Hallucinate (2025); Nature version (2026)
- Zhang & Press, How Language Model Hallucinations Can Snowball, ICML 2024
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts, 2023
- Anthropic, Towards Understanding Sycophancy in Language Models, 2023
- Farquhar et al., Detecting hallucinations in large language models using semantic entropy, Nature, 2024