03 — Code Review & Auditing AI-Generated Code
At a glance
After completing this lesson you can:
- Systematically conduct engineering code reviews focusing on correctness, race conditions, and boundary security.
- Identify the 6 most common defects introduced by AI coding assistants (silent $O(n^2)$ loops, missing transaction rollback, unhandled async exceptions, SQL/command injection, unbounded memory growth, and brittle mocking).
- Write actionable, empathetic, and unambiguous code review comments for teammates and PR authors.
Time: ~50 minutes · Prerequisites: 02 — Clean & Hexagonal Architecture
Reading Companion
- Book: Software Engineering at Google — Titus Winters, Tom Manshreck, Hyrum Wright
- Chapter 9: Code Review (Why review, Respectful critiques, Standard of review).
- Chapter 19: Engineering for Reliability.
Why this matters in production
AI tools can generate 1,000 lines of functional-looking code in 10 seconds. However, AI code frequently overlooks distributed failure modes: it forgets retry limits, leaves database locks dangling, catches exceptions blindly with except: pass, and assumes the network is 100% reliable. The ultimate superpower of a mid-to-senior backend engineer in 2026 is critical auditing: reading code ruthlessly to prevent subtle security, concurrency, and performance bugs from reaching production.
Deep dive
The 6 Classic AI Anti-Patterns Checklist
- Unbounded Buffering: Reading entire files/tables into RAM (
file.read(),SELECT *) causing OOM. - Missing Atomic Idempotency: Executing payments or sending emails without idempotency keys.
- Leaky Exception Swallowing:
except Exception: passconcealing data corruption. - Race Conditions / Missing Locks: Read-modify-write without database
SELECT ... FOR UPDATE. - Accidental $O(n^2)$ Operations: Using
list.insert(0), nested linear scans, or repeated string concatenations. - False-Confidence Tests: Over-mocking internal methods such that the test passes while the code is completely broken.
Hands on
python3 phase1-cs-and-architecture/03-software-architecture/03-code-review-and-ai-auditing/examples/01_demo.py
python3 phase1-cs-and-architecture/03-software-architecture/03-code-review-and-ai-auditing/examples/02_trap.py
AI Trap & Code Review
# BAD AI-GENERATED CODE — CLASSIC TOCTOU RACE CONDITION
def withdraw_funds(user_id: int, amount: int, db):
user = db.query("SELECT balance FROM users WHERE id = %s", user_id)
if user.balance >= amount:
# Time-Of-Check to Time-Of-Use (TOCTOU) bug!
# Concurrent request can withdraw at the same microsecond!
db.execute("UPDATE users SET balance = balance - %s WHERE id = %s", amount, user_id)
Exercises
- Rung 1 (
audit_security_traps): Scan Python source code strings for dangerous patterns:shell=True,eval(, and bareexcept:. - Rung 2 (
audit_and_fix_race_condition— Fix the AI Bug): Fix a balance decrement function vulnerable to lost updates by wrapping in atomic conditional SQL / transactional locks. - Rung 3 (
linter_rule_unbounded_read): Implement a static AST visitor checking thatfile.read()orcursor.fetchall()includes size limits or is replaced with streaming iterators. - Rung 4 (
construct_review_feedback): Given a list of detected PR defects, format structured, non-judgmental Markdown review comments citing file, line number, impact, and proposed fix. - Rung 5 (
automated_pr_quality_gate): Build a pipeline gate combining static AST checks, complexity heuristics, and test coverage thresholds returning approval (APPROVEorCHANGES_REQUESTED).
Wrapping up
Can you explain?
- What is a TOCTOU (Time-of-Check to Time-of-Use) race condition?
- Why is "LGTM" without reading tests considered dangerous engineering practice?
- What is the difference between subjective style nitpicks and blocking correctness concerns in code review?
Further Reading & References
- Martin Fowler: Microservices and the Bounded Context
- Cosmic Python (Architecture Patterns with Python)
- Google Engineering Practices: Code Review Developer Guide
- Alistair Cockburn: Hexagonal Architecture (Ports and Adapters)
Show reference solution notes
Solution & Engineering Notes — 03 Code Review & AI Auditing
- AST Parsing over Regex: Regex parsing of code breaks on strings, comments, and whitespace variations. Python's
astmodule inspects the real syntactic structure cleanly. - Constructive Review Framework: Good review comments follow: Observation (what happened) $\rightarrow$ Impact (why it matters in production) $\rightarrow$ Suggestion (concrete code fix).
Self-check
Run python3 -m unittest phase1-cs-and-architecture/03-software-architecture/03-code-review-and-ai-auditing/test_exercises.py -v until green, then record it here. Saved to progress/rungs.json; commit it.
Completion edits PROGRESS.md; commit it with the lesson.