Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·43

Build Systems

Companion to Volume 3, chapter 43: how a build's jobs, Maven, Gradle and the speed-and-trust machinery (up-to-date checks, caches, hermetic tasks, reproducible builds) connect; new angles (a build as a kitchen's prep list, an input as anything that could change the dish, a cache as yesterday's prep reused); what the chapter simplifies, measured with Gradle 8.14 on TiffinBox and with the build's stage 44: a test task that stayed UP-TO-DATE after the file it checks was broken, a compiler plugin that Gradle tracks only if it's given as a property (and refuses otherwise), skipping by content hash that only works because the jars are reproducible, and a public API check that would have caught stage 42's record change; the theory behind them (build systems as memoisation, early cutoff, Merkle hashing); how Gradle refuses a compiler argument it can't track, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 43 has five parts: what a build system does (jobs and models), Maven (the POM, lifecycle and plugins, scopes, dependencyManagement and BOMs, repositories, multi-module builds), Gradle (the model, configurations, version catalogs, resolution controls, locking, reproducible builds, caching and incremental builds), other ecosystems and CI builds.

what a build does Maven Gradle speed and trust the jobs compile, test, package, publish a task graph inputs to outputs dependencies fetch, resolve, scope CI builds clean, cached, the same the POM coordinates, parent lifecycle and plugins phases bind goals BOMs, dependencyManagement one version, on purpose multi-module builds a reactor Gradle's model tasks, plugins, DSL configurations api, implementation catalogs, constraints platforms, locking compile avoidance the ABI, not the bytes up-to-date checks inputs unchanged the build cache outputs by input hash hermetic tasks declare every input reproducible builds same inputs, same bytes as needs run in drives with across declares pinned by enables extended by safe only if gives builds on: ch42 modules and packaging · goes on: ch47 Spring Boot (its plugins) · ch54 backend testing · Vol 8 CI/CD exercises: P1–P9 configurations, incremental builds, the cache, BOMs and locking, Maven, other ecosystems, reproducibility, CI; C1–C3
Concept map of chapter 43, build systems: what a build system does (jobs, task graphs and models), Maven (the POM, lifecycle, phases, goals and plugins, scopes, dependencyManagement and BOMs, repositories, multi-module builds), Gradle (the model, configurations, version catalogs, resolution controls, locking, reproducible builds, caching and incremental builds), other ecosystems and CI builds, with links such as declared inputs making skipping safe and one version decided on purpose.

The links worth remembering:

  • A build is a graph from inputs to outputs. Every speed feature (up-to-date checks, incremental compilation, the build cache) is "skip a step whose inputs haven't changed". Every one is only as correct as the list of inputs.
  • Versions are decided once, on purpose. BOMs, platforms, constraints and lock files exist so that the graph of dependencies gives one answer, today and next month.
  • Speed and trust come from the same discipline. Declared inputs make skipping safe; the same declarations make outputs reproducible and cacheable across machines.

Explain it differently

1. A build is a kitchen's prep list. "Chop onions" needs onions and gives chopped onions. If nothing about the onions changed since this morning, the chopped ones in the fridge will do. A build tool keeps that list for every step, and skips the steps whose ingredients are the same as last time.

2. An input is anything that could change the dish. Not only the ingredients on the recipe card: the oven, the salt in the drawer, the weather if the dough is proving. If the cook doesn't count the salt as an ingredient, a dish made with new salt is served from yesterday's batch (Gaps 1).

3. The build cache is yesterday's prep, from any kitchen. If another branch of the restaurant prepped exactly these ingredients the same way, you can use their prep. The label on the container has to list everything that went in, or you'll use someone else's mistake.

4. Early cutoff: the same sauce from a new pan. If you remake the sauce and it tastes exactly the same, nobody downstream needs to remake their dishes. A build that compares results (hashes of outputs) rather than times stops there (Gaps 3).

5. An API file is the menu printed for the regulars. The kitchen can change how it cooks a dish; changing what's on the menu needs a decision, a note and a new printing (Gaps 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Gradle 8.14.3 on OpenJDK 21.0.12 (offline, the java plugin only, TiffinBox's core and server copied into a Gradle build in exp/44) and the build's stage 44, unless stated.

1. A built-in test task can serve a stale pass too. The exercises show a custom task with an undeclared input. TiffinBox's ContractTest is an ordinary JUnit test run by Gradle's own test task. It reads contract/api.json, whose path comes in as a system property. Remove RefundDue from the contract, which the server still sends, so the test must fail:

Terminal
== the contract as it is
    > Task :server:test UP-TO-DATE
    BUILD SUCCESSFUL in 948ms
== RefundDue removed from the contract (the server still sends it, so the test must now fail)
    > Task :server:test UP-TO-DATE
    BUILD SUCCESSFUL in 880ms
== the same, after declaring the file: inputs.file(...)
    > Task :server:test
    ContractTest > everyResponseTypeMatchesTheContract() FAILED
    5 tests completed, 1 failed
    > Task :server:test FAILED

Gradle records the system property's value, a path, and that didn't change. The test passed without running, against a contract the code no longer meets. Nothing in the build script was custom or unusual; the test simply opened a file. Any test that reads fixtures, golden files, schemas or rules from outside its source set has this hole until the files are declared. The build cache makes it worse: the stale pass travels to other machines.

2. A compiler plugin is an input, and Gradle won't take it as a string. TiffinBox compiles with LangLint, a javac plugin, passed as -processorpath … -Xplugin:LangLint. Copied into Gradle as compiler arguments, the build refused to start:

Terminal
> Java compilation initialization error
    Cannot specify -processorpath or --processor-path via `CompileOptions.compilerArgs`. Use the `CompileOptions.annotationProcessorPath` property instead.

As strings, a changed langlint.jar would have been invisible (Gaps 1 again). As a property, its contents are fingerprinted, and changing the plugin meant recompiling everything:

Terminal
nothing changed                                 956 ms
    > Task :core:compileJava UP-TO-DATE
the lint plugin's jar changed                  1580 ms
    > Task :core:compileJava
      Input property 'options.annotationProcessorPath' file /tmp/w/g/lint.jar has changed.
    Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments.

Correct, and expensive at scale: a new lint rule recompiles every module in a monorepo. That's a reason to keep analysers in their own task (Error Prone in a separate check, or a lint task over compiled classes, like stage 41's ClassScan) when the codebase is large.

3. Skipping by content only works if outputs are reproducible. The chapter shows that the build cache keys on input hashes. The other half: a step whose output is byte-for-byte the same as last time shouldn't make anything downstream rebuild. Stage 44's tools/build.sh hashes inputs, including the jars of upstream modules. Add a public method to core (the API check stops the build), then remove it again:

Terminal
== the method removed again
  tools/lint  up to date
  core        building (changed: its last build failed)
  core        built in 6 s
  core's API: unchanged (524 lines)
  tools/tbx   up to date
  server      building (changed: contract/api.json)

Core was rebuilt, its jar came out identical (stage 30's fixed dates, stage 43's pinned JDK), so tbx didn't rebuild. The server rebuilt only because the scenario had also restored contract/api.json. With a timestamp in the jar, every core rebuild would rebuild everything after it. A whole-jar hash is cruder than Gradle's compile avoidance, which compares only the ABI (in Gradle, a method body edit left the server UP-TO-DATE); it is still the difference between 6 seconds and 75.

4. The ABI the build tracks is the API your users depend on. Compile avoidance treats public signatures as the interface between modules. Write that interface down and it becomes reviewable. Stage 44 dumps core's public types and members, record components included, into core/api.txt, and the build fails when they differ. Run against stage 42's change:

Terminal
core's API changed. If that is meant, run tools/build.sh --accept-api and commit core/api.txt with a note in VERSION's next release.
  - in.tiffinbox.core.IdempotencyKey components(java.lang.String hex)
  + in.tiffinbox.core.IdempotencyKey components(long hi, long lo)
  + in.tiffinbox.core.IdempotencyKey method long hi()
  + in.tiffinbox.core.IdempotencyKey method long lo()
  + in.tiffinbox.core.IdempotencyKey new(long, long)

That's the change chapter 42's companion found to be binary compatible but source incompatible. Stage 42 made it without anyone deciding it was an API change. Kotlin's binary-compatibility validator, japicmp and Metalava do the same for real libraries; the committed file makes every change to it show in code review.

Common misconceptions

Misconception What's actually true Where it's shown
"Gradle always runs the tests when something changed." Only when something it knows about changed. Gaps 1
"A system property pointing at a file makes the file an input." Only the path is. Declare the file. Gaps 1
"Compiler arguments are just strings." Paths in them are inputs; Gradle refuses the ones it can't track. Gaps 2
"A new lint rule is a cheap change." It changes every compile task's inputs. Gaps 2
"Content hashing needs nothing from the outputs." It needs them reproducible, or every rebuild cascades. Gaps 3
"If it compiles, the API didn't change." Record components and new members change it; only a recorded API shows that. Gaps 4
"A method body edit recompiles the callers." Not with compile avoidance; only ABI changes do. Chapter lab, Experiment 1
"A cached result is always right." Only if every input was declared. Exercises P3

Theoretical gaps: the ideas behind the chapter

1. A build system is memoisation of a pure function. Mokhov, Mitchell and Peyton Jones's "Build Systems à la Carte" (2018) describes every build system as two choices: a scheduler (in what order to run tasks: topological like Make and Gradle, restarting like Bazel, or suspending like Shake) and a rebuilder (how to decide whether a task is up to date: dirty bits, verifying traces of input hashes, or constructive traces that store outputs, which is a build cache). Correctness needs every task to be a function of its declared inputs; Gaps 1 is a task that wasn't.

2. Early cutoff. When a rebuilt task's output equals the old output, its dependents need not rebuild. Make can't do this (it compares timestamps); Shake, Bazel and hash-based builds can. Gaps 3 is early cutoff, and it only pays when outputs are deterministic.

3. Merkle hashing. A task's key is a hash over its inputs' hashes, and upstream outputs are inputs, so a key summarises the whole history that produced it (as a Git commit does). That is why a remote cache can be shared safely between machines, and why one undeclared input poisons every key built on it.

4. Hermeticity and tracing. Bazel enforces declared inputs with a sandbox: a file not declared isn't there. Other tools trace instead: Tup records which files each command actually reads, and strace does the same by hand, as stage 44 uses it (tools/build.sh --trace), check that what a step actually opened is what it declared. A sandbox prevents the mistake; a trace detects it.

Applying it

Code walkthrough

Gaps 2's refusal is a few lines in Gradle. From gradle/gradle at v8.14.3, platforms/jvm/language-java/src/main/java/org/gradle/api/internal/tasks/compile/JavaCompilerArgumentsBuilder.java.

Validating before compiling

Java
        List<Object> compilerArgs = Cast.uncheckedCast(spec.getCompileOptions().getCompilerArgs());
        List<String> compArgs = compilerArgs
            .stream()
            .map(Object::toString)
            .collect(Collectors.toList());

        validateCompilerArgs(compArgs);

        addLauncherOptions();
        addMainOptions(compArgs);
        addClasspath();
        addUserProvidedArgs(compArgs);
        addSourceFiles();

Gradle builds javac's command line itself: options from the task's properties (release, encoding, the processor path), the class path, the user's extra arguments, then the sources. Before any of it, the user's arguments are checked.

The two arguments it won't accept

Java
    private void validateCompilerArgs(List<String> compilerArgs) {
        for (String arg : compilerArgs) {
            if ("-sourcepath".equals(arg) || "--source-path".equals(arg)) {
                throw new InvalidUserDataException("Cannot specify -sourcepath or --source-path via `CompileOptions.compilerArgs`. " +
                    "Use the `CompileOptions.sourcepath` property instead.");
            }

            if ("-processorpath".equals(arg) || "--processor-path".equals(arg)) {
                throw new InvalidUserDataException("Cannot specify -processorpath or --processor-path via `CompileOptions.compilerArgs`. " +

Both name directories or JARs whose contents change what javac produces. Given as properties, they are fingerprinted inputs (and the processor path also decides whether incremental compilation is possible). Given as strings, they would be compared as strings. Gradle chose to fail loudly for these two. It can't do that for every path a user might smuggle in: a path in -Xplugin: options, a system property for a test (Gaps 1), an environment variable (Exercises P3). Those are the build author's job to declare.

Debugging drills

D1. Green on CI, red on a laptop

CI's build is green and its test task was FROM-CACHE. A developer who runs the same commit with --no-build-cache gets a failing test that checks responses against a JSON schema in a schemas/ directory.

D2. Every build recompiles everything

After a platform team added a shared Error Prone check, every developer's incremental build of a 60-module repository takes 9 minutes instead of 40 seconds, for a while, and then becomes fast again.

D3. A one-line change rebuilds the world

In a hand-written build (shell scripts with hash-based skipping), changing a log message in a base library rebuilds all 30 services, even though no service's code changed.

D4. A library changed, and nobody noticed

Consumers of an internal library start failing to compile after a minor version upgrade: a record they deconstruct gained a component. The library's changelog doesn't mention it.

Career-oriented

Interview prep

Mid-level 1: Maven's lifecycle in one sentence each

Question. "What happens when you run mvn verify?"

How to get there. Phases, and what plugins bind to them.

Mid-level 2: api or implementation

Question. "In Gradle, when do you declare a dependency as api rather than implementation?"

How to get there. Who sees the types, and what recompiles.

Senior 1: a fast build that's wrong

Question. "Our builds got 4× faster with the remote build cache, but twice this quarter a release shipped with a test that would have failed. What do you do?"

How to get there. Find the undeclared inputs, then make them impossible to miss.

Senior 2: when to write your own build logic

Question. "A team wants to replace 2,000 lines of Gradle plugins with shell scripts, because 'nobody understands the plugins'. What would you advise?"

How to get there. What the tool gives for free that scripts must rebuild, and what's actually wrong.

Staff 1: a monorepo's build at scale

Question. "Our monorepo has 400 modules and CI takes 45 minutes. Plan the next year."

How to get there. Measure where time goes, then cut work, then cache, then parallelise.

Staff 2: provenance of what you build

Question. "Security wants every artifact to say exactly what went into it. How does the build provide that?"

How to get there. Inputs you already track, plus where they're recorded and signed.