Cache key
Inputs, normalization, and tools for explaining a cache miss
Kache hashes the inputs that can change compiler output and normalizes machine-local paths that should not. Missing a real input risks a wrong hit; retaining harmless machine identity causes avoidable misses.
Rust key inputs
Apple targets and custom target specs use a new key namespace. Their first build after upgrading misses old Rust entries, even with deployment-target variables unset, because older entries may contain objects built for a different minimum OS version.
The exact set depends on the invocation. It can include:
- rustc identity and target, including the contents of a custom target spec file
- linker identity for outputs that invoke linking
- crate name, crate types, edition, cfg values, and features
- source and included file contents discovered through dep-info
- code-generation flags, rustflags, and requested emit kinds
- lint levels and
--check-cfgvalues (-A,-W,-D,-F,--force-warn,--cap-lints), in order, because they decide whether a compile succeeds - diagnostic presentation flags (
--error-format,--json,--color), in order, because a hit replays the stored diagnostics. A terminal width is handled separately, as described below -Zflags,RUSTC_BOOTSTRAPwhen set,--sysroot, and theCARGO_CFG_*variables- the library of a codegen backend selected by name, or a backend dylib passed as a path when
cache.trust_codegen_backendsallows it, by content - other rustc flags Kache does not model, with paths normalized (
KACHE_LOG=warnnames them) - the contents of
--externdependencies - native static archives the unit links, found through
-Ldirectories,-lspecs and-C link-arg - compile-time environment values rustc reports
MACOSX_DEPLOYMENT_TARGET,IPHONEOS_DEPLOYMENT_TARGET,TVOS_DEPLOYMENT_TARGET,WATCHOS_DEPLOYMENT_TARGET, andXROS_DEPLOYMENT_TARGETfor Apple targets and custom target specs, including library and metadata compilations- native libc version and hashed CRT/startup objects for host-loaded Linux outputs, and the contents of the linker the C compiler driver runs for them (the driver's default
ld, or the one-fuse-ld,--ld-pathor-Bin-C link-argselects) - macOS SDK identity (version and build) and
MACOSX_DEPLOYMENT_TARGET, when set, for host-loaded Darwin outputs - for native Windows MSVC links: the linker (
link.exe,lld-link.exe, or therust-lld.exein rustc's sysroot), the MSVC, SDK and UCRT environment for the architecture, and the import and static libraries - configured salt, extra inputs, and declared environment inputs
- for a workspace or path package with a build script, the files and variables that script declares with
cargo:rerun-if-changedandcargo:rerun-if-env-changed
Host-loaded Linux and macOS links, and native Windows MSVC links, pass through if those inputs cannot be resolved, so no host receives a binary built against inputs the key did not record. Links for rustc-bundled self-contained WebAssembly targets (wasm32-unknown-unknown, the WASI family, wasm32v1-none, wasm64-unknown-unknown) are cached. Links with -C link-self-contained=no, links for a WebAssembly custom target spec or emscripten, and links for any other WebAssembly target that needs an external toolchain pass through. Libraries and metadata for these targets still cache.
For eligible native Windows MSVC links, absolute .res inputs also enter the key by content. Kache checks a resource's standard binary header and streams the file on each key. Absolute /MANIFESTINPUT:C:\path\app.manifest inputs can cache when their XML fits the supported application-metadata subset. Pass /MANIFEST:EMBED as well; MSVC requires it for manifest inputs. Kache validates each manifest and hashes its original bytes from the same read on every key. Resource and manifest inputs retain their kinds and argument order.
The supported XML includes assembly identity and dependencies, descriptions, execution privileges, OS compatibility, DPI awareness and long-path awareness. UTF-8 and BOM-marked UTF-16 are accepted. DTDs, general entities, processing instructions, XInclude, schema references, file/COM/type-library entries and unknown elements or attributes pass through. Manifests are limited to 1 MiB, 32 nested elements, 4096 elements, 32 attributes per element and 32 namespace bindings in scope. Raw .obj, .o, .a and .lib inputs, linker response files, side-by-side manifest outputs, and a link-args value that mixes /LIBPATH with other arguments still pass through.
Manifest inputs also key the selected mt.exe path and original bytes. Kache searches rustc's tool directories followed by the discovered MSVC environment's PATH. Missing, unreadable or non-regular mergers, linker wrappers, and an mt.exe in the linker directory, working directory or Windows system directories pass through. Dangling directory links and /MANIFESTDEPENDENCY also pass through. Changes to the directories checked during merger selection prevent storing a result under the earlier key.
/NODEFAULTLIB and /NODEFAULTLIB:name are exclusions, not file inputs; a name ending in .lib does not make an exclusion uncacheable. /DEFAULTLIB:name is a narrow exception to the file-option restriction: only names in Kache's modeled CRT, vcruntime and UCRT families are accepted, with an optional .lib suffix. The option and name are case-insensitive, and -DEFAULTLIB:name is also accepted. Paths, quoted names, = spellings, comma-packed arguments and arbitrary libraries remain unsupported. A link-arg carries one option; link-args may carry whitespace-separated options.
Each explicit default library must have a selected runtime hash, even if NODEFAULTLIB could suppress it. Requests retain their order in the key. Resolution uses LINK's modeled search order rather than rustc's -l lookup: the working directory, ordered /LIBPATH directories, then LIB. Missing candidates allow the search to continue. A non-file candidate, metadata error other than absence, or unreadable selected file makes the link uncacheable instead of falling back to a later copy.
An explicitly requested runtime must also be a regular COFF/GNU32 archive of at most 64 MiB. Kache accepts version-0 COFF short-import members and ordinary x86, x64, Thumb-2 ARM or ARM64 COFF members without .drectve, .debug$T or .debug$P sections. Those sections can introduce further libraries, PDBs or precompiled type inputs. Archive member and section names are limited to 256 bytes. Thin, BSD and GNU64 archives, bigobj, LTCG, malformed containers and unsupported member formats pass through. Kache validates and hashes the same file bytes in one read; this check does not change invocations without explicit DEFAULTLIB requests.
On macOS, every cached executable link gets ld64 -oso_prefix set to Cargo's profile directory, so N_OSO object paths in the binary are not checkout-local. A cached proc-macro link gets -install_name @rpath/lib<crate>.dylib. A cached executable or test binary built with debug info also stores a .dSYM bundle, made with dsymutil while its object files still exist. A restore unpacks it beside the binary, where lldb looks first. Without dsymutil, the binary is cached without one.
Restoring one debug bundle allows up to 8 GiB of unpacked file contents in total by default. Set cache.restore_max_size or KACHE_RESTORE_MAX_SIZE to change this limit, for example kache config set cache.restore_max_size 12GiB. Larger bundles fall back to recompilation. Restore failures in reports and logs include the underlying cause, such as exceeding this limit. Control characters in those details become spaces, and long messages are truncated.
On Windows, executable caching remains opt-in. A cached PE executable and the sibling PDB named by its CodeView record are stored and restored together after checking their GUID and executable-validation ages. The check also covers explicit -o names without an .exe suffix. Ambiguous or malformed debug records, missing or incompatible PDBs, non-sibling PDB paths, and an incremental-link .ilk sidecar leave the compilation uncached. A PE without a CodeView record needs no PDB; non-PE executables keep their existing handling.
The PE's mapped CodeView address and raw file pointer must identify the same bytes. File-only CodeView records with no mapped address are left uncached, even though PE permits that layout. FASTLINK PDBs are also left uncached: a matching GUID and age do not make their original object and library files portable. Kache reads the PDB Info feature tail to identify that mode, with a 1 MiB admission limit for the Info stream. Larger streams and unsupported features cause a cache miss.
Windows executable keys use a separate pairing-admission field, so older EXE-only entries cannot win local, remote or concurrent lookups. Linked executables for custom targets, or an explicit target with RUST_TARGET_PATH set, use that field conservatively because their file format is not inferred from the target name. Those entries miss once after upgrading; libraries and known non-Windows executable targets without that custom-target ambiguity retain their keys. Cached pairs are checked again before any output is restored.
Since v2.1.0, a reported Windows DLL also stores existing sibling import/export
artifacts with that DLL's name (foo.dll.lib, foo.dll.exp, or foo.dll.a).
Missing sidecars are omitted. Cargo builds do not scan the directory or collect
another crate's import library.
-C split-debuginfo=off skips Kache's .dSYM generation and restoration, including bundles in older cache entries. -C debuginfo=0 and -C debuginfo=none also skip bundling. Without a bundle, source-level debugging of a cached binary can depend on the producing build's object files.
Incremental directory names and harmless local path spellings are excluded or normalized.
Changing diagnostic presentation can cause a miss even when the artifact bytes would match. Builds with the same diagnostic flags still share entries. The diagnostic-key update also causes existing rustc entries to miss once, including invocations without explicit presentation flags.
Cargo passes --diagnostic-width only when stderr is a terminal. Kache leaves a
single width between 1 and 65,535 columns out of the key and forwards it
unchanged to rustc, so a crate built in a terminal, after a resize, and through
a pipe by an editor, agent or script computes the same key.
A compile whose output is the same at every width is stored under that key and
shared by all of them. This covers crates without warnings and dependencies
whose lints are capped, including nightly Cargo's silent unused-dependency
report. Only empty output and known JSON records without rendered text count.
Compiler stdout, rendered warnings, a future-incompat report containing
warnings, and unknown or truncated diagnostics do not.
When a terminal build renders warnings, Kache stores it under a second key derived from the first key and the width. A later build at that width hits it and replays the warnings exactly as rustc rendered them. Another width compiles once and stores its own entry. A piped build stores its warnings under the shared key, which terminal builds use only when its output is width-free.
Malformed or repeated width options stay in the key, so a cached success cannot hide rustc's error about them. After upgrading, crates that warn at a terminal width miss once. Piped builds and capped dependencies keep their keys.
Explicit per-kind Rust output destinations, such as --emit=metadata=custom.rmeta, pass through to rustc so it writes the requested file. Emit kinds without destinations still use the cache. This fix changes Rust cache keys, so existing Rust entries miss once after upgrading.
Use kache explain and trace logging to see the components for a particular build.
Input predictions are enabled by default for eligible Rust units. Kache
revalidates their recorded inputs and falls back to dependency discovery when
the record cannot be used. Set KACHE_INPUT_PREDICTIONS=0 or
[cache] input_predictions = false to disable predictions.
A proc macro can list a directory and include each file in it, so a new file
can change a crate's output while every input Kache recorded stays the same.
The macro need not be a direct dependency: sqlx::migrate! and
include_dir! reach their macro crates through a library that re-exports
them. A record for a workspace or path crate is therefore used only while the
workspace and the crate's OUT_DIR hold what the recording build saw. This
applies in the crate's own checkout as well as in another target directory or
checkout. The check leaves out the target directory, .git, the contents of
any other directory Cargo tagged as a target directory, Kache's own cache and
runtime directories, and what Cargo writes in its home, such as its downloads
and its .global-cache record. Kache and Cargo write to all of them, and a CI
job may keep Kache's cache and Cargo's home inside the project, as GitLab
requires for cached paths. The rest of Cargo's home counts, such as
.cargo/config.toml when the home is the project's .cargo. An entry Kache
cannot read counts by its name, since a proc macro cannot read it either.
Checking an unchanged workspace costs one stat of each entry, and writing a
record stats each entry again; Kache reads the files again after a change.
The check has costs:
- After any change in the workspace, each crate runs dependency discovery
once on the next build that would otherwise restore it, such as a build
after
cargo clean, in a new target directory, or on CI with a restored cache. - With adaptive incremental mode, the build that starts incremental compilation of a crate you are editing, and the first edit after a hit, run dependency discovery before compiling. On a large crate that takes roughly half as long as an incremental check.
- A record written while files in the workspace change does not carry the check, so its crate runs dependency discovery again on the next build, even if the files end up unchanged.
- A workspace of more than 20,000 entries is not checked, so its crates always use dependency discovery.
- A crate that reads a file outside the workspace, in a target directory
other than its
OUT_DIR, or through a symlinked directory always uses dependency discovery.
The check does not see:
- A directory a macro lists outside the workspace, or through a symlinked directory, that held no file the crate read when the record was made. A file added there goes unseen.
- On Windows, a listed file removed and put back with its old size and modification time while the crate compiles. On Linux and macOS its new inode and change time show it.
A registry crate is the same files wherever it is built, so it is checked
against its package and OUT_DIR only when it has a proc-macro dependency of
its own. A vendored crate (one cargo vendor copied into the tree, as Firefox
does under third_party/rust) is checked against its own package, its
OUT_DIR, and the files and dot-directories at the top of each directory
between it and the workspace root, so it shares records at any tree size.
With a remote configured, records travel with the entries. A machine with no record for a unit asks the remote for one before running the pre-pass, and records made here go to a writable remote. A record that names a machine-local path outside the Cargo registry is not published, and registry paths travel relative to it. A record from the remote is checked like a local one.
Clippy
cargo clippy runs workspace crates through clippy-driver, which Cargo
composes with Kache as kache clippy-driver rustc …. Kache keys those units
like any rustc unit. It also adds the Clippy version, the lint arguments Cargo
passes in CLIPPY_ARGS, CLIPPY_DISABLE_DOCS_LINKS, the package's
Cargo.toml (the cargo lint group reads it), and the content of the .clippy.toml or clippy.toml Clippy would
load, found from CLIPPY_CONF_DIR or the crate's manifest directory upwards. A hit restores the outputs and replays the recorded
diagnostics, so warnings appear exactly as on the first run. Other
RUSTC_WORKSPACE_WRAPPER drivers stay uncached.
Miri
cargo miri sends no Rust compile through Kache. cargo-miri sets
RUSTC_WRAPPER to itself and clears RUSTC_WORKSPACE_WRAPPER, and the
environment variable overrides build.rustc-wrapper from Cargo's config, so
Kache never sees the Miri compiles or the Miri sysroot build. It prints a
warning only when RUSTC_WRAPPER was set in the environment. Build scripts
that compile C through CC or HOST_CC still reach Kache, as in any other
build.
Misses without a record
The first time a unit is built on a machine, Kache has no recorded closure to
derive a key from. When no remote, fallback wrapper or read-only store is
configured and the store holds no entry for the unit, the miss is certain.
Kache then compiles first and keys from the dep-info the compile emitted,
instead of spawning rustc --emit=dep-info to discover the closure before
compiling. When an entry could exist, because the store holds one for the unit
or the unit's record no longer applies, a compile that does not link also
starts at once: rustc writes its dep-info right after macro expansion, Kache
keys from it there, and if that key is stored it stops rustc and restores the
entry. A predicted key that missed is re-derived from the running compile the
same way. Every input in that closure is checked against the build's start
time. An input written during the compile leaves the result unstored, and so
does one written so shortly before the build started that its recorded write
time cannot tell the two apart: within the same kernel clock tick (1 to 10 ms)
on Linux, 1 ms on macOS and Windows, 20 ms on other systems, and 2 seconds on file systems
that keep whole seconds, such as HFS+ and FAT. Peers of the same unit in other
target directories wait for this compile as they would for a pre-pass.
Crates with extra inputs keep the pre-pass, and so does every Rust unit when
the scheduler is off (KACHE_SCHEDULER=0). A unit with
adaptive incremental
state keeps it too, because its key decides whether a miss compiles
incrementally, and so does a crate listed in KACHE_INCREMENTAL_CRATES. When
such a unit misses and no incremental lane takes the compile, Kache compiles
before keying again from the closure the compile emits, so a source written
during the compile leaves the result unstored. For a unit that links, a
predicted key is first re-derived with the pre-pass, because that compile
cannot be stopped on a hit.
[cache] deferred_discovery = false or KACHE_DEFERRED_DISCOVERY=0 restores
the pre-pass everywhere.
A C or C++ compile without a recorded read set does the same: it compiles with a dependency file and keys from the digest of the files that compile read, instead of preprocessing first. An input written while that compile ran, or within the same margin before it started, leaves its result unstored and records no read set, so the unit's next build compiles first again. A unit whose input a build step rewrites right before every compile is therefore not cached. A record whose files changed is rediscovered with the preprocessor, which yields the same key.
Since v2.1.0, unchanged C/C++ header inputs reuse their recorded keys. Existing C/C++ objects miss once after upgrading because older memo validation could accept a stale key. Recorded input sets remain usable. The C/C++ recipe fix does not change Rust keys. V2.1.0 also advances the shared key version from 33 to 34, so existing Rust entries miss once. Old entries expire through normal cache cleanup.
Path normalization
Kache maps known roots to stable sentinels before hashing and asks the compiler to emit matching remapped paths. This allows equivalent worktrees and runners to share entries.
Common mappings include the workspace, Cargo home, Rustup home, temporary directory, target directory, and configured base directories. Add a missing root with KACHE_BASE_DIR or paths.base_dirs.
Source files under Cargo's profile directory, such as the code a build script generates in OUT_DIR, appear as /kache/profile/... in compiled output, and their key identity leaves out the profile name. A custom profile that inherits dev and changes nothing compiles the same crates as dev, so it reuses their entries, including crates that include! generated code.
Do not choose an overly broad base directory. Normalization merges path identities, so two different inputs must not map to the same sentinel.
Disable Rust path normalization for a local profiling or debugging session:
KACHE_RUSTC_PATH_NORMALIZE=0 cargo build
That puts real paths in debug information and makes the key local to those path identities. C/C++ has the corresponding KACHE_CC_PATH_NORMALIZE=0 control.
Coverage-instrumented Rust builds use real paths and a separate, path-local key namespace so coverage tools can find source files.
Crates that trybuild builds under target/tests/trybuild/ get the same treatment. trybuild passes --cfg trybuild to every one of them. It compares rustc's rendered diagnostics against the checked-in .stderr snapshots after substituting the real crate, workspace, and registry directories, so a remapped path such as /kache/home/... or /proc/self/cwd/... would fail every snapshot. Those units still cache, keyed by the real paths their output records. A registry dependency trybuild builds is keyed by its path under the Cargo home, so worktrees on one machine share it. Its build script's OUT_DIR lives in the target directory and joins the key only when the crate's code reads from it: an include!d generated file, or an env!("OUT_DIR") value the compiled code keeps. The test crates trybuild generates are keyed by their directory under the target directory.
An explicit -L native= directory inside a unit's own OUT_DIR can share an
rlib key across target directory and profile names. Kache retains its path
below the profile directory and hashes the native archives, including their member names,
timestamps and contents. Archives whose digest retains their path can still
miss after relocation. This applies only when Rust path normalization is on,
the search path and OUT_DIR are absolute, and the resolved search directory
stays inside that OUT_DIR. Native links, test binaries, staticlib outputs,
metadata-only outputs, and bare, all= or framework= search paths keep their existing path
identity, as do coverage, trybuild and normalization opt-out builds.
Debugger source maps
On macOS and Windows, map the stable workspace prefix back to your checkout:
set substitute-path /kache/workspace /absolute/path/to/checkout
settings set target.source-map /kache/workspace /absolute/path/to/checkout
Linux workspace paths use /proc/self/cwd when possible, so running the debugger from the workspace root usually resolves them directly.
Generated sources under Cargo's profile directory appear under /kache/profile on every platform. Map that prefix to the profile you debug, for example set substitute-path /kache/profile /absolute/path/to/target/debug.
Crates from the registry or Git appear under /kache/.cargo on every platform. Map that prefix to your Cargo home the same way, for example set substitute-path /kache/.cargo /absolute/path/to/.cargo, to step into them.
Inputs the compiler does not report
A proc macro can read files and environment variables rustc never reports. Tauri's generate_context! reads tauri.conf.json and TAURI_CONFIG; an asset embedder lists a directory. When the package's own build script declares those inputs with cargo:rerun-if-changed or cargo:rerun-if-env-changed, Cargo reruns the script after a change and recompiles the package. Kache keys every Rust unit of a workspace or path package on what its build script declared, so that recompile misses instead of restoring the artifact built from the old inputs. A script that declares nothing makes the package's own files other than Rust sources the input, as Cargo does. Build scripts describes what is keyed and what is not.
For an input no build script declares, or one another package's build script declares, use these controls:
cache.key_saltorKACHE_KEY_SALTfor an opaque toolchain boundary- crate
kache.tomlfor files read during compilation but absent from dep-info workspace.extra_inputsfor workspace-root provider inputscache.key_env_varsfor environment read by proc macros throughstd::envcache.path_only_env_varsfor locator variables proven not to affect emitted bytes, and for thecrate:VARassertion that keeps a crate whose include comes from another crate's macro (tonic::include_proto!,lalrpop_mod!) reusable across checkouts
See Configuration for syntax and safety limits.
Explain a miss
kache explain my_crate
kache explain with no crate explains the latest build: each cause of its misses, costliest first, against the build before it. --root limits it to one build tree. kache explain my_crate says why that crate's last compile missed and how its stored entries differ in target, profile, features and crate type.
To have explain name the input groups that changed, turn on [cache] explain_miss (or KACHE_EXPLAIN_MISS=1) before the builds you want to compare; both builds need it. The wrapper compares a miss with the last recorded hit for the same Cargo compilation unit in that build tree. A library and binary with the same crate name are separate units. If either record lacks a unit identity, the wrapper leaves its group comparison unavailable.
The setting also records dependency digests and unit ids that let explain follow a miss down to the dependency that changed and, in a second checkout with no earlier build of the crate, compare with the same unit built in another checkout. Groups are hashed after path normalization, so the checkout path alone does not change them. The exception is remap when path remapping is off: that group keys the checkout path on purpose. Any other group that differs between checkouts is a real input difference or a path that normalization missed.
A changed link group can include timestamps in native archives, even when
their object code is identical. See
deterministic native archives
before changing cache settings.
For individual components, run the trace command kache explain my_crate suggests, typically:
KACHE_LOG=trace cargo build -p my_crate 2>&1 | grep '\[key:my_crate\]'
With KACHE_LOG=warn, the wrapper also logs residual absolute path detected in ... when a keyed value still names a home or temporary directory after normalization.