AI coding assistant hallucinations are confident, plausible-looking errors in generated code or technical advice. In a build pipeline, a made-up dependency can...
AI Coding Assistant Hallucinations: How to Stop Fake Packages and Unsafe Code
AI coding assistant hallucinations are confident, plausible-looking errors in generated code or technical advice. In a build pipeline, a made-up dependency can become executable software, while stale authentication or cloud guidance can expose real accounts and data. The useful response is not to ban assistants; it is to verify their output before trust.
I’m Ermenildo Castro. In software teams, I’ve seen how a tidy patch can earn quick approval simply because it compiles and reads well. AI tools make that pressure stronger: they can produce a plausible answer before a reviewer has time to check whether the package exists or the security advice is current. Speed is useful. Unchecked trust is not.
The risk is practical, not theoretical. A bad recommendation can enter a pull request, pass a basic build, and reach an environment with secrets or production access. That does not mean every generated line is dangerous. It means teams need a clear rule: treat generated output as a draft, then use evidence and tests to decide what earns trust.
What Are AI Coding Assistant Hallucinations?
An AI coding assistant hallucination is a generated claim or code suggestion that sounds credible but is not grounded in the facts needed for the task. A model may invent a library, use an API that does not exist, cite a false configuration option, or offer a security pattern that no longer meets current needs. The model is not checking truth in the way a compiler or trusted registry does. It is generating likely text from patterns learned during training and from the context it receives.
That distinction matters. A language model can produce the same confident tone for a correct answer and a fabricated one. It may have learned examples from different software versions, incomplete documents, or code that was never a good model to begin with. A vague prompt can add another problem: when key details are missing, the assistant may fill them in rather than ask what version, platform, or threat model applies.
Code is especially good at disguising mistakes. A made-up package can follow familiar naming rules. A fabricated method can look like the other methods in an SDK. The code may even compile if a developer has a similarly named dependency, a local stub, or a different version than the one the assistant assumed. Passing a build is useful evidence about syntax and behavior under that test. It is not proof that the package is trustworthy or the security design is sound.
I remember reviewing a change where the dependency choice looked ordinary and the patch was neat enough to invite a quick approval. The useful question was not whether the code looked professional; it was whether the package was real, maintained, and the right tool for the job. That pause is easy to skip when everyone is trying to keep a release moving. It is also exactly where a simple registry check can prevent a costly mistake.
Researchers have measured this problem. A study testing 16 code-generating models reported that roughly one in five recommended dependencies in its test conditions pointed to packages that did not exist, with more than 205,000 unique fabricated names across the test set. That is not a universal rate for every model, language, or prompt. It is evidence that fabricated package suggestions are common enough to deserve controls. The research paper on package hallucinations describes the issue and its security implications.
One attack pattern is called slopsquatting. An attacker watches for package names that AI tools tend to invent, registers a matching name on a public registry such as npm or PyPI, and waits for a developer to install it. If installation runs package code, that code may inherit the permissions of the build process. The invented name can recur in model answers, making the risk more durable than a one-off typo.
Core Benefits and Why the Risk Matters
AI coding assistants can save time. They can sketch a test, explain an unfamiliar API, draft repetitive code, or help a developer explore a new library. Those are real benefits when a person checks the result. The point is not to treat every suggestion as suspect forever; the point is to match the amount of checking to the damage a bad answer could cause.
Here is where careful use helps:
- Faster first drafts: An assistant can produce a starting point for routine code, leaving the engineer more time to inspect edge cases and design choices. I have found that this works best when the task is narrow and the expected behavior is already clear.
- Quicker learning: A tool can explain an error message or show a small example. But I check the official documentation before relying on details that affect a production service. A fluent explanation is not the same as a verified one.
- More test ideas: A model can suggest boundary cases a developer has not yet listed. Those suggestions become valuable when they are turned into real tests, rather than accepted as proof that the code is correct.
- Less repetitive work: Drafting boilerplate can reduce typing and help teams keep common patterns consistent. Consistency only helps if the shared pattern is safe and maintained.
- A prompt for review: A generated answer can expose assumptions the team should discuss, such as which identity provider is in use or which cloud role a service actually needs.
The security risk follows the same path as the productivity gain: suggestions arrive quickly and in large numbers. A reviewer who can carefully check five changes may struggle to check fifty, especially when each patch looks plausible. That is why the controls should not depend on attention alone. A registry check can reject an unknown package before installation. A static analysis rule can flag a dangerous function. A reviewer can then focus on judgment, intent, and context.
Authentication is a good example of why the stakes vary. A model might suggest SMS codes because examples of that approach are common in public code. SMS may be better than having no second factor, but it is not phishing-resistant and should not be treated as the strongest option for sensitive accounts. Current guidance favors phishing-resistant methods, including passkeys, where they fit the service and recovery plan. The NIST digital identity guidance explains authenticator requirements, while CISA’s guidance on phishing-resistant MFA gives practical direction.
A security review also protects people who never see the code. Customers cannot check whether a service grants an unnecessary cloud permission or stores credentials safely. Engineers and organizations have a duty to handle that trust with care. In plain terms, safe automation is part of good stewardship: it helps ensure the convenience of one team does not shift avoidable risk onto everyone else.
Step-by-Step Guide to Building Guardrails
You do not need a new committee to make AI coding safer. Start with controls that fit the way code already moves from a developer’s editor into a build. Add stronger checks where the code can touch accounts, data, money, or production systems.
- Set a clear rule for generated code. Tell developers that suggestions are drafts, not approved sources. Require them to verify packages, security-sensitive APIs, and configuration before merging. Make the rule specific: for example, no new dependency enters the project without a registry check, a reason for adding it, and an identified maintainer.
- Check dependencies before installation. Verify the exact package name and registry using trusted registry records or an approved internal mirror. Check ownership, version history, project activity, and whether the package matches the intended use. A name that sounds right is not enough. If it is new or unfamiliar, ask why the project needs it instead of quietly adding it.
- Use lockfiles and review dependency changes. A lockfile records resolved versions and helps make builds repeatable. It does not prove that a dependency is safe, so review the lockfile change as well as the manifest. Use dependency review or software composition analysis to flag new packages, known vulnerabilities, suspicious version changes, and licenses that conflict with project rules.
- Limit what the build can do. Install and test unfamiliar code in an isolated environment. Give build jobs only the credentials they need, keep secrets out of untrusted pull-request jobs, and restrict network access where practical. Package installation can run scripts or build steps, depending on the ecosystem and setup. Assume those steps deserve the same care as other code execution.
- Check security advice against current sources. For authentication, cryptography, and cloud access, compare generated suggestions with official documentation and your organization’s standards. Do not accept a custom password scheme, home-built encryption, or broad cloud role because the assistant explains it smoothly. Ask a reviewer with the right expertise when a change affects a critical path.
- Ground the assistant in approved material. Retrieval-augmented generation can provide answers based on documents your team trusts, such as current API references and internal standards. That can reduce errors caused by stale training data, but it does not guarantee correctness. Documents can be old, retrieved passages can be irrelevant, and a model can still draw the wrong conclusion. Show the source and require a check.
- Measure what your controls catch. Track new dependencies proposed by AI-assisted changes, how many fail registry or policy checks, and how often reviewers find security defects. Test the controls with known fake package names and deliberately unsafe examples. Keep measures simple enough that teams will use them. A rate is useful only when its scope and test conditions are recorded.
- Keep a human responsible for the decision. Automation can check whether a package exists, whether a version is pinned, or whether a policy rule is broken. It cannot decide by itself whether the dependency is appropriate for your product or whether an authentication flow fits your users. Name a code owner for important security choices, and make that person’s review part of the normal workflow.
I have seen teams get better results when checks happen before a pull request reaches a busy reviewer. A small automated stop sign is less costly than expecting every engineer to remember every risk, every time. The NIST Secure Software Development Framework offers a broader set of practices for building security into software work, rather than treating it as a last-minute inspection.
Comparison Table: AI-Assisted Coding vs. Developer-Led Coding
A useful comparison is not a claim that one workflow is always safer. Manual coding also produces mistakes, and AI-generated code can be sound when it is checked. The difference is where errors tend to enter and which checks are needed. The table compares AI-assisted work with a developer-led process that does not rely on generated suggestions.
| Area | AI-assisted coding | Developer-led coding | Practical control |
|---|
| First draft | Arrives quickly and may include plausible but unverified APIs or packages. | Takes longer to write, but the developer may know the chosen tool or source. | Review purpose, package identity, and documentation before merging. |
| Dependency selection | A fabricated name can be suggested with a convincing explanation. | A developer can still choose a wrong, abandoned, or compromised package. | Verify the exact registry entry and review dependency changes in both workflows. |
| Security advice | May reflect old examples or miss the system’s threat model. | Can reflect a person’s outdated knowledge or rushed assumptions. | Check authentication, cryptography, and cloud permissions against current standards. |
| Review pressure | High suggestion volume can make shallow review tempting. | Reviewers see fewer generated fragments, but may still miss defects. | Automate repeatable checks; reserve human review for design and context. |
| Published evidence | One study of 16 models reported roughly one in five suggested dependencies in its test conditions did not exist. | The cited study did not compare this rate with manual dependency selection. | Treat the finding as a warning about tested model output, not a universal rate. |
The most important distinction is not that humans are always right or models are always wrong. It is that the model can produce an answer without confirming the package registry, application version, or deployment context. A developer can also skip those checks. Good engineering makes the important checks repeatable, no matter who wrote the first draft.
For teams adopting assistants, that means measuring their own process instead of relying on marketing claims or one research percentage. Record how dependencies are introduced, which checks run, and where reviewers find problems. Keep the evidence tied to a specific tool, version, prompt type, and codebase. Broad accuracy scores hide the details that matter to a security team.
Common Mistakes to Avoid
Mistake 1: Trusting code because it compiles. A successful build tells you the code met the checks that ran. It does not tell you that a dependency belongs to the right maintainer, that the code handles an attacker’s input, or that permissions are limited. Add tests and review the behavior, but do not confuse a green status badge with a security audit.
Mistake 2: Assuming a lockfile solves package risk. Lockfiles help reproduce a build and keep versions from drifting unexpectedly. They can also faithfully pin a malicious or unsuitable package. Review the source, version, ownership, and reason for each new dependency. If your team uses an approved package list or private registry, enforce it in the pipeline rather than relying on memory.
Mistake 3: Treating all generated security advice as current. An assistant may reproduce patterns found in old tutorials or examples written for another framework version. This is common in authentication, cryptography, and cloud policy, where small details matter. I do not accept a security claim just because it comes with confident reasoning. I look for current official guidance and ask whether it fits the service’s actual risks.
Mistake 4: Believing retrieval makes the answer safe. Retrieval-augmented generation can show the model relevant documents, which is useful. It can still fetch an old page, miss a key limitation, or summarize a rule incorrectly. Keep source documents current, expose citations to reviewers, and verify important claims at the source. A link is evidence to inspect, not a stamp of approval.
Mistake 5: Relying on one human to catch everything. People get tired, face deadlines, and cannot memorize every package or security rule. That is not a character flaw; it is a process weakness when the system depends on perfect attention. Put repeatable checks in CI, assign owners to sensitive areas, and make it easy to pause a change when evidence is missing.
Mistake 6: Giving the assistant more access than it needs. A coding tool does not need production secrets to draft a unit test. A build job does not need administrator rights to compile an ordinary service. Use least privilege, separate secrets from untrusted code, and review what data the assistant can send to an external service. Security includes the tool’s access, not just the text it writes.
The OWASP security community tracks misinformation as a risk in its Top 10 for Large Language Model Applications. That classification supports a useful habit: verify consequential claims against trusted sources, then keep a person accountable for decisions that can harm users. The category is broad; your controls should be specific to the code and data at risk.
Frequently Asked Questions
Can I trust code written by an AI coding assistant?
Treat it as a draft, not as trusted code. Check that dependencies exist in the intended registry, confirm APIs against current documentation, run tests, and review security-sensitive behavior. The required review depends on the risk: a small formatting helper needs less scrutiny than login, payments, data access, or deployment code. A polished answer is not proof.
What is slopsquatting?
Slopsquatting is a supply-chain attack in which someone registers a package name that AI models have been known to invent. A developer may install the package after seeing the suggestion, believing it is a real dependency. The name’s plausibility helps the trick, so verify package identity and ownership before installing unfamiliar suggestions.
Do passkeys prevent AI-generated authentication mistakes?
No. Passkeys are a phishing-resistant authentication option when implemented and supported appropriately, but an assistant can still configure them incorrectly, mishandle recovery, or recommend a poor account design. Check the flow against current identity guidance, test recovery and account changes, and use stronger methods for sensitive accounts where they fit the service.
What should an AI-code security check include?
At minimum, verify package names and versions, review dependency changes, run tests and static analysis, scan for known vulnerable components, and check permissions and secrets handling. For critical paths, have a qualified reviewer inspect the design. Use isolated builds and least-privilege credentials so a bad suggestion cannot inherit more access than necessary.
Final Thought
AI assistants can make ordinary development work faster, and there is no prize for refusing a useful tool just because it can make mistakes. But the same confidence that makes an answer easy to use can make a false detail easy to miss. The fix is not to ask people to be suspicious of every line forever. It is to build a workflow where important claims have to show their work.
A package should point to a real, reviewed source. A security pattern should match current guidance and the service in front of you. A build should run with only the access it needs. Those are ordinary engineering disciplines, applied to a new source of code and advice. I would rather spend a few minutes checking an unfamiliar dependency than explain later why a build system trusted it without asking basic questions.
Software serves people. That makes careful review more than a tidy technical habit: it is part of the responsibility that comes with handling their data, accounts, and trust. Keep the useful speed. Put verification in the pipeline. Let evidence, not confidence, decide what ships.