Git Bisect: Finding the Exact Commit That Broke Your Code

Last Tuesday a teammate pinged me: "The chart export stopped working sometime in the last three weeks." The feature had passed QA, shipped, and then quietly broke. Nobody noticed for days, and now we had 180 commits between the last known good release tag and HEAD, spanning four feature branches that had been merged to main. My first instinct years ago would have been to scroll through git log and start checking out commits at random. In my experience, that instinct is exactly what turns a 10-minute diagnosis into a half-day of frustration. This is the exact problem git bisect was built to solve — isolating a regression to a single commit through binary search, regardless of how large the range is.

Why Scrolling Through git log Fails You on Regressions

When a regression report comes in without a clear cause, most developers try a linear approach: check out a commit from a week ago, test manually, then move forward or backward. If you have 200 commits to search, worst-case you test 200 times. Even with a disciplined approach, you're looking at dozens of checkouts and rebuilds. I've watched teams spend an entire afternoon doing this before they remember bisect exists.

The core issue is that git log presents history as a flat list, but you don't need to examine every item. A regression, by definition, is a binary property — a commit either contains the bug or it doesn't. That property lets you apply binary search. Instead of testing N commits, you test roughly log2(N). For 180 commits, that's about 8 tests instead of 180. For 1,000 commits, it's about 10. The time savings compound when each test involves installing dependencies, running a build, or executing an integration suite.

This matters even more in active codebases where merges obscure the timeline. A linear scan forces you to make assumptions about which branch introduced the problem. Bisect makes no assumptions; it walks the actual commit graph and finds the first commit where the behavior flips from good to bad. If you're working in a repository where multiple teams merge daily, that graph-aware search is the only reliable method I've found that doesn't miss the culprit.

The Cost of Manual Guesswork

Beyond raw time, manual hunting introduces bias. Developers tend to check commits that "look suspicious" — a large refactoring, a dependency upgrade — and skip commits that appear trivial. In my experience, the breaking change is often in the trivial commit: a one-line CSS change that hides an error message, a default prop value flipped from false to true, a regex that was "cleaned up." Automated binary search removes that bias entirely. It tests the middle commit without caring what the commit message says.

How Git Bisect Transforms Your Commit Graph Into a Searchable Range

Under the hood, git bisect doesn't just split a list in half. It works on Git's directed acyclic graph (DAG) and selects the commit that most evenly divides the number of commits between good and bad boundaries. When history is linear, this is simple midpoint selection. When history includes merges, Git calculates the best candidate to minimize the remaining search space regardless of branching topology.

You start by declaring boundaries: one commit you know is good and one you know is bad. Usually the bad commit is HEAD or the current release, and the good commit is the last release tag, a previously deployed SHA, or simply a commit you verified locally. Once those two points are marked, Git checks out a commit roughly halfway between them. You test it, tell Git whether it's good or bad, and Git halves the range again. This continues until the range collapses to a single commit — the first bad commit.

This process is logarithmic. I once traced a performance regression across 1,742 commits in a monorepo. A manual scan would have been absurd; bisect found it in 11 steps. The commit was a seemingly harmless optimization to a shared utility that changed iteration order from stable to non-deterministic under certain conditions. Without bisect, we would have blamed the wrong team entirely, because the symptom appeared in a dashboard package far from the actual change.

What Bisect Actually Checks Out

A common misconception is that bisect checks out every commit in order. It doesn't. It checks out commits in an order determined by the graph structure to maximize information gain per test. You can see this in action with git bisect visualize or git bisect log, which shows the remaining candidates. If your history is heavily branched, the sequence may appear to jump backward and forward in time. That's expected and intentional. Trust the algorithm rather than trying to outguess it.

Marking the Boundaries: Choosing Good and Bad Commits With Confidence

The accuracy of a bisect session depends entirely on correctly marking the boundaries. If you mark a commit as good when it was actually already broken, the search will converge on the wrong result. I've made this mistake when I relied on a passing CI badge from two weeks ago instead of actually reproducing the bug locally at that commit.

Start with the simplest reliable markers you can prove:

# Start a bisect session
git bisect start

# Mark the current commit as bad (it has the bug)
git bisect bad HEAD

# Mark a known good point - use a tag if you have one
git bisect good v2.14.0

# Or use a specific commit hash you verified
git bisect good a1b2c3d4e5f6

If you don't have a tagged release, use git log --oneline --grep="release" or check your deployment history to find a SHA you know was deployed without the regression. When in doubt, go further back than you think necessary. It's cheaper to add a few extra bisect steps than to start over because your "good" commit was already broken.

For cases where HEAD isn't bad but a feature branch tip is, you can mark any commit as bad: git bisect bad feature/new-export. You can also mark multiple good commits if you know several points in history were healthy — Git will use them to narrow the search space more efficiently. This is particularly useful when you maintain release branches alongside main, a workflow discussed in Git Branching Strategies: Trunk-Based, GitFlow and Ship/Show/Ask.

Verifying Before You Declare Good or Bad

Before you answer git bisect good or git bisect bad, run the exact reproduction steps every time. Don't rely on memory. I keep a one-liner reproduction command in my notes for the session — a curl request, a specific unit test, or a script that opens the app and checks for the broken behavior. If you have flaky tests, run the check twice. A single mislabeled commit will send the search down the wrong half of the graph and waste more time than double-checking.

When you're satisfied with your markers, Git will immediately check out a midpoint commit and prompt you: Bisecting: X revisions left to test after this. Now you're in the loop.

Automating the Hunt With git bisect run and Deterministic Test Scripts

Manual bisect is effective, but git bisect run is where the tool becomes genuinely powerful for intermediate teams. Instead of you testing each checkout by hand, you provide a script that exits with a status code Git can interpret: 0 for good, 1-124 (or 126, 127) for bad, and 125 for skip when the commit can't be tested.

The key is writing a deterministic script. It must return the same answer for the same commit every time, without human judgment or flaky side effects. I've found the best approach is to isolate the reproduction to a single automated test that was previously passing and now fails.

#!/bin/sh
# bisect-test.sh - exit 0 = good, 1 = bad, 125 = skip

# Ensure clean build artifacts
npm run build --silent 2>/dev/null
if [ $? -ne 0 ]; then
  echo "Build failed - skipping commit"
  exit 125
fi

# Run the specific regression test
npm test -- --testPathPattern="export-chart.test.ts" --silent
STATUS=$?

if [ $STATUS -eq 0 ]; then
  echo "Test passed - commit is good"
  exit 0
else
  echo "Test failed - commit is bad"
  exit 1
fi

Make the script executable (chmod +x bisect-test.sh) and hand it to bisect:

git bisect start HEAD v2.14.0
git bisect run ./bisect-test.sh

# When finished, inspect the result
git bisect log
git bisect reset

Git will now walk the entire range without intervention. In my experience, this automation is essential for regressions that require a full build. Manually rebuilding at each step invites mistakes like forgetting to clear a cache or run migrations, which pollutes the result. A script ensures each iteration starts from a clean state.

For Python-based tooling, you can use a similar pattern with pytest and explicitly handle interpreter exit codes. The Python Documentation on sys.exit() and process status codes is a useful reference for ensuring your test harness returns 0 for success and non-zero for failure, which maps directly to what bisect expects. For frontend codebases, the same principle applies with Jest, Vitest, or Playwright — pick one test that captures the regression and nothing else.

Crafting Scripts That Don't Lie

A few lessons I've learned from scripts that gave false results: first, always handle the untestable case. If a commit in the middle of your range doesn't compile because of a temporary dependency issue, exit 125 so Git skips it rather than marking it bad. Second, avoid network calls in the test script; use mocked data or local fixtures so bisect doesn't fail due to an offline service. Third, keep the script hermetic — pin Node versions, clear caches, or use git clean -fdx inside the script if you must. A bisect run that takes 8 automated steps should be trustworthy without you watching it.

If you want to prevent this class of regression permanently, consider wiring that same test into a pre-push check. The approach is covered in detail in Git Hooks for Automation: Pre-commit, Pre-push and CI Integration, and it has saved my teams from repeating bisect hunts for the same kind of breakage.

When Bisect Gets Confused: Skipping Untestable Commits and Noisy Merges

Real histories are messy. Some commits won't build, some commits are merge commits that combine several lines of work, and some commits contain unrelated changes that mask the regression. Bisect has specific tools for these situations, and knowing when to use them is the difference between a clean result and a session you have to abort.

When Git checks out a commit that fails to build for reasons unrelated to your bug, mark it as skipped:

git bisect skip
# Or provide a range of broken commits
git bisect skip a1b2c3d..f6e5d4c3

Git will then choose an alternative commit near the midpoint that hasn't been tested. Exiting with 125 in a run script does the same thing automatically. Don't mark an untestable commit as good or bad just to keep moving — that corrupts the search.

Merge commits deserve special attention. By default, bisect will test merge commits themselves, which is usually what you want because the merge is where integration issues surface. However, if your team uses a rebase-heavy workflow, the history is linear and you won't encounter this. Understanding whether your history is dominated by merges or rebases changes how you interpret bisect results, which is why I often point colleagues to Git Rebase vs Merge: Understanding the Trade-offs before they start diagnosing history-related issues.

Diagnosis Method Best For Search Complexity Limitation
git bisect (manual or run) Finding the first commit that introduced a binary regression O(log N) Requires reproducible good/bad signal; fails on flaky tests
git blame Finding who last touched a specific line O(1) per line Points to last edit, not first failure; misses moved code
git log --grep / --oneline Locating commits by message or file path O(N) scan Relies on commit messages; misses silent regressions
Manual checkout + test Quick sanity check over 2-3 commits O(N) Does not scale; highly biased toward "suspicious" commits

I've also found it helpful to combine bisect with git bisect visualize when dealing with noisy merges. That command launches gitk or your configured visualization tool showing only the remaining candidates, so you can see whether the remaining range is clustered around a specific feature merge. If it is, you can often guess the area of the codebase to investigate while bisect finishes.

Dealing With Flaky or Non-Deterministic Failures

Flaky tests are the natural enemy of bisect. If your test passes 80% of the time on good commits and fails 80% of the time on bad commits, bisect may wander. The fix isn't to run bisect more times — it's to stabilize the signal first. Isolate the regression to a deterministic unit test if possible, or wrap the flaky test in a retry loop inside your bisect script that only reports good after three consecutive passes. In my experience, spending 20 minutes hardening the test script saves hours of ambiguous bisect runs.

From Culprit Commit to Permanent Prevention: What to Do After You Find It

When bisect finishes, it prints something like:

a1b2c3d4e5f6 is the first bad commit
commit a1b2c3d4e5f6
Author: Jane Doe <jane@example.com>
Date:   Tue Oct 15 14:22:11 2024 +0200

    refactor: normalize export payload keys to camelCase

 src/export/serializer.ts | 42 +++++++++++++----------------
 src/export/types.ts      |  8 ++---
 2 files changed, 22 insertions(+), 28 deletions(-)

Your job isn't done. The first thing I do is verify the result independently: check out the commit's parent, confirm the test passes, then check out the culprit commit and confirm it fails. Run git bisect reset to return to your original branch before you do this, otherwise you'll be testing in a detached HEAD state and may confuse your next steps.

git bisect reset
git checkout a1b2c3d4e5f6^  # parent - should be good
./bisect-test.sh; echo $?
git checkout a1b2c3d4e5f6   # culprit - should be bad
./bisect-test.sh; echo $?

Once verified, read the diff carefully. Understand why the change broke the feature, not just that it did. In the example above, the serializer started emitting fileName while the downstream consumer still expected file_name. The fix might be to revert the key normalization or to update the consumer — the commit itself tells you which direction is less risky.

This is also the moment to make the regression impossible to reintroduce. Keep your bisect test script, clean it up, and commit it as a permanent regression test. If the bug was in serialization logic, add a unit test that asserts the wire format explicitly. If it was a CSS issue that hid an error, add a visual regression test or an assertion that the error element is visible when the API returns a 500. The cost of that test is trivial compared to the cost of debugging the same class of issue again.

Finally, consider what process allowed the regression to ship without detection. Was there coverage on the affected path? Did code review miss the coupling between serializer and consumer? Could a conventional commit prefix like fix! or refactor have triggered a different review gate? For teams adopting stricter commit discipline, Conventional Commits: Automating Changelogs and Semantic Versioning offers a complementary practice that makes it easier to map regressions to intended behavior, though it doesn't replace bisect for discovery.

Bisect also leaves behind a useful audit trail. git bisect log outputs a replayable log of the session that you can save in the bug ticket or post-mortem. I've started attaching that log to incident reports — it shows exactly which commits were tested and how the culprit was identified, which makes the diagnosis reviewable by anyone on the team.

Frequently Asked Questions

How is git bisect different from git blame for debugging regressions?

They answer different questions. git blame tells you who last modified a specific line of code, which is useful when you already know where the bug lives. git bisect tells you which commit first introduced a failure in behavior, even if the broken line hasn't been touched since. I've seen blame point to a two-year-old formatting commit while bisect correctly identified a three-day-old logic change in a different file that caused that line to execute differently.

Can I use git bisect if the bug is not consistently reproducible?

Not reliably until you stabilize the reproduction. Bisect assumes a deterministic signal: a given commit is either good or bad every time you test it. If your failure is flaky due to race conditions, timing, or external services, first isolate a deterministic subset — a unit test that fails 100% on bad commits and passes 100% on good ones. You can also wrap flaky tests in a script that retries several times and only declares "good" after consecutive passes. Without that stability, bisect may converge on the wrong commit.

What should I do when git bisect lands on a merge commit?

Examine the merge diff and the individual parents. Run git show <merge-sha> to see the combined changes and git log --merges --oneline <good>..<bad> to see which branch was merged. Then check out each parent branch tip individually and test — sometimes the bug was latent on the feature branch and only surfaced after the merge due to interaction with main. If you need to, you can continue bisecting inside the merged branch by starting a new bisect session bounded by that branch's base and tip.

Do I need to clean up after a bisect session?

Yes. Always run git bisect reset when you're done. Bisect leaves you in a detached HEAD state and stores state in .git/BISECT_* files. Reset returns you to the branch you were on before you started and removes that temporary state. If you forget, you may accidentally commit or branch from a bisect checkout instead of your intended branch. The reset command is safe to run even if the session was interrupted or you closed your terminal.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards