AI coding hallucinations look real. A model predicts likely code, package names, and explanations from learned patterns, but it can fill a knowledge gap with a convincing answer that does not exist or is unsafe, leaving developers to separate polished output from verified fact. That gap matters.
Key Takeaways- A convincing code suggestion is not proof that a package or API exists.
- Fake dependency names can become a supply-chain risk when someone registers them first.
- Review security-sensitive code against trusted standards, not just the assistant’s explanation.
- Put checks in CI: allowlists, lockfiles, registry validation, and human review.
The speed is real. The confidence is not evidence. I have seen a tidy code change pass a quick review because every line looked familiar, only for a closer check to uncover an API that did not belong to the library at all. A compiler can catch some errors, but it cannot tell you whether the package is trustworthy or the security design is sound.
This is not an argument for banning coding assistants. They can help with routine work and give engineers a useful first draft. The sensible approach is to treat their output like a contribution from a very fast, very confident junior teammate: useful, sometimes sharp, and never exempt from review. A secure build respects the people whose data it holds. That is stewardship, not red tape.
What Are AI Coding Assistant Hallucinations?
An AI coding hallucination is an output that sounds plausible but is false, unsupported, or unsafe. In a coding assistant, that might be a package name that does not exist, a function with an invented signature, a made-up configuration option, or security advice that no longer reflects current guidance. The assistant is not necessarily trying to mislead anyone. It is generating likely text from patterns, not checking every claim against a live source of truth.
That difference matters. A language model learns relationships among words and code patterns. When asked for a solution, it produces a sequence that resembles examples it has seen. If its context does not clearly support an answer, it may still return one that fits the style of the request. The result can read smoothly while being wrong. A polished explanation is a writing feature, not a safety control.
Code makes this harder to notice than a factual mistake in ordinary prose. A nonexistent package can follow the naming rules of a real ecosystem. An invented method can look like the rest of an SDK. Some false suggestions fail at install or compile time, which is annoying but visible. Others compile, run, and quietly do the wrong thing. The dangerous cases are not always the loud ones.
I learned to be suspicious of code that looks almost too neatly tailored to the prompt. In a review, a short helper can appear to solve a problem exactly, while one imported function turns out not to exist in the version the project uses. That does not make every generated line suspect. It does mean the review should verify important facts instead of letting familiar syntax stand in for evidence.
A 2024 research study tested 16 code-generating models and found that roughly one in five package recommendations in its test set referred to packages that did not exist. The researchers counted more than 205,000 unique fabricated package names across their outputs. Those numbers describe that study’s prompts and models, not a universal rate for every assistant or coding task. The findings are still a strong reason to check dependencies. Read the study of package hallucinations in code-generating models for its methods and limits.

Why AI Hallucinations in Coding Assistants Matter
The risk is not simply that a developer wastes ten minutes debugging. An unchecked suggestion can change what code enters a product, what dependencies run during a build, and what permissions a service receives. Frankly, that is why this belongs in security review, not only in a discussion about developer productivity.
- Package supply-chain exposure: If an assistant invents a dependency, a developer may search for it or install it directly. If an attacker has registered that name, the package could run code in a developer’s environment or build pipeline. Package managers do not know that the name began as a model’s guess.
- Authentication mistakes: A generated login flow may lean on weak recovery steps, mishandle sessions, or treat a one-time code as stronger than it is. Authentication choices depend on threat models and current standards. A confident answer does not replace that work.
- Cryptography errors: Models can reproduce older examples, deprecated algorithms, unsafe defaults, or incorrect advice about key storage. Cryptographic code has little patience for plausible-looking mistakes. A function that passes a basic test can still fail under real attack conditions.
- Excessive cloud access: A suggested IAM policy may grant broad permissions because that makes the example run with fewer errors. The convenience is tempting. The extra access can turn a small application bug into a much larger incident.
- Maintenance and review costs: Invented APIs and unsupported configuration options create rework. A team that accepts them without checking may also leave behind fragile code that the next engineer cannot explain.
There is a specific dependency attack pattern worth knowing. Researchers call it slopsquatting: an attacker registers package names that AI tools tend to invent, then waits for someone to install one. Traditional typosquatting relies on a person mistyping a real package name. Slopsquatting relies on a model repeating a plausible name. In the study above, fabricated names recurred across prompts rather than appearing only once, which makes the idea more than a random typo scenario.
Be careful with the claim, though. A study showing repeatable invented names does not prove every fake name has been registered or that a large campaign is underway. It shows a credible path from model output to package installation. Threat modeling should account for that path without turning a research finding into a claim about incidents that have not been reported.
The problem also grows with volume. One engineer can inspect a handful of suggestions closely. A team that accepts hundreds of generated changes each week cannot rely on attention alone. Build controls need to do the repetitive checks, while people focus on meaning, safety, and user impact. That division is practical, and it protects the dignity of the work rather than asking reviewers to pretend they can catch everything by staring harder.
Step-by-Step Guide to Building Guardrails
Controls work best when they are layered. No single prompt, scanner, or reviewer can establish that generated code is safe. Here is a practical sequence I have used to turn a vague worry into checks a team can run.
- Set a clear policy for AI-generated changes. Decide which tasks may use an assistant and which need extra review. For example, autocomplete for a test fixture may need routine review, while changes to authentication, encryption, payments, or cloud permissions should require a named reviewer with relevant knowledge. Keep the rule short enough that engineers can follow it without a meeting.
- Verify every dependency before installation. Before adding a package, confirm that it exists in the intended registry and that the name, publisher, version, and purpose match the project’s needs. Do not trust a package simply because the assistant supplied a convincing description. Check the official registry page and, where appropriate, the project’s own documentation or repository.
- Use dependency allowlists where the risk justifies them. An allowlist restricts which packages a project or build can install. This can be a full policy for a sensitive service or a narrower rule for high-risk environments. Allowlists need maintenance, but they make an unknown package a visible exception instead of a quiet addition.
- Review lockfile changes. Lockfiles record exact dependency versions and, in many ecosystems, integrity information. Require review of changes to them, especially new direct dependencies and unexpected transitive packages. A lockfile does not make a bad package good. It does make changes easier to inspect and builds more repeatable.
- Check imports and package names automatically. Add a CI job that confirms requested packages resolve in approved registries and comply with policy. Combine that with dependency scanners and secret detection. These tools have limits; a package can exist and still be malicious or unsuitable. But they can catch a simple fabricated name before it reaches a production build.
- Use least privilege in build systems. A package install script should not receive more access than it needs. Keep tokens scoped, avoid exposing production credentials to pull-request builds, and isolate untrusted jobs. If an attacker-controlled package does run, a restricted environment limits the damage.
- Review security logic against trusted references. For authentication, cryptography, authorization, and cloud access, compare the code with current, authoritative guidance. NIST’s digital identity guidelines describe authentication requirements, while the FIDO Alliance explains how passkeys work. Treat these as sources to consult, not as a substitute for applying the right standard to your system.
- Ask for evidence, then verify it. If an assistant names an API or cites a document, check that the API appears in the versioned documentation and that the cited source says what the answer claims. Retrieval-augmented generation can ground answers in approved documentation, but it can still retrieve stale pages or misstate them. A link is a lead, not a proof stamp.
- Track what your checks catch. Record rejected dependencies, unsupported imports, scanner findings, and review changes tied to generated code. Keep the measures useful: count real findings, track how quickly they are resolved, and note false alarms. Do not set a target that rewards teams for finding fewer issues. A benchmark can reveal trends, but it should not be mistaken for a guarantee.
- Revisit the controls. Registries, models, package policies, and frameworks change. Review the process when you add a new assistant or move a build system. The NIST Secure Software Development Framework is a useful reference for organizing secure development practices across the software lifecycle. Keep the checks close to the work so they remain part of the routine.
A useful starting gate is modest: registry validation, lockfile review, a dependency scanner, and a person reviewing changes to critical security paths. Then add controls based on what your pipeline actually finds. That is better than buying an elaborate tool and assuming the problem has been solved.

Comparison: Slopsquatting and Traditional Typosquatting
Slopsquatting is closely related to typosquatting, but the route to the wrong package name differs. In traditional typosquatting, someone mistypes a package name or chooses a lookalike. In slopsquatting, a model generates a plausible name that may not have existed before. Both can lead a developer to install an untrusted package, so both deserve supply-chain safeguards.
| Risk | Slopsquatting from AI hallucinations | Traditional typosquatting |
|---|
| How the name appears | A code assistant invents a plausible dependency name | A user mistypes a name or selects a lookalike |
| How an attacker may exploit it | Register a name that models repeatedly suggest, then wait for installation | Register a misspelling or confusingly similar name |
| Repeat behavior | Researchers observed recurring hallucinated names across prompts | Depends on common typos, user habits, and package popularity |
| Evidence cited here | One study of 16 code-generating models found roughly one in five recommendations in its test set were nonexistent; it recorded more than 205,000 unique fabricated names | No comparable rate is provided by that study |
| Main defenses | Validate names, restrict approved packages, inspect lockfiles, isolate builds | Validate names, restrict approved packages, inspect lockfiles, isolate builds |
| Key caveat | The study’s rate is not a universal rate, and not every invented name is registered | A misspelled name is not automatically malicious |
Here is the kicker: the first mistake may look identical in a pull request. Both cases can show a new dependency with a reasonable-sounding name. Teams do not need to guess which attack came first. They need controls that make an unapproved package visible before it runs.
The research figure should be read carefully. It describes outputs produced in a particular test, not the odds that any individual AI suggestion is fake in day-to-day development. Models, prompts, languages, and package ecosystems vary. Still, a repeatable source of plausible names gives attackers something to test, which is enough to justify ordinary dependency hygiene.
Common Mistakes to Avoid
Good intentions do not make weak controls useful. Most bad processes fail because they trust one signal too much. I have seen teams add a scanner, declare victory, and leave the most important question unanswered: does this code do what we think it does?
- Assuming code that compiles is safe. Compilation shows that code passes particular syntax and type checks. It does not establish that a package is legitimate, that a permission is narrow, or that an authentication flow resists phishing. Test results answer the questions they were designed to answer, not every security question.
- Treating a package’s existence as approval. Registry validation catches names that are absent. It does not establish the publisher’s identity, package quality, maintenance status, or behavior. Check the source, ownership, version history, and project fit. Use organization policy for packages that can run during builds.
- Relying on prompts to eliminate hallucinations. Asking a model not to invent APIs may reduce some errors. It cannot guarantee that the next answer is grounded in current documentation. Prompts shape output; they are not a security boundary.
- Assuming retrieval-augmented generation is automatically correct. Connecting a model to internal documentation can improve grounding, but the content may be stale, incomplete, or irrelevant to the question. The model can also misread a correct page. Keep sources versioned and have reviewers check the passages that support important claims.
- Treating SMS codes as the only factor worth discussing. SMS is not equally suitable for every account or threat. Current NIST guidance treats public switched telephone network authentication as restricted and calls for risk consideration. Phishing-resistant methods such as passkeys are stronger choices for many high-value accounts, but recovery, device loss, and account enrollment still need careful design.
- Granting broad permissions to make generated code work. If a suggested cloud policy fails, the quick fix is sometimes to add broad access. That hides the real issue and increases the blast radius. Ask which exact action and resource the service needs, then grant only that.
- Making human review the only barrier. Review matters, especially for critical paths, but people are inconsistent and busy. A reviewer may miss a package name among dozens of ordinary changes. Automate the repeatable checks and use human judgment where context matters.
- Measuring activity instead of risk reduction. Counting assistant-generated lines says little about safety. Track whether controls catch unsupported dependencies and risky changes, then inspect the findings. A clean dashboard can mean the system is safe, or it can mean the scanner is looking in the wrong place.
OWASP’s Top 10 for Large Language Model Applications includes risks tied to misinformation and overreliance. That is a useful reminder, not a turnkey policy. Each team still needs to decide which outputs can affect users, data, infrastructure, and money. Security guidance earns its keep when it changes a concrete review or build step.

Frequently Asked Questions
What is an AI hallucination in coding?
It is code or an explanation generated by an AI model that looks plausible but is false, unsupported, or unsafe. Common examples include nonexistent packages, invented API methods, outdated security advice, and cloud policies with excessive access. A suggestion may fail immediately, or it may run while doing something the developer did not intend. Check the relevant registry, versioned documentation, and security guidance before relying on it.
What is slopsquatting?
Slopsquatting is a package supply-chain attack in which an attacker registers a name that a code-generating model tends to hallucinate. A developer may then install that package while following the assistant’s suggestion. It resembles typosquatting, but the misleading name can come from model output rather than a human typing error. The research behind the term shows repeatable hallucinated names; it does not mean every fake name is already registered or malicious.
How can developers prevent fake AI-suggested packages?
Confirm a package exists in the correct registry and verify its publisher, purpose, and version. Use dependency allowlists where appropriate, review lockfile changes, and run automated checks before installation or build. Keep CI credentials limited and isolate untrusted jobs. These controls work together: registry checks can catch a nonexistent name, while provenance review and least privilege address risks that a simple existence check cannot.
Are passkeys safer than SMS codes for authentication?
Passkeys are designed to resist phishing because they are bound to the legitimate website or app origin, while SMS codes can be exposed to attacks such as number takeover or real-time phishing. That does not make every passkey setup perfect. Enrollment, recovery, device loss, and account support processes still matter. Follow current guidance, select methods based on the account’s risk, and avoid letting an AI-generated example decide the policy for you.
Final Thought
AI coding assistants are useful because they shorten the distance between a question and a first draft. That speed has value. It also shifts work into verification, where a package name, security assumption, or permissions block needs a second look before it becomes part of a product.
I have learned that the best safeguard is rarely a dramatic rule. It is the small gate that runs every time: check the registry, review the lockfile, limit build credentials, and ask a qualified person to examine changes that protect users. The checks should be boring and dependable. That is a compliment.
No model can take responsibility for a service after it ships. The people who build and operate it still have that duty, and they need tools that help them meet it without relying on perfect attention. Treat generated code as a proposal, not an authority. Verify the facts, protect the pipeline, and keep the productivity gains without letting trust outrun evidence.
A fast answer is a starting point. A safe system comes from checking what that answer asks you to run.