PREP WITH PROOF
Menu
SOFTWARE ENGINEERING & DEBUGGING / PRACTICAL GUIDE

Git Bisect: Find a Regression with a Reproducible Test

Use git bisect to isolate a regression, automate a stable test, handle untestable revisions and replay decisions. Includes a complete temporary-repository lab.

THE QUICK ANSWER

Git bisect narrows the history between a verified good revision and a verified bad revision using repeated test outcomes. The test must classify the same behavior consistently. Preserve untestable states, distinguish test-infrastructure failure from product failure, and confirm the reported boundary before preparing a fix.

You know the feature regressed, but not which change caused it

A test passes in an older release and fails today. Dozens of commits changed code, configuration and dependencies in between. Reading every diff is possible, but the faster investigation often begins with one small, repeatable test and two revisions whose behavior you have actually checked.

Git bisect selects candidate revisions, you classify them, and the search narrows the remaining history. In a simple linear good-to-bad history this reduces the number of revisions you need to test substantially. The useful result depends on the classification rule, not on the apparent precision of the commit hash at the end.

This guide includes a complete Bash and Python 3 lab executed locally with Git 2.51.1. It creates its own temporary repository, inserts a deliberate arithmetic defect, identifies its introduction and replays the recorded decisions. It performs no network access or remote repository changes. This is a controlled teaching history, not a measurement of search speed or a production incident.

Define the failure before choosing the endpoints

Write a concrete question such as “Does adding these two signed integers return the expected values?” or “Does this request preserve the required header?” Avoid combining unrelated failures into “the build is bad.” The first version with any build failure may be different from the version that introduced the reported bug.

Use the same input data, environment assumptions and expected result when checking the good and bad revisions. A release label is not evidence that the chosen test passes there. Likewise, the latest commit is not a valid bad endpoint if the failure occurs only against a changed external service.

Record the exact commit IDs and the test invocation. Keep fixtures and the test driver available across historical checkouts. An external driver is often helpful when the regression test itself was added after the suspected change; otherwise moving to an older revision may remove the tool you need to classify it.

Use an investigation worktree and preserve your current work

Check the working tree before starting. Historical checkouts can conflict with local edits or leave generated files behind. A dedicated detached worktree provides an investigation checkout without moving the branch in your main working directory. It still shares repository objects and references, so it is not a security sandbox for untrusted build scripts.

The example below assumes verified good and bad revisions already exist locally as tags. Adapt those names to recorded commit IDs or real refs. Run tests only in a suitable environment for the code under investigation, and keep generated outputs and temporary edits from contaminating the next candidate.

When the search finishes, save the investigation records outside the checkout before removing that worktree. Do not use cleanup commands that discard unrelated work merely to make a test pass. If a test changes tracked files, make restoration part of the controlled test procedure and verify it between candidates.

# Example refs: substitute revisions whose behavior you have verified.
git status --short
git worktree add --detach ../regression-investigation verified-bad
cd ../regression-investigation
git bisect start verified-bad verified-good
# Test the selected revision, then classify the SAME behavior:
git bisect good
# Or use git bisect bad, or git bisect skip when it cannot be tested.
# Continue until Git reports a boundary or remaining candidates.
git bisect log > ../regression-bisect.log
git bisect reset

Source: Git: detached worktrees and cleanup ↗

Keep stale outputs from deciding the answer

A historical checkout changes tracked source files, but it does not necessarily rebuild generated output or remove an ignored cache. A test that imports yesterday’s compiled package can report the same result for every candidate even while the source changes correctly. Make the build output location and cleanup rule part of the test design.

Pin the dependencies and runtime needed for the history you are investigating. Installing today’s newest packages at each step can introduce a moving variable unrelated to the original commits. If an older revision needs an unavailable toolchain, record that inability explicitly instead of treating a setup exception as the feature’s bad result.

Also inspect the test’s side effects. Database fixtures, environment files and reused services can persist across candidates. Prefer an isolated fixture that is recreated consistently, and keep external network responses out of a deterministic local test when the failure does not require them. Repeatedly rebuilding only the source is insufficient if the stateful dependency still contains data from the previous candidate.

Before automation, deliberately run the checker against one known passing and one known failing state, and inspect its exact exit codes. Then simulate a setup problem and verify that the checker skips or aborts according to the chosen policy. These checks validate the measurement tool before its classifications begin narrowing the history.

Make the automatic checker’s exit status intentional

git bisect run invokes a command at each selected revision. The command’s exit status becomes evidence. Zero means good. Statuses 1 through 127 mean bad, except 125, which means the revision cannot be tested. Other statuses abort the automated search. A missing executable can produce 127, so blindly forwarding shell failures can misclassify a broken test environment as a product regression.

Build or dependency failures need an explicit policy. If the investigation concerns runtime behavior and an unrelated old build cannot run in the prepared environment, skipping may be appropriate. If the reported regression is that the build broke, skipping that failure would erase the signal you are investigating. Choose the predicate first.

The lab checker uses 1 for an incorrect arithmetic result, 125 for a missing or syntactically unusable teaching module, and 128 for an unexpected checker exception. Those choices are part of this lab’s policy, not a universal wrapper for every project. Inspect your own test tool’s statuses and normalize them deliberately.

Checker outcomeExit statusMeaning in this search
Expected result observed0Good revision
Target behavior fails1Bad revision
Known unrelated inability to test125Skip this revision
Unexpected harness error128Abort and repair the investigation
Shell cannot find a commandOften 127Danger: treated as bad unless deliberately handled

Source: Git: bisect commands, exit statuses and skipped revisions ↗

Run a complete regression search in a temporary repository

Save this as bisect_lab.sh and run bash bisect_lab.sh. It requires Bash, Python 3 and a Git version supporting git init -b. The script makes twelve commits: revisions 1 through 6 add correctly, and revision 7 introduces subtraction that remains through revision 12. It computes the expected commit ID locally, so it does not rely on a copied example hash.

The test driver lives outside the repository and avoids Python bytecode files. The lab validates both endpoints, runs the search, asserts the first bad revision, resets to the starting revision and replays the saved decisions. All temporary files and repository configuration stay within the disposable directory; the EXIT trap removes it afterward.

#!/usr/bin/env bash
set -eu
lab_dir=$(mktemp -d)
trap 'rm -rf "$lab_dir"' EXIT

git init -q -b main "$lab_dir/repo"
cd "$lab_dir/repo"
git config user.name 'Prep With Proof Lab'
git config user.email 'lab@example.invalid'
git config commit.gpgsign false
mkdir "$lab_dir/empty-hooks"
git config core.hooksPath "$lab_dir/empty-hooks"
git config core.fsmonitor false

# The checker is outside the repository history and survives every checkout.
cat > "$lab_dir/check.py" <<'CHECK'
import runpy
import sys

try:
    namespace = runpy.run_path("calc.py")
    add = namespace.get("add")
    if not callable(add):
        sys.exit(125)
    passed = add(2, 3) == 5 and add(-2, 5) == 3
except (OSError, SyntaxError):
    sys.exit(125)
except Exception:
    sys.exit(128)
sys.exit(0 if passed else 1)
CHECK

for revision in {1..12}; do
  if (( revision >= 7 )); then
    expression='a - b'
  else
    expression='a + b'
  fi
  printf '# revision %s\ndef add(a, b):\n    return %s\n' "$revision" "$expression" > calc.py
  git add calc.py
  git commit -q -m "revision $revision"
  if (( revision == 1 )); then good=$(git rev-parse HEAD); fi
  if (( revision == 7 )); then expected=$(git rev-parse HEAD); fi
done
bad=$(git rev-parse HEAD)

# Confirm the endpoints with the same checker before searching.
git switch -q --detach "$good"
python3 -B "$lab_dir/check.py"
git switch -q main
if python3 -B "$lab_dir/check.py"; then
  printf '%s\n' 'Expected the final revision to fail' >&2
  exit 1
else
  test "$?" -eq 1
fi

git bisect start "$bad" "$good"
git bisect run python3 -B "$lab_dir/check.py"
test "$(git rev-parse refs/bisect/bad)" = "$expected"
git bisect log > "$lab_dir/bisect.log"
git bisect reset
test "$(git rev-parse HEAD)" = "$bad"

# Replaying records the same classifications; it does not rerun Python.
git bisect replay "$lab_dir/bisect.log"
test "$(git rev-parse refs/bisect/bad)" = "$expected"
git bisect reset
printf '%s\n' 'PASS: found revision 7, restored HEAD, and replayed the search'

A first bad revision is a boundary to confirm

Inspect the reported commit and retest its relevant parent with the same driver. In the lab the history is linear, the defect persists and there is one parent. Real histories can include merges, repaired regressions and dependencies between changes. Record what the search actually establishes for your tested history.

git show helps inspect the candidate’s changes. A search limited with --first-parent follows only first-parent history when encountering merges; this can locate the integration point that brought a failure onto that line rather than the original topic-branch change. A path-limited search also changes which commits are eligible, so use it only when the scope is justified.

Do not turn “first bad under this test” into proof of root cause. Confirm the triggering code path, reproduce the failure and test a proposed correction. A commit may expose a previously hidden defect or change a dependency rather than contain an obvious erroneous line. The investigation should explain the behavior, not assign blame based on chronology.

Do not assume HEAD is the reported first bad commit: the last revision tested can be a good one. Inspect the reported boundary explicitly; the lab asserts the refs/bisect/bad reference before resetting the session.

Source: Git: inspect a commit with show ↗

Keep skipped and inconsistent results visible

A skipped revision remains unknown, not good. If an untestable commit is adjacent to the transition, Git may be unable to identify one unique first bad commit. Report the remaining candidates and repair the test environment if possible. Choosing the most plausible hash from that set is a separate hypothesis.

Flaky tests undermine binary classification. Before searching, repeat the endpoint checks enough to understand the instability and remove changing external inputs. A majority vote can still hide a low-frequency failure; define any repeated-run rule and preserve the observations instead of quietly changing the threshold mid-search.

The same caution applies when the behavior fails, is fixed, and fails again. A search across that history may find a boundary that does not answer the intended incident question. Narrow the interval to the observed regression and inspect the surrounding history. Search speed cannot compensate for endpoints that describe different failures.

Source: Git: bisect commands, exit statuses and skipped revisions ↗

Save decisions, correct mistakes, and retain the verification work

git bisect log records the classifications used in the search. Replay applies those decisions; it does not execute the test again or prove that another machine has the same environment. Keep the driver, fixture versions, dependency setup and relevant output alongside the log if another engineer needs to reproduce the investigation.

If you classified a revision incorrectly, save the log, remove the mistaken classification and reset before replaying the corrected record. Do not force later answers to agree with an earlier mistake. After the corrected search, confirm the candidate and its relevant predecessor again before implementing a fix.

Finish with the tested endpoints, the classification rule, any skipped revisions, the candidate boundary and a regression test that demonstrates the repair. Use the linked merge-and-rebase guide when the resulting fix must be integrated into an active branch. The valuable deliverable is a reproducible explanation and a verified correction, not only a hash from an automated search.

KEEP THESE THREE THINGS

Your next steps

  1. Verify both endpoints with the same stable behavior test before bisecting.
  2. Separate product failure, untestable revisions and unexpected harness errors.
  3. Preserve the decision log and test environment, then confirm the boundary and proposed fix.

Sources & official resources

Linked resources checked on 2026-10-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →