03 — Code Review & Auditing AI-Generated Code

At a glance

After completing this lesson you can:

Time: ~50 minutes · Prerequisites: 02 — Clean & Hexagonal Architecture

Reading Companion

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

  1. Unbounded Buffering: Reading entire files/tables into RAM (file.read(), SELECT *) causing OOM.
  2. Missing Atomic Idempotency: Executing payments or sending emails without idempotency keys.
  3. Leaky Exception Swallowing: except Exception: pass concealing data corruption.
  4. Race Conditions / Missing Locks: Read-modify-write without database SELECT ... FOR UPDATE.
  5. Accidental $O(n^2)$ Operations: Using list.insert(0), nested linear scans, or repeated string concatenations.
  6. 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

  1. Rung 1 (audit_security_traps): Scan Python source code strings for dangerous patterns: shell=True, eval(, and bare except:.
  2. 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.
  3. Rung 3 (linter_rule_unbounded_read): Implement a static AST visitor checking that file.read() or cursor.fetchall() includes size limits or is replaced with streaming iterators.
  4. 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.
  5. Rung 5 (automated_pr_quality_gate): Build a pipeline gate combining static AST checks, complexity heuristics, and test coverage thresholds returning approval (APPROVE or CHANGES_REQUESTED).

Wrapping up

Can you explain?

  1. What is a TOCTOU (Time-of-Check to Time-of-Use) race condition?
  2. Why is "LGTM" without reading tests considered dangerous engineering practice?
  3. What is the difference between subjective style nitpicks and blocking correctness concerns in code review?

Further Reading & References

Show reference solution notes

Solution & Engineering Notes — 03 Code Review & AI Auditing

  1. AST Parsing over Regex: Regex parsing of code breaks on strings, comments, and whitespace variations. Python's ast module inspects the real syntactic structure cleanly.
  2. 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.

Confidence:

Completion edits PROGRESS.md; commit it with the lesson.