Skip to content

rust: prevent unsafe cross-checkout cache hits - #2794

Open
pamarcos wants to merge 23 commits into
mozilla:mainfrom
pamarcos:rust-basedirs
Open

pamarcos wants to merge 23 commits into
mozilla:mainfrom
pamarcos:rust-basedirs

Conversation

@pamarcos

@pamarcos pamarcos commented Aug 5, 2026 •

Copy link
Copy Markdown
  • rust: add support for SCCACHE_BASEDIRS when hashing #2918 and fix(rust): write dep-info locally not restoring from cache #2894 supplied the underlying feature and dep-info handling.
  • This PR prevents cached artifacts from returning another checkout’s paths. All four can make checkout B reuse an artifact containing checkout A’s paths:
    1. Environment literals: env!("CARGO_MANIFEST_DIR") embeds the directory verbatim. Normalizing its cache-key value can return the wrong string, even with compiler remapping enabled.
    2. Missing compiler remapping: Stripping paths from the key alone does not change file!() output. Different absolute source paths must remain distinct unless rustc remaps them.
    3. Different remap destinations: Mapping A to /first and B to /second produces different output. Remap destinations must remain significant in the key.
    4. Procedural macros: A macro can read the physical working directory and embed it without recording an environment dependency. Compiler remapping does not rewrite that arbitrary output.
  • Four executable regressions demonstrate the failures; a control proves safe reuse still works.
  • The conservative guards reduce cache hits, and the cache-key bump invalidates existing Rust entries.

mmastrac and others added 5 commits July 31, 2026 13:25
SCCACHE_BASEDIRS now normalizes cwd, CARGO_MANIFEST_DIR,
CARGO_WORKSPACE_DIR, CARGO_TARGET_TMPDIR, CARGO_MANIFEST_PATH,
CARGO_BIN_EXE_*, dep-info env var values, and the concatenated
argument string in the Rust compiler's hash key computation. This
enables cache hits when the same crate is compiled from different
absolute paths on different machines (e.g., CI runners with
different checkout roots).

strip_basedir_prefix now also matches when the value equals the
basedir minus its trailing '/', so `cwd == basedir` strips to the
empty string rather than passing through. Without this, two
machines with different checkout paths produced different hashes
even with matching basedirs -- the feature's central claim.
mozilla#2652
mozilla#2678

Keep rustc-reported environment dependencies location-sensitive and hash
PGO data and LLVM plugins before normalizing their paths. Preserve non-path
argument bytes on Windows and use conservative matching for non-ASCII input.

Handle exact and overlapping basedirs consistently, bump the Rust cache-key
version, and document that embedded paths still require compiler remapping.
mozilla#2652
mozilla#2678

Replace broad Rust argument scanning with normalization of explicit remap
prefixes and path-valued Cargo variables. Hash the actual path produced by
rustc remapping, honoring scope and mapping precedence, while keeping
unremapped working directories location-sensitive.

Frame normalized values to prevent absolute and relative inputs from sharing
a key. Reduce the mock and integration-test changes, and leave profile and
plugin paths location-sensitive.
Hash effective source paths without conflating duplicate remaps, and preserve Cargo path values whenever procedural macros can run.

Honor rustc remap-scope precedence, keep non-identity distributed path transforms local, add CARGO_INSTALL_ROOT coverage, and bump the key version.
Version 7 was introduced by this unmerged change series, so later refinements do not require another upstream cache-key version.
@sylvestre

Copy link
Copy Markdown
Collaborator

Long comment #0 written by a llm isn't useful... Please make it shorter

@codecov-commenter

codecov-commenter commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.35691% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.01%. Comparing base (97bd4af) to head (80b59fa).

Files with missing lines Patch % Lines
tests/sccache_cargo.rs 98.40% 3 Missing ⚠️
src/compiler/rust.rs 99.76% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2794      +/-   ##
==========================================
+ Coverage   78.74%   79.01%   +0.27%     
==========================================
  Files          74       74              
  Lines       45218    45800     +582     
==========================================
+ Hits        35606    36191     +585     
+ Misses       9612     9609       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@pamarcos

pamarcos commented Aug 5, 2026

Copy link
Copy Markdown
Author

Long comment #0 written by a llm isn't useful... Please make it shorter

Roger. I cut most of it. Left the implementation details available in case someone's interested, though.

Build expected remapped paths with Path::join because rustc uses platform-native separators. This fixes the Windows test matrix without changing remap behavior.
Exercise malformed and nonmatching remap values, separated scope syntax, and absolute source arguments.

Coverage report: https://app.codecov.io/gh/mozilla/sccache/pull/2794?src=pr&el=tree
Comment thread src/compiler/rust.rs Resolved
Comment thread src/compiler/rust.rs Outdated
// rustc dep-info. They can be explicit externs or resolved from a crate search path.
let normalize_cargo_paths = !basedirs.is_empty()
&& remap_path(&cwd, &os_string_arguments).is_some()
&& env_vars.iter().any(|(var, _)| is_path_cargo_env(var))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Env sanitization is better to be be split out to its own PR

@pamarcos pamarcos Aug 10, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can still split it in a separate PR if you insist, but I didn't do it at first because is a hard requirement for this feature to work with cargo. Otherwise, AFAIU without this we could only make the rustc compiler support cross-worktree cache hits.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, the rationale is well understood. Just feel like a fix of #2494 could be shipped incrementally without too much burden on review side, and has value on its own, and is also easy to revert/bisect if something bug pops up.

I not a maintainer btw. You could keep your original comment I don't mind.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, I'll keep it as it is for now waiting for a maintainer to give their opinion on it. I'll do whatever makes everyone's life easier

Cargo does not provide CARGO_WORKSPACE_DIR as a built-in environment variable. Do not treat a user-defined variable with that name as a path eligible for basedir normalization.
Retain physical cache-key paths whenever a procedural macro may observe them. Rewrite cached dep-info targets for the current output paths while preserving permissions and rejecting ambiguous records.
Keep the locally generated dependency records from the hash probe and use them to rebuild cached dep-info after extraction. This prevents absolute source paths, environment records, and checksums from referring to the producer checkout.
CARGO_WORKSPACE_DIR is not provided by Cargo, so asserting its treatment as an arbitrary user-defined variable does not document useful built-in behavior.
@packplusplus

packplusplus commented Aug 25, 2026 •

Copy link
Copy Markdown

We're running into these cache path issue with our shared ci runners writing back to shared s3 (multiple runners on a single host with randomized build dirs). I'm running a POC on if this works for us. I feel like cleaning up the failed ci jobs would be a positive step in getting it merged while you wait for a maintainer.

Edit: The POC work is interesting. The conservative decision no explicit externs, and crate search paths contain no dynamic libraries made the cache efficacy for several of our builds negligible. An ai slopped version that allows ordinary .rlib externs and -L dependency normalization gave better caching (closer to 25%), but I'm not sure the safety of it (certainly not enough to propose to upstream).

Edit 2: the slopped version is too risky, it 100% had a physical path from a cached library artifact. there may still be a path, but i'm wary of diving too deep on this.

Find compiler dep-info recursively so the cross-checkout test works with both legacy and build-dir layout v2. Allow the readonly-permission Clippy lint only on Windows, where its Unix warning does not apply.
@codspeed

codspeed Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 62 untouched benchmarks
⏩ 6 skipped benchmarks1


Comparing pamarcos:rust-basedirs (80b59fa) with main (97bd4af)

Open in CodSpeed

Footnotes

  1. 6 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@pamarcos

pamarcos commented Oct 4, 2026 •

Copy link
Copy Markdown
Author

@codspeedbot fix this regression

EDIT: I am merging master into this PR so that they are in sync, hoping the performance difference comes from a newer version, not these changes.

@sylvestre

Copy link
Copy Markdown
Collaborator

rustfmt is sad :)
could you please run cargo fmt?

Diff in /home/runner/work/sccache/sccache/tests/sccache_cargo.rs:95:
         .find_map(|entry| {
             let path = entry.ok()?.into_path();
             (path.extension().is_some_and(|extension| extension == "d")
-                && path.file_stem().is_some_and(|stem| {
-                    stem.as_encoded_bytes().starts_with(b"basedirs_test-")
-                }))
+                && path
+                    .file_stem()
+                    .is_some_and(|stem| stem.as_encoded_bytes().starts_with(b"basedirs_test-")))
             .then_some(path)
         })
         .context("missing dep-info for second checkout")?;
##[error]Process completed with exit code 1.
Post job cleanup.
[command]/usr/bin/git version
git version 2.56.0
Temporarily overriding HOME='/home/runner/work/_temp/c12af8f4-23c1-405e-93fe-292a48dfbc39' before making global git config changes
Adding repository directory to the temporary git global config as a safe directory
[command]/usr/bin/git config --global --add safe.directory /home/runner/work/sccache/sccache

@sylvestre

Copy link
Copy Markdown
Collaborator

thanks for the PR!
This can't land yet because the dep-info changes (the strict target check and the rewrite on every cache hit) affect all Rust users, not only those using SCCACHE_BASEDIRS. Details are inline.
CodSpeed also reports a 10.8% regression, please check whether it comes from this change.

Comment thread src/compiler/rust.rs Outdated
}

#[cfg(windows)]
fn strip_basedir_prefix<'a>(value: &'a [u8], basedirs: &[Vec<u8>]) -> Cow<'a, [u8]> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both functions always return Cow::Borrowed, so a plain &[u8] would do, no?
and the prefix_len == 0 branch is the same as &value[0..]

Comment thread src/compiler/rust.rs Outdated
}

#[cfg_attr(windows, allow(clippy::permissions_set_readonly_false))]
fn rewrite_dep_info_targets(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function is quite long, with a lot of cfg(windows) permission handling
could it be simplified or split up?

Comment thread src/compiler/rust.rs Outdated
let mut target_dependencies = target_line
.strip_prefix(&*target)
.filter(|suffix| suffix.starts_with(": "))
.context("Rust dep-info target does not match requested path")?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

before, any target name was accepted here; now a mismatch fails the hash for every Rust compile
why does this need to be strict when basedirs are not set?

Comment thread src/compiler/rust.rs Outdated
let can_normalize_paths = !basedirs.is_empty()
&& self.parsed_args.externs.is_empty()
&& !self.parsed_args.crate_link_paths.iter().any(|path| {
fs::read_dir(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking read_dir on every -L dir inside the async hash, for every compile
also cargo always passes -L dependency=target/debug/deps, which usually has a proc-macro .so, so in practice this disables the feature
could this be checked only when basedirs are set, in spawn_blocking?

Comment thread src/compiler/rust.rs Outdated
})
.collect::<Vec<_>>();
source_inputs.sort();
for index in 0..source_inputs.len() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this duplicate detection is hard to follow
could it be simplified, maybe with chunk_by on the sorted list?

Comment thread src/compiler/rust.rs Outdated
Ok((CCompileCommand::new(command), dist_command, Cacheable::Yes))
}

fn postprocess_cache_hit(&self, cwd: &Path) -> Result<()> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this rewrites the dep-info on every cache hit, even without SCCACHE_BASEDIRS
could it run only when the key was actually normalized?

@pamarcos

pamarcos commented Nov 3, 2026 •

Copy link
Copy Markdown
Author

Thanks for the insightful feedback :)

I see that while this PR was waiting for someone to approve the CI to be run, two other related PRs have already been merged: #2918 and #2918.

I'm gonna use what's upstream but keeping the safety guarantees that this PR provides, with examples of some cache reusability that are wrong with the upstream approach if that's ok for you.

Adopt upstream's local dep-info generation and remove the cached-output rewrite hook.
Keep literal environment dependencies, remap destinations, and unremapped source identities
in Rust cache keys. Restrict normalization around procedural macros and partial remap scopes.
Advance the Rust cache-key version to avoid reusing unsafe entries.

Add executable regressions comparing cached and fresh builds across checkouts, alongside a
safe cache-hit control. Document the supported cases and conservative Cargo limitations.

Related: mozilla#2918
Related: mozilla#2894
@sylvestre

Copy link
Copy Markdown
Collaborator

sorry but it needs to be rebased

@pamarcos pamarcos changed the title rust: support SCCACHE_BASEDIRS across checkout roots rust: prevent unsafe cross-checkout cache hits Nov 3, 2026
@pamarcos

pamarcos commented Nov 3, 2026

Copy link
Copy Markdown
Author

sorry but it needs to be rebased

yep, @sylvestre. I ended up leaving what's upstream but with the safe guarantees that this PR provided in terms of cache invalidation.

Comment thread docs/Rust.md
| Sources and working directories remapped to the same virtual paths, without other path-sensitive inputs | A hit is possible. |

To enable the last case, set `SCCACHE_BASEDIRS` to the checkout roots and pass
`--remap-path-prefix=<current-checkout>=/workspace` to rustc in each checkout.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, cargo has a trim-paths feature that we probably want to take a look: https://doc.rust-lang.org/nightly/cargo/reference/profiles.html#trim-paths (will be stabilized in 1.101).

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.

6 participants