ADR-039: cargo-chef for the Docker Dependency-Cache Layer
Status
Accepted 2026-06-20. Resolves #617. Supersedes the manual manifest-copy + stub-src dependency-cache scheme that had been in the Dockerfile builder stage since the early service images.
Amended 2026-09-21 — #1977 A3 (BuildKit cache mounts on the cook + build steps; the no-cache definition). See Amendment — #1977 A3 (2026-09-21).
Amended 2026-10-07 — #2136 (automatic rebuilds keep the cargo cache mounts; they are emptied only when the builder environment changed). See Amendment — #2136 (2026-10-07).
Amended 2026-11-08 — #3003 (a CI build cooks into a target directory inside the layer, so the registry cache carries the cooked dependencies; local builds keep the mount). See Amendment — #3003 (2026-11-08).
Amended 2026-11-10 — #3044, #3045, #3046 (the devstack images copy the one musl build’s binaries and compile nothing; the cook layer serves the release images, which release-build bakes; no CI build exports a registry cache). See Amendment — #3044–#3046 (2026-11-10).
Context
The multi-stage Dockerfile builder stage tried to cache the compiled dependency graph the conventional pre-cargo-chef way: copy every workspace member’s Cargo.toml, write a stub src/lib.rs/main.rs for each, run a throwaway cargo build to compile dependencies into a cached layer, then COPY the real source and build again.
That scheme had silently gone inert (#617). The manifest-copy block listed only ~24 of the workspace’s ~57 members — craig-composition (which the build’s -p list names), the five -contracts crates, craig-validation, plugins/example, and others were never copied. cargo aborts loading a workspace on the first missing member manifest, so the pre-build (cargo build … 2>/dev/null || true) compiled *nothing and the || true swallowed the error. Net effect: every image build recompiled the entire dependency graph from scratch — slow CI image jobs and slow local cargo xtask dev reloads (which build through this same Dockerfile, per docker-compose.yml build: context:. target: craig-X).
The root cause is structural: the scheme requires two Dockerfile edits per new crate (a COPY line and a stub-src line). That manual coupling is exactly what drifted — and it scales linearly with the workspace, which has grown past 50 members.
Decision
Adopt cargo-chef (pinned 0.1.77, installed --locked) for a recipe-based dependency-cache layer.
Three options were weighed:
| Option | Assessment | Verdict |
|---|---|---|
Repair the manual scheme |
Copy all ~57 manifests + stubs. Restores caching but re-incurs the per-crate two-edit maintenance that caused #617; drifts again the next time a crate is added without updating the Dockerfile. |
Rejected |
|
Simplest Dockerfile, but provides no dependency caching — any source change invalidates the single copy layer, so deps recompile every build. Fails the #617 acceptance ("a no-op source change rebuilds without recompiling the dependency graph"). |
Rejected |
cargo-chef |
Recipe-based cook layer keyed on |
Chosen |
Structure (chef → planner → builder):
-
chefbase onrust:1.94-alpine. Installscargo-chefwithcargo install --locked cargo-chef --version 0.1.77. CRAIG builds natively on Alpine (the image target already isx86_64-unknown-linux-musl), so neithercooknorbuildneeds a--targetflag — unlike the glibc→musl cross-compile path in the cargo-chef README. Thecargo-chefcompile is a one-time cost cached in this stage until the pinned version bumps. -
planner—COPY . .thencargo chef prepare --recipe-path recipe.json.recipe.jsonis a pure function of the manifests +Cargo.lock, so it is byte-identical across source-only changes (prepareitself does no compilation). -
builder—COPY --from=planner recipe.json, thencargo chef cook --release -p <12 service/tool bins> [--features $CRAIG_WEB_FEATURES] --recipe-path recipe.json. This is the cached layer: Docker keys it onrecipe.json’s content (+ the `CRAIG_WEB_FEATURESbuild-arg), so a source-only change reuses it. Thecookpackage set and features mirror the finalcargo buildexactly so the cooked artifacts are reused verbatim. ThenCOPY . .+ the realcargo buildrecompiles only the workspace crates.
cargo chef cook forwards standard cargo build flags (-p, --features, --release, --bin), so mirroring CRAIG’s existing multi--p + CRAIG_WEB_FEATURES invocation is exact.
Consequences
-
A no-op source change skips dependency recompilation — the dominant win is the local
cargo xtask dev start/reload/restart-serviceloop and CI image jobs (the host-cargo pre-push battery is unaffected — it never builds images). -
Adding a workspace crate needs no Dockerfile edit; the inert-by-drift failure mode is structurally eliminated.
-
New build-time dependency (
cargo-chef), pinned +--locked; bumping it is a one-line version change in thechefstage. The runtime images are unchanged (still minimalalpine:3.23per service; cargo-chef lives only in the build stages). -
The
chefstage pays a one-timecargo-chefcompile, cached until the version bump.
Amendment — #1977 A3 (2026-09-21)
What changed. The builder stage’s cargo chef cook and cargo build RUNs both run over three BuildKit cache mounts with fixed, daemon-global ids — craig-cargo-registry → /usr/local/cargo/registry, craig-cargo-git → /usr/local/cargo/git, craig-target → /app/target — all sharing=locked. The binary copy-out (mkdir -p /out && cp target/<profile>/<bin> /out/, #694) is FOLDED into the build RUN: a cache mount is not layer content, so a later RUN would see an empty /app/target; /out is ordinary layer storage and the runtime stages' COPY --from=builder /out/<bin> lines are unchanged. The decision above still holds — cook stays the recipe-keyed layer — but the mount makes the cooked dependencies AND the workspace `.fingerprint`s persist across `docker build`s, so a source-only change recompiles only the crates whose fingerprints moved, where Build B below recompiled every workspace crate.
No-cache is now two things. With mounts, bypassing the layer cache alone is no longer a from-scratch compile (a bypassed cook re-reads the mount). --no-cache therefore means the layer bypass docker_build_args emits on each recipe’s first build (#1347) AND docker builder prune --force --filter type=exec.cachemount (docker::prune_build_cache_mounts), run ONCE at the head of build_devstack_images_serial when no_cache, and in devstack::tear_down(true) after down --rmi local — so dev clean / dev restart / dev reseed keep their from-scratch promise. builder prune has no per-id filter: the prune drops every cache-mount record on the daemon, acceptable under the devstack’s as-if-alone-on-the-machine rule. cargo xtask dev start --no-cache is the explicit entry (it forces RebuildType::NoCache through the existing lattice join; a first run or --force --no-cache cold-starts with bring_up(true)); --force alone stays a cold start WITH the caches. Guard-derived NoCache (Cargo.lock / Dockerfile drift) keeps today’s meaning — it prunes too, so a lock-only change is still a full compile (making it incremental is a follow-up, not this amendment).
Recipe interaction. ONE shared craig-target across the four #1347 recipes: cargo fingerprints per (package, features, profile), so recipes 2–4 compile only their feature-changed crates (craig-web / craig-composition under plugin-example; craig-intake under self-signed-tls / state-tx-stub) on top of recipe 1’s artifacts instead of a full workspace each. The serial loop is untouched — sharing=locked is the belt, the loop the braces — and the memory floor moves only DOWN (fewer rustc / linker processes per recipe; the last builder layer is /out alone rather than all of target/).
CI posture. dind is ephemeral: every job starts with empty mounts, so CI does exactly today’s work. The raw-compose jobs that still build concurrently (the #1347 residue) now queue on the locked mounts instead of racing the shared layer — memory-safer, slower in wall time; sharing=private would restore their parallelism at the cost of N private mount instances (not chosen).
R1 caveat and the recorded fallback (P2). cargo chef cook compiles the dependency graph against skeleton workspace members and then removes the members' own artifacts from target/, so the members recompile in the build step regardless of the mount; the win is bounded to dependencies plus whatever fingerprints the real build leaves behind. If the integrator’s one-crate rebuild misses the < 20 s per-recipe acceptance on the reference host, P2 ships in the same MR: a CARGO_CHEF_COOK build-arg (default 1; the devstack serial loop passes 0, skipping cook so the mount itself is the dependency cache). Which shipped, and the numbers, are recorded by the integrator on the line below.
MEASURED (2026-09-21, the reference host; P1 shipped, P2 not applied). One-crate cargo xtask dev refresh — a blank line appended to, then removed from, services/craig-reporting/src/main.rs; the second run is the reported one: 4 recipes rebuilt (9 images fully layer-cached), builder cargo build RUN 2.3 s / 1.1 s / 1.1 s / 2.4 s for recipes 1–4 (craig-reporting recompiled in recipes 1 and 4, zero crates in 2 and 3 — the shared mount already held the artifact), Σ 6.9 s of compile inside a 29.1 s refresh wall (13 docker build`s + recreate + health); the first run 2.5 / 1.1 / 1.2 / 2.4 s. Before (#1977’s table, main): a FULL workspace compile ≈ 55 s per recipe on every code push. The cook layers stayed CACHED (recipe unchanged); the mount is what turns the build RUN incremental. Cold build under the new Dockerfile (empty mounts, the first `dev start after the change): recipe 1 cook 41.1 s over 598 crates + build 52.5 s over 59 members, recipes 2–4 on the shared mount 1.8 + 42.6 / 3.0 + 14.5 / 2.4 + 45.4 s ≈ 206 s of builder RUN in total. Peak RSS during the one-crate builds: host free used 13.6 GiB vs 12.5 GiB idle (≈ +1.1 GiB); docker stats --no-stream (the devstack containers — BuildKit execs under the docker driver are not containers) 4.80 GiB vs 4.73 GiB idle; 5 s sampling. docker builder du --verbose lists the three ids: craig-cargo-git 1.59 MB, craig-cargo-registry 471.5 MB, craig-target 12.23 GB.
Amendment — #2136 (2026-10-07)
The question. Since A3 the devstack guard took the no-cache path (the layer bypass AND emptying the mounts) whenever Cargo.toml / Cargo.lock or the Dockerfile changed. So every dependency bump paid a cold build from empty mounts, exactly where the mounts help most: 496 s for a one-crate dependency add (#2123), about 688 s inside !1772’s own battery. Each trigger is decided below, with the reason.
Cargo.toml / Cargo.lock: never empty the mounts.
-
The change moves
recipe.json, so the cook layer re-runs over the kept mounts, and cargo’s own fingerprints rebuild exactly what moved. Versions, features,[profile],[patch], members and edition are in the unit hash or the fingerprint, and the rustc version is in every fingerprint. This is the ordinary host-target/workflow. -
cargo-chef removes the skeleton members' artifacts after cook (A3), so a warm-mount cook cannot leave dummy members behind.
-
The cost is disk growth from superseded artifacts, bounded by the explicit resets below and by BuildKit’s builder GC.
-
The guard reports a cached rebuild (
check_deps_stale).
Dockerfile: empty the mounts only when the builder environment changed.
-
The builder environment is what
builderinherits: every instruction before the firstFROM(globalARG`s), each stage in `builder’s local `FROMchain (cheftoday, with its base image), andbuilder’s own `FROMline (its flags). -
It is what the mounts' contents depend on beyond cargo’s fingerprints: the C toolchain, the system packages build scripts probe (a changed
apkset never re-runs apkg-config/ccprobe, because nothing the build script tracks moved) and the cargo-chef pin. -
A base-image or
RUSTFLAGSchange recompiles everything anyway (rustc and flags are fingerprinted), so emptying costs no compile and stops the 12 GBcraig-targetfrom doubling. -
Every other
Dockerfileedit keeps the mounts: comments, runtime stages,COPYlines, the cook / build argv,ARGdefaults (profile and features are fingerprinted) and mount ids (a new id is a new, empty mount). -
The guard reports a cached rebuild either way, and its reason names which (
check_dockerfile_stale).
Where it is decided: the record lives as long as the mounts.
-
.devstack/builder_env.sha256records the builder environment the mounts were last filled under: the sha256 of the environment’s instruction text, whitespace-collapsed, comments dropped (devstack_guard::builder_environment_fingerprint, on the dockerfile-hygiene lint’s parser). -
It is checked and rewritten in
docker::build_devstack_images_serial, which the devstack app-image builds behindbring_up,dev refresh,migrate applyand validate’s Docker step pass through. The mounts are emptied when--no-cacheasks or the record differs, and the current environment is recorded before the firstdocker build. -
The staleness markers die with every teardown (
clear_markers), but the mounts survive every teardown exceptdev restart’s, so the record is kept across them. A `chefedit followed bydev clean+dev start, adev reseed, a store-key adoption or the #955 conservative refresh therefore still empties the mounts. -
With no record yet (a fresh clone, or the first build after this amendment), the mounts are adopted only when the
Dockerfileis the one the last converge blessed (.devstack/dockerfile.sha256). Otherwise they are emptied. -
No staleness check sets
RebuildType::NoCacheany more;dev start --no-cacheis its only source. -
A builder-environment change needs no layer bypass: it is a text change, so BuildKit rebuilds
chefand its descendants anyway. -
A unit test pins that the committed
builderancestry carries no input its text omits (noARG,COPY,ADDor heredoc), and thatbuilderitself adds onlyARG,COPYand cargo `RUN`s. So an environment change can only land in the fingerprinted text.
The ensure_ready volume wipe keeps the images and the mounts. Its VolumeWipe arm serves every volume-wipe verdict: a modified, deleted or wipe-before-apply migration, a key, envelope-format or bundle change, or a devstack/postgres/ or garage Dockerfile change. It was tear_down(true) + bring_up(true), so every such wipe in validate’s devstack phase emptied the mounts and rebuilt cold. It is now tear_down(false) + a cached bring_up (no-cache only under --no-cache), the shape dev refresh’s wipe already had. A NEW migration still reaches the binary over the kept mount, because every service embedding `sqlx::migrate!() carries a build.rs with cargo:rerun-if-changed=migrations (#2220).
The explicit resets are cargo xtask dev start --no-cache (the layer bypass plus the prune) and dev restart (down --rmi local plus the prune).
Corrections of A3, as built. A3’s "Guard-derived NoCache (Cargo.lock / Dockerfile drift) keeps today’s meaning" is superseded by the decisions above. A3’s "`dev clean` / dev restart / dev reseed keep their from-scratch promise" was never true of dev clean and dev reseed: both have called tear_down(false) since A3 and never emptied the mounts. They still do not.
Residuals: not detected, stated rather than claimed away.
-
A floating
rust:1.97-alpinetag moving under identical text, or a BuildKit-GC’dcheflayer whoseapk addre-resolves newer packages, changes the environment without changing the text. Nothing passes--pull.-
A rustc change is in every cargo fingerprint, so everything recompiles and no stale Rust artifact is linked.
-
A same-rustc C-toolchain or package move keeps build-script C objects. They are ABI-compatible within an Alpine branch, and the same exposure existed before.
-
dev start --no-cacheis the reset.
-
-
Mount ids are daemon-global, so another clone’s build fills the same mounts while its record lives in its own
.devstack/. This is pre-existing. -
A build outside that choke point fills the mounts without checking or recording: the
cluster-testsrig’sdocker compose build(the #1347 residue),cargo xtask rewrite-scheme’s `craig-cases-rewritebuild (gone since #2268), and any hand-rundocker build. When the record then differs from the tree, the next devstack build empties the mounts (the safe direction). Only such a build under a different builder environment followed by a return to the recorded one goes unseen;dev start --no-cacheis the reset.
Landing. The change that introduced this amendment also edits a Dockerfile comment. On an existing box, the first app-image build after it lands finds no record and an unblessed Dockerfile, so it empties the mounts once. From then on the record decides.
MEASURED: not yet run. The measurement needs Docker and a dependency-only change, so it is manual and outside the battery (this change touches neither Cargo.lock nor the builder environment): on a scratch tree, cargo update -p <leaf>, then cargo xtask dev refresh. Expect the cook to compile only the bumped crates and the build RUN only the members. Record the cook / build seconds and docker builder du here.
Amendment — #3003 (2026-11-08)
The problem. Since A3 the cook and the final build write cargo’s target directory to the craig-target cache mount. A cache mount is not layer content, and a BuildKit registry cache (--cache-to type=registry,mode=max, which cargo xtask ci images has used since #2931) carries layers only. A CI job runs on a fresh VM, so it imports the cook layer from the registry and reports it CACHED, but the layer holds no compiled dependency. The final build then compiles every third-party crate. On the train (pipelines 3040886666 and 3040892255), a car’s build job compiled 494 of them in its first image’s builder stage (15m 44s).
What changed. A build arg, CRAIG_CARGO_TARGET, names the target directory. The cook and the final build in builder and in tools-builder both pass it as the same --target-dir "${CRAIG_CARGO_TARGET}", and the copy-out to /out reads the binaries from it.
-
Locally (docker compose,
cargo xtask dev, validate’s Docker step) the default is/app/target, thecraig-targetmount, so A3 and #2136 hold unchanged. -
On CI, the publish (
ci images --publish-digests) passes/cargo-targetfor every image of both cargo stages (docker::publish_specs,ci::buildx::ci_cargo_build_args). No cache mount covers that path, so the cooked dependencies are layer content:main’s `mode=maxexport carries them, and a car’s final build reuses them.
The three mounts stay on both RUNs, because a Dockerfile cannot mount conditionally. On CI the craig-target mount is simply unused.
Two CI-only settings keep the layers small. Without them, the final build’s layer held the whole target directory beside /out: 7.18 GB uncompressed, 1.97 GB gzip, of which 3.1 GB was incremental state. mode=max would export that layer on every cache write, and no car ever reuses it, since COPY . . differs.
-
CARGO_INCREMENTAL=0. Both stages declareARG CARGO_INCREMENTALwith no default. An undefined ARG is not set in a RUN’s environment, so a local build keeps the profile’s incremental setting. The publish passes0, which reaches the cook and the final build alike, so their fingerprints agree. Incremental state is useless on a fresh VM. -
The final layer holds
/outalone. After the copy-out, the build RUN deletes the target directory, in the same RUN, unless it is/app/targetor below it. The mount path is therefore never deleted, and on CI the layer records only a whiteout and/out, as before this amendment. The cook layer keeps its target directory: that is the point.
Both build args are --build-arg`s of the publish, so they feed the cache tag’s input hash (`cook_cache::collect): the CI tag differs from what the same recipe’s local build would hash. The release promotion (--push) keeps the defaults, so this amendment does not change it.
Costs.
-
The cook layer is now a registry blob: 1.57 GB uncompressed, 469 MB gzip, for the first devstack recipe.
mainwrites it once per recipe (export_needed); cars only read. -
A car’s final build still fetches the crate sources (about 4 s here), because the registry mount the seed fills is empty on a fresh builder. Fetching is not a compile.
MEASURED (2026-11-08, luchs, the first devstack recipe: --target builder, CARGO_PROFILE=devstack, CRAIG_DEVSTACK_FEATURES=authz-witness, CRAIG_CARGO_TARGET=/cargo-target, CARGO_INCREMENTAL=0). Each build ran on a fresh docker-container builder, and a type=local,mode=max cache stood in for the registry.
-
Build 1 (cold, exporting): the cook compiled 571 crates (63 of them the
craig-skeletons) in 2m 13s. The final build compiled the 63craig-members only, in 1m 55s. The cache export took 41.5 s, and wall time was 6m 08s. The final layer is 1.71 GB uncompressed, 339 MB gzip:/outand the target directory’s whiteout. -
Build 2 (a one-line source change, importing build 1’s cache): the cook was
CACHED. The final build compiled 63 crates, every one acraig-*member and no third-party crate, in 1m 52s. Wall time was 2m 21s.
Amendment — #3044–#3046 (2026-11-10)
What changed. Plan ci-dev-loop (#3042) moved the devstack’s compile out of the image build.
-
The devstack images compile nothing (U2, #3044).
cargo xtask dev startcompiles the workspace once, musl and static, in craig-tools (target/craig-tools/x86_64-unknown-linux-musl/devstack/,xtask/src/lanes.rs). The fourteen<service>-devstacktargets on thedevstack-runtimebase thenCOPYthose binaries in from the named build contextdevstack-bins. No stage underdevstack-runtimeruns cargo, sodev start,dev refresh,migrate applyand the CI car never reach the cook or the build RUN. A3’s cache mounts and #2136’s record no longer apply to a devstack build. -
The cook layer serves the release images (U3, #3045). The
builderandtools-builderstages, with their cook, now build the twelve deployable images and the release smoke’s three side images throughdocker buildx bake --file docker-bake.hclin the protectedrelease-buildjob. A direct build of a production target, such as thecluster-testsrig’sdocker compose buildor a hand-rundocker build --target craig-<svc>, also uses it. The decision above (a recipe-keyed cook layer, auto-discovered members) stands for those builds. -
No CI build exports a registry cache (U4, #3046). The car’s image publish (
ci images --publish-digests), theBuildKitcontainer builder and the registry cache were retired withxtask/src/cmd/ci/. The bake passes neitherCRAIG_CARGO_TARGETnorCARGO_INCREMENTAL, sorelease-buildcooks under the Dockerfile defaults: the/app/targetmount, as a local build does. Amendment #3003’s CI branch (/cargo-targetas layer content,CARGO_INCREMENTAL=0, themode=maxexport) therefore has no caller. Its build args stay in theDockerfilewith their local defaults, which keep A3 and #2136 for the builds above.Amended (2026-11-10, #3054): the two build args and the target-directory delete they selected are removed from the
Dockerfile. The cook and the final build pass no--target-dir, so cargo writestarget/under the stage’s/appworkdir: thecraig-targetmount, as every caller already had it. A3 and #2136 hold unchanged.
Why. The CI car compiled the workspace twice: once into the service images under the chef stages, and once into the test binaries in craig-tools. Under resolver 2 the two compiles shared nothing. One compile whose binaries both the images and the lanes use removes the image compile from every car and from every local dev start. The release images keep the chef stages because release-artifact-gate reads the Dockerfile’s `cargo build units and the bake file to keep test-only features out of shipped bytes (plan ci-dev-loop § Facts the design rests on).
Cost. A release-build run starts on a fresh VM with an empty mount and no registry cache, so its cook compiles the dependency graph cold on every run. It runs on a tag, on the weekly schedule and by hand, never per car, so that cold cook is not on any car’s path.
Verification
Verified 2026-06-20 with docker build --target craig-rules (the builder compiles all 12 binaries regardless of which runtime target is selected), a no-op source change (a comment appended to services/craig-rules/src/main.rs), then a rebuild:
-
Build A (cook populated):
cargo chef cookcompiled the full external dependency graph (~1m43s); the finalcargo buildthen compiled only thecraig-*workspace crates (~2m15s) — reusing cook’s/app/targetdeps (target/is.dockerignore`d, so `COPY . .does not clobber it). Image built successfully, and the build step did NOT download a toolchain (cook and build share therust:1.94-alpinebase —rust-toolchain.tomlis `.dockerignore`d so "stable" is not re-resolved to a newer rustc that would invalidate the cooked layer). -
Build B (no-op source change): the
COPY --from=planner recipe.jsonandcargo chef cooklayers both reportedCACHED(recipe.json is byte-identical —cargo chef prepareskeletonizes function bodies, so a source-body change does not alter it); the finalcargo buildrecompiled only thecraig-workspace crates and *no external dependency. This satisfies the #617 acceptance criterion: a no-op source change rebuilds without recompiling the dependency graph.