Sub topic 5
Reading the diff line by line
This chapter assumes you can read a unified diff, run basic Git commands, and write unit tests. It also assumes you have used an AI coding assistant to produce a change. By now you have checked the change against the requirement and decided it is small enough to review. This chapter covers the next step: reading what the assistant actually changed.
Why the diff is the unit of review
An assistant's chat summary describes what it intended to do. The diff shows what it did. These often differ. The summary may say "added input validation" while the diff also renames a helper, reformats a file, and removes a retry loop.
Review the diff, not the summary. Treat the summary as a list of claims, then check each claim against the lines.
Get the shape of the change first
Before reading any line, look at the size and spread of the change. Then read in a deliberate order.
git diff --stat
git diff
git add -pgit diff --statlists each changed file with the number of added and removed lines. Look for files you did not expect to see, such as lock files, CI configuration, or unrelated modules.git diffshows the full change. Read it from top to bottom at least once.git add -pwalks through each hunk (a contiguous block of changes) and asks whether to stage it. Staging hunk by hunk means you accept only what you have reviewed. Answernto a hunk you do not understand,sto split a large hunk, andeto edit one.
Untracked files do not appear in git diff. Run git status as well, so a new file the assistant created does not escape review.
Read the tests first
If the change touches tests, read those hunks before the code. Tests state what the assistant believes the behavior should be, and you can compare that belief with your requirement.
Watch for these patterns:
- A test was deleted, skipped, or loosened to make a failure go away.
- An assertion was changed to match new output, when the old assertion was the correct one.
- A new test only checks that the code runs, with no meaningful assertion.
- A mock replaces the very thing the test should exercise.
A passing test suite after the assistant edited the tests proves little. Passing tests are evidence only when the tests themselves are trustworthy.
Read each hunk with three questions
For every hunk, ask:
- What does this line do? Say it in your own words. If you cannot, you do not yet understand it, and you should not accept it.
- Why is it here? Match it to a part of the requirement. A line that serves no stated need is scope creep or a mistake.
- What does it assume? Look for assumptions about input type, size, ordering, encoding, time zone, concurrency, and whether a value can be empty or
None.
The third question catches the most bugs. Consider this function.
def average(values):
return sum(values) / len(values)It looks correct and reads cleanly. It assumes values is never empty. On an empty list, len(values) is 0 and Python raises ZeroDivisionError. The requirement never said what should happen, so the assistant silently picked a behavior: crash with an unrelated error.
Things that hide in a diff
Some problems do not look like problems when you skim. Scan for each of these deliberately.
| What to look for | Why it matters |
|---|---|
| Removed lines | Deleted checks, logging, error handling, or comments may be load-bearing. |
| Changed signatures | Callers elsewhere in the codebase may break, and the diff will not show them. |
| Broad `except` blocks | `except Exception: pass` hides real failures. |
| Changed defaults or constants | A timeout, limit, or flag value can alter behavior with no visible logic change. |
| Whitespace and reformatting | Noise can bury a real change. Use `git diff -w` to hide whitespace-only edits. |
| New imports | Each one is a new dependency to verify, covered in a later chapter. |
| Comments that describe other code | AI-written comments often explain intent that the code does not implement. |
| Duplicated logic | The assistant may rewrite a helper that already exists in your codebase. |
Removed lines deserve extra attention. Reviewers tend to read the green additions and skim the red deletions. An assistant that "simplifies" a function may delete a guard clause that handled a rare case.
Reading beyond the changed lines
A diff shows a few lines of context around each change. That is rarely enough. For any non-trivial hunk, open the whole file and read the surrounding function. Then check three things outside the diff:
- Callers. Search for every use of a function whose signature or return value changed. A new
Nonereturn can break a caller that never expected one. - Callees. If the new code calls an existing function, read that function. Do not trust the assistant's guess about what it returns or raises.
- Shared state. If the code mutates a global, a cache, or an argument, ask who else reads it.
You can widen the context in the diff itself.
git diff -U10 -- path/to/file.py
git grep -n "function_name"-U10 shows ten lines of context instead of three. git grep finds callers quickly.
Worked example: a plausible but flawed change
Suppose the requirement is "return a user's record by name." The assistant produces this.
import sqlite3
def find_user_unsafe(conn: sqlite3.Connection, name: str):
# Builds SQL by string formatting: vulnerable to injection.
query = f"SELECT id, name FROM users WHERE name = '{name}'"
return conn.execute(query).fetchall()Apply the three questions to the query line.
- What does it do? It inserts
namedirectly into the SQL text. - Why is it here? It satisfies the requirement, so the intent is fine.
- What does it assume? It assumes
namecontains no SQL syntax. That is false for untrusted input. Passing"' OR '1'='1"turns the query into one that matches every row.
The fix keeps the intent and removes the assumption.
import sqlite3
def find_user(conn: sqlite3.Connection, name: str):
# Parameterized query: the driver treats name as data, not SQL.
return conn.execute(
"SELECT id, name FROM users WHERE name = ?", (name,)
).fetchall()A later chapter covers security review in detail. The point here is that line-by-line reading found the flaw without running anything. The first function passes a happy-path test, so only careful reading, or a targeted test, exposes it.
Common reviewer mistakes
- Skimming because the code is tidy. AI output is consistently formatted and well named. Polish is not evidence of correctness.
- Reviewing only what is green. Read deletions and moved code too.
- Accepting a large hunk whole. If
git add -poffers a hunk you cannot explain, split it withsor skip it. - Trusting the explanation. The assistant may describe code accurately, or describe what it meant to write. Verify against the lines.
- Stopping at the first bug. One found defect does not mean the rest is clean. Defects in generated code often cluster.
When the diff is too hard to read
Sometimes you cannot form a clear picture. The hunks are large, the changes are tangled, or the code is clever in ways you cannot follow. Treat that as information about the change, not about you.
- Ask the assistant to split the work into smaller steps, each with its own diff.
- Ask for the simplest version that meets the requirement.
- Reject the change and restate the requirement more narrowly.
Code you cannot read is code you cannot maintain. Declining it is a valid outcome.
Summary
Read the diff, not the chat summary. Get the shape with --stat and git status, read the tests first, then review each hunk by asking what it does, why it is there, and what it assumes. Check removed lines, changed signatures, and callers outside the diff. Stage hunks with git add -p so that only reviewed code enters your commit.
Exercise
An assistant's change shows git diff --stat output with two files you expected and one you did not: package-lock.json, with 400 changed lines. The chat summary says nothing about dependencies. What should you do before staging anything, and why?
Show answer
Treat the lock file change as an unexplained part of the change. Inspect it with git diff -- package-lock.json, and look at package.json for new or upgraded dependencies. Each new or changed package must be checked as real, appropriate, and necessary. If the change is not tied to the requirement, revert that file (for example with git restore package-lock.json) or ask the assistant to explain it. Do not stage it with git add .. Use git add -p or stage files by name so only reviewed changes go in.
Exercise
This function was added to compute a page count. Name the assumption that makes it risky, and describe a test that would expose it. def pagecount(totalitems, pagesize): return totalitems // page_size
Show answer
The code assumes total_items is an exact multiple of page_size. Floor division drops the remainder, so 25 items with a page size of 10 gives 2 pages instead of 3. It also assumes page_size is never 0, which would raise ZeroDivisionError. A test should assert page_count(25, 10) == 3, and another should check the chosen behavior for page_size of 0, for example that it raises ValueError.
Exercise
While reading a diff, you find that an assistant deleted a test named test_average_of_empty_list_raises and the full suite now passes. Why is the passing suite not good evidence, and what do you do?
Show answer
The suite passes because the test that checked an edge case was removed, not because the behavior is correct. Passing tests count as evidence only if the tests are trustworthy. Restore the deleted test, run it, and see whether it fails. If it fails, the code has a real defect and needs a fix. If you believe the test was wrong, justify that against the requirement before accepting the deletion.