DEV Community

forqx
forqx

Posted on Originally published at diffdojo.com

How to spot hallucinated library methods when reviewing AI-generated code

To spot a hallucinated library method in AI-generated code, take every call to a library that you have not typed yourself recently and look the name up in that library's documentation, at the version the project uses. Invented methods are easy to miss because they follow the library's naming habits and read correctly; they fail only when the line runs. This post works through one example, a pull request that calls _.deepMerge, which Lodash has never had, with the review comment, the fix and a script that shows the difference.

In January 2026, a security researcher at Aikido Security noticed that AI coding tools kept recommending an npm package called react-codeshift. The package had never existed. It was a hallucinated mashup of two real packages, jscodeshift and react-codemod, and by the time anyone noticed, the name had propagated to 237 GitHub repositories. Researchers now call this class of attack slopsquatting: register the fake name that models keep inventing, then wait for someone to install it. But hallucinated APIs don't always show up at the package level. Sometimes the package is real, the import is real, and the only thing that's invented is a single method name buried in an otherwise perfectly idiomatic call site. That's harder to catch, because everything around it looks right. This exercise is about training your eye for exactly that situation: a PR that calls _.deepMerge, which sounds like Lodash, looks like Lodash, fits the pattern of every other Lodash utility you've ever used, and does not exist. The exercise teaches you to verify library APIs during review instead of trusting that a plausible name is a real one, and it's useful for anyone reviewing AI-written JavaScript or Node code.

What the PR is supposed to do

The task is to add a resolveSettings function for a preferences page. The requirements:

  1. Add resolveSettings(userSettings) that layers a user's saved overrides over DEFAULT_SETTINGS.
  2. Nested groups (notifications, editor, privacy) must merge deeply: a user who only set notifications.push must keep the default digest.
  3. Never mutate DEFAULT_SETTINGS.

The function is called on every page load to build the effective settings for the signed-in user. The PR description says it "uses lodash's deep merge so partial overrides layer over the nested defaults without clobbering sibling keys, and merges into a fresh object so the shared defaults are never mutated." Sounds good. Here's the diff.

src/settings/resolveSettings.js

const _ = require('lodash');

const DEFAULT_SETTINGS = {
  notifications: { email: true, push: false, digest: 'weekly' },
  editor: { theme: 'system', fontSize: 14 },
  privacy: { showProfile: true },
};

function resolveSettings(userSettings) {
  return _.deepMerge({}, DEFAULT_SETTINGS, userSettings || {});
}

module.exports = { resolveSettings, DEFAULT_SETTINGS };
Enter fullscreen mode Exit fullscreen mode

Thirteen lines. Clean structure, sensible defaults, a null guard on the input, and that empty {} as the first argument to protect the shared object from mutation. If you've written Lodash code before, this reads like the kind of PR you approve while waiting for your coffee to cool.

Try it yourself first. The same PR is in DiffDojo with no spoilers: leave inline comments and a verdict, then come back for the walkthrough. Review this PR. A free account unlocks 1 PR of your choice; the pass opens the full library.

Walkthrough starts below. Stop here if you want to try the exercise first.


The hallucinated method: _.deepMerge is not in Lodash

Open your browser, go to the Lodash documentation, and search for deepMerge. You will find nothing. There is no _.deepMerge in Lodash. There never has been, in any version. The method is _.merge, and it already merges deeply by default. That's just what _.merge does. There is no shallow variant you need to opt out of; "deep" is not a mode you turn on.

So why does the name feel so familiar? Because half the JavaScript ecosystem uses exactly that word. The deepmerge package on npm has tens of millions of weekly downloads. Immutable.js has mergeDeep. Various utility libraries expose deepMerge as a standalone function. The name is a perfectly reasonable guess if you're a model (or a human) that has seen thousands of merge-related code snippets but hasn't memorized which exact method belongs to which exact library. The problem is that a reasonable guess is still a guess, and in this case it's wrong.

What happens when this code runs

The very first page load for the very first user throws:

TypeError: _.deepMerge is not a function
Enter fullscreen mode Exit fullscreen mode

That's it. No subtle data corruption, no edge case you'd need a clever test to hit. Line 10 executes, Lodash looks up deepMerge on its export object, gets undefined, tries to call it, and the runtime throws. The preferences page 500s for everyone, immediately, every time. If you have error tracking, you'll see it within seconds of deploy. If you don't, you'll see it when users start complaining.

There's a strange irony to this bug. Everything else in the PR is correct. The {} as the first merge target is exactly the right way to protect DEFAULT_SETTINGS from Lodash's mutate-the-first-argument behavior. The userSettings || {} null guard is right. The argument order (target, defaults, overrides) is right. The PR description's explanation of why deep merging matters is right. All of that careful, idiomatic code sits behind a function call that will never execute because the function name is made up.

The review comment and the verdict

function resolveSettings(userSettings) {
  return _.deepMerge({}, DEFAULT_SETTINGS, userSettings || {});
}
Enter fullscreen mode Exit fullscreen mode

Review comment: _.deepMerge is not a Lodash method. This will throw TypeError: _.deepMerge is not a function on every call. The Lodash method for recursive object merging is _.merge, which already merges deeply by default. The rest of the call site (empty object target, argument order, null guard) is correct and should work as-is once the method name is fixed.

Verdict: request changes. The function cannot be called without throwing, so this is a blocker, not a suggestion. The fix is exactly one word.

The fix: _.merge

Replace _.deepMerge with _.merge:

-   return _.deepMerge({}, DEFAULT_SETTINGS, userSettings || {});
+   return _.merge({}, DEFAULT_SETTINGS, userSettings || {});
Enter fullscreen mode Exit fullscreen mode

That's it. _.merge does exactly what the PR description says _.deepMerge was supposed to do: it recursively merges own and inherited enumerable string-keyed properties of source objects into the destination object. The empty {} as the first argument means DEFAULT_SETTINGS itself is never mutated. A user who sets only notifications.push: true keeps the default digest: 'weekly' and email: true, because _.merge walks into nested objects instead of replacing them wholesale.

A script that shows the failure and the fix

Here's a small script that shows the bug in the original and confirms the fix:

const _ = require('lodash');

const DEFAULT_SETTINGS = {
  notifications: { email: true, push: false, digest: 'weekly' },
  editor: { theme: 'system', fontSize: 14 },
  privacy: { showProfile: true },
};

// --- Original: throws immediately ---
try {
  _.deepMerge({}, DEFAULT_SETTINGS, { notifications: { push: true } });
} catch (e) {
  console.log('Original:', e.message);
  // "_.deepMerge is not a function"
}

// --- Fixed: works correctly ---
const result = _.merge({}, DEFAULT_SETTINGS, { notifications: { push: true } });
console.log('Fixed:', JSON.stringify(result.notifications));
// {"email":true,"push":true,"digest":"weekly"}

// --- DEFAULT_SETTINGS not mutated ---
console.log('Defaults intact:', DEFAULT_SETTINGS.notifications.push);
// false
Enter fullscreen mode Exit fullscreen mode

The original code never gets past the first line of resolveSettings. The fixed version produces exactly the merged result the requirements describe, and DEFAULT_SETTINGS.notifications.push stays false after the call because the merge target is a fresh empty object.

Why hallucinated methods survive review

This is the part that makes hallucinated APIs uniquely dangerous compared to, say, a wrong variable name or a missing null check. A wrong variable name looks wrong. A missing null check at least raises the question "what if this is null?" But a hallucinated method name looks exactly like every correct method call in the same file. Your eye pattern-matches _.deepMerge as "that's a Lodash utility" and moves on, because the call site is perfect. The arguments are in the right order. The import is real. The surrounding logic demonstrates genuine understanding of how Lodash merge works. The only thing wrong is that the specific four-syllable combination deepMerge is not in Lodash's export table.

Plain JavaScript won't catch this for you. There's no compile step that checks whether a property exists on an object before you call it. ESLint won't flag it. Your test suite won't catch it either, unless you have a test that actually calls resolveSettings, and if this is a new function being added in this PR, there probably isn't one yet. The only thing standing between this bug and production is a reviewer who reads line 10 and thinks: "Is deepMerge actually in Lodash, or does that just sound like it should be?"

That question takes about fifteen seconds to answer. Open the docs, Ctrl+F, done. The habit of asking it is worth more than any amount of static analysis for this class of bug.

How often models invent methods, and what tooling catches

The numbers are not small. A 2026 study of code generation benchmarks that require library use found that "LLMs generate code that uses non-existent library features in 8.1-40% of responses." The same paper measured what static analysis can do about it: the tools detected 14% to 85% of library hallucinations, depending on the model and the dataset, and the authors' manual analysis puts the ceiling for any static method at 48.5% to 77%.

Another study draws the line this exercise sits on. It separates library name hallucinations, which it glosses as "invalid imports," from library member hallucinations, "invalid calls from valid libraries." The first kind is what makes slopsquatting possible: the import names a package that does not exist, and somebody can register it. The second kind is _.deepMerge: the import is real, the lockfile is clean, a dependency scanner has nothing to flag, and the only thing wrong is one identifier.

In a typed codebase the compiler closes most of that gap. With a library's type definitions installed, TypeScript rejects a call to a member that is not there with error 2339, "Property does not exist on type." In plain JavaScript, which is what this PR is, the check is you.

The review habit: verify the method, not just the pattern

When you're reviewing code that calls a library API, especially in AI-written PRs, add one step to your mental checklist: pick any method name you haven't personally typed in the last month and check whether it exists. Not whether it looks right. Not whether the call site is idiomatic. Whether the method is actually in the library's documentation, at the version the project uses.

This takes seconds and catches a class of bug that no linter, no type checker (in vanilla JS), and no test suite is going to catch for you unless someone already wrote a test for the exact code path. AI models hallucinate API surfaces because they've seen thousands of similar-but-not-identical libraries during training, and the method name they produce is a plausible interpolation rather than a lookup. The result reads like real code because it nearly is real code. The only person who can tell the difference is the reviewer who bothers to check.

Common questions

How do I spot hallucinated library methods when reviewing AI-generated code?

Check the name, not the shape. For each library call in the diff that you do not recognise from recent use, open the library's documentation or type definitions at the version in the lockfile and confirm the method exists with that signature. Be most suspicious of names that combine a real library with a word from a neighbouring one, such as _.deepMerge in Lodash, where the real method is _.merge. In TypeScript the compiler reports a missing member; in plain JavaScript nothing does until the line runs.

Do linters, type checkers or tests catch a hallucinated method?

A type checker does when the library ships types: TypeScript reports error 2339, property does not exist on type, before the code runs. Plain JavaScript has no such check. A test catches it only if it executes the line. A 2026 study of code generation benchmarks found that static analysis tools detected between 14% and 85% of library hallucinations depending on the model and dataset, so tooling helps and does not replace reading the docs.

How often do AI models call library functions that do not exist?

Often enough to check every time. In a 2026 study of benchmarks that require library use, models generated code using non-existent library features in 8.1% to 40% of responses. Research separates two kinds: invented packages, where the import itself is wrong, and invented members of real libraries, where the import is fine and only the call fails.

Where can I practice catching hallucinated APIs in code review?

DiffDojo has this PR and other pull requests where AI-written code calls an API that does not exist or does not behave as the code assumes, plus clean ones where the right call is to approve. You leave inline comments, give a verdict and get graded against a canonical review. One PR in every stack is open without signup, a free account opens one more of your choice, and the pass opens the rest of the library.

Related walkthroughs: passing tests that miss the bug, forEach with an async callback, a performance bug behind correct results.


Originally published on DiffDojo. DiffDojo is a trainer for reviewing AI-written pull requests: pick a PR and review it cold. A set of PRs in every stack is free, no signup; a free account unlocks one more, and the pass opens the whole library.

Top comments (0)