Back to Insights
AI & Machine Learning•AI Coding Agents Are Smarter Than Ever—So Why Do They Still Fail at the Basics? A Deep Dive into Real-World Failure Patterns•deep dive•November 21, 2026•14 min read

AI Coding Agents Are Smarter Than Ever—So Why Do They Still Fail at the Basics? A Deep Dive into Real-World Failure Patterns

A technical deep-dive into why state-of-the-art AI coding agents ace complex tasks yet fail at trivial ones—and how to engineer around their blind spots.

T
Tamiz UddinFull-Stack Engineer

The paradox is everywhere. An AI coding agent will generate a 200-line distributed systems architecture that looks like it came from a principal engineer, then turn around and use the wrong HTTP method in a fetch call, or forget to handle a null check that a junior dev would never miss. It will refactor a 5,000-line module flawlessly, then leave a dangling import that breaks the build. Why does the same model that can reason about complex concurrency fail at the basics of its own language's standard library?

The answer isn't a simple quality issue—it's structural. The failure patterns aren't random noise; they cluster around specific architectural weaknesses in how these systems are built. Understanding those patterns is the difference between treating AI agents as a magic bullet and engineering them as the powerful but flawed tools they really are.

1. The Paradox: Complexity Succeeds, Basics Fail

Consider this real-world scenario from a recent large-scale deployment of a leading AI coding agent. The agent was tasked with implementing a payment reconciliation service. It produced a beautiful, well-architected solution with proper async/await handling, idempotency keys, and a dead-letter queue. The code review passed. The unit tests passed. It was genuinely good work.

Then, in the same session, the agent was asked to add a simple utility function that formats a date string. It produced:

javascript
function formatDate(date) {
  return date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' });
}

That's correct. But the agent was working in a codebase that used a custom date library, not the native Date object. The input was a string, not a Date. The agent didn't check. It crashed at runtime. The failure wasn't a reasoning failure—it was a context failure. The agent had lost track of the input type because it was buried in a 50-file repository that the agent had only partially loaded.

This is the central paradox: AI agents are exceptional at local reasoning but unreliable at global consistency. They can solve a hard problem in isolation, but they struggle to maintain the implicit invariants of a large codebase.

2. Root Cause #1: The Context Window Paradox

The most significant structural limitation is the context window. Modern agents have impressive context windows—200k, 1M, even 2M tokens. But here's the dirty secret: context is not the same as comprehension.

When an agent processes a 200k-token context, it doesn't read it all with equal attention. The transformer architecture uses attention mechanisms that are computationally expensive and, in practice, have a decay effect. Information in the middle of a long context is often "lost"—the model attends more heavily to the beginning (the system prompt, the task description) and the end (the most recent code).

This is known as "lost in the middle" or the context fragmentation problem. In practical terms:

  • The agent sees the task description clearly.
  • The agent sees the most recent code clearly.
  • The agent sees the 10,000 tokens in between as a blur.

So when an agent is asked to modify a function in a large file, it might miss that a helper function was already defined 3,000 lines earlier, or that a variable was renamed in a previous edit. The agent doesn't fail because it's stupid; it fails because its attention is diluted.

The Multi-File Problem

This gets worse with multi-file changes. Agents use retrieval-augmented generation (RAG) or file-grep tools to find relevant code. But these tools are imperfect. When an agent searches for getUserById, it might find the definition but not the caller. It might miss a second definition in a test file. It might miss that the function was deprecated.

The result is a class of bugs that look like carelessness but are actually retrieval failures: the agent simply didn't see the relevant code, so it couldn't account for it.

3. Root Cause #2: The Training Data Gap

AI models are trained on massive corpora of public code. That's their superpower—they've seen billions of lines of JavaScript, Python, TypeScript, Go, Rust, etc. But that's also their weakness: they're trained on the past, not your codebase.

The "Average Code" Bias

Because models are trained on the distribution of code in the wild, they learn to produce the average solution. This is great for common patterns—most codebases have similar CRUD operations, similar error handling, similar file structures. But it's terrible for codebases that deviate from the norm.

If your codebase uses a custom error-handling pattern, a specific dependency injection style, or a non-standard folder structure, the agent will often revert to the generic pattern. It doesn't know your conventions because they're not in its training data. It will produce code that works in isolation but clashes with your architecture.

The Version Mismatch Problem

Training data has a cutoff date. If your project uses a library version released after that cutoff, the model has never seen it. It will confidently generate code using the old API. This is why agents frequently produce code that uses deprecated methods or removed features.

A classic example: an agent asked to write a React component might use ReactDOM.render() instead of createRoot() because ReactDOM.render was in its training data for longer. It's not a hallucination—it's a temporal hallucination. The model is right about the past but wrong about the present.

4. Root Cause #3: Statelessness and the Missing Verification Loop

AI agents are fundamentally stateless. They don't remember what they did in a previous turn. Each generation is a fresh inference. This is a fundamental architectural difference from a human developer.

A human dev writes code, runs tests, sees the failure, and iterates. An AI agent, in its default configuration, generates code and moves on. It doesn't run tests unless specifically prompted to. It doesn't check for syntax errors unless the tooling catches them.

The One-Shot Generation Problem

Most agent frameworks operate in a one-shot generation mode: the agent generates a response, and the user accepts or rejects it. There's no feedback loop. If the generated code has a bug, the agent never knows. It's like asking a developer to write code without ever running it.

Some newer agents have added test-run loops—the agent runs tests, sees failures, and iterates. But this is expensive and often disabled by default. Even when enabled, the agent's ability to diagnose test failures is limited. It sees the error message but often can't trace it back to the root cause in its own generated code.

The Missing Mental Model

Human developers build a mental model of the codebase as they work. They know that UserService is in src/services/user-service.ts and that it's imported in 14 files. They know the naming conventions. They know the architecture.

AI agents don't build this mental model. They have a snapshot of the codebase at the moment of the prompt, but they don't maintain it across turns. Each new prompt is a fresh start. This is why agents are so good at isolated tasks and so bad at tasks that require cross-file consistency.

5. Root Cause #4: The "Good Enough" Optimization

LLMs are trained to maximize the probability of the next token. They're not trained to maximize correctness. This creates a subtle but pervasive bias toward plausible but incorrect outputs.

When a model generates code, it's not trying to produce the correct code—it's trying to produce the most likely code. The most likely code is the code that most resembles the training data. This means:

  • The model prefers familiar patterns over correct patterns. If a familiar pattern has a subtle bug, the model will reproduce it.
  • The model prefers simple solutions over robust ones. It will skip error handling because error handling is less common in training data than happy-path code.
  • The model prefers to complete the task rather than perfect it. It will produce a solution that satisfies the prompt, even if the solution is incomplete or fragile.

The "Almost Right" Problem

This is why you see so many "almost right" solutions. The agent produces code that is 95% correct. The logic is sound, but:

  • It forgot to handle the edge case.
  • It used a magic number instead of a named constant.
  • It didn't add a type annotation.
  • It didn't handle the error.

These aren't failures of reasoning; they're failures of optimization. The model optimized for likelihood, not correctness. And because the training data is full of code that skips error handling, the model reproduces that pattern.

6. Failure Pattern Taxonomy: What Actually Breaks in Production

Now that we understand the root causes, let's look at the actual failure patterns. These are the recurring bugs that show up in real-world deployments, categorized by their underlying cause.

Pattern 1: The Off-by-One Error

Frequency: Very high Root cause: Training data bias

Off-by-one errors are the most common bug in human programming, and AI agents reproduce them with alarming regularity. The model sees the pattern for (let i = 0; i <= arr.length; i++) in its training data and reproduces it, even when the correct code is i < arr.length. The model doesn't reason about array indices; it reproduces the most common pattern.

javascript
// AI-generated
for (let i = 0; i <= items.length; i++) {
  console.log(items[i]); // undefined on the last iteration
}

Pattern 2: The Wrong API

Frequency: High Root cause: Training data cutoff + version mismatch

The agent uses an API that doesn't exist in your version of the library. This is especially common with fast-moving libraries like React, Next.js, and Node.js.

python
# AI-generated using the old API
import requests
response = requests.get(url)
response.json()

# Your project uses httpx, not requests

Pattern 3: The Missing Null Check

Frequency: Very high Root cause: "Good enough" optimization

The agent assumes a value is always present because that's the happy path. It doesn't handle the case where the value is null or undefined. This is the most dangerous pattern because it causes runtime crashes that pass static analysis.

typescript
// AI-generated
const user = await getUserById(id);
console.log(user.name); // TypeError: Cannot read properties of undefined

Pattern 4: The Incomplete Refactor

Frequency: High Root cause: Context fragmentation

The agent renames a function or variable but doesn't update all the call sites. It sees the definition in its context but misses the callers in other files. The result is a broken build or a runtime error.

javascript
// Before
function fetchData() { ... }

// After (AI-generated)
function fetchUserData() { ... }
// But fetchData() is still called in 5 other files

Pattern 5: The Security Vulnerability

Frequency: Moderate but high impact Root cause: Training data bias + missing security awareness

The agent generates code that is vulnerable to injection attacks, XSS, or SQL injection because it reproduces insecure patterns from its training data. This is the most serious pattern because it introduces security flaws that pass functional tests.

python
# AI-generated
query = f"SELECT * FROM users WHERE name = '{user_input}'"
# SQL injection vulnerability

Pattern 6: The Wrong Import

Frequency: Very high Root cause: Retrieval failure

The agent imports a module that doesn't exist, or imports the wrong module entirely. This is often caused by the agent guessing the import path based on the file structure it's seen.

typescript
// AI-generated
import { UserService } from './services/user-service';
// But the actual file is './services/userService'

Pattern 7: The Silent Error Swallowing

Frequency: High Root cause: "Good enough" optimization

The agent catches an error and does nothing with it. This is common because the training data is full of empty catch blocks. The agent reproduces the pattern without realizing it's hiding bugs.

javascript
// AI-generated
try {
  await saveUser(user);
} catch (error) {
  // empty catch block - error is silently swallowed
}

7. Engineering Mitigations: How to Build Around the Blind Spots

Understanding the failure patterns is step one. Step two is engineering around them. Here are the practical mitigations that work in production.

Mitigation 1: Constrain the Context

Problem: Context fragmentation Solution: Reduce the amount of code the agent sees. Instead of giving the agent the entire repository, give it only the files relevant to the task.

bash
# Instead of:
# agent --repo ./entire-project

# Use:
# agent --files src/services/user-service.ts src/types/user.ts

By constraining the context, you reduce the chance that the agent will miss important details. The agent can focus its attention on a smaller set of files, which improves both accuracy and consistency.

Mitigation 2: Add a Verification Loop

Problem: Statelessness Solution: Force the agent to run tests before it's done. Most agent frameworks support this, but it's often disabled by default.

bash
# Enable test-run loop
agent --run-tests --test-command "npm test"

This creates a feedback loop: the agent generates code, runs tests, sees failures, and iterates. This is the single most effective mitigation because it catches errors that the agent would otherwise miss.

Mitigation 3: Use TypeScript (or Strict Types)

Problem: Missing null checks, wrong APIs Solution: Use a strongly typed language or enable strict mode. TypeScript catches many of the failure patterns automatically.

typescript
// TypeScript catches this at compile time
const user = await getUserById(id);
console.log(user.name); // Error: 'user' is possibly 'undefined'

Static type checking is the most reliable safety net because it doesn't rely on the agent to be correct. It catches the error before it reaches production.

Mitigation 4: Add Custom Lint Rules

Problem: Security vulnerabilities, error swallowing Solution: Add custom ESLint rules that flag the specific patterns the agent produces.

javascript
// .eslintrc.js
module.exports = {
  rules: {
    'no-empty': 'error', // Flags empty catch blocks
    'no-unused-vars': 'error', // Flags incomplete refactors
    'security/detect-possible-timing-attacks': 'error',
  },
};

Lint rules catch the "good enough" patterns that pass tests but fail in production.

Mitigation 5: Require Tests for Generated Code

Problem: "Almost right" solutions Solution: Make test coverage a requirement for accepting AI-generated code. The agent must produce tests that pass before the code is merged.

bash
# CI pipeline
test:
  stage: test
  script:
    - npm run test -- --coverage
    - npx jest --coverageThreshold='{"global":{"branches":80,"functions":80,"lines":80,"statements":80}}'

This forces the agent to think about edge cases, because the tests will fail if it doesn't.

Mitigation 6: Use a Human-in-the-Loop Review Process

Problem: All of the above Solution: Never let AI-generated code go to production without human review. The human reviewer should focus on the specific failure patterns, not on the overall quality.

markdown
## AI Code Review Checklist
- [ ] Does the code handle null/undefined values?
- [ ] Does the code use the correct API for the project's library versions?
- [ ] Does the code handle errors, or does it silently swallow them?
- [ ] Does the code follow the project's naming and structure conventions?
- [ ] Does the code introduce any security vulnerabilities?

This is the most important mitigation because it catches the patterns that automated tools miss.

Mitigation 7: Provide Project-Specific Context

Problem: Training data gap Solution: Give the agent a project-specific prompt that describes your conventions, architecture, and constraints.

markdown
# Project Context
- Language: TypeScript (strict mode)
- Framework: Next.js 14 (App Router)
- Database: PostgreSQL with Prisma
- Error handling: Use a custom AppError class
- Naming: camelCase for variables, PascalCase for components
- No magic numbers: Use constants from src/constants.ts

This helps the agent understand your codebase's unique characteristics and reduces the chance that it will revert to generic patterns.

8. The Verdict: Treat Agents as Junior Devs with a PhD in Theory

The most useful mental model for working with AI coding agents is to treat them as junior developers with exceptional theoretical knowledge but limited practical experience.

  • They know the theory. They can explain complex algorithms, design patterns, and architectural principles at a level that would impress a principal engineer.
  • They lack the context. They don't know your codebase, your conventions, your history, or your constraints.
  • They don't verify. They don't run tests, check for edge cases, or validate their work.
  • They optimize for likelihood, not correctness. They produce the most common solution, not the best solution.

This mental model changes how you use them:

  • Don't ask them to do everything. Give them well-scoped, isolated tasks.
  • Don't trust them to verify their work. Add verification loops, tests, and linting.
  • Don't expect them to know your codebase. Provide project-specific context.
  • Don't skip code review. Treat their output as a first draft, not a final product.

The future of AI coding agents is bright. They're getting smarter, more context-aware, and more reliable. But the fundamental architectural limitations—context fragmentation, training data bias, statelessness, and likelihood optimization—will persist for the foreseeable future.

Your job as an engineer is to understand these limitations and build systems that work with the agent, not against it. The agents aren't failing at the basics because they're dumb. They're failing because we're asking them to be something they're not: omniscient, infallible, and self-verifying.

Treat them as what they are—powerful, flawed, and irreplaceable tools—and you'll get far more value from them than you ever thought possible.

Frequently Asked Questions

Q: Why do AI coding agents fail at simple tasks but succeed at complex ones?

A: This is the context fragmentation problem. Complex tasks are often well-specified in the prompt, so the agent has all the information it needs. Simple tasks often require knowledge of the broader codebase—conventions, types, existing functions—that isn't in the prompt. The agent fails not because the task is hard, but because it lacks the context to solve it correctly.

Q: Are these failure patterns inherent to all AI coding agents, or just some?

A: The patterns are inherent to the transformer architecture and the training process. All LLM-based agents share the same fundamental limitations: context fragmentation, training data bias, statelessness, and likelihood optimization. However, the severity varies. Agents with better context management, test-run loops, and retrieval systems can mitigate some of these issues, but they can't eliminate them.

Q: What's the single most effective way to reduce AI coding agent failures?

A: The most effective mitigation is adding a verification loop—forcing the agent to run tests before it's done. This creates a feedback loop that catches errors the agent would otherwise miss. The second most effective is using a strongly typed language like TypeScript, which catches many failure patterns at compile time. Combined, these two mitigations can eliminate the majority of AI-generated bugs.


For more technical insights on software engineering, AI tooling, and developer workflows, explore Tamiz's Insights or the main blog.

The Anatomy of an AI Bug: Seven Failure Patterns You'll Meet in Production

When we dissect AI-generated failures in real codebases, a clear taxonomy emerges. These aren't random defects—they cluster around specific cognitive blind spots in the underlying models. Here are the seven most common failure modes I've catalogued from hundreds of code reviews and incident post-mortems.

1. The Off-by-One Cascade

Boundary conditions are the Achilles' heel of every language model. They understand the concept of a loop, but they struggle with the exact semantics of inclusive vs. exclusive ranges, zero-based vs. one-based indexing, and the precise edge cases of empty collections.

Consider this AI-generated function that was supposed to return the sum of all even numbers in a list:

python
# AI-generated: "Return the sum of all even numbers in a list"
def sum_evens(numbers):
    total = 0
    for i in range(1, len(numbers)):  # BUG: skips index 0
        if numbers[i] % 2 == 0:
            total += numbers[i]
    return total

# Test:
print(sum_evens([2, 3, 4, 5, 6]))  # Returns 10, but should be 12

The AI correctly identified the modulo check but started the loop at index 1 instead of 0. This is a classic off-by-one that slips through because the logic looks right—the variable names are correct, the condition is syntactically valid, and the intent is clear. But the first element is silently dropped.

The fix is trivial:

python
def sum_evens_fixed(numbers):
    total = 0
    for i in range(len(numbers)):  # Start at 0
        if numbers[i] % 2 == 0:
            total += numbers[i]
    return total

print(sum_evens_fixed([2, 3, 4, 5, 6]))  # 12 ✓

Why does this happen? Language models are trained on vast corpora of code where range(1, n) is a common idiom for "skip the first element." When the prompt doesn't explicitly specify the starting index, the model defaults to the most statistically probable pattern—which is often wrong for the given context.

2. The Null/Undefined Confusion

AI models frequently conflate null, None, undefined, and 0. They know these are "falsy" values, but they don't always understand the semantic differences between "not set" and "set to zero."

Here's a real-world example from a JavaScript codebase:

javascript
// AI-generated: "Get the user's display name, falling back to 'Guest'"
function getDisplayName(user) {
    return user.name || 'Guest';  // BUG: empty string '' returns 'Guest'
}

// Test:
console.log(getDisplayName({ name: 'Alice' }));   // 'Alice' ✓
console.log(getDisplayName({ name: '' }));        // 'Guest' ✗ (should be '')
console.log(getDisplayName({ name: null }));      // 'Guest' ✓
console.log(getDisplayName({}));                  // 'Guest' ✓

The || operator treats empty strings, 0, false, NaN, and null as falsy. If the user's name is an empty string—which is a valid value in many systems—the fallback incorrectly kicks in.

The correct implementation distinguishes between "missing" and "empty":

javascript
function getDisplayNameFixed(user) {
    return user.name !== null && user.name !== undefined 
        ? user.name 
        : 'Guest';
}

This failure mode is particularly insidious because it passes most tests. Developers typically test with valid names and null, but rarely test with empty strings or 0. The AI exploits the same blind spot.

3. The Async/Await Sequencing Trap

When AI models generate asynchronous code, they often serialize operations that could run in parallel. The code is correct in the sense that it produces the right output, but it's inefficient—and in some cases, the serialization introduces subtle timing bugs.

javascript
// AI-generated: "Fetch user data and then fetch their posts"
async function getUserWithPosts(userId) {
    const user = await fetchUser(userId);
    const posts = await fetchPosts(userId);  // BUG: sequential, not parallel
    return { user, posts };
}

// The fix:
async function getUserWithPostsFixed(userId) {
    const [user, posts] = await Promise.all([
        fetchUser(userId),
        fetchPosts(userId)
    ]);
    return { user, posts };
}

The buggy version adds unnecessary latency. But the more dangerous variant is when the AI assumes a dependency that doesn't exist:

javascript
// AI-generated: "Fetch a user's profile and their recent orders"
async function getProfileAndOrders(userId) {
    const user = await fetchUser(userId);
    // BUG: This doesn't need to wait for `user` to resolve
    const orders = await fetchOrders(userId);  
    return { user, orders };
}

In this case, fetchOrders doesn't depend on fetchUser's result, but the AI serialized them anyway. This isn't just a performance issue—if fetchUser fails, fetchOrders never runs, even though it could have succeeded independently.

4. The Type Coercion Trap

Dynamic languages like JavaScript and Python give AI models too much freedom. They often rely on implicit type coercion, which leads to bugs that only surface with specific input types.

javascript
// AI-generated: "Add two numbers"
function add(a, b) {
    return a + b;  // BUG: if a='5' and b=3, returns '53' not 8
}

// Test:
console.log(add(5, 3));      // 8 ✓
console.log(add('5', 3));    // '53' ✗ (string concatenation)
console.log(add(5, '3'));    // '53' ✗
console.log(add('5', '3'));  // '53' ✗

The AI sees + and assumes numeric addition. But in JavaScript, + is overloaded—it does concatenation when either operand is a string. The model doesn't account for the possibility that inputs might arrive as strings from form fields, URL parameters, or API responses.

The fix requires explicit type coercion:

javascript
function addFixed(a, b) {
    return Number(a) + Number(b);
}

This failure mode is particularly dangerous in production because the bug is intermittent—it only manifests when the input types are unexpected. The code passes all unit tests that use numbers, then fails when a string slips through from an untrusted source.

5. The Mutation Blind Spot

AI models often forget that objects and arrays are mutable references, not values. They generate code that accidentally mutates shared state, leading to bugs that are incredibly hard to trace.

javascript
// AI-generated: "Create a copy of an array with an extra element"
function appendElement(arr, element) {
    const newArr = arr;  // BUG: this is a reference, not a copy
    newArr.push(element);
    return newArr;
}

const original = [1, 2, 3];
const result = appendElement(original, 4);

console.log(result);    // [1, 2, 3, 4]
console.log(original);  // [1, 2, 3, 4] ✗ (original was mutated!)

The AI correctly creates a "new" array variable, but it assigns a reference instead of a copy. The push operation mutates the original array. This is a classic bug that causes mysterious side effects across the codebase.

The fix:

javascript
function appendElementFixed(arr, element) {
    return [...arr, element];
}

This failure mode is especially common when AI models work with nested data structures. They understand that const prevents reassignment, but they don't always understand that it doesn't prevent mutation.

6. The Error Handling Gap

AI models generate code that assumes success. They skip try/catch blocks or handle errors inconsistently—often swallowing exceptions silently or returning default values that mask real failures.

python
# AI-generated: "Read a config file and parse JSON"
def load_config(path):
    with open(path) as f:
        return json.load(f)  # BUG: no error handling

# Test:
print(load_config('missing.json'))  # FileNotFoundError: unhandled!

The AI knows that open and json.load are the right functions, but it doesn't consider what happens when the file doesn't exist or contains invalid JSON. The code crashes in production.

The correct version handles both failure modes:

python
def load_config_fixed(path):
    try:
        with open(path) as f:
            return json.load(f)
    except FileNotFoundError:
        return {}  # Default config
    except json.JSONDecodeError:
        return {}  # Invalid JSON, use default

But there's a subtler variant that's even more dangerous:

python
# AI-generated: "Read a config file and parse JSON"
def load_config(path):
    try:
        with open(path) as f:
            return json.load(f)
    except Exception:
        return {}  # BUG: swallows ALL exceptions, including programming errors

This version catches every exception, including TypeError, ValueError, and KeyError—which might indicate bugs in the code itself, not just missing files. The AI can't distinguish between "expected" errors (file not found) and "unexpected" errors (logic bugs), so it treats them all the same.

7. The Regex Overreach

AI models are particularly bad at regular expressions. They generate patterns that are either too broad (matching invalid input) or too narrow (rejecting valid input). The failure is subtle because the regex looks correct at first glance.

python
# AI-generated: "Validate an email address"
import re

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

# Test:
print(is_valid_email('user@example.com'))       # True ✓
print(is_valid_email('user.name+tag@sub.domain.co'))  # True ✓
print(is_valid_email('user@localhost'))          # False ✓ (no TLD)
print(is_valid_email('user@.com'))               # False ✓

This pattern is actually decent. But AI models often generate much worse patterns:

python
# AI-generated: "Validate an email address"
def is_valid_email_buggy(email):
    pattern = r'^[a-zA-Z0-9]+@[a-zA-Z]+$'  # BUG: too narrow
    return bool(re.match(pattern, email))

# Test:
print(is_valid_email_buggy('user@example.com'))       # True ✓
print(is_valid_email_buggy('user.name@example.com'))  # False ✗ (rejects valid!)
print(is_valid_email_buggy('user+tag@example.com'))   # False ✗ (rejects valid!)

The AI generated a pattern that only accepts simple alphanumeric usernames and domain names. It rejects valid emails with dots, plus signs, or hyphens. This is a "false negative" bug—valid input is rejected.

The opposite is also common:

python
# AI-generated: "Validate an email address"
def is_valid_email_too_broad(email):
    pattern = r'^.+@.+$'  # BUG: too broad
    return bool(re.match(pattern, email))

# Test:
print(is_valid_email_too_broad('user@example.com'))  # True ✓
print(is_valid_email_too_broad('not