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
On this page
- Branch Protection Policies: Defending the Mainline
- Reading a failing run
- Worked example: reproduce the failure and fix it
- Fixing, reverting and quarantining
- Check your understanding
- Apply it
- Review prompt
Lessons of Continuous Integration
- Integrating continuously: small batches and a green main Concept · 15 min
- Anatomy of a pipeline: triggers, jobs, runners, steps and reuse Concept · 20 min
- Lab: a pull-request pipeline with caching and a test matrix Lab · 30 min
- Merge gates and reading a failing run Worked example · 20 min
- Securing the pipeline itself: lessons from compromised actions Worked example · 20 min
- Check: fix and harden a broken workflow Knowledge check · 6 questions
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)andtest (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-ignoreor 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-levelif:(a job skipped by a condition reports success), or make one always-running aggregator job (for exampleci-ok, withneeds: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 formigrations/**). - 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:
-
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).
-
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 likeactions/checkoutoractions/setup-python. -
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.
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.
from dataclasses import asdict, dataclass
@dataclass
class User:
id: str
email: str
role: str = "viewer"
def to_dict(self) -> dict:
return asdict(self)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.
COLUMNS=80 python -m pytest -qq --color=no tests/test_users.py::test_user_serialization
echo "exit=$?"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=1Now 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):
def to_dict(self) -> dict:
# role is internal; the API contract exposes only id and email
return {"id": self.id, "email": self.email}COLUMNS=80 python -m pytest -qq --color=no
echo "exit=$?"... [100%]
exit=0Push 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 byfile: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 tomain. Unless the fix is quick and obvious, revert the broken commit withgit revert <sha>through a pull request, somainis 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.flakyfrom 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
06. Apply it
In your own repositories:
- Require status checks on main: protect
mainby 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
mainbefore 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.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.