AI Coding Hallucinations: How to Stop Fake Packages and Unsafe Code
Fast code can still be false. An AI coding hallucination is an unsupported or fabricated suggestion that sounds convincing, such as a nonexistent software package, an invented function, or security advice that leaves an application exposed. Check the claim.
The danger is not that every suggestion is wrong. It is that correct and incorrect answers can arrive in the same polished voice, so a plausible explanation may get less scrutiny than a rough draft. I’m Ermenildo Castro, and I’ve learned that fast code review works only when it checks the underlying claim, not just the neatness of the code.
I have seen a tidy snippet pass an initial review because it compiled and matched the style of the code around it. A closer check revealed that the key library call did not do what its comment claimed. That kind of miss is easy to make when a team is moving quickly, and it is why verification belongs in the build process, not just in someone’s memory. The goal is not to ban coding assistants. It is to keep their speed without handing them unearned trust.
What Are AI Coding Hallucinations?
An AI coding hallucination occurs when a model generates a claim or code element that appears credible but is false, unsupported, or unsuitable for the task. In software work, that might be a made-up package, an API call that never existed, a misleading explanation of a real function, or a security setting that grants far more access than the application needs.
Language models generate text by predicting likely next pieces of text from patterns in training data and the current prompt. They do not automatically check each answer against a live package registry, the current version of a framework, or your organization’s security rules. When a prompt asks about an unfamiliar library or leaves out important details, the model can fill the gap with something that resembles the surrounding code. It may sound certain. Confidence is not proof.
Code makes these mistakes harder to spot than a visibly garbled paragraph. A fabricated package name may follow familiar naming conventions. An invented method may fit the style of a real SDK. The code can even compile if the bad behavior sits in an overlooked branch or an unsafe default. A successful build only shows that the compiler accepted the syntax and types; it does not show that the code is secure or that the model’s explanation is true.
I once reviewed a generated integration that looked ordinary at first glance. The import name matched the style of the project, and the surrounding code was clean. But the dependency was not in our approved registry list, and a quick check showed that the suggested package name had no known maintainer or release history. That pause mattered. A suggestion does not become trustworthy just because it looks like the rest of the codebase.
Researchers have measured this problem in dependency suggestions. A study of 16 code-generating models reported that roughly one in five recommended package names in its test set referred to nonexistent packages, producing more than 205,000 unique fabricated names across the experiments. Those results describe the study’s test conditions, not a universal rate for every tool or prompt. Still, the finding shows why teams should verify package claims instead of assuming a familiar-sounding name is real. See the research paper on package hallucinations.
Why These Hallucinations Matter
Some AI mistakes are harmless. Others reach production. A fabricated dependency, a weak login flow, or an overly broad cloud permission can turn an autocomplete suggestion into a security problem.
- Supply-chain exposure: If a developer installs a package that does not exist, an attacker may register that name in a public registry and publish malicious code. Researchers call this slopsquatting: an attacker claims an AI-invented package name, rather than relying on a developer to mistype a legitimate one. If the build installs it, package scripts or imported code may run with the permissions available to that environment.
- Weak authentication: A model may suggest a familiar but unsuitable approach, such as SMS codes as the only protection for a high-risk account. SMS can still serve some use cases, but it is vulnerable to attacks such as SIM swapping and interception. For important accounts, phishing-resistant methods such as passkeys or hardware security keys are usually stronger choices. CISA explains the value of phishing-resistant multifactor authentication.
- Cryptographic mistakes: Generated code might use outdated algorithms, unsafe modes, or poor key handling. Cryptography is easy to write incorrectly, even when the code appears to work in a basic test.
- Excessive permissions: An AI-generated cloud policy may grant broad access because that makes the sample function without clarifying what the service truly needs. That shortcut can turn a minor bug into a larger breach.
- False confidence: An explanation that sounds authoritative can discourage a reviewer from checking a detail they would normally verify. Polished prose is not a security control.
I’ve watched teams focus on whether generated code passed tests, then skip the harder question: what does it do when the unusual case happens? Tests help, but a happy-path test cannot prove a dependency is trustworthy or that an access policy is appropriately narrow. The basic discipline is simple: verify the source, check the behavior, and limit the damage if a mistake slips through.
This is also a matter of stewardship. Software teams handle other people’s data, time, and trust; careful review respects the people who depend on the service, not only the team trying to ship it. The OWASP guidance for large language model applications includes risks tied to misleading model output and excessive trust. That guidance supports a plain rule: important decisions need evidence from sources you can inspect.
A Step-by-Step Guide to Safer AI-Assisted Coding
You do not need to slow every edit to a crawl. Put checks around the kinds of suggestions that can harm users or systems, then automate the boring verification.
- Mark sensitive areas before using an assistant. Identify code that touches authentication, authorization, payments, cryptography, personal data, cloud permissions, deployment, and dependency management. I have found that teams get better reviews when they label these areas clearly in the repository. A reviewer can then tell when generated code needs extra attention instead of treating every diff the same way.
- Check each dependency against a trusted registry. Confirm the exact package name, registry, version, maintainer information, and release history before installing it. Do not rely on the model’s description of what a package does. Check the official project documentation and compare it with the code you intend to use. If the package is new or unfamiliar, ask why it is needed and whether a known alternative already exists.
- Use an allowlist where the risk justifies it. For production builds, restrict dependencies to approved registries, known packages, or a managed internal catalog. An allowlist is not a magic shield; it needs an owner and a process for approving updates. But it stops an arbitrary suggestion from becoming a trusted dependency by default.
- Pin and review dependency versions. Use a lockfile and review changes to it like changes to application code. Pinning makes builds more repeatable, while review helps reveal a new or unexpected package. Where supported, check package integrity and provenance information. A lockfile cannot tell you that every package is safe, but it gives the team a clear record of what the build will fetch.
- Run builds with limited permissions. Keep installation and build jobs away from production credentials unless they truly need them. Use short-lived credentials, restrict network access where practical, and separate build environments from deployment environments. I have seen a harmless-looking test job inherit secrets it never needed. Least privilege reduces the damage if a dependency or generated script behaves badly.
- Review security-sensitive behavior, not only syntax. Ask what the code permits, what it rejects, and how it handles failure. For authentication, check identity verification, session handling, recovery, rate limits, and phishing resistance. For cloud policies, compare every permission with the service’s actual needs. For cryptography, use reviewed libraries and approved patterns rather than accepting fresh custom code from a model.
- Add automated checks to the pipeline. Run dependency scanning, static analysis, secret detection, tests, and policy checks on pull requests. Tools such as software composition analysis can flag known vulnerable packages; static analysis can catch some unsafe code paths. Neither tool can establish that every answer from a model is correct, so keep their scope honest. The NIST Secure Software Development Framework is a useful reference for making security checks part of regular software work.
- Ground suggestions in approved documentation. Retrieval-augmented generation, or RAG, can give a model access to documentation your team selects, including current API references and internal engineering rules. That can reduce errors caused by stale or missing context. It does not guarantee a correct answer: the model can still misread the retrieved material or make a bad inference. Ask it to cite the relevant document, then verify the claim yourself.
- Track what your own tools get wrong. Build a small set of prompts that represent your real coding tasks, then record invented imports, incorrect API claims, and unsafe security recommendations. Recheck the set when you change models, prompts, or retrieval sources. Published benchmarks can help you shape the test, but your own repository and workflows are what your guardrails must protect. Measurement turns a vague worry into a defect rate you can discuss and improve.
The important part is that checks happen before code reaches a trusted environment. Human review still matters, especially for critical paths, but it cannot carry the whole load when suggestions arrive faster than people can inspect them. Automate package verification and basic policy checks, then spend human attention on behavior, context, and risk.
AI Package Hallucinations vs. Traditional Typosquatting
The two attacks share a result: a developer installs a package controlled by an attacker. The way the attacker gets the name into the workflow is different.
| Risk | AI package hallucination (slopsquatting) | Traditional typosquatting |
| How the package name appears | A model invents a plausible name that may not exist yet. | A developer mistypes a real package name or chooses a lookalike. |
| Attacker’s opportunity | Register names that models repeatedly suggest, then wait for someone to install them. | Register common misspellings or confusingly similar names. |
| Typical trigger | Accepting a generated import or install command without checking the registry. | Typing quickly, copying an incorrect command, or overlooking a similar name. |
| What helps prevent it | Registry verification, approved-package lists, lockfile review, and restricted build permissions. | Careful name checks, trusted registries, package controls, and lockfile review. |
| What the two have in common | Both exploit trust in a dependency name and can expose a build to malicious code. | Both exploit trust in a dependency name and can expose a build to malicious code. |
Slopsquatting is not simply a new label for a typo. A developer can enter the exact name suggested by a model and still install an attacker’s package if someone registered that fabricated name first. The research on package hallucinations reported repeated names across model outputs, which can make monitoring worthwhile: a name that recurs is easier for an attacker to target than one that appears only once.
Typosquatting remains a real risk, and the same controls address parts of both problems. The difference is where teams need to look. Traditional dependency defenses often focus on misspellings and vulnerable versions. AI-assisted coding adds another check: is this package name a real, maintained project that our team intends to trust? Treat every new dependency as a decision, not a line of autocomplete.
Common Mistakes to Avoid
A few popular shortcuts create a false sense of safety. Frankly, the hardest part is not finding a tool; it is making sure people use the tool’s result as evidence rather than as permission to stop thinking.
- Assuming that code which compiles is safe. A compiler checks syntax and type rules, not whether an authentication flow resists phishing or whether a package is malicious. I once saw an integration pass its basic tests because those tests only checked that a response arrived. They did not inspect which permissions the code requested. Test the security property, not just the expected output.
- Trusting the assistant because it explains itself. A clear explanation can still be wrong, especially when a model gives a plausible reason for a function or package it has invented. Verify the claim against primary documentation, source code, or a trusted registry. Treat unsupported statements as questions to investigate.
- Using a security prompt as the only safeguard. Telling a model to write secure code may improve the answer, but it does not create a guarantee. The model can miss context, use outdated conventions, or misunderstand a requirement. Prompts guide output; they do not replace tests, reviews, or policy checks.
- Relying on a single scanner. Dependency scanners, static analysis, and tests each catch different problems. A scanner may find a known vulnerable version but miss a newly published malicious package. Static analysis may flag a risky pattern but not know that a cloud permission is unnecessary. Combine controls and understand what each one cannot see.
- Giving build jobs broad access. A trusted repository can still receive a bad dependency suggestion. If a build has long-lived credentials, broad network access, and permission to deploy, a compromised package can do more harm. Keep permissions narrow, and separate build, test, and release duties.
- Making human review a checkbox. A reviewer who does not know the library or security area may approve a neat diff without noticing the risk. For sensitive code, assign a qualified reviewer and provide the relevant requirements. Time pressure is not a substitute for expertise.
- Assuming RAG solves hallucination. Retrieval can provide useful, current material, but a model may still draw the wrong conclusion or cite a source that does not support its answer. Check both the cited document and the claim. Grounding is a useful guardrail, not a certification stamp.
- Checking only once. Model behavior, package registries, dependencies, and documentation change. Re-run checks when the model changes, the prompt changes, or the code takes on a new role. Security is a routine responsibility, not a one-time approval.
The NIST Generative AI Profile discusses risks such as confabulated output and the need to manage them across the system’s life cycle. That is a more useful frame than asking whether AI is safe in the abstract. Ask what the tool can affect, what evidence supports its output, and what happens if it is wrong.
Frequently Asked Questions
What is an AI coding hallucination?
It is a code suggestion or factual claim produced by an AI model that seems credible but is fabricated, incorrect, or unsupported. Examples include a nonexistent package, an invented API method, or a security recommendation that is unsuitable for the service. These mistakes can be hard to notice because the code may look consistent with real examples. Verify dependencies and important behavior against trusted sources before use.
What is slopsquatting?
Slopsquatting is a software supply-chain attack in which someone registers a package name that an AI model has hallucinated. A developer may then install that package after accepting the model’s suggestion. If the package contains malicious code, it may run during installation, testing, or application use, depending on the package and environment. Check the registry and package history before adding an unfamiliar dependency.
Can retrieval-augmented generation prevent hallucinations?
No. Retrieval-augmented generation can supply approved documentation and give a model better context than its stored training patterns alone. That may reduce some errors, but the model can still misread the source, combine facts incorrectly, or invent details. Require useful citations for important claims, and check that each cited page actually supports the answer.
How should teams review AI-generated security code?
Use stronger review for authentication, authorization, cryptography, cloud permissions, and code that handles sensitive data. Check the implementation against trusted security guidance, test expected and failure cases, and limit the permissions available to builds. Automated scanning helps catch known issues, while a qualified human reviewer checks context and intent. No single check can cover every failure mode.
AI assistants can save time. They can also produce a convincing mistake in seconds, and the right response is neither blind trust nor blanket rejection. Build verification into the ordinary path: check packages, restrict permissions, test security behavior, and review high-impact changes with care. That protects the people who rely on the software while letting developers use a helpful tool responsibly.
I would rather see a team ship one hour later than explain why an invented dependency received production credentials. The work is not glamorous. It is the steady practice of checking claims, limiting access, and taking responsibility for the systems we build. Keep the useful speed, but make trust something the code earns.