View as Markdown

Scopes with Bazel

Compute scopes from Bazel's dependency graph with bazel-diff so every impacted package is reported.


Bazel knows the entire dependency graph of your monorepo, which makes it a good source of scopes, as long as the query asks which targets a pull request can break rather than which packages hold the files it touched.

bazel-diff answers that question. It hashes every target in the graph at two revisions (over the target’s own content, its rule attributes and its transitive dependencies), then reports the targets whose hash changed. That is the impacted set, and its packages are your scopes.

Here’s the whole setup running on a Bazel monorepo, from the scope detection step in CI to several packages testing in their own lanes at once:

To use the manual scopes mechanism, configure Mergify to expect scopes from your CI system:

.mergify.ymlyaml
scopes:
source:
manual:
queue_rules:
- name: default
batch_size: 5

Why the impacted set is not the changed set

Section titled Why the impacted set is not the changed set

Scopes are a safety mechanism: the queue keeps pull requests that share a scope apart, and the jobs gated on a scope skip the rest. A scope list that comes up short is therefore not merely imprecise: it lets the queue parallelize pull requests that conflict and lets those jobs skip work the change really did affect.

Queries built on changed file paths produce exactly that kind of short list. buildfiles() returns the BUILD and .bzl files needed to load the packages the changed files live in, which walks the graph away from the dependents instead of towards them: a change to a library reports the library and the packages defining the macros its BUILD file loads, not the packages that depend on the library. Reverse-dependency queries such as rdeps() close part of the gap but open another: a pull request that only edits BUILD or .bzl files has no changed target to start from, so the query returns nothing at all.

Detecting scopes with bazel-diff

Section titled Detecting scopes with bazel-diff

bazel-diff compares two revisions, so the job that computes scopes needs three things:

  • A JVM. bazel-diff ships as a single bazel-diff_deploy.jar on its releases page.

  • Full git history, so the base commit exists locally. With actions/checkout that means fetch-depth: 0; with filter: blob:none, each checkout fetches the file contents its revision needs.

  • A working tree it can move. Hashes are generated once per revision, so the job checks out the base, then the head.

The detection itself is three bazel-diff commands, run against the merge-queue-aware $BASE and $HEAD revisions each pipeline resolves for itself:

Terminal windowbash
curl -fsSL -o /tmp/bazel-diff.jar \
"https://github.com/Tinder/bazel-diff/releases/download/v42.0.0/bazel-diff_deploy.jar"
echo "0170b70fe2f24477ab056c11f5c3240d8b45a1dca5ab73ad252c096679c5500c /tmp/bazel-diff.jar" \
| sha256sum -c - || exit 1
git checkout --quiet --force --end-of-options "$BASE" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/base-hashes.json || exit 1
git checkout --quiet --force --end-of-options "$HEAD" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/head-hashes.json || exit 1
# The impacted targets land in a file rather than straight into the awk
# pipeline: a pipeline reports its last command's status, so a failed
# bazel-diff would go unnoticed and leave an empty scope list.
java -jar /tmp/bazel-diff.jar get-impacted-targets \
--workspacePath "$(pwd)" --targetType Rule \
--startingHashes /tmp/base-hashes.json --finalHashes /tmp/head-hashes.json \
> /tmp/impacted.txt || exit 1
awk -F: '/^\/\// { print $1 }' /tmp/impacted.txt | sort -u

A few details worth knowing:

  • --targetType Rule keeps rules and drops the source and generated files that share their packages. --includeTargetType on generate-hashes is what records the type, so the two flags go together.

  • The awk turns each impacted label into its package label, so //lib/core:core becomes //lib/core and a target in the root package becomes //. It also drops labels from external repositories, which are not yours to queue on.

  • Scoping on packages rather than targets is a choice, and yours to change: drop the -F: and print the whole label to get the finer grain, keeping the /^\/\// filter so external labels stay out. Either grain can be given a capacity of its own with scopes.capacities, which takes any name the scopes API accepts.

  • git checkout --force is deliberate: bazel writes to MODULE.bazel.lock, and a plain checkout refuses to move over the modified file. Run this on a CI checkout, not a working tree you care about.

Running bazel-diff as a service removes the download and checkout, plus both hashing runs.

bazel-diff is a Bazel module, so a workspace already on Bzlmod can declare it instead of downloading anything:

bazel
bazel_dep(name = "bazel-diff", version = "42.0.0")
Terminal windowbash
bazel run @bazel-diff//cli:bazel-diff -- generate-hashes --workspacePath "$(pwd)" hashes.json

That is the install bazel-diff recommends. Every pipeline here uses the released JAR regardless: they check out two revisions of your workspace, and bazel run @bazel-diff//... resolves against whichever MODULE.bazel is checked out at the time, which at $BASE may pin a different version or not declare bazel-diff at all.

Each pipeline downloads a JAR over the network and runs it with the same privileges as the rest of the job, so the first command names exactly what runs: the URL points at a version instead of latest, and sha256sum -c checks the bytes behind it. Recompute the digest when you bump the version:

Terminal windowbash
sha256sum bazel-diff_deploy.jar # shasum -a 256 on macOS

The release also ships SLSA provenance beside the JAR, which says the artifact came out of the project’s own release workflow. The GitHub CLI checks it and exits non-zero if the provenance does not hold:

Terminal windowbash
curl -fsSL -o /tmp/bazel-diff.jar.intoto.jsonl \
"https://github.com/Tinder/bazel-diff/releases/download/v42.0.0/bazel-diff_deploy.jar.intoto.jsonl"
gh attestation verify /tmp/bazel-diff.jar \
--bundle /tmp/bazel-diff.jar.intoto.jsonl \
--repo Tinder/bazel-diff --signer-repo bazel-contrib/.github
yaml
name: Detect Scopes
on:
pull_request:
jobs:
detect-scopes:
runs-on: ubuntu-26.04
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v5
with:
# The queue-aware base commit must exist locally to be checked out.
fetch-depth: 0
# Every commit, without the file contents of past revisions. Leave
# it out with persist-credentials: false, or if a later step reads
# file history (git blame, git log -p): git fetches each missing
# file on demand, one round trip at a time, with the job's token.
filter: blob:none
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- name: Get git refs
id: refs
uses: Mergifyio/gha-mergify-ci@v33
with:
action: scopes-git-refs
- name: Get scopes
id: scopes
env:
HEAD: ${{ steps.refs.outputs.head }}
BASE: ${{ steps.refs.outputs.base }}
run: |
# scopes-git-refs reports an empty base on any event that is neither
# a pull request nor a push. Checking out an empty revision, or
# letting the tool fall back to a default base, reports scopes for
# the wrong range.
[ -n "$BASE" ] || { echo "no base ref reported" >&2; exit 1; }
curl -fsSL -o /tmp/bazel-diff.jar \
"https://github.com/Tinder/bazel-diff/releases/download/v42.0.0/bazel-diff_deploy.jar"
echo "0170b70fe2f24477ab056c11f5c3240d8b45a1dca5ab73ad252c096679c5500c /tmp/bazel-diff.jar" \
| sha256sum -c - || exit 1
git checkout --quiet --force --end-of-options "$BASE" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/base-hashes.json
git checkout --quiet --force --end-of-options "$HEAD" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/head-hashes.json
# The impacted targets land in a file rather than straight into the awk
# pipeline: a pipeline reports its last command's status, so a failed
# bazel-diff would go unnoticed and upload an empty scope list.
java -jar /tmp/bazel-diff.jar get-impacted-targets \
--workspacePath "$(pwd)" --targetType Rule \
--startingHashes /tmp/base-hashes.json --finalHashes /tmp/head-hashes.json \
> /tmp/impacted.txt || exit 1
scopes=$(awk -F: '/^\/\// { print $1 }' /tmp/impacted.txt | sort -u | paste -sd, -)
echo "scopes=$scopes" >> "$GITHUB_OUTPUT"
- name: Scopes upload
uses: Mergifyio/gha-mergify-ci@v33
with:
action: scopes-upload
scopes: ${{ steps.scopes.outputs.scopes }}

Grant id-token: write to the job, or to the whole workflow. The job then trades its GitHub-signed ID token for a Mergify OIDC CI token, and no MERGIFY_TOKEN is stored:

yaml
permissions:
id-token: write # lets the job ask GitHub for an ID token
contents: read # actions/checkout needs it

A permissions block sets every permission it does not list to none: list the ones your other steps need too.

Mergify refuses the ID token until a trust policy of your organization matches the job. A GitHub organization Owner or a CI Admin writes one under Settings → Security & Access → CI Authentication → Trust Policies on the dashboard. OIDC Authentication covers trust policies, pull requests from forks and refused exchanges. If your workflows store MERGIFY_TOKEN today, move them off it.

Other CIs authenticate with a ci application key, and so do the GitHub Actions jobs OIDC leaves out: runs for pull requests from forks when your organization sends them secrets, and jobs that send scopes from the base branch (pull_request_target, workflow_run, issue_comment). Store the key as the MERGIFY_TOKEN repository secret and set it on the job:

yaml
env:
MERGIFY_TOKEN: ${{ secrets.MERGIFY_TOKEN }}

A MERGIFY_TOKEN that is set wins over the ID token. For pull requests from forks, set it on those runs only and drop the fork condition from the upload step, as Jobs that keep a key shows. Store the key in your Dependabot secrets too, since runs for Dependabot pull requests read only those.

Using the mergifyio/mergify-ci Buildkite plugin, a first step resolves the merge-queue-aware base and head SHAs and exposes them as meta-data, a second computes the impacted packages with bazel-diff into the mergify-ci.scopes meta-data, and a third uploads them. The upload runs in its own step because the plugin replaces the step’s command, so a step that both detects and uploads never runs its detection:

yaml
steps:
- label: ":mag: Get git refs"
key: git-refs
plugins:
- mergifyio/mergify-ci#v27:
action: scopes-git-refs
- label: ":mag: Detect scopes"
key: detect-scopes
depends_on: git-refs
command: |
# The base meta-data is only published when a base was resolved, so a
# missing key means there is no base to check out. Check the value too:
# an empty one would send the tool back to a default base and report
# scopes for the wrong range.
BASE=$(buildkite-agent meta-data get "mergify-ci.base") || exit 1
HEAD=$(buildkite-agent meta-data get "mergify-ci.head") || exit 1
[ -n "$$BASE" ] || { echo "no base ref reported" >&2; exit 1; }
curl -fsSL -o /tmp/bazel-diff.jar \
"https://github.com/Tinder/bazel-diff/releases/download/v42.0.0/bazel-diff_deploy.jar"
echo "0170b70fe2f24477ab056c11f5c3240d8b45a1dca5ab73ad252c096679c5500c /tmp/bazel-diff.jar" \
| sha256sum -c - || exit 1
git checkout --quiet --force --end-of-options "$$BASE" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/base-hashes.json
git checkout --quiet --force --end-of-options "$$HEAD" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/head-hashes.json
# The impacted targets land in a file rather than straight into the awk
# pipeline: a pipeline reports its last command's status, so a failed
# bazel-diff would go unnoticed and upload an empty scope list.
java -jar /tmp/bazel-diff.jar get-impacted-targets \
--workspacePath "$(pwd)" --targetType Rule \
--startingHashes /tmp/base-hashes.json --finalHashes /tmp/head-hashes.json \
> /tmp/impacted.txt || exit 1
SCOPES=$(awk -F: '/^\/\// { print $$1 }' /tmp/impacted.txt | sort -u | paste -sd, -)
buildkite-agent meta-data set "mergify-ci.scopes" "$$SCOPES"
- label: ":mag: Upload scopes"
depends_on: detect-scopes
plugins:
- mergifyio/mergify-ci#v27:
action: scopes-upload

The plugin reads your application key from MERGIFY_TOKEN in the agent’s environment. Without it the step still runs, but it logs a warning and sends nothing, and the build stays green, so a missing token looks like a pipeline that reports no scopes.

Install the Mergify CLI in your pipeline and export MERGIFY_TOKEN, which a GitHub Actions job granted id-token: write does without. Use mergify ci git-refs to get the merge-queue-aware base and head SHAs and mergify ci scopes-send to upload the detected scopes:

Terminal windowbash
REFS=$(mergify ci git-refs --format json)
# -e so a null ref fails here instead of flowing on as the literal string
# "null": git-refs reports no base outside pull request and push events.
BASE=$(printf '%s' "$REFS" | jq -er '.base') || exit 1
HEAD=$(printf '%s' "$REFS" | jq -er '.head') || exit 1
curl -fsSL -o /tmp/bazel-diff.jar \
"https://github.com/Tinder/bazel-diff/releases/download/v42.0.0/bazel-diff_deploy.jar"
echo "0170b70fe2f24477ab056c11f5c3240d8b45a1dca5ab73ad252c096679c5500c /tmp/bazel-diff.jar" \
| sha256sum -c - || exit 1
git checkout --quiet --force --end-of-options "$BASE" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/base-hashes.json || exit 1
git checkout --quiet --force --end-of-options "$HEAD" -- || exit 1
java -jar /tmp/bazel-diff.jar generate-hashes \
--workspacePath "$(pwd)" --includeTargetType /tmp/head-hashes.json || exit 1
# The impacted targets land in a file rather than straight into the awk
# pipeline: a pipeline reports its last command's status, so a failed
# bazel-diff would go unnoticed and upload an empty scope list.
java -jar /tmp/bazel-diff.jar get-impacted-targets \
--workspacePath "$(pwd)" --targetType Rule \
--startingHashes /tmp/base-hashes.json --finalHashes /tmp/head-hashes.json \
> /tmp/impacted.txt || exit 1
awk -F: '/^\/\// { print $1 }' /tmp/impacted.txt | sort -u \
| jq -R -s '{scopes: split("\n") | map(select(length > 0))}' > scopes.json
mergify ci scopes-send --scopes-json scopes.json

Both commands read the pull request from the environment on GitHub Actions, Buildkite, and a Jenkins multibranch pipeline; Reporting scopes from Jenkins shows a complete stage. On any other CI, git-refs falls back to the last commit, HEAD^..HEAD, which misses the rest of the pull request, and scopes-send finds no pull request number, skips the upload, and still passes. There, diff from the merge base of the pull request's head commit and its target branch, and pass --pull-request with the number and --head-sha with the head commit, not a merge commit your CI built.

Two generate-hashes runs cost roughly two bazel query passes over the graph. On most repositories that is a small job, but there are ways to trim it:

  • Cache the base hashes. On pull_request events the base is usually the same commit across many pull requests. Storing base-hashes.json under a cache key derived from the base SHA removes one checkout and one hash from most runs.

  • Scope the content hashing. generate-hashes --modified-filepaths reads only the files listed in a changed-file list instead of every source file. The list must be a superset of what actually changed, or the targets behind a missing file are skipped, which is why the flag is still marked experimental.

Running bazel-diff as a service

Section titled Running bazel-diff as a service

For a workspace large enough that generate-hashes dominates the job, bazel-diff serve removes those runs rather than trimming them: a long-lived process holds its own clone of the workspace, caches the hashes it generates per commit SHA, and answers impacted-target queries over HTTP. The query service is experimental, and documented in the bazel-diff README.

Terminal windowbash
java -jar bazel-diff_deploy.jar serve \
--workspacePath /path/to/workspace-clone \
--cacheDir /var/cache/bazel-diff \
--port 8080

The CI step then drops the JVM, the second checkout and both hashing runs:

Terminal windowbash
curl -fsSL --get "http://bazel-diff.internal:8080/impacted_targets" \
--data-urlencode "from=$BASE" --data-urlencode "to=$HEAD" \
-o /tmp/impacted.json || exit 1
jq -r '.impactedTargets[]' /tmp/impacted.json | awk -F: '/^\/\// { print $1 }' | sort -u

The response is written to a file and the pipeline reads it back, so that a failed request stops the job. Piping curl straight into jq would hide it: an instance that answers 503 because it is still fetching leaves curl failing while jq succeeds on empty input, and the pull request goes up with no scopes at all.

What you take on in exchange is a service to run: a host, a clone to keep fetched, and a /health endpoint to route on, since an instance reports unhealthy until its first fetch finishes.

Changes the dependency graph cannot see

Section titled Changes the dependency graph cannot see

Some changes invalidate everything while leaving no trace in the graph: a .bazelrc edit, a CI image bump, a change to a toolchain that lives outside the workspace. Two mechanisms cover them.

On the Bazel side, list those files in a file passed to generate-hashes --seed-filepaths. Their content is mixed into every target hash, so editing one of them marks the whole graph impacted.

On the Mergify side, mark the pull request as a barrier instead of enumerating scopes. With gha-mergify-ci or the mergifyio/mergify-ci Buildkite plugin, set all_scopes: true on the scopes-upload action; with the CLI, pass --all to mergify ci scopes-send. The queue then serializes around that pull request.

When bazel-diff is more than you want

Section titled When bazel-diff is more than you want

bazel-diff costs a JVM and a second checkout. If that is more than the job is worth, prefer file-pattern scopes over a dependency-graph query you cannot trust: patterns are coarse, but they need no CI job at all and they never quietly claim a change is smaller than it is.

Was this page helpful?