Skip to content

perf(gha): per-crate fingerprint revalidation via blake3 sidecar - #281

Merged
zackees merged 1 commit into
mainfrom
perf/gha-snapshot-fp-revalidation
May 19, 2026
Merged

zackees merged 1 commit into
mainfrom
perf/gha-snapshot-fp-revalidation

Conversation

@zackees

@zackees zackees commented May 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

Replaces #279's blanket "don't touch fingerprints" with a per-crate decision based on blake3 of source content — a stable-cargo replica of nightly's `-Z checksum-freshness`.

  • Save side: `zccache snapshot-fp-record` walks each cargo fingerprint dir, parses its rustc-emitted `.d` Makefile, blake3-hashes every workspace-local source (skipping vendored `.cargo/registry/` paths), writes a JSON sidecar at `/.zccache-fp-manifest.json` that rides the existing snapshot tar.
  • Restore side: `zccache snapshot-fp-validate` rehashes every recorded source in parallel. Crates where every source still matches → future-stamp their `dep-*` files so cargo trusts the cache. Crates with any mismatch → leave alone so cargo invokes rustc.

What changes for users

Scenario Before #279 #279 This PR
Unchanged sources Skip rustc (fast) Cargo re-fingerprints every crate (slow) Skip rustc (fast) ✓
Changed sources in 1 crate Silently links old binary (BUG) Re-fingerprints every crate (slow but correct) Re-fingerprints only changed crate (correct & fast) ✓
Missing manifest (snapshot from older daemon) n/a n/a Falls back to #279 behaviour ✓

Bench (this workspace's `target/`)

  • `snapshot-fp-record`: 350 ms, 6.2 KB manifest, 38 workspace sources hashed
  • `snapshot-fp-validate`: 37 ms (all clean)

Files

  • `crates/zccache-cli/src/snapshot_fp.rs` (new, +473 / 5 unit tests)
  • Two new subcommands in `crates/zccache-cli/src/main.rs`
  • Wired in `action.yml` (validate between warm + touch) and `action/cleanup/action.yml` (record before tar)
  • `action/cleanup/select-hot-target.py`: keep the manifest in hot-mode tars

Closes #280. Builds on #279 — that PR's conservative "rebuild everything" is now the fallback path when the manifest is absent or unparseable.

Test plan

  • 5 unit tests
  • Local smoke against this repo's `target/`
  • cargo clippy + fmt clean
  • CI: push a single-line test edit; only that crate rebuilds
  • CI: unchanged-source PR hits the fast path (clean count > 0 in validate log)

🤖 Generated with Claude Code

Replaces the blanket future-stamp of `target/` files with a content-hash
analogue of cargo's nightly `-Z checksum-freshness`. Stable cargo decides
crate freshness via `source.mtime > dep_info.mtime → rebuild`; the
existing CI cache flow makes that signal worthless across runners (see
PR #279), so this PR makes the freshness decision per-crate based on
blake3 of the actual source content.

## Mechanism

**Save side** (`zccache snapshot-fp-record`, run from
`action/cleanup/action.yml` before tarring):
- Walks `target/<profile>/.fingerprint/` and the sibling `deps/` dir.
- For each crate, parses its rustc-emitted Makefile-format `.d` file to
  get the tracked source list (much simpler than cargo's binary
  dep-info format).
- blake3-hashes every workspace-local source (skips
  `.cargo/registry/` and `.cargo/git/` — those are pinned by
  `Cargo.lock`, which is already part of the cache key).
- Writes a sidecar manifest to `<target>/.zccache-fp-manifest.json`.
  Lives inside `target/` so it rides the existing snapshot tar with no
  changes to `prepare-target-snapshot.sh`. `select-hot-target.py` adds
  the basename to `MUST_KEEP_NAMES` so hot-mode tars include it.

**Restore side** (`zccache snapshot-fp-validate`, run from `action.yml`
between `zccache warm` and the existing find-touch step):
- Reads the manifest. Missing/corrupt/version-mismatched manifest is a
  silent no-op: cargo's normal mtime check still fires (overbuild but
  correct — same state as PR #279).
- Per crate, rehashes every recorded source in parallel (rayon).
- If **every** tracked source matches its recorded hash → bumps that
  crate's `dep-*` files to `now + 60s` so cargo's mtime check trusts the
  cache. Any mismatch → leaves the crate alone → cargo correctly
  invokes rustc.
- Doesn't touch fingerprints of crates not in the manifest (e.g. crates
  with no workspace-local sources, or new crates introduced since
  snapshot save).

## Measurements

Run against this workspace's `target/` (~420 cargo fingerprint dirs):
- `snapshot-fp-record`: **~350 ms total**, manifest is **6.2 KB** for
  18 workspace crates / 38 sources (vendored-dep filter dropped this
  from 1.3 MB / 7817 sources).
- `snapshot-fp-validate`: **~37 ms** for the no-changes case (all 18
  crates clean).

Both costs are dwarfed by even the cheapest CI build step.

## Why this is the right design (vs alternatives)

| Approach | Code surface | Robustness | Notes |
|---|---|---|---|
| **A: blake3 sidecar (this PR)** | ~470 lines Rust | Highest | Works on any clone depth, any git config, doesn't depend on git tooling on the runner |
| B: `git diff` against a saved commit SHA | ~50 lines shell | Medium | Requires `fetch-depth` deep enough; fails open on shallow clones |
| C: `git-restore-mtime` to set source mtimes from git history | ~10 lines shell | Medium | Needs an extra tool installed; merge commits over-rebuild |

(A) self-contains and mirrors exactly what `-Z checksum-freshness` does
upstream — when that feature stabilises we'd replace this sidecar with
cargo's native version, not a different mechanism.

## Test plan

- [x] 5 unit tests cover: record→validate round-trip on unchanged tree,
  validate marks dirty crate (modified source) as not-clean and leaves
  its dep-info mtime untouched, missing manifest is a silent no-op,
  `.d` parser handles Windows + Unix paths and escaped spaces.
- [x] Local smoke test on this repo's `target/`: 420 cargo dirs, 18
  workspace crates, 38 sources, 6.2 KB manifest, sub-second e2e.
- [x] clippy + fmt clean.
- [ ] CI: after this lands, push a single-line edit to a test in any
  workspace crate; only that crate (+ reverse-deps) should rebuild.
- [ ] CI: confirm unchanged-source PRs hit the fast path (clean count
  > 0 in the validate log line).

Closes #280.
Builds on #279 (which keeps the conservative "rebuild everything"
fallback intact for the missing-manifest case).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit fa646ce into main May 19, 2026
23 checks passed
@zackees
zackees deleted the perf/gha-snapshot-fp-revalidation branch May 19, 2026 08:13
zackees added a commit that referenced this pull request May 19, 2026
)

Extends the per-crate content-hash freshness mechanism from PR #281 to
cover cargo's full set of staleness signals for workspace crates, and
removes the blanket post-restore `find ... -touch '+1 min'` in
action.yml that originally caused the silent-underbuild bug (PR #279).

## What's covered now

Manifest v2 generalises the v1 `dep_info_files: Vec<String>` (names
inside `<fp_dir>/`) into `stamp_targets: Vec<String>` (paths relative
to `target_dir`) so we can address every freshness anchor cargo uses:

1. **Library / bin / test compilation** — `CheckDepInfo` with `.d` file
   under `target/<profile>/deps/<fp_dir>.d`. Already in v1.
2. **Build script compilation** — `CheckDepInfo` with `.d` file under
   `target/<profile>/build/<fp_dir>/build_script_build-<hash>.d`. New.
3. **Build script execution** — `RerunIfChanged` from
   `<fp_dir>/run-build-script-build-script-build.json`, with `paths`
   relative to the crate's manifest dir and an `output` file in
   `build/<fp_dir>/`. New.

For (3), `record` walks the workspace once to build a package-name →
manifest-dir map (parsing `[package].name` from each `Cargo.toml`
manually — no new `toml` dep). Crates using workspace inheritance for
`name` are skipped (cargo's normal check applies).

## Action change

`action.yml` no longer runs the blanket `find "$TARGET" -type f -not
-path '*/.fingerprint/*' -exec touch -t '+1 min'`. snapshot-fp-validate
now covers every freshness anchor cargo uses for workspace crates, so
there's nothing left for the blanket touch to legitimately address —
and the cargo internals it was forging through (build script outputs,
dep-info anchors) are exactly what gets exploited if a stale anchor
slips through.

A snapshot saved by a v1-manifest daemon will produce a
version-mismatch warning at restore and validate silently no-ops →
falls through to cargo's baseline mtime check (overbuild but correct).
First snapshot saved by this daemon will be v2.

## Tests

- Existing 5 lib/parser tests still pass.
- 3 new tests:
  - `record_handles_build_script_compilation` — synthetic build-script
    compile fingerprint (dep-* in fp_dir, .d in build/<dir>/); confirms
    one entry with stamp_target pointing at the in-fingerprint anchor.
  - `record_handles_run_build_script` — synthetic RerunIfChanged json
    + matching `build/<dir>/output` file; validate must bump that
    output's mtime.
  - `strip_hash_suffix_classifies_correctly` and
    `parse_package_name_*` — helper functions.

Local smoke on this repo's `target/`: 28 crates / 48 sources / 9.5 KB
manifest / 725 ms record (vs PR #281's 18/38/6.2KB/350 ms — the
increment is workspace-crate discovery + the 3 workspace crates with
build.rs each producing 2-3 extra entries).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request May 19, 2026
…ess (#283)

The mtime+atime set in `warm_target` looks at first glance like another
freshness forgery for cargo (and was originally commented that way: "so
cargo sees the file as fresh"). After the snapshot-fp work landed (PRs
#281 / #282) it was tempting to delete it as redundant.

It isn't. The touch's actual purpose:

* `warm` hardlinks each cached artifact (`~/.zccache/artifacts/<key>_<i>`)
  into `target/<profile>/deps/<name>`. The two paths share an inode.
* `crates/zccache-daemon/src/eviction.rs` picks the highest mtime
  across an artifact's data files as the "last-used" timestamp for its
  LRU eviction decision.
* Touching the dst path bumps the shared inode's mtime, which the next
  eviction pass reads as "this artifact was recently used → keep it".

Cargo, on the other hand, never mtime-checks rlib outputs — they're
content-keyed by filename hash, and cargo's freshness check uses
dep-info-file mtimes (now correctly managed per-crate by
`snapshot-fp-validate`). So the touch is irrelevant to cargo and
removing it would silently break eviction's LRU ordering on machines
where `warm` is part of the build flow.

Updates the comment so a future cleanup doesn't repeat the same
mis-reading. No behaviour change.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request May 19, 2026
… path (#302)

Eliminates the 2x disk write on rustc cold misses by skipping the
std::fs::read of the compiler's output and synchronously hardlinking
the output into the cache.

Net effect on Windows-with-Defender cold compiles: one disk write per
output instead of two — Defender scans the file rustc just wrote, not
a second copy the daemon was paying to materialize.

Implementation:
* New helper persist_artifact_paths() alongside persist_artifact_payloads().
  Routes through persist_artifact_file (hardlink + copy fallback) instead
  of persist_artifact_output (byte write). Pack mode still materializes
  bytes — the optimization is limited to the default unpacked layout.
* Multi-compile miss task at server.rs:6624 fetches output size via
  fs::metadata (avoiding the read), synchronously hardlinks via
  persist_artifact_paths, builds CachedArtifact with CachedPayload::File
  pointing at the cache file (not the original output — cargo's tmp+rename
  rebuild pattern would detach the inode from the user-visible path).
  WAL entry still goes through the background index writer added in #281.

What's out of scope (deferred to #296's Option B):
* ArtifactPayload::Path on the protocol layer (sccache-emulation Store/Get
  callers — code paths nobody hits today).
* The two other in-daemon persist sites (handle_link_ephemeral, single-file
  compile path) — they're a smaller fraction of cold-write Defender cost
  and can be migrated incrementally with the same persist_artifact_paths
  helper introduced here.

Tests: 2 new unit tests for the hardlink path (inode-equality on Unix,
copy-fallback error case). 213 daemon unit tests pass (was 211).
cargo clippy -p zccache-daemon --all-targets -- -D warnings clean.
rustc_issue_210_async_populate_test integration passes.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(gha): optimize target-cache restore — skip rustc spawn for unchanged crates after fingerprint-mtime fix

1 participant