AI coding hallucinations happen when an assistant invents facts or code that appears valid but is not grounded in verified sources. In software teams, these...
AI Coding Hallucinations: How to Stop Fake Packages and Unsafe Code
AI coding hallucinations happen when an assistant invents facts or code that appears valid but is not grounded in verified sources. In software teams, these errors can create fake dependencies, insecure authentication, weak cryptography, or risky cloud permissions. The answer is straightforward: treat generated output as untrusted until tools and people verify it.
Key Takeaways- AI suggestions can invent libraries, functions, and security guidance.
- A fabricated package name can become a supply-chain attack if someone registers it first.
- Code that compiles may still be unsafe, outdated, or simply wrong.
- Use registry checks, dependency review, security tests, and human approval together.
- Track how often your tools produce unsupported claims; do not rely on memory alone.
The speed is useful. The confidence can be misleading. I have reviewed generated code that looked tidy enough to approve at a glance, only to find that a key detail had no reliable source behind it. That is the central risk: fluent output can make weak evidence look like solid engineering.
This is not a call to ban coding assistants. It is a call to put them in the right place. Let them draft, explain, and suggest; keep authority over dependencies, security decisions, and production changes with people and verified systems. The goal is not to slow every developer down. It is to make the dangerous mistakes hard to ship.
What Are AI Coding Hallucinations?
An AI coding hallucination is an answer that sounds plausible but contains invented or inaccurate information. A language model produces text by estimating which tokens are likely to follow the ones already present. It does not automatically check whether a package exists, whether a function has the stated arguments, or whether a security recommendation is still current. Some assistants can consult tools or documentation, but that ability must be built into the workflow; it is not guaranteed by a confident tone.
In ordinary writing, a false detail may be obvious after a fact check. Code is trickier. A made-up package can follow the naming style of a real ecosystem. An invented method can fit neatly beside genuine calls. The code may even compile if the wrong behavior is hidden behind a valid function or if the fabricated dependency is registered later. Syntax is a weak test of truth.
I once reviewed a generated example that used a convincing-looking SDK method. The surrounding code was clean, and the compiler did not complain because the method name happened to exist in a local wrapper. The real problem was that the method skipped a permission check the service required. A neat diff can hide a bad assumption. That is why review needs to ask what the code does, not merely whether it runs.
Hallucinations can appear in several forms: nonexistent package names, incorrect import paths, invented configuration settings, false claims about API behavior, outdated cryptographic choices, and security explanations that omit an important threat. They can also mix true and false details. That blend is especially hard to spot because one correct statement can lend undeserved weight to the next.
A useful rule is to separate plausibility from verification. A model’s answer is a lead, not proof. Check official documentation, source code, package registries, and your own tests before trusting claims that affect a build or a user’s account. For security-sensitive work, ask for the source of each important claim and confirm it yourself. The model can help with the search; it should not be the final authority.
Why AI Coding Hallucinations Matter
Fast suggestions can save time. Unchecked suggestions can spend that time many times over. The important benefit of guardrails is that they let a team keep useful assistance while reducing the chance that a plausible error reaches users, a production service, or the software supply chain.
- They protect the dependency chain. A package is not just a line in a manifest. It may bring maintainers, transitive packages, install scripts, and new code into a build. A fabricated name that later gets registered can point developers toward an attacker-controlled project. Researchers who tested 16 code-generating models reported that roughly one in five package recommendations in their test setting referred to packages that did not exist. Their study also recorded more than 205,000 unique fabricated package names across the test set. Those figures describe that research, not a universal rate for every assistant or coding task. See the study, We Have a Package for You!.
- They reduce security drift. A model may repeat an old pattern because it appeared often in training examples. That matters in authentication, encryption, and cloud permissions, where a once-common practice may no longer meet current needs. The issue is not that every generated answer is unsafe. It is that teams need a way to distinguish a current recommendation from a familiar one.
- They make review more focused. Automated checks can catch registry and policy problems before a human reviewer spends time reading every line. Reviewers can then focus on intent, data flow, permission boundaries, and failure cases. That is a better use of scarce attention than asking someone to manually verify every package spelling.
- They help teams measure risk. If a team records rejected package suggestions, false API claims, and security defects found during review, it can see whether a tool or workflow is improving. Vague concern turns into evidence. That makes it easier to adjust prompts, approved tools, and testing rules instead of arguing from anecdotes.
- They support responsible engineering. Software decisions affect people who did not choose the tools used to build it. Careful review is a form of stewardship: protect user accounts, data, and service availability instead of treating speed as the only measure of success. Frankly, that is just part of doing the work well.
There is a real productivity upside when teams use assistants thoughtfully. Developers can get a first draft, test ideas, and learn unfamiliar APIs faster. But an assistant that removes typing while adding unreviewed risk has not saved the team much. Measure the whole task, including debugging, review, and recovery from mistakes.
How to Build Guardrails Into the Development Pipeline
Start with one rule: generated code is a proposal. Then make the pipeline check the risky parts automatically, because a human cannot inspect every suggestion at machine speed.
- Set a trusted dependency policy. Maintain an approved package list or a clear process for adding packages. Record the package name, registry, owner or publisher, version, license, and reason for use. For a new dependency, inspect its source and maintenance history rather than trusting the name alone. An allowlist should not become a permanent rubber stamp; review important packages again when ownership or behavior changes.
- Check package names before installation. Configure development tools and CI to confirm that each requested package exists in the expected registry. Compare the name against the official documentation or registry page, and watch for close lookalikes. A registry lookup confirms existence, not safety, so do not stop there. A real package can still be compromised or poorly maintained.
- Review changes to dependency files. Require review for edits to manifests and lockfiles. Use automated dependency review to flag new packages, version changes, licenses, and known vulnerabilities. GitHub documents its dependency review feature, which can help teams inspect changes in pull requests. Check that the lockfile records the exact versions your build will install.
- Run builds in a restricted environment. A package may run code during installation or build, depending on the ecosystem and configuration. Do not give a routine build job broad production credentials. Use short-lived credentials, limited permissions, isolated runners, and network controls where practical. If something suspicious executes, reduce the damage it can do.
- Verify APIs and security advice against primary sources. For a library call, check the official API reference and the version your project uses. For authentication, cryptography, and cloud permissions, compare the suggestion with current standards and your organization’s rules. The CISA guidance on phishing-resistant MFA is a better starting point for MFA choices than an unverified code snippet. Passkeys can offer phishing resistance, but recovery, device security, and account policy still need careful design.
- Test behavior, not just syntax. Add unit tests, integration tests, static analysis, secret scanning, and security checks that match the risk. For authentication code, test failure paths, session handling, rate limits, and recovery. For cloud policy, compare requested permissions with actual service needs. A successful compile proves only that the compiler accepted the program.
- Keep a human approval step for critical paths. Require an experienced reviewer for changes to identity, payment, encryption, authorization, deployment, or sensitive data. Ask the reviewer to verify the assumptions and sources, not simply to approve a polished diff. The NIST Secure Software Development Framework offers a useful set of practices for building security into software work.
- Measure and improve. Track how often suggestions name nonexistent packages, fail source checks, or introduce defects. Save examples in a safe test set and run them when models, prompts, or editor tools change. Published package-hallucination research can help teams design a benchmark, but the useful measure is the one that reflects your languages, tools, and codebase.
I have seen teams add a rule and assume the risk is gone. It is not. A registry check may stop an invented package, while doing nothing about an insecure authentication flow. Use layers: each check should catch a different failure, and no single gate should pretend to prove that code is safe.
Comparison: AI Package Hallucination and Typosquatting
These threats overlap, but they start in different places. In typosquatting, an attacker registers a name close to a popular package, hoping a developer makes a typing error. With slopsquatting, the attacker registers a name that a model tends to invent, then waits for a developer to accept the suggestion. The latter skips the typo: the model supplies the wrong name with a straight face.
| Factor | AI package hallucination and slopsquatting | Traditional typosquatting |
|---|
| How the risky name appears | A model recommends a package that may not exist yet | A developer mistypes or misremembers a real package name |
| Attacker’s preparation | Identify recurring fabricated names and register them | Register a lookalike name near a popular package |
| What makes it convincing | The suggestion fits the prompt and may be repeated by the model | The package name resembles the intended dependency |
| Main defense | Verify package names against trusted registries and approved lists | Check spelling, publisher, repository, and package history |
| When the risk starts | When the suggestion is accepted and installed | When the wrong lookalike package is selected and installed |
The researchers’ findings matter because fabricated names may recur. Their study described patterns across sessions, which means an attacker could focus on names likely to be suggested again rather than guessing randomly. That does not mean every invented name will be registered or every recommendation will attract an attacker. It does mean package suggestions deserve the same care as any other external dependency.
Here is the kicker: checking that a package exists is necessary, but not enough. A threat actor can publish a real package with a malicious payload, and a legitimate project can still have a vulnerability. Review the publisher, source repository, release history, download patterns, and permissions. Use lockfiles and scanning tools to limit surprise changes. A name is only the first clue.
The term slopsquatting is useful because it names a specific path from model output to supply-chain risk. But do not let the label distract from the control. Verify what you install, restrict what build jobs can do, and make package changes visible in review. Those habits also help against ordinary typosquatting, compromised maintainers, and careless dependency updates.
Common Mistakes to Avoid
Mistake 1: Treating a confident answer as a checked answer. A model can explain a false claim in fluent detail. I have seen reviewers mistake a tidy explanation for evidence, especially when the code looks familiar. Ask for documentation, then open it. If the answer cannot be confirmed, mark it as uncertain and do not ship it on confidence alone.
Mistake 2: Assuming compilation means correctness. The compiler checks many useful rules, but it does not know whether a package should be trusted or an authorization check is missing. Tests can also miss cases they never cover. Keep static checks, tests, and human reasoning in the same process. Each catches a different class of mistake.
Mistake 3: Blocking only nonexistent packages. That control catches one failure, not all failures. A real dependency may be compromised, over-privileged, abandoned, or unsuitable for your project. Scan for known issues, inspect ownership, pin versions, and review changes. The goal is not to prove every package harmless; it is to make risk visible and bounded.
Mistake 4: Copying generated authentication code without checking current guidance. SMS codes are still used in many systems, but they are not phishing-resistant and should not be treated as the strongest choice for every account. For high-impact accounts, evaluate phishing-resistant MFA such as passkeys or security keys, and design recovery with equal care. Passkeys are not magic: a compromised device or weak recovery process can still expose an account.
Mistake 5: Giving CI broad credentials because it is convenient. A build that runs untrusted code should not also hold unrestricted access to production. Use scoped permissions and separate jobs for testing and deployment. Frankly, a build should not be able to do everything just because nobody has taken time to limit it.
Mistake 6: Expecting reviewers to catch every issue by memory. Reviewers miss things, especially when a change is large or the deadline is close. Put repetitive checks in automation and reserve human attention for decisions that require context. That is not distrust of engineers; it is sensible protection against fatigue.
Mistake 7: Never checking whether the controls work. A policy written in a wiki will not stop an install command. Test your pipeline with harmless examples: an unknown package, an unexpected permission, or an unapproved dependency update. Record what happens, fix gaps, and repeat after tooling changes. Security controls need tests too.
OWASP tracks misinformation as a risk in its guidance for large language model applications. Its advice supports a practical point: compare model output with verified sources and retain human oversight for important decisions. See the OWASP Top 10 for LLM Applications. Do not treat a framework as a substitute for judgment; use it to make the right checks harder to forget.
Frequently Asked Questions
What is an AI coding hallucination?
It is a generated claim or code suggestion that looks credible but is false, unsupported, or out of date. Examples include a nonexistent package, an invented API method, or a security setting that does not work as described. The model may not signal uncertainty, so verify important claims in official documentation, registries, source code, or tests before using them.
What is slopsquatting?
Slopsquatting is a supply-chain attack in which someone registers a package name that AI models are likely to hallucinate. A developer may then install the attacker’s package after accepting the model’s suggestion. It resembles typosquatting, but the name can come from generated output rather than a typing mistake. Package review and registry checks help reduce the risk.
Can AI-generated code be used safely?
Yes, when the team treats it like any other untrusted contribution. Review the logic, verify dependencies and APIs, run tests and security checks, and restrict the permissions available to builds. Raise the level of review for authentication, encryption, authorization, cloud access, and sensitive data. The question is not whether a person or model wrote the code; it is whether the result has been checked.
Are passkeys always better than SMS codes?
Passkeys can provide phishing-resistant sign-in and are often a strong option, especially for important accounts. But no method should be chosen without considering account recovery, device loss, accessibility, and the risks of the service. Follow current security guidance and test the full sign-in and recovery flow. Do not accept a generated authentication pattern just because it is familiar or easy to paste.
Final Thought
AI assistants can make the first draft faster. They cannot take responsibility for what a team installs, deploys, or asks users to trust. That responsibility belongs to the people who set the rules, review the changes, and decide what reaches production. I have found that the strongest workflows do not ask engineers to be suspicious of every line forever; they make verification routine, visible, and proportionate to the risk.
Start small if your pipeline has no guardrails. Check package names, review lockfile changes, limit build permissions, and require a careful look at security-sensitive code. Then measure what those checks catch and strengthen the gaps. A few boring controls can prevent a very exciting incident, which is exactly the kind of excitement software teams should avoid.
Speed matters. So does the dignity and safety of the people using the software. Keep the assistant in the role of a helpful draft writer, and keep verified evidence in charge. That is how a team gets useful help without handing its judgment to autocomplete.