Skip to content
16 changes: 16 additions & 0 deletions docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 5 additions & 11 deletions src/cache/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<GetPathResult> {
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<Duration> {
Expand Down
33 changes: 18 additions & 15 deletions src/cache/ipc_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,36 +71,38 @@ impl IpcStorage {
#[async_trait]
impl CacheStorage for IpcStorage {
async fn get(&self, key: &str) -> Result<Cache> {
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<GetPathResult> {
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:?}"),
}
}

Expand All @@ -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:?}"),
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/cache/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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<GetPathResult> {
Ok(GetPathResult::Unsupported)
}
}

Expand Down
83 changes: 82 additions & 1 deletion src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -76,6 +76,10 @@ pub enum Response {
///
/// Currently only `.rmeta` notifications are sent (for Cargo pipelining).
ArtifactNotification(Vec<u8>),

// 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.
Expand Down Expand Up @@ -127,3 +131,80 @@ pub struct StorageHandshakeInfo {
pub cache_mode: CacheMode,
pub max_size: Option<u64>,
}

#[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<ServerInfo>),
DistStatus(DistInfo),
ShuttingDown(Box<ServerInfo>),
CompileFinished(CompileFinished),
StorageHandshake(StorageHandshakeInfo),
StorageGetPath(GetPathResult),
StorageGetRaw(Option<Vec<u8>>),
StoragePutRaw(Result<(), String>),
StorageGetPreprocessorEntry(Result<Option<Vec<u8>>, String>),
StoragePutPreprocessorEntry(Result<(), String>),
RecordStats,
ArtifactNotification(Vec<u8>),
}

#[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::<LegacyResponse>(&bytes).is_err());
let Response::StorageReadError(error) = bincode::deserialize(&bytes).unwrap() else {
panic!("expected a storage read error");
};
assert_eq!(error, "backend read failed");
}
}
Loading
Loading