From 27f4d9e6a13404499359789abf010beeca75ded1 Mon Sep 17 00:00:00 2001 From: Tripp Cashel Date: Tue, 18 Aug 2026 12:39:41 -0400 Subject: [PATCH 1/8] server: scope basedirs to compile requests --- README.md | 15 ++- docs/Configuration.md | 2 +- src/cache/basedirs.rs | 185 +++++++++++++++++++++++++++++ src/cache/mod.rs | 2 + src/commands.rs | 10 +- src/compiler/nvcc.rs | 13 +- src/config.rs | 147 +++++++++++++++-------- src/server.rs | 47 ++++++-- tests/sccache_cargo.rs | 261 +++++++++++++++++++++++++++++++++++++---- 9 files changed, 599 insertions(+), 83 deletions(-) create mode 100644 src/cache/basedirs.rs diff --git a/README.md b/README.md index 188fa8149f..4a998f371d 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,9 @@ This is similar to ccache's `CCACHE_BASEDIR` and helps when: * Multiple developers working with different username paths * Working with multiple project checkouts simultaneously -**Note:** Only absolute paths are supported. Relative paths will prevent server from starting. +**Note:** Only absolute paths are supported. A relative request value fails that +compiler invocation. A relative config-file value prevents the server from +starting. You can also configure this in the sccache config file: @@ -379,6 +381,17 @@ basedirs = ["/home/user/project"] basedirs = ["/home/user/project", "/home/user/workspace"] ``` +The environment variable applies to each compiler invocation. Its value +overrides the config-file value for that request, so a persistent sccache +daemon can serve builds from different checkout roots without a restart. Set +`SCCACHE_BASEDIRS=""` on an invocation to disable the config-file fallback for +that request. + +Only the config file defines the daemon's fallback. A `SCCACHE_BASEDIRS` value +in the environment that starts the daemon does not become global daemon state. +Statistics report the config-file fallback and do not accumulate paths from +individual requests. + --- Known Caveats diff --git a/docs/Configuration.md b/docs/Configuration.md index 6fc796c505..b6bde3e4df 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -192,7 +192,7 @@ Note that some env variables may need sccache server restart to take effect. * `SCCACHE_ALLOW_CORE_DUMPS` to enable core dumps by the server * `SCCACHE_ALLOW_INCREMENTAL` set to `1` to allow Rust builds with `CARGO_INCREMENTAL=1`; incremental crates go uncached. See [Rust caveats](Rust.md) * `SCCACHE_CONF` configuration file path -* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. Environment variable takes precedence over file configuration. Only absolute paths are supported; relative paths will cause an error and prevent the server from start. +* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. The environment variable applies to each compiler invocation and overrides the config-file fallback for that request. An explicitly empty value disables the fallback for that request. Only the config file defines the daemon fallback; the daemon ignores `SCCACHE_BASEDIRS` in its startup environment. Statistics report only the configured fallback. Only absolute paths are supported; a relative path causes an error for the affected invocation or during config-file loading. * `SCCACHE_CACHED_CONF` * `SCCACHE_DIST_CLIENT_CACHE_DIR` distributed toolchain cache directory; overrides `[dist].cache_dir` from the configuration file. * `SCCACHE_IDLE_TIMEOUT` how long the local daemon process waits for more client requests before exiting, in seconds. Set to `0` to run sccache permanently diff --git a/src/cache/basedirs.rs b/src/cache/basedirs.rs new file mode 100644 index 0000000000..0d9a38d142 --- /dev/null +++ b/src/cache/basedirs.rs @@ -0,0 +1,185 @@ +// Copyright 2026 Mozilla Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use bytes::Bytes; + +use crate::cache::multilevel::MultiLevelStats; +use crate::cache::{Cache, CacheMode, CacheWrite, GetPathResult, Storage}; +use crate::compiler::PreprocessorCacheEntry; +use crate::config::PreprocessorCacheModeConfig; +use crate::errors::*; + +struct BasedirsStorage { + inner: Arc, + basedirs: Vec>, +} + +pub(crate) fn with_basedirs(storage: Arc, basedirs: Vec>) -> Arc { + if storage.basedirs() == basedirs { + storage + } else { + Arc::new(BasedirsStorage { + inner: storage, + basedirs, + }) + } +} + +#[async_trait] +impl Storage for BasedirsStorage { + async fn get(&self, key: &str) -> Result { + self.inner.get(key).await + } + + async fn get_with_raw(&self, key: &str) -> Result<(Cache, Option)> { + self.inner.get_with_raw(key).await + } + + async fn put(&self, key: &str, entry: CacheWrite) -> Result { + self.inner.put(key, entry).await + } + + async fn get_raw(&self, key: &str) -> Result> { + self.inner.get_raw(key).await + } + + async fn put_raw(&self, key: &str, data: Bytes) -> Result { + self.inner.put_raw(key, data).await + } + + async fn check(&self) -> Result { + self.inner.check().await + } + + fn location(&self) -> String { + self.inner.location() + } + + fn cache_type_name(&self) -> &'static str { + self.inner.cache_type_name() + } + + async fn current_size(&self) -> Result> { + self.inner.current_size().await + } + + async fn max_size(&self) -> Result> { + self.inner.max_size().await + } + + fn multilevel_stats(&self) -> Option { + self.inner.multilevel_stats() + } + + fn preprocessor_cache_mode_config(&self) -> PreprocessorCacheModeConfig { + self.inner.preprocessor_cache_mode_config() + } + + fn basedirs(&self) -> &[Vec] { + &self.basedirs + } + + async fn get_path(&self, key: &str) -> GetPathResult { + self.inner.get_path(key).await + } + + async fn get_preprocessor_cache_entry( + &self, + key: &str, + ) -> Result>> { + self.inner.get_preprocessor_cache_entry(key).await + } + + async fn put_preprocessor_cache_entry( + &self, + key: &str, + entry: PreprocessorCacheEntry, + ) -> Result<()> { + self.inner.put_preprocessor_cache_entry(key, entry).await + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::cache::disk::DiskCache; + use crate::cache::readonly::ReadOnlyStorage; + + #[tokio::test] + async fn request_view_preserves_storage_capabilities() -> Result<()> { + let tempdir = tempfile::tempdir()?; + + let fallback = vec![b"/configured/".to_vec()]; + let storage: Arc = Arc::new(DiskCache::new( + tempdir.path(), + 1024 * 1024, + &tokio::runtime::Handle::current(), + PreprocessorCacheModeConfig::default(), + CacheMode::ReadWrite, + fallback.clone(), + )); + + let unchanged = with_basedirs(Arc::clone(&storage), fallback.clone()); + assert!(Arc::ptr_eq(&unchanged, &storage)); + + let request_basedirs = vec![b"/request/".to_vec()]; + let view = with_basedirs(Arc::clone(&storage), request_basedirs.clone()); + let empty_view = with_basedirs(Arc::clone(&storage), vec![]); + assert!(!Arc::ptr_eq(&view, &storage)); + assert_eq!(view.basedirs(), request_basedirs); + assert!(empty_view.basedirs().is_empty()); + assert_eq!(storage.basedirs(), fallback); + assert_eq!(view.location(), storage.location()); + assert_eq!(view.cache_type_name(), storage.cache_type_name()); + + let key = "0123456789abcdef"; + let raw: Bytes = CacheWrite::default().finish()?.into(); + + view.put_raw(key, raw.clone()).await?; + assert_eq!(view.get_raw(key).await?.as_deref(), Some(raw.as_ref())); + let (cache, combined_raw) = view.get_with_raw(key).await?; + assert!(matches!(cache, Cache::Hit(_))); + assert_eq!(combined_raw.as_deref(), Some(raw.as_ref())); + assert!(matches!(view.get_path(key).await, GetPathResult::Found(_))); + + let entry_key = "fedcba9876543210"; + view.put(entry_key, CacheWrite::default()).await?; + assert!(matches!(view.get(entry_key).await?, Cache::Hit(_))); + + let preprocessor_key = "preprocessor"; + view.put_preprocessor_cache_entry(preprocessor_key, PreprocessorCacheEntry::default()) + .await?; + assert!( + view.get_preprocessor_cache_entry(preprocessor_key) + .await? + .is_some() + ); + assert_eq!( + view.preprocessor_cache_mode_config(), + storage.preprocessor_cache_mode_config() + ); + assert_eq!(view.current_size().await?, storage.current_size().await?); + assert_eq!(view.max_size().await?, storage.max_size().await?); + + let read_only: Arc = Arc::new(ReadOnlyStorage(Arc::clone(&storage))); + let read_only_view = with_basedirs(read_only, vec![b"/read-only-request/".to_vec()]); + assert_eq!(read_only_view.check().await?, CacheMode::ReadOnly); + + Ok(()) + } +} diff --git a/src/cache/mod.rs b/src/cache/mod.rs index b59e73bfb3..aeb5769adc 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -14,6 +14,7 @@ #[cfg(feature = "azure")] pub mod azure; +pub(crate) mod basedirs; #[allow(clippy::module_inception)] pub mod cache; pub mod cache_io; @@ -44,6 +45,7 @@ pub mod webdav; #[cfg(any_http_remote)] pub(crate) mod http_client; +pub(crate) use crate::cache::basedirs::with_basedirs; pub use crate::cache::cache::*; pub use crate::cache::cache_io::*; pub use crate::cache::ipc_storage::IpcStorage; diff --git a/src/commands.rs b/src/commands.rs index 78c3531ba7..706331d7c2 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -797,7 +797,15 @@ fn empty_server_info(config: &Config) -> Result { pub fn run_command(cmd: Command) -> Result { // Config isn't required for all commands, but if it's broken then we should flag // it early and loudly. - let config = &Config::load()?; + let config = if matches!( + &cmd, + Command::StartServer | Command::InternalStartServer | Command::ShowStats(_, _) + ) { + Config::load_with_file_basedirs()? + } else { + Config::load()? + }; + let config = &config; let startup_timeout = config.server_startup_timeout; match cmd { diff --git a/src/compiler/nvcc.rs b/src/compiler/nvcc.rs index befc0b806e..5ad9371770 100644 --- a/src/compiler/nvcc.rs +++ b/src/compiler/nvcc.rs @@ -1325,16 +1325,19 @@ where }, )), CompilerArguments::Ok(hasher) => { + let env_vars = env_vars + .iter() + .chain([("SCCACHE_DIRECT".into(), "false".into())].iter()) + .cloned() + .collect::>(); + let storage = srvc.storage_for_request(&env_vars)?; srvc.start_compile_task( compiler, hasher, args, cwd.to_owned(), - env_vars - .iter() - .chain([("SCCACHE_DIRECT".into(), "false".into())].iter()) - .cloned() - .collect::>(), + env_vars, + storage, ) .await } diff --git a/src/config.rs b/src/config.rs index b637f370e3..37261bfb15 100644 --- a/src/config.rs +++ b/src/config.rs @@ -27,13 +27,17 @@ use serde::{ #[cfg(test)] use serial_test::serial; use std::env; +use std::ffi::OsStr; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::result::Result as StdResult; use std::str::FromStr; use std::sync::{LazyLock, Mutex}; -use std::{collections::HashMap, fmt}; -use typed_path::Utf8TypedPathBuf; +use std::{ + collections::{HashMap, HashSet}, + fmt, +}; +use typed_path::TypedPathBuf; use crate::errors::*; @@ -1328,9 +1332,19 @@ pub struct Config { impl Config { pub fn load() -> Result { - let env_conf = config_from_env()?; - let skip_cache_check = skip_cache_check_from_env()?; + Self::load_with_env_config(config_from_env()?) + } + pub(crate) fn load_with_file_basedirs() -> Result { + let mut env_conf = config_from_env()?; + // A daemon can outlive the shell that started it. Per-invocation basedirs + // arrive with compile requests, so only the file can define the fallback. + env_conf.basedirs = None; + Self::load_with_env_config(env_conf) + } + + fn load_with_env_config(env_conf: EnvConfig) -> Result { + let skip_cache_check = skip_cache_check_from_env()?; let file_conf_path = config_file("SCCACHE_CONF", "config"); let file_conf = try_read_config_file(&file_conf_path) .context("Failed to load config file")? @@ -1375,48 +1389,8 @@ impl Config { file_basedirs }; - // Validate that all basedirs are absolute paths - // basedirs_raw is Vec - let mut basedirs = Vec::with_capacity(basedirs_raw.len()); - for d in basedirs_raw { - let p = Utf8TypedPathBuf::from(d); - if !p.is_absolute() { - bail!("Basedir path must be absolute: {:?}", p); - } - // Normalize basedir: - // remove double separators, cur_dirs, parent_dirs, trailing slashes - let p_norm = p.normalize(); - let mut bytes = p_norm.to_string().into_bytes(); - - // Always add a trailing `/` to basedirs to ensure we only match complete path - // components - bytes.push(b'/'); - - // normalize windows paths: use slashes and lowercase - let normalized = { - #[cfg(target_os = "windows")] - { - normalize_win_path(&bytes) - } - - #[cfg(not(target_os = "windows"))] - { - bytes - } - }; - // push only if not already present - if !basedirs.contains(&normalized) { - basedirs.push(normalized); - } - } - - if !basedirs.is_empty() && log::log_enabled!(log::Level::Debug) { - let basedirs_str: Vec = basedirs - .iter() - .map(|b| String::from_utf8_lossy(b).into_owned()) - .collect(); - debug!("Using basedirs for path normalization: {:?}", basedirs_str); - } + let basedirs = normalize_basedirs(basedirs_raw.into_iter().map(String::into_bytes))?; + log_basedirs(&basedirs); let client_side_mode = env_client_side_mode.unwrap_or(file_client_side_mode) // Logging always writes to stderr in the client process, disregarding @@ -1441,6 +1415,55 @@ impl Config { } } +fn normalize_basedirs(basedirs_raw: impl IntoIterator>) -> Result>> { + let mut basedirs = Vec::new(); + let mut seen = HashSet::new(); + for directory in basedirs_raw { + let path = TypedPathBuf::from(directory); + if !path.is_absolute() { + bail!("Basedir path must be absolute: {:?}", path); + } + + // Normalize duplicate separators, current and parent components, and + // trailing separators, then end with `/` so only complete path components match. + let mut normalized = path.normalize().as_bytes().to_vec(); + normalized.push(b'/'); + #[cfg(target_os = "windows")] + let normalized = normalize_win_path(&normalized); + + if seen.insert(normalized.clone()) { + basedirs.push(normalized); + } + } + + Ok(basedirs) +} + +fn log_basedirs(basedirs: &[Vec]) { + if !basedirs.is_empty() && log::log_enabled!(log::Level::Debug) { + let basedirs_str: Vec = basedirs + .iter() + .map(|basedir| String::from_utf8_lossy(basedir).into_owned()) + .collect(); + debug!("Using basedirs for path normalization: {:?}", basedirs_str); + } +} + +pub(crate) fn parse_basedirs_env(value: &OsStr) -> Result>> { + #[cfg(target_os = "windows")] + let separator = b';'; + #[cfg(not(target_os = "windows"))] + let separator = b':'; + + normalize_basedirs( + value + .as_encoded_bytes() + .split(|byte| *byte == separator) + .filter(|path| !path.is_empty()) + .map(<[u8]>::to_vec), + ) +} + #[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(default)] #[serde(deny_unknown_fields)] @@ -2045,6 +2068,38 @@ fn config_basedirs_overrides() { assert!(config.basedirs.is_empty()); } +#[test] +fn request_basedirs_parse_multiple_paths_and_reject_relative_paths() { + #[cfg(target_os = "windows")] + let (value, expected) = ( + OsStr::new(r"C:\first\root;D:/second/root"), + vec![b"c:/first/root/".to_vec(), b"d:/second/root/".to_vec()], + ); + #[cfg(not(target_os = "windows"))] + let (value, expected) = ( + OsStr::new("/first/root:/second/root"), + vec![b"/first/root/".to_vec(), b"/second/root/".to_vec()], + ); + + assert_eq!(parse_basedirs_env(value).unwrap(), expected); + assert!(parse_basedirs_env(OsStr::new("relative/root")).is_err()); +} + +#[test] +#[cfg(unix)] +fn request_basedirs_preserve_non_utf8_paths() { + use std::os::unix::ffi::OsStrExt as _; + + let raw = b"/tmp/non-\xff-utf8"; + let mut expected = raw.to_vec(); + expected.push(b'/'); + + assert_eq!( + parse_basedirs_env(OsStr::from_bytes(raw)).unwrap(), + vec![expected] + ); +} + #[test] #[cfg(not(target_os = "windows"))] fn test_deserialize_basedirs() { diff --git a/src/server.rs b/src/server.rs index 86ee1cbde5..1ec17975a4 100644 --- a/src/server.rs +++ b/src/server.rs @@ -13,15 +13,13 @@ // limitations under the License.SCCACHE_MAX_FRAME_LENGTH use crate::cache::readonly::ReadOnlyStorage; -use crate::cache::{CacheMode, Storage, storage_from_config}; +use crate::cache::{CacheMode, Storage, storage_from_config, with_basedirs}; use crate::compiler::PreprocessorCacheEntry; use crate::compiler::{ CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher, CompilerKind, CompilerProxy, DistType, Language, MissType, NO_CRATE_TYPE_PASSED, get_compiler_info, }; -#[cfg(feature = "dist-client")] -use crate::config; -use crate::config::Config; +use crate::config::{self, Config}; use crate::dist; use crate::jobserver::Client; use crate::mock_command::{CommandCreatorSync, ProcessCommandCreator}; @@ -43,7 +41,7 @@ use serde::{Deserialize, Serialize}; use std::cell::Cell; use std::collections::{HashMap, HashSet}; use std::env; -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::future::Future; use std::io::{self, Write}; use std::marker::Unpin; @@ -82,6 +80,18 @@ const DEFAULT_IDLE_TIMEOUT: u64 = 600; #[cfg(feature = "dist-client")] const DIST_CLIENT_RECREATE_TIMEOUT: Duration = Duration::from_secs(30); +fn is_basedirs_env(name: &OsStr) -> bool { + #[cfg(target_os = "windows")] + { + name.as_encoded_bytes() + .eq_ignore_ascii_case(b"SCCACHE_BASEDIRS") + } + #[cfg(not(target_os = "windows"))] + { + name == "SCCACHE_BASEDIRS" + } +} + /// Result of background server startup. #[derive(Debug, Serialize, Deserialize)] pub enum ServerStartup { @@ -1283,12 +1293,29 @@ where let cmd = compile.args; let cwd: PathBuf = compile.cwd.into(); let env_vars = compile.env_vars; + let storage = self.storage_for_request(&env_vars)?; let me = self.clone(); let info = self .compiler_info(exe.into(), cwd.clone(), &cmd, &env_vars) .await; - Ok(me.check_compiler(info, cmd, cwd, env_vars).await) + Ok(me.check_compiler(info, cmd, cwd, env_vars, storage).await) + } + + pub(crate) fn storage_for_request( + &self, + env_vars: &[(OsString, OsString)], + ) -> Result> { + let Some((_, value)) = env_vars + .iter() + .rev() + .find(|(name, _)| is_basedirs_env(name)) + else { + return Ok(self.storage.clone()); + }; + + let basedirs = config::parse_basedirs_env(value)?; + Ok(with_basedirs(self.storage.clone(), basedirs)) } /// Run a compile entirely in the current process (used in client-side mode). @@ -1492,6 +1519,7 @@ where cmd: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, + storage: Arc, ) -> SccacheResponse { match compiler { Err(e) => { @@ -1517,7 +1545,7 @@ where me.notification_tx = Some(tx); let finished = util::spawn_on( &self.rt, - me.start_compile_task(c, hasher, cmd, cwd, env_vars), + me.start_compile_task(c, hasher, cmd, cwd, env_vars, storage), ); rx.map(|chunk| Ok(Response::ArtifactNotification(chunk))) .chain(futures::stream::once(async move { @@ -1527,7 +1555,7 @@ where } else { futures::stream::once( self.clone() - .start_compile_task(c, hasher, cmd, cwd, env_vars) + .start_compile_task(c, hasher, cmd, cwd, env_vars, storage) .map_ok(Response::CompileFinished), ) .boxed() @@ -1574,6 +1602,7 @@ where arguments: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, + storage: Arc, ) -> Result { self.stats.lock().await.requests_executed += 1; @@ -1614,7 +1643,7 @@ where &me, client, me.creator.clone(), - me.storage.clone(), + storage, arguments, cwd, env_vars, diff --git a/tests/sccache_cargo.rs b/tests/sccache_cargo.rs index 869ae6b662..5b002822d3 100644 --- a/tests/sccache_cargo.rs +++ b/tests/sccache_cargo.rs @@ -13,6 +13,7 @@ use fs_err as fs; use helpers::{SCCACHE_BIN, SccacheTest}; use predicates::prelude::*; use serial_test::serial; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -43,6 +44,238 @@ fn test_rust_cargo_build_readonly() -> Result<()> { test_rust_cargo_cmd_readonly("build", SccacheTest::new(None)?) } +#[test] +#[serial] +fn test_request_basedirs_reuse_one_daemon() -> Result<()> { + let test_info = SccacheTest::new(None)?; + let roots = ["first", "second", "empty", "override"] + .into_iter() + .map(|name| test_info.tempdir.path().join(name)) + .collect::>(); + + for root in &roots { + write_basedirs_crate(root, "request-basedirs-test", 42)?; + } + let roots = roots + .into_iter() + .map(fs::canonicalize) + .collect::>>()?; + let config_path = test_info.tempdir.path().join("config"); + write_basedirs_config(&config_path, &roots)?; + restart_sccache( + &test_info, + Some(vec![( + "SCCACHE_CONF".into(), + config_path.as_os_str().to_owned(), + )]), + )?; + + let unrelated = fs::canonicalize(CRATE_DIR.as_os_str())?; + for (client_side, use_override, answer) in + [(false, true, 42), (true, false, 7), (true, true, 8)] + { + // Force Cargo to invoke rustc again without restarting the daemon. + for root in &roots { + write_basedirs_crate(root, "request-basedirs-test", answer)?; + } + zero_sccache_stats()?; + + // Client-side mode must support both request overrides and the file + // fallback supplied by the daemon handshake. + let first_basedir = use_override.then_some(roots[0].as_os_str()); + let second_basedir = use_override.then_some(roots[1].as_os_str()); + cargo_build_request(&test_info, &roots[0], first_basedir, client_side)?; + cargo_build_request(&test_info, &roots[1], second_basedir, client_side)?; + + // Both roots are in the file fallback. An empty or nonmatching request + // override must replace that fallback, so these are misses rather than hits. + cargo_build_request(&test_info, &roots[2], Some(OsStr::new("")), client_side)?; + cargo_build_request( + &test_info, + &roots[3], + Some(unrelated.as_os_str()), + client_side, + )?; + + test_info + .show_stats()? + .try_stdout( + predicates::str::contains(r#""cache_hits":{"counts":{"Rust":1}"#).from_utf8(), + )? + .try_stdout( + predicates::str::contains(r#""cache_misses":{"counts":{"Rust":3}"#).from_utf8(), + )? + .try_stdout(predicate::function(|output: &[u8]| { + serde_json::from_slice::(output) + .ok() + .and_then(|stats| stats["basedirs"].as_array().map(Vec::len)) + == Some(4) + }))? + .try_success()?; + } + + Ok(()) +} + +#[test] +#[serial] +fn test_show_stats_without_daemon_uses_file_basedirs() -> Result<()> { + #[cfg(target_os = "windows")] + let (configured, expected) = ("C:/configured/fallback", "c:/configured/fallback/"); + #[cfg(not(target_os = "windows"))] + let (configured, expected) = ("/configured/fallback", "/configured/fallback/"); + + let tempdir = tempfile::Builder::new() + .prefix("sccache_test_show_stats_basedirs") + .tempdir()?; + let cache_dir = tempdir.path().join("cache"); + fs::create_dir(&cache_dir)?; + let config_path = tempdir.path().join("config"); + fs::write(&config_path, format!("basedirs = [{configured:?}]\n"))?; + + stop_sccache()?; + Command::new(SCCACHE_BIN.as_os_str()) + .args(["--show-stats", "--stats-format=json"]) + .env("SCCACHE_DIR", &cache_dir) + .env("SCCACHE_CONF", &config_path) + .env("SCCACHE_BASEDIRS", "relative/request-value") + .assert() + .try_stdout(predicates::str::contains(format!(r#""basedirs":["{expected}"]"#)).from_utf8())? + .try_success()?; + + Ok(()) +} + +#[test] +#[serial] +fn test_concurrent_request_basedirs_do_not_leak() -> Result<()> { + let test_info = SccacheTest::new(None)?; + let first_a = test_info.tempdir.path().join("first-a"); + let second_a = test_info.tempdir.path().join("second-a"); + let first_b = test_info.tempdir.path().join("first-b"); + let second_b = test_info.tempdir.path().join("second-b"); + + for root in [&first_a, &second_a] { + write_basedirs_crate(root, "concurrent-basedirs-a", 42)?; + } + for root in [&first_b, &second_b] { + write_basedirs_crate(root, "concurrent-basedirs-b", 7)?; + } + let first_a = fs::canonicalize(first_a)?; + let second_a = fs::canonicalize(second_a)?; + let first_b = fs::canonicalize(first_b)?; + let second_b = fs::canonicalize(second_b)?; + + for (client_side, answer) in [(false, 42), (true, 43)] { + for root in [&first_a, &second_a] { + write_basedirs_crate(root, "concurrent-basedirs-a", answer)?; + } + for root in [&first_b, &second_b] { + write_basedirs_crate(root, "concurrent-basedirs-b", answer + 1)?; + } + cargo_build_request(&test_info, &first_a, Some(first_a.as_os_str()), client_side)?; + cargo_build_request(&test_info, &first_b, Some(first_b.as_os_str()), client_side)?; + zero_sccache_stats()?; + + let mut build_a = cargo_build_command( + &test_info, + &second_a, + Some(second_a.as_os_str()), + client_side, + ) + .spawn()?; + let mut build_b = cargo_build_command( + &test_info, + &second_b, + Some(second_b.as_os_str()), + client_side, + ) + .spawn()?; + assert!(build_a.wait()?.success()); + assert!(build_b.wait()?.success()); + + test_info + .show_stats()? + .try_stdout( + predicates::str::contains(r#""cache_hits":{"counts":{"Rust":2}"#).from_utf8(), + )? + .try_stdout(predicates::str::contains(r#""cache_misses":{"counts":{}"#).from_utf8())? + .try_success()?; + } + + Ok(()) +} + +fn write_basedirs_crate(root: &Path, name: &str, answer: u32) -> Result<()> { + fs::create_dir_all(root.join("src"))?; + fs::write( + root.join("Cargo.toml"), + format!("[package]\nname = {name:?}\nversion = \"0.1.0\"\nedition = \"2024\"\n"), + )?; + fs::write( + root.join("src/lib.rs"), + format!( + "pub const MANIFEST: &str = env!(\"CARGO_MANIFEST_DIR\");\npub fn answer() -> u32 {{ {answer} }}\n" + ), + )?; + Ok(()) +} + +fn write_basedirs_config(config_path: &Path, basedirs: &[PathBuf]) -> Result<()> { + let basedirs = basedirs + .iter() + .map(|path| format!("{:?}", path.to_string_lossy())) + .collect::>() + .join(", "); + fs::write(config_path, format!("basedirs = [{basedirs}]\n"))?; + Ok(()) +} + +fn zero_sccache_stats() -> Result<()> { + Command::new(SCCACHE_BIN.as_os_str()) + .arg("--zero-stats") + .assert() + .try_success()?; + Ok(()) +} + +fn cargo_build_command( + test_info: &SccacheTest, + root: &Path, + basedirs: Option<&OsStr>, + client_side: bool, +) -> Command { + let mut command = Command::new(CARGO.as_os_str()); + command + // `--target-dir` rather than `CARGO_TARGET_DIR`, + // since cargo forwards `CARGO_*` to rustc and sccache hashes them. + .args(["build", "--color=never", "--target-dir"]) + .arg(root.join("target")) + .envs(test_info.env.iter().cloned()) + .env_remove("SCCACHE_BASEDIRS") + .env_remove("SCCACHE_CLIENT_SIDE") + .current_dir(root); + if let Some(basedirs) = basedirs { + command.env("SCCACHE_BASEDIRS", basedirs); + } + if client_side { + command.env("SCCACHE_CLIENT_SIDE", "1"); + } + command +} + +fn cargo_build_request( + test_info: &SccacheTest, + root: &Path, + basedirs: Option<&OsStr>, + client_side: bool, +) -> Result { + cargo_build_command(test_info, root, basedirs, client_side) + .assert() + .try_success()?; + Ok(root.join("target")) +} + #[test] #[serial] #[cfg(unix)] @@ -190,7 +423,7 @@ fn test_rust_cargo_cmd(cmd: &str, test_info: SccacheTest) -> Result<()> { fn restart_sccache( test_info: &SccacheTest, - additional_envs: Option>, + additional_envs: Option>, ) -> Result<()> { let cache_dir = test_info.tempdir.path().join("cache"); @@ -427,17 +660,7 @@ fn build_checkout(test_info: &SccacheTest, name: &str) -> Result { /// /// Returns the checkout's target directory. fn cargo_build(test_info: &SccacheTest, checkout: &Path) -> Result { - let target_dir = checkout.join("target"); - Command::new(CARGO.as_os_str()) - // `--target-dir` rather than `CARGO_TARGET_DIR`, - // since cargo forwards `CARGO_*` to rustc and sccache hashes them. - .args(["build", "--color=never", "--target-dir"]) - .arg(&target_dir) - .envs(test_info.env.iter().cloned()) - .current_dir(checkout) - .assert() - .try_success()?; - Ok(target_dir) + cargo_build_request(test_info, checkout, None, false) } /// Read the dep-info file cargo keeps for the crate `name` under `target_dir`. @@ -561,20 +784,18 @@ fn test_rust_cargo_basedirs_other_checkout() -> Result<()> { let test_info = SccacheTest::new(None)?; let tempdir = real_tempdir(&test_info)?; let [a, b] = ["a", "b"].map(|name| tempdir.join(name)); - let basedirs = std::env::join_paths([&a, &b])?.into_string().unwrap(); + let basedirs = std::env::join_paths([&a, &b])?; restart_sccache( &test_info, - Some(vec![("SCCACHE_BASEDIRS".into(), basedirs)]), + // The launcher and the daemon both ignore a startup value. + Some(vec![("SCCACHE_BASEDIRS".into(), "relative/startup-value".into())]), )?; write_out_dir_crate(&a)?; - cargo_build(&test_info, &a)?; - Command::new(SCCACHE_BIN.as_os_str()) - .arg("--zero-stats") - .assert() - .try_success()?; + cargo_build_request(&test_info, &a, Some(&basedirs), false)?; + zero_sccache_stats()?; write_out_dir_crate(&b)?; - let target_b = cargo_build(&test_info, &b)?; + let target_b = cargo_build_request(&test_info, &b, Some(&basedirs), false)?; test_info .show_stats()? From b5fff837c0227171fc87b6791325fbdd9db2657f Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 00:12:51 -0800 Subject: [PATCH 2/8] server: pass request basedirs to the hashers, not a storage wrapper `generate_hash_key` and `get_cached_or_compile` take the basedirs next to the storage, so a request's `SCCACHE_BASEDIRS` reaches the C and Rust hashers without a `Storage` wrapper that forwards every method. --- src/cache/basedirs.rs | 185 --------------------------------------- src/cache/mod.rs | 2 - src/compiler/c.rs | 5 +- src/compiler/compiler.rs | 89 +++++++++++++++++++ src/compiler/nvcc.rs | 4 +- src/compiler/rust.rs | 26 ++++-- src/server.rs | 65 +++++++++----- src/test/mock_storage.rs | 10 --- 8 files changed, 156 insertions(+), 230 deletions(-) delete mode 100644 src/cache/basedirs.rs diff --git a/src/cache/basedirs.rs b/src/cache/basedirs.rs deleted file mode 100644 index 0d9a38d142..0000000000 --- a/src/cache/basedirs.rs +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2026 Mozilla Foundation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use std::sync::Arc; -use std::time::Duration; - -use async_trait::async_trait; -use bytes::Bytes; - -use crate::cache::multilevel::MultiLevelStats; -use crate::cache::{Cache, CacheMode, CacheWrite, GetPathResult, Storage}; -use crate::compiler::PreprocessorCacheEntry; -use crate::config::PreprocessorCacheModeConfig; -use crate::errors::*; - -struct BasedirsStorage { - inner: Arc, - basedirs: Vec>, -} - -pub(crate) fn with_basedirs(storage: Arc, basedirs: Vec>) -> Arc { - if storage.basedirs() == basedirs { - storage - } else { - Arc::new(BasedirsStorage { - inner: storage, - basedirs, - }) - } -} - -#[async_trait] -impl Storage for BasedirsStorage { - async fn get(&self, key: &str) -> Result { - self.inner.get(key).await - } - - async fn get_with_raw(&self, key: &str) -> Result<(Cache, Option)> { - self.inner.get_with_raw(key).await - } - - async fn put(&self, key: &str, entry: CacheWrite) -> Result { - self.inner.put(key, entry).await - } - - async fn get_raw(&self, key: &str) -> Result> { - self.inner.get_raw(key).await - } - - async fn put_raw(&self, key: &str, data: Bytes) -> Result { - self.inner.put_raw(key, data).await - } - - async fn check(&self) -> Result { - self.inner.check().await - } - - fn location(&self) -> String { - self.inner.location() - } - - fn cache_type_name(&self) -> &'static str { - self.inner.cache_type_name() - } - - async fn current_size(&self) -> Result> { - self.inner.current_size().await - } - - async fn max_size(&self) -> Result> { - self.inner.max_size().await - } - - fn multilevel_stats(&self) -> Option { - self.inner.multilevel_stats() - } - - fn preprocessor_cache_mode_config(&self) -> PreprocessorCacheModeConfig { - self.inner.preprocessor_cache_mode_config() - } - - fn basedirs(&self) -> &[Vec] { - &self.basedirs - } - - async fn get_path(&self, key: &str) -> GetPathResult { - self.inner.get_path(key).await - } - - async fn get_preprocessor_cache_entry( - &self, - key: &str, - ) -> Result>> { - self.inner.get_preprocessor_cache_entry(key).await - } - - async fn put_preprocessor_cache_entry( - &self, - key: &str, - entry: PreprocessorCacheEntry, - ) -> Result<()> { - self.inner.put_preprocessor_cache_entry(key, entry).await - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::cache::disk::DiskCache; - use crate::cache::readonly::ReadOnlyStorage; - - #[tokio::test] - async fn request_view_preserves_storage_capabilities() -> Result<()> { - let tempdir = tempfile::tempdir()?; - - let fallback = vec![b"/configured/".to_vec()]; - let storage: Arc = Arc::new(DiskCache::new( - tempdir.path(), - 1024 * 1024, - &tokio::runtime::Handle::current(), - PreprocessorCacheModeConfig::default(), - CacheMode::ReadWrite, - fallback.clone(), - )); - - let unchanged = with_basedirs(Arc::clone(&storage), fallback.clone()); - assert!(Arc::ptr_eq(&unchanged, &storage)); - - let request_basedirs = vec![b"/request/".to_vec()]; - let view = with_basedirs(Arc::clone(&storage), request_basedirs.clone()); - let empty_view = with_basedirs(Arc::clone(&storage), vec![]); - assert!(!Arc::ptr_eq(&view, &storage)); - assert_eq!(view.basedirs(), request_basedirs); - assert!(empty_view.basedirs().is_empty()); - assert_eq!(storage.basedirs(), fallback); - assert_eq!(view.location(), storage.location()); - assert_eq!(view.cache_type_name(), storage.cache_type_name()); - - let key = "0123456789abcdef"; - let raw: Bytes = CacheWrite::default().finish()?.into(); - - view.put_raw(key, raw.clone()).await?; - assert_eq!(view.get_raw(key).await?.as_deref(), Some(raw.as_ref())); - let (cache, combined_raw) = view.get_with_raw(key).await?; - assert!(matches!(cache, Cache::Hit(_))); - assert_eq!(combined_raw.as_deref(), Some(raw.as_ref())); - assert!(matches!(view.get_path(key).await, GetPathResult::Found(_))); - - let entry_key = "fedcba9876543210"; - view.put(entry_key, CacheWrite::default()).await?; - assert!(matches!(view.get(entry_key).await?, Cache::Hit(_))); - - let preprocessor_key = "preprocessor"; - view.put_preprocessor_cache_entry(preprocessor_key, PreprocessorCacheEntry::default()) - .await?; - assert!( - view.get_preprocessor_cache_entry(preprocessor_key) - .await? - .is_some() - ); - assert_eq!( - view.preprocessor_cache_mode_config(), - storage.preprocessor_cache_mode_config() - ); - assert_eq!(view.current_size().await?, storage.current_size().await?); - assert_eq!(view.max_size().await?, storage.max_size().await?); - - let read_only: Arc = Arc::new(ReadOnlyStorage(Arc::clone(&storage))); - let read_only_view = with_basedirs(read_only, vec![b"/read-only-request/".to_vec()]); - assert_eq!(read_only_view.check().await?, CacheMode::ReadOnly); - - Ok(()) - } -} diff --git a/src/cache/mod.rs b/src/cache/mod.rs index aeb5769adc..b59e73bfb3 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -14,7 +14,6 @@ #[cfg(feature = "azure")] pub mod azure; -pub(crate) mod basedirs; #[allow(clippy::module_inception)] pub mod cache; pub mod cache_io; @@ -45,7 +44,6 @@ pub mod webdav; #[cfg(any_http_remote)] pub(crate) mod http_client; -pub(crate) use crate::cache::basedirs::with_basedirs; pub use crate::cache::cache::*; pub use crate::cache::cache_io::*; pub use crate::cache::ipc_storage::IpcStorage; diff --git a/src/compiler/c.rs b/src/compiler/c.rs index 68d911e70e..e065b4f84f 100644 --- a/src/compiler/c.rs +++ b/src/compiler/c.rs @@ -402,6 +402,7 @@ where pool: &tokio::runtime::Handle, rewrite_includes_only: bool, storage: Arc, + basedirs: &[Vec], cache_control: CacheControl, ) -> Result> { let start_of_compilation = std::time::SystemTime::now(); @@ -490,7 +491,7 @@ where self.compiler.plusplus(), self.parsed_args.is_multiarch(), preprocessor_cache_mode_config, - storage.basedirs(), + basedirs, )? } else { None @@ -663,7 +664,7 @@ where .with_extra_hashes(&extra_hashes) .with_env_vars(&env_vars) .with_plusplus(self.compiler.plusplus()) - .with_basedirs(storage.basedirs()) + .with_basedirs(basedirs) .with_assembler_digest(assembler_digest.as_deref()) .with_input_file_name(hashed_input_file_name( self.parsed_args.language, diff --git a/src/compiler/compiler.rs b/src/compiler/compiler.rs index 6be1aa6e4a..ae4ed2811f 100644 --- a/src/compiler/compiler.rs +++ b/src/compiler/compiler.rs @@ -564,6 +564,7 @@ where pool: &tokio::runtime::Handle, rewrite_includes_only: bool, storage: Arc, + basedirs: &[Vec], cache_control: CacheControl, ) -> Result>; @@ -579,6 +580,7 @@ where dist_client: Option>, creator: T, storage: Arc, + basedirs: &[Vec], arguments: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, @@ -602,6 +604,7 @@ where &pool, rewrite_includes_only, storage.clone(), + basedirs, cache_control, ) .await; @@ -769,6 +772,7 @@ where dist_client, creator, storage, + basedirs, arguments, cwd, env_vars, @@ -2644,6 +2648,7 @@ LLVM version: 6.0", pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -2654,6 +2659,75 @@ LLVM version: 6.0", assert_ne!(results[0].key, results[1].key); } + /// The basedirs passed to `generate_hash_key` key two C checkouts alike. + #[test] + fn test_basedirs_argument_reaches_c_hash() { + let f = TestFixture::new(); + let clang = f.mk_bin("clang").unwrap(); + let runtime = single_threaded_runtime(); + let pool = runtime.handle(); + + let key = |root: &str, basedirs: &[Vec]| { + let creator = new_creator(); + next_command( + &creator, + Ok(MockChild::new( + exit_status(0), + "compiler_id=clang\ncompiler_version=\"16.0.0\"", + "", + )), + ); + next_assembler(&creator, "GNU assembler (GNU Binutils) 2.42", ""); + let c = detect_compiler( + creator.clone(), + &clang, + f.tempdir.path(), + &[], + &[], + pool, + None, + ) + .wait() + .unwrap() + .0; + next_command( + &creator, + Ok(MockChild::new( + exit_status(0), + format!("# 1 \"{root}/foo.c\"\n"), + "", + )), + ); + let arguments = ovec!["-c", "foo.c", "-o", "foo.o", format!("-I{root}/include")]; + let mut hasher = match c.parse_arguments(&arguments, ".".as_ref(), &[]) { + CompilerArguments::Ok(h) => h, + o => panic!("Bad result from parse_arguments: {:?}", o), + }; + hasher + .generate_hash_key( + &creator, + f.tempdir.path().to_path_buf(), + vec![], + false, + pool, + false, + Arc::new(MockStorage::new(None, false)), + basedirs, + CacheControl::Default, + ) + .wait() + .unwrap() + .key + }; + + let basedirs = [b"/checkout/a/".to_vec(), b"/checkout/b/".to_vec()]; + assert_ne!(key("/checkout/a", &[]), key("/checkout/b", &[])); + assert_eq!( + key("/checkout/a", &basedirs), + key("/checkout/b", &basedirs) + ); + } + #[test_case(true ; "with preprocessor cache")] #[test_case(false ; "without preprocessor cache")] fn test_multiarch_hash_covers_every_arch(preprocessor_cache_mode: bool) { @@ -2716,6 +2790,7 @@ LLVM version: 6.0", pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -2793,6 +2868,7 @@ LLVM version: 6.0", pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -2890,6 +2966,7 @@ LLVM version: 6.0", pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -2957,6 +3034,7 @@ LLVM version: 6.0", pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -3065,6 +3143,7 @@ LLVM version: 6.0", None, creator.clone(), storage.clone(), + &[], arguments.clone(), cwd.to_path_buf(), vec![], @@ -3102,6 +3181,7 @@ LLVM version: 6.0", None, creator, storage, + &[], arguments, cwd.to_path_buf(), vec![], @@ -3196,6 +3276,7 @@ LLVM version: 6.0", Some(dist_client.clone()), creator.clone(), storage.clone(), + &[], arguments.clone(), cwd.to_path_buf(), vec![], @@ -3233,6 +3314,7 @@ LLVM version: 6.0", Some(dist_client.clone()), creator, storage, + &[], arguments, cwd.to_path_buf(), vec![], @@ -3319,6 +3401,7 @@ LLVM version: 6.0", None, creator, storage, + &[], arguments.clone(), cwd.to_path_buf(), vec![], @@ -3412,6 +3495,7 @@ LLVM version: 6.0", None, creator, storage, + &[], arguments.clone(), cwd.to_path_buf(), vec![], @@ -3507,6 +3591,7 @@ LLVM version: 6.0", None, creator.clone(), storage.clone(), + &[], arguments.clone(), cwd.to_path_buf(), vec![], @@ -3536,6 +3621,7 @@ LLVM version: 6.0", None, creator, storage, + &[], arguments, cwd.to_path_buf(), vec![], @@ -3631,6 +3717,7 @@ LLVM version: 6.0", None, creator, storage, + &[], arguments, cwd.to_path_buf(), vec![], @@ -3710,6 +3797,7 @@ LLVM version: 6.0", Some(dist_client.clone()), creator.clone(), storage.clone(), + &[], arguments.clone(), f.tempdir.path().to_path_buf(), vec![], @@ -3828,6 +3916,7 @@ LLVM version: 6.0", Some(dist_client.clone()), creator.clone(), storage.clone(), + &[], arguments.clone(), cwd.to_path_buf(), vec![], diff --git a/src/compiler/nvcc.rs b/src/compiler/nvcc.rs index 5ad9371770..bd8bb21bf6 100644 --- a/src/compiler/nvcc.rs +++ b/src/compiler/nvcc.rs @@ -1330,14 +1330,14 @@ where .chain([("SCCACHE_DIRECT".into(), "false".into())].iter()) .cloned() .collect::>(); - let storage = srvc.storage_for_request(&env_vars)?; + let basedirs = srvc.basedirs_for_request(&env_vars)?; srvc.start_compile_task( compiler, hasher, args, cwd.to_owned(), env_vars, - storage, + basedirs, ) .await } diff --git a/src/compiler/rust.rs b/src/compiler/rust.rs index 5f2e7b8514..6e0922e08a 100644 --- a/src/compiler/rust.rs +++ b/src/compiler/rust.rs @@ -1835,11 +1835,11 @@ where _may_dist: bool, pool: &tokio::runtime::Handle, _rewrite_includes_only: bool, - storage: Arc, + _storage: Arc, + basedirs: &[Vec], _cache_control: CacheControl, ) -> Result> { trace!("[{}]: generate_hash_key", self.parsed_args.crate_name); - let basedirs = storage.basedirs(); // TODO: this doesn't produce correct arguments if they should be concatenated - should use iter_os_strings let os_string_arguments: Vec<(OsString, Option)> = self .parsed_args @@ -4287,6 +4287,7 @@ hash 42fac6f0 stable_crate_id StableCrateId(12206970385906972588) &pool, false, Arc::new(MockStorage::new(None, preprocessor_cache_mode)), + &[], CacheControl::Default, ) .wait() @@ -4379,6 +4380,7 @@ hash 42fac6f0 stable_crate_id StableCrateId(12206970385906972588) &pool, false, Arc::new(MockStorage::new(None, false)), + &[], CacheControl::Default, ) .wait() @@ -4469,6 +4471,7 @@ hash 42fac6f0 stable_crate_id StableCrateId(12206970385906972588) &pool, false, Arc::new(MockStorage::new(None, false)), + &[], CacheControl::Default, ) .wait() @@ -4514,6 +4517,7 @@ foo.rs: &[], pre_func, MockStorage::new(None, preprocessor_cache_mode), + &[], ) } @@ -4524,6 +4528,7 @@ foo.rs: env_deps: &[(&str, OsString)], pre_func: F, storage: MockStorage, + basedirs: &[Vec], ) -> String where A: AsRef, @@ -4578,6 +4583,7 @@ foo.rs: &pool, false, Arc::new(storage), + basedirs, CacheControl::Default, ) .wait() @@ -4606,7 +4612,7 @@ foo.rs: fn test_equal_hashes_basedirs() { // The root shows up in the cwd, an argument, a `CARGO_*` variable // and an env-dep (`include!(concat!(env!("OUT_DIR"), ...))`). - fn key(f: &TestFixture, outside: &str, basedirs: Vec>) -> String { + fn key(f: &TestFixture, outside: &str, basedirs: &[Vec]) -> String { let root = f.tempdir.path(); hash_key_with( f, @@ -4629,20 +4635,21 @@ foo.rs: ], &[("OUT_DIR", root.join("target").join("out").into())], nothing, - MockStorage::new(None, false).with_basedirs(basedirs), + MockStorage::new(None, false), + basedirs, ) } let a = TestFixture::new(); let b = TestFixture::new(); let both = vec![basedir(a.tempdir.path()), basedir(b.tempdir.path())]; - assert_ne!(key(&a, "x", vec![]), key(&b, "x", vec![])); - assert_eq!(key(&a, "x", both.clone()), key(&b, "x", both.clone())); + assert_ne!(key(&a, "x", &[]), key(&b, "x", &[])); + assert_eq!(key(&a, "x", &both), key(&b, "x", &both)); // A difference outside the basedirs still counts. - assert_ne!(key(&a, "x", both.clone()), key(&b, "y", both)); + assert_ne!(key(&a, "x", &both), key(&b, "y", &both)); // A basedir nothing lives under leaves the key as it was. let elsewhere = basedir(&std::env::temp_dir().join("sccache-elsewhere")); - assert_eq!(key(&a, "x", vec![]), key(&a, "x", vec![elsewhere])); + assert_eq!(key(&a, "x", &[]), key(&a, "x", &[elsewhere])); } /// An env-dep equal to a basedir is keyed apart from an unset one, which rustc @@ -4672,7 +4679,8 @@ foo.rs: &env_vars, &[("Y", val.unwrap_or_default())], nothing, - MockStorage::new(None, false).with_basedirs(vec![basedir(&root)]), + MockStorage::new(None, false), + &[basedir(&root)], ) }; assert_ne!(key(None), key(Some(root.clone().into()))); diff --git a/src/server.rs b/src/server.rs index 1ec17975a4..b790d8b59c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -13,7 +13,7 @@ // limitations under the License.SCCACHE_MAX_FRAME_LENGTH use crate::cache::readonly::ReadOnlyStorage; -use crate::cache::{CacheMode, Storage, storage_from_config, with_basedirs}; +use crate::cache::{CacheMode, Storage, storage_from_config}; use crate::compiler::PreprocessorCacheEntry; use crate::compiler::{ CacheControl, CompileResult, Compiler, CompilerArguments, CompilerHasher, CompilerKind, @@ -92,6 +92,21 @@ fn is_basedirs_env(name: &OsStr) -> bool { } } +/// The request's own `SCCACHE_BASEDIRS` when it sets one, `fallback` otherwise. +fn request_basedirs( + env_vars: &[(OsString, OsString)], + fallback: &[Vec], +) -> Result>> { + match env_vars + .iter() + .rev() + .find(|(name, _)| is_basedirs_env(name)) + { + Some((_, value)) => config::parse_basedirs_env(value), + None => Ok(fallback.to_vec()), + } +} + /// Result of background server startup. #[derive(Debug, Serialize, Deserialize)] pub enum ServerStartup { @@ -1293,29 +1308,20 @@ where let cmd = compile.args; let cwd: PathBuf = compile.cwd.into(); let env_vars = compile.env_vars; - let storage = self.storage_for_request(&env_vars)?; + let basedirs = self.basedirs_for_request(&env_vars)?; let me = self.clone(); let info = self .compiler_info(exe.into(), cwd.clone(), &cmd, &env_vars) .await; - Ok(me.check_compiler(info, cmd, cwd, env_vars, storage).await) + Ok(me.check_compiler(info, cmd, cwd, env_vars, basedirs).await) } - pub(crate) fn storage_for_request( + pub(crate) fn basedirs_for_request( &self, env_vars: &[(OsString, OsString)], - ) -> Result> { - let Some((_, value)) = env_vars - .iter() - .rev() - .find(|(name, _)| is_basedirs_env(name)) - else { - return Ok(self.storage.clone()); - }; - - let basedirs = config::parse_basedirs_env(value)?; - Ok(with_basedirs(self.storage.clone(), basedirs)) + ) -> Result>> { + request_basedirs(env_vars, self.storage.basedirs()) } /// Run a compile entirely in the current process (used in client-side mode). @@ -1519,7 +1525,7 @@ where cmd: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, - storage: Arc, + basedirs: Vec>, ) -> SccacheResponse { match compiler { Err(e) => { @@ -1545,7 +1551,7 @@ where me.notification_tx = Some(tx); let finished = util::spawn_on( &self.rt, - me.start_compile_task(c, hasher, cmd, cwd, env_vars, storage), + me.start_compile_task(c, hasher, cmd, cwd, env_vars, basedirs), ); rx.map(|chunk| Ok(Response::ArtifactNotification(chunk))) .chain(futures::stream::once(async move { @@ -1555,7 +1561,7 @@ where } else { futures::stream::once( self.clone() - .start_compile_task(c, hasher, cmd, cwd, env_vars, storage) + .start_compile_task(c, hasher, cmd, cwd, env_vars, basedirs) .map_ok(Response::CompileFinished), ) .boxed() @@ -1602,7 +1608,7 @@ where arguments: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, - storage: Arc, + basedirs: Vec>, ) -> Result { self.stats.lock().await.requests_executed += 1; @@ -1643,7 +1649,8 @@ where &me, client, me.creator.clone(), - storage, + me.storage.clone(), + &basedirs, arguments, cwd, env_vars, @@ -3064,6 +3071,24 @@ mod tests { (body, finished) } + #[test] + fn request_basedirs_override_the_fallback() { + #[cfg(target_os = "windows")] + let (fallback, request, normalized) = (b"c:/fallback/", r"C:\request", b"c:/request/"); + #[cfg(not(target_os = "windows"))] + let (fallback, request, normalized) = (b"/fallback/", "/request", b"/request/"); + let fallback = [fallback.to_vec()]; + let env = |value: &str| vec![(OsString::from("SCCACHE_BASEDIRS"), OsString::from(value))]; + + assert_eq!(request_basedirs(&[], &fallback).unwrap(), fallback); + assert_eq!( + request_basedirs(&env(request), &fallback).unwrap(), + [normalized.to_vec()] + ); + assert!(request_basedirs(&env(""), &fallback).unwrap().is_empty()); + assert!(request_basedirs(&env("relative"), &fallback).is_err()); + } + #[test] fn records_non_cacheable_crate_type_detail_in_existing_stats_map() { let mut stats = ServerStats::default(); diff --git a/src/test/mock_storage.rs b/src/test/mock_storage.rs index b9ceb75116..d4260e79e2 100644 --- a/src/test/mock_storage.rs +++ b/src/test/mock_storage.rs @@ -28,7 +28,6 @@ pub struct MockStorage { tx: mpsc::UnboundedSender>, delay: Option, preprocessor_cache_mode: bool, - basedirs: Vec>, } impl MockStorage { @@ -40,15 +39,9 @@ impl MockStorage { rx: Arc::new(Mutex::new(rx)), delay, preprocessor_cache_mode, - basedirs: vec![], } } - pub(crate) fn with_basedirs(mut self, basedirs: Vec>) -> Self { - self.basedirs = basedirs; - self - } - /// Queue up `res` to be returned as the next result from `Storage::get`. pub(crate) fn next_get(&self, res: Result) { self.tx.unbounded_send(res).unwrap(); @@ -88,7 +81,4 @@ impl Storage for MockStorage { ..Default::default() } } - fn basedirs(&self) -> &[Vec] { - &self.basedirs - } } From 95de8827ff939502f8a5fe41913fd6d7644d6897 Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 00:13:28 -0800 Subject: [PATCH 3/8] server: compile uncached when a request's SCCACHE_BASEDIRS is invalid A relative path in a compile's `SCCACHE_BASEDIRS` failed the whole request, so the build saw an error rather than a compile. The server now answers `UnhandledCompile`, the client runs the real compiler, and the stats count the compile as not cacheable under `SCCACHE_BASEDIRS`. --- README.md | 15 +++------------ docs/Configuration.md | 2 +- src/server.rs | 43 ++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 44 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4a998f371d..48d8d1fc98 100644 --- a/README.md +++ b/README.md @@ -367,9 +367,7 @@ This is similar to ccache's `CCACHE_BASEDIR` and helps when: * Multiple developers working with different username paths * Working with multiple project checkouts simultaneously -**Note:** Only absolute paths are supported. A relative request value fails that -compiler invocation. A relative config-file value prevents the server from -starting. +**Note:** Only absolute paths are supported. A relative path in a compile's environment runs that compile without caching, and `sccache --show-stats` counts it as not cacheable. A relative path in the config file prevents the server from starting. You can also configure this in the sccache config file: @@ -381,16 +379,9 @@ basedirs = ["/home/user/project"] basedirs = ["/home/user/project", "/home/user/workspace"] ``` -The environment variable applies to each compiler invocation. Its value -overrides the config-file value for that request, so a persistent sccache -daemon can serve builds from different checkout roots without a restart. Set -`SCCACHE_BASEDIRS=""` on an invocation to disable the config-file fallback for -that request. +The environment variable applies to each compiler invocation. Its value overrides the config-file value for that request, so a persistent sccache daemon can serve builds from different checkout roots without a restart. Set `SCCACHE_BASEDIRS=""` on an invocation to disable the config-file fallback for that request. -Only the config file defines the daemon's fallback. A `SCCACHE_BASEDIRS` value -in the environment that starts the daemon does not become global daemon state. -Statistics report the config-file fallback and do not accumulate paths from -individual requests. +Only the config file defines the daemon's fallback. A `SCCACHE_BASEDIRS` value in the environment that starts the daemon does not become global daemon state. Statistics report the config-file fallback and do not accumulate paths from individual requests. --- diff --git a/docs/Configuration.md b/docs/Configuration.md index b6bde3e4df..6d57553521 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -192,7 +192,7 @@ Note that some env variables may need sccache server restart to take effect. * `SCCACHE_ALLOW_CORE_DUMPS` to enable core dumps by the server * `SCCACHE_ALLOW_INCREMENTAL` set to `1` to allow Rust builds with `CARGO_INCREMENTAL=1`; incremental crates go uncached. See [Rust caveats](Rust.md) * `SCCACHE_CONF` configuration file path -* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. The environment variable applies to each compiler invocation and overrides the config-file fallback for that request. An explicitly empty value disables the fallback for that request. Only the config file defines the daemon fallback; the daemon ignores `SCCACHE_BASEDIRS` in its startup environment. Statistics report only the configured fallback. Only absolute paths are supported; a relative path causes an error for the affected invocation or during config-file loading. +* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. The environment variable applies to each compiler invocation and overrides the config-file fallback for that request. An explicitly empty value disables the fallback for that request. Only the config file defines the daemon fallback; the daemon ignores `SCCACHE_BASEDIRS` in its startup environment. Statistics report only the configured fallback. Only absolute paths are supported; a relative path in a compile's environment runs that compile uncached, and one in the config file prevents the server from starting. * `SCCACHE_CACHED_CONF` * `SCCACHE_DIST_CLIENT_CACHE_DIR` distributed toolchain cache directory; overrides `[dist].cache_dir` from the configuration file. * `SCCACHE_IDLE_TIMEOUT` how long the local daemon process waits for more client requests before exiting, in seconds. Set to `0` to run sccache permanently diff --git a/src/server.rs b/src/server.rs index b790d8b59c..adb0c7f15c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1308,13 +1308,12 @@ where let cmd = compile.args; let cwd: PathBuf = compile.cwd.into(); let env_vars = compile.env_vars; - let basedirs = self.basedirs_for_request(&env_vars)?; let me = self.clone(); let info = self .compiler_info(exe.into(), cwd.clone(), &cmd, &env_vars) .await; - Ok(me.check_compiler(info, cmd, cwd, env_vars, basedirs).await) + Ok(me.check_compiler(info, cmd, cwd, env_vars).await) } pub(crate) fn basedirs_for_request( @@ -1525,7 +1524,6 @@ where cmd: Vec, cwd: PathBuf, env_vars: Vec<(OsString, OsString)>, - basedirs: Vec>, ) -> SccacheResponse { match compiler { Err(e) => { @@ -1543,6 +1541,20 @@ where CompilerArguments::Ok(hasher) => { debug!("parse_arguments: Ok: {:?}", cmd); + let basedirs = match self.basedirs_for_request(&env_vars) { + Ok(basedirs) => basedirs, + Err(e) => { + warn!("Not caching {cmd:?}: invalid SCCACHE_BASEDIRS: {e:#}"); + self.stats + .lock() + .await + .record_not_cacheable("SCCACHE_BASEDIRS", None); + return Message::WithoutBody(Response::Compile( + CompileResponse::UnhandledCompile, + )); + } + }; + let body = if c.kind() == CompilerKind::Rust { // Only rustc emits artifact notifications, // for `.rmeta` pipelining. @@ -3089,6 +3101,31 @@ mod tests { assert!(request_basedirs(&env("relative"), &fallback).is_err()); } + /// An invalid request value runs the compiler uncached and shows in the stats. + #[test] + fn invalid_request_basedirs_compile_uncached() { + let (_f, runtime, service, mut compile) = rustc_miss_fixture(); + compile + .env_vars + .push(("SCCACHE_BASEDIRS".into(), "relative/root".into())); + + let response = runtime + .block_on(service.handle_compile(compile)) + .unwrap() + .into_inner(); + + assert!( + matches!( + response, + Response::Compile(CompileResponse::UnhandledCompile) + ), + "unexpected response: {response:?}" + ); + let stats = runtime.block_on(service.take_stats()); + assert_eq!(stats.requests_not_cacheable, 1); + assert_eq!(stats.not_cached.get("SCCACHE_BASEDIRS"), Some(&1)); + } + #[test] fn records_non_cacheable_crate_type_detail_in_existing_stats_map() { let mut stats = ServerStats::default(); From 8b145ab613a6364d23998609fe15f82eefd21c54 Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 00:14:44 -0800 Subject: [PATCH 4/8] config: read SCCACHE_BASEDIRS only from compile requests The server and `--show-stats` take their basedirs from the config file and each compile request carries its own, so `config_from_env` has no reader for `SCCACHE_BASEDIRS`. Dropping it removes the hardcoded command list in `run_command` and the second, `to_string_lossy` parse that mangled non-UTF-8 paths; `parse_basedirs_env` is the one parser. --- src/commands.rs | 10 +- src/config.rs | 454 ++---------------------------------------------- 2 files changed, 13 insertions(+), 451 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 706331d7c2..78c3531ba7 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -797,15 +797,7 @@ fn empty_server_info(config: &Config) -> Result { pub fn run_command(cmd: Command) -> Result { // Config isn't required for all commands, but if it's broken then we should flag // it early and loudly. - let config = if matches!( - &cmd, - Command::StartServer | Command::InternalStartServer | Command::ShowStats(_, _) - ) { - Config::load_with_file_basedirs()? - } else { - Config::load()? - }; - let config = &config; + let config = &Config::load()?; let startup_timeout = config.server_startup_timeout; match cmd { diff --git a/src/config.rs b/src/config.rs index 37261bfb15..66269bc30c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -839,7 +839,6 @@ pub fn try_read_config_file(path: &Path) -> Result>, dist_cache_dir: Option, client_side_mode: Option, } @@ -1267,27 +1266,11 @@ fn config_from_env() -> Result { multilevel, }; - // ======= Base directory ======= - // Support multiple paths separated by ';' on Windows and ':' on other platforms - // to match PATH behavior. - #[cfg(target_os = "windows")] - let split_symbol = ';'; - #[cfg(not(target_os = "windows"))] - let split_symbol = ':'; - let basedirs = env::var_os("SCCACHE_BASEDIRS").map(|s| { - s.to_string_lossy() - .split(split_symbol) - .filter(|s| !s.is_empty()) - .map(|s| s.to_owned()) - .collect() - }); - let dist_cache_dir = env::var_os("SCCACHE_DIST_CLIENT_CACHE_DIR").map(PathBuf::from); let client_side_mode = bool_from_env_var("SCCACHE_CLIENT_SIDE")?; Ok(EnvConfig { cache, - basedirs, dist_cache_dir, client_side_mode, }) @@ -1332,19 +1315,9 @@ pub struct Config { impl Config { pub fn load() -> Result { - Self::load_with_env_config(config_from_env()?) - } - - pub(crate) fn load_with_file_basedirs() -> Result { - let mut env_conf = config_from_env()?; - // A daemon can outlive the shell that started it. Per-invocation basedirs - // arrive with compile requests, so only the file can define the fallback. - env_conf.basedirs = None; - Self::load_with_env_config(env_conf) - } - - fn load_with_env_config(env_conf: EnvConfig) -> Result { + let env_conf = config_from_env()?; let skip_cache_check = skip_cache_check_from_env()?; + let file_conf_path = config_file("SCCACHE_CONF", "config"); let file_conf = try_read_config_file(&file_conf_path) .context("Failed to load config file")? @@ -1372,7 +1345,6 @@ impl Config { let EnvConfig { cache, - basedirs: env_basedirs, dist_cache_dir: env_dist_cache_dir, client_side_mode: env_client_side_mode, } = env_conf; @@ -1382,14 +1354,8 @@ impl Config { dist.cache_dir = cache_dir; } - // Environment variable takes precedence over file config if it is set - let basedirs_raw = if let Some(basedirs) = env_basedirs { - basedirs - } else { - file_basedirs - }; - - let basedirs = normalize_basedirs(basedirs_raw.into_iter().map(String::into_bytes))?; + // `SCCACHE_BASEDIRS` is read per compile request, see `parse_basedirs_env`. + let basedirs = normalize_basedirs(file_basedirs.into_iter().map(String::into_bytes))?; log_basedirs(&basedirs); let client_side_mode = env_client_side_mode.unwrap_or(file_client_side_mode) @@ -1799,7 +1765,6 @@ fn config_overrides() { }), ..Default::default() }, - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -1891,197 +1856,24 @@ fn config_overrides() { ); } -#[test] -#[cfg(target_os = "windows")] -fn config_basedirs_overrides() { - // Test that env variable takes precedence over file config - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec!["C:/env/basedir".to_string()].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["C:/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert_eq!(config.basedirs, vec![b"c:/env/basedir/".to_vec()]); - - // Test that file config is used when env is None - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: None, - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["C:/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert_eq!(config.basedirs, vec![b"c:/file/basedir/".to_vec()]); - - // Test that env config is used when env is set but empty - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec![].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["C:/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert!(config.basedirs.is_empty()); - - // Test that both empty results in empty - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec![].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec![], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert!(config.basedirs.is_empty()); -} - -#[test] -#[cfg(not(target_os = "windows"))] -fn config_basedirs_overrides() { - // Test that env variable takes precedence over file config - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec!["/env/basedir".to_string()].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert_eq!(config.basedirs, vec![b"/env/basedir/".to_vec()]); - - // Test that file config is used when env is None - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: None, - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert_eq!(config.basedirs, vec![b"/file/basedir/".to_vec()]); - - // Test that env config is used when env is set but empty - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec![].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec!["/file/basedir".to_string()], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert!(config.basedirs.is_empty()); - - // Test that both empty results in empty - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: vec![].into(), - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec![], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert!(config.basedirs.is_empty()); - let env_conf = EnvConfig { - cache: Default::default(), - basedirs: None, - dist_cache_dir: None, - client_side_mode: None, - }; - - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec![], - client_side_mode: false, - }; - - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - assert!(config.basedirs.is_empty()); -} - #[test] fn request_basedirs_parse_multiple_paths_and_reject_relative_paths() { #[cfg(target_os = "windows")] - let (value, expected) = ( - OsStr::new(r"C:\first\root;D:/second/root"), + let (value, spaced, expected) = ( + OsStr::new(r"C:\first\root;;D:/second/root"), + OsStr::new(" C:/first/root ; D:/second/root "), vec![b"c:/first/root/".to_vec(), b"d:/second/root/".to_vec()], ); #[cfg(not(target_os = "windows"))] - let (value, expected) = ( - OsStr::new("/first/root:/second/root"), + let (value, spaced, expected) = ( + OsStr::new("/first/root::/second/root"), + OsStr::new(" /first/root : /second/root "), vec![b"/first/root/".to_vec(), b"/second/root/".to_vec()], ); + // Empty entries are skipped; spaces are kept, so a leading one makes the path relative. assert_eq!(parse_basedirs_env(value).unwrap(), expected); + assert!(parse_basedirs_env(spaced).is_err()); assert!(parse_basedirs_env(OsStr::new("relative/root")).is_err()); } @@ -2205,220 +1997,6 @@ fn test_cache_mode_from_env_var() { } } -#[test] -#[serial(config_from_env)] -#[cfg(not(target_os = "windows"))] -fn test_env_basedirs_single() { - unsafe { - std::env::set_var("SCCACHE_BASEDIRS", "/home/user/project"); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec!["/home/user/project".to_string()] - ); -} - -#[test] -#[serial(config_from_env)] -#[cfg(target_os = "windows")] -fn test_env_basedirs_single() { - unsafe { - std::env::set_var("SCCACHE_BASEDIRS", "C:/home/user/project"); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec!["C:/home/user/project".to_string()] - ); -} - -#[test] -#[serial(config_from_env)] -#[cfg(not(target_os = "windows"))] -fn test_env_basedirs_multiple() { - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - "/home/user/project:/home/user/workspace", - ); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec![ - "/home/user/project".to_string(), - "/home/user/workspace".to_string() - ] - ); -} - -#[test] -#[serial(config_from_env)] -#[cfg(target_os = "windows")] -fn test_env_basedirs_multiple() { - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - "C:/home/user/project;C:/home/user/workspace", - ); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec![ - "C:/home/user/project".to_string(), - "C:/home/user/workspace".to_string() - ] - ); -} - -#[test] -#[serial(config_from_env)] -#[cfg(not(target_os = "windows"))] -fn test_env_basedirs_with_spaces() { - // Test that spaces around paths are not trimmed - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - " /home/user/project : /home/user/workspace ", - ); - } - let env_conf = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - env_conf.basedirs.clone().expect("SCCACHE_BASEDIRS is set"), - vec![ - " /home/user/project ".to_string(), - " /home/user/workspace ".to_string() - ] - ); - // The lead to trailing spaces are preserved and server fails to start - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec![], - client_side_mode: false, - }; - Config::from_env_and_file_configs(env_conf, file_conf) - .expect_err("Should fail due to non-absolute path"); -} - -#[test] -#[serial(config_from_env)] -#[cfg(target_os = "windows")] -fn test_env_basedirs_with_spaces() { - // Test that spaces around paths are not trimmed - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - " C:/home/user/project ; C:/home/user/workspace ", - ); - } - let env_conf = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - env_conf.basedirs.clone().expect("SCCACHE_BASEDIRS is set"), - vec![ - " C:/home/user/project ".to_string(), - " C:/home/user/workspace ".to_string() - ] - ); - // The lead to trailing spaces are preserved and server fails to start - let file_conf = FileConfig { - cache: Default::default(), - dist: Default::default(), - server_startup_timeout_ms: None, - basedirs: vec![], - client_side_mode: false, - }; - Config::from_env_and_file_configs(env_conf, file_conf) - .expect_err("Should fail due to non-absolute path"); -} - -#[test] -#[serial(config_from_env)] -#[cfg(not(target_os = "windows"))] -fn test_env_basedirs_empty_entries() { - // Test that empty entries are filtered out - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - "/home/user/project::/home/user/workspace", - ); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec![ - "/home/user/project".to_string(), - "/home/user/workspace".to_string() - ] - ); -} - -#[test] -#[serial(config_from_env)] -#[cfg(target_os = "windows")] -fn test_env_basedirs_empty_entries() { - // Test that empty entries are filtered out - unsafe { - std::env::set_var( - "SCCACHE_BASEDIRS", - "c:/home/user/project;;c:/home/user/workspace", - ); - } - let config = config_from_env().unwrap(); - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - - assert_eq!( - config.basedirs.expect("SCCACHE_BASEDIRS is set"), - vec![ - "c:/home/user/project".to_string(), - "c:/home/user/workspace".to_string() - ] - ); -} - -#[test] -#[serial(config_from_env)] -fn test_env_basedirs_not_set() { - unsafe { - std::env::remove_var("SCCACHE_BASEDIRS"); - } - let config = config_from_env().unwrap(); - assert!(config.basedirs.is_none()); -} - #[test] #[serial(config_from_env)] #[cfg(feature = "s3")] @@ -3236,7 +2814,6 @@ fn test_integration_config_normalizes_and_strips() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3272,7 +2849,6 @@ fn test_integration_normalized_path_with_double_slashes() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3304,7 +2880,6 @@ fn test_integration_windows_path_normalization() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3337,7 +2912,6 @@ fn test_integration_cow_borrowed_when_no_match() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3370,7 +2944,6 @@ fn test_integration_cow_borrowed_when_empty_basedirs() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3402,7 +2975,6 @@ fn test_integration_multiple_basedirs_longest_match() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3439,7 +3011,6 @@ fn test_integration_paths_with_dots_normalized() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; @@ -3472,7 +3043,6 @@ fn test_integration_windows_mixed_slashes() { let env_conf = EnvConfig { cache: Default::default(), - basedirs: None, dist_cache_dir: None, client_side_mode: None, }; From aaafa55a39b8f87f63d0e4bd38459906a181f70c Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 00:29:42 -0800 Subject: [PATCH 5/8] config: parse the env-to-strip test's basedirs as a request does `config_from_env` no longer reads `SCCACHE_BASEDIRS`, so the test feeds the value through `parse_basedirs_env`. --- src/config.rs | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src/config.rs b/src/config.rs index 66269bc30c..a6fba182dd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3068,36 +3068,25 @@ fn test_integration_windows_mixed_slashes() { } #[test] -#[serial(config_from_env)] #[cfg(not(target_os = "windows"))] fn test_integration_env_variable_to_strip() { - // Test full flow: SCCACHE_BASEDIRS env var -> Config -> strip_basedirs + // Test full flow: a request's SCCACHE_BASEDIRS -> parse_basedirs_env -> strip_basedirs use crate::util::strip_basedirs; - unsafe { - env::set_var("SCCACHE_BASEDIRS", "/home/user/project:/tmp/build"); - } - - let env_conf = config_from_env().unwrap(); - let file_conf = FileConfig::default(); - let config = Config::from_env_and_file_configs(env_conf, file_conf).unwrap(); - - unsafe { - env::remove_var("SCCACHE_BASEDIRS"); - } + let basedirs = parse_basedirs_env(OsStr::new("/home/user/project:/tmp/build")).unwrap(); // Should have two normalized basedirs - assert_eq!(config.basedirs.len(), 2); - assert_eq!(config.basedirs[0], b"/home/user/project/"); - assert_eq!(config.basedirs[1], b"/tmp/build/"); + assert_eq!(basedirs.len(), 2); + assert_eq!(basedirs[0], b"/home/user/project/"); + assert_eq!(basedirs[1], b"/tmp/build/"); // Test stripping with both let input1 = b"# 1 \"/home/user/project/src/main.c\""; - let output1 = strip_basedirs(input1, &config.basedirs); + let output1 = strip_basedirs(input1, &basedirs); assert_eq!(&*output1, b"# 1 \"src/main.c\""); let input2 = b"# 1 \"/tmp/build/obj/file.o\""; - let output2 = strip_basedirs(input2, &config.basedirs); + let output2 = strip_basedirs(input2, &basedirs); assert_eq!(&*output2, b"# 1 \"obj/file.o\""); } From 9536afa04fd23e766b830893a54cd78eba118ccd Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 00:29:43 -0800 Subject: [PATCH 6/8] tests: apply rustfmt to the basedirs tests --- src/compiler/compiler.rs | 5 +---- tests/sccache_cargo.rs | 5 ++++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/compiler/compiler.rs b/src/compiler/compiler.rs index ae4ed2811f..04a70e4235 100644 --- a/src/compiler/compiler.rs +++ b/src/compiler/compiler.rs @@ -2722,10 +2722,7 @@ LLVM version: 6.0", let basedirs = [b"/checkout/a/".to_vec(), b"/checkout/b/".to_vec()]; assert_ne!(key("/checkout/a", &[]), key("/checkout/b", &[])); - assert_eq!( - key("/checkout/a", &basedirs), - key("/checkout/b", &basedirs) - ); + assert_eq!(key("/checkout/a", &basedirs), key("/checkout/b", &basedirs)); } #[test_case(true ; "with preprocessor cache")] diff --git a/tests/sccache_cargo.rs b/tests/sccache_cargo.rs index 5b002822d3..0d9ceac7ea 100644 --- a/tests/sccache_cargo.rs +++ b/tests/sccache_cargo.rs @@ -788,7 +788,10 @@ fn test_rust_cargo_basedirs_other_checkout() -> Result<()> { restart_sccache( &test_info, // The launcher and the daemon both ignore a startup value. - Some(vec![("SCCACHE_BASEDIRS".into(), "relative/startup-value".into())]), + Some(vec![( + "SCCACHE_BASEDIRS".into(), + "relative/startup-value".into(), + )]), )?; write_out_dir_crate(&a)?; From 89b519dcaafb321926080323e917c4ec5d7a7e2d Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 12:07:57 -0800 Subject: [PATCH 7/8] docs: plain wording for per-request SCCACHE_BASEDIRS --- README.md | 2 +- docs/Configuration.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 48d8d1fc98..07dd0ab4e2 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ This is similar to ccache's `CCACHE_BASEDIR` and helps when: * Multiple developers working with different username paths * Working with multiple project checkouts simultaneously -**Note:** Only absolute paths are supported. A relative path in a compile's environment runs that compile without caching, and `sccache --show-stats` counts it as not cacheable. A relative path in the config file prevents the server from starting. +**Note:** Only absolute paths are supported. If a build passes a relative path, sccache compiles without caching. A relative path in the config file stops the server from starting. You can also configure this in the sccache config file: diff --git a/docs/Configuration.md b/docs/Configuration.md index 6d57553521..33a0b1761f 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -192,7 +192,7 @@ Note that some env variables may need sccache server restart to take effect. * `SCCACHE_ALLOW_CORE_DUMPS` to enable core dumps by the server * `SCCACHE_ALLOW_INCREMENTAL` set to `1` to allow Rust builds with `CARGO_INCREMENTAL=1`; incremental crates go uncached. See [Rust caveats](Rust.md) * `SCCACHE_CONF` configuration file path -* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. The environment variable applies to each compiler invocation and overrides the config-file fallback for that request. An explicitly empty value disables the fallback for that request. Only the config file defines the daemon fallback; the daemon ignores `SCCACHE_BASEDIRS` in its startup environment. Statistics report only the configured fallback. Only absolute paths are supported; a relative path in a compile's environment runs that compile uncached, and one in the config file prevents the server from starting. +* `SCCACHE_BASEDIRS` base directory (or directories) to strip from paths for cache key computation. This is similar to ccache's `CCACHE_BASEDIR` and enables cache hits across different absolute paths when compiling the same source code. Multiple directories can be separated by `;` on Windows hosts and by `:` on any other operating system. When multiple directories are specified, the longest matching prefix is used. Path matching is **case-insensitive** on Windows and **case-sensitive** on other operating systems. The environment variable applies to each compiler invocation and overrides the config-file fallback for that request. `SCCACHE_BASEDIRS=""` disables the fallback. Setting `SCCACHE_BASEDIRS` when starting the server has no effect. Put `basedirs` in the config file to set a default for every build. `sccache --show-stats` shows the config file's `basedirs`, not the values builds pass. Only absolute paths are supported; see the note in the README. * `SCCACHE_CACHED_CONF` * `SCCACHE_DIST_CLIENT_CACHE_DIR` distributed toolchain cache directory; overrides `[dist].cache_dir` from the configuration file. * `SCCACHE_IDLE_TIMEOUT` how long the local daemon process waits for more client requests before exiting, in seconds. Set to `0` to run sccache permanently From e21d2b39b719e6f6a43473b1322da01c02b0a43b Mon Sep 17 00:00:00 2001 From: Frederic Barthelemy Date: Wed, 4 Nov 2026 13:44:06 -0800 Subject: [PATCH 8/8] tests: cover request-scoped basedirs resolution Check that the request's SCCACHE_BASEDIRS and the config file fallback reach the hasher through the server, that the last request value wins, and that equal basedirs collapse to one. --- src/config.rs | 16 ++++++++++++ src/server.rs | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/src/config.rs b/src/config.rs index a6fba182dd..d9be4a0009 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1892,6 +1892,22 @@ fn request_basedirs_preserve_non_utf8_paths() { ); } +#[test] +fn request_basedirs_keep_the_first_of_equal_paths() { + #[cfg(target_os = "windows")] + let (value, expected) = ( + OsStr::new(r"C:\root;c:/other;c:/root/;C:/root/./"), + vec![b"c:/root/".to_vec(), b"c:/other/".to_vec()], + ); + #[cfg(not(target_os = "windows"))] + let (value, expected) = ( + OsStr::new("/root:/other:/root/:/root/./"), + vec![b"/root/".to_vec(), b"/other/".to_vec()], + ); + + assert_eq!(parse_basedirs_env(value).unwrap(), expected); +} + #[test] #[cfg(not(target_os = "windows"))] fn test_deserialize_basedirs() { diff --git a/src/server.rs b/src/server.rs index adb0c7f15c..008fac0a0f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -3101,6 +3101,78 @@ mod tests { assert!(request_basedirs(&env("relative"), &fallback).is_err()); } + #[test] + fn request_basedirs_use_the_last_value() { + #[cfg(target_os = "windows")] + let (first, last, normalized) = (r"C:\first", r"C:\last", b"c:/last/"); + #[cfg(not(target_os = "windows"))] + let (first, last, normalized) = ("/first", "/last", b"/last/"); + let env_vars: Vec<(OsString, OsString)> = vec![ + ("SCCACHE_BASEDIRS".into(), first.into()), + ("SCCACHE_BASEDIRS_EXTRA".into(), "relative".into()), + ("SCCACHE_BASEDIRS".into(), last.into()), + ]; + + assert_eq!( + request_basedirs(&env_vars, &[]).unwrap(), + [normalized.to_vec()] + ); + } + + /// Whether `dep` compiled in a second root hits the entry the first root wrote. + fn second_root_hits(file_basedirs: bool, request_basedirs: Option<&str>) -> bool { + use crate::cache::disk::DiskCache; + use crate::config::PreprocessorCacheModeConfig; + + let roots = [TestFixture::new(), TestFixture::new()]; + let both = env::join_paths(roots.iter().map(|f| f.tempdir.path())).unwrap(); + let runtime = Runtime::new().unwrap(); + let storage = Arc::new(DiskCache::new( + roots[0].tempdir.path().join("cache"), + u64::MAX, + runtime.handle(), + PreprocessorCacheModeConfig::default(), + CacheMode::ReadWrite, + if file_basedirs { + config::parse_basedirs_env(&both).unwrap() + } else { + vec![] + }, + )); + let service = MockService::mock_with_storage(storage, runtime.handle().clone()); + + for f in &roots { + let rustc = f.mk_bin("rustc").unwrap(); + std::fs::create_dir(f.tempdir.path().join("lib")).unwrap(); + std::fs::create_dir(f.tempdir.path().join("bin")).unwrap(); + f.touch("lib.rs").unwrap(); + mock_rustc_cache_miss(&service.creator, f); + let mut compile = dep_compile(f, &rustc); + if let Some(value) = request_basedirs { + let value = value.replace("{both}", both.to_str().unwrap()); + compile + .env_vars + .push(("SCCACHE_BASEDIRS".into(), value.into())); + } + let (_, finished) = compile_body(&runtime, &service, compile); + assert_eq!(Some(0), finished.retcode); + } + + let stats = runtime.block_on(service.take_stats()); + stats.cache_hits.counts.values().sum::() == 1 + } + + #[test_case::test_case(false, None => false ; "no basedirs")] + #[test_case::test_case(false, Some("{both}") => true ; "request basedirs")] + #[test_case::test_case(true, None => true ; "config file basedirs")] + #[test_case::test_case(true, Some("") => false ; "empty request value clears config file basedirs")] + fn request_basedirs_reach_the_hasher( + file_basedirs: bool, + request_basedirs: Option<&str>, + ) -> bool { + second_root_hits(file_basedirs, request_basedirs) + } + /// An invalid request value runs the compiler uncached and shows in the stats. #[test] fn invalid_request_basedirs_compile_uncached() {