The Problem
In March 2026, a developer asked an AI coding assistant to implement idempotency for payment retries. The code looked correct. It passed every unit test. It was reviewed and merged. Two hours later, 847 customers were charged twice for the same transaction -- $179,564 in erroneous charges.
The bug was a classic check-then-act race condition: two threads could both read "no existing payment" and both proceed to charge. No human engineer writing payment code would skip database-level locking. But the AI had never been trained on the specific failure mode of concurrent access patterns in payment systems. It produced code that was syntactically perfect, structurally naive.
This is not an isolated incident. A 2025 study analyzing 3,500 code artifacts from 7 different AI models found that AI-generated code has 1.7x more defects than human-written code, despite being less structurally complex. The defects are not random -- they cluster into specific, predictable patterns that this course will teach you to detect, test for, and prevent.
The four primary AI defect categories
The arXiv study (2508.21634) analyzed AI-generated code across multiple models and identified four dominant defect patterns that appear with significantly higher frequency in AI code than in human code:
| Category | What it looks like | Why AI does it |
|---|
| Variable assignment errors | result = process(data) where result is overwritten later without using the first value, or variables are assigned but never read | AI models predict the next token based on patterns, not data flow. They produce assignments that look correct locally but break the data flow graph. |
| Repetitive logic | The same 5-line block copy-pasted 4 times with minor variations instead of a loop or function | AI models generate code by pattern matching against training data. When they've seen similar patterns repeated, they reproduce the repetition rather than abstracting. |
| Hallucinated APIs | Calling json.parse() in Python (should be json.loads()), or calling a function that doesn't exist in the imported library | AI models mix up APIs across languages and libraries. They confidently call functions that sound right but don't exist. |
| Missing exception handling | data["key"] without try/except, int(user_input) without validation, file operations without error handling | AI models generate the "happy path" first and often stop there. The training data contains more correct examples than error-handling examples. |
The 1.7x multiplier is not uniform
The defect rate varies by language and task. Python AI code shows approximately 5,000 more vulnerable samples than human code in the study's dataset. Java shows 18,000 more. The defect multiplier is highest in tasks involving security-sensitive operations (encoding, escaping, cryptography) and lowest in straightforward CRUD operations. This means your testing strategy should be proportional to the risk category, not applied uniformly.
Why less complexity means more defects
The counterintuitive finding from the study is that AI code is less structurally complex than human code but more defect-prone. This seems paradoxical until you understand what "complexity" means in this context.
Human engineers add complexity deliberately: defensive checks, error handling, edge-case branches, abstraction layers. These add cyclomatic complexity but reduce defects because they handle the scenarios where code would otherwise fail. AI models produce simpler code because they generate the most probable path through a problem -- which is usually the happy path. The missing complexity IS the missing safety net.
| Metric | Human Code | AI Code | Implication |
|---|
| Cyclomatic complexity | Higher | Lower | AI code has fewer branches -- fewer edge cases handled |
| Lines of code | More | Fewer | AI code is more concise but omits defensive code |
| Defect density | Lower | 1.7x higher | Simpler code, more bugs -- because the simplicity is naivety |
| Repetition | Lower | Higher | AI reproduces patterns instead of abstracting |
Recognizing AI defect patterns in real code
Let's look at a real example. An AI assistant was asked to write a function that processes a list of user records and returns only active users with their email addresses normalized to lowercase:
def get_active_users(users):
result = []
for user in users:
if user["status"] == "active":
email = user["email"].lower()
result.append({"name": user["name"], "email": email})
return result
This looks fine. But it has three AI-typical defects:
- Missing exception handling:
user["status"] will throw KeyError if the key doesn't exist. user["email"] will throw KeyError or AttributeError if email is None (.lower() on None). - No type validation: If
user["email"] is an integer, .lower() will throw AttributeError. - Missing null check on the list itself: If
users is None, the for loop will throw TypeError.
A human engineer with experience would write:
def get_active_users(users):
if not users:
return []
result = []
for user in users:
if not isinstance(user, dict):
continue
if user.get("status") != "active":
continue
email = user.get("email")
if not email or not isinstance(email, str):
continue
result.append({"name": user.get("name", ""), "email": email.lower()})
return result
The human version is more complex -- and that complexity is exactly what prevents the defects.
An AI assistant generates the following function to parse a JSON string and extract a field. Which AI defect pattern is most prominently exhibited?
def extract_field(json_str, field):
data = json.loads(json_str)
return data[field]
~~~ Repetitive logic -- the same pattern is duplicated unnecessarily Hallucinated API -- json.loads does not exist in Python's standard library Missing exception handling -- json.loads can throw JSONDecodeError on invalid input, data[field] can throw KeyError, and neither is handled Variable assignment error -- data is assigned but the wrong variable is returned ~~~ 2 ~~~ The function has zero error handling. json.loads() will raise json.JSONDecodeError if json_str is not valid JSON. data[field] will raise KeyError if the field doesn't exist. Neither case is handled, meaning any malformed input or missing field will crash the program with an unhandled exception. This is the most common AI defect pattern: the model generates the happy path and stops, omitting the defensive code that a human engineer would add by habit.
### The Hallucinated API Pattern in Practice
Hallucinated APIs deserve special attention because they are the hardest to catch with traditional testing. If you write a test that imports the same hallucinated API, the test passes -- because you're testing the same incorrect assumption.
The 2025 USENIX study on AI package hallucination found that **19.7% of AI-recommended packages don't exist**. Open-source models hallucinate at 21.7%, commercial models at 5.2%. The study identified over 205,000 unique hallucinated package names across 16 models.
A real example: an AI assistant generated Python code that imported `from dateutil.parser import parse` -- which is correct. But it also generated `from requests.adapters import HTTPAdapter` and then called `session.mount('https://', CustomAdapter())` where `CustomAdapter` was never defined. The model hallucinated a class that sounded like it should exist in the `requests` library but doesn't.
This is why **dependency verification** (Phase 6) and **mutation testing** (Phase 4) are critical layers in the verification pyramid. Traditional tests won't catch hallucinated APIs if the test author makes the same assumption.
```checkpoint
Your team uses an AI coding assistant that generates Python code. A junior developer runs the generated code and gets an `ImportError` for a package called `fastvalidate`. The developer says "the AI must be right, let me just pip install it." Why is this dangerous, and what should they do instead?
~~~
It is not dangerous -- if the AI recommended the package, it probably exists and just needs to be installed
It is dangerous because installing third-party packages always violates company policy
It is not dangerous because pip will verify the package's integrity automatically
It is dangerous because `fastvalidate` may be a hallucinated package name. An attacker could have registered a malicious package with that name (slopsquatting). The developer should verify the package exists on PyPI, check the publisher's identity and registration date, and search for the official documentation before installing anything
~~~
3
~~~
This is the slopsquatting attack vector. The USENIX 2025 study found that 19.7% of AI-recommended packages don't exist. Attackers monitor AI model outputs for hallucinated package names and register malicious packages with those names. When a developer blindly `pip install`s the hallucinated name, they install the attacker's code. The correct response is to verify the package against PyPI, check publisher identity and registration date (packages registered less than 90 days ago are a red flag), and confirm the package is documented in official sources. This is covered in depth in Phase 6.