Skip to content

feat(cargo-build-cache): Add an action to cache Cargo build output - #1006

Merged
coroiu merged 11 commits into
mainfrom
cargo-build-cache
Nov 3, 2026
Merged

coroiu merged 11 commits into
mainfrom
cargo-build-cache

Conversation

@coroiu

@coroiu coroiu commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR: A composite action that lets a Cargo workspace reuse its own build output between CI runs. In bitwarden/sdk-internal this logic is copied into six places, and in experiments it cut the test, lint and build workflows from 14-20 minutes to a few minutes for typical PRs. This PR moves it here so sdk-internal, and later other Rust repos like clients' desktop_native, can use one implementation.

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-46495

📔 Objective

Caching target/ is not enough for Cargo to skip the workspace's own crates. Cargo compares source file modification times with the build output, and a fresh checkout gives every file the current time, so every workspace crate looks changed. rust-cache avoids this by not caching workspace crates at all.

cargo-build-cache is one step before the build. It restores target/ with actions/cache, sets every tracked file to a fixed old time, and marks as new only the files whose content hash differs from the hashes stored with the cache. Without stored hashes, every crate rebuilds: slower, but never stale. It then writes the current hashes into target/ as the record for the next run.

actions/cache saves target/ at the end of the job, so callers don't need a save step. It saves only when the job succeeded, and skips the save on an exact key match. A run whose build succeeded but whose tests failed therefore saves nothing; the next run falls back to an older cache.

The hashes are taken before the build, so steps after it (tests that rewrite snapshots, for example) can't make the record describe content that was never compiled. Steps between this action and the build must not change tracked files. The README says so.

Key: cargo-build-<os>-<key>-<hash of rustc -vV>-<YYYY-MM>-<sha>. A new cache starts every month so old dependency builds don't accumulate. Pull requests fall back to the previous month until the default branch has built the new one.

Two inputs cover what sdk-internal needed beyond the basic case:

  • key, for builds that produce different output (per check, license, target, or a container image digest Cargo doesn't track).
  • reset_sysroot_mtimes, for builds whose dep-info lists toolchain files (-Zbuild-std, cargo-udeps). A fresh toolchain install gives those files new times, which otherwise makes every crate rebuild.

Tracked symlinks are hashed by their link text, the same hash git stores. If a link changed, every crate rebuilds, because Cargo looks through the link at the target's file times. Submodules are skipped, so crates using them always rebuild.

Compared with sdk-internal's script, one bug is fixed: git hash-object --stdin-paths resolves paths from the repository root, so the script failed in a workspace below the root.

Testing

  • test-cargo-build-cache.yml builds a three-crate fixture workspace on Ubuntu, macOS and Windows. A first job builds and saves. A second job edits one crate and checks Cargo's fresh flags: only the edited crate and the crate depending on it may rebuild. The first job also rewrites a tracked file after the build, so recording at the wrong time would fail the second job.
  • Locally (macOS): the script end to end with the workspace at the root and in a subdirectory, plus actionlint, bwwl, shellcheck and prettier.
  • The fixture's symlinks (one dangling, one to a directory) are created at runtime in the test jobs, not tracked. GitHub's runner downloads the whole repository when a workflow uses any action from it, and fails on a tracked dangling symlink. That would break every bitwarden/gh-actions/* user, so a guard step fails the test workflow if the repository tracks a symlink.
  • Verified on real runners (Ubuntu, macOS and Windows): actions/cache's post step runs when nested in this composite action and saves the cache, and it skips the save on an exact key hit. A temporary job that failed after a successful build saved nothing (checked on Ubuntu only).
  • Also measured against all five sdk-internal workflows (ci: Speed up the build and lint workflows with the build cache sdk-internal#1704): about the same speed as the copied steps, and only the changed crates rebuilt.
  • Not covered: symlinks checked out as plain files on Windows (the runners check them out as real symlinks).

Rollout

sdk-internal switches to @main after this merges, replacing its six copies and scripts/ci-build-cache.sh. The first run there after switching is cold, because the key prefix changes.

🤖 AI-assisted review

  • Multi-agent review (architecture, code quality, bug analysis, security, then validation and severity audit): no findings after the audit.
  • One finding was validated and reproduced, then dismissed by the audit because no current consumer is affected: tracked dangling symlinks or symlinks to directories broke hashing and failed the save. Fixed anyway in the last commit, with fixture coverage.

… output

Caching target/ is not enough for Cargo to reuse the workspace crates'
build output: a fresh checkout gives every source file the current time,
so every workspace crate looks changed. restore resets the times of
tracked files whose content matches the hashes stored with the cache,
and save stores the hashes of the files the build compiled.

The logic comes from sdk-internal, which copies it into several
workflows. The script also works in a Cargo workspace below the
repository root now.
git hash-object --stdin-paths follows symlinks, so a dangling symlink
or a symlink to a directory made hashing fail: restore built
everything and save failed the job after a successful build. Symlinks
are now hashed the way git stores them, a changed symlink rebuilds all
workspace crates, and submodule directories are skipped.
@coroiu coroiu added the ai-review Request a Claude code review label Oct 30, 2026
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

🤖 Bitwarden Claude Code Review

Overall Assessment: APPROVE

Re-reviewed after the TEMP failing-job check was reverted. The test workflow no longer has the failing-build and check-failing-build jobs, so it no longer fails on purpose, and the earlier blocker is gone. The merged cargo-build-cache action is the same as last time. Inputs reach the shell only through env, key and toolchain are checked against strict patterns, actions/cache is pinned to a SHA, and the README matches action.yml and build-cache.sh mark. The fixture Cargo.toml/Cargo.lock files only list the three local workspace crates and add no external dependencies.

Code Review Details
  • ❓ QUESTION: The PR description still describes separate cargo-build-cache/restore and cargo-build-cache/save actions, and a save that runs after a failed step. The merged action replaces both and saves only when the job succeeds.
    • Suggested: before merge, update the TL;DR, Objective and Testing sections to describe the single action.

The warm build also logs how the fixture's symlinks were checked out.
The runner downloads an action by unpacking the whole repository, and
fails on a dangling symlink, which broke every job that used an action
from this branch. The test workflow now adds the symlinks to the index
and checks them out before restoring, so the repository contains none.
@coroiu
coroiu marked this pull request as ready for review October 30, 2026 11:31
@coroiu
coroiu requested a review from a team as a code owner October 30, 2026 11:31
@coroiu
coroiu requested a review from AmyLGalles October 30, 2026 11:32
The action uses actions/cache, whose post step saves the build output at
the end of the job, so callers need one step instead of two. The record
of the build inputs is written into the target directory when the files
are marked, which is the content the build compiles.

A job that fails after a successful build no longer saves its build
output, because actions/cache only saves when the job succeeded.
@coroiu coroiu changed the title feat(cargo-build-cache): Add actions to cache Cargo build output feat(cargo-build-cache): Add an action to cache Cargo build output Oct 30, 2026
@coroiu
coroiu merged commit 20568ed into main Nov 3, 2026
18 checks passed
@coroiu
coroiu deleted the cargo-build-cache branch November 3, 2026 08:12
coroiu added a commit to bitwarden/sdk-internal that referenced this pull request Nov 3, 2026
bitwarden/gh-actions#1006 is merged, so the workflows can use the action from main.
coroiu added a commit to bitwarden/sdk-internal that referenced this pull request Nov 3, 2026
**TL;DR: The build and lint workflows only rebuild what a PR changed.**
With the Rust tests fixed in #1683, the slowest checks on a PR were the
WASM build (19.6 min median), Android (16.4), Swift (16.4) and Lint
(14.8). Each now uses the build cache from #1683, through a shared
action in bitwarden/gh-actions, and drops duplicate work, so a typical
PR's checks should finish in about 10 minutes, and much of that is the
clients and Android breaking-change checks.

## 🎟️ Tracking

No ticket. Follow-up to #1683, #1690 and #1691. Uses the
`cargo-build-cache` action from bitwarden/gh-actions#1006.

## 📔 Objective

Each workflow was measured on its own experiment branch with
`workflow_dispatch`, against the latest successful PR run on `main`.
Single runs per scenario.

| Workflow | PR median on `main` (before) | Leaf-crate change |
`bitwarden-core` change |
|---|---|---|---|
| Lint | 14.8 min | 1.9 min | 3.1 min |
| WASM build | 19.6 min | 4.4 min (PR mode) | 8.9 min (full build) |
| Swift | 16.4 min | Build job 4.2 min | 9.3 min (whole run) |
| Android | 16.4 min | Build jobs about 2 min, Combine about 2 min |
Build jobs about 2.5-3 min |

The clients and Android breaking-change checks (about 5 min each) wait
on the other repo and are unchanged. I haven't measured a full PR end to
end, since the experiments ran as dispatches.

One commit per fix:

**Swift**
- Build the three Apple targets in one cargo call. Each target ended
with a single-threaded LTO step, and now those steps overlap. Output is
byte-identical.
- Build cache in the Build job.

**Android**
- Build cache per ABI. rust-cache did restore, but its cleanup deletes
`target/<triple>/release` before saving, so about 318 dependencies
compiled in every run. The `cross` image digest is part of the key,
because the NDK and linker are not in cargo's fingerprints. The
workspace is mounted at the same path inside the container, so the mtime
marking works there too.
- Cache `cross` itself (`.bin`), which was compiled from git on every
run (42 s). This cache has no restore keys, because cargo-run-bin stores
`cross` under its version, not its git rev.
- Gradle build cache for the demo app build. Tasks with unchanged inputs
come from the cache. A PR that changes the uniffi API changes the
bindings, so those PRs get less out of it.

**Lint**
- Run clippy once. `lint.sh` set `RUSTFLAGS="-D warnings"`, so its
clippy run after the SARIF step rechecked all ~630 crates. The SARIF
step is now the gate, with `pipefail`, and findings are still uploaded
when it fails.
- Build cache for clippy, doc and udeps. Before, the shared rust-cache
key held no `target/` at all.
- Keep udeps fresh across toolchain installs. cargo-udeps records the
nightly sysroot files in every crate's dep-info, and a fresh toolchain
install gives them new mtimes, so all 547 dependencies were checked
again.

**WASM**
- `fix:` The `bitwarden-wasm-internal` build script reran on any file
change but not on a changed `SDK_VERSION` or a new commit. With a cached
`target/`, the package could embed an old version string. It now reruns
on those.
- Build cache per license.
- Keep the rust-src mtimes stable. `-Zbuild-std` compiles the standard
library from rust-src, which gets new mtimes on every toolchain install,
so all 364 crates rebuilt even with the cache.
- Run `wasm-opt` once. The bundler and nodejs `.wasm` files were
byte-identical in every run, so the second is a copy. The script checks
this each time and falls back to optimizing both.
- Build the MVP/wasm2js fallback in parallel with the SIMD build
(`build.sh -p`, used in CI). Local `./build.sh -r` stays sequential.
- On pull requests, skip `wasm-opt`, `wasm2js` and `terser` for the
fallback (`build.sh -s`). Nothing in the PR flow loads the fallback: the
clients check only type-checks the package, and the integration tests
load the Node build. The MVP cargo build and the check that both builds
share one glue file still run. `main` builds the full package as before.

### What a PR no longer checks

- `wasm-opt`, `wasm2js` and `terser` on the WASM fallback. Failures
there show up on `main`.
- The PR package's fallback file is a stub, the same as in debug builds.

### Output

- WASM: all 751 package files are byte-identical between a clean build
and a cached build, except `VERSION` (the commit hash).
- Swift: the `.a` files and all generated `.swift`, `.h` and
`.modulemap` files are byte-identical to `main`. The xcframework's
`Info.plist` differs only in the order of `AvailableLibraries`, which
also changes between runs on `main`.

### Good to know

- Builds on `main`, including the ones that publish, also use the cache.
The comparisons above showed no difference from clean builds.
- The first run of each workflow after merge has no cache yet and takes
about as long as before this change.
- The last two commits replace the cache steps in all workflows,
including `rust-test.yml` from #1683, with one
`bitwarden/gh-actions/cargo-build-cache` step, and delete
`scripts/ci-build-cache.sh`. The action uses the same logic, and is
measured as fast as the copies in all five workflows. Its cache keys
start with `cargo-build-`, so the first run of each workflow after merge
is cold, including Rust tests.
- The action saves through `actions/cache` at the end of the job, which
only happens when the job succeeded. A job that fails after a successful
build, for example on a failing test, no longer saves its build output,
and the next run falls back to an older cache. Lint already behaved that
way.
- Pre-existing and out of scope here: the `cross` images (`:main`),
`binaryen` and `terser` are unpinned.

## 🤖 AI-assisted review

- Multi-agent review (architecture, code quality, bug analysis,
security, then validation and severity audit). Two Refactor findings, no
Blockers or Important ones.
- Fixed: the Android `.bin` cache had a prefix restore key.
cargo-run-bin stores `cross` under its version only, not its git rev, so
after a rev bump the old binary would have been restored and used on
`main`. The cache now has no restore keys.
- Addressed: the cache steps were copied into six places. The last
commit replaces them with the shared action from
bitwarden/gh-actions#1006.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-review Request a Claude code review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants