Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 3

Merge gates and reading a failing run

Set up branch protection and required checks as merge gates, then diagnose a failing CI run from its log and reproduce it locally.

Contentsand lesson path

What you will learn

  • Gate merges with required status checks and branch protection, and trace a failing run from its logs to the root cause.

Prerequisites: Git Workflow, Build & Test Pipeline

01. Branch Protection Policies: Defending the Mainline

Good intentions do not keep a mainline green; the hosting platform has to enforce it. Branch protection rules (GitHub also offers rulesets; GitLab has protected branches and merge request approvals) act as merge gates. Most teams block direct pushes to main, so every change goes through a pull request and its automated checks before it is merged.

Common merge gate settings:

  • Require status checks to pass before merging: Specific CI jobs must finish successfully. Required checks are matched by the job's display name: in the lab 03 workflow those are lint, test (py3.13) and test (py3.14). If any required check fails or times out, the hosting platform blocks the merge button; this is a policy check enforced by the platform, not a cryptographic lock.
  • A required check must run on every pull request: If a whole workflow is skipped by a paths, paths-ignore or branch filter (for example a docs-only pull request), its required checks never report and stay Pending, which blocks the merge. Either do not path-filter workflows that provide required checks, or keep the workflow running and skip work inside it with a job-level if: (a job skipped by a condition reports success), or make one always-running aggregator job (for example ci-ok, with needs: on every other job) the only required check.
  • Require branches to be up to date before merging: the pull request branch must contain the latest commit from main, so its checks ran against current code. This catches semantic merge bugs, where two independently valid pull requests conflict when combined, as far as your tests exercise the affected code.
  • Require pull request reviews and CODEOWNERS: changes need approval from the owners of the paths they touch (for example the security team for auth/** or the database team for migrations/**).
  • Require signed commits and linear history: linear history forbids merge commits on the branch, and signed commits show which GPG, SSH or S/MIME key signed each commit. A signature proves who held the key, not that the code is correct.

Consider semantic merge conflicts. Suppose engineer Alice opens a pull request that renames an internal utility function from fetch_user() to get_user_by_id(), updating all existing invocations across the repository. Simultaneously, engineer Bob opens a pull request that introduces a new checkout flow that calls fetch_user(). Both pull requests pass their CI test suites, because each is tested against a main that does not yet contain the other. However, if Alice merges her pull request first and Bob immediately merges his without updating his branch from main, Git finds no conflicting lines, yet main is now broken: the new checkout flow calls a function that no longer exists. Requiring branches to be up to date makes Bob's pull request re-run its tests on top of the latest main, so a test that calls fetch_user() would now fail before the merge. It catches semantic conflicts only as far as your tests cover them: if no test calls the new checkout flow, the break still reaches main.

Also separate blocking checks from informational ones. Builds, unit tests, migration dry-runs and secret scanners are usually required; coverage deltas or documentation link checks can report without blocking, so they never hold up an urgent security fix.

02. Reading a failing run

When a pull request check turns red, it is tempting to re-run the whole pipeline or to scroll through thousands of log lines. A short routine works better:

  1. Classify the failure: decide whether the failure is an Infrastructure Failure (runner out of disk space, API rate limiting, docker daemon socket crash), a Dependency Failure (upstream package repository 503 error, lockfile hash mismatch), or a Code Regression (assertion mismatch, unhandled null exception, syntax error).

  2. Find the failing step: expand only the step marked with an exit status of 1 (or non-zero). Avoid scrolling through hundreds of lines in successful previous steps like actions/checkout or actions/setup-python.

  3. Read the failure from the bottom up: start with the short test summary, then find the first frame in your own code (a test or application file and line number), skipping standard library and test-runner frames.

The log below comes from the worked example in the next section: a pull request added a role field to User, and the API contract test still expects the old payload.

Illustrative output · the failing step in the CI log (paths, versions and times differ)
Run python -m pytest --junitxml=reports/junit-py3.13.xml
============================= test session starts ==============================
platform linux -- Python 3.13.x, pytest-9.1.1, pluggy-1.7.0
rootdir: /home/runner/work/api/api
collected 3 items

tests/test_users.py .F.                                                  [100%]

=================================== FAILURES ===================================
___________________________ test_user_serialization ____________________________

    def test_user_serialization():
        user = User(id="usr_928", email="[email protected]", role="editor")
>       assert sorted(user.to_dict()) == CONTRACT_FIELDS
E       AssertionError: assert ['email', 'id', 'role'] == ['email', 'id']
E         
E         Left contains one more item: 'role'
E         Use -v to get more diff

tests/test_users.py:13: AssertionError
- generated xml file: /home/runner/work/api/api/reports/junit-py3.13.xml -
=========================== short test summary info ============================
FAILED tests/test_users.py::test_user_serialization - AssertionError: assert ...
========================= 1 failed, 2 passed in <time> =========================
Error: Process completed with exit code 1.

Apply the routine. The runner, checkout and setup steps passed, so this is not an infrastructure or dependency failure: the step that exited with code 1 ran the tests. The short summary names one test, and the frame marked > is line 13 of tests/test_users.py. The E lines say what differs: the payload has a role field that the contract does not list.

03. Worked example: reproduce the failure and fix it

Before you change any code, reproduce the failure on your machine. These are the two files from the pull request, at the root of a project with pytest 9.1.1 installed (as in lesson 03). The pull request added role to User, and to_dict() now returns every field.

Python · users.py (as in the pull request)
from dataclasses import asdict, dataclass


@dataclass
class User:
    id: str
    email: str
    role: str = "viewer"

    def to_dict(self) -> dict:
        return asdict(self)
Python · tests/test_users.py
from users import User

# The API contract: the only fields that clients may receive.
CONTRACT_FIELDS = ["email", "id"]


def test_default_role():
    assert User(id="usr_1", email="[email protected]").role == "viewer"


def test_user_serialization():
    user = User(id="usr_928", email="[email protected]", role="editor")
    assert sorted(user.to_dict()) == CONTRACT_FIELDS


def test_email_kept():
    assert User(id="usr_2", email="[email protected]").email == "[email protected]"

Run only the failing test, selected by its node id: the file path, :: and the test name. -qq drops the header and the timing line. pytest draws its ==== separator lines as wide as your terminal, and in a terminal it adds colour, which also changes where it cuts the last summary line. COLUMNS=80 fixes the width and --color=no turns colour off, so with pytest 9.1.1 your output should match the block below line for line.

Bash · run the failing test by its node id
COLUMNS=80 python -m pytest -qq --color=no tests/test_users.py::test_user_serialization
echo "exit=$?"
Expected output
F                                                                        [100%]
=================================== FAILURES ===================================
___________________________ test_user_serialization ____________________________

    def test_user_serialization():
        user = User(id="usr_928", email="[email protected]", role="editor")
>       assert sorted(user.to_dict()) == CONTRACT_FIELDS
E       AssertionError: assert ['email', 'id', 'role'] == ['email', 'id']
E         
E         Left contains one more item: 'role'
E         Use -v to get more diff

tests/test_users.py:13: AssertionError
=========================== short test summary info ============================
FAILED tests/test_users.py::test_user_serialization - AssertionError: assert ...
exit=1

Now decide which side is wrong. If clients should receive role, the contract changed: update CONTRACT_FIELDS and the API documentation in the same pull request. Here role is meant to stay internal, so the serializer is wrong. Replace to_dict() in users.py so that it returns only the contract fields (and drop the asdict import, which is no longer used):

Python · users.py (the fixed method)
    def to_dict(self) -> dict:
        # role is internal; the API contract exposes only id and email
        return {"id": self.id, "email": self.email}
Bash · run the whole suite again
COLUMNS=80 python -m pytest -qq --color=no
echo "exit=$?"
Expected output
...                                                                      [100%]
exit=0

Push the fix to the same branch. The pull request runs its checks again, and the merge gate opens only when they pass on the new commit.

04. Fixing, reverting and quarantining

What you do next depends on where the failure happened:

  • Pull request failures: the author reproduces the failing assertion locally by selecting the failing test by its node id (python -m pytest tests/test_users.py::test_user_serialization), and then runs the same command the CI step ran (python -m pytest --junitxml=reports/junit-py3.13.xml) before pushing. pytest selects tests by node id, not by file:line. After fixing the serialization logic or updating outdated test fixtures, a new commit is pushed to the branch. The CI pipeline triggers automatically and re-evaluates the merge gates.
  • Mainline failures (red main): if a regression escaped the pull request checks (for example through an unpinned dependency or a race condition) and reached main, do not push guesses straight to main. Unless the fix is quick and obvious, revert the broken commit with git revert <sha> through a pull request, so main is green again while the author investigates (lesson 01 discusses the time box).
  • Quarantining flaky tests: if a test is proven to fail intermittently without code changes, quarantine it: skip it with a tracked reason (@pytest.mark.skip(reason="flaky, see ISSUE-402")) or move it to a non-blocking job, and track the fix in a high-priority ticket. Automatic retries (@pytest.mark.flaky from the third-party pytest-rerunfailures plugin, not built into pytest) re-run a failing test up to a set number of times (reruns=N) and report it as passed if any attempt passes, which hides the flakiness; use them only as a short, tracked stopgap.
  • Blameless review: when a serious bug gets past the merge gates, treat it as a gap in the safeguards rather than one person's mistake, and ask which test, lint rule or static check would have caught it earlier.

05. Check your understanding

Practice check · 3 questions

Skipped required checks, log reading and re-runs

Three questions on merge gates and on reading a failing run.

Q1. A docs-only pull request skips a workflow through `paths-ignore`, and that workflow's job is a required check. What does the pull request show?
Q2. When inspecting a failed continuous integration run log containing 10,000 lines of console text, which step provides the fastest path to root cause identification?
Q3. Why is repeatedly clicking `Re-run all jobs` considered an engineering anti-pattern when encountering intermittent test failures on pull requests?
Practice only: not graded, not saved, not evidence.

06. Apply it

In your own repositories:

  • Require status checks on main: protect main by requiring passing builds from all critical matrix and security jobs, and make sure every required check runs on every pull request (no workflow-level path filters on required workflows).
  • Require branches to be up to date: test each change against the current main before merging, so your tests get a chance to catch semantic conflicts.
  • Triage failures step by step: identify the failing step first, read the error summary from the bottom up, and reproduce locally before modifying code.
  • Quarantine flaky tests quickly: do not accept flaky tests as normal; skip them with a tracked reason or move them to a non-blocking job, and track the fix in a ticket.
  • Revert broken commits on main: when a bad merge slips through, revert first to unblock colleagues, then fix in a separate PR.
  • Hold blameless reviews: when regressions bypass CI gates, identify gaps in test fixtures or pipeline lint rules.

07. Review prompt

Explain how branch protection rules and required status checks keep a broken change out of main, and where they stop helping. Detail the step-by-step heuristic for triaging a failing CI workflow log, and discuss why flaky tests must be quarantined rather than repeatedly re-run.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check