Sub topic 2
Continuous integration: merging early and verifying every change
Prerequisites
This chapter assumes you can do the following:
- Commit, branch, and open a pull request in Git.
- Build an application and run its tests from the command line.
- Read simple YAML.
You do not need prior experience with any CI service. The examples use GitHub Actions, but the ideas apply to any CI tool.
The working model
Continuous integration (CI) is the practice of merging every developer's changes into a shared branch frequently, and automatically verifying each change when it arrives. The shared branch is usually called main or trunk. "Verifying" means a server, not a person, builds the code and runs the tests, then reports pass or fail.
Two ideas make up CI, and both are needed:
- Integrate often. Changes reach the shared branch in hours or a day or two, not weeks.
- Verify automatically. Every proposed change triggers the same build and test steps on a clean machine.
Teams that only do the second idea have a build server but still suffer long-lived branches. Teams that only do the first merge quickly but find breakage by hand, usually late.
Why integration hurts when it is delayed
Two developers can each change code that works alone, and the combination can still fail. One renames a function while the other adds a new call to the old name. Each developer's tests pass on their own branch. The failure appears only when the changes meet.
The cost of finding such a conflict grows with the time between the two changes:
- Textual merge conflicts get larger as branches drift apart.
- Semantic conflicts, like the rename above, give no warning from Git. The merge succeeds and the build breaks.
- The author has forgotten the details of a change that is three weeks old, so debugging is slower.
CI shrinks this gap. If each change is small and merges within a day, a failure points at a small diff written recently.
The core practices
CI is a set of habits as well as a tool. These are the habits that make the tool useful.
- Keep one shared mainline. Everyone merges to the same branch. Short-lived feature branches are fine. Branches that live for weeks defeat the purpose.
- Commit small and often. A pull request that changes 40 lines is easy to review and easy to fix when it fails.
- Make the build self-contained. One command, or one pipeline, should take a fresh checkout to a tested result, with no manual setup steps.
- Keep the build fast. The usual target is under about ten minutes. Slow feedback makes people batch their changes, which brings back large merges.
- Fix a broken mainline first. When
maingoes red, repairing or reverting is the team's top priority, because every other change is now being verified against a broken base. - Run checks on a clean environment. A fresh runner has none of the files, tools, or environment variables on a developer's laptop, so it exposes "works on my machine" problems.
A minimal CI workflow
This GitHub Actions workflow checks out the code, installs dependencies, and runs the tests on every push to main and every pull request. Save it as .github/workflows/ci.yml.
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm testHere is what each part does:
onlists the triggers. Apushtomainverifies code that has just merged. Apull_requestevent verifies a proposed change before it merges, which is where most of the value is.runs-on: ubuntu-latestselects a fresh virtual machine for the job. It is discarded afterwards.actions/checkout@v4copies the repository onto that machine. Without it, the runner has no code.actions/setup-node@v4installs Node.js 20. Thecache: npmoption stores downloaded packages between runs, which shortens install time.npm ciinstalls exactly the versions inpackage-lock.json. Unlikenpm install, it fails if the lock file andpackage.jsondisagree, and it never rewrites the lock file. That makes runs repeatable.npm testruns the test suite. If it exits with a non-zero status, the step fails, the job fails, and the commit is marked red.
Each run step stops the job at the first failure, so later steps do not execute after a failed one.
What happens on each change
The second run on main matters. Another change may have merged after your pull request was last tested, so the combination on main has not been verified until that run finishes.
Common errors
Treating a red build as normal. If the team ignores failures, people stop trusting the signal. Branch protection rules that require passing checks before merging make the signal binding instead of advisory.
Flaky tests. A flaky test passes and fails on the same code. Typical causes are timing assumptions, shared state between tests, dependence on test order, and calls to real external services. Reflexively re-running hides the problem and teaches people to distrust failures. Quarantine or fix flaky tests quickly, and track how often each one fails.
Missing lock files. If dependencies are not pinned, the same commit can build today and fail tomorrow because a transitive package released a new version. Commit the lock file and install from it.
Tests that need the developer's environment. A test that reads a file in your home directory or assumes a database on localhost will fail on the runner. Create what the tests need inside the workflow, for example with service containers, or replace the dependency with a test double.
Wrong trigger. If you only trigger on push to main, you find problems after merging. Include pull_request so you find them before.
Slow pipelines. A thirty-minute check encourages large, infrequent merges. Use caching, run independent jobs in parallel, and keep slow tests out of the per-change path where you can.
Edge cases
Pull requests from forks. For security, workflows triggered by forked pull requests usually run with a read-only token and no access to repository secrets. A test that needs a secret, such as an API key, will fail for outside contributors. Design tests so the default CI path does not need secrets.
What gets tested on a pull request. On GitHub, the pull_request event runs against a temporary merge of the branch into the current base, not the branch tip alone. This is useful because it tests the combination. It also means a pull request can turn red without any new commits, because the base moved.
Stale approvals and merge queues. Two pull requests can each pass on their own and still break main together. Requiring branches to be up to date before merging, or using a merge queue that tests each change on top of the queued ones, closes this gap at the cost of extra runs.
Duplicate runs. If you trigger on both push and pull_request for all branches, a push to an open pull request starts two runs. Restricting push to main, as the workflow above does, avoids this.
Concurrency. Rapid pushes to one branch queue up runs for commits nobody cares about anymore. Most CI systems can cancel in-progress runs when a newer commit arrives.
Where CI stops
CI answers the question "does this change integrate and pass our checks?" It does not decide how code reaches users. Packaging the output for reuse, promoting it through environments, and releasing it are the subjects of later chapters. This chapter's workflow stops at a verified commit, which is the starting point for those steps.
Exercise
Your team's workflow triggers only on push to main. Last week, two broken changes reached main and blocked everyone for an hour. Name one change to the trigger configuration and one team practice that would reduce this. Explain why each works.
Show answer
Add a pull_request trigger so the build and tests run before merge, and make that check required through branch protection so a red change cannot merge. The failure is then found on the proposed change, not on the shared branch. For the practice, keep pull requests small and merge them often, and have the team fix or revert a red main before doing other work. Small changes make failures easy to locate, and an immediate fix limits how long the broken base blocks others.