Reviewing AI-written code: a risk-based checklist and automated checks
AI-written PRs are long, confident and plausible. How to let machines catch what machines can (compiling, tests, ArchUnit, mutation testing, dependency scans) and keep humans on invariants, permissions, migrations and failure behaviour; with a checklist by risk level.
On this page
1. The problem
An agent opens a 1,400-line PR, "refactor the refund service, no behaviour change", 212 tests green, approved after 9 minutes. The next week 37 orders are refunded but still "paid": @Transactional moved onto an internally called method.
2. Key idea
AI-written code fails in ways that look right: clean syntax, green tests, bugs in invariants, access checks and failure behaviour. Machines take the repetitive part, people the part that can't be undone.
| Common AI mistake | Example | Who catches it |
|---|---|---|
| Invented API or library | a method that doesn't exist; a package named like a real one | compiler; dependency review |
| Tests that re-check the implementation | assert exactly what the mock returns | mutation testing |
| Behaviour change inside a "refactor" | lost transaction, reordered validation | characterization tests; people |
| Missing access check | load an order by id without checking the owner | mostly people |
| Architecture drift | controller calls a repository directly | ArchUnit |
| Dangerous migration | rename a column in one step during a rolling deploy | migration lint; people |
2.1 Where do you read carefully?
High-risk areas: money, auth and access, personal data, migrations, concurrency, public APIs.
| Review style | Use when | Don't use when |
|---|---|---|
| Skim, rely on the machine gate | tests, docs, local refactors with characterization tests | the PR touches a high-risk area |
| Read every line | files in a high-risk area | all 1,400 lines: you tire and miss things |
| Ask to split the PR | mechanical renames mixed with logic | renames generated by the IDE |
A characterization test records current behaviour and is merged on its own before the refactor: the evidence for "no behaviour change".
3. In Java
Conventions become CI tests: the agent reads the failure and fixes it.
@AnalyzeClasses(packages = "com.shop")
class ArchitectureTest {
@ArchTest
static final ArchRule web_does_not_use_repositories =
noClasses().that().resideInAPackage("..web..")
.should().dependOnClassesThat().resideInAPackage("..repository..");
@ArchTest // blocks the most common self-invocation shape
static final ArchRule transactional_only_on_public_service_methods =
methods().that().areAnnotatedWith(Transactional.class)
.should().bePublic()
.andShould().beDeclaredInClassesThat().resideInAPackage("..service..");
}
// mvn verify -> a violation fails the build, naming the class and methodThe CI machine gate and mutation testing
| Gate | Catches | Example tools |
|---|---|---|
| Compile, tests | invented methods, behaviour already under test | mvn verify |
| Architecture rules | layer drift, misplaced @Transactional |
ArchUnit |
| Static analysis | swallowed errors, nulls | Error Prone, SpotBugs, Sonar |
| Mutation tests on the diff | tests that don't catch bugs | PIT, limited to changed packages |
| Dependency and secret scans | vulnerable libraries, keys in code | Dependabot, gitleaks |
| Migration lint | long table locks, incompatible changes | squawk (PostgreSQL) |
Mutation testing makes small edits to the code (turn > into >=, drop a call) and reruns the tests. If they stay green, they don't check that behaviour. For AI-written tests, the surviving-mutant rate is more honest than line coverage.
4. Working with AI
Hand to AI: the first review pass (a diff summary by risk area), characterization tests before a refactor.
Check in AI-written code:
- A "no behaviour change" PR has characterization tests merged first.
- Every data access checks permission against the caller, not an id the client sent.
- Transactions, locks and idempotency survive extracting or merging methods.
- Migrations are compatible with the running version and have a rollback path.
Here is the diff of a PR described as "refactor, no behaviour change".
1. List every change that could alter behaviour: transactions, validation order, error handling, defaults, queries.
2. For each item, write a test that would fail if behaviour changed.
Do not change code. Do not conclude "safe" without a test for step 2.5. Exercises
Exercise 1: Review a "no behaviour change" refactor
The old version had @Transactional on public void refund(long orderId). The AI extracted a method as below and wrote "just split for readability". Find the bug, name a test that proves it, fix it.
public void refund(long orderId) {
Order order = orders.findById(orderId).orElseThrow();
validate(order);
applyRefund(order);
}
@Transactional
void applyRefund(Order order) {
payments.reverse(order.paymentId());
order.markRefunded();
orders.save(order);
}Solution to Exercise 1
refundcallsapplyRefundthroughthis, not through Spring's proxy, so@Transactionaldoes nothing (self-invocation). A failure insaveafterreverseleaves the money refunded while the order still says "paid".- Test: an integration test where
orders.savethrows, asserting earlier changes roll back; or assertTransactionSynchronizationManager.isActualTransactionActive()insideapplyRefund. - Fix: put
@Transactionalback on the publicrefund. The ArchUnit rule in section 3 flags it immediately. - Also: calling the payment gateway inside a DB transaction holds a connection while waiting on the network; refunds need an idempotency key so a retry doesn't refund twice.
Exercise 2: Read an incident after a deploy
A rolling deploy starts. For the first 4 minutes 50% of requests fail with 500 and column "phone" does not exist, only on old-version pods. The PR's migration: ALTER TABLE customer RENAME COLUMN phone TO phone_number;. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the migration isn't backward compatible. It runs when the first new pod starts, while old pods still read
phone. - 15 minutes: rolling back the app doesn't help because the column is already renamed. Let the deploy finish, or add
phoneback with a compensating migration if you must return to the old version. - Root fix: expand and contract across several deploys: add the new column, write both, backfill, switch reads, and only then drop the old column. Add a migration lint that blocks
RENAME COLUMNandDROP COLUMNwithout an approval label.
Summary
- Machines catch the repetitive part; people read money, access, migrations and concurrency line by line.
- Characterization tests are merged before any "no behaviour change" refactor.
- Mutation testing shows whether AI-written tests catch bugs.
- Self-invocation drops
@Transactional; migrations must work with the running version.
Comments
Community rules