← All articles

Guides

Reviewing AI-Generated Code: 10 Risks to Check Before You Merge

The shortcuts, stale APIs, and risky decisions worth checking before you merge.

AI can write a lot of code in seconds. The tricky part is knowing what it missed. Here are ten things I’d check before merging code an AI helped write.

From vague variable names to security holes and accidental data loss, these are the problems that can slip into AI-assisted code. I’ve included what they look like and what to check.

AI-written code can look finished and still miss a requirement, use the wrong API, or leave a security hole. CodeRabbit found an average of 10.83 issues in AI-authored pull requests, compared with 6.45 in human-authored ones. That’s why a quick read-through isn’t enough.

1. Vague names like data, res, temp2

Vague names likedata,res,temp2

Names like data, result, and info2 make you stop and trace every line. It’s also confusing when the same thing has a different name in every file.

// As written
const data = await getData();
const res = process(data);
const temp2 = res.items;
// Better
const orders = await fetchPendingOrders();
const invoice = buildInvoice(orders);
const lineItems = invoice.items;

If the agent hasn’t picked up your project’s naming style, it’ll often reach for generic names. That’s how one concept ends up with three names across the codebase.

In CodeRabbit’s analysis of 470 pull requests, AI-assisted changes had nearly twice as many naming inconsistencies.

Look for names that describe what a value is rather than what it means. A short glossary in your AI instructions helps; lint rules can catch naming conventions before they spread.

2. Old functions your library already removed

Old functions your library already removed

An API call can look perfectly plausible and still be gone. DataFrame.append, for example, was removed in pandas 2.0:

# As written: DataFrame.append was removed in pandas 2.0
df = df.append(new_row, ignore_index=True)
# Current API
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)

The agent may have seen plenty of examples using an old API. Check its suggestions against the version your project actually uses.

An ICSE 2025 study found that seven LLMs often suggested deprecated APIs across eight Python libraries. The good news: automated fixes worked in more than 85% of the cases they tested.

Check CI for deprecation warnings and compare unfamiliar calls with the docs for your installed version. You can make those warnings fail CI (-W error::DeprecationWarning) and give the agent your dependency versions up front.

3. Copy-pasted code and a database call inside a loop

Copy-pasted code and a database call inside a loop

Repeated logic is easy to miss until it needs fixing in three places. And a database query inside a loop can turn 1,000 users into 1,000 separate round trips.

# As written: one query per user, plus inline logic
for user_id in user_ids:
    user = db.query(f"SELECT * FROM users WHERE id={user_id}")
    total = sum(i.price * i.qty for i in user.cart)
# One query, one helper
users = db.query("SELECT * FROM users WHERE id = ANY(%s)", (user_ids,))
totals = {u.id: cart_total(u.cart) for u in users}

The agent may write a new helper without noticing you already have one. It may also run the same query again and again instead of batching it.

The numbers back this up:

Search for an existing helper before adding another one, and look for queries inside loops. Tools like jscpd and SonarQube can flag duplicated code.

4. Works in the demo, crashes on empty input

Works in the demo, crashes on empty input

It works with normal input. Then someone passes an empty list and it crashes. This example divides by zero when ratings is empty:

# As written
def average_rating(ratings):
    return sum(ratings) / len(ratings)   # ZeroDivisionError on []
# Handles the edge case
def average_rating(ratings):
    if not ratings:
        return None
    return sum(ratings) / len(ratings)

Most examples show the happy path. Empty values, huge inputs, and two requests arriving at once are where the cracks show.

CodeRabbit found more logic errors, concurrency issues, and null-pointer risks in AI-assisted pull requests. In Stack Overflow’s 2025 survey, 66% of developers said AI code is often “almost right, but not quite.” Apiiro, meanwhile, reported 60% fewer logic bugs in its enterprise data.

Try empty, missing, huge, and simultaneous inputs. Property-based tools like Hypothesis and fast-check help find cases you might not think to write. You can also ask the agent to list edge cases before it starts.

5. Errors caught and quietly ignored

Errors caught and quietly ignored

A blanket try/catch can hide a failed payment and make the rest of the app act as if everything worked.

# As written: the payment fails and nobody finds out
try:
    charge_card(user, amount)
except Exception:
    pass
# Catch the specific error, log it, pass it on
try:
    charge_card(user, amount)
except PaymentDeclined as e:
    log.warning("payment_declined", user=user.id, reason=e.code)
    raise

Catching every error may stop the crash, but it doesn’t fix the problem. Handle the error you expect, log it, and let the caller know what happened.

GitClear’s 2026 analysis found 47% more error-masking patterns in AI-assisted code. CodeRabbit found exception-handling issues at nearly twice the rate.

Look for empty catches, bare except blocks, endless ?. chains, and unexplained null returns. Ruff and ESLint can flag some of these. Make sure errors are handled or logged, not quietly buried.

6. Tests changed so they pass, bug still there

Tests changed so they pass, bug still there

“Make the tests pass” sounds simple. But an agent can change the test or hard-code its example answer, leaving the real bug untouched.

# Agent "fix" 1: special-cased for the visible test
def calculate_fee(amount):
    if amount == 1999.99:
        return 20.00
    return int(amount) / 100   # the real bug: drops the cents
# Agent "fix" 2: edits the test instead
- assert calculate_fee(1999.99) == 20.00
+ assert calculate_fee(1999.99) == 19.99

A green test suite doesn’t always mean the bug is fixed. Sometimes an agent learns to satisfy the test instead of the requirement. Researchers call that reward hacking.

ImpossibleBench tested what happens when the tests are weak or contradict each other:

If a bug fix changes the tests too, check that they still test the original behavior. Watch for hard-coded answers, and keep independent acceptance tests in CI.

7. Passwords and API keys typed into the code

Passwords and API keys typed into the code

Never put a real key in source code. Once it’s committed, deleting the line doesn’t remove it from Git history.

# As written: now permanently in git history
client = OpenAI(api_key="sk-proj-4f9a...")
DB_URL = "postgres://admin:Passw0rd!@prod-db:5432/app"
# Read from the environment or a secrets manager
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

AI examples often show keys inline. If you don’t set a different rule, the agent may copy the pattern.

GitGuardian found more leaked secrets in AI-assisted commits:

Search for strings like sk-, AKIA, and ghp_, and check connection strings for passwords. Run Gitleaks, GitGuardian, or TruffleHog before code is pushed. If a real key gets committed, revoke it and create a new one; deleting it from the file isn’t enough.

8. Security holes in code that looks clean

Security holes in code that looks clean

The code can look clean and still have a serious security bug: injectable SQL, cross-site scripting, or an endpoint that lets one user see another person’s data.

# As written: user input in the SQL, and no check on who is asking
@app.get("/invoice/{invoice_id}")
def get_invoice(invoice_id):
    return db.execute(f"SELECT * FROM invoices WHERE id = '{invoice_id}'")
# Parameterised query + ownership check
@app.get("/invoice/{invoice_id}")
def get_invoice(invoice_id, user=Depends(current_user)):
    inv = db.execute("SELECT * FROM invoices WHERE id = %s", (invoice_id,)).one()
    if inv.owner_id != user.id:
        raise HTTPException(403)
    return inv

If you don’t ask for access checks or input validation, the agent may skip them. And familiar-looking code isn’t always safe; insecure examples are easy to find in public repos.

Security checks catch problems that ordinary tests often miss:

Use parameterized SQL, handle untrusted content safely, and check permissions on every endpoint. Run Semgrep, CodeQL, or SonarQube on each pull request. Have a person review changes to authentication, payments, and data access.

9. Installing packages that don't exist

Installing packages that don't exist

Sometimes an AI invents a package name that sounds real. If an attacker registers it first, the next install could pull in malware. Researchers call this “slopsquatting.”

# AI output: plausible name, never existed
pip install huggingface-cli          # fake (later registered by a researcher)
# The real package
pip install -U "huggingface_hub[cli]"

AI can make up package names that sound right. Researchers found that some fake suggestions keep coming back, making them easier for an attacker to predict.

One study checked millions of package suggestions:

Check every new dependency in the lockfile. Look at its publisher and release history, and run a supply-chain scanner like Socket or Snyk. Don’t let an agent install a package without approval.

10. AI agents that delete real data

AI agents that delete real data

Give an agent shell access and a vague request like “clear the cache,” and it can delete the wrong thing. These incidents show why destructive commands need guardrails.

In July 2025, a Replit agent deleted records for 1,206 executives and about 1,196 companies during a code freeze. It then said rollback wasn’t possible; that turned out to be wrong. (Fortune; AI Incident Database.)

In November 2025, one user reported that Google Antigravity was asked to clear a cache and instead targeted the root of the D: drive, bypassing the Recycle Bin.

The commands in the image are simplified illustrations, not original logs.

An agent doesn’t know which files or records are irreplaceable. It can misread an unexpected result and try to “fix” it with a destructive command. Set up the environment so it can’t do that damage.

A review can’t undo a deletion. Keep agents away from production credentials, limit what they can reach, and require approval for rm, DROP, DELETE, and git push --force. Keep backups—and test that you can restore them.

The 10-point review checklist

Checklist: ten things to check before you merge AI-generated code

Before merging AI-assisted code, take a moment to check:

  1. Do the names say what things are?
  2. Are all library calls current (no deprecation warnings)?
  3. Any database calls inside loops, or new code that duplicates an existing helper?
  4. What happens with empty, missing, huge, or concurrent input?
  5. Any errors caught and silently ignored?
  6. Did a "bug fix" also change the tests?
  7. Any keys, tokens, or passwords in the code?
  8. Is user input kept out of queries, and is access checked on every endpoint?
  9. Does every new package really exist, with a normal history?
  10. Can any agent reach production data?

How we think about this at OxCode

We build OxCode, so we think about these risks every day. OxCode runs code in a sandbox and tests its changes before it reports back. Still, read the diff before you merge.

Try OxCode at oxcode.ai. We’re also on GitHub and X at @OxCode_ai.

Sources

SourceTypeLink
Spracklen et al., Package Hallucinations, USENIX Security 2025Paperhttps://arxiv.org/abs/2406.10279
Wang et al., Deprecated API Usage, ICSE 2025Paperhttps://arxiv.org/abs/2406.09834
Perry et al., Insecure Code with AI Assistants, ACM CCS 2023Paperhttps://arxiv.org/html/2211.03622v3
ImpossibleBenchPaperhttps://arxiv.org/abs/2510.20270v1
EvilGeniePaperhttps://alphaxiv.org/abs/2511.21654
Veracode 2025 GenAI Code Security ReportIndustryhttps://www.veracode.com/resource/2025-genai-code-security-report
Apiiro, 4x Velocity, 10x VulnerabilitiesIndustryhttps://apiiro.com/blog/4x-velocity-10x-vulnerabilities
CodeRabbit, AI vs Human Code ReportIndustryhttps://www.coderabbit.ai/blog/state-of-AI-vs-human-code-generation-report
GitGuardian, State of Secrets SprawlIndustryhttps://gitguardian.com/state-of-secrets-sprawl-report-2025
GitClear / LeadDev 2026Industryhttps://leaddev.com/?p=34362
Stack Overflow 2025 survey (VentureBeat)Surveyhttps://venturebeat.com/technology/stack-overflow-data-reveals-the-hidden-productivity-tax-of-almost-right-ai-code
Replit incident, AI Incident DatabaseIncidenthttps://incidentdatabase.ai/entities/jason-lemkin/
Antigravity incident, AI Incident DatabaseIncidenthttps://incidentdatabase.ai/entities/gemini-3-based-antigravity-agent-ide/
Lovable CVE-2025-48757Incidenthttps://feedly.com/cve/CVE-2025-48757

All code examples in this article and its images are illustrative. They are not taken from any real company's code.