diff --git a/docs/Architecture.md b/docs/Architecture.md index 07a06437c4..b4d198d5d7 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -160,6 +160,22 @@ are exchanged with `StorageGetPreprocessorEntry` / `StoragePutPreprocessorEntry` Because each CLI process accumulates its own statistics, it flushes them to the daemon with `RecordStats` before exiting. +`StorageGetPath` and `StorageGetRaw` preserve backend read errors across IPC +using a separate `StorageReadError` response. Hit and miss replies retain their +existing wire format; older clients cannot decode the new error response as a +miss. Restart the daemon after upgrading so both processes use the updated +error handling. If the CLI cannot decode a cached archive, the error identifies +the local path or, for raw bytes received over IPC, the cache key. + +A compilation recorded as a cache miss also increments `Cache read errors` and +`Cache errors` if the lookup failed. Ordinary misses increment neither error +counter; overall lookup timeouts are counted separately as `Cache timeouts`. + +A multilevel cache tries the next tier when a tier read fails. These failures +do not increment the aggregate error counters, even if the chain is exhausted. +If the chain returns raw bytes that the CLI cannot open as an archive, the CLI +reports a read error rather than trying another tier. + Client-side mode is enabled with the `SCCACHE_CLIENT_SIDE` environment variable (or the `client_side_mode` config key). It is expected to become the only supported configuration in the future, with server-side mode eventually diff --git a/src/cache/disk.rs b/src/cache/disk.rs index dce55ed8d2..53527a0638 100644 --- a/src/cache/disk.rs +++ b/src/cache/disk.rs @@ -165,24 +165,18 @@ impl CacheStorage for DiskCache { .await? } - async fn get_path(&self, key: &str) -> GetPathResult { + async fn get_path(&self, key: &str) -> Result { let rel_path = make_key_path(key); let lru = self.lru.clone(); self.pool .spawn_blocking(move || { - match lru - .lock() - .unwrap() - .get_or_init() - .ok() - .and_then(|c| c.get_abs_path(&rel_path)) - { + let path = lru.lock().unwrap().get_or_init()?.get_abs_path(&rel_path); + Ok(match path { Some(p) => GetPathResult::Found(p), None => GetPathResult::Miss, - } + }) }) - .await - .unwrap_or(GetPathResult::Miss) + .await? } async fn put(&self, key: &str, entry: CacheWrite) -> Result { diff --git a/src/cache/ipc_storage.rs b/src/cache/ipc_storage.rs index 927fceea23..1bd2ce1f91 100644 --- a/src/cache/ipc_storage.rs +++ b/src/cache/ipc_storage.rs @@ -71,36 +71,38 @@ impl IpcStorage { #[async_trait] impl CacheStorage for IpcStorage { async fn get(&self, key: &str) -> Result { - match self.get_path(key).await { + match self.get_path(key).await? { GetPathResult::Found(path) => { let file = std::fs::File::open(&path) .with_context(|| format!("IpcStorage::get: open {}", path.display()))?; - match CacheRead::from(file) { - Ok(entry) => Ok(Cache::Hit(entry)), - Err(_) => Ok(Cache::Miss), - } + let entry = CacheRead::from(file) + .with_context(|| format!("IpcStorage::get: read {}", path.display()))?; + Ok(Cache::Hit(entry)) } GetPathResult::Miss => Ok(Cache::Miss), // Backend doesn't support paths (S3, Redis, …); fall back to bytes over IPC. GetPathResult::Unsupported => match self.get_raw(key).await? { - Some(bytes) => match CacheRead::from(Cursor::new(bytes)) { - Ok(entry) => Ok(Cache::Hit(entry)), - Err(_) => Ok(Cache::Miss), - }, + Some(bytes) => { + let entry = CacheRead::from(Cursor::new(bytes)).with_context(|| { + format!("IpcStorage::get: decode archive for key {key}") + })?; + Ok(Cache::Hit(entry)) + } None => Ok(Cache::Miss), }, } } - async fn get_path(&self, key: &str) -> GetPathResult { - match self + async fn get_path(&self, key: &str) -> Result { + let resp = self .rpc(Request::StorageGetPath { key: key.to_owned(), }) - .await - { - Ok(Response::StorageGetPath(result)) => result, - _ => GetPathResult::Unsupported, + .await?; + match resp { + Response::StorageGetPath(result) => Ok(result), + Response::StorageReadError(e) => bail!("IpcStorage::get_path: daemon error: {e}"), + other => bail!("IpcStorage::get_path: unexpected response: {other:?}"), } } @@ -116,6 +118,7 @@ impl CacheStorage for IpcStorage { .await?; match resp { Response::StorageGetRaw(opt) => Ok(opt.map(Bytes::from)), + Response::StorageReadError(e) => bail!("IpcStorage::get_raw: daemon error: {e}"), other => bail!("IpcStorage::get_raw: unexpected response: {other:?}"), } } diff --git a/src/cache/storage.rs b/src/cache/storage.rs index a41f8401ac..f29922fe61 100644 --- a/src/cache/storage.rs +++ b/src/cache/storage.rs @@ -28,7 +28,7 @@ use crate::config::PreprocessorCacheModeConfig; use crate::errors::*; /// Result of [`Storage::get_path`]. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum GetPathResult { /// Cache hit: the entry lives at this filesystem path. Found(PathBuf), @@ -135,8 +135,8 @@ pub trait CacheStorage: Send + Sync { /// Return the filesystem path of the cached entry for `key`. /// Default impl returns [`GetPathResult::Unsupported`]. - async fn get_path(&self, _key: &str) -> GetPathResult { - GetPathResult::Unsupported + async fn get_path(&self, _key: &str) -> Result { + Ok(GetPathResult::Unsupported) } } diff --git a/src/protocol.rs b/src/protocol.rs index a35c1388b1..8b32a329a2 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -23,7 +23,7 @@ pub enum Request { /// One-shot handshake: client requests cache metadata from the daemon. StorageHandshake, /// Fetch the filesystem path of the cached entry for `key`. - /// Returns `None` if the backend does not support direct file access or the key is absent. + /// Reports a missing key, unsupported direct file access, or a lookup error. StorageGetPath { key: String }, /// Fetch raw (zip) bytes for `key`; returns `None` on a miss. StorageGetRaw { key: String }, @@ -76,6 +76,10 @@ pub enum Response { /// /// Currently only `.rmeta` notifications are sent (for Cargo pipelining). ArtifactNotification(Vec), + + // Append new variants to preserve bincode's existing response discriminants. + /// A failed `StorageGetPath` or `StorageGetRaw` lookup. + StorageReadError(String), } /// Possible responses from the server for a `Compile` request. @@ -127,3 +131,80 @@ pub struct StorageHandshakeInfo { pub cache_mode: CacheMode, pub max_size: Option, } + +#[cfg(test)] +mod tests { + use super::*; + + // Freeze the schema before StorageReadError to exercise mixed-build replies. + #[derive(Serialize, Deserialize, Debug)] + enum LegacyResponse { + Compile(CompileResponse), + ZeroStats, + Stats(Box), + DistStatus(DistInfo), + ShuttingDown(Box), + CompileFinished(CompileFinished), + StorageHandshake(StorageHandshakeInfo), + StorageGetPath(GetPathResult), + StorageGetRaw(Option>), + StoragePutRaw(Result<(), String>), + StorageGetPreprocessorEntry(Result>, String>), + StoragePutPreprocessorEntry(Result<(), String>), + RecordStats, + ArtifactNotification(Vec), + } + + #[test] + fn storage_raw_replies_preserve_legacy_hits_and_misses() { + for expected in [None, Some(vec![1, 2, 3])] { + let old = bincode::serialize(&LegacyResponse::StorageGetRaw(expected.clone())).unwrap(); + let new = bincode::serialize(&Response::StorageGetRaw(expected.clone())).unwrap(); + assert_eq!(old, new); + + let LegacyResponse::StorageGetRaw(actual) = bincode::deserialize(&new).unwrap() else { + panic!("expected a legacy raw lookup reply"); + }; + assert_eq!(actual, expected); + let Response::StorageGetRaw(actual) = bincode::deserialize(&old).unwrap() else { + panic!("expected a raw lookup reply"); + }; + assert_eq!(actual, expected); + } + } + + #[test] + fn storage_path_replies_preserve_legacy_outcomes() { + for expected in [ + GetPathResult::Found("cache.zip".into()), + GetPathResult::Miss, + GetPathResult::Unsupported, + ] { + let old = + bincode::serialize(&LegacyResponse::StorageGetPath(expected.clone())).unwrap(); + let new = bincode::serialize(&Response::StorageGetPath(expected.clone())).unwrap(); + assert_eq!(old, new); + + let LegacyResponse::StorageGetPath(old_client) = bincode::deserialize(&new).unwrap() + else { + panic!("expected a legacy path lookup reply"); + }; + assert_eq!(old_client, expected); + let Response::StorageGetPath(new_client) = bincode::deserialize(&old).unwrap() else { + panic!("expected a path lookup reply"); + }; + assert_eq!(new_client, expected); + } + } + + #[test] + fn storage_read_errors_are_not_legacy_misses() { + let bytes = + bincode::serialize(&Response::StorageReadError("backend read failed".into())).unwrap(); + assert!(bincode::deserialize::(&bytes).is_err()); + let Response::StorageReadError(error) = bincode::deserialize(&bytes).unwrap() else { + panic!("expected a storage read error"); + }; + assert_eq!(error, "backend read failed"); + } +} diff --git a/src/server.rs b/src/server.rs index bef10d69aa..abcea23e14 100644 --- a/src/server.rs +++ b/src/server.rs @@ -928,6 +928,12 @@ where type SccacheRequest = Message>; type SccacheResponse = Message> + Send>>>; +fn storage_read_error(key: &str, error: Error) -> Response { + let message = format!("{error:#}"); + warn!("Cache lookup failed for key {key}: {message}"); + Response::StorageReadError(message) +} + /// Messages sent from all services to the main event loop indicating activity. /// /// Whenever a request is receive a `Request` message is sent which will reset @@ -1012,20 +1018,19 @@ where } Request::StorageGetPath { key } => { debug!("handle_client: storage_get_path key={}", key); - Ok(Message::WithoutBody(Response::StorageGetPath( - me.storage.get_path(&key).await, - ))) + let response = match me.storage.get_path(&key).await { + Ok(result) => Response::StorageGetPath(result), + Err(error) => storage_read_error(&key, error), + }; + Ok(Message::WithoutBody(response)) } Request::StorageGetRaw { key } => { debug!("handle_client: storage_get_raw key={}", key); - let resp = match me.storage.get_raw(&key).await { - Ok(opt) => Response::StorageGetRaw(opt.map(|b| b.to_vec())), - Err(e) => { - warn!("storage_get_raw error: {e:#}"); - Response::StorageGetRaw(None) - } + let response = match me.storage.get_raw(&key).await { + Ok(result) => Response::StorageGetRaw(result.map(|bytes| bytes.to_vec())), + Err(error) => storage_read_error(&key, error), }; - Ok(Message::WithoutBody(resp)) + Ok(Message::WithoutBody(response)) } Request::StoragePutRaw { key, data } => { debug!("handle_client: storage_put_raw key={}", key); @@ -1681,6 +1686,7 @@ where stats.cache_timeouts += 1; } MissType::CacheReadError => { + stats.cache_read_errors += 1; stats.cache_errors.increment(&kind, &lang); } } @@ -2628,6 +2634,7 @@ fn fatal_error_message(err: &anyhow::Error) -> String { #[cfg(test)] mod tests { use super::*; + use crate::cache::CacheStorage; use crate::mock_command::{MockChild, MockCommandCreator, exit_status}; use crate::test::utils::{TestFixture, next_command, next_command_calls}; @@ -3053,6 +3060,207 @@ mod tests { (body, finished) } + fn connect_ipc_storage( + runtime: &Runtime, + storage: Arc, + ) -> ( + crate::cache::IpcStorage, + tokio::task::JoinHandle>, + ) { + let listener = runtime + .block_on(tokio::net::TcpListener::bind("127.0.0.1:0")) + .unwrap(); + let addr = crate::net::SocketAddr::Net(listener.local_addr().unwrap()); + let service = MockService::mock_with_storage(storage, runtime.handle().clone()); + let server = runtime.spawn(async move { + let (socket, _) = listener.accept().await?; + service.bind(socket).await + }); + let connection = crate::client::connect_to_server(&addr).unwrap(); + let storage = crate::cache::ipc_storage::IpcStorage::connect(connection).unwrap(); + (storage, server) + } + + #[test_case::test_case(Err(anyhow!("backend read failed")), true; "backend_error")] + #[test_case::test_case(Ok(Some(bytes::Bytes::from_static(b"not a zip"))), true; "invalid_archive")] + #[test_case::test_case(Ok(None), false; "normal_miss")] + fn ipc_lookup_outcomes_reach_service_stats( + lookup: Result>, + read_error: bool, + ) { + use crate::test::mock_storage::MockStorage; + + let (_f, runtime, mut service, compile) = rustc_miss_fixture(); + let backend = Arc::new(MockStorage::new(None, false)); + backend.next_get_raw(lookup); + let (storage, server) = connect_ipc_storage(&runtime, backend); + service.storage = Arc::new(storage); + + let (response, finished, _) = runtime + .block_on(service.compile_direct(compile, &mut Vec::new())) + .unwrap(); + assert!(matches!(response, CompileResponse::CompileStarted)); + assert_eq!(finished.unwrap().retcode, Some(0)); + assert_eq!(service.creator.lock().unwrap().children.len(), 0); + let stats = runtime.block_on(service.take_stats()); + assert_eq!(stats.cache_read_errors, u64::from(read_error)); + assert_eq!(stats.cache_errors.all(), u64::from(read_error)); + assert_eq!(stats.cache_misses.all(), 1); + assert_eq!(stats.compilations, 1); + assert_eq!(stats.requests_executed, 1); + assert_eq!(stats.cache_timeouts, 0); + assert_eq!(stats.cache_hits.all(), 0); + assert_eq!(stats.compile_fails, 0); + + drop(service); + runtime.block_on(server).unwrap().unwrap(); + } + + #[test] + fn ipc_invalid_raw_archive_error_identifies_key() { + let runtime = Runtime::new().unwrap(); + let backend = Arc::new(crate::test::mock_storage::MockStorage::new(None, false)); + backend.next_get_raw(Ok(Some(bytes::Bytes::from_static(b"not a zip")))); + let (storage, server) = connect_ipc_storage(&runtime, backend); + + let key = "0123456789abcdef"; + let error = runtime.block_on(storage.get(key)).err().unwrap(); + assert!(error.to_string().contains(key), "{error:#}"); + assert!(error.downcast_ref::().is_some()); + + drop(storage); + runtime.block_on(server).unwrap().unwrap(); + } + + #[test] + fn ipc_disk_lookup_preserves_hits_misses_and_archive_errors() { + use crate::cache::{Cache, CacheWrite, GetPathResult}; + + let (_f, runtime, service, _compile) = rustc_miss_fixture(); + let (storage, server) = connect_ipc_storage(&runtime, service.storage.clone()); + let key = "0123456789abcdef"; + assert!(matches!( + runtime.block_on(storage.get(key)).unwrap(), + Cache::Miss + )); + + let mut entry = CacheWrite::new(); + entry.put_stdout(b"cached output").unwrap(); + runtime.block_on(service.storage.put(key, entry)).unwrap(); + match runtime.block_on(storage.get(key)).unwrap() { + Cache::Hit(mut entry) => assert_eq!(entry.get_stdout(), b"cached output"), + _ => panic!("expected a cache hit"), + } + + runtime + .block_on( + service + .storage + .put_raw(key, bytes::Bytes::from_static(b"not a zip")), + ) + .unwrap(); + let GetPathResult::Found(path) = runtime.block_on(service.storage.get_path(key)).unwrap() + else { + panic!("expected a cached archive path"); + }; + let error = runtime.block_on(storage.get(key)).err().unwrap(); + assert!(format!("{error:#}").contains(path.to_str().unwrap())); + assert!(error.downcast_ref::().is_some()); + + drop(storage); + runtime.block_on(server).unwrap().unwrap(); + } + + #[test_case::test_case(true; "initialization_error")] + #[test_case::test_case(false; "normal_miss")] + fn ipc_disk_path_lookup_outcomes_reach_service_stats(initialization_error: bool) { + let (f, runtime, mut service, compile) = rustc_miss_fixture(); + if initialization_error { + std::fs::write(f.tempdir.path().join("cache"), b"not a directory").unwrap(); + } + let (storage, server) = connect_ipc_storage(&runtime, service.storage.clone()); + service.storage = Arc::new(storage); + + let (response, finished, _) = runtime + .block_on(service.compile_direct(compile, &mut Vec::new())) + .unwrap(); + assert!(matches!(response, CompileResponse::CompileStarted)); + assert_eq!(finished.unwrap().retcode, Some(0)); + assert_eq!( + std::fs::read(f.tempdir.path().join("libdep.rlib")).unwrap(), + b"rlib" + ); + let stats = runtime.block_on(service.take_stats()); + assert_eq!(stats.cache_read_errors, u64::from(initialization_error)); + assert_eq!(stats.cache_errors.all(), u64::from(initialization_error)); + assert_eq!(stats.cache_misses.all(), 1); + assert_eq!(stats.cache_hits.all(), 0); + assert_eq!(stats.cache_timeouts, 0); + assert_eq!(stats.compile_fails, 0); + assert_eq!(stats.cache_writes, u64::from(!initialization_error)); + assert_eq!(stats.cache_write_errors, u64::from(initialization_error)); + + drop(service); + runtime.block_on(server).unwrap().unwrap(); + } + + #[test_case::test_case(true, false; "daemon_read_error")] + #[test_case::test_case(false, false; "daemon_normal_miss")] + #[test_case::test_case(true, true; "client_side_read_error")] + #[test_case::test_case(false, true; "client_side_normal_miss")] + fn cache_lookup_outcomes_preserve_service_stats(read_error: bool, client_side: bool) { + use crate::cache::Cache; + use crate::test::mock_storage::MockStorage; + + let (f, runtime, mut service, compile) = rustc_miss_fixture(); + let storage = Arc::new(MockStorage::new(None, false)); + storage.next_get(if read_error { + Err(anyhow!("cache lookup failed")) + } else { + Ok(Cache::Miss) + }); + service.storage = storage; + + let (finished, stats) = if client_side { + let (response, finished, _) = runtime + .block_on(service.compile_direct(compile, &mut Vec::new())) + .unwrap(); + assert!(matches!(response, CompileResponse::CompileStarted)); + ( + finished.expect("compile started"), + runtime.block_on(service.take_stats()), + ) + } else { + let (_, finished) = compile_body(&runtime, &service, compile); + ( + finished, + runtime.block_on(service.get_info()).unwrap().stats, + ) + }; + + assert_eq!(finished.retcode, Some(0)); + assert_eq!( + std::fs::read(f.tempdir.path().join("libdep.rlib")).unwrap(), + b"rlib" + ); + assert_eq!(service.creator.lock().unwrap().children.len(), 0); + assert_eq!(stats.requests_executed, 1); + assert_eq!(stats.cache_read_errors, u64::from(read_error)); + assert_eq!(stats.cache_errors.all(), u64::from(read_error)); + assert_eq!( + stats.cache_errors.get("Rust").copied().unwrap_or(0), + u64::from(read_error) + ); + assert_eq!(stats.cache_misses.all(), 1); + assert_eq!(stats.cache_misses.get("Rust"), Some(&1)); + assert_eq!(stats.compilations, 1); + assert_eq!(stats.cache_hits.all(), 0); + assert_eq!(stats.cache_timeouts, 0); + assert_eq!(stats.compile_fails, 0); + assert_eq!(stats.cache_writes, 1); + assert_eq!(stats.cache_write_errors, 0); + } + #[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 01e501477c..4fc098b547 100644 --- a/src/test/mock_storage.rs +++ b/src/test/mock_storage.rs @@ -16,6 +16,7 @@ use crate::cache::{Cache, CacheStorage, CacheWrite, PreprocessorCacheStorage}; use crate::config::PreprocessorCacheModeConfig; use crate::errors::*; use async_trait::async_trait; +use bytes::Bytes; use futures::channel::mpsc; use std::sync::Arc; use std::time::Duration; @@ -26,6 +27,8 @@ use tokio::time::sleep; pub struct MockStorage { rx: Arc>>>, tx: mpsc::UnboundedSender>, + raw_rx: Mutex>>>, + raw_tx: mpsc::UnboundedSender>>, delay: Option, preprocessor_cache_mode: bool, basedirs: Vec>, @@ -35,10 +38,13 @@ impl MockStorage { /// Create a new `MockStorage`. if `delay` is `Some`, wait for that amount of time before returning from operations. pub(crate) fn new(delay: Option, preprocessor_cache_mode: bool) -> MockStorage { let (tx, rx) = mpsc::unbounded(); + let (raw_tx, raw_rx) = mpsc::unbounded(); Self { tx, rx: Arc::new(Mutex::new(rx)), delay, + raw_tx, + raw_rx: Mutex::new(raw_rx), preprocessor_cache_mode, basedirs: vec![], } @@ -53,6 +59,11 @@ impl MockStorage { pub(crate) fn next_get(&self, res: Result) { self.tx.unbounded_send(res).unwrap(); } + + /// Queue up `res` to be returned as the next result from `Storage::get_raw`. + pub(crate) fn next_get_raw(&self, res: Result>) { + self.raw_tx.unbounded_send(res).unwrap(); + } } #[async_trait] @@ -67,6 +78,13 @@ impl CacheStorage for MockStorage { .try_recv() .expect("MockStorage get called but no get results available") } + async fn get_raw(&self, _key: &str) -> Result> { + self.raw_rx + .lock() + .await + .try_recv() + .expect("MockStorage get_raw called but no get_raw results available") + } async fn put(&self, _key: &str, _entry: CacheWrite) -> Result { Ok(if let Some(delay) = self.delay { sleep(delay).await;