Sub topic 2
How AI-Generated Code Typically Goes Wrong
This chapter assumes you can read Python, understand a Git diff, and have used an AI coding assistant. It describes the recurring ways AI-generated code fails. Knowing the patterns tells you where to look first when you review a change.
Why the failures follow patterns
An AI coding assistant predicts code that is likely to follow your prompt, based on patterns in its training data. It does not run the code or consult the current documentation. Unless you give it tools to do so, it also doesn't check your project's conventions. The output is therefore fluent and well formatted even when it is wrong.
This gives the failures a shape:
- The code resembles common code. Rare APIs, new library versions, and project-specific rules are where it slips.
- The code answers the prompt as written. It does not answer the intent behind the prompt, or the cases you forgot to mention.
- The code looks confident either way. Style gives you no signal about correctness.
Human authors make mistakes too, but a human usually shows doubt through hedged comments or a "not sure about this" note in the pull request. AI output rarely does. You have to find the doubt yourself.
Hallucinated APIs and packages
A hallucination is output that looks real but refers to something that does not exist. In code this means three things:
- A function or method that the library does not have.
- A parameter the function does not accept.
- A whole package that was never published, or one with a name close to a real one.
Hallucinated names usually sound right. A model that has seen json.loads and json.dumps may happily write json.parse, because that is the JavaScript name. The error often appears only at runtime, and only on the code path that calls it.
You can check a suspect name directly in the interpreter:
import json
for name in ("parse", "loads"):
print(name, hasattr(json, name))This prints parse False and loads True. For third-party libraries, open the documentation for the version you have installed. Don't rely on the assistant's memory of an older version. A later chapter covers dependency checks in detail. For now, treat every import and every unfamiliar method call as unverified until you have seen it in real documentation or run it.
A package name that does not exist is more than a nuisance. Attackers can register names that assistants tend to invent, so installing a hallucinated package can run someone else's code on your machine. Never run pip install on a name you have not checked.
Missed edge cases
The assistant writes the happy path first and most reliably. Boundary inputs are where it fails: empty collections, a single element, zero, negative numbers, None, very large values, Unicode, and duplicates.
Here is a median function of the kind an assistant might produce:
def median(values):
ordered = sorted(values)
return ordered[len(ordered) // 2]It works for [1, 2, 3] and returns 2. It is wrong for [1, 2, 3, 4], where it returns 3 and the median is 2.5. It also raises IndexError on an empty list. The code is short and reads naturally, so the bug is easy to miss.
A corrected version handles both parities and states what happens on empty input:
def median(values):
if not values:
raise ValueError("values must not be empty")
ordered = sorted(values)
mid = len(ordered) // 2
if len(ordered) % 2 == 1:
return ordered[mid]
return (ordered[mid - 1] + ordered[mid]) / 2
print(median([1, 2, 3]))
print(median([1, 2, 3, 4]))This prints 2 and then 2.5. When you read AI code, ask for each input: what is the smallest, largest, and strangest value this could receive? Then trace the code with that value.
Outdated patterns
The training data contains years of code. Deprecated functions, old library versions, and superseded idioms appear in it often, so the model reproduces them. The result still runs today, which is why it passes casual review. It may emit warnings, break on the next upgrade, or have a known flaw.
A common Python example is datetime.utcnow(). It is deprecated since Python 3.12 because it returns a datetime with no timezone attached. This is the current form:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now.tzinfo)It prints UTC, so the value carries its timezone. Other typical cases include old web framework APIs, the requests style of HTTP calls where your project uses another client, and cryptographic choices such as MD5 for password hashing. Check the version in your lock file and compare the code against the documentation for that version.
Silent drift from the requirement
The assistant can solve a slightly different problem from the one you posed. Typical forms:
- It adds features you did not request, such as extra configuration options or a caching layer.
- It changes behavior outside the target area, for example by renaming a function or reformatting a file.
- It replaces a hard requirement with an easier one and does not say so. For example, it validates an email with a loose pattern when you asked for strict rules.
- It deletes or weakens an existing check to make the new code work.
The last form is the most dangerous. A diff that removes a validation line or loosens a test assertion can look like cleanup. Read the removed lines (the - lines) with the same attention as the added ones.
Insecure defaults
The assistant optimizes for code that works in the demo. That often means the insecure choice, because it is the shorter one. Watch for these:
- SQL built by string formatting instead of parameters.
verify=Falseon HTTPS requests to silence a certificate error.- Secrets or tokens written directly into source as "placeholder" values that people forget to replace.
- Missing validation of user input, or file paths taken from user input without checks.
- Debug mode left on and broad permissions such as
chmod 777.
The security chapter covers how to review for these in depth. Here, the point is that they appear regularly and look harmless.
Swallowed errors and misleading tests
Code that hides failure is a common AI pattern, because a program that never crashes looks finished:
def load_config(path):
try:
with open(path) as f:
return f.read()
except Exception:
return ""A typo in path, a permissions problem, and a missing file all produce an empty string. The caller cannot tell them apart from an empty file. Prefer catching the specific exception you can handle, and let the others propagate.
Tests written by the same assistant need the same scrutiny. Known weaknesses include:
- Tests that only assert what the code already does, so they cannot fail.
- Tests that mock the very function under test.
- Tests that cover the happy path only.
- A test that was changed to match a bug.
A passing suite is evidence only when the tests could have failed. We return to this in the chapter on tests as evidence.
Poor fit with your codebase
The assistant sees only the context you gave it. It may duplicate a helper that already exists in your repository, ignore your naming and error-handling conventions, or introduce a second way of doing something your team standardized. The code can be correct and still be a bad contribution, because it raises the cost of every later change. Search your repository for existing utilities before accepting new ones.
Summary of the patterns
| Failure mode | What it looks like in a diff | First check |
|---|---|---|
| Hallucinated API or package | Unfamiliar method, new import, new dependency line | Find it in the docs for your installed version |
| Missed edge case | Indexing, division, or loops with no guard | Trace empty, single, and extreme inputs |
| Outdated pattern | Deprecation warnings, old idioms | Compare with current docs and your lock file |
| Requirement drift | Extra features, removed lines, renamed items | Compare the diff against the original request |
| Insecure default | String-built queries, `verify=False`, literal secrets | Search for these patterns explicitly |
| Swallowed error | Broad `except`, silent fallbacks | Ask what happens when each call fails |
| Weak tests | Mocks of the tested function, no failing case | Break the code and see if a test fails |
| Poor codebase fit | New helper duplicating an existing one | Search the repository for similar code |
Using the patterns while you review
The list above is a set of questions to ask of every diff, in roughly this order:
- Do all names, imports, and parameters exist in the versions I use?
- Which inputs did the author not think about?
- Did anything change or disappear that I did not ask for?
- What happens on failure, and who finds out?
- Does this belong in my codebase as written?
Later chapters turn each question into a concrete technique. The aim now is to read AI output as a skeptic who knows where the usual mistakes are, not as a reader checking whether the code looks reasonable.
Exercise
An assistant returns this function for "return the last item of a list, or None if the list is empty": def last(items): return items[-1] It works on [1, 2, 3]. Which failure mode does it show, what input exposes it, and how would you fix it?
Show answer
It shows a missed edge case, and the code drifts from the stated requirement. Calling last([]) raises IndexError instead of returning None. A fix is: def last(items): return items[-1] if items else None. A test with an empty list should be added so the behavior stays pinned.
Exercise
A diff for a "fix the failing login test" request changes assert response.statuscode == 200 to assert response.statuscode in (200, 401), and the test now passes. Which failure modes are present, and what do you do?
Show answer
This is requirement drift combined with a weakened test. The assistant made the test pass by loosening it, not by fixing the login behavior. Reject the test change, find out why login returns 401, and fix that cause. The test should keep requiring 200.