Q24 of 40 · Git

How does `git bisect` work, and how would you use it to find which commit broke an API test?

GitMidgitbisectdebuggingregressionbinary-search

Short answer

Short answer: `git bisect` performs a binary search through commit history: you mark the current commit as 'bad' and an older known-good commit as 'good', then Git checks out the midpoint. You test and mark each midpoint until the first bad commit is isolated — O(log n) steps.

Detail

git bisect automates the process of finding which commit introduced a regression. Instead of checking out commits one by one, it uses binary search: with 1000 commits between good and bad, it finds the culprit in at most 10 steps.

Manual workflow: start with git bisect start, mark the current HEAD as git bisect bad, and mark a known-good commit as git bisect good <sha>. Git checks out the commit halfway between. You test, then mark it good or bad. Repeat until Git prints "first bad commit."

Automated workflow: if you have a script that exits 0 for a passing test and non-zero for a failing one, you can hand it to git bisect run <command> and let Git do the whole binary search unattended. This is the power move for QA engineers — point it at your Gradle test task.

Cleanup: always run git bisect reset at the end to restore HEAD to where you started; otherwise you're in a detached HEAD state.

Skipping commits: if a commit doesn't compile or is otherwise untestable, use git bisect skip and Git will choose an adjacent commit.

// EXAMPLE

# Start bisect session
git bisect start

# Mark current HEAD as broken
git bisect bad

# Mark last known-good release tag as good
git bisect good v2.3.0

# Git checks out midpoint — run your test manually
./gradlew test --tests "com.example.OrderApiTest"
# Test passed → mark good
git bisect good

# Test failed → mark bad
git bisect bad

# Repeat until Git prints:
# "a1b2c3d4 is the first bad commit"

# --- Automated mode (recommended) ---
git bisect start
git bisect bad HEAD
git bisect good v2.3.0

# Script must exit 0 for PASS, non-zero for FAIL
git bisect run ./gradlew test --tests "com.example.OrderApiTest"
# Git runs the binary search automatically and prints the culprit

# Always clean up after bisect
git bisect reset

// WHAT INTERVIEWERS LOOK FOR

Understanding the binary search mechanism (O(log n)). The automated `git bisect run` form — this signals real-world usage. Knowing to `git bisect reset` to leave detached HEAD state. Knowing `git bisect skip` for untestable commits.

// COMMON PITFALL

Forgetting `git bisect reset` after the session ends, leaving HEAD detached at the bad commit. All subsequent git commands then operate on a detached HEAD, which confuses many developers.