Skip to content

fix(gha): preserve fingerprint mtimes on target-snapshot restore - #279

Merged
zackees merged 1 commit into
mainfrom
fix/gha-target-cache-fingerprint-staleness
May 19, 2026
Merged

zackees merged 1 commit into
mainfrom
fix/gha-target-cache-fingerprint-staleness

Conversation

@zackees

@zackees zackees commented May 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • When cache-target: "true" + target-restore-fallback: "true", the action restored a target/ snapshot from a previous commit and then touched every file (including target/debug/.fingerprint/<crate>-*/dep-<crate>) to now + 1 minute. Cargo's incremental check trusted that future mtime over the just-checked-out source files and skipped rustc entirely — linking the previous commit's binaries against the current source layout.
  • Exclude */.fingerprint/* from the touch pass. Output files (rlib/rmeta/build artifacts) still get the future stamp so the original "output newer than source" optimization works for unchanged crates. Fingerprint dep-info files keep their snapshot mtime — older than the newly-checked-out changed sources, so cargo correctly detects the change and re-invokes rustc.

Symptom (observed during PR #278)

All three test workflows (linux / Test, macos / Test, windows / Test) failed identically on a fresh commit, with panic line numbers and error strings matching the previous commit's source — including string literals that the new commit had explicitly changed. Bumping `Cargo.lock` to bust the restore-key chain was the workaround; this PR makes that workaround unnecessary.

Test plan

The bug only manifests in a CI caching layer, so end-to-end CI is the only real test:

  • After this merges, branch off main and push a single-line edit to a test in `crates/zccache-cli/src/main.rs` (e.g. flip an assertion, or add a `panic!("intentional")`). The change MUST show up in the test failure log on linux/macos/windows.
  • Confirm CI is still fast on unchanged-source PRs (the restore-key fallback should still hit when no source changed; the touch still applies to rlibs so cargo still skips relinking).
  • No regression in the `Test zccache-action` self-test workflow.

Follow-up (separate PR)

Defensive layer: add a workspace-source-tree hash to the restore-key fallback chain so a re-introduction of this class of bug doesn't silently re-occur. Not included here to keep the fix focused.

🤖 Generated with Claude Code

When `cache-target: "true"` + `target-restore-fallback: "true"` are set,
the action restores a `target/` snapshot from a previous commit that
shared the same `Cargo.lock`. The post-restore step touched *every* file
in `target/` to `now + 1 minute` so cargo's "output mtime > source mtime"
check would treat the restored artifacts as up-to-date.

The problem: that touch also hits `target/debug/.fingerprint/<crate>-*/`,
which contains the dep-info files cargo uses to decide whether to invoke
rustc at all. Future-stamping them makes cargo trust the cached binary
even when the source has changed — silently linking the *previous*
commit's compiled binary against the current source layout. Symptoms
observed in PR #278: identical failures on all three test workflows
(linux/macos/windows) with panic line numbers and error strings matching
the previous commit's source, not the just-pushed source.

Fix: exclude `*/.fingerprint/*` from the stamping pass. Output files
(rlib/rmeta/build artifacts) still get the future stamp so the original
"output newer than source" optimization works for unchanged crates.
Fingerprint dep-info files keep their original mtimes from when the
snapshot was saved — older than newly-checked-out changed sources, so
cargo correctly detects the change and re-invokes rustc.

Verification: after this lands, a contributor pushing a single-line edit
to a test file should see that change reflected in CI test output. The
PR-278 workaround of bumping `Cargo.lock` to bust the restore-key chain
is no longer necessary for source-only changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit b5c28af into main May 19, 2026
23 checks passed
@zackees
zackees deleted the fix/gha-target-cache-fingerprint-staleness branch May 19, 2026 07:25
zackees added a commit that referenced this pull request May 19, 2026
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 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 31, 2026
setup-soldr v0.9.24 raises the cache-payload-max-bytes default
2GiB → 6GiB (forge-ci/setup-soldr#280 / #279). Should let zccache's
own build-cache (4-5 GiB observed) actually save instead of
chronic-skipping every run.

19 pins bumped across 9 files.

Co-authored-by: Claude Opus 4.7 <[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.

1 participant