Code review interview: a rubric and 4 diffs
Published
By the Unrust team · 10 min read · Editorial method
Code review interview prep: a pass order, a comment format and 4 diffs we ran. A set rewrite passed its test on only 56 of 100 hash seeds.
What is a code review interview, and how do you prepare?
A code review interview usually gives you a diff to review, and you find the defects, rank them and explain each one; formats vary. To prepare, use a fixed pass order (tests, correctness, security, performance, readability), label every comment blocking or nit, and practice on diffs you have actually run.
Formats vary by company and role, so ask what a code review round will include, such as whether you can run the code. This post describes no company's round and promises no interview result.
The four diffs below are our own code review interview examples, in Python and JavaScript, and a five-point rubric at the end grades your comments on them. Each hides one defect that matters, and each defect shows up in a run: predict the output first, then compare it with the real one.
We ran every Python program in this post on eight CPython builds (3.9.25 to 3.15.2) and every JavaScript program on seven Node.js builds (18.20.4 to 24.11.0) on November 25, 2026. The output shown comes from CPython 3.11.2 and Node.js 24.11.0, and the text says where other builds differ.
What should you check first when reviewing a diff?
Check the tests first, because they show what the author believes the change does: would any test fail if the code were wrong? Then check correctness and edge cases, security, performance and readability, in that order. The order is our suggestion, not a standard.
Google's published review guide backs the first two passes. It asks whether the tests will actually fail when the code is broken, and it tells reviewers to keep thinking about edge cases and concurrency problems even though the author is expected to have tested the change.
The table maps each pass to the question it asks and to the diff in this post that hides a defect there. Diff 2 appears twice because a speed-up is a performance change and also a change in when the work finishes.
Pass Ask Defect hides in
------------- ----------------------------------------------------- ---------------
1 Tests Would any test fail if the code were wrong? Diff 1
2 Correctness Which input, failure or runtime version breaks it? Diffs 2 and 4
3 Security Can untrusted input reach a query, command or path? Diff 3
4 Performance What does a speed-up change about waiting and errors? Diff 2
5 Readability Could the next reader follow it in a minute? nits onlyHow do you word a review comment without sounding harsh?
Start the comment with a label, then give the evidence, the fix and a question. The label tells the author how much weight the comment carries, and the Conventional Comments convention says that prefixing a label makes the intention clear and changes the tone.
Use the same four parts each time: what happens, the input and output that show it, what to change, and one question about what you cannot see. If you are not sure a problem exists, consider making the comment a question, as Conventional Comments suggests.
In the table, blocking means the comment should stop the merge until it is resolved, and non-blocking means it should not. In our four diffs the main defect is always blocking, but a real diff mixes blocking issues with nits, so rank them before you speak.
Label Use it when Example
------------------------- ------------------------------------------ -------------------------------------
issue (blocking) the change breaks behavior or safety The set returns emails in any order.
suggestion (non-blocking) a better option exists and nothing breaks Limit how many saves run at once.
nitpick (non-blocking) it is a preference, not a defect Rename rows to users.
question you cannot see the contract or the callers Is the order part of the contract?
praise something is done well The test states the order it expects.Do you get to run the code in a code review interview?
It depends on the format, so ask at the start whether you may run the code and which language version it targets. If you can run it, run the tests first. If you cannot, write down the input you would try and the output you expect, then say what a different output would mean.
Predicting is a skill you can practice, which is why each diff below asks you to predict before the answer opens. A prediction that names an input and an output is a comment you can defend whether or not a terminal is available.
Diff 1 (Python): does the passing test prove the rewrite is safe?
A pull request titled 'simplify unique_emails' replaces a loop with a one-line set comprehension, and its test stays unchanged. The function should return each normalized email once, in first-seen order.
Predict before you open the answer: if you run the test, what do you see, and what would you ask before approving?
# the pull request
def unique_emails(rows):
- seen = set()
- out = []
- for row in rows:
- email = row["email"].strip().lower()
- if email not in seen:
- seen.add(email)
- out.append(email)
- return out
+ return list({row["email"].strip().lower() for row in rows})
# the test, unchanged
ROWS = [{"email": " Zed@example.com"}, {"email": "amy@example.com"}, {"email": "zed@example.com "}]
assert unique_emails(ROWS) == ["zed@example.com", "amy@example.com"]Reveal the answer and explanation
The test passes on only 56 of 100 hash seeds (0 to 99) on CPython 3.11.2, so one green run proves little. The Python documentation calls a set unordered and says str hashes are salted with a value that changes between runs, so the two emails can come back in either order. The loop and dict.fromkeys passed on 100 of 100 seeds.
Comment: issue (blocking): list(set) returns the emails in an order that changes between runs, and the test expects first-seen order, so it passes on only 56 of 100 hash seeds. dict.fromkeys keeps first-seen order, because dictionaries keep insertion order since Python 3.7. Is the order part of the contract?
If the order is not part of the contract, fix the test instead, for example by comparing sorted lists. Either way, a test that passes only some of the time should not merge. To check a suspect test yourself, run it under a few different PYTHONHASHSEED values.
# emails.py
import os
import subprocess
import sys
def before(rows):
seen = set()
out = []
for row in rows:
email = row["email"].strip().lower()
if email not in seen:
seen.add(email)
out.append(email)
return out
def after(rows):
return list({row["email"].strip().lower() for row in rows})
def fixed(rows):
return list(dict.fromkeys(row["email"].strip().lower() for row in rows))
ROWS = [{"email": " Zed@example.com"}, {"email": "amy@example.com"}, {"email": "zed@example.com "}]
WANT = ["zed@example.com", "amy@example.com"]
VARIANTS = {"before": before, "after": after, "fixed": fixed}
if len(sys.argv) > 1:
# child process: run the test once and report it through the exit code
sys.exit(0 if VARIANTS[sys.argv[1]](ROWS) == WANT else 1)
print("Python", sys.version.split()[0])
for name in VARIANTS:
passes = 0
for seed in range(100):
env = dict(os.environ, PYTHONHASHSEED=str(seed))
passes += subprocess.run([sys.executable, __file__, name], env=env).returncode == 0
print(f"{name:<6} passes on {passes} of 100 hash seeds")
$ python3 emails.py
Python 3.11.2
before passes on 100 of 100 hash seeds
after passes on 56 of 100 hash seeds
fixed passes on 100 of 100 hash seeds
CPython 3.9.25 and 3.10.22 print one different line:
after passes on 53 of 100 hash seedsDiff 2 (JavaScript): does the faster import still wait for the saves?
A pull request titled 'import users faster' replaces a loop that awaits each save with forEach(async ...). Its test calls the function and checks that it returns 'saved 3', and the test still passes.
Predict three things before you open the answer: when the caller gets 'saved 3', what happens if save(3) rejects, and what the exit code of the process is.
// the pull request
async function importUsers(ids, save) {
- for (const id of ids) {
+ ids.forEach(async (id) => {
await save(id);
- }
+ });
return `saved ${ids.length}`;
}
// the test, unchanged: it awaits importUsers([1, 2, 3], save) and expects 'saved 3'Reveal the answer and explanation
The caller gets 'saved 3' before any save has finished, so the success message no longer means the work is done. MDN says forEach() expects a synchronous function and does not wait for promises. In our run, caller: saved 3 comes before done 1.
When save(3) rejects, the loop version and the Promise.all version both hand the error to the caller and exit with code 0. The forEach version never tells the caller: the rejection is unhandled, and Node.js ends the process with exit code 1, because its default for an unhandled rejection is to throw. Node.js also prints the uncaught error and a stack trace on stderr, which we left out of the output.
Comment: issue (blocking): forEach(async) returns before the saves finish and drops their errors; await Promise.all(ids.map((id) => save(id))) keeps the speed-up and passes the error to the caller. Do the saves have to run in order, and what should the caller see if one fails?
If the saves must run in order, keep the loop, because Promise.all starts them together. If the list can be large, a suggestion (non-blocking) is to limit how many saves run at once.
// import_users.js
const events = [];
const log = (message) => events.push(message);
const makeSave = (failId) => (id) =>
new Promise((resolve, reject) => {
log(`start ${id}`);
setTimeout(() => {
if (id === failId) {
log(`fail ${id}`);
reject(new Error(`save(${id}) failed`));
} else {
log(`done ${id}`);
resolve(id);
}
}, 20);
});
async function before(ids, save) {
for (const id of ids) {
await save(id);
}
return `saved ${ids.length}`;
}
async function after(ids, save) {
ids.forEach(async (id) => {
await save(id);
});
return `saved ${ids.length}`;
}
async function fixed(ids, save) {
await Promise.all(ids.map((id) => save(id)));
return `saved ${ids.length}`;
}
const importUsers = { before, after, fixed }[process.argv[2]];
const failId = process.argv[3] === "reject" ? 3 : -1;
process.on("exit", (code) => console.log(`${events.join(", ")} | exit ${code}`));
importUsers([1, 2, 3], makeSave(failId))
.then((result) => log(`caller: ${result}`))
.catch((error) => log(`caller caught: ${error.message}`));
# every save succeeds
$ node import_users.js before
start 1, done 1, start 2, done 2, start 3, done 3, caller: saved 3 | exit 0
$ node import_users.js after
start 1, start 2, start 3, caller: saved 3, done 1, done 2, done 3 | exit 0
$ node import_users.js fixed
start 1, start 2, start 3, done 1, done 2, done 3, caller: saved 3 | exit 0
# save(3) rejects
$ node import_users.js before reject
start 1, done 1, start 2, done 2, start 3, fail 3, caller caught: save(3) failed | exit 0
$ node import_users.js after reject
start 1, start 2, start 3, caller: saved 3, done 1, done 2, fail 3 | exit 1
$ node import_users.js fixed reject
start 1, start 2, start 3, done 1, done 2, fail 3, caller caught: save(3) failed | exit 0
All 7 Node.js builds (18.20.4 to 24.11.0) print these six lines.Diff 3 (Python and SQLite): can an ordinary name break the query?
A pull request titled 'make the query easier to read' swaps a ? placeholder for an f-string. Its test looks up the name Ada, and it still passes.
Predict the result for four inputs: Ada, O'Brien, x' OR '1'='1 and x'; DROP TABLE users; --. Which ones behave differently from the old version, and which claim would you not make without running it?
# the pull request
def find_user(con, name):
- return con.execute("SELECT id, name FROM users WHERE name = ?", (name,)).fetchall()
+ return con.execute(f"SELECT id, name FROM users WHERE name = '{name}'").fetchall()
# the test, unchanged: find_user(con, "Ada") returns [(1, "Ada")]
# inputs to predict: "Ada", "O'Brien", "x' OR '1'='1", "x'; DROP TABLE users; --"Reveal the answer and explanation
Two inputs break the new version. O'Brien, an ordinary name, raises OperationalError: near "Brien": syntax error, and x' OR '1'='1 returns all three users where the placeholder version returns none. The Python documentation shows a string-built query under the comment 'Never do this -- insecure!' and recommends parameter substitution.
The fourth input does not drop the table here, because sqlite3 refuses a second statement: ProgrammingError on 3.11 and later, Warning on 3.9 and 3.10. Do not tell an interviewer that DROP TABLE would run; whether a stacked statement runs depends on the driver and its settings.
Comment: issue (blocking): the f-string puts user input into the SQL text, so a normal name with an apostrophe fails and a crafted one returns every row; restore the ? placeholder and add both inputs as tests. Where does name come from, and what did the placeholder get in the way of?
# find_user.py
import sqlite3
def find_before(con, name):
return con.execute("SELECT id, name FROM users WHERE name = ?", (name,)).fetchall()
def find_after(con, name):
return con.execute(f"SELECT id, name FROM users WHERE name = '{name}'").fetchall()
def make_db():
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
con.executemany("INSERT INTO users (name) VALUES (?)", [("Ada",), ("O'Brien",), ("Grace",)])
return con
INPUTS = ["Ada", "O'Brien", "x' OR '1'='1", "x'; DROP TABLE users; --"]
for value in INPUTS:
for label, find in (("before", find_before), ("after", find_after)):
try:
result = f"rows {[name for _, name in find(make_db(), value)]}"
except Exception as exc:
result = f"{type(exc).__name__}: {exc}"
print(f"{value!r:<28} {label:<6} {result}")
$ python3 find_user.py
'Ada' before rows ['Ada']
'Ada' after rows ['Ada']
"O'Brien" before rows ["O'Brien"]
"O'Brien" after OperationalError: near "Brien": syntax error
"x' OR '1'='1" before rows []
"x' OR '1'='1" after rows ['Ada', "O'Brien", 'Grace']
"x'; DROP TABLE users; --" before rows []
"x'; DROP TABLE users; --" after ProgrammingError: You can only execute one statement at a time.
CPython 3.9.25 and 3.10.22 print one different line:
"x'; DROP TABLE users; --" after Warning: You can only execute one statement at a time.Diff 4 (Python and JavaScript): does every call exist on the runtime you ship?
A pull request titled 'use modern APIs' replaces slicing with itertools.batched in Python, and a sorted copy and a manual grouping with toSorted and Object.groupBy in JavaScript. We wrote it the way an assistant might suggest it: fluent, correct on a current runtime and unaware of yours.
Predict where it fails if your CI runs Python 3.11 and Node.js 18. Which calls would you check before approving?
# python
def chunks(rows, size):
- return [rows[i:i + size] for i in range(0, len(rows), size)]
+ return [list(batch) for batch in itertools.batched(rows, size)]
// javascript
-const sorted = [...scores].sort((a, b) => a - b);
-const groups = {};
-for (const n of scores) (groups[n % 2 ? "odd" : "even"] ??= []).push(n);
+const sorted = scores.toSorted((a, b) => a - b);
+const groups = Object.groupBy(scores, (n) => (n % 2 ? "odd" : "even"));Reveal the answer and explanation
itertools.batched raises AttributeError on CPython 3.9 to 3.11 and works on 3.12 and later, and the Python documentation marks it as added in version 3.12. toSorted fails on Node.js 18.20.4 and 19.9.0 and works from 20.0.0, and Object.groupBy fails until 21.0.0. MDN's compatibility data lists the same two Node.js versions.
Comment: issue (blocking): this calls itertools.batched, which needs Python 3.12; on 3.11 it raises AttributeError. Use slicing, or raise the minimum version everywhere. Which Python and Node.js versions do we support?
Check the return type too. batched yields tuples, and the diff converts each batch to a list, which keeps the old shape and is worth a praise comment. A suggestion (non-blocking) is to add the oldest supported version to the CI matrix, so the next change fails in the pull request.
# chunks.py
import itertools
def chunks(rows, size):
return [list(batch) for batch in itertools.batched(rows, size)]
try:
print(chunks(list(range(7)), 3))
except AttributeError as exc:
print(f"AttributeError: {exc}")
// modern.js
const scores = [3, 1, 2, 4];
const calls = {
toSorted: () => scores.toSorted((a, b) => a - b),
groupBy: () => Object.groupBy(scores, (n) => (n % 2 ? "odd" : "even")),
};
for (const [name, call] of Object.entries(calls)) {
try {
console.log(`${name}: ${JSON.stringify(call())}`);
} catch (error) {
console.log(`${name}: ${error.name}: ${error.message}`);
}
}
Results of python3 chunks.py and node modern.js, grouped by build:
CPython 3.9.25, 3.10.22, 3.11.2, 3.11.18
AttributeError: module 'itertools' has no attribute 'batched'
CPython 3.12.16, 3.13.18, 3.14.10, 3.15.2
[[0, 1, 2], [3, 4, 5], [6]]
Node.js 18.20.4, 19.9.0
toSorted: TypeError: scores.toSorted is not a function
groupBy: TypeError: Object.groupBy is not a function
Node.js 20.0.0
toSorted: [1,2,3,4]
groupBy: TypeError: Object.groupBy is not a function
Node.js 21.0.0, 22.11.0, 22.23.5, 24.11.0
toSorted: [1,2,3,4]
groupBy: {"odd":[3,1],"even":[2,4]}What should you ask the author in a code review interview?
Ask for what the diff cannot show: the contract, the caller, the data source and the supported versions. Each of our four diffs ends in one such question, and the table pairs it with the defect and the evidence from our runs.
These are questions for the author of the diff, not questions an interviewer will ask you. A good one names the fact that would change your verdict.
Diff Blocking issue Evidence we ran Ask the author
---- ----------------------------- --------------------------------- ----------------------------------
1 Set loses first-seen order Test passes on 56 of 100 seeds Is the order part of the contract?
2 forEach(async) does not wait 'saved 3' before any save; exit 1 Must the saves run in order?
3 f-string builds the SQL O'Brien errors; OR trick: 3 rows Where does name come from?
4 Calls missing on older builds AttributeError and TypeError Which versions do we support?How do you practice for a code review interview?
Practice on diffs you can run: predict the output, write one labeled comment per defect, run the code, then score each comment out of five. Repeat the kind of defect you missed. The 30-minute split and the five-point rubric below are our suggestion, not a tested method.
The plan is for one diff in one sitting, and its minutes are planned ones, not measured ones. If you have no diff, swap broken functions with a colleague or review an old pull request of your own.
Give the evidence point only when the comment shows an input and an output. Log each missed defect with a short label such as order, waiting, input or version, and start the next sitting with a diff of that kind.
30-minute plan for one diff (our suggestion)
Minutes Step
------- --------------------------------------------------------------------
3 Read the description and the tests; write the contract in one line
10 Read the diff in pass order; note each input that could break it
5 Predict the output, then run the code or compare with a given output
7 Write one labeled comment per defect: evidence, fix, question
5 Score each comment with the rubric; rewrite the weakest
Five-point rubric for each comment (our suggestion)
Point The comment...
----- -----------------------------------------------------------------
1 names the defect in one sentence
2 shows the input and the output, run or predicted and then checked
3 carries a label that matches the risk (blocking or non-blocking)
4 proposes a fix or a test that would catch the defect
5 asks the author for something you cannot seeQuick answers about the code review interview
Is a code review interview the same as reviewing a pull request at work? The skills overlap, but the conditions differ. At work you can run the code, read the history and ask the team, while in a round you may have one diff and limited time, so ask what to expect and practice both ways: run diffs at your desk and predict outputs when you cannot.
What is the difference between a blocking comment and a nit? A blocking comment names a defect that should stop the merge until it is resolved, such as a flaky test, a lost error or untrusted input reaching a query. A nit is a trivial preference, such as a name, that the author can ignore. Conventional Comments defines the blocking decoration and the nitpick label.
What if you suspect a defect but cannot prove it? Ask a question instead of asserting a bug, as Conventional Comments suggests when you are not sure a problem exists. Name the input that worries you and ask what the author expects, and if you can run the code, run that input first and turn the question into an issue with the output.
Should you review AI-written code differently? Use the same pass order, then add one check: does every call exist on the runtime you ship? Fluent code can call something your version lacks, as Diff 4 does with itertools.batched on CPython 3.11 and earlier, so review the tests, the failure paths and the inputs as you would for any author.
Will practicing these diffs get you through a code review round? We cannot promise any interview result, and formats and scoring differ by company, so ask what your round includes. These diffs train one habit, checking a claim about code by running it or predicting its output, which is useful in any format but does not replace preparing for yours.
References and next steps
- Google Engineering Practices: What to look for in a code review
- Conventional Comments: labels and decorations for review comments
- Python documentation: how to use placeholders to bind values in SQL queries
- Unrust use case: How to Prepare for a Focused Code Review
- Unrust blog: Read a code diff for behavior, not just changed lines
- Unrust blog: How do I review AI-generated code that looks correct?
- Unrust guide: How do you review AI-generated code?
- When to practice code review instead of algorithm puzzles
See how you read code with the AI off
Take Unrust's free diagnostic with AI and autocomplete off: about 14 minutes in one sitting, with no account needed for your first read. Its Find the Flaw skill reads logic against intent, and its AI-slop Detection skill catches clean-looking code that is wrong. It is a snapshot of unassisted reasoning on short exercises and cannot predict interview success.
More from the blog
- Read a code diff for behavior, not just changed lines
Code review · 4 min read
- Debugging interview: 6 steps and a mock round
Debugging & logs · 12 min read
- How to memorize code: a 10-minute drill
Recall & learning · 8 min read