TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Incremental Builds & the Action Cache

Incremental Builds & the Action Cache

Make decides what to rebuild by comparing timestamps (Incremental Builds in Build Fundamentals). Bazel compares content. For every action it computes an action key from:

  • the command line (arguments) and the environment variables the action gets,
  • the digests (SHA-256 by default) of every declared input file,
  • the declared output paths, the execution platform and a few other properties.

If the key and the output digests match what the action cache recorded last time, the action is skipped. Three consequences follow directly:

Event Make Bazel
touch a source file (same content) rebuilds nothing
change a comment in a .cc file rebuild + relink everything downstream recompile that file; if the object file comes out identical, stop there
change a compiler flag often nothing (flags aren't inputs) every affected action reruns
switch branches and back rebuild everything touched outputs from before are cache hits again (with a disk or remote cache)

The second row is called early cutoff: when an action's output is byte-identical to before, the actions that consume it see unchanged inputs and don't run.

A model of action keys

python · try it yourself
import hashlib

def digest(data):
    return hashlib.sha256(data.encode()).hexdigest()[:12]

def action_key(argv, inputs, env):
    """inputs: {path: content}. Paths and digests, not timestamps."""
    parts = ["argv=" + " ".join(argv), "env=" + repr(sorted(env.items()))]
    parts += [f"in={p}:{digest(c)}" for p, c in sorted(inputs.items())]
    return digest("\n".join(parts))

def compile_cc(src, flags):
    """A fake compiler: drops comments, so a comment-only edit gives the same object."""
    code = "\n".join(l for l in src.splitlines() if not l.strip().startswith("//"))
    return "OBJ[" + digest(code + repr(flags)) + "]"

cache = {}
def run(name, argv, inputs, env, fn):
    key = action_key(argv, inputs, env)
    if key in cache:
        print(f"  {name:8} cache hit   key={key}")
        return cache[key]
    out = fn()
    cache[key] = out
    print(f"  {name:8} executed    key={key}")
    return out

def build(src, flags):
    env = {"PATH": "/bin:/usr/bin:/usr/local/bin"}
    obj = run("compile", ["gcc", *flags, "-c", "main.cc"], {"main.cc": src}, env, lambda: compile_cc(src, flags))
    run("link", ["gcc", "-o", "app", "main.o"], {"main.o": obj}, env, lambda: "EXE")

v1 = "// version 1\nint main() { return 0; }"
print("first build:");                 build(v1, ["-O0"])
print("same content again (a touch):"); build(v1, ["-O0"])
print("comment changed:");             build(v1.replace("version 1", "version 2"), ["-O0"])
print("flag changed:");                build(v1, ["-O2"])
first build:
  compile  executed    key=334d25c0a6e1
  link     executed    key=4e51b0896dba
same content again (a touch):
  compile  cache hit   key=334d25c0a6e1
  link     cache hit   key=4e51b0896dba
comment changed:
  compile  executed    key=f708a0cb9cec
  link     cache hit   key=4e51b0896dba
flag changed:
  compile  executed    key=db20cf6e00b8
  link     executed    key=c80ca536ba8e

The comment edit changed the compile key, so the compile ran, but the produced object was the same, so the link key was already in the cache. That's early cutoff in miniature.

The real thing, with --explain

--explain=FILE makes Bazel write why each action ran; --verbose_explanations adds detail:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p lib app
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "math", srcs = ["math.cc"], hdrs = ["math.h"], visibility = ["//visibility:public"])\n' > lib/BUILD.bazel
printf '#pragma once\nint triple(int x);\n' > lib/math.h
printf '#include "lib/math.h"\n// version 1\nint triple(int x) { return 3 * x; }\n' > lib/math.cc
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "app", srcs = ["main.cc"], deps = ["//lib:math"])\n' > app/BUILD.bazel
printf '#include <cstdio>\n#include "lib/math.h"\nint main() { std::printf("%%d\\n", triple(14)); }\n' > app/main.cc
explain() { bazel build --explain=why.log --verbose_explanations //app 2>&1 | grep -E 'process'; grep '^Executing' why.log | grep -v BazelWorkspaceStatus | sed 's/: action changed.*/: changed/' | sort ; }
bazel build //app 2>&1 | grep -E 'process'
echo "== touch (same content)";  touch lib/math.cc; explain
echo "== comment only";          sed -i 's/version 1/version 2/' lib/math.cc; explain
echo "== real change";           sed -i 's/3 \* x/4 * x/' lib/math.cc; explain
echo "== header change";         echo '// docs' >> lib/math.h; explain
INFO: 8 processes: 5 internal, 3 processwrapper-sandbox.
== touch (same content)
INFO: 1 process: 1 action cache hit, 1 internal.
== comment only
INFO: 2 processes: 1 action cache hit, 1 internal, 1 processwrapper-sandbox.
Executing action 'Compiling lib/math.cc': changed
== real change
INFO: 4 processes: 2 internal, 2 processwrapper-sandbox.
Executing action 'Compiling lib/math.cc': changed
Executing action 'Linking app/app': changed
Executing runfiles for //app:app: changed
== header change
INFO: 3 processes: 1 action cache hit, 1 internal, 2 processwrapper-sandbox.
Executing action 'Compiling app/main.cc': changed
Executing action 'Compiling lib/math.cc': changed

Reading it:

  • touch: Bazel noticed the file's metadata changed, hashed it again, and found the same digest; the compile was an action cache hit and nothing ran. A new timestamp with the same content isn't a change.
  • comment only: Compiling lib/math.cc ran (its input changed) and produced the same object file (fastbuild has no debug info with line numbers), so there was no archive and no link: early cutoff.
  • real change: compiling lib/math.cc gave a different object, so the link (and the runfiles tree of the binary) reran too. (A fastbuild cc_binary links the library's object files directly, so no archive step is involved.)
  • header change: both compiles include math.h, so both reran, and the objects didn't change (only a comment was added), so nothing else did.

Note: N action cache hit in the summary counts actions whose key Bazel found in its local action cache after deciding to check them (for example after bazel clean keeps the action cache but drops outputs, or when outputs come back from a branch switch). When nothing changed at all, Bazel doesn't even get that far: the Skyframe graph in the server's memory knows the outputs are current.

Two levels of incrementality

Level Lives in Survives
Skyframe (analysis + execution graph) the Bazel server's memory until the server stops or the configuration changes ("discarding analysis cache")
Action cache (keys → output digests) the output base on disk bazel shutdown, not bazel clean (clean deletes outputs, clean --expunge everything)
Disk / remote cache (action results + file contents) a directory or a server everything; shared across workspaces, branches, machines

The next two lessons add the third level.

Test yourself

You run touch on a source file without changing it. What does Bazel rebuild?

  1. The file and everything downstream
  2. Nothing, because action keys use content digests, not timestamps
  3. Only the link
  4. Everything

What is 'early cutoff'?

  1. Stopping a build after the first error
  2. When an action reruns but produces identical output, its dependents don't rerun
  3. Killing slow actions
  4. Skipping tests

Which flag writes the reason each action was executed to a file?

  1. --announce_rc
  2. --explain=FILE (with --verbose_explanations for detail)
  3. --subcommands
  4. --profile