Skip to content

zccache: compiler cache designed for speed - #1

Closed
zackees with Copilot wants to merge 3 commits into
mainfrom
copilot/optimize-sccache-for-speed
Closed

zackees with Copilot wants to merge 3 commits into
mainfrom
copilot/optimize-sccache-for-speed

Conversation

Copilot AI commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Implements zccache from scratch — a local compiler cache that wraps gcc/g++/clang and caches compile-only steps, returning cached objects on repeat builds.

Design priorities vs sccache

sccache zccache
Hash SHA-256 / MD4 BLAKE3 (≈3× faster)
Backend local / S3 / GCS local-only (no network)
Server daemon process none — direct file I/O
Cache hit file copy hard link (zero-copy, same FS)

Core algorithm

  1. Parse — only cache -c (compile-only) with a single source file; link steps pass through unchanged
  2. Preprocess — run -E to expand all includes; header changes are automatically detected
  3. Hash — BLAKE3 over (compiler binary + version) || preprocessed source || sorted flags
  4. Lookup — hard-link cached object (and .d dep file) to output path on hit; compile + store on miss

Key files

  • src/compiler.rs — arg parsing (strips -o/-MF/-MT from cache key), preprocessor + compiler invocation
  • src/cache.rs — cache store/restore with hard-link → copy fallback; clear
  • src/hash.rs — BLAKE3 compiler identity (first 256 KB of binary + version string) + cache key
  • src/stats.rs — atomic JSON stats (hits / misses / errors)

Usage

# Direct wrapping
zccache gcc -c foo.c -o foo.o

# Build system integration
CC="zccache gcc" CXX="zccache g++" make
cmake -DCMAKE_C_COMPILER_LAUNCHER=zccache ..

# Cache management
zccache --show-stats
zccache --clear-cache

Environment variables: ZCCACHE_DIR (cache location), ZCCACHE_DISABLE (bypass), ZCCACHE_DEBUG (hit/miss logging).

Original prompt

sccache but designed for speed


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI changed the title [WIP] Optimize sccache for improved performance zccache: compiler cache designed for speed Mar 8, 2026
@zackees zackees closed this Mar 10, 2026
zackees added a commit that referenced this pull request May 10, 2026
…#139) (#160)

* test(depgraph): RED tests pin path-independence of rustc cache key (#139)

Adds four failing tests asserting that `RustcCompileContext::context_key`
is invariant under workspace-location changes. Demonstrates fix #1 from
issue #139 — cache hits at 0.35% because the same crate at two on-disk
paths gets two different keys.

New tests:
- rustc_context_key_ignores_cargo_manifest_dir — vary CARGO_MANIFEST_DIR
- rustc_context_key_ignores_cargo_manifest_path — vary CARGO_MANIFEST_PATH
- rustc_context_key_sensitive_to_cargo_pkg_version — negative control,
  PASSES on main (CARGO_PKG_VERSION must still affect the key)
- rustc_context_key_ignores_extern_directory_prefix — same-filename
  rmeta in two different target dirs must hash the same

Current failure output (RED state):

    ---- rustc_context_key_ignores_cargo_manifest_dir ----
    assertion `left == right` failed: CARGO_MANIFEST_DIR is volatile ...

    ---- rustc_context_key_ignores_cargo_manifest_path ----
    assertion `left == right` failed: CARGO_MANIFEST_PATH is volatile ...

    ---- rustc_context_key_ignores_extern_directory_prefix ----
    assertion `left == right` failed: extern rmeta paths with the same
    filename ... must produce equal cache keys ...

    test result: FAILED. 315 passed; 3 failed.

GREEN implementation follows in next commit.

Refs #139

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(depgraph): normalize path-dependent inputs out of rustc cache key (#139)

Cache hits sat at 0.35% (2227 misses / 8 hits / 53 errors in the compile
journal) because the rustc cache key embedded inputs that vary per
on-disk workspace location. Same project at `...\zccache` vs
`...\zccache2` produced two disjoint key spaces, so every dep-crate
compile cold-missed.

Two changes:

1. Strip volatile CARGO_* env vars before hashing.
   Introduces `VOLATILE_CARGO_ENV_VARS = ["CARGO_MANIFEST_DIR",
   "CARGO_MANIFEST_PATH"]`. Both are absolute paths handed in by cargo
   and neither affects compiled output in a way that other key
   components do not already cover (the source path is hashed directly,
   `CARGO_PKG_*` carries the identity of the crate). The filter is
   applied in `from_parsed_args` AND in `context_key()` itself —
   defense-in-depth so the public struct cannot be hand-built into a
   path-sensitive key.

   Kept (and asserted by negative-control test): `CARGO_PKG_VERSION`,
   `CARGO_PKG_NAME`, every other `CARGO_PKG_*` — these feed `env!()`
   macros and are baked into rustc output.

   Already-excluded for orthogonal reasons (unchanged): `CARGO_MAKEFLAGS`
   (job-server token), `CARGO_INCREMENTAL` (handled via `-C incremental`
   stripping).

2. Hash only the file-name component of `--extern name=path` values.
   Cargo embeds its per-package `metadata=` hash in the file name
   (`libserde-abc123.rmeta`), which uniquely identifies the extern's
   identity. The directory prefix is incidental — it changes per
   workspace location and per target-dir layout, and including it
   cascaded misses through the entire dep graph after any move.

   Two extern values with different file names (e.g. `liba_v1.rlib` vs
   `liba_v2.rlib`) still produce different keys, so the existing
   `rustc_different_extern_paths_different_key` test continues to pass.

Tests added in the preceding RED commit (T1, T2, T4) now pass; T3
(`CARGO_PKG_VERSION` sensitivity) was already passing on main and
continues to pass — the filter is intentionally narrow.

    test result: ok. 318 passed; 0 failed; 0 ignored

Refs #139

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

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

* perf(daemon): hardlink-based byte-passing on cold compiles (closes #296)

Route the single-compile and link-ephemeral persist paths through the
existing `persist_artifact_paths` (hardlink + copy-fallback) instead of
`persist_artifact_payloads` (byte-write). This halves the Defender
real-time scan wall-clock on cold compiles on Windows: the compiler
already wrote `target/.../<output>` (scan #1); the daemon's previous
byte-write of the same content to `~/.zccache/artifacts/<key>_<i>` was
Defender scan #2. Hardlinking from the compiler's output path makes
the cache file share the same inode — no additional bytes written, no
extra scan.

Cross-volume case is unchanged: `persist_artifact_file` falls back to
`std::fs::copy`, identical to the prior byte-write semantics. Users on
a separate dev drive can opt into `ZCCACHE_COLOCATE=1` (already wired in
`core::config`) to place the cache on the project's volume so hardlinks
succeed there too.

The in-memory `CachedArtifact` still holds resident `Bytes` payloads
(unchanged), so warm hits within the daemon's memory window stay on
the inline-bytes fast path. Cold misses paid the eager `std::fs::read`
of the output for the in-memory cache anyway; the only behavior change
is that the daemon's *disk* write is now a hardlink syscall instead of
a full content write.

Sites changed:
- `daemon/server/handle_compile.rs` single-compile miss persist (was
  `persist_artifact_payloads(...&payloads)`, now
  `persist_artifact_paths(...&[output_path])`).
- `daemon/server/handle_link.rs` link-ephemeral miss persist (was
  `persist_artifact_payloads`, now `persist_artifact_paths` with
  `read_targets` source paths).

`handle_compile_multi.rs` was already on the hardlink path (synchronous
in the miss task, PR landed before #365). Its fallback `persist_jobs`
queue is dead code today but kept for completeness.

Also: add `zccache-cli` to `ci/release_checks.py::RUST_PUBLISH_ORDER`
(stop hook was failing with "missing publishable crates: zccache-cli"
because the Wave-6 collapse renamed `zccache-cli` to a pyo3 cdylib but
the publish list wasn't updated).

Verification:
- `soldr cargo check --workspace --all-targets`: clean
- `soldr cargo test --workspace --tests`: pass (env-specific
  `cli_installers` failures are pre-existing — missing `ctcb.exe`)
- `uv run python ci/perf_local.py` (medium / cold-tar-untar-warm):
  PASS at 7.51x speedup, cold=1m02s warm=8.38s. Cold dropped slightly
  vs prior measurement; warm within run-to-run noise. The Defender
  payoff is Windows-host-specific and not measurable in the Linux
  Docker harness.

* fix: cargo fmt + remove stale `mod python` decl + allow deprecated re-export

CI on PR #374 surfaced three issues:

- `crates/zccache/src/fingerprint/mod.rs:33` had a stale `#[cfg(feature = "python")] mod python;` referencing a file that was moved to the thin py-binding crate in wave 4. `-D unexpected-cfgs` rejected the dangling feature gate. Removed the line.
- `crates/zccache/src/cli/mod.rs:15` re-exports `gc_daemon_spawn_logs` which is `#[deprecated]`. `-D warnings` rejected it. Added `#[allow(deprecated)]` on the re-export block (the deprecation note tells callers to use `gc_log_directory` instead, but the re-export keeps the public path stable).
- `cargo fmt --all` reformatted 77 files. No semantic changes, just whitespace + import ordering.

* style: fix rustfmt formatting on #[allow(deprecated)] re-export

Trailing-comment attributes must be on their own line per rustfmt rules.
Wasn't caught by my prior `cargo fmt --all` because of the
`mod python;` resolution error preempting the formatter.

* fix: Windows CloseHandle extern clash + broken intra-doc-links

CI on the second run surfaced three more `-D warnings`-promoted issues:

- Windows-only: ipc/mod.rs declares `extern \"system\" { fn CloseHandle... }`
  in three places. windows-sys also defines CloseHandle with HANDLE/BOOL
  newtypes; the underlying ABI matches but the signatures clash in
  rustc's eyes (`clashing_extern_declarations` warn). Suppressed with
  `#[allow(clashing_extern_declarations)]` on each block with a comment
  explaining the rationale.
- Rustdoc: `symbols/mod.rs` had `[\`crate::marker\`]` and `[\`crate::cache\`]`
  — broken since the monocrate collapse renamed paths. Fixed to
  `[\`self::marker\`]` / `[\`self::cache\`]`.
- Rustdoc: `depgraph/snapshot/mod.rs` linked to `[\`tests\`]` (cfg(test)
  module not visible to rustdoc). Demoted to plain backticks.
- Rustdoc: `cli/commands/mod.rs` links to `[\`args\`]` (private
  sibling), `depgraph/snapshot/mod.rs` links to `[\`persistence\`]` (also
  private). Both demoted to plain backticks — pub→priv links are an
  error under `-D rustdoc::private-intra-doc-links`.
- Added README.md to `symbols/` and `depgraph/snapshot/` (readme_guard
  hook required them after the Edits).

* docs: drop broken intra-doc link to Config::default in bin

The bin compiles as a separate crate so [`Config::default`] doesn't
resolve. Demote to plain backticks.
zackees added a commit that referenced this pull request Jun 20, 2026
…813) (#831)

Adds Dockerfile.jobserver-test mirroring the existing Dockerfile.cc-test
pattern, validating issue #813's compile-concurrency cap end-to-end
inside a Docker container.

Test flow:
- Stage `builder` — compile zccache + zccache-daemon (release).
- Stage `tester` — Rust toolchain image; runs:
  1. Generate 60 trivial Rust source files
  2. Start zccache-daemon --foreground with
     ZCCACHE_MAX_PARALLEL_COMPILES=1 in env
  3. Launch a 50ms-cadence sampler that polls `pgrep -f rustc`
  4. Fire 60 concurrent `zccache rustc` invocations
  5. Stop daemon + sampler
  6. Parse the CSV samples; assert peak rustc count <= 1

This validates the same property the in-process test #826 validates
(no overlapping compile intervals when cap=1) but at the REAL
end-to-end level — actual daemon, real cargo-style rustc spawns,
observable via system process counting.

## Why process counting rather than log parsing

The original design was to grep daemon-lifecycle.log for the
`compile_start`/`compile_end` events #816 added. Empirically:

- daemon-lifecycle.log contains only structured JSON spawn/
  shutdown events (it's an EventLogger sink, not the
  tracing-subscriber output).
- tracing::info! output from #816's compile_exec instrumentation
  goes to a separate file the daemon stdout/stderr redirect
  doesn't capture (likely a non-blocking tracing-appender file
  layer somewhere; ran out of time pinning down the exact path).

Sampling `pgrep` is more robust:
- Works regardless of where tracing logs land.
- Observes the same property (cap enforced) end-to-end.
- Doesn't depend on the log format staying stable across
  refactors of the instrumentation code.

A follow-up could pin down the tracing-subscriber file location
and parse those events for richer assertion (per-compile durations,
exit codes) — filing that as a small task on the meta.

## Verification status

- Builds zccache successfully (cached layer from build #1).
- Tester stage runs and daemon binds socket (verified across builds
  #2-7).
- Final local validation hit a Docker Desktop daemon hang on this
  Win10 box (the documented "wsl --shutdown required" failure mode
  per #408's cancellation-recovery checklist). CI will validate on
  fresh runners.

Refs #813
Refs #817

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

* fix(daemon-core): address COW materialization follow-up findings (#1042)

Fixes 4 of the 5 confirmed correctness bugs and the confirmed test-coverage
regression from the post-merge review of #1040 (issue #1042):

- artifact_io.rs: write the digest sidecar for a blob's final name *before*
  the publishing rename, not after — a digest-write failure can no longer
  leave an orphaned, undigested blob visible in the cache (finding #1).
- artifact_io.rs: persist_artifact_file tries a hardlink before falling
  back to a full copy, restoring the STORE-direction fast path that
  commit 49dd59c dropped when it switched to reflink-then-copy
  (finding #4/#5). break_output_hardlink_before_compile already
  unconditionally detaches any shared alias (OS link-count based, not
  registry-based) before a compiler writes to that path again, so sharing
  an inode with the freshly-compiled source is safe.
- link_registry.rs / write_cached.rs: commit_hardlink_registration no
  longer marks a blob suspect on a merely-unresolvable output identity
  (only on a genuine identity mismatch), and a commit failure now falls
  back to a copy the same way a failed std::fs::hard_link already does,
  instead of hard-failing the whole materialization (finding #3).
- fs_caps.rs: cap the per-volume-pair capability cache at 4096 entries,
  clearing it wholesale when exceeded — a cheap, self-correcting bound on
  the previously-unbounded growth (finding #6, PLAUSIBLE/low severity).
- tests/write_cached.rs: restored deterministic hardlink-tier assertions
  in 4 tests (including the issue #197 poisoning regression test) that had
  been weakened to silently skip their actual invariant when the hardlink
  tier wasn't taken (finding #5).

Finding #2 (evicting valid pre-existing/pre-#1039 blobs with no digest
sidecar) was investigated but NOT fixed as originally scoped: a first
attempt trusted any digest-less blob with hardlink_count <= 1, but that
heuristic is unsound — a since-deleted alias could have poisoned the blob
before being removed, and link count only reflects the present, not
whether a risky mutation window existed in the past. This was caught by
the existing failed_restart_eviction_restores_readonly_and_retries_after_alias_delete
regression test. Reverted to the original conservative eviction. Finding
#1's fix already eliminates the primary real-world trigger (a
freshly-persisted blob can no longer become visible without its digest);
the remaining cost is a one-time cache miss for blobs written by a
pre-#1039 zccache version on upgrade, which is the safer trade-off.

Added regression tests for findings #1, #3, #4, and the reverted-#2
investigation. Local: 434/434 zccache-daemon-core unit tests pass on
Windows; Docker Linux validation pending.

* fix: harden COW persistence and parallelize rust-plan restore

Closes #1042\nCloses #1044

* style: format COW and restore changes

* fix: preserve compiler output writability on store hardlinks

* test: allow shared inode store fast path

* fix: migrate legacy COW blob digests

Closes #1046

* test: skip hardlink-only cases on unsupported filesystems
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.

2 participants