TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Toolkit: CI, BuildBuddy & Affected Targets

Toolkit: CI, BuildBuddy & Affected Targets

Running bazel test //... on every commit is correct and, thanks to caching, often affordable. At scale, CI pipelines add three things: build event data (what happened, for dashboards and flaky-test tracking), affected-target computation (build and test only what a change can influence) and a results UI.

The Build Event Protocol

Every Bazel command emits a stream of build events: started, options, targets configured, actions, test results, build finished. You can write it to a file or stream it to a server:

Flag Destination
--build_event_json_file=bep.json newline-delimited JSON, for scripts
--build_event_binary_file=bep.pb protobuf, compact
--bes_backend=grpcs://remote.buildbuddy.io + --bes_results_url=… a Build Event Service: BuildBuddy, EngFlow, Buildbarn's bb-portal…
bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_python", version = "2.4.5")' > MODULE.bazel
mkdir -p t
cat > t/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "good_test", size = "small", srcs = ["good_test.py"])
py_test(name = "bad_test", size = "small", srcs = ["bad_test.py"])
EOF
echo 'print("fine")' > t/good_test.py
echo 'raise SystemExit("broken")' > t/bad_test.py
bazel test //t:all --build_event_json_file=bep.json >/dev/null 2>&1
echo "exit code: $?"
echo "== event kinds"
jq -r '.id | keys[0]' bep.json | grep -v '^progress
  

 | sort | uniq -c | sort -k2 | awk '{print $2, $1}'
echo "== test summaries"
jq -r 'select(.id.testSummary) | "\(.id.testSummary.label) \(.testSummary.overallStatus)"' bep.json | sort
echo "== exit"
jq -r 'select(.id.buildFinished) | .finished.exitCode.name' bep.json
exit code: 3
== event kinds
buildFinished 1
buildMetadata 1
buildMetrics 1
buildToolLogs 1
configuration 1
convenienceSymlinksIdentified 1
namedSet 2
optionsParsed 1
pattern 1
started 1
structuredCommandLine 3
targetCompleted 2
targetConfigured 2
testResult 2
testSummary 2
unstructuredCommandLine 1
workspace 1
workspaceStatus 1
== test summaries
//t:bad_test FAILED
//t:good_test PASSED
== exit
TESTS_FAILED

(progress events, whose number depends on timing, are left out of the count.) bazel test exits with 3 when the build succeeded but tests failed (1 = build failure, 2 = bad command line, 4 = no tests found, 8 = interrupted), so CI can tell the cases apart. The JSON stream gives a CI script structured results without parsing logs; a BES server turns the same stream into a web page per invocation with timing, logs and cache statistics.

BuildBuddy and friends (not run here)

text
# .bazelrc
build:ci --bes_results_url=https://app.buildbuddy.io/invocation/
build:ci --bes_backend=grpcs://remote.buildbuddy.io
build:ci --remote_cache=grpcs://remote.buildbuddy.io
build:ci --remote_header=x-buildbuddy-api-key=<from CI secrets>
build:ci --build_metadata=ROLE=CI --build_metadata=REPO_URL=https://github.com/acme/shop

BuildBuddy, EngFlow and similar services combine a BES UI, a remote cache, remote execution and analytics (slowest targets, cache hit rate over time, flaky tests). Self-hosted options exist for all of them; the open-source bazel-remote + a BEP JSON archive is the minimal version.

Affected targets: build only what a change touches

For a pull request you want: which targets could produce different outputs because of these changed files? Two ways to answer it:

Approach How Catches
Query on changed files bazel query 'rdeps(//..., set(<changed files>))' source-file changes; misses changes to MODULE.bazel, .bazelrc, toolchains, macros
Hash the target graph (bazel-diff, Aspect's target-determinator) hash every target (attributes + inputs + transitive hashes) at both commits and diff everything that changes a target, including BUILD files, .bzl macros and external dependency versions

The query approach, for real:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p lib/strings lib/http app tools
lib() { printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "%s", srcs = ["%s.cc"], hdrs = ["%s.h"], deps = [%s], visibility = ["//visibility:public"])\n' "$2" "$2" "$2" "$3" > $1/BUILD.bazel; touch $1/$2.cc $1/$2.h; }
lib lib/strings strings ''
lib lib/http http '"//lib/strings"'
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "server", srcs = ["main.cc"], deps = ["//lib/http"])\n' > app/BUILD.bazel
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "lint", srcs = ["lint.cc"])\n' > tools/BUILD.bazel
touch app/main.cc tools/lint.cc
git init -q && git add -A && git commit -qm "base"
echo '// faster split' >> lib/strings/strings.cc
changed=$(git diff --name-only HEAD | tr '\n' ' ')
echo "changed: $changed"
bazel query "rdeps(//..., set($changed))" --output=label 2>/dev/null | grep -v '\.cc
  

changed: lib/strings/strings.cc
//app:server
//lib/http:http
//lib/strings:strings

The tool binary //tools:lint is not in the list, so CI can skip it. Feed the list to bazel build/bazel test (--target_pattern_file= takes a file of patterns). Mind the limits from the table: a change to .bazelrc, MODULE.bazel or a .bzl file should fall back to building everything, or use a graph-hashing tool.

Graph hashing, modelled

bazel-diff and target-determinator work like this model: every target's hash covers its own definition, its files and the hashes of its dependencies, so any change anywhere below a target changes its hash.

python · try it yourself
import hashlib

def H(*parts):
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:8]

def target_hashes(targets, files):
    memo = {}
    def h(name):
        if name not in memo:
            t = targets[name]
            memo[name] = H(name, repr(t["attrs"]), *[H(f, files[f]) for f in t["srcs"]], *[h(d) for d in t["deps"]])
        return memo[name]
    return {name: h(name) for name in targets}

files = {"strings.cc": "v1", "http.cc": "v1", "main.cc": "v1", "lint.cc": "v1"}
targets = {
    "//lib/strings": {"srcs": ["strings.cc"], "deps": [], "attrs": {"copts": []}},
    "//lib/http":    {"srcs": ["http.cc"], "deps": ["//lib/strings"], "attrs": {}},
    "//app:server":  {"srcs": ["main.cc"], "deps": ["//lib/http"], "attrs": {}},
    "//tools:lint":  {"srcs": ["lint.cc"], "deps": [], "attrs": {}},
}
before = target_hashes(targets, files)

def changed(after):
    return sorted(t for t in before if before[t] != after[t])

print("source edit in strings.cc:", changed(target_hashes(targets, {**files, "strings.cc": "v2"})))
targets["//lib/strings"]["attrs"] = {"copts": ["-O3"]}          # a BUILD-file change, no source change
print("copts change in BUILD:   ", changed(target_hashes(targets, files)))
source edit in strings.cc: ['//app:server', '//lib/http', '//lib/strings']
copts change in BUILD:    ['//app:server', '//lib/http', '//lib/strings']

The second case is the one the plain query misses: no source file changed, but the BUILD file did, and the hash approach still flags strings and everything above it.

Test yourself

What exit code does bazel test return when everything built but a test failed?

  1. 1
  2. 2
  3. 3
  4. 4

Why can rdeps(//..., set(changed files)) miss affected targets?

  1. query is slow
  2. Changes to BUILD/.bzl files, MODULE.bazel or flags don't appear as changed source files of targets
  3. It ignores tests
  4. It only works on Go

What is the Build Event Protocol used for?

  1. Remote execution
  2. A structured stream of what a Bazel command did, for CI scripts and results UIs
  3. Formatting BUILD files
  4. Lockfiles