From a5c8b893be685263bec1a5683681ddee74b93bbd Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 19:24:21 +0800 Subject: [PATCH 1/9] fix(cache): cap remote cache uploads, retry transient errors, and use HTTP/1.1 Co-authored-by: Gemini 4 Neon --- CHANGELOG.md | 1 + Cargo.lock | 22 +- crates/vt/src/session/cache/remote.rs | 191 ++++++-- crates/vt_remote_cache/Cargo.toml | 4 +- crates/vt_remote_cache/README.md | 6 +- crates/vt_remote_cache/src/lib.rs | 674 ++++++++++++++++++++++---- crates/vt_remote_cache/src/retry.rs | 555 +++++++++++++++++++++ 7 files changed, 1310 insertions(+), 143 deletions(-) create mode 100644 crates/vt_remote_cache/src/retry.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index fe274ce3e..ad334a2d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Fixed** Remote cache operations now cap concurrent uploads to 4 per endpoint, use pooled HTTP/1.1 connections instead of multiplexing all reads and uploads over one HTTP/2 connection, retry transient `5xx`/`429`/`408` and network failures with jittered backoff, and back off briefly during sustained endpoint outages, preventing `503` upload bursts and Windows connection-reset drops ([#1016](https://github.com/voidzero-dev/vite-task/pull/1016)). - **Fixed** Tasks that list `node_modules`, the workspace root, or `node_modules/.vite` no longer miss the cache when pnpm's `node_modules/.pnpm-workspace-state-*.json`, Vite's `node_modules/.vite-temp`, the workspace root's `.git`, or the task cache directory appear or disappear. Direct accesses to `node_modules/.vite-temp` and `.DS_Store` are now skipped as well, so they are neither tracked as inputs nor archived as outputs ([#1014](https://github.com/voidzero-dev/vite-task/pull/1014)). - **Fixed** When a command handler sets a working directory for a command it generates, `vp run` now runs that command in the selected directory and includes the directory in its cache fingerprint ([#1005](https://github.com/voidzero-dev/vite-task/pull/1005)). - **Fixed** On Windows, tasks with automatic file-access tracking can now run Git Bash's `sh` and other MSYS2 or Cygwin programs, which aborted with `fatal error - MapViewOfFileEx 'shared.5'(…) Win32 error 487` ([#830](https://github.com/voidzero-dev/vite-task/issues/830), [#952](https://github.com/voidzero-dev/vite-task/pull/952)). diff --git a/Cargo.lock b/Cargo.lock index 1a88b4cbd..f1c07adcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1798,25 +1798,6 @@ dependencies = [ "regex-syntax", ] -[[package]] -name = "h2" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "half" version = "2.7.1" @@ -1948,7 +1929,6 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2", "http", "http-body", "httparse", @@ -3636,7 +3616,6 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "h2", "http", "http-body", "http-body-util", @@ -5336,6 +5315,7 @@ dependencies = [ "base64 0.22.1", "bytes", "ciborium", + "getrandom 0.4.2", "reqwest", "rustls", "serde", diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index e9864f849..58addfe32 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -400,34 +400,66 @@ const CHECK_BUFFER_CHUNKS: usize = 16; /// Download the blob `blob_id` to the file at `path`, until `cancel_token` is /// cancelled. The chunks flow one way: from the network to the archive check /// on a blocking thread, which writes each one to the file as it takes it. +/// If the stream drops mid-transfer with a network error, the download is +/// retried once from the start (with a single header attempt), overwriting the +/// partial `.tmp` file. async fn download_checked( client: &Client, blob_id: &str, path: &AbsolutePath, cancel_token: &CancellationToken, ) -> Result<(), ReadError> { - let download = cancel_token - .run_until_cancelled(client.download(blob_id)) - .await - .ok_or(ReadError::Cancelled)? - .map_err(ReadError::Download)?; - let file = File::create(path.as_path()).map_err(ReadError::WriteArchive)?; - let (sender, receiver) = mpsc::channel(CHECK_BUFFER_CHUNKS); - let check = tokio::task::spawn_blocking(move || { - let mut reader = DownloadReader { receiver, chunk: Bytes::new(), file, write_error: None }; - let checked = archive::read_output_archive(&mut reader, |_| {}); - if let Some(err) = reader.write_error { - return Err(ReadError::WriteArchive(err)); + const MAX_STREAM_ATTEMPTS: usize = 2; + + for attempt in 0..MAX_STREAM_ATTEMPTS { + let download_fut = async { + if attempt == 0 { + client.download(blob_id).await + } else { + client.download_once(blob_id).await + } + }; + let download = cancel_token + .run_until_cancelled(download_fut) + .await + .ok_or(ReadError::Cancelled)? + .map_err(ReadError::Download)?; + let file = File::create(path.as_path()).map_err(ReadError::WriteArchive)?; + let (sender, receiver) = mpsc::channel(CHECK_BUFFER_CHUNKS); + let check = tokio::task::spawn_blocking(move || { + let mut reader = + DownloadReader { receiver, chunk: Bytes::new(), file, write_error: None }; + let checked = archive::read_output_archive(&mut reader, |_| {}); + if let Some(err) = reader.write_error { + return Err(ReadError::WriteArchive(err)); + } + checked.map_err(ReadError::CorruptArchive) + }); + // Cancelling drops the sender, which ends the check. + let sent = cancel_token.run_until_cancelled(send_chunks(download, sender)).await; + // Wait for the check even after a network error or cancellation, so the + // file is closed before the caller removes it or retries. + let checked = check.await.unwrap_or_else(|err| Err(ReadError::CorruptArchive(err.into()))); + if cancel_token.is_cancelled() { + return Err(ReadError::Cancelled); } - checked.map_err(ReadError::CorruptArchive) - }); - // Cancelling drops the sender, which ends the check. - let sent = cancel_token.run_until_cancelled(send_chunks(download, sender)).await; - // Wait for the check even after a network error or cancellation, so the - // file is closed before the caller removes it. - let checked = check.await.unwrap_or_else(|err| Err(ReadError::CorruptArchive(err.into()))); - sent.ok_or(ReadError::Cancelled)?.map_err(ReadError::Download)?; - checked + match sent.ok_or(ReadError::Cancelled)? { + Ok(()) => return checked, + Err(err @ vt_remote_cache::Error::Network(_)) if attempt + 1 < MAX_STREAM_ATTEMPTS => { + // Local disk write failures are not transient network drops. + if let Err(err @ ReadError::WriteArchive(_)) = checked { + return Err(err); + } + tracing::debug!( + ?err, + attempt = attempt + 1, + "retrying remote cache archive download after mid-stream network error" + ); + } + Err(err) => return Err(ReadError::Download(err)), + } + } + unreachable!("MAX_STREAM_ATTEMPTS is always at least 1") } /// Send the blob's chunks through `sender` until the blob ends or the receiver @@ -1081,7 +1113,7 @@ mod tests { #[tokio::test] async fn failed_upload_sets_its_error() { let (error_status, _) = - serve_stalled(b"HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\n\r\n"); + serve_stalled(b"HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n"); // Nothing can listen on port 0. let unreachable = anonymous("http://127.0.0.1:0/projects/test"); let github_oidc_unavailable = ResolvedRemoteCacheConfig { @@ -1096,7 +1128,7 @@ mod tests { let uploads = RemoteUploads::default(); for (remote_config, message) in [ - (error_status, "HTTP status 500"), + (error_status, "HTTP status 403"), (unreachable, "network error"), (github_oidc_unavailable, "failed to authenticate"), ] { @@ -1108,19 +1140,120 @@ mod tests { } } + #[tokio::test] + async fn mid_stream_download_network_error_is_retried() { + let dir = tempfile::tempdir().unwrap(); + let cache_dir = AbsolutePathBuf::new(dir.path().to_path_buf()).unwrap(); + // Build a valid `.tar.zst` archive with a real entry so a strict prefix + // is valid zstd up to EOF (preventing the archive check from failing + // ahead of the network truncation error). + let payload = vec![b'x'; 4096]; + let mut encoder = zstd::Encoder::new(Vec::new(), zstd::DEFAULT_COMPRESSION_LEVEL).unwrap(); + { + let mut tar = tar::Builder::new(&mut encoder); + let mut header = tar::Header::new_gnu(); + header.set_size(u64::try_from(payload.len()).unwrap()); + header.set_mode(0o644); + header.set_cksum(); + tar.append_data(&mut header, "dist/out.txt", payload.as_slice()).unwrap(); + tar.finish().unwrap(); + } + let archive_bytes = encoder.finish().unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let server = std::thread::spawn(move || { + let truncated_prefix = &archive_bytes[..archive_bytes.len() / 2]; + for response in [ + // Attempt 1: valid prefix truncated before announced Content-Length -> mid-stream network error. + [ + vt_str::format!( + "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", + archive_bytes.len() + ) + .as_bytes(), + truncated_prefix, + ] + .concat(), + // Attempt 2: complete valid archive. + [ + vt_str::format!( + "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", + archive_bytes.len() + ) + .as_bytes(), + &archive_bytes, + ] + .concat(), + ] { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut buf = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&buf[..n]); + } + stream.write_all(&response).unwrap(); + } + }); + + let archive_name = RemoteClients::default() + .download_archive(&remote_config, "1", &cache_dir, &CancellationToken::new()) + .await + .unwrap(); + assert!(cache_dir.join(archive_name.as_str()).as_path().is_file()); + server.join().unwrap(); + } + #[tokio::test] async fn interrupting_the_wait_cancels_the_uploads() { - let (remote_config, requested) = serve_stalled(b""); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let total = vt_remote_cache::MAX_CONCURRENT_STORES + 2; + let (all_slots_filled_tx, all_slots_filled_rx) = oneshot::channel(); + std::thread::spawn(move || { + // Hold open `MAX_CONCURRENT_STORES` requests while more uploads are + // pending so cancelling interrupts both active and queued uploads. + let mut streams = Vec::new(); + for _ in 0..vt_remote_cache::MAX_CONCURRENT_STORES { + let Ok((mut stream, _)) = listener.accept() else { break }; + let mut request = Vec::new(); + let mut buf = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + match stream.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => request.extend_from_slice(&buf[..n]), + } + } + streams.push(stream); + } + let _ = all_slots_filled_tx.send(()); + // Wait until the client drops the connections on cancel. + for mut stream in streams { + let mut buf = [0; 64]; + while stream.read(&mut buf).is_ok_and(|n| n > 0) {} + } + }); + let clients = RemoteClients::default(); let uploads = RemoteUploads::default(); - let error = Arc::new(OnceLock::new()); - uploads.spawn(prepare_upload(&clients, &remote_config).unwrap(), Arc::clone(&error)); - requested.await.unwrap(); - assert_eq!(uploads.pending(), 1); + let mut errors = Vec::with_capacity(total); + for _ in 0..total { + let error = Arc::new(OnceLock::new()); + uploads.spawn(prepare_upload(&clients, &remote_config).unwrap(), Arc::clone(&error)); + errors.push(error); + } + all_slots_filled_rx.await.unwrap(); + assert_eq!(uploads.pending(), total); let interrupt_token = CancellationToken::new(); tokio::join!(uploads.wait(&interrupt_token), async { interrupt_token.cancel() }); assert_eq!(uploads.pending(), 0); - assert!(matches!(error.get(), Some(UploadError::Interrupted)), "{error:?}"); + for error in errors { + assert!(matches!(error.get(), Some(UploadError::Interrupted)), "{error:?}"); + } } } diff --git a/crates/vt_remote_cache/Cargo.toml b/crates/vt_remote_cache/Cargo.toml index 607665be6..436e14dfc 100644 --- a/crates/vt_remote_cache/Cargo.toml +++ b/crates/vt_remote_cache/Cargo.toml @@ -11,8 +11,8 @@ rust-version.workspace = true base64 = { workspace = true } bytes = { workspace = true } ciborium = { workspace = true } +getrandom = { workspace = true } reqwest = { workspace = true, features = [ - "http2", "multipart", "rustls-no-provider", "stream", @@ -23,7 +23,7 @@ serde = { workspace = true, features = ["derive"] } serde_bytes = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } -tokio = { workspace = true, features = ["fs", "sync"] } +tokio = { workspace = true, features = ["fs", "sync", "time"] } tracing = { workspace = true } url = { workspace = true } vt_path = { workspace = true } diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index 29c1ab722..020121017 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -12,10 +12,10 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta `Client::download` gets a blob by its ID. After a 200 response, it returns a `Download`, from which the caller reads the blob's chunks as they arrive. -`Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. +`Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. At most `MAX_CONCURRENT_STORES` (4) stores run concurrently per client. -Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. +Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Transient network errors and retryable HTTP statuses (`408`, `429`, and `5xx` other than `501`, `505`, and `511`) are retried with jittered exponential backoff (up to 3 retries within a 60-second retry budget for stores, and up to 2 retries within a 15-second retry budget for fetches and downloads). On `429 Too Many Requests`, concurrent requests of the same kind (reads or stores) on that client share a cooldown using the response's integer `Retry-After` header (clamped to 10 seconds, floored at the attempt's backoff); `5xx` responses use per-request backoff only. After 3 consecutive exhausted outage failures (network errors or retryable `5xx`), a per-client circuit breaker short-circuits requests with `Error::Unavailable` for 30 seconds before probing with one request. -reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. HTTPS requests use HTTP/2 if the server accepts it during the TLS handshake and HTTP/1.1 otherwise. HTTP endpoints always use HTTP/1.1. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request. +reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 20-second per-attempt timeout. `Error` names the kind of failure: an invalid endpoint, a client that couldn't be created, a blob file that couldn't be read, credentials that couldn't be obtained, a network error (including timeouts and responses that end early), a status other than 200 (or 404, for a fetch), or a malformed fetch response. Its messages contain no OS-specific details, so they can be shown to users as is. The details are in the source: the underlying error, the parse error for an endpoint that isn't a URL, or the message in an error response's body. Network errors leave out the request URL, since the endpoint may contain credentials, such as a token in its query. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index 5987090f8..5820c0ad8 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -2,6 +2,7 @@ //! bytes; the caller decides what they contain. pub mod auth; +mod retry; #[cfg(test)] mod test_server; @@ -12,16 +13,20 @@ use std::{ use bytes::Bytes; use reqwest::{ - Response, StatusCode, + Body, Response, StatusCode, header::{CONTENT_TYPE, HeaderMap}, multipart::{Form, Part}, }; use serde::{Deserialize, Deserializer, Serialize}; +use tokio::sync::Semaphore; use url::{ParseError, Url}; use vt_path::AbsolutePath; use vt_str::Str; -use crate::auth::{Auth, AuthError, Operation}; +use crate::{ + auth::{Auth, AuthError, Operation}, + retry::{AttemptError, OutageBreaker, RateLimit, RetryConfig, parse_retry_after}, +}; /// Time allowed to establish a connection, including the TLS handshake. const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); @@ -30,6 +35,22 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); /// arrive, it also bounds sending the request. const READ_TIMEOUT: Duration = Duration::from_secs(60); +/// Total timeout for a single `POST /fetch` attempt. Fetches transfer small +/// metadata payloads, so bounding them more tightly lets a hung lookup retry +/// or fall back quickly instead of stalling a task for [`READ_TIMEOUT`]. +const FETCH_TIMEOUT: Duration = Duration::from_secs(20); + +/// Idle timeout for pooled HTTP/1.1 keep-alive connections, kept below typical +/// NAT and edge proxy idle cutoffs to reduce stale-socket resets on reuse. +const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30); + +/// Maximum number of concurrent `POST /store` uploads in flight per [`Client`]. +/// +/// Bounding uploads per client shapes bursts against backends with per-isolate +/// admission limits, prevents uplink thrashing, and caps open blob file +/// handles. +pub const MAX_CONCURRENT_STORES: usize = 4; + /// A failed remote cache operation. The messages name only the kind of /// failure, so they are the same on every platform. The details, if any, are /// in the source. @@ -64,6 +85,10 @@ pub enum Error { /// The body of a 200 fetch response isn't an exact or fallback match. #[error("malformed response")] MalformedResponse(#[source] ciborium::de::Error), + /// The remote cache endpoint recently failed repeatedly, so this request + /// was skipped during the outage cooldown window. + #[error("remote cache temporarily unavailable")] + Unavailable, } /// The message in the body of an error response. @@ -150,6 +175,16 @@ pub struct Client { store_url: Url, /// `{endpoint}/blob`, to which each download appends a blob ID. blob_url: Url, + /// Bounds concurrent `POST /store` uploads in flight for this endpoint. + store_permits: Semaphore, + /// Shared cooldown for `429 Too Many Requests` on read operations so + /// upload rate limits do not stall fetches on the task critical path. + read_rate_limit: RateLimit, + /// Shared cooldown for `429 Too Many Requests` on store operations. + store_rate_limit: RateLimit, + /// Circuit breaker that short-circuits requests during sustained outages. + outage: OutageBreaker, + retry: RetryConfig, } impl Client { @@ -162,6 +197,10 @@ impl Client { /// Returns [`Error::InvalidEndpoint`] if `endpoint` isn't a usable URL, or /// [`Error::HttpClient`] if the HTTP client can't be created. pub fn new(endpoint: &str, auth: Arc) -> Result { + Self::with_retry(endpoint, auth, RetryConfig::DEFAULT) + } + + fn with_retry(endpoint: &str, auth: Arc, retry: RetryConfig) -> Result { let endpoint = parse_endpoint(endpoint)?; let fetch_url = route_url(&endpoint, "fetch")?; let store_url = route_url(&endpoint, "store")?; @@ -171,15 +210,31 @@ impl Client { // ring too. let _ = rustls::crypto::ring::default_provider().install_default(); // A redirect fails like any other status. Following one could turn a - // store into a GET of a login page that responds with 200. HTTPS - // endpoints use HTTP/2 if the server accepts it in the TLS handshake. + // store into a GET of a login page that responds with 200. Force + // HTTP/1.1 connection pooling (even if another crate enables reqwest's + // `http2` feature) so concurrent uploads and fetches get independent + // sockets instead of sharing fate on one multiplexed H2 connection. + // reqwest's default 15s TCP keep-alive stays enabled. let http = reqwest::Client::builder() + .http1_only() .connect_timeout(CONNECT_TIMEOUT) .read_timeout(READ_TIMEOUT) + .pool_idle_timeout(POOL_IDLE_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .build() .map_err(Error::HttpClient)?; - Ok(Self { http, auth, fetch_url, store_url, blob_url }) + Ok(Self { + http, + auth, + fetch_url, + store_url, + blob_url, + store_permits: Semaphore::new(MAX_CONCURRENT_STORES), + read_rate_limit: RateLimit::default(), + store_rate_limit: RateLimit::default(), + outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), + retry, + }) } async fn auth_headers(&self, operation: Operation) -> Result { @@ -188,7 +243,9 @@ impl Client { /// Fetch the entries stored under `key` with `POST {endpoint}/fetch`, /// falling back to the key associated with `secondary_key`. Returns - /// `None` for a 404 response, which means neither key matched. + /// `None` for a 404 response, which means neither key matched. Transient + /// network errors and retryable HTTP statuses (`408`, `429`, `5xx` except + /// `501`/`505`/`511`) are retried with jittered exponential backoff. /// /// # Errors /// @@ -197,33 +254,53 @@ impl Client { /// body of a 200 response isn't an exact or fallback match. #[tracing::instrument(level = "debug", skip_all)] pub async fn fetch(&self, key: &[u8], secondary_key: &[u8]) -> Result, Error> { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Fetch).await?; - let body = encode_cbor(&FetchRequest { key, secondary_key }); - let response = self - .http - .post(self.fetch_url.clone()) - .headers(headers) - .header(CONTENT_TYPE, "application/cbor") - .body(body) - .send() - .await - .map_err(network_error)?; - log_response(&response, start); - if response.status() == StatusCode::NOT_FOUND { - // Read the body so the connection can be reused. It doesn't matter - // if that fails, because the status alone is the answer. - let _ = response.bytes().await; - return Ok(None); - } - let body = check_status(response).await?.bytes().await.map_err(network_error)?; - tracing::debug!(bytes = body.len(), elapsed = ?start.elapsed(), "remote cache fetch received"); - decode_fetched(&body).map(Some) + let body = Bytes::from(encode_cbor(&FetchRequest { key, secondary_key })); + let policy = self.retry.read; + let result = retry::run("fetch", policy, &self.read_rate_limit, &self.outage, || { + let body = body.clone(); + async move { + let start = Instant::now(); + let headers = self.auth_headers(Operation::Fetch).await?; + let response = self + .http + .post(self.fetch_url.clone()) + .headers(headers) + .header(CONTENT_TYPE, "application/cbor") + .timeout(FETCH_TIMEOUT) + .body(body) + .send() + .await + .map_err(network_error)?; + log_response(&response, start); + if response.status() == StatusCode::NOT_FOUND { + // Read the body so the connection can be reused. It doesn't matter + // if that fails, because the status alone is the answer. + let _ = response.bytes().await; + return Ok(None); + } + let body = check_status(response, policy.max_retry_after) + .await? + .bytes() + .await + .map_err(network_error)?; + tracing::debug!( + bytes = body.len(), + elapsed = ?start.elapsed(), + "remote cache fetch received" + ); + decode_fetched(&body).map(Some).map_err(AttemptError::from) + } + }) + .await; + drop(body); + result } /// Start downloading the blob `blob_id` with /// `GET {endpoint}/blob/{blob_id}`. Its chunks are read from the returned - /// [`Download`] as they arrive. + /// [`Download`] as they arrive. Transient network errors and retryable + /// HTTP statuses (`408`, `429`, `5xx` except `501`/`505`/`511`) before the + /// response headers arrive are retried with jittered exponential backoff. /// /// # Errors /// @@ -231,18 +308,49 @@ impl Client { /// fails, or the server responds with a status other than 200. #[tracing::instrument(level = "debug", skip_all)] pub async fn download(&self, blob_id: &str) -> Result { - let start = Instant::now(); + self.download_with_policy(blob_id, self.retry.read).await + } + + /// Start downloading the blob `blob_id` with a single attempt (no header + /// retries), used when retrying a download that dropped mid-stream so + /// outer and inner retry layers do not multiply. + /// + /// # Errors + /// + /// Returns an error if the credentials can't be obtained, the request + /// fails, or the server responds with a status other than 200. + #[tracing::instrument(level = "debug", skip_all)] + pub async fn download_once(&self, blob_id: &str) -> Result { + self.download_with_policy(blob_id, self.retry.read.once()).await + } + + async fn download_with_policy( + &self, + blob_id: &str, + policy: retry::RetryPolicy, + ) -> Result { let mut url = self.blob_url.clone(); url.path_segments_mut().map_err(|()| Error::InvalidEndpoint(None))?.push(blob_id); - let headers = self.auth_headers(Operation::Download).await?; - let response = self.http.get(url).headers(headers).send().await.map_err(network_error)?; - log_response(&response, start); - Ok(Download { response: check_status(response).await? }) + retry::run("download", policy, &self.read_rate_limit, &self.outage, || { + let url = url.clone(); + async move { + let start = Instant::now(); + let headers = self.auth_headers(Operation::Download).await?; + let response = + self.http.get(url).headers(headers).send().await.map_err(network_error)?; + log_response(&response, start); + Ok(Download { response: check_status(response, policy.max_retry_after).await? }) + } + }) + .await } /// Store `value` under `key` with `POST {endpoint}/store`, uploading the /// file at `blob` as its blob. Fetches that match no key fall back to this - /// entry through `secondary_key`. + /// entry through `secondary_key`. At most [`MAX_CONCURRENT_STORES`] stores + /// run concurrently per client, and transient network errors or retryable + /// HTTP statuses (`408`, `429`, `5xx` except `501`/`505`/`511`) are + /// retried with jittered exponential backoff. /// /// # Errors /// @@ -250,6 +358,7 @@ impl Client { /// can't be opened, the request fails, or the server responds with a /// status other than 200. #[tracing::instrument(level = "debug", skip_all)] + #[expect(clippy::missing_panics_doc, reason = "store_permits semaphore is never closed")] pub async fn store( &self, key: &[u8], @@ -257,37 +366,55 @@ impl Client { value: &[u8], blob: Option<&AbsolutePath>, ) -> Result<(), Error> { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Store).await?; - let auth = start.elapsed(); - let metadata = StoreMetadata { key, secondary_key, value }; - let mut form = Form::new().part("metadata", metadata_part(&metadata)); - let blob_bytes = if let Some(blob) = blob { - let (part, length) = blob_part(blob).await?; - form = form.part("blob", part); - Some(length) - } else { - None - }; - tracing::debug!( - value_bytes = value.len(), - blob_bytes, - ?auth, - "sending a remote cache store" - ); - let response = self - .http - .post(self.store_url.clone()) - .headers(headers) - .multipart(form) - .send() - .await - .map_err(network_error)?; - log_response(&response, start); - // The response's blob ID isn't needed. Read the body anyway, so the - // connection can be reused. - check_status(response).await?.bytes().await.map_err(network_error)?; - Ok(()) + let queue_start = Instant::now(); + let permit = self.store_permits.acquire().await.expect("store semaphore is never closed"); + let queued = queue_start.elapsed(); + let metadata_bytes = Bytes::from(encode_cbor(&StoreMetadata { key, secondary_key, value })); + let value_bytes = value.len(); + let policy = self.retry.store; + let result = retry::run("store", policy, &self.store_rate_limit, &self.outage, || { + let metadata_bytes = metadata_bytes.clone(); + async move { + let start = Instant::now(); + let headers = self.auth_headers(Operation::Store).await?; + let auth = start.elapsed(); + let mut form = Form::new().part("metadata", metadata_part(metadata_bytes)); + let blob_bytes = if let Some(blob) = blob { + let (part, length) = blob_part(blob).await?; + form = form.part("blob", part); + Some(length) + } else { + None + }; + tracing::debug!( + value_bytes, + blob_bytes, + ?queued, + ?auth, + "sending a remote cache store" + ); + let response = self + .http + .post(self.store_url.clone()) + .headers(headers) + .multipart(form) + .send() + .await + .map_err(network_error)?; + log_response(&response, start); + // The response's blob ID isn't needed. Read the body anyway, so the + // connection can be reused. + check_status(response, policy.max_retry_after) + .await? + .bytes() + .await + .map_err(network_error)?; + Ok(()) + } + }) + .await; + drop(permit); + result } } @@ -304,17 +431,25 @@ fn log_response(response: &Response, start: Instant) { } /// Only HTTP 200 counts as success. For other statuses, the error includes the -/// message in the response body. -async fn check_status(response: Response) -> Result { +/// message in the response body. For `429 Too Many Requests`, any valid +/// integer `Retry-After` header is also returned (clamped to `max_retry_after`) +/// so the client's shared cooldown can honor it. +async fn check_status( + response: Response, + max_retry_after: Duration, +) -> Result { let status = response.status(); if status == StatusCode::OK { return Ok(response); } + let rate_limit_delay = (status == StatusCode::TOO_MANY_REQUESTS) + .then(|| parse_retry_after(response.headers(), max_retry_after)) + .flatten(); let message = response.text().await.ok().and_then(|text| { let text = text.trim(); (!text.is_empty()).then(|| ServerMessage(Str::from(text))) }); - Err(Error::Status(status, message)) + Err(AttemptError { error: Error::Status(status, message), rate_limit_delay }) } fn network_error(err: reqwest::Error) -> Error { @@ -354,8 +489,11 @@ fn encode_cbor(value: &impl Serialize) -> Vec { bytes } -fn metadata_part(metadata: &StoreMetadata<'_>) -> Part { - Part::bytes(encode_cbor(metadata)).mime_str("application/cbor").expect("valid MIME type") +fn metadata_part(metadata_bytes: Bytes) -> Part { + let length = u64::try_from(metadata_bytes.len()).expect("metadata length fits in u64"); + Part::stream_with_length(Body::from(metadata_bytes), length) + .mime_str("application/cbor") + .expect("valid MIME type") } /// The blob part streamed from the file at `path`, and its length. @@ -370,7 +508,11 @@ async fn blob_part(path: &AbsolutePath) -> Result<(Part, u64), Error> { #[cfg(test)] mod tests { - use std::{io::Read as _, net::TcpListener}; + use std::{ + io::{Read as _, Write as _}, + net::TcpListener, + sync::atomic::{AtomicUsize, Ordering}, + }; use reqwest::header::{HeaderName, HeaderValue}; use vt_path::AbsolutePathBuf; @@ -378,9 +520,34 @@ mod tests { use super::*; use crate::{ auth::{Anonymous, AuthHeaders}, + retry::RetryPolicy, test_server::{contains, no_request_waiting, serve_once, serve_raw_once}, }; + /// Zero-delay retry config with the same attempt counts as production, so + /// retry tests exercise the full retry loop without sleeping. + const FAST_RETRY: RetryConfig = RetryConfig { + read: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + ..RetryPolicy::READ + }, + store: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + ..RetryPolicy::STORE + }, + ..RetryConfig::DEFAULT + }; + + /// Single-attempt retry config for tests that intentionally drop the + /// connection after inspecting one request (such as TLS `ClientHello`). + const NO_RETRY: RetryConfig = RetryConfig { + read: RetryPolicy { max_retries: 0, ..FAST_RETRY.read }, + store: RetryPolicy { max_retries: 0, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + fn store_url(endpoint: &str) -> Result { route_url(&parse_endpoint(endpoint)?, "store") } @@ -489,11 +656,25 @@ mod tests { client_with_auth(listener, Arc::new(Anonymous)) } + fn fast_client_for(listener: &TcpListener) -> Client { + client_with_retry(listener, Arc::new(Anonymous), FAST_RETRY) + } + fn client_with_auth(listener: &TcpListener, auth: Arc) -> Client { let port = listener.local_addr().unwrap().port(); Client::new(&vt_str::format!("http://127.0.0.1:{port}/projects/test"), auth).unwrap() } + fn client_with_retry( + listener: &TcpListener, + auth: Arc, + retry: RetryConfig, + ) -> Client { + let port = listener.local_addr().unwrap().port(); + Client::with_retry(&vt_str::format!("http://127.0.0.1:{port}/projects/test"), auth, retry) + .unwrap() + } + /// The `metadata` part of a store request for key `k`, secondary key `s`, /// and value `v`. fn metadata_part_bytes() -> Vec { @@ -556,15 +737,17 @@ mod tests { #[tokio::test] async fn fetch_fails_on_an_error_status() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = client_for(&listener); + let client = fast_client_for(&listener); let server = std::thread::spawn(move || { - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"try later") + (0..3) + .map(|_| serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"try later")) + .collect::>() }); let error = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(error, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{error:?}"); assert_eq!(std::error::Error::source(&error).unwrap().to_string(), "try later"); - server.join().unwrap(); + assert_eq!(server.join().unwrap().len(), 3); } async fn read_to_end(mut download: Download) -> Result, Error> { @@ -623,9 +806,13 @@ mod tests { let blob = AbsolutePathBuf::new(dir.path().join("archive.tar.zst")).unwrap(); std::fs::write(blob.as_path(), b"archive bytes").unwrap(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = client_for(&listener); + let client = fast_client_for(&listener); let server = std::thread::spawn(move || { - serve_once(&listener, "HTTP/1.1 500 Internal Server Error", b"storage failed\n") + (0..4) + .map(|_| { + serve_once(&listener, "HTTP/1.1 500 Internal Server Error", b"storage failed\n") + }) + .collect::>() }); let err = client.store(b"k", b"s", b"v", Some(&blob)).await.unwrap_err(); @@ -633,13 +820,16 @@ mod tests { assert_eq!(err.to_string(), "HTTP status 500"); assert_eq!(std::error::Error::source(&err).unwrap().to_string(), "storage failed"); - let request = server.join().unwrap(); - assert!(request.starts_with(b"POST /projects/test/store HTTP/1.1\r\n")); - assert!(contains(&request, b"content-type: multipart/form-data; boundary=")); - assert!(contains(&request, &metadata_part_bytes())); - let blob = + let requests = server.join().unwrap(); + assert_eq!(requests.len(), 4); + let blob_part = b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; - assert!(contains(&request, blob)); + for request in &requests { + assert!(request.starts_with(b"POST /projects/test/store HTTP/1.1\r\n")); + assert!(contains(request, b"content-type: multipart/form-data; boundary=")); + assert!(contains(request, &metadata_part_bytes())); + assert!(contains(request, blob_part)); + } } #[tokio::test] @@ -772,12 +962,13 @@ mod tests { } #[tokio::test] - async fn offers_http2_over_tls() { + async fn uses_http1_only_over_tls() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - let client = Client::new( + let client = Client::with_retry( &vt_str::format!("https://127.0.0.1:{port}/projects/test"), Arc::new(Anonymous), + NO_RETRY, ) .unwrap(); let server = std::thread::spawn(move || read_client_hello(&listener)); @@ -785,14 +976,321 @@ mod tests { let error = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(error, Error::Network(_)), "{error:?}"); - // The ALPN extension lists h2, then http/1.1. - assert!(contains(&server.join().unwrap(), b"\x02h2\x08http/1.1")); + // HTTP/1.1 only: the ALPN extension lists http/1.1 and must not offer h2. + let client_hello = server.join().unwrap(); + assert!(contains(&client_hello, b"\x08http/1.1")); + assert!(!contains(&client_hello, b"\x02h2")); + } + + #[tokio::test] + async fn fetch_retries_transient_statuses_and_network_errors() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = fast_client_for(&listener); + let ok_body = exact(vec![cbor_value(vec![ + ("value", ciborium::Value::Bytes(b"v".to_vec())), + ("blob_id", ciborium::Value::Null), + ])]); + let server = std::thread::spawn(move || { + // Attempt 1: 503 with Retry-After: 60 (must not stall or fail). + serve_raw_once( + &listener, + b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 39\r\n\r\nService unavailable (concurrency_limit)", + ); + // Attempt 2: connection dropped mid-response (network error). + serve_raw_once(&listener, b"HTTP/1.1 200 OK\r\ncontent-length: 100\r\n\r\n"); + // Attempt 3: succeeds. + serve_once(&listener, "HTTP/1.1 200 OK", &ok_body); + }); + + let start = Instant::now(); + assert_eq!( + client.fetch(b"k", b"s").await.unwrap(), + Some(Fetched::Exact { entries: vec![Entry { value: b"v".to_vec(), blob_id: None }] }) + ); + assert!(start.elapsed() < Duration::from_secs(5), "503 Retry-After: 60 should be ignored"); + server.join().unwrap(); + } + + #[tokio::test] + async fn download_retries_transient_error_before_headers() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = fast_client_for(&listener); + let server = std::thread::spawn(move || { + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"busy"); + serve_once(&listener, "HTTP/1.1 200 OK", b"archive bytes"); + }); + + let download = client.download("7").await.unwrap(); + assert_eq!(read_to_end(download).await.unwrap(), b"archive bytes"); + server.join().unwrap(); + } + + #[tokio::test] + async fn store_retries_transient_errors_and_resends_blob() { + let dir = tempfile::tempdir().unwrap(); + let blob = AbsolutePathBuf::new(dir.path().join("archive.tar.zst")).unwrap(); + std::fs::write(blob.as_path(), b"archive bytes").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = fast_client_for(&listener); + let server = std::thread::spawn(move || { + let first = serve_raw_once( + &listener, + b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + // Drop connection before sending headers on attempt 2. + { + let (stream, _) = listener.accept().unwrap(); + drop(stream); + } + let third = serve_once(&listener, "HTTP/1.1 200 OK", b""); + (first, third) + }); + + client.store(b"k", b"s", b"v", Some(&blob)).await.unwrap(); + let (first, third) = server.join().unwrap(); + let blob_part = + b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; + assert!(contains(&first, blob_part)); + assert!(contains(&third, blob_part)); + } + + #[tokio::test] + async fn non_retryable_statuses_fail_without_retrying() { + for status_line in [ + "HTTP/1.1 400 Bad Request", + "HTTP/1.1 401 Unauthorized", + "HTTP/1.1 403 Forbidden", + "HTTP/1.1 413 Payload Too Large", + "HTTP/1.1 501 Not Implemented", + ] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = fast_client_for(&listener); + let server = { + let listener = listener.try_clone().unwrap(); + std::thread::spawn(move || serve_once(&listener, status_line, b"nope")) + }; + + let error = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(error, Error::Status(_, _)), "{status_line}: {error:?}"); + server.join().unwrap(); + assert!(no_request_waiting(&listener), "{status_line} should not retry"); + } + } + + #[tokio::test] + async fn download_once_does_not_retry() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = fast_client_for(&listener); + let server = { + let listener = listener.try_clone().unwrap(); + std::thread::spawn(move || { + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"busy") + }) + }; + + let error = client.download_once("7").await.unwrap_err(); + assert!(matches!(error, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{error:?}"); + server.join().unwrap(); + assert!(no_request_waiting(&listener)); + } + + #[tokio::test] + async fn rate_limit_429_respects_retry_after() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let cooldown = Duration::from_millis(80); + let retry = RetryConfig { + read: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.read }, + store: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + let client = client_with_retry(&listener, Arc::new(Anonymous), retry); + let server = std::thread::spawn(move || { + // `Retry-After: 5` is clamped to `cooldown` (80 ms). + serve_raw_once( + &listener, + b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + serve_once(&listener, "HTTP/1.1 200 OK", b""); + }); + + let start = Instant::now(); + client.store(b"k", b"s", b"v", None).await.unwrap(); + assert!( + start.elapsed() >= Duration::from_millis(60), + "429 Retry-After cooldown was not respected: {:?}", + start.elapsed() + ); + server.join().unwrap(); + } + + #[tokio::test] + async fn rate_limit_429_pauses_same_kind_peers_without_stalling_reads() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let cooldown = Duration::from_millis(80); + let retry = RetryConfig { + // Single attempt so the first store returns 429 immediately after + // publishing the store cooldown; a read runs right away while a + // peer store waits for the cooldown. + read: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.read }, + store: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + let client = client_with_retry(&listener, Arc::new(Anonymous), retry); + let server = std::thread::spawn(move || { + serve_raw_once( + &listener, + b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + serve_once(&listener, "HTTP/1.1 200 OK", b""); + }); + + let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(err, Error::Status(StatusCode::TOO_MANY_REQUESTS, _)), "{err:?}"); + + let fetch_start = Instant::now(); + assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); + assert!( + fetch_start.elapsed() < Duration::from_millis(50), + "store 429 should not stall fetch: {:?}", + fetch_start.elapsed() + ); + + let store_start = Instant::now(); + client.store(b"k", b"s", b"v", None).await.unwrap(); + assert!( + store_start.elapsed() >= Duration::from_millis(40), + "peer store did not wait for shared 429 cooldown: {:?}", + store_start.elapsed() + ); + server.join().unwrap(); + } + + #[tokio::test] + async fn outage_breaker_short_circuits_after_repeated_failures() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let retry = RetryConfig { + outage_threshold: 2, + outage_cooldown: Duration::from_secs(30), + ..NO_RETRY + }; + let client = client_with_retry(&listener, Arc::new(Anonymous), retry); + let server = { + let listener = listener.try_clone().unwrap(); + std::thread::spawn(move || { + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + }) + }; + + for _ in 0..2 { + let err = client.fetch(b"k", b"s").await.unwrap_err(); + assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); + } + server.join().unwrap(); + + // Third request short-circuits locally without hitting the server. + let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(err, Error::Unavailable), "{err:?}"); + assert_eq!(err.to_string(), "remote cache temporarily unavailable"); + assert!(no_request_waiting(&listener)); + } + + #[tokio::test] + async fn concurrent_stores_are_capped_at_max_concurrent_stores() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = Arc::new(fast_client_for(&listener)); + let total_stores = MAX_CONCURRENT_STORES * 2; + let in_flight = Arc::new(AtomicUsize::new(0)); + let max_in_flight = Arc::new(AtomicUsize::new(0)); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (filled_tx, filled_rx) = std::sync::mpsc::channel::<()>(); + + let server = { + let in_flight = Arc::clone(&in_flight); + let max_in_flight = Arc::clone(&max_in_flight); + std::thread::spawn(move || { + let mut handlers = Vec::with_capacity(total_stores); + for _ in 0..total_stores { + let (mut stream, _) = listener.accept().unwrap(); + let in_flight = Arc::clone(&in_flight); + let max_in_flight = Arc::clone(&max_in_flight); + let release_rx = Arc::clone(&release_rx); + let filled_tx = filled_tx.clone(); + handlers.push(std::thread::spawn(move || { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let header_end = loop { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&buf[..n]); + if let Some(pos) = + request.windows(4).position(|window| window == b"\r\n\r\n") + { + break pos + 4; + } + }; + let content_length: usize = std::str::from_utf8(&request[..header_end]) + .unwrap() + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&buf[..n]); + } + let current = in_flight.fetch_add(1, Ordering::SeqCst) + 1; + max_in_flight.fetch_max(current, Ordering::SeqCst); + if current == MAX_CONCURRENT_STORES { + let _ = filled_tx.send(()); + } + let _ = release_rx.lock().unwrap().recv(); + in_flight.fetch_sub(1, Ordering::SeqCst); + stream + .write_all(b"HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n") + .unwrap(); + })); + } + for handler in handlers { + handler.join().unwrap(); + } + }) + }; + + let mut tasks = Vec::with_capacity(total_stores); + for _ in 0..total_stores { + let client = Arc::clone(&client); + tasks.push(tokio::spawn(async move { client.store(b"k", b"s", b"v", None).await })); + } + + // Wait until all `MAX_CONCURRENT_STORES` slots are occupied, then release + // every request one by one. + tokio::task::spawn_blocking(move || { + filled_rx.recv().unwrap(); + for _ in 0..total_stores { + release_tx.send(()).unwrap(); + } + }) + .await + .unwrap(); + + for task in tasks { + task.await.unwrap().unwrap(); + } + server.join().unwrap(); + assert_eq!(max_in_flight.load(Ordering::SeqCst), MAX_CONCURRENT_STORES); } #[tokio::test] async fn network_errors_leave_out_the_url() { let endpoint = "http://user:password@127.0.0.1:0/projects/test?token=secret"; - let client = Client::new(endpoint, Arc::new(Anonymous)).unwrap(); + let client = Client::with_retry(endpoint, Arc::new(Anonymous), NO_RETRY).unwrap(); let error = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(error, Error::Network(_)), "{error:?}"); diff --git a/crates/vt_remote_cache/src/retry.rs b/crates/vt_remote_cache/src/retry.rs new file mode 100644 index 000000000..da9508e99 --- /dev/null +++ b/crates/vt_remote_cache/src/retry.rs @@ -0,0 +1,555 @@ +//! Retry policy, jittered exponential backoff, shared `429` cooldown +//! coordination, and a per-client outage circuit breaker for remote cache +//! requests. + +use std::{ + sync::{Mutex, PoisonError}, + time::Duration, +}; + +use reqwest::{ + StatusCode, + header::{HeaderMap, RETRY_AFTER}, +}; +use tokio::time::Instant; + +use crate::Error; + +/// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response. +pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(10); + +/// Maximum extra jitter added when waking from a shared `429` cooldown so +/// concurrent waiters do not fire in lockstep. +const MAX_COOLDOWN_JITTER: Duration = Duration::from_millis(250); + +/// Consecutive exhausted outage failures before the circuit breaker opens. +const OUTAGE_FAILURE_THRESHOLD: u32 = 3; + +/// How long the circuit breaker stays open before permitting one probe request. +const OUTAGE_COOLDOWN: Duration = Duration::from_secs(30); + +/// Retry parameters for one kind of remote cache operation. +#[derive(Debug, Clone, Copy)] +pub struct RetryPolicy { + /// Number of retries after the initial attempt (`0` means one attempt total). + pub max_retries: u32, + /// Nominal backoff before the first retry; doubles on each subsequent retry. + pub base_delay: Duration, + /// Upper bound on computed exponential backoff. + pub max_delay: Duration, + /// Upper bound on `Retry-After` delays honored for `429` responses. + pub max_retry_after: Duration, + /// Total elapsed time budget for starting retries within one operation. + /// Does not abort an already in-flight HTTP attempt; prevents slow + /// timeouts or 30 s server waits from multiplying into multi-minute stalls. + pub max_elapsed: Duration, +} + +impl RetryPolicy { + /// Retry policy for `POST /fetch` and `GET /blob/{id}` reads: up to 2 + /// retries (3 attempts total) with nominal delays of 250 ms and 500 ms + /// (jittered), bounded by a 15 s retry-start budget so a dead endpoint + /// falls back quickly. + pub const READ: Self = Self { + max_retries: 2, + base_delay: Duration::from_millis(250), + max_delay: Duration::from_secs(5), + max_retry_after: MAX_RETRY_AFTER, + max_elapsed: Duration::from_secs(15), + }; + /// Retry policy for `POST /store` uploads: up to 3 retries (4 attempts + /// total) with nominal delays of 500 ms, 1 s, and 2 s (jittered), bounded + /// by a 60 s retry-start budget. + pub const STORE: Self = Self { + max_retries: 3, + base_delay: Duration::from_millis(500), + max_delay: Duration::from_secs(10), + max_retry_after: MAX_RETRY_AFTER, + max_elapsed: Duration::from_secs(60), + }; + + /// Single-attempt policy with no retries, preserving `max_retry_after` for + /// recording `429` cooldowns. + pub const fn once(self) -> Self { + Self { max_retries: 0, ..self } + } + + /// Backoff delay for zero-based `attempt`, with `[0.5x, 1.0x]` equal jitter. + fn delay(self, attempt: u32) -> Duration { + let multiplier = 1_u32.checked_shl(attempt).unwrap_or(u32::MAX); + let nominal = self.base_delay.saturating_mul(multiplier).min(self.max_delay); + equal_jitter(nominal) + } +} + +/// Retry and circuit-breaker configuration shared across a [`crate::Client`]. +#[derive(Debug, Clone, Copy)] +pub struct RetryConfig { + pub read: RetryPolicy, + pub store: RetryPolicy, + pub outage_threshold: u32, + pub outage_cooldown: Duration, +} + +impl RetryConfig { + pub const DEFAULT: Self = Self { + read: RetryPolicy::READ, + store: RetryPolicy::STORE, + outage_threshold: OUTAGE_FAILURE_THRESHOLD, + outage_cooldown: OUTAGE_COOLDOWN, + }; +} + +/// Shared cooldown gate for `429 Too Many Requests` responses. +/// +/// Only `429` updates this gate; `5xx` responses (including `503`, which some +/// backends send with a coarse `Retry-After: 60` on transient admission errors) +/// use per-request backoff instead so one `503` does not stall sibling requests. +#[derive(Debug, Default)] +pub struct RateLimit { + until: Mutex>, +} + +impl RateLimit { + /// Wait until any active `429` cooldown has elapsed, with a small random + /// wake-up spread so concurrent waiters do not resume in lockstep. + pub async fn wait(&self) { + let mut waited = false; + let mut last_remaining = Duration::ZERO; + loop { + let until = *self.until.lock().unwrap_or_else(PoisonError::into_inner); + let Some(until) = until else { + break; + }; + let now = Instant::now(); + if until <= now { + break; + } + let remaining = until.saturating_duration_since(now); + waited = true; + last_remaining = remaining; + sleep(remaining).await; + } + if waited { + let spread = (last_remaining / 4).min(MAX_COOLDOWN_JITTER); + sleep(random_up_to(spread)).await; + } + } + + /// Extend the shared cooldown to at least `now + delay`. Concurrent `429`s + /// never shorten an existing cooldown. + pub fn record(&self, delay: Duration) { + if delay.is_zero() { + return; + } + let target = Instant::now() + delay; + let mut until = self.until.lock().unwrap_or_else(PoisonError::into_inner); + *until = Some(until.map_or(target, |previous| previous.max(target))); + } +} + +/// Per-client circuit breaker for sustained endpoint outages. +/// +/// Opens after `threshold` consecutive exhausted outage failures (network +/// errors or retryable `5xx` responses, excluding `429`), fast-failing later +/// requests with [`Error::Unavailable`] for `cooldown`. Once `cooldown` +/// elapses, a single half-open probe request is permitted; if it succeeds, +/// normal requests resume, and if it fails or is cancelled, another cooldown +/// starts. +#[derive(Debug)] +pub struct OutageBreaker { + threshold: u32, + cooldown: Duration, + state: Mutex, +} + +#[derive(Debug, Default)] +struct OutageState { + failures: u32, + open_until: Option, + probing: bool, + generation: u64, +} + +impl OutageBreaker { + pub const fn new(threshold: u32, cooldown: Duration) -> Self { + Self { + threshold, + cooldown, + state: Mutex::new(OutageState { + failures: 0, + open_until: None, + probing: false, + generation: 0, + }), + } + } + + /// Try to enter the breaker. Returns `None` while the circuit is open or + /// another half-open probe is already in flight. + pub fn enter(&self) -> Option> { + if self.threshold == 0 { + return Some(OutagePermit { + breaker: self, + generation: 0, + probe: false, + completed: true, + }); + } + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let probe = if let Some(until) = state.open_until { + if Instant::now() < until || state.probing { + return None; + } + state.probing = true; + true + } else { + false + }; + let generation = state.generation; + drop(state); + Some(OutagePermit { breaker: self, generation, probe, completed: false }) + } +} + +/// Active lease on an [`OutageBreaker`]. Dropping an unfinished probe permit +/// (for example on Ctrl-C cancellation) releases the probe slot and starts +/// another cooldown so the circuit cannot get stuck. +pub struct OutagePermit<'a> { + breaker: &'a OutageBreaker, + generation: u64, + probe: bool, + completed: bool, +} + +impl OutagePermit<'_> { + pub const fn is_probe(&self) -> bool { + self.probe + } + + pub fn finish(mut self, result: Result<(), &Error>) { + if self.completed { + return; + } + let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); + if state.generation == self.generation { + let outage = result.err().is_some_and(is_outage_error); + if outage { + state.failures = state.failures.saturating_add(1); + if self.probe || state.failures >= self.breaker.threshold { + state.open_until = Some(Instant::now() + self.breaker.cooldown); + state.probing = false; + state.generation = state.generation.wrapping_add(1); + tracing::debug!( + failures = state.failures, + cooldown = ?self.breaker.cooldown, + "remote cache circuit opened after repeated failures" + ); + } + } else { + state.failures = 0; + if self.probe { + state.open_until = None; + state.probing = false; + state.generation = state.generation.wrapping_add(1); + tracing::debug!("remote cache circuit closed after probe succeeded"); + } + } + } + drop(state); + self.completed = true; + } +} + +impl Drop for OutagePermit<'_> { + fn drop(&mut self) { + if self.probe && !self.completed { + let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); + if state.generation == self.generation { + state.probing = false; + state.open_until = Some(Instant::now() + self.breaker.cooldown); + } + } + } +} + +/// Failure from a single attempt, carrying an optional `Retry-After` delay from +/// a `429` response. +pub struct AttemptError { + pub error: Error, + pub rate_limit_delay: Option, +} + +impl From for AttemptError { + fn from(error: Error) -> Self { + Self { error, rate_limit_delay: None } + } +} + +/// Whether `error` is transient and safe to retry for an idempotent remote +/// cache operation. +pub const fn is_retryable(error: &Error) -> bool { + match error { + Error::Network(_) => true, + Error::Status(status, _) => is_retryable_status(*status), + Error::InvalidEndpoint(_) + | Error::HttpClient(_) + | Error::ReadBlob(_) + | Error::Auth(_) + | Error::MalformedResponse(_) + | Error::Unavailable => false, + } +} + +/// Whether `error` counts toward tripping the outage circuit breaker. Excludes +/// `429` rate limits and non-retryable `4xx` / `501` / `505` / `511` errors. +const fn is_outage_error(error: &Error) -> bool { + match error { + Error::Network(_) => true, + Error::Status(status, _) => is_retryable_server_error(*status), + Error::InvalidEndpoint(_) + | Error::HttpClient(_) + | Error::ReadBlob(_) + | Error::Auth(_) + | Error::MalformedResponse(_) + | Error::Unavailable => false, + } +} + +const fn is_retryable_status(status: StatusCode) -> bool { + matches!(status.as_u16(), 408 | 429) || is_retryable_server_error(status) +} + +const fn is_retryable_server_error(status: StatusCode) -> bool { + matches!(status.as_u16(), 500 | 502..=504 | 506..=510 | 512..=599) +} + +/// Parse an integer delta-seconds `Retry-After` header, clamped to `max`. +/// Non-numeric values return `None` so callers fall back to exponential backoff. +pub fn parse_retry_after(headers: &HeaderMap, max: Duration) -> Option { + let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim(); + let seconds: u64 = value.parse().ok()?; + Some(Duration::from_secs(seconds).min(max)) +} + +/// Run `attempt_fn` through `outage`, `rate_limit`, and `policy`. +pub async fn run( + operation: &'static str, + policy: RetryPolicy, + rate_limit: &RateLimit, + outage: &OutageBreaker, + mut attempt_fn: F, +) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let Some(permit) = outage.enter() else { + tracing::debug!(operation, "skipping remote cache request while circuit is open"); + return Err(Error::Unavailable); + }; + // A half-open probe makes a single attempt so it either recovers or + // re-opens promptly instead of holding the only probe slot across retries. + let policy = if permit.is_probe() { policy.once() } else { policy }; + let started = Instant::now(); + let total_attempts = policy.max_retries.saturating_add(1); + let mut final_result = None; + for attempt in 0..total_attempts { + rate_limit.wait().await; + match attempt_fn().await { + Ok(value) => { + final_result = Some(Ok(value)); + break; + } + Err(AttemptError { error, rate_limit_delay }) => { + let is_rate_limited = + matches!(error, Error::Status(StatusCode::TOO_MANY_REQUESTS, _)); + let backoff = policy.delay(attempt); + // Floor 429 cooldowns at `backoff` so `Retry-After: 0` cannot + // trigger an immediate tight retry loop. + let cooldown = rate_limit_delay.map_or(backoff, |delay| delay.max(backoff)); + if is_rate_limited { + // Publish the cooldown even on the last attempt so concurrent + // requests pause instead of immediately hitting the same 429. + rate_limit.record(cooldown); + } + let next_wait = if is_rate_limited { cooldown } else { backoff }; + let budget_exhausted = + started.elapsed().saturating_add(next_wait) >= policy.max_elapsed; + if attempt + 1 >= total_attempts || !is_retryable(&error) || budget_exhausted { + final_result = Some(Err(error)); + break; + } + if is_rate_limited { + tracing::debug!( + operation, + attempt = attempt + 1, + total_attempts, + ?cooldown, + ?error, + "retrying remote cache request after 429 cooldown" + ); + } else { + tracing::debug!( + operation, + attempt = attempt + 1, + total_attempts, + delay = ?backoff, + ?error, + "retrying remote cache request" + ); + sleep(backoff).await; + } + } + } + } + let result = final_result.expect("total_attempts is always at least 1"); + permit.finish(result.as_ref().map(|_| ())); + result +} + +/// Apply `[0.5x, 1.0x]` equal jitter to `delay` to desynchronize concurrent +/// clients without collapsing backoff to zero. +fn equal_jitter(delay: Duration) -> Duration { + let Ok(millis) = u64::try_from(delay.as_millis()) else { + return delay; + }; + if millis <= 1 { + return delay; + } + let half = millis / 2; + let span = millis - half; + let offset = getrandom::u64().map_or(span, |random| random % (span + 1)); + Duration::from_millis(half + offset) +} + +/// Random duration uniformly sampled in `[0, max]`. +fn random_up_to(max: Duration) -> Duration { + let Ok(millis) = u64::try_from(max.as_millis()) else { + return max; + }; + if millis == 0 { + return Duration::ZERO; + } + let offset = getrandom::u64().map_or(millis, |random| random % (millis + 1)); + Duration::from_millis(offset) +} + +#[expect( + clippy::disallowed_methods, + reason = "intentional backoff delay between remote cache retry attempts" +)] +async fn sleep(duration: Duration) { + if !duration.is_zero() { + tokio::time::sleep(duration).await; + } +} + +#[cfg(test)] +mod tests { + use reqwest::header::HeaderValue; + + use super::*; + + #[test] + fn equal_jitter_stays_within_half_to_full_bounds() { + assert_eq!(equal_jitter(Duration::ZERO), Duration::ZERO); + assert_eq!(equal_jitter(Duration::from_millis(1)), Duration::from_millis(1)); + for base in [Duration::from_millis(250), Duration::from_millis(500), Duration::from_secs(2)] + { + for _ in 0..64 { + let jittered = equal_jitter(base); + assert!(jittered >= base / 2 && jittered <= base, "{jittered:?} not in half..full"); + } + } + } + + #[test] + fn retry_policy_delay_caps_and_avoids_shift_overflow() { + let policy = RetryPolicy::STORE; + for attempt in [0, 1, 2, 10, 64, 100, u32::MAX] { + let delay = policy.delay(attempt); + assert!(delay <= policy.max_delay, "attempt {attempt}: {delay:?}"); + } + let attempt0 = policy.delay(0); + assert!(attempt0 >= Duration::from_millis(250) && attempt0 <= Duration::from_millis(500)); + let attempt1 = policy.delay(1); + assert!(attempt1 >= Duration::from_millis(500) && attempt1 <= Duration::from_secs(1)); + } + + #[test] + fn parse_retry_after_handles_valid_clamped_and_invalid_values() { + let header = |value: &str| { + HeaderMap::from_iter([(RETRY_AFTER, HeaderValue::from_str(value).unwrap())]) + }; + let max = Duration::from_secs(10); + assert_eq!(parse_retry_after(&HeaderMap::new(), max), None); + assert_eq!(parse_retry_after(&header("0"), max), Some(Duration::ZERO)); + assert_eq!(parse_retry_after(&header(" 4 "), max), Some(Duration::from_secs(4))); + assert_eq!(parse_retry_after(&header("60"), max), Some(max)); + assert_eq!(parse_retry_after(&header("999999999999"), max), Some(max)); + assert_eq!(parse_retry_after(&header("-1"), max), None); + assert_eq!(parse_retry_after(&header("Wed, 21 Oct 2026 07:28:00 GMT"), max), None); + } + + #[test] + fn rate_limit_record_never_shortens_existing_cooldown() { + let rate_limit = RateLimit::default(); + rate_limit.record(Duration::from_secs(10)); + let first = rate_limit.until.lock().unwrap().unwrap(); + rate_limit.record(Duration::from_secs(1)); + let second = rate_limit.until.lock().unwrap().unwrap(); + assert_eq!(first, second); + } + + #[test] + fn retryable_status_excludes_non_transient_5xx() { + for retryable in [408, 429, 500, 502, 503, 504, 520, 524] { + let status = StatusCode::from_u16(retryable).unwrap(); + assert!(is_retryable_status(status), "{retryable} should be retryable"); + } + for non_retryable in [400, 401, 403, 404, 413, 501, 505, 511] { + let status = StatusCode::from_u16(non_retryable).unwrap(); + assert!(!is_retryable_status(status), "{non_retryable} should not be retryable"); + } + } + + #[test] + fn outage_breaker_opens_probes_recovers_and_handles_dropped_probes() { + let breaker = OutageBreaker::new(3, Duration::from_secs(30)); + let server_error = Error::Status(StatusCode::SERVICE_UNAVAILABLE, None); + let rate_limit_error = Error::Status(StatusCode::TOO_MANY_REQUESTS, None); + + // 429 does not count as an outage and resets consecutive failure count. + breaker.enter().unwrap().finish(Err(&server_error)); + breaker.enter().unwrap().finish(Err(&server_error)); + breaker.enter().unwrap().finish(Err(&rate_limit_error)); + assert!(breaker.enter().is_some()); + + // Three consecutive outage failures open the circuit. + for _ in 0..3 { + breaker.enter().unwrap().finish(Err(&server_error)); + } + assert!(breaker.enter().is_none()); + + // Expire cooldown: exactly one half-open probe is admitted. + breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + let dropped_probe = breaker.enter().unwrap(); + assert!(dropped_probe.is_probe()); + assert!(breaker.enter().is_none()); + // Dropping an unfinished probe re-opens the circuit instead of leaking the slot. + drop(dropped_probe); + assert!(breaker.enter().is_none()); + + // Failed probe re-opens the circuit. + breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + breaker.enter().unwrap().finish(Err(&server_error)); + assert!(breaker.enter().is_none()); + + // Successful probe closes the circuit. + breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + breaker.enter().unwrap().finish(Ok(())); + assert!(breaker.enter().is_some()); + assert!(breaker.enter().is_some()); + } +} From b921c4e1d990c440a97fd02960f4cc09a6a6ea48 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 19:43:13 +0800 Subject: [PATCH 2/9] fix(cache): separate read and store outage circuit breakers Co-authored-by: Gemini 4 Neon --- crates/vt_remote_cache/README.md | 2 +- crates/vt_remote_cache/src/lib.rs | 127 ++++++++++++++++++------------ 2 files changed, 78 insertions(+), 51 deletions(-) diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index 020121017..fbc04c47b 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -14,7 +14,7 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta `Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. At most `MAX_CONCURRENT_STORES` (4) stores run concurrently per client. -Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Transient network errors and retryable HTTP statuses (`408`, `429`, and `5xx` other than `501`, `505`, and `511`) are retried with jittered exponential backoff (up to 3 retries within a 60-second retry budget for stores, and up to 2 retries within a 15-second retry budget for fetches and downloads). On `429 Too Many Requests`, concurrent requests of the same kind (reads or stores) on that client share a cooldown using the response's integer `Retry-After` header (clamped to 10 seconds, floored at the attempt's backoff); `5xx` responses use per-request backoff only. After 3 consecutive exhausted outage failures (network errors or retryable `5xx`), a per-client circuit breaker short-circuits requests with `Error::Unavailable` for 30 seconds before probing with one request. +Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Transient network errors and retryable HTTP statuses (`408`, `429`, and `5xx` other than `501`, `505`, and `511`) are retried with jittered exponential backoff (up to 3 retries within a 60-second retry budget for stores, and up to 2 retries within a 15-second retry budget for fetches and downloads). On `429 Too Many Requests`, concurrent requests of the same kind (reads or stores) on that client share a cooldown using the response's integer `Retry-After` header (clamped to 10 seconds, floored at the attempt's backoff); `5xx` responses use per-request backoff only. After 3 consecutive exhausted outage failures (network errors or retryable `5xx`), a circuit breaker for that kind of operation (reads or stores) short-circuits requests with `Error::Unavailable` for 30 seconds before probing with one request. reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 20-second per-attempt timeout. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index 5820c0ad8..f966aa588 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -182,8 +182,14 @@ pub struct Client { read_rate_limit: RateLimit, /// Shared cooldown for `429 Too Many Requests` on store operations. store_rate_limit: RateLimit, - /// Circuit breaker that short-circuits requests during sustained outages. - outage: OutageBreaker, + /// Circuit breaker that short-circuits read requests (fetch and download) + /// during sustained outages. Kept separate from stores so store failures + /// do not block the task-critical read path. + read_outage: OutageBreaker, + /// Circuit breaker that short-circuits store requests during sustained + /// outages. Kept separate from reads so successful reads cannot reset + /// consecutive store failures. + store_outage: OutageBreaker, retry: RetryConfig, } @@ -232,7 +238,8 @@ impl Client { store_permits: Semaphore::new(MAX_CONCURRENT_STORES), read_rate_limit: RateLimit::default(), store_rate_limit: RateLimit::default(), - outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), + read_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), + store_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), retry, }) } @@ -256,7 +263,7 @@ impl Client { pub async fn fetch(&self, key: &[u8], secondary_key: &[u8]) -> Result, Error> { let body = Bytes::from(encode_cbor(&FetchRequest { key, secondary_key })); let policy = self.retry.read; - let result = retry::run("fetch", policy, &self.read_rate_limit, &self.outage, || { + let result = retry::run("fetch", policy, &self.read_rate_limit, &self.read_outage, || { let body = body.clone(); async move { let start = Instant::now(); @@ -331,7 +338,7 @@ impl Client { ) -> Result { let mut url = self.blob_url.clone(); url.path_segments_mut().map_err(|()| Error::InvalidEndpoint(None))?.push(blob_id); - retry::run("download", policy, &self.read_rate_limit, &self.outage, || { + retry::run("download", policy, &self.read_rate_limit, &self.read_outage, || { let url = url.clone(); async move { let start = Instant::now(); @@ -372,47 +379,48 @@ impl Client { let metadata_bytes = Bytes::from(encode_cbor(&StoreMetadata { key, secondary_key, value })); let value_bytes = value.len(); let policy = self.retry.store; - let result = retry::run("store", policy, &self.store_rate_limit, &self.outage, || { - let metadata_bytes = metadata_bytes.clone(); - async move { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Store).await?; - let auth = start.elapsed(); - let mut form = Form::new().part("metadata", metadata_part(metadata_bytes)); - let blob_bytes = if let Some(blob) = blob { - let (part, length) = blob_part(blob).await?; - form = form.part("blob", part); - Some(length) - } else { - None - }; - tracing::debug!( - value_bytes, - blob_bytes, - ?queued, - ?auth, - "sending a remote cache store" - ); - let response = self - .http - .post(self.store_url.clone()) - .headers(headers) - .multipart(form) - .send() - .await - .map_err(network_error)?; - log_response(&response, start); - // The response's blob ID isn't needed. Read the body anyway, so the - // connection can be reused. - check_status(response, policy.max_retry_after) - .await? - .bytes() - .await - .map_err(network_error)?; - Ok(()) - } - }) - .await; + let result = + retry::run("store", policy, &self.store_rate_limit, &self.store_outage, || { + let metadata_bytes = metadata_bytes.clone(); + async move { + let start = Instant::now(); + let headers = self.auth_headers(Operation::Store).await?; + let auth = start.elapsed(); + let mut form = Form::new().part("metadata", metadata_part(metadata_bytes)); + let blob_bytes = if let Some(blob) = blob { + let (part, length) = blob_part(blob).await?; + form = form.part("blob", part); + Some(length) + } else { + None + }; + tracing::debug!( + value_bytes, + blob_bytes, + ?queued, + ?auth, + "sending a remote cache store" + ); + let response = self + .http + .post(self.store_url.clone()) + .headers(headers) + .multipart(form) + .send() + .await + .map_err(network_error)?; + log_response(&response, start); + // The response's blob ID isn't needed. Read the body anyway, so the + // connection can be reused. + check_status(response, policy.max_retry_after) + .await? + .bytes() + .await + .map_err(network_error)?; + Ok(()) + } + }) + .await; drop(permit); result } @@ -1167,7 +1175,7 @@ mod tests { } #[tokio::test] - async fn outage_breaker_short_circuits_after_repeated_failures() { + async fn outage_breaker_short_circuits_per_kind_independently() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let retry = RetryConfig { outage_threshold: 2, @@ -1178,21 +1186,40 @@ mod tests { let server = { let listener = listener.try_clone().unwrap(); std::thread::spawn(move || { + // Store #1 fails, interleaved fetch succeeds (must not reset store failures), + // store #2 fails (opens store breaker), fetch still works, + // then two fetch failures open read breaker. + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); }) }; + let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); + // A successful fetch must not reset consecutive store failures. + assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); + let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); + + // Store breaker is now open, but reads still reach the server. + assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); + let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + assert!(matches!(err, Error::Unavailable), "{err:?}"); + assert_eq!(err.to_string(), "remote cache temporarily unavailable"); + + // Two consecutive fetch failures open the read breaker as well. for _ in 0..2 { let err = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); } server.join().unwrap(); - // Third request short-circuits locally without hitting the server. - let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); + let err = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(err, Error::Unavailable), "{err:?}"); - assert_eq!(err.to_string(), "remote cache temporarily unavailable"); assert!(no_request_waiting(&listener)); } From 7dbc3e9e35753b96c4dd17f3b509f856a0955392 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:04:16 +0800 Subject: [PATCH 3/9] refactor(cache): move remote cache retry, circuit breaker, and store cap to vt Keep vt_remote_cache a single-attempt HTTP/1.1 protocol client that surfaces retry hints on Error, and own retry, 429 cooldowns, per-kind outage circuit breakers, upload concurrency capping, and unified header+stream download retries in vt::session::cache::remote. Co-authored-by: Gemini 4 Neon --- Cargo.lock | 2 +- crates/vt/Cargo.toml | 2 + crates/vt/src/session/cache/remote.rs | 809 ++++++++++++++--- .../src/session/cache/remote}/retry.rs | 262 +++--- crates/vt_remote_cache/Cargo.toml | 3 +- crates/vt_remote_cache/README.md | 4 +- crates/vt_remote_cache/src/lib.rs | 834 +++++------------- 7 files changed, 1069 insertions(+), 847 deletions(-) rename crates/{vt_remote_cache/src => vt/src/session/cache/remote}/retry.rs (72%) diff --git a/Cargo.lock b/Cargo.lock index f1c07adcf..ec8175b57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4988,6 +4988,7 @@ dependencies = [ "derive_more", "fspy", "futures-util", + "getrandom 0.4.2", "nix 0.31.2", "once_cell", "owo-colors", @@ -5315,7 +5316,6 @@ dependencies = [ "base64 0.22.1", "bytes", "ciborium", - "getrandom 0.4.2", "reqwest", "rustls", "serde", diff --git a/crates/vt/Cargo.toml b/crates/vt/Cargo.toml index 271cda206..ef0eed828 100644 --- a/crates/vt/Cargo.toml +++ b/crates/vt/Cargo.toml @@ -22,6 +22,7 @@ clap = { workspace = true, features = ["derive"] } ctrlc = { workspace = true } derive_more = { workspace = true, features = ["debug", "from"] } futures-util = { workspace = true } +getrandom = { workspace = true } once_cell = { workspace = true } owo-colors = { workspace = true, features = ["supports-colors"] } petgraph = { workspace = true } @@ -41,6 +42,7 @@ tokio = { workspace = true, features = [ "macros", "process", "sync", + "time", ] } tokio-util = { workspace = true, features = ["rt"] } tracing = { workspace = true } diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index 58addfe32..a8e69980b 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -13,16 +13,18 @@ //! remote value format, and the target OS and architecture. Platforms share an //! endpoint's namespace, but their keys differ. +mod retry; + use std::{ fs::File, io::{self, Read as _, Write as _}, sync::{Arc, Mutex, OnceLock, PoisonError}, - time::Instant, + time::{Duration, Instant}, }; use bytes::Bytes; use rustc_hash::FxHashMap; -use tokio::sync::mpsc; +use tokio::sync::{Semaphore, mpsc}; use tokio_util::{sync::CancellationToken, task::TaskTracker}; use tracing::Instrument as _; use vt_path::AbsolutePath; @@ -40,11 +42,19 @@ use wincode::{ error::{WriteError, WriteResult}, }; +use self::retry::{OutageBreaker, RateLimit, RetryConfig, RetryableError}; use super::{ BaselineDetails, CACHE_SCHEMA_VERSION, CacheEntryKey, CacheEntryValue, CacheMiss, Checked, Comparison, TaskCacheConfig, archive, deserialize_cache, serialize_cache, }; +/// Maximum number of concurrent remote cache uploads in flight per endpoint. +/// +/// Bounding uploads per endpoint shapes bursts against backends with +/// per-isolate admission limits, prevents uplink thrashing, and caps open +/// archive file handles. +const MAX_CONCURRENT_STORES: usize = 4; + /// Why an entry wasn't uploaded. #[derive(Debug, thiserror::Error)] pub enum UploadError { @@ -60,6 +70,43 @@ pub enum UploadError { /// Ctrl-C cancelled the upload before it finished. #[error("interrupted")] Interrupted, + /// The remote cache endpoint recently failed repeatedly, so this upload + /// was skipped during the outage cooldown window. + #[error("remote cache temporarily unavailable")] + Unavailable, +} + +impl RetryableError for UploadError { + fn is_retryable(&self) -> bool { + matches!(self, Self::Remote(err) if err.is_retryable()) + } + + fn is_outage(&self) -> bool { + matches!(self, Self::Remote(err) if err.is_outage()) + } + + fn is_rate_limited(&self) -> bool { + matches!(self, Self::Remote(err) if err.is_rate_limited()) + } + + fn is_cancelled(&self) -> bool { + matches!(self, Self::Interrupted) + } + + fn retry_after(&self) -> Option { + match self { + Self::Remote(err) => err.retry_after(), + Self::Encode(_) + | Self::Compress(_) + | Self::TooLarge + | Self::Interrupted + | Self::Unavailable => None, + } + } + + fn unavailable() -> Self { + Self::Unavailable + } } /// Why no entry could be read from the remote cache. It's a cache miss, and @@ -91,6 +138,47 @@ pub enum ReadError { /// finished. The task doesn't start then, so this miss isn't reported. #[error("cancelled")] Cancelled, + /// The remote cache endpoint recently failed repeatedly, so this read was + /// skipped during the outage cooldown window. + #[error("remote cache temporarily unavailable")] + Unavailable, +} + +impl RetryableError for ReadError { + fn is_retryable(&self) -> bool { + matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_retryable()) + } + + fn is_outage(&self) -> bool { + matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_outage()) + } + + fn is_rate_limited(&self) -> bool { + matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_rate_limited()) + } + + fn is_cancelled(&self) -> bool { + matches!(self, Self::Cancelled) + } + + fn retry_after(&self) -> Option { + match self { + Self::Fetch(err) | Self::Download(err) => err.retry_after(), + Self::CorruptValue(_) + | Self::CorruptKey(_) + | Self::MismatchedBlob + | Self::CorruptArchive(_) + | Self::WriteArchive(_) + | Self::Validate(_) + | Self::Encode(_) + | Self::Cancelled + | Self::Unavailable => None, + } + } + + fn unavailable() -> Self { + Self::Unavailable + } } impl ReadError { @@ -195,28 +283,146 @@ struct ClientKey { auth: RemoteCacheAuth, } +/// Per-endpoint client and session resilience state (upload concurrency cap, +/// `429` cooldown gates, and read/store outage circuit breakers). +#[derive(Debug)] +struct RemoteEndpoint { + client: Client, + /// Bounds concurrent uploads in flight for this endpoint. + store_permits: Semaphore, + /// Shared cooldown for `429 Too Many Requests` on read operations so + /// upload rate limits do not stall fetches on the task critical path. + read_rate_limit: RateLimit, + /// Shared cooldown for `429 Too Many Requests` on store operations. + store_rate_limit: RateLimit, + /// Circuit breaker that short-circuits read requests (fetch and download) + /// during sustained outages. Kept separate from stores so store failures + /// do not block the task-critical read path. + read_outage: OutageBreaker, + /// Circuit breaker that short-circuits store requests during sustained + /// outages. Kept separate from reads so successful reads cannot reset + /// consecutive store failures. + store_outage: OutageBreaker, + retry: RetryConfig, +} + +impl RemoteEndpoint { + fn new( + remote_config: &ResolvedRemoteCacheConfig, + retry: RetryConfig, + ) -> Result { + let client = Client::new(&remote_config.url, build_auth(&remote_config.auth))?; + Ok(Self { + client, + store_permits: Semaphore::new(MAX_CONCURRENT_STORES), + read_rate_limit: RateLimit::default(), + store_rate_limit: RateLimit::default(), + read_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), + store_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), + retry, + }) + } + + async fn fetch( + &self, + key: &[u8], + secondary_key: &[u8], + cancel_token: &CancellationToken, + ) -> Result, ReadError> { + cancel_token + .run_until_cancelled(retry::run( + "fetch", + self.retry.read, + &self.read_rate_limit, + &self.read_outage, + || async { self.client.fetch(key, secondary_key).await.map_err(ReadError::Fetch) }, + )) + .await + .ok_or(ReadError::Cancelled)? + } + + async fn download_checked( + &self, + blob_id: &str, + path: &AbsolutePath, + cancel_token: &CancellationToken, + ) -> Result<(), ReadError> { + cancel_token + .run_until_cancelled(retry::run( + "download", + self.retry.read, + &self.read_rate_limit, + &self.read_outage, + || download_once(&self.client, blob_id, path, cancel_token), + )) + .await + .ok_or(ReadError::Cancelled)? + } + + async fn store( + &self, + key: &[u8], + secondary_key: &[u8], + value: &[u8], + blob: Option<&AbsolutePath>, + ) -> Result<(), UploadError> { + let queue_start = Instant::now(); + let permit = self.store_permits.acquire().await.expect("store semaphore is never closed"); + let queued = queue_start.elapsed(); + if !queued.is_zero() { + tracing::debug!(?queued, "acquired remote cache upload slot"); + } + let result = retry::run( + "store", + self.retry.store, + &self.store_rate_limit, + &self.store_outage, + || async { + self.client + .store(key, secondary_key, value, blob) + .await + .map_err(UploadError::Remote) + }, + ) + .await; + drop(permit); + result + } +} + /// Remote cache clients, each created when its endpoint is first used with /// its auth. -#[derive(Debug, Default)] +#[derive(Debug)] pub struct RemoteClients { - clients: Mutex>>, + clients: Mutex>>, + retry: RetryConfig, +} + +impl Default for RemoteClients { + fn default() -> Self { + Self::with_retry(RetryConfig::DEFAULT) + } } impl RemoteClients { - fn client( + fn with_retry(retry: RetryConfig) -> Self { + Self { clients: Mutex::new(FxHashMap::default()), retry } + } + + fn endpoint( &self, remote_config: &ResolvedRemoteCacheConfig, - ) -> Result, vt_remote_cache::Error> { + ) -> Result, vt_remote_cache::Error> { let key = ClientKey { url: Arc::clone(&remote_config.url), auth: remote_config.auth.clone() }; let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner); - if let Some(client) = clients.get(&key) { - return Ok(Arc::clone(client)); + if let Some(endpoint) = clients.get(&key) { + return Ok(Arc::clone(endpoint)); } - let client = Arc::new(Client::new(&remote_config.url, build_auth(&remote_config.auth))?); - clients.insert(key, Arc::clone(&client)); + let endpoint = Arc::new(RemoteEndpoint::new(remote_config, self.retry)?); + clients.insert(key, Arc::clone(&endpoint)); drop(clients); - Ok(client) + Ok(endpoint) } /// Fetch the entries stored under `cache_key` in the remote cache that @@ -230,14 +436,10 @@ impl RemoteClients { execution_cache_key: &ExecutionCacheKey, cancel_token: &CancellationToken, ) -> Result, ReadError> { - let client = self.client(remote_config).map_err(ReadError::Fetch)?; + let endpoint = self.endpoint(remote_config).map_err(ReadError::Fetch)?; let key = encode_key(cache_key)?; let secondary_key = encode_key(execution_cache_key)?; - cancel_token - .run_until_cancelled(client.fetch(&key, &secondary_key)) - .await - .ok_or(ReadError::Cancelled)? - .map_err(ReadError::Fetch) + endpoint.fetch(&key, &secondary_key, cancel_token).await } /// Download the blob `blob_id` from the remote cache that `remote_config` @@ -253,12 +455,12 @@ impl RemoteClients { cancel_token: &CancellationToken, ) -> Result { let start = Instant::now(); - let client = self.client(remote_config).map_err(ReadError::Download)?; + let endpoint = self.endpoint(remote_config).map_err(ReadError::Download)?; let archive_name = vt_str::format!("{}.tar.zst", uuid::Uuid::new_v4()); let archive_path = cache_dir.join(archive_name.as_str()); let temp_path = cache_dir.join(vt_str::format!("{archive_name}.tmp").as_str()); let result = - download_checked(&client, blob_id, &temp_path, cancel_token).await.and_then(|()| { + endpoint.download_checked(blob_id, &temp_path, cancel_token).await.and_then(|()| { std::fs::rename(temp_path.as_path(), archive_path.as_path()) .map_err(ReadError::WriteArchive) }); @@ -290,7 +492,7 @@ impl RemoteClients { cache_dir: &AbsolutePath, ) -> Result> + Send + use<>, UploadError> { let start = Instant::now(); - let client = self.client(remote_config)?; + let endpoint = self.endpoint(remote_config)?; let key = encode_key(cache_key)?; let secondary_key = encode_key(execution_cache_key)?; let value = encode_value(cache_value)?; @@ -301,10 +503,7 @@ impl RemoteClients { elapsed = ?start.elapsed(), "prepared a remote cache upload" ); - Ok(async move { - client.store(&key, &secondary_key, &value, archive.as_deref()).await?; - Ok(()) - }) + Ok(async move { endpoint.store(&key, &secondary_key, &value, archive.as_deref()).await }) } } @@ -397,69 +596,49 @@ impl RemoteUploads { /// Chunks buffered between the download and the archive check. const CHECK_BUFFER_CHUNKS: usize = 16; -/// Download the blob `blob_id` to the file at `path`, until `cancel_token` is -/// cancelled. The chunks flow one way: from the network to the archive check -/// on a blocking thread, which writes each one to the file as it takes it. -/// If the stream drops mid-transfer with a network error, the download is -/// retried once from the start (with a single header attempt), overwriting the -/// partial `.tmp` file. -async fn download_checked( +/// Single attempt to download the blob `blob_id` to `path` while streaming it +/// through the archive check on a blocking thread, stopping if `cancel_token` +/// is cancelled. Always waits for the blocking check task to finish so the +/// file handle is closed before the caller removes it or retries. +async fn download_once( client: &Client, blob_id: &str, path: &AbsolutePath, cancel_token: &CancellationToken, ) -> Result<(), ReadError> { - const MAX_STREAM_ATTEMPTS: usize = 2; - - for attempt in 0..MAX_STREAM_ATTEMPTS { - let download_fut = async { - if attempt == 0 { - client.download(blob_id).await - } else { - client.download_once(blob_id).await - } - }; - let download = cancel_token - .run_until_cancelled(download_fut) - .await - .ok_or(ReadError::Cancelled)? - .map_err(ReadError::Download)?; - let file = File::create(path.as_path()).map_err(ReadError::WriteArchive)?; - let (sender, receiver) = mpsc::channel(CHECK_BUFFER_CHUNKS); - let check = tokio::task::spawn_blocking(move || { - let mut reader = - DownloadReader { receiver, chunk: Bytes::new(), file, write_error: None }; - let checked = archive::read_output_archive(&mut reader, |_| {}); - if let Some(err) = reader.write_error { - return Err(ReadError::WriteArchive(err)); - } - checked.map_err(ReadError::CorruptArchive) - }); - // Cancelling drops the sender, which ends the check. - let sent = cancel_token.run_until_cancelled(send_chunks(download, sender)).await; - // Wait for the check even after a network error or cancellation, so the - // file is closed before the caller removes it or retries. - let checked = check.await.unwrap_or_else(|err| Err(ReadError::CorruptArchive(err.into()))); - if cancel_token.is_cancelled() { - return Err(ReadError::Cancelled); + let download = cancel_token + .run_until_cancelled(client.download(blob_id)) + .await + .ok_or(ReadError::Cancelled)? + .map_err(ReadError::Download)?; + let file = File::create(path.as_path()).map_err(ReadError::WriteArchive)?; + let (sender, receiver) = mpsc::channel(CHECK_BUFFER_CHUNKS); + let check = tokio::task::spawn_blocking(move || { + let mut reader = DownloadReader { receiver, chunk: Bytes::new(), file, write_error: None }; + let checked = archive::read_output_archive(&mut reader, |_| {}); + if let Some(err) = reader.write_error { + return Err(ReadError::WriteArchive(err)); } - match sent.ok_or(ReadError::Cancelled)? { - Ok(()) => return checked, - Err(err @ vt_remote_cache::Error::Network(_)) if attempt + 1 < MAX_STREAM_ATTEMPTS => { - // Local disk write failures are not transient network drops. - if let Err(err @ ReadError::WriteArchive(_)) = checked { - return Err(err); - } - tracing::debug!( - ?err, - attempt = attempt + 1, - "retrying remote cache archive download after mid-stream network error" - ); + checked.map_err(ReadError::CorruptArchive) + }); + // Cancelling drops the sender, which ends the check. + let sent = cancel_token.run_until_cancelled(send_chunks(download, sender)).await; + // Wait for the check even after a network error or cancellation, so the + // file is closed before the caller removes it or retries. + let checked = check.await.unwrap_or_else(|err| Err(ReadError::CorruptArchive(err.into()))); + if cancel_token.is_cancelled() { + return Err(ReadError::Cancelled); + } + match sent.ok_or(ReadError::Cancelled)? { + Ok(()) => checked, + Err(err) => { + // Local disk write failures are not transient network drops. + if let Err(err @ ReadError::WriteArchive(_)) = checked { + return Err(err); } - Err(err) => return Err(ReadError::Download(err)), + Err(ReadError::Download(err)) } } - unreachable!("MAX_STREAM_ATTEMPTS is always at least 1") } /// Send the blob's chunks through `sender` until the blob ends or the receiver @@ -586,7 +765,12 @@ fn decode_key(bytes: &[u8]) -> Result { #[cfg(test)] mod tests { - use std::{collections::BTreeMap, net::TcpListener, time::Duration}; + use std::{ + collections::BTreeMap, + net::TcpListener, + sync::atomic::{AtomicUsize, Ordering}, + time::Duration, + }; use tokio::sync::oneshot; use vt_glob::path::PathGlobSet; @@ -597,7 +781,7 @@ mod tests { remote_cache::{GithubOidcAuth, RemoteCacheAccess, Secret}, }; - use super::*; + use super::{retry::RetryPolicy, *}; use crate::session::{ cache::{Change, FileCheck, InputChangeKind}, execute::{ @@ -606,6 +790,29 @@ mod tests { }, }; + /// Zero-delay retry config with production attempt counts so tests + /// exercise the full retry loop without sleeping. + const FAST_RETRY: RetryConfig = RetryConfig { + read: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + ..RetryPolicy::READ + }, + store: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + ..RetryPolicy::STORE + }, + ..RetryConfig::DEFAULT + }; + + /// Single-attempt retry config for tests that expect immediate failure. + const NO_RETRY: RetryConfig = RetryConfig { + read: RetryPolicy { max_retries: 0, ..FAST_RETRY.read }, + store: RetryPolicy { max_retries: 0, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + /// A key whose spawn fingerprint runs `vtt build`. `SpawnFingerprint`'s /// fields are private to `vt_plan`, so it's decoded from types with the /// same encoding. Update them if `SpawnFingerprint` changes. @@ -1124,7 +1331,7 @@ mod tests { }), ..unreachable.clone() }; - let clients = RemoteClients::default(); + let clients = RemoteClients::with_retry(NO_RETRY); let uploads = RemoteUploads::default(); for (remote_config, message) in [ @@ -1140,13 +1347,57 @@ mod tests { } } - #[tokio::test] - async fn mid_stream_download_network_error_is_retried() { - let dir = tempfile::tempdir().unwrap(); - let cache_dir = AbsolutePathBuf::new(dir.path().to_path_buf()).unwrap(); - // Build a valid `.tar.zst` archive with a real entry so a strict prefix - // is valid zstd up to EOF (preventing the archive check from failing - // ahead of the network truncation error). + /// Read one complete HTTP/1.1 request (head + `Content-Length` body) from + /// `listener`, write `raw_response`, and return the raw request bytes. + fn serve_raw_once(listener: &TcpListener, raw_response: &[u8]) -> Vec { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let header_end = loop { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0, "connection closed before the request head ended"); + request.extend_from_slice(&buf[..n]); + if let Some(pos) = request.windows(4).position(|window| window == b"\r\n\r\n") { + break pos + 4; + } + }; + let content_length: usize = std::str::from_utf8(&request[..header_end]) + .unwrap() + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0, "connection closed before the request body ended"); + request.extend_from_slice(&buf[..n]); + } + stream.write_all(raw_response).unwrap(); + request + } + + fn serve_once(listener: &TcpListener, status_line: &str, body: &[u8]) -> Vec { + let head = vt_str::format!( + "{status_line}\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", + body.len() + ); + serve_raw_once(listener, &[head.as_bytes(), body].concat()) + } + + fn no_request_waiting(listener: &TcpListener) -> bool { + listener.set_nonblocking(true).unwrap(); + let none = matches!(listener.accept(), Err(err) if err.kind() == io::ErrorKind::WouldBlock); + listener.set_nonblocking(false).unwrap(); + none + } + + fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack.windows(needle.len()).any(|window| window == needle) + } + + fn build_valid_archive() -> Vec { let payload = vec![b'x'; 4096]; let mut encoder = zstd::Encoder::new(Vec::new(), zstd::DEFAULT_COMPRESSION_LEVEL).unwrap(); { @@ -1158,16 +1409,55 @@ mod tests { tar.append_data(&mut header, "dist/out.txt", payload.as_slice()).unwrap(); tar.finish().unwrap(); } - let archive_bytes = encoder.finish().unwrap(); + encoder.finish().unwrap() + } + + #[tokio::test] + async fn fetch_retries_transient_statuses_and_network_errors() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let server = std::thread::spawn(move || { + // Attempt 1: 503 with Retry-After: 60 (must not stall or fail). + serve_raw_once( + &listener, + b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 39\r\n\r\nService unavailable (concurrency_limit)", + ); + // Attempt 2: connection dropped mid-response (network error). + serve_raw_once(&listener, b"HTTP/1.1 200 OK\r\ncontent-length: 100\r\n\r\n"); + // Attempt 3: 404 miss succeeds. + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + }); + + let key = cache_key(ResolvedGlobConfig::default_auto()); + let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); + let start = Instant::now(); + let fetched = RemoteClients::with_retry(FAST_RETRY) + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap(); + assert_eq!(fetched, None); + assert!(start.elapsed() < Duration::from_secs(5), "503 Retry-After: 60 should be ignored"); + server.join().unwrap(); + } + + #[tokio::test] + async fn download_retries_header_and_mid_stream_network_errors() { + let dir = tempfile::tempdir().unwrap(); + let cache_dir = AbsolutePathBuf::new(dir.path().to_path_buf()).unwrap(); + let archive_bytes = build_valid_archive(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let remote_config = anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); let server = std::thread::spawn(move || { let truncated_prefix = &archive_bytes[..archive_bytes.len() / 2]; - for response in [ - // Attempt 1: valid prefix truncated before announced Content-Length -> mid-stream network error. - [ + // Attempt 1: 503 before headers. + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"busy"); + // Attempt 2: valid prefix truncated before announced Content-Length -> mid-stream network error. + serve_raw_once( + &listener, + &[ vt_str::format!( "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", archive_bytes.len() @@ -1176,8 +1466,11 @@ mod tests { truncated_prefix, ] .concat(), - // Attempt 2: complete valid archive. - [ + ); + // Attempt 3: complete valid archive. + serve_raw_once( + &listener, + &[ vt_str::format!( "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", archive_bytes.len() @@ -1186,20 +1479,10 @@ mod tests { &archive_bytes, ] .concat(), - ] { - let (mut stream, _) = listener.accept().unwrap(); - let mut request = Vec::new(); - let mut buf = [0; 1024]; - while !request.windows(4).any(|window| window == b"\r\n\r\n") { - let n = stream.read(&mut buf).unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&buf[..n]); - } - stream.write_all(&response).unwrap(); - } + ); }); - let archive_name = RemoteClients::default() + let archive_name = RemoteClients::with_retry(FAST_RETRY) .download_archive(&remote_config, "1", &cache_dir, &CancellationToken::new()) .await .unwrap(); @@ -1207,18 +1490,328 @@ mod tests { server.join().unwrap(); } + #[tokio::test] + async fn store_retries_transient_errors_and_resends_blob() { + let dir = tempfile::tempdir().unwrap(); + let cache_dir = AbsolutePathBuf::new(dir.path().to_path_buf()).unwrap(); + std::fs::write(cache_dir.join("uploader.tar.zst").as_path(), b"archive bytes").unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let server = std::thread::spawn(move || { + let first = serve_raw_once( + &listener, + b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + // Drop connection before sending headers on attempt 2. + { + let (stream, _) = listener.accept().unwrap(); + drop(stream); + } + let third = serve_once(&listener, "HTTP/1.1 200 OK", b""); + (first, third) + }); + + let clients = RemoteClients::with_retry(FAST_RETRY); + let key = cache_key(ResolvedGlobConfig::default_auto()); + let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); + clients + .prepare_upload(&remote_config, &key, &execution_key, &cache_value(), &cache_dir) + .unwrap() + .await + .unwrap(); + let (first, third) = server.join().unwrap(); + let blob_part = + b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; + assert!(contains(&first, blob_part)); + assert!(contains(&third, blob_part)); + } + + #[tokio::test] + async fn non_retryable_statuses_fail_without_retrying() { + for status_line in [ + "HTTP/1.1 400 Bad Request", + "HTTP/1.1 401 Unauthorized", + "HTTP/1.1 403 Forbidden", + "HTTP/1.1 413 Payload Too Large", + "HTTP/1.1 501 Not Implemented", + ] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = anonymous(&vt_str::format!( + "http://{}/projects/test", + listener.local_addr().unwrap() + )); + let server = { + let listener = listener.try_clone().unwrap(); + std::thread::spawn(move || serve_once(&listener, status_line, b"nope")) + }; + + let clients = RemoteClients::with_retry(FAST_RETRY); + let error = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); + assert!(matches!(error, UploadError::Remote(_)), "{status_line}: {error:?}"); + server.join().unwrap(); + assert!(no_request_waiting(&listener), "{status_line} should not retry"); + } + } + + #[tokio::test] + async fn rate_limit_429_respects_retry_after() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let cooldown = Duration::from_millis(80); + let retry = RetryConfig { + read: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.read }, + store: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + let server = std::thread::spawn(move || { + // `Retry-After: 5` is clamped to `cooldown` (80 ms). + serve_raw_once( + &listener, + b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + serve_once(&listener, "HTTP/1.1 200 OK", b""); + }); + + let clients = RemoteClients::with_retry(retry); + let start = Instant::now(); + prepare_upload(&clients, &remote_config).unwrap().await.unwrap(); + assert!( + start.elapsed() >= Duration::from_millis(60), + "429 Retry-After cooldown was not respected: {:?}", + start.elapsed() + ); + server.join().unwrap(); + } + + #[tokio::test] + async fn rate_limit_429_pauses_same_kind_peers_without_stalling_reads() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let cooldown = Duration::from_millis(80); + let retry = RetryConfig { + read: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.read }, + store: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.store }, + ..FAST_RETRY + }; + let server = std::thread::spawn(move || { + serve_raw_once( + &listener, + b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", + ); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + serve_once(&listener, "HTTP/1.1 200 OK", b""); + }); + + let clients = RemoteClients::with_retry(retry); + let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); + assert!(matches!(err, UploadError::Remote(ref r) if r.is_rate_limited()), "{err:?}"); + + let key = cache_key(ResolvedGlobConfig::default_auto()); + let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); + let fetch_start = Instant::now(); + assert_eq!( + clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap(), + None + ); + assert!( + fetch_start.elapsed() < Duration::from_millis(50), + "store 429 should not stall fetch: {:?}", + fetch_start.elapsed() + ); + + let store_start = Instant::now(); + prepare_upload(&clients, &remote_config).unwrap().await.unwrap(); + assert!( + store_start.elapsed() >= Duration::from_millis(40), + "peer store did not wait for shared 429 cooldown: {:?}", + store_start.elapsed() + ); + server.join().unwrap(); + } + + #[tokio::test] + async fn outage_breaker_short_circuits_per_kind_independently() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let retry = RetryConfig { + outage_threshold: 2, + outage_cooldown: Duration::from_secs(30), + ..NO_RETRY + }; + let server = { + let listener = listener.try_clone().unwrap(); + std::thread::spawn(move || { + // Store #1 fails, interleaved fetch succeeds (must not reset store failures), + // store #2 fails (opens store breaker), fetch still works, + // then two fetch failures open read breaker. + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 404 Not Found", b""); + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); + }) + }; + + let clients = RemoteClients::with_retry(retry); + let key = cache_key(ResolvedGlobConfig::default_auto()); + let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); + + let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); + assert!(matches!(err, UploadError::Remote(ref r) if r.is_outage()), "{err:?}"); + // A successful fetch must not reset consecutive store failures. + assert_eq!( + clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap(), + None + ); + let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); + assert!(matches!(err, UploadError::Remote(ref r) if r.is_outage()), "{err:?}"); + + // Store breaker is now open, but reads still reach the server. + assert_eq!( + clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap(), + None + ); + let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); + assert!(matches!(err, UploadError::Unavailable), "{err:?}"); + assert_eq!(err.to_string(), "remote cache temporarily unavailable"); + + // Two consecutive fetch failures open the read breaker as well. + for _ in 0..2 { + let err = clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap_err(); + assert!(matches!(err, ReadError::Fetch(ref r) if r.is_outage()), "{err:?}"); + } + server.join().unwrap(); + + let err = clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap_err(); + assert!(matches!(err, ReadError::Unavailable), "{err:?}"); + assert_eq!(err.to_string(), "remote cache temporarily unavailable"); + assert!(no_request_waiting(&listener)); + } + + #[tokio::test] + async fn concurrent_stores_are_capped_at_max_concurrent_stores() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let remote_config = + anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); + let total_stores = MAX_CONCURRENT_STORES * 2; + let in_flight = Arc::new(AtomicUsize::new(0)); + let max_in_flight = Arc::new(AtomicUsize::new(0)); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let (filled_tx, filled_rx) = std::sync::mpsc::channel::<()>(); + + let server = { + let in_flight = Arc::clone(&in_flight); + let max_in_flight = Arc::clone(&max_in_flight); + std::thread::spawn(move || { + let mut handlers = Vec::with_capacity(total_stores); + for _ in 0..total_stores { + let (mut stream, _) = listener.accept().unwrap(); + let in_flight = Arc::clone(&in_flight); + let max_in_flight = Arc::clone(&max_in_flight); + let release_rx = Arc::clone(&release_rx); + let filled_tx = filled_tx.clone(); + handlers.push(std::thread::spawn(move || { + let mut request = Vec::new(); + let mut buf = [0; 4096]; + let header_end = loop { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&buf[..n]); + if let Some(pos) = + request.windows(4).position(|window| window == b"\r\n\r\n") + { + break pos + 4; + } + }; + let content_length: usize = std::str::from_utf8(&request[..header_end]) + .unwrap() + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let n = stream.read(&mut buf).unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&buf[..n]); + } + let current = in_flight.fetch_add(1, Ordering::SeqCst) + 1; + max_in_flight.fetch_max(current, Ordering::SeqCst); + if current == MAX_CONCURRENT_STORES { + let _ = filled_tx.send(()); + } + let _ = release_rx.lock().unwrap().recv(); + in_flight.fetch_sub(1, Ordering::SeqCst); + stream + .write_all(b"HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n") + .unwrap(); + })); + } + for handler in handlers { + handler.join().unwrap(); + } + }) + }; + + let clients = RemoteClients::with_retry(FAST_RETRY); + let mut tasks = Vec::with_capacity(total_stores); + for _ in 0..total_stores { + let upload = prepare_upload(&clients, &remote_config).unwrap(); + tasks.push(tokio::spawn(upload)); + } + + tokio::task::spawn_blocking(move || { + filled_rx.recv().unwrap(); + for _ in 0..total_stores { + release_tx.send(()).unwrap(); + } + }) + .await + .unwrap(); + + for task in tasks { + task.await.unwrap().unwrap(); + } + server.join().unwrap(); + assert_eq!(max_in_flight.load(Ordering::SeqCst), MAX_CONCURRENT_STORES); + } + #[tokio::test] async fn interrupting_the_wait_cancels_the_uploads() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let remote_config = anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); - let total = vt_remote_cache::MAX_CONCURRENT_STORES + 2; + let total = MAX_CONCURRENT_STORES + 2; let (all_slots_filled_tx, all_slots_filled_rx) = oneshot::channel(); std::thread::spawn(move || { // Hold open `MAX_CONCURRENT_STORES` requests while more uploads are // pending so cancelling interrupts both active and queued uploads. let mut streams = Vec::new(); - for _ in 0..vt_remote_cache::MAX_CONCURRENT_STORES { + for _ in 0..MAX_CONCURRENT_STORES { let Ok((mut stream, _)) = listener.accept() else { break }; let mut request = Vec::new(); let mut buf = [0; 1024]; diff --git a/crates/vt_remote_cache/src/retry.rs b/crates/vt/src/session/cache/remote/retry.rs similarity index 72% rename from crates/vt_remote_cache/src/retry.rs rename to crates/vt/src/session/cache/remote/retry.rs index da9508e99..1f563bf23 100644 --- a/crates/vt_remote_cache/src/retry.rs +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -1,22 +1,17 @@ //! Retry policy, jittered exponential backoff, shared `429` cooldown -//! coordination, and a per-client outage circuit breaker for remote cache +//! coordination, and per-kind outage circuit breakers for remote cache //! requests. use std::{ + fmt::Debug, sync::{Mutex, PoisonError}, time::Duration, }; -use reqwest::{ - StatusCode, - header::{HeaderMap, RETRY_AFTER}, -}; use tokio::time::Instant; -use crate::Error; - /// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response. -pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(10); +pub(super) const MAX_RETRY_AFTER: Duration = Duration::from_secs(10); /// Maximum extra jitter added when waking from a shared `429` cooldown so /// concurrent waiters do not fire in lockstep. @@ -28,9 +23,28 @@ const OUTAGE_FAILURE_THRESHOLD: u32 = 3; /// How long the circuit breaker stays open before permitting one probe request. const OUTAGE_COOLDOWN: Duration = Duration::from_secs(30); +/// Classification of an attempt's error for retry, `429` cooldown, and +/// circuit-breaker handling. +pub(super) trait RetryableError: Debug { + /// Whether this error is transient and safe to retry. + fn is_retryable(&self) -> bool; + /// Whether this error indicates a backend outage (network errors and + /// retryable `5xx`, excluding `429`, client errors, and local failures). + fn is_outage(&self) -> bool; + /// Whether this error is a `429 Too Many Requests` response. + fn is_rate_limited(&self) -> bool; + /// Whether the operation was cancelled locally and must neither retry nor + /// update outage circuit-breaker success/failure counts. + fn is_cancelled(&self) -> bool; + /// Parsed `Retry-After` delay from the server response, if any. + fn retry_after(&self) -> Option; + /// Error returned when the outage circuit breaker is open. + fn unavailable() -> Self; +} + /// Retry parameters for one kind of remote cache operation. #[derive(Debug, Clone, Copy)] -pub struct RetryPolicy { +pub(super) struct RetryPolicy { /// Number of retries after the initial attempt (`0` means one attempt total). pub max_retries: u32, /// Nominal backoff before the first retry; doubles on each subsequent retry. @@ -70,7 +84,7 @@ impl RetryPolicy { /// Single-attempt policy with no retries, preserving `max_retry_after` for /// recording `429` cooldowns. - pub const fn once(self) -> Self { + const fn once(self) -> Self { Self { max_retries: 0, ..self } } @@ -82,9 +96,9 @@ impl RetryPolicy { } } -/// Retry and circuit-breaker configuration shared across a [`crate::Client`]. +/// Retry and circuit-breaker configuration shared across a remote endpoint. #[derive(Debug, Clone, Copy)] -pub struct RetryConfig { +pub(super) struct RetryConfig { pub read: RetryPolicy, pub store: RetryPolicy, pub outage_threshold: u32, @@ -106,7 +120,7 @@ impl RetryConfig { /// backends send with a coarse `Retry-After: 60` on transient admission errors) /// use per-request backoff instead so one `503` does not stall sibling requests. #[derive(Debug, Default)] -pub struct RateLimit { +pub(super) struct RateLimit { until: Mutex>, } @@ -148,16 +162,15 @@ impl RateLimit { } } -/// Per-client circuit breaker for sustained endpoint outages. +/// Circuit breaker for sustained endpoint outages. /// /// Opens after `threshold` consecutive exhausted outage failures (network /// errors or retryable `5xx` responses, excluding `429`), fast-failing later -/// requests with [`Error::Unavailable`] for `cooldown`. Once `cooldown` -/// elapses, a single half-open probe request is permitted; if it succeeds, -/// normal requests resume, and if it fails or is cancelled, another cooldown -/// starts. +/// requests for `cooldown`. Once `cooldown` elapses, a single half-open probe +/// request is permitted; if it succeeds, normal requests resume, and if it +/// fails or is cancelled, another cooldown starts. #[derive(Debug)] -pub struct OutageBreaker { +pub(super) struct OutageBreaker { threshold: u32, cooldown: Duration, state: Mutex, @@ -215,7 +228,7 @@ impl OutageBreaker { /// Active lease on an [`OutageBreaker`]. Dropping an unfinished probe permit /// (for example on Ctrl-C cancellation) releases the probe slot and starts /// another cooldown so the circuit cannot get stuck. -pub struct OutagePermit<'a> { +pub(super) struct OutagePermit<'a> { breaker: &'a OutageBreaker, generation: u64, probe: bool, @@ -227,13 +240,12 @@ impl OutagePermit<'_> { self.probe } - pub fn finish(mut self, result: Result<(), &Error>) { + pub fn finish(mut self, outage: bool) { if self.completed { return; } let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); if state.generation == self.generation { - let outage = result.err().is_some_and(is_outage_error); if outage { state.failures = state.failures.saturating_add(1); if self.probe || state.failures >= self.breaker.threshold { @@ -273,101 +285,53 @@ impl Drop for OutagePermit<'_> { } } -/// Failure from a single attempt, carrying an optional `Retry-After` delay from -/// a `429` response. -pub struct AttemptError { - pub error: Error, - pub rate_limit_delay: Option, -} - -impl From for AttemptError { - fn from(error: Error) -> Self { - Self { error, rate_limit_delay: None } - } -} - -/// Whether `error` is transient and safe to retry for an idempotent remote -/// cache operation. -pub const fn is_retryable(error: &Error) -> bool { - match error { - Error::Network(_) => true, - Error::Status(status, _) => is_retryable_status(*status), - Error::InvalidEndpoint(_) - | Error::HttpClient(_) - | Error::ReadBlob(_) - | Error::Auth(_) - | Error::MalformedResponse(_) - | Error::Unavailable => false, - } -} - -/// Whether `error` counts toward tripping the outage circuit breaker. Excludes -/// `429` rate limits and non-retryable `4xx` / `501` / `505` / `511` errors. -const fn is_outage_error(error: &Error) -> bool { - match error { - Error::Network(_) => true, - Error::Status(status, _) => is_retryable_server_error(*status), - Error::InvalidEndpoint(_) - | Error::HttpClient(_) - | Error::ReadBlob(_) - | Error::Auth(_) - | Error::MalformedResponse(_) - | Error::Unavailable => false, - } -} - -const fn is_retryable_status(status: StatusCode) -> bool { - matches!(status.as_u16(), 408 | 429) || is_retryable_server_error(status) -} - -const fn is_retryable_server_error(status: StatusCode) -> bool { - matches!(status.as_u16(), 500 | 502..=504 | 506..=510 | 512..=599) -} - -/// Parse an integer delta-seconds `Retry-After` header, clamped to `max`. -/// Non-numeric values return `None` so callers fall back to exponential backoff. -pub fn parse_retry_after(headers: &HeaderMap, max: Duration) -> Option { - let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim(); - let seconds: u64 = value.parse().ok()?; - Some(Duration::from_secs(seconds).min(max)) -} - /// Run `attempt_fn` through `outage`, `rate_limit`, and `policy`. -pub async fn run( +pub(super) async fn run( operation: &'static str, policy: RetryPolicy, rate_limit: &RateLimit, outage: &OutageBreaker, mut attempt_fn: F, -) -> Result +) -> Result where + E: RetryableError, F: FnMut() -> Fut, - Fut: Future>, + Fut: Future>, { let Some(permit) = outage.enter() else { tracing::debug!(operation, "skipping remote cache request while circuit is open"); - return Err(Error::Unavailable); + return Err(E::unavailable()); }; // A half-open probe makes a single attempt so it either recovers or // re-opens promptly instead of holding the only probe slot across retries. let policy = if permit.is_probe() { policy.once() } else { policy }; let started = Instant::now(); let total_attempts = policy.max_retries.saturating_add(1); - let mut final_result = None; for attempt in 0..total_attempts { rate_limit.wait().await; match attempt_fn().await { Ok(value) => { - final_result = Some(Ok(value)); - break; + permit.finish(false); + return Ok(value); } - Err(AttemptError { error, rate_limit_delay }) => { - let is_rate_limited = - matches!(error, Error::Status(StatusCode::TOO_MANY_REQUESTS, _)); + Err(error) => { + if error.is_cancelled() { + // Drop `permit` without finishing so cancelling a probe + // re-opens the cooldown and cancelling a normal request + // does not reset consecutive failures. + return Err(error); + } + let is_rate_limited = error.is_rate_limited(); let backoff = policy.delay(attempt); // Floor 429 cooldowns at `backoff` so `Retry-After: 0` cannot // trigger an immediate tight retry loop. - let cooldown = rate_limit_delay.map_or(backoff, |delay| delay.max(backoff)); + let cooldown = if is_rate_limited { + error + .retry_after() + .map_or(backoff, |delay| delay.min(policy.max_retry_after).max(backoff)) + } else { + backoff + }; if is_rate_limited { // Publish the cooldown even on the last attempt so concurrent // requests pause instead of immediately hitting the same 429. @@ -376,9 +340,9 @@ where let next_wait = if is_rate_limited { cooldown } else { backoff }; let budget_exhausted = started.elapsed().saturating_add(next_wait) >= policy.max_elapsed; - if attempt + 1 >= total_attempts || !is_retryable(&error) || budget_exhausted { - final_result = Some(Err(error)); - break; + if attempt + 1 >= total_attempts || !error.is_retryable() || budget_exhausted { + permit.finish(error.is_outage()); + return Err(error); } if is_rate_limited { tracing::debug!( @@ -403,9 +367,7 @@ where } } } - let result = final_result.expect("total_attempts is always at least 1"); - permit.finish(result.as_ref().map(|_| ())); - result + unreachable!("total_attempts is always at least 1") } /// Apply `[0.5x, 1.0x]` equal jitter to `delay` to desynchronize concurrent @@ -447,10 +409,40 @@ async fn sleep(duration: Duration) { #[cfg(test)] mod tests { - use reqwest::header::HeaderValue; - use super::*; + #[derive(Debug, PartialEq, Eq)] + enum TestError { + Outage, + Cancelled, + } + + impl RetryableError for TestError { + fn is_retryable(&self) -> bool { + matches!(self, Self::Outage) + } + + fn is_outage(&self) -> bool { + matches!(self, Self::Outage) + } + + fn is_rate_limited(&self) -> bool { + false + } + + fn is_cancelled(&self) -> bool { + matches!(self, Self::Cancelled) + } + + fn retry_after(&self) -> Option { + None + } + + fn unavailable() -> Self { + Self::Outage + } + } + #[test] fn equal_jitter_stays_within_half_to_full_bounds() { assert_eq!(equal_jitter(Duration::ZERO), Duration::ZERO); @@ -477,21 +469,6 @@ mod tests { assert!(attempt1 >= Duration::from_millis(500) && attempt1 <= Duration::from_secs(1)); } - #[test] - fn parse_retry_after_handles_valid_clamped_and_invalid_values() { - let header = |value: &str| { - HeaderMap::from_iter([(RETRY_AFTER, HeaderValue::from_str(value).unwrap())]) - }; - let max = Duration::from_secs(10); - assert_eq!(parse_retry_after(&HeaderMap::new(), max), None); - assert_eq!(parse_retry_after(&header("0"), max), Some(Duration::ZERO)); - assert_eq!(parse_retry_after(&header(" 4 "), max), Some(Duration::from_secs(4))); - assert_eq!(parse_retry_after(&header("60"), max), Some(max)); - assert_eq!(parse_retry_after(&header("999999999999"), max), Some(max)); - assert_eq!(parse_retry_after(&header("-1"), max), None); - assert_eq!(parse_retry_after(&header("Wed, 21 Oct 2026 07:28:00 GMT"), max), None); - } - #[test] fn rate_limit_record_never_shortens_existing_cooldown() { let rate_limit = RateLimit::default(); @@ -502,33 +479,19 @@ mod tests { assert_eq!(first, second); } - #[test] - fn retryable_status_excludes_non_transient_5xx() { - for retryable in [408, 429, 500, 502, 503, 504, 520, 524] { - let status = StatusCode::from_u16(retryable).unwrap(); - assert!(is_retryable_status(status), "{retryable} should be retryable"); - } - for non_retryable in [400, 401, 403, 404, 413, 501, 505, 511] { - let status = StatusCode::from_u16(non_retryable).unwrap(); - assert!(!is_retryable_status(status), "{non_retryable} should not be retryable"); - } - } - #[test] fn outage_breaker_opens_probes_recovers_and_handles_dropped_probes() { let breaker = OutageBreaker::new(3, Duration::from_secs(30)); - let server_error = Error::Status(StatusCode::SERVICE_UNAVAILABLE, None); - let rate_limit_error = Error::Status(StatusCode::TOO_MANY_REQUESTS, None); - // 429 does not count as an outage and resets consecutive failure count. - breaker.enter().unwrap().finish(Err(&server_error)); - breaker.enter().unwrap().finish(Err(&server_error)); - breaker.enter().unwrap().finish(Err(&rate_limit_error)); + // Non-outage failure (e.g., 429) resets consecutive failure count. + breaker.enter().unwrap().finish(true); + breaker.enter().unwrap().finish(true); + breaker.enter().unwrap().finish(false); assert!(breaker.enter().is_some()); // Three consecutive outage failures open the circuit. for _ in 0..3 { - breaker.enter().unwrap().finish(Err(&server_error)); + breaker.enter().unwrap().finish(true); } assert!(breaker.enter().is_none()); @@ -543,13 +506,40 @@ mod tests { // Failed probe re-opens the circuit. breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); - breaker.enter().unwrap().finish(Err(&server_error)); + breaker.enter().unwrap().finish(true); assert!(breaker.enter().is_none()); // Successful probe closes the circuit. breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); - breaker.enter().unwrap().finish(Ok(())); + breaker.enter().unwrap().finish(false); assert!(breaker.enter().is_some()); assert!(breaker.enter().is_some()); } + + #[tokio::test] + async fn cancelled_probe_does_not_close_open_circuit() { + let breaker = OutageBreaker::new(1, Duration::from_secs(30)); + let rate_limit = RateLimit::default(); + let policy = + RetryPolicy { max_retries: 0, base_delay: Duration::ZERO, ..RetryPolicy::READ }; + + // Open the circuit with one outage failure. + let err = run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, || async { + Err(TestError::Outage) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Outage); + assert!(breaker.enter().is_none()); + + // Expire cooldown and cancel the half-open probe: circuit must stay open. + breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + let err = run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, || async { + Err(TestError::Cancelled) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Cancelled); + assert!(breaker.enter().is_none()); + } } diff --git a/crates/vt_remote_cache/Cargo.toml b/crates/vt_remote_cache/Cargo.toml index 436e14dfc..bf80338ad 100644 --- a/crates/vt_remote_cache/Cargo.toml +++ b/crates/vt_remote_cache/Cargo.toml @@ -11,7 +11,6 @@ rust-version.workspace = true base64 = { workspace = true } bytes = { workspace = true } ciborium = { workspace = true } -getrandom = { workspace = true } reqwest = { workspace = true, features = [ "multipart", "rustls-no-provider", @@ -23,7 +22,7 @@ serde = { workspace = true, features = ["derive"] } serde_bytes = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } -tokio = { workspace = true, features = ["fs", "sync", "time"] } +tokio = { workspace = true, features = ["fs", "sync"] } tracing = { workspace = true } url = { workspace = true } vt_path = { workspace = true } diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index fbc04c47b..1101835cb 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -12,9 +12,9 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta `Client::download` gets a blob by its ID. After a 200 response, it returns a `Download`, from which the caller reads the blob's chunks as they arrive. -`Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. At most `MAX_CONCURRENT_STORES` (4) stores run concurrently per client. +`Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. -Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Transient network errors and retryable HTTP statuses (`408`, `429`, and `5xx` other than `501`, `505`, and `511`) are retried with jittered exponential backoff (up to 3 retries within a 60-second retry budget for stores, and up to 2 retries within a 15-second retry budget for fetches and downloads). On `429 Too Many Requests`, concurrent requests of the same kind (reads or stores) on that client share a cooldown using the response's integer `Retry-After` header (clamped to 10 seconds, floored at the attempt's backoff); `5xx` responses use per-request backoff only. After 3 consecutive exhausted outage failures (network errors or retryable `5xx`), a circuit breaker for that kind of operation (reads or stores) short-circuits requests with `Error::Unavailable` for 30 seconds before probing with one request. +Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error` exposes `is_retryable`, `is_outage`, `is_rate_limited`, and `retry_after` (parsed delta-seconds `Retry-After`) to inform those policies. reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 20-second per-attempt timeout. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index f966aa588..923dd8148 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -2,7 +2,6 @@ //! bytes; the caller decides what they contain. pub mod auth; -mod retry; #[cfg(test)] mod test_server; @@ -13,20 +12,16 @@ use std::{ use bytes::Bytes; use reqwest::{ - Body, Response, StatusCode, - header::{CONTENT_TYPE, HeaderMap}, + Response, StatusCode, + header::{CONTENT_TYPE, HeaderMap, RETRY_AFTER}, multipart::{Form, Part}, }; use serde::{Deserialize, Deserializer, Serialize}; -use tokio::sync::Semaphore; use url::{ParseError, Url}; use vt_path::AbsolutePath; use vt_str::Str; -use crate::{ - auth::{Auth, AuthError, Operation}, - retry::{AttemptError, OutageBreaker, RateLimit, RetryConfig, parse_retry_after}, -}; +use crate::auth::{Auth, AuthError, Operation}; /// Time allowed to establish a connection, including the TLS handshake. const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); @@ -35,7 +30,7 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); /// arrive, it also bounds sending the request. const READ_TIMEOUT: Duration = Duration::from_secs(60); -/// Total timeout for a single `POST /fetch` attempt. Fetches transfer small +/// Total timeout for a single `POST /fetch` request. Fetches transfer small /// metadata payloads, so bounding them more tightly lets a hung lookup retry /// or fall back quickly instead of stalling a task for [`READ_TIMEOUT`]. const FETCH_TIMEOUT: Duration = Duration::from_secs(20); @@ -44,13 +39,6 @@ const FETCH_TIMEOUT: Duration = Duration::from_secs(20); /// NAT and edge proxy idle cutoffs to reduce stale-socket resets on reuse. const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30); -/// Maximum number of concurrent `POST /store` uploads in flight per [`Client`]. -/// -/// Bounding uploads per client shapes bursts against backends with per-isolate -/// admission limits, prevents uplink thrashing, and caps open blob file -/// handles. -pub const MAX_CONCURRENT_STORES: usize = 4; - /// A failed remote cache operation. The messages name only the kind of /// failure, so they are the same on every platform. The details, if any, are /// in the source. @@ -80,15 +68,78 @@ pub enum Error { /// The server responded with a status other than 200, or for a fetch, /// other than 200 or 404. The source is the message in the response body, /// if any. - #[error("HTTP status {}", .0.as_u16())] - Status(StatusCode, #[source] Option), + #[error("HTTP status {}", status.as_u16())] + Status { + /// The HTTP status code returned by the server. + status: StatusCode, + /// The message in the response body, if any. + #[source] + message: Option, + /// Parsed delta-seconds `Retry-After` header, if present and valid. + retry_after: Option, + }, /// The body of a 200 fetch response isn't an exact or fallback match. #[error("malformed response")] MalformedResponse(#[source] ciborium::de::Error), - /// The remote cache endpoint recently failed repeatedly, so this request - /// was skipped during the outage cooldown window. - #[error("remote cache temporarily unavailable")] - Unavailable, +} + +impl Error { + /// Whether this failure is transient and safe to retry for an idempotent + /// remote cache operation (`Network`, `408`, `429`, and retryable `5xx`). + #[must_use] + pub const fn is_retryable(&self) -> bool { + match self { + Self::Network(_) => true, + Self::Status { status, .. } => { + matches!(status.as_u16(), 408 | 429) || is_retryable_server_error(*status) + } + Self::InvalidEndpoint(_) + | Self::HttpClient(_) + | Self::ReadBlob(_) + | Self::Auth(_) + | Self::MalformedResponse(_) => false, + } + } + + /// Whether this failure indicates a backend outage (`Network` or retryable + /// `5xx`, excluding `429` rate limits and client errors). + #[must_use] + pub const fn is_outage(&self) -> bool { + match self { + Self::Network(_) => true, + Self::Status { status, .. } => is_retryable_server_error(*status), + Self::InvalidEndpoint(_) + | Self::HttpClient(_) + | Self::ReadBlob(_) + | Self::Auth(_) + | Self::MalformedResponse(_) => false, + } + } + + /// Whether the server responded with `429 Too Many Requests`. + #[must_use] + pub const fn is_rate_limited(&self) -> bool { + matches!(self, Self::Status { status, .. } if status.as_u16() == 429) + } + + /// The parsed delta-seconds `Retry-After` header from an error response, + /// if any. + #[must_use] + pub const fn retry_after(&self) -> Option { + match self { + Self::Status { retry_after, .. } => *retry_after, + Self::InvalidEndpoint(_) + | Self::HttpClient(_) + | Self::ReadBlob(_) + | Self::Auth(_) + | Self::Network(_) + | Self::MalformedResponse(_) => None, + } + } +} + +const fn is_retryable_server_error(status: StatusCode) -> bool { + matches!(status.as_u16(), 500 | 502..=504 | 506..=510 | 512..=599) } /// The message in the body of an error response. @@ -167,6 +218,9 @@ pub enum Fetched { } /// A client for one remote cache endpoint. +/// +/// Each method sends a single HTTP/1.1 request and leaves retry, rate-limit, +/// circuit-breaker, and concurrency policies to the caller. #[derive(Debug)] pub struct Client { http: reqwest::Client, @@ -175,22 +229,6 @@ pub struct Client { store_url: Url, /// `{endpoint}/blob`, to which each download appends a blob ID. blob_url: Url, - /// Bounds concurrent `POST /store` uploads in flight for this endpoint. - store_permits: Semaphore, - /// Shared cooldown for `429 Too Many Requests` on read operations so - /// upload rate limits do not stall fetches on the task critical path. - read_rate_limit: RateLimit, - /// Shared cooldown for `429 Too Many Requests` on store operations. - store_rate_limit: RateLimit, - /// Circuit breaker that short-circuits read requests (fetch and download) - /// during sustained outages. Kept separate from stores so store failures - /// do not block the task-critical read path. - read_outage: OutageBreaker, - /// Circuit breaker that short-circuits store requests during sustained - /// outages. Kept separate from reads so successful reads cannot reset - /// consecutive store failures. - store_outage: OutageBreaker, - retry: RetryConfig, } impl Client { @@ -203,10 +241,6 @@ impl Client { /// Returns [`Error::InvalidEndpoint`] if `endpoint` isn't a usable URL, or /// [`Error::HttpClient`] if the HTTP client can't be created. pub fn new(endpoint: &str, auth: Arc) -> Result { - Self::with_retry(endpoint, auth, RetryConfig::DEFAULT) - } - - fn with_retry(endpoint: &str, auth: Arc, retry: RetryConfig) -> Result { let endpoint = parse_endpoint(endpoint)?; let fetch_url = route_url(&endpoint, "fetch")?; let store_url = route_url(&endpoint, "store")?; @@ -229,19 +263,7 @@ impl Client { .redirect(reqwest::redirect::Policy::none()) .build() .map_err(Error::HttpClient)?; - Ok(Self { - http, - auth, - fetch_url, - store_url, - blob_url, - store_permits: Semaphore::new(MAX_CONCURRENT_STORES), - read_rate_limit: RateLimit::default(), - store_rate_limit: RateLimit::default(), - read_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), - store_outage: OutageBreaker::new(retry.outage_threshold, retry.outage_cooldown), - retry, - }) + Ok(Self { http, auth, fetch_url, store_url, blob_url }) } async fn auth_headers(&self, operation: Operation) -> Result { @@ -250,9 +272,7 @@ impl Client { /// Fetch the entries stored under `key` with `POST {endpoint}/fetch`, /// falling back to the key associated with `secondary_key`. Returns - /// `None` for a 404 response, which means neither key matched. Transient - /// network errors and retryable HTTP statuses (`408`, `429`, `5xx` except - /// `501`/`505`/`511`) are retried with jittered exponential backoff. + /// `None` for a 404 response, which means neither key matched. /// /// # Errors /// @@ -261,53 +281,38 @@ impl Client { /// body of a 200 response isn't an exact or fallback match. #[tracing::instrument(level = "debug", skip_all)] pub async fn fetch(&self, key: &[u8], secondary_key: &[u8]) -> Result, Error> { - let body = Bytes::from(encode_cbor(&FetchRequest { key, secondary_key })); - let policy = self.retry.read; - let result = retry::run("fetch", policy, &self.read_rate_limit, &self.read_outage, || { - let body = body.clone(); - async move { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Fetch).await?; - let response = self - .http - .post(self.fetch_url.clone()) - .headers(headers) - .header(CONTENT_TYPE, "application/cbor") - .timeout(FETCH_TIMEOUT) - .body(body) - .send() - .await - .map_err(network_error)?; - log_response(&response, start); - if response.status() == StatusCode::NOT_FOUND { - // Read the body so the connection can be reused. It doesn't matter - // if that fails, because the status alone is the answer. - let _ = response.bytes().await; - return Ok(None); - } - let body = check_status(response, policy.max_retry_after) - .await? - .bytes() - .await - .map_err(network_error)?; - tracing::debug!( - bytes = body.len(), - elapsed = ?start.elapsed(), - "remote cache fetch received" - ); - decode_fetched(&body).map(Some).map_err(AttemptError::from) - } - }) - .await; - drop(body); - result + let start = Instant::now(); + let headers = self.auth_headers(Operation::Fetch).await?; + let body = encode_cbor(&FetchRequest { key, secondary_key }); + let response = self + .http + .post(self.fetch_url.clone()) + .headers(headers) + .header(CONTENT_TYPE, "application/cbor") + .timeout(FETCH_TIMEOUT) + .body(body) + .send() + .await + .map_err(network_error)?; + log_response(&response, start); + if response.status() == StatusCode::NOT_FOUND { + // Read the body so the connection can be reused. It doesn't matter + // if that fails, because the status alone is the answer. + let _ = response.bytes().await; + return Ok(None); + } + let body = check_status(response).await?.bytes().await.map_err(network_error)?; + tracing::debug!( + bytes = body.len(), + elapsed = ?start.elapsed(), + "remote cache fetch received" + ); + decode_fetched(&body).map(Some) } /// Start downloading the blob `blob_id` with /// `GET {endpoint}/blob/{blob_id}`. Its chunks are read from the returned - /// [`Download`] as they arrive. Transient network errors and retryable - /// HTTP statuses (`408`, `429`, `5xx` except `501`/`505`/`511`) before the - /// response headers arrive are retried with jittered exponential backoff. + /// [`Download`] as they arrive. /// /// # Errors /// @@ -315,49 +320,18 @@ impl Client { /// fails, or the server responds with a status other than 200. #[tracing::instrument(level = "debug", skip_all)] pub async fn download(&self, blob_id: &str) -> Result { - self.download_with_policy(blob_id, self.retry.read).await - } - - /// Start downloading the blob `blob_id` with a single attempt (no header - /// retries), used when retrying a download that dropped mid-stream so - /// outer and inner retry layers do not multiply. - /// - /// # Errors - /// - /// Returns an error if the credentials can't be obtained, the request - /// fails, or the server responds with a status other than 200. - #[tracing::instrument(level = "debug", skip_all)] - pub async fn download_once(&self, blob_id: &str) -> Result { - self.download_with_policy(blob_id, self.retry.read.once()).await - } - - async fn download_with_policy( - &self, - blob_id: &str, - policy: retry::RetryPolicy, - ) -> Result { + let start = Instant::now(); let mut url = self.blob_url.clone(); url.path_segments_mut().map_err(|()| Error::InvalidEndpoint(None))?.push(blob_id); - retry::run("download", policy, &self.read_rate_limit, &self.read_outage, || { - let url = url.clone(); - async move { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Download).await?; - let response = - self.http.get(url).headers(headers).send().await.map_err(network_error)?; - log_response(&response, start); - Ok(Download { response: check_status(response, policy.max_retry_after).await? }) - } - }) - .await + let headers = self.auth_headers(Operation::Download).await?; + let response = self.http.get(url).headers(headers).send().await.map_err(network_error)?; + log_response(&response, start); + Ok(Download { response: check_status(response).await? }) } /// Store `value` under `key` with `POST {endpoint}/store`, uploading the /// file at `blob` as its blob. Fetches that match no key fall back to this - /// entry through `secondary_key`. At most [`MAX_CONCURRENT_STORES`] stores - /// run concurrently per client, and transient network errors or retryable - /// HTTP statuses (`408`, `429`, `5xx` except `501`/`505`/`511`) are - /// retried with jittered exponential backoff. + /// entry through `secondary_key`. /// /// # Errors /// @@ -365,7 +339,6 @@ impl Client { /// can't be opened, the request fails, or the server responds with a /// status other than 200. #[tracing::instrument(level = "debug", skip_all)] - #[expect(clippy::missing_panics_doc, reason = "store_permits semaphore is never closed")] pub async fn store( &self, key: &[u8], @@ -373,56 +346,37 @@ impl Client { value: &[u8], blob: Option<&AbsolutePath>, ) -> Result<(), Error> { - let queue_start = Instant::now(); - let permit = self.store_permits.acquire().await.expect("store semaphore is never closed"); - let queued = queue_start.elapsed(); - let metadata_bytes = Bytes::from(encode_cbor(&StoreMetadata { key, secondary_key, value })); - let value_bytes = value.len(); - let policy = self.retry.store; - let result = - retry::run("store", policy, &self.store_rate_limit, &self.store_outage, || { - let metadata_bytes = metadata_bytes.clone(); - async move { - let start = Instant::now(); - let headers = self.auth_headers(Operation::Store).await?; - let auth = start.elapsed(); - let mut form = Form::new().part("metadata", metadata_part(metadata_bytes)); - let blob_bytes = if let Some(blob) = blob { - let (part, length) = blob_part(blob).await?; - form = form.part("blob", part); - Some(length) - } else { - None - }; - tracing::debug!( - value_bytes, - blob_bytes, - ?queued, - ?auth, - "sending a remote cache store" - ); - let response = self - .http - .post(self.store_url.clone()) - .headers(headers) - .multipart(form) - .send() - .await - .map_err(network_error)?; - log_response(&response, start); - // The response's blob ID isn't needed. Read the body anyway, so the - // connection can be reused. - check_status(response, policy.max_retry_after) - .await? - .bytes() - .await - .map_err(network_error)?; - Ok(()) - } - }) - .await; - drop(permit); - result + let start = Instant::now(); + let headers = self.auth_headers(Operation::Store).await?; + let auth = start.elapsed(); + let metadata = encode_cbor(&StoreMetadata { key, secondary_key, value }); + let mut form = Form::new().part("metadata", metadata_part(metadata)); + let blob_bytes = if let Some(blob) = blob { + let (part, length) = blob_part(blob).await?; + form = form.part("blob", part); + Some(length) + } else { + None + }; + tracing::debug!( + value_bytes = value.len(), + blob_bytes, + ?auth, + "sending a remote cache store" + ); + let response = self + .http + .post(self.store_url.clone()) + .headers(headers) + .multipart(form) + .send() + .await + .map_err(network_error)?; + log_response(&response, start); + // The response's blob ID isn't needed. Read the body anyway, so the + // connection can be reused. + check_status(response).await?.bytes().await.map_err(network_error)?; + Ok(()) } } @@ -438,26 +392,27 @@ fn log_response(response: &Response, start: Instant) { ); } +/// Parse an integer delta-seconds `Retry-After` header. Non-numeric values +/// (including HTTP dates) return `None`. +fn parse_retry_after(headers: &HeaderMap) -> Option { + let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim(); + let seconds: u64 = value.parse().ok()?; + Some(Duration::from_secs(seconds)) +} + /// Only HTTP 200 counts as success. For other statuses, the error includes the -/// message in the response body. For `429 Too Many Requests`, any valid -/// integer `Retry-After` header is also returned (clamped to `max_retry_after`) -/// so the client's shared cooldown can honor it. -async fn check_status( - response: Response, - max_retry_after: Duration, -) -> Result { +/// message in the response body and any valid integer `Retry-After` header. +async fn check_status(response: Response) -> Result { let status = response.status(); if status == StatusCode::OK { return Ok(response); } - let rate_limit_delay = (status == StatusCode::TOO_MANY_REQUESTS) - .then(|| parse_retry_after(response.headers(), max_retry_after)) - .flatten(); + let retry_after = parse_retry_after(response.headers()); let message = response.text().await.ok().and_then(|text| { let text = text.trim(); (!text.is_empty()).then(|| ServerMessage(Str::from(text))) }); - Err(AttemptError { error: Error::Status(status, message), rate_limit_delay }) + Err(Error::Status { status, message, retry_after }) } fn network_error(err: reqwest::Error) -> Error { @@ -497,11 +452,8 @@ fn encode_cbor(value: &impl Serialize) -> Vec { bytes } -fn metadata_part(metadata_bytes: Bytes) -> Part { - let length = u64::try_from(metadata_bytes.len()).expect("metadata length fits in u64"); - Part::stream_with_length(Body::from(metadata_bytes), length) - .mime_str("application/cbor") - .expect("valid MIME type") +fn metadata_part(metadata: Vec) -> Part { + Part::bytes(metadata).mime_str("application/cbor").expect("valid MIME type") } /// The blob part streamed from the file at `path`, and its length. @@ -516,11 +468,7 @@ async fn blob_part(path: &AbsolutePath) -> Result<(Part, u64), Error> { #[cfg(test)] mod tests { - use std::{ - io::{Read as _, Write as _}, - net::TcpListener, - sync::atomic::{AtomicUsize, Ordering}, - }; + use std::{io::Read as _, net::TcpListener}; use reqwest::header::{HeaderName, HeaderValue}; use vt_path::AbsolutePathBuf; @@ -528,34 +476,9 @@ mod tests { use super::*; use crate::{ auth::{Anonymous, AuthHeaders}, - retry::RetryPolicy, test_server::{contains, no_request_waiting, serve_once, serve_raw_once}, }; - /// Zero-delay retry config with the same attempt counts as production, so - /// retry tests exercise the full retry loop without sleeping. - const FAST_RETRY: RetryConfig = RetryConfig { - read: RetryPolicy { - base_delay: Duration::ZERO, - max_delay: Duration::ZERO, - ..RetryPolicy::READ - }, - store: RetryPolicy { - base_delay: Duration::ZERO, - max_delay: Duration::ZERO, - ..RetryPolicy::STORE - }, - ..RetryConfig::DEFAULT - }; - - /// Single-attempt retry config for tests that intentionally drop the - /// connection after inspecting one request (such as TLS `ClientHello`). - const NO_RETRY: RetryConfig = RetryConfig { - read: RetryPolicy { max_retries: 0, ..FAST_RETRY.read }, - store: RetryPolicy { max_retries: 0, ..FAST_RETRY.store }, - ..FAST_RETRY - }; - fn store_url(endpoint: &str) -> Result { route_url(&parse_endpoint(endpoint)?, "store") } @@ -660,27 +583,59 @@ mod tests { } } - fn client_for(listener: &TcpListener) -> Client { - client_with_auth(listener, Arc::new(Anonymous)) + #[test] + fn parse_retry_after_handles_valid_and_invalid_values() { + let header = |value: &str| { + HeaderMap::from_iter([(RETRY_AFTER, HeaderValue::from_str(value).unwrap())]) + }; + assert_eq!(parse_retry_after(&HeaderMap::new()), None); + assert_eq!(parse_retry_after(&header("0")), Some(Duration::ZERO)); + assert_eq!(parse_retry_after(&header(" 4 ")), Some(Duration::from_secs(4))); + assert_eq!(parse_retry_after(&header("60")), Some(Duration::from_secs(60))); + assert_eq!(parse_retry_after(&header("-1")), None); + assert_eq!(parse_retry_after(&header("Wed, 21 Oct 2026 07:28:00 GMT")), None); } - fn fast_client_for(listener: &TcpListener) -> Client { - client_with_retry(listener, Arc::new(Anonymous), FAST_RETRY) + #[test] + fn error_retry_classification_handles_statuses_correctly() { + let status_err = |code: u16, retry_after: Option| Error::Status { + status: StatusCode::from_u16(code).unwrap(), + message: None, + retry_after, + }; + for code in [500, 502, 503, 504, 520, 524] { + let err = status_err(code, Some(Duration::from_secs(60))); + assert!(err.is_retryable(), "{code} should be retryable"); + assert!(err.is_outage(), "{code} should be an outage"); + assert!(!err.is_rate_limited(), "{code} is not 429"); + assert_eq!(err.retry_after(), Some(Duration::from_secs(60))); + } + let err_408 = status_err(408, None); + assert!(err_408.is_retryable()); + assert!(!err_408.is_outage()); + assert!(!err_408.is_rate_limited()); + + let err_429 = status_err(429, Some(Duration::from_secs(5))); + assert!(err_429.is_retryable()); + assert!(!err_429.is_outage()); + assert!(err_429.is_rate_limited()); + assert_eq!(err_429.retry_after(), Some(Duration::from_secs(5))); + + for code in [400, 401, 403, 404, 413, 501, 505, 511] { + let err = status_err(code, None); + assert!(!err.is_retryable(), "{code} should not be retryable"); + assert!(!err.is_outage(), "{code} should not be an outage"); + assert!(!err.is_rate_limited()); + } } - fn client_with_auth(listener: &TcpListener, auth: Arc) -> Client { - let port = listener.local_addr().unwrap().port(); - Client::new(&vt_str::format!("http://127.0.0.1:{port}/projects/test"), auth).unwrap() + fn client_for(listener: &TcpListener) -> Client { + client_with_auth(listener, Arc::new(Anonymous)) } - fn client_with_retry( - listener: &TcpListener, - auth: Arc, - retry: RetryConfig, - ) -> Client { + fn client_with_auth(listener: &TcpListener, auth: Arc) -> Client { let port = listener.local_addr().unwrap().port(); - Client::with_retry(&vt_str::format!("http://127.0.0.1:{port}/projects/test"), auth, retry) - .unwrap() + Client::new(&vt_str::format!("http://127.0.0.1:{port}/projects/test"), auth).unwrap() } /// The `metadata` part of a store request for key `k`, secondary key `s`, @@ -745,17 +700,29 @@ mod tests { #[tokio::test] async fn fetch_fails_on_an_error_status() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); + let client = client_for(&listener); let server = std::thread::spawn(move || { - (0..3) - .map(|_| serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"try later")) - .collect::>() + serve_raw_once( + &listener, + b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 9\r\n\r\ntry later", + ) }); let error = client.fetch(b"k", b"s").await.unwrap_err(); - assert!(matches!(error, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{error:?}"); + assert!( + matches!( + error, + Error::Status { + status: StatusCode::SERVICE_UNAVAILABLE, + retry_after: Some(delay), + .. + } if delay == Duration::from_secs(60) + ), + "{error:?}" + ); + assert_eq!(error.to_string(), "HTTP status 503"); assert_eq!(std::error::Error::source(&error).unwrap().to_string(), "try later"); - assert_eq!(server.join().unwrap().len(), 3); + server.join().unwrap(); } async fn read_to_end(mut download: Download) -> Result, Error> { @@ -814,30 +781,23 @@ mod tests { let blob = AbsolutePathBuf::new(dir.path().join("archive.tar.zst")).unwrap(); std::fs::write(blob.as_path(), b"archive bytes").unwrap(); let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); + let client = client_for(&listener); let server = std::thread::spawn(move || { - (0..4) - .map(|_| { - serve_once(&listener, "HTTP/1.1 500 Internal Server Error", b"storage failed\n") - }) - .collect::>() + serve_once(&listener, "HTTP/1.1 500 Internal Server Error", b"storage failed\n") }); let err = client.store(b"k", b"s", b"v", Some(&blob)).await.unwrap_err(); - assert!(matches!(err, Error::Status(StatusCode::INTERNAL_SERVER_ERROR, _))); + assert!(matches!(err, Error::Status { status: StatusCode::INTERNAL_SERVER_ERROR, .. })); assert_eq!(err.to_string(), "HTTP status 500"); assert_eq!(std::error::Error::source(&err).unwrap().to_string(), "storage failed"); - let requests = server.join().unwrap(); - assert_eq!(requests.len(), 4); + let request = server.join().unwrap(); let blob_part = b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; - for request in &requests { - assert!(request.starts_with(b"POST /projects/test/store HTTP/1.1\r\n")); - assert!(contains(request, b"content-type: multipart/form-data; boundary=")); - assert!(contains(request, &metadata_part_bytes())); - assert!(contains(request, blob_part)); - } + assert!(request.starts_with(b"POST /projects/test/store HTTP/1.1\r\n")); + assert!(contains(&request, b"content-type: multipart/form-data; boundary=")); + assert!(contains(&request, &metadata_part_bytes())); + assert!(contains(&request, blob_part)); } #[tokio::test] @@ -868,7 +828,10 @@ mod tests { }); let error = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(error, Error::Status(StatusCode::FOUND, None)), "{error:?}"); + assert!( + matches!(error, Error::Status { status: StatusCode::FOUND, message: None, .. }), + "{error:?}" + ); server.join().unwrap(); } @@ -973,10 +936,9 @@ mod tests { async fn uses_http1_only_over_tls() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - let client = Client::with_retry( + let client = Client::new( &vt_str::format!("https://127.0.0.1:{port}/projects/test"), Arc::new(Anonymous), - NO_RETRY, ) .unwrap(); let server = std::thread::spawn(move || read_client_hello(&listener)); @@ -990,334 +952,10 @@ mod tests { assert!(!contains(&client_hello, b"\x02h2")); } - #[tokio::test] - async fn fetch_retries_transient_statuses_and_network_errors() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); - let ok_body = exact(vec![cbor_value(vec![ - ("value", ciborium::Value::Bytes(b"v".to_vec())), - ("blob_id", ciborium::Value::Null), - ])]); - let server = std::thread::spawn(move || { - // Attempt 1: 503 with Retry-After: 60 (must not stall or fail). - serve_raw_once( - &listener, - b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 39\r\n\r\nService unavailable (concurrency_limit)", - ); - // Attempt 2: connection dropped mid-response (network error). - serve_raw_once(&listener, b"HTTP/1.1 200 OK\r\ncontent-length: 100\r\n\r\n"); - // Attempt 3: succeeds. - serve_once(&listener, "HTTP/1.1 200 OK", &ok_body); - }); - - let start = Instant::now(); - assert_eq!( - client.fetch(b"k", b"s").await.unwrap(), - Some(Fetched::Exact { entries: vec![Entry { value: b"v".to_vec(), blob_id: None }] }) - ); - assert!(start.elapsed() < Duration::from_secs(5), "503 Retry-After: 60 should be ignored"); - server.join().unwrap(); - } - - #[tokio::test] - async fn download_retries_transient_error_before_headers() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); - let server = std::thread::spawn(move || { - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"busy"); - serve_once(&listener, "HTTP/1.1 200 OK", b"archive bytes"); - }); - - let download = client.download("7").await.unwrap(); - assert_eq!(read_to_end(download).await.unwrap(), b"archive bytes"); - server.join().unwrap(); - } - - #[tokio::test] - async fn store_retries_transient_errors_and_resends_blob() { - let dir = tempfile::tempdir().unwrap(); - let blob = AbsolutePathBuf::new(dir.path().join("archive.tar.zst")).unwrap(); - std::fs::write(blob.as_path(), b"archive bytes").unwrap(); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); - let server = std::thread::spawn(move || { - let first = serve_raw_once( - &listener, - b"HTTP/1.1 503 Service Unavailable\r\nretry-after: 60\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", - ); - // Drop connection before sending headers on attempt 2. - { - let (stream, _) = listener.accept().unwrap(); - drop(stream); - } - let third = serve_once(&listener, "HTTP/1.1 200 OK", b""); - (first, third) - }); - - client.store(b"k", b"s", b"v", Some(&blob)).await.unwrap(); - let (first, third) = server.join().unwrap(); - let blob_part = - b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; - assert!(contains(&first, blob_part)); - assert!(contains(&third, blob_part)); - } - - #[tokio::test] - async fn non_retryable_statuses_fail_without_retrying() { - for status_line in [ - "HTTP/1.1 400 Bad Request", - "HTTP/1.1 401 Unauthorized", - "HTTP/1.1 403 Forbidden", - "HTTP/1.1 413 Payload Too Large", - "HTTP/1.1 501 Not Implemented", - ] { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); - let server = { - let listener = listener.try_clone().unwrap(); - std::thread::spawn(move || serve_once(&listener, status_line, b"nope")) - }; - - let error = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(error, Error::Status(_, _)), "{status_line}: {error:?}"); - server.join().unwrap(); - assert!(no_request_waiting(&listener), "{status_line} should not retry"); - } - } - - #[tokio::test] - async fn download_once_does_not_retry() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = fast_client_for(&listener); - let server = { - let listener = listener.try_clone().unwrap(); - std::thread::spawn(move || { - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"busy") - }) - }; - - let error = client.download_once("7").await.unwrap_err(); - assert!(matches!(error, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{error:?}"); - server.join().unwrap(); - assert!(no_request_waiting(&listener)); - } - - #[tokio::test] - async fn rate_limit_429_respects_retry_after() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let cooldown = Duration::from_millis(80); - let retry = RetryConfig { - read: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.read }, - store: RetryPolicy { max_retry_after: cooldown, ..FAST_RETRY.store }, - ..FAST_RETRY - }; - let client = client_with_retry(&listener, Arc::new(Anonymous), retry); - let server = std::thread::spawn(move || { - // `Retry-After: 5` is clamped to `cooldown` (80 ms). - serve_raw_once( - &listener, - b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", - ); - serve_once(&listener, "HTTP/1.1 200 OK", b""); - }); - - let start = Instant::now(); - client.store(b"k", b"s", b"v", None).await.unwrap(); - assert!( - start.elapsed() >= Duration::from_millis(60), - "429 Retry-After cooldown was not respected: {:?}", - start.elapsed() - ); - server.join().unwrap(); - } - - #[tokio::test] - async fn rate_limit_429_pauses_same_kind_peers_without_stalling_reads() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let cooldown = Duration::from_millis(80); - let retry = RetryConfig { - // Single attempt so the first store returns 429 immediately after - // publishing the store cooldown; a read runs right away while a - // peer store waits for the cooldown. - read: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.read }, - store: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.store }, - ..FAST_RETRY - }; - let client = client_with_retry(&listener, Arc::new(Anonymous), retry); - let server = std::thread::spawn(move || { - serve_raw_once( - &listener, - b"HTTP/1.1 429 Too Many Requests\r\nretry-after: 5\r\nconnection: close\r\ncontent-length: 0\r\n\r\n", - ); - serve_once(&listener, "HTTP/1.1 404 Not Found", b""); - serve_once(&listener, "HTTP/1.1 200 OK", b""); - }); - - let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(err, Error::Status(StatusCode::TOO_MANY_REQUESTS, _)), "{err:?}"); - - let fetch_start = Instant::now(); - assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); - assert!( - fetch_start.elapsed() < Duration::from_millis(50), - "store 429 should not stall fetch: {:?}", - fetch_start.elapsed() - ); - - let store_start = Instant::now(); - client.store(b"k", b"s", b"v", None).await.unwrap(); - assert!( - store_start.elapsed() >= Duration::from_millis(40), - "peer store did not wait for shared 429 cooldown: {:?}", - store_start.elapsed() - ); - server.join().unwrap(); - } - - #[tokio::test] - async fn outage_breaker_short_circuits_per_kind_independently() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let retry = RetryConfig { - outage_threshold: 2, - outage_cooldown: Duration::from_secs(30), - ..NO_RETRY - }; - let client = client_with_retry(&listener, Arc::new(Anonymous), retry); - let server = { - let listener = listener.try_clone().unwrap(); - std::thread::spawn(move || { - // Store #1 fails, interleaved fetch succeeds (must not reset store failures), - // store #2 fails (opens store breaker), fetch still works, - // then two fetch failures open read breaker. - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); - serve_once(&listener, "HTTP/1.1 404 Not Found", b""); - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); - serve_once(&listener, "HTTP/1.1 404 Not Found", b""); - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"down"); - }) - }; - - let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); - // A successful fetch must not reset consecutive store failures. - assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); - let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); - - // Store breaker is now open, but reads still reach the server. - assert_eq!(client.fetch(b"k", b"s").await.unwrap(), None); - let err = client.store(b"k", b"s", b"v", None).await.unwrap_err(); - assert!(matches!(err, Error::Unavailable), "{err:?}"); - assert_eq!(err.to_string(), "remote cache temporarily unavailable"); - - // Two consecutive fetch failures open the read breaker as well. - for _ in 0..2 { - let err = client.fetch(b"k", b"s").await.unwrap_err(); - assert!(matches!(err, Error::Status(StatusCode::SERVICE_UNAVAILABLE, _)), "{err:?}"); - } - server.join().unwrap(); - - let err = client.fetch(b"k", b"s").await.unwrap_err(); - assert!(matches!(err, Error::Unavailable), "{err:?}"); - assert!(no_request_waiting(&listener)); - } - - #[tokio::test] - async fn concurrent_stores_are_capped_at_max_concurrent_stores() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let client = Arc::new(fast_client_for(&listener)); - let total_stores = MAX_CONCURRENT_STORES * 2; - let in_flight = Arc::new(AtomicUsize::new(0)); - let max_in_flight = Arc::new(AtomicUsize::new(0)); - let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); - let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); - let (filled_tx, filled_rx) = std::sync::mpsc::channel::<()>(); - - let server = { - let in_flight = Arc::clone(&in_flight); - let max_in_flight = Arc::clone(&max_in_flight); - std::thread::spawn(move || { - let mut handlers = Vec::with_capacity(total_stores); - for _ in 0..total_stores { - let (mut stream, _) = listener.accept().unwrap(); - let in_flight = Arc::clone(&in_flight); - let max_in_flight = Arc::clone(&max_in_flight); - let release_rx = Arc::clone(&release_rx); - let filled_tx = filled_tx.clone(); - handlers.push(std::thread::spawn(move || { - let mut request = Vec::new(); - let mut buf = [0; 4096]; - let header_end = loop { - let n = stream.read(&mut buf).unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&buf[..n]); - if let Some(pos) = - request.windows(4).position(|window| window == b"\r\n\r\n") - { - break pos + 4; - } - }; - let content_length: usize = std::str::from_utf8(&request[..header_end]) - .unwrap() - .lines() - .find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse().unwrap()) - }) - .unwrap_or(0); - while request.len() < header_end + content_length { - let n = stream.read(&mut buf).unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&buf[..n]); - } - let current = in_flight.fetch_add(1, Ordering::SeqCst) + 1; - max_in_flight.fetch_max(current, Ordering::SeqCst); - if current == MAX_CONCURRENT_STORES { - let _ = filled_tx.send(()); - } - let _ = release_rx.lock().unwrap().recv(); - in_flight.fetch_sub(1, Ordering::SeqCst); - stream - .write_all(b"HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n") - .unwrap(); - })); - } - for handler in handlers { - handler.join().unwrap(); - } - }) - }; - - let mut tasks = Vec::with_capacity(total_stores); - for _ in 0..total_stores { - let client = Arc::clone(&client); - tasks.push(tokio::spawn(async move { client.store(b"k", b"s", b"v", None).await })); - } - - // Wait until all `MAX_CONCURRENT_STORES` slots are occupied, then release - // every request one by one. - tokio::task::spawn_blocking(move || { - filled_rx.recv().unwrap(); - for _ in 0..total_stores { - release_tx.send(()).unwrap(); - } - }) - .await - .unwrap(); - - for task in tasks { - task.await.unwrap().unwrap(); - } - server.join().unwrap(); - assert_eq!(max_in_flight.load(Ordering::SeqCst), MAX_CONCURRENT_STORES); - } - #[tokio::test] async fn network_errors_leave_out_the_url() { let endpoint = "http://user:password@127.0.0.1:0/projects/test?token=secret"; - let client = Client::with_retry(endpoint, Arc::new(Anonymous), NO_RETRY).unwrap(); + let client = Client::new(endpoint, Arc::new(Anonymous)).unwrap(); let error = client.fetch(b"k", b"s").await.unwrap_err(); assert!(matches!(error, Error::Network(_)), "{error:?}"); From d268418dba0eba01a27787e997d790f8360dcc52 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:09:15 +0800 Subject: [PATCH 4/9] refactor(cache): replace retry is_* predicates with RetryHint and OutagePhase enums Co-authored-by: Gemini 4 Neon --- crates/vt/src/session/cache/remote.rs | 79 +++---- crates/vt/src/session/cache/remote/retry.rs | 219 +++++++++++--------- crates/vt_remote_cache/README.md | 2 +- crates/vt_remote_cache/src/lib.rs | 114 +++++----- 4 files changed, 198 insertions(+), 216 deletions(-) diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index a8e69980b..0f3999249 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -19,7 +19,7 @@ use std::{ fs::File, io::{self, Read as _, Write as _}, sync::{Arc, Mutex, OnceLock, PoisonError}, - time::{Duration, Instant}, + time::Instant, }; use bytes::Bytes; @@ -33,7 +33,7 @@ use vt_plan::{ remote_cache::{RemoteCacheAuth, ResolvedRemoteCacheConfig}, }; use vt_remote_cache::{ - Client, Download, Entry, Fetched, + Client, Download, Entry, Fetched, RetryHint, auth::{Anonymous, Auth, GithubOidc}, }; use vt_str::Str; @@ -42,7 +42,7 @@ use wincode::{ error::{WriteError, WriteResult}, }; -use self::retry::{OutageBreaker, RateLimit, RetryConfig, RetryableError}; +use self::retry::{OutageBreaker, RateLimit, RetryAction, RetryConfig, RetryableError}; use super::{ BaselineDetails, CACHE_SCHEMA_VERSION, CacheEntryKey, CacheEntryValue, CacheMiss, Checked, Comparison, TaskCacheConfig, archive, deserialize_cache, serialize_cache, @@ -77,30 +77,13 @@ pub enum UploadError { } impl RetryableError for UploadError { - fn is_retryable(&self) -> bool { - matches!(self, Self::Remote(err) if err.is_retryable()) - } - - fn is_outage(&self) -> bool { - matches!(self, Self::Remote(err) if err.is_outage()) - } - - fn is_rate_limited(&self) -> bool { - matches!(self, Self::Remote(err) if err.is_rate_limited()) - } - - fn is_cancelled(&self) -> bool { - matches!(self, Self::Interrupted) - } - - fn retry_after(&self) -> Option { + fn retry_action(&self) -> RetryAction { match self { - Self::Remote(err) => err.retry_after(), - Self::Encode(_) - | Self::Compress(_) - | Self::TooLarge - | Self::Interrupted - | Self::Unavailable => None, + Self::Remote(err) => RetryAction::Failed(err.retry_hint()), + Self::Interrupted => RetryAction::Cancelled, + Self::Encode(_) | Self::Compress(_) | Self::TooLarge | Self::Unavailable => { + RetryAction::Failed(RetryHint::Permanent) + } } } @@ -145,25 +128,10 @@ pub enum ReadError { } impl RetryableError for ReadError { - fn is_retryable(&self) -> bool { - matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_retryable()) - } - - fn is_outage(&self) -> bool { - matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_outage()) - } - - fn is_rate_limited(&self) -> bool { - matches!(self, Self::Fetch(err) | Self::Download(err) if err.is_rate_limited()) - } - - fn is_cancelled(&self) -> bool { - matches!(self, Self::Cancelled) - } - - fn retry_after(&self) -> Option { + fn retry_action(&self) -> RetryAction { match self { - Self::Fetch(err) | Self::Download(err) => err.retry_after(), + Self::Fetch(err) | Self::Download(err) => RetryAction::Failed(err.retry_hint()), + Self::Cancelled => RetryAction::Cancelled, Self::CorruptValue(_) | Self::CorruptKey(_) | Self::MismatchedBlob @@ -171,8 +139,7 @@ impl RetryableError for ReadError { | Self::WriteArchive(_) | Self::Validate(_) | Self::Encode(_) - | Self::Cancelled - | Self::Unavailable => None, + | Self::Unavailable => RetryAction::Failed(RetryHint::Permanent), } } @@ -1608,7 +1575,10 @@ mod tests { let clients = RemoteClients::with_retry(retry); let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); - assert!(matches!(err, UploadError::Remote(ref r) if r.is_rate_limited()), "{err:?}"); + assert!( + matches!(err, UploadError::Remote(ref r) if matches!(r.retry_hint(), RetryHint::RateLimited { .. })), + "{err:?}" + ); let key = cache_key(ResolvedGlobConfig::default_auto()); let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); @@ -1666,7 +1636,10 @@ mod tests { let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); - assert!(matches!(err, UploadError::Remote(ref r) if r.is_outage()), "{err:?}"); + assert!( + matches!(err, UploadError::Remote(ref r) if r.retry_hint() == RetryHint::Outage), + "{err:?}" + ); // A successful fetch must not reset consecutive store failures. assert_eq!( clients @@ -1676,7 +1649,10 @@ mod tests { None ); let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); - assert!(matches!(err, UploadError::Remote(ref r) if r.is_outage()), "{err:?}"); + assert!( + matches!(err, UploadError::Remote(ref r) if r.retry_hint() == RetryHint::Outage), + "{err:?}" + ); // Store breaker is now open, but reads still reach the server. assert_eq!( @@ -1696,7 +1672,10 @@ mod tests { .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) .await .unwrap_err(); - assert!(matches!(err, ReadError::Fetch(ref r) if r.is_outage()), "{err:?}"); + assert!( + matches!(err, ReadError::Fetch(ref r) if r.retry_hint() == RetryHint::Outage), + "{err:?}" + ); } server.join().unwrap(); diff --git a/crates/vt/src/session/cache/remote/retry.rs b/crates/vt/src/session/cache/remote/retry.rs index 1f563bf23..15f83343d 100644 --- a/crates/vt/src/session/cache/remote/retry.rs +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -9,6 +9,7 @@ use std::{ }; use tokio::time::Instant; +use vt_remote_cache::RetryHint; /// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response. pub(super) const MAX_RETRY_AFTER: Duration = Duration::from_secs(10); @@ -23,21 +24,21 @@ const OUTAGE_FAILURE_THRESHOLD: u32 = 3; /// How long the circuit breaker stays open before permitting one probe request. const OUTAGE_COOLDOWN: Duration = Duration::from_secs(30); -/// Classification of an attempt's error for retry, `429` cooldown, and -/// circuit-breaker handling. +/// Mutually exclusive disposition of an attempt's error for retry, `429` +/// cooldown, and circuit-breaker handling. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum RetryAction { + /// Locally cancelled: stop immediately without updating circuit-breaker + /// success/failure counts (an unfinished probe still re-opens on drop). + Cancelled, + /// Protocol-level retry classification from [`RetryHint`]. + Failed(RetryHint), +} + +/// Error types that can participate in [`run`]. pub(super) trait RetryableError: Debug { - /// Whether this error is transient and safe to retry. - fn is_retryable(&self) -> bool; - /// Whether this error indicates a backend outage (network errors and - /// retryable `5xx`, excluding `429`, client errors, and local failures). - fn is_outage(&self) -> bool; - /// Whether this error is a `429 Too Many Requests` response. - fn is_rate_limited(&self) -> bool; - /// Whether the operation was cancelled locally and must neither retry nor - /// update outage circuit-breaker success/failure counts. - fn is_cancelled(&self) -> bool; - /// Parsed `Retry-After` delay from the server response, if any. - fn retry_after(&self) -> Option; + /// Classify this error into its mutually exclusive [`RetryAction`]. + fn retry_action(&self) -> RetryAction; /// Error returned when the outage circuit breaker is open. fn unavailable() -> Self; } @@ -176,23 +177,32 @@ pub(super) struct OutageBreaker { state: Mutex, } -#[derive(Debug, Default)] +#[derive(Debug)] struct OutageState { - failures: u32, - open_until: Option, - probing: bool, + phase: OutagePhase, generation: u64, } +#[derive(Debug)] +enum OutagePhase { + Closed { failures: u32 }, + Open { until: Instant }, + HalfOpen, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum OutageOutcome { + Healthy, + Outage, +} + impl OutageBreaker { pub const fn new(threshold: u32, cooldown: Duration) -> Self { Self { threshold, cooldown, state: Mutex::new(OutageState { - failures: 0, - open_until: None, - probing: false, + phase: OutagePhase::Closed { failures: 0 }, generation: 0, }), } @@ -210,14 +220,13 @@ impl OutageBreaker { }); } let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - let probe = if let Some(until) = state.open_until { - if Instant::now() < until || state.probing { - return None; + let probe = match state.phase { + OutagePhase::Closed { .. } => false, + OutagePhase::Open { until } if Instant::now() >= until => { + state.phase = OutagePhase::HalfOpen; + true } - state.probing = true; - true - } else { - false + OutagePhase::Open { .. } | OutagePhase::HalfOpen => return None, }; let generation = state.generation; drop(state); @@ -240,32 +249,45 @@ impl OutagePermit<'_> { self.probe } - pub fn finish(mut self, outage: bool) { + pub fn finish(mut self, outcome: OutageOutcome) { if self.completed { return; } let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); if state.generation == self.generation { - if outage { - state.failures = state.failures.saturating_add(1); - if self.probe || state.failures >= self.breaker.threshold { - state.open_until = Some(Instant::now() + self.breaker.cooldown); - state.probing = false; + match (&mut state.phase, outcome) { + (OutagePhase::Closed { failures }, OutageOutcome::Outage) => { + *failures = failures.saturating_add(1); + if *failures >= self.breaker.threshold { + let count = *failures; + state.phase = + OutagePhase::Open { until: Instant::now() + self.breaker.cooldown }; + state.generation = state.generation.wrapping_add(1); + tracing::debug!( + failures = count, + cooldown = ?self.breaker.cooldown, + "remote cache circuit opened after repeated failures" + ); + } + } + (OutagePhase::Closed { failures }, OutageOutcome::Healthy) => { + *failures = 0; + } + (OutagePhase::HalfOpen, OutageOutcome::Outage) => { + state.phase = + OutagePhase::Open { until: Instant::now() + self.breaker.cooldown }; state.generation = state.generation.wrapping_add(1); tracing::debug!( - failures = state.failures, cooldown = ?self.breaker.cooldown, - "remote cache circuit opened after repeated failures" + "remote cache circuit re-opened after probe failed" ); } - } else { - state.failures = 0; - if self.probe { - state.open_until = None; - state.probing = false; + (OutagePhase::HalfOpen, OutageOutcome::Healthy) => { + state.phase = OutagePhase::Closed { failures: 0 }; state.generation = state.generation.wrapping_add(1); tracing::debug!("remote cache circuit closed after probe succeeded"); } + (OutagePhase::Open { .. }, _) => {} } } drop(state); @@ -277,9 +299,9 @@ impl Drop for OutagePermit<'_> { fn drop(&mut self) { if self.probe && !self.completed { let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); - if state.generation == self.generation { - state.probing = false; - state.open_until = Some(Instant::now() + self.breaker.cooldown); + if state.generation == self.generation && matches!(state.phase, OutagePhase::HalfOpen) { + state.phase = OutagePhase::Open { until: Instant::now() + self.breaker.cooldown }; + state.generation = state.generation.wrapping_add(1); } } } @@ -311,40 +333,35 @@ where rate_limit.wait().await; match attempt_fn().await { Ok(value) => { - permit.finish(false); + permit.finish(OutageOutcome::Healthy); return Ok(value); } - Err(error) => { - if error.is_cancelled() { + Err(error) => match error.retry_action() { + RetryAction::Cancelled => { // Drop `permit` without finishing so cancelling a probe // re-opens the cooldown and cancelling a normal request // does not reset consecutive failures. return Err(error); } - let is_rate_limited = error.is_rate_limited(); - let backoff = policy.delay(attempt); - // Floor 429 cooldowns at `backoff` so `Retry-After: 0` cannot - // trigger an immediate tight retry loop. - let cooldown = if is_rate_limited { - error - .retry_after() - .map_or(backoff, |delay| delay.min(policy.max_retry_after).max(backoff)) - } else { - backoff - }; - if is_rate_limited { + RetryAction::Failed(RetryHint::Permanent) => { + permit.finish(OutageOutcome::Healthy); + return Err(error); + } + RetryAction::Failed(RetryHint::RateLimited { retry_after }) => { + let backoff = policy.delay(attempt); + // Floor 429 cooldowns at `backoff` so `Retry-After: 0` cannot + // trigger an immediate tight retry loop. + let cooldown = retry_after + .map_or(backoff, |delay| delay.min(policy.max_retry_after).max(backoff)); // Publish the cooldown even on the last attempt so concurrent // requests pause instead of immediately hitting the same 429. rate_limit.record(cooldown); - } - let next_wait = if is_rate_limited { cooldown } else { backoff }; - let budget_exhausted = - started.elapsed().saturating_add(next_wait) >= policy.max_elapsed; - if attempt + 1 >= total_attempts || !error.is_retryable() || budget_exhausted { - permit.finish(error.is_outage()); - return Err(error); - } - if is_rate_limited { + if attempt + 1 >= total_attempts + || started.elapsed().saturating_add(cooldown) >= policy.max_elapsed + { + permit.finish(OutageOutcome::Healthy); + return Err(error); + } tracing::debug!( operation, attempt = attempt + 1, @@ -353,7 +370,21 @@ where ?error, "retrying remote cache request after 429 cooldown" ); - } else { + } + RetryAction::Failed(hint @ (RetryHint::Transient | RetryHint::Outage)) => { + let backoff = policy.delay(attempt); + if attempt + 1 >= total_attempts + || started.elapsed().saturating_add(backoff) >= policy.max_elapsed + { + let outcome = match hint { + RetryHint::Outage => OutageOutcome::Outage, + RetryHint::Transient + | RetryHint::Permanent + | RetryHint::RateLimited { .. } => OutageOutcome::Healthy, + }; + permit.finish(outcome); + return Err(error); + } tracing::debug!( operation, attempt = attempt + 1, @@ -364,7 +395,7 @@ where ); sleep(backoff).await; } - } + }, } } unreachable!("total_attempts is always at least 1") @@ -418,24 +449,11 @@ mod tests { } impl RetryableError for TestError { - fn is_retryable(&self) -> bool { - matches!(self, Self::Outage) - } - - fn is_outage(&self) -> bool { - matches!(self, Self::Outage) - } - - fn is_rate_limited(&self) -> bool { - false - } - - fn is_cancelled(&self) -> bool { - matches!(self, Self::Cancelled) - } - - fn retry_after(&self) -> Option { - None + fn retry_action(&self) -> RetryAction { + match self { + Self::Outage => RetryAction::Failed(RetryHint::Outage), + Self::Cancelled => RetryAction::Cancelled, + } } fn unavailable() -> Self { @@ -443,6 +461,11 @@ mod tests { } } + fn expire_open(breaker: &OutageBreaker) { + breaker.state.lock().unwrap().phase = + OutagePhase::Open { until: Instant::now() - Duration::from_secs(1) }; + } + #[test] fn equal_jitter_stays_within_half_to_full_bounds() { assert_eq!(equal_jitter(Duration::ZERO), Duration::ZERO); @@ -484,19 +507,19 @@ mod tests { let breaker = OutageBreaker::new(3, Duration::from_secs(30)); // Non-outage failure (e.g., 429) resets consecutive failure count. - breaker.enter().unwrap().finish(true); - breaker.enter().unwrap().finish(true); - breaker.enter().unwrap().finish(false); + breaker.enter().unwrap().finish(OutageOutcome::Outage); + breaker.enter().unwrap().finish(OutageOutcome::Outage); + breaker.enter().unwrap().finish(OutageOutcome::Healthy); assert!(breaker.enter().is_some()); // Three consecutive outage failures open the circuit. for _ in 0..3 { - breaker.enter().unwrap().finish(true); + breaker.enter().unwrap().finish(OutageOutcome::Outage); } assert!(breaker.enter().is_none()); // Expire cooldown: exactly one half-open probe is admitted. - breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + expire_open(&breaker); let dropped_probe = breaker.enter().unwrap(); assert!(dropped_probe.is_probe()); assert!(breaker.enter().is_none()); @@ -505,13 +528,13 @@ mod tests { assert!(breaker.enter().is_none()); // Failed probe re-opens the circuit. - breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); - breaker.enter().unwrap().finish(true); + expire_open(&breaker); + breaker.enter().unwrap().finish(OutageOutcome::Outage); assert!(breaker.enter().is_none()); // Successful probe closes the circuit. - breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); - breaker.enter().unwrap().finish(false); + expire_open(&breaker); + breaker.enter().unwrap().finish(OutageOutcome::Healthy); assert!(breaker.enter().is_some()); assert!(breaker.enter().is_some()); } @@ -533,7 +556,7 @@ mod tests { assert!(breaker.enter().is_none()); // Expire cooldown and cancel the half-open probe: circuit must stay open. - breaker.state.lock().unwrap().open_until = Some(Instant::now() - Duration::from_secs(1)); + expire_open(&breaker); let err = run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, || async { Err(TestError::Cancelled) }) diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index 1101835cb..62d5caca4 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -14,7 +14,7 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta `Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. -Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error` exposes `is_retryable`, `is_outage`, `is_rate_limited`, and `retry_after` (parsed delta-seconds `Retry-After`) to inform those policies. +Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error::retry_hint` classifies failures into `RetryHint::{Permanent, Transient, RateLimited { retry_after }, Outage}` to inform those policies. reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 20-second per-attempt timeout. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index 923dd8148..d030f4ecc 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -83,65 +83,52 @@ pub enum Error { MalformedResponse(#[source] ciborium::de::Error), } -impl Error { - /// Whether this failure is transient and safe to retry for an idempotent - /// remote cache operation (`Network`, `408`, `429`, and retryable `5xx`). - #[must_use] - pub const fn is_retryable(&self) -> bool { - match self { - Self::Network(_) => true, - Self::Status { status, .. } => { - matches!(status.as_u16(), 408 | 429) || is_retryable_server_error(*status) - } - Self::InvalidEndpoint(_) - | Self::HttpClient(_) - | Self::ReadBlob(_) - | Self::Auth(_) - | Self::MalformedResponse(_) => false, - } - } - - /// Whether this failure indicates a backend outage (`Network` or retryable - /// `5xx`, excluding `429` rate limits and client errors). - #[must_use] - pub const fn is_outage(&self) -> bool { - match self { - Self::Network(_) => true, - Self::Status { status, .. } => is_retryable_server_error(*status), - Self::InvalidEndpoint(_) - | Self::HttpClient(_) - | Self::ReadBlob(_) - | Self::Auth(_) - | Self::MalformedResponse(_) => false, - } - } - - /// Whether the server responded with `429 Too Many Requests`. - #[must_use] - pub const fn is_rate_limited(&self) -> bool { - matches!(self, Self::Status { status, .. } if status.as_u16() == 429) - } +/// How a caller's retry, rate-limit, and circuit-breaker policy should treat a +/// failed remote cache request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RetryHint { + /// Permanent or local failure that should not be retried (such as `4xx` + /// other than `408`/`429`, `501`/`505`/`511`, auth, blob I/O, or malformed + /// responses). + Permanent, + /// Transient failure (`408 Request Timeout`) that can be retried with + /// per-request backoff without counting toward a backend outage breaker. + Transient, + /// `429 Too Many Requests`: retryable, and callers may coordinate a shared + /// cooldown across sibling requests using `retry_after` if present. + RateLimited { + /// Parsed delta-seconds `Retry-After` header, if present and valid. + retry_after: Option, + }, + /// Transport or server outage (`Network` or retryable `5xx`): retryable + /// with per-request backoff, and counts toward a backend outage breaker. + /// Intentionally omits `Retry-After` so coarse server headers on `503` do + /// not stall sibling requests. + Outage, +} - /// The parsed delta-seconds `Retry-After` header from an error response, - /// if any. +impl Error { + /// Classify this failure for a caller's retry, rate-limit, and + /// circuit-breaker policy. #[must_use] - pub const fn retry_after(&self) -> Option { + pub const fn retry_hint(&self) -> RetryHint { match self { - Self::Status { retry_after, .. } => *retry_after, + Self::Network(_) => RetryHint::Outage, + Self::Status { status, retry_after, .. } => match status.as_u16() { + 408 => RetryHint::Transient, + 429 => RetryHint::RateLimited { retry_after: *retry_after }, + 500 | 502..=504 | 506..=510 | 512..=599 => RetryHint::Outage, + _ => RetryHint::Permanent, + }, Self::InvalidEndpoint(_) | Self::HttpClient(_) | Self::ReadBlob(_) | Self::Auth(_) - | Self::Network(_) - | Self::MalformedResponse(_) => None, + | Self::MalformedResponse(_) => RetryHint::Permanent, } } } -const fn is_retryable_server_error(status: StatusCode) -> bool { - matches!(status.as_u16(), 500 | 502..=504 | 506..=510 | 512..=599) -} - /// The message in the body of an error response. #[derive(Debug, thiserror::Error)] #[error("{0}")] @@ -597,7 +584,7 @@ mod tests { } #[test] - fn error_retry_classification_handles_statuses_correctly() { + fn error_retry_hint_handles_statuses_correctly() { let status_err = |code: u16, retry_after: Option| Error::Status { status: StatusCode::from_u16(code).unwrap(), message: None, @@ -605,27 +592,20 @@ mod tests { }; for code in [500, 502, 503, 504, 520, 524] { let err = status_err(code, Some(Duration::from_secs(60))); - assert!(err.is_retryable(), "{code} should be retryable"); - assert!(err.is_outage(), "{code} should be an outage"); - assert!(!err.is_rate_limited(), "{code} is not 429"); - assert_eq!(err.retry_after(), Some(Duration::from_secs(60))); + assert_eq!(err.retry_hint(), RetryHint::Outage, "{code} should be an outage"); } - let err_408 = status_err(408, None); - assert!(err_408.is_retryable()); - assert!(!err_408.is_outage()); - assert!(!err_408.is_rate_limited()); - - let err_429 = status_err(429, Some(Duration::from_secs(5))); - assert!(err_429.is_retryable()); - assert!(!err_429.is_outage()); - assert!(err_429.is_rate_limited()); - assert_eq!(err_429.retry_after(), Some(Duration::from_secs(5))); - + assert_eq!(status_err(408, None).retry_hint(), RetryHint::Transient); + assert_eq!( + status_err(429, Some(Duration::from_secs(5))).retry_hint(), + RetryHint::RateLimited { retry_after: Some(Duration::from_secs(5)) } + ); + assert_eq!( + status_err(429, None).retry_hint(), + RetryHint::RateLimited { retry_after: None } + ); for code in [400, 401, 403, 404, 413, 501, 505, 511] { let err = status_err(code, None); - assert!(!err.is_retryable(), "{code} should not be retryable"); - assert!(!err.is_outage(), "{code} should not be an outage"); - assert!(!err.is_rate_limited()); + assert_eq!(err.retry_hint(), RetryHint::Permanent, "{code} should be permanent"); } } From 17baccd4861c3e55a5c275ef028734ad1e0769d5 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:26:55 +0800 Subject: [PATCH 5/9] test(cache): add deterministic zero-sleep remote cache resilience e2e tests Co-authored-by: Gemini 4 Neon --- Cargo.lock | 2 + crates/vt/src/session/cache/mod.rs | 11 +- crates/vt/src/session/cache/remote.rs | 24 +- crates/vt/src/session/cache/remote/retry.rs | 18 + crates/vt/src/session/mod.rs | 8 +- crates/vt_bin/Cargo.toml | 3 + crates/vt_bin/src/vtt/main.rs | 4 +- crates/vt_bin/src/vtt/mock_remote_cache.rs | 672 ++++++++++++++++++ .../remote_cache_resilience/package.json | 4 + .../remote_cache_resilience/snapshots.toml | 151 ++++ .../outage_circuit_breaker_per_kind.md | 61 ++ .../snapshots/retry_transient_failures.md | 60 ++ .../snapshots/upload_concurrency_cap.md | 36 + .../remote_cache_resilience/src/a.txt | 1 + .../remote_cache_resilience/vite-task.json | 97 +++ 15 files changed, 1135 insertions(+), 17 deletions(-) create mode 100644 crates/vt_bin/src/vtt/mock_remote_cache.rs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/src/a.txt create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/vite-task.json diff --git a/Cargo.lock b/Cargo.lock index ec8175b57..2870784c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5047,6 +5047,7 @@ dependencies = [ "anyhow", "async-trait", "cargo-platform", + "ciborium", "clap", "cow-utils", "cp_r", @@ -5059,6 +5060,7 @@ dependencies = [ "notify", "regex", "serde", + "serde_bytes", "serde_json", "shell-escape", "tempfile", diff --git a/crates/vt/src/session/cache/mod.rs b/crates/vt/src/session/cache/mod.rs index 820ad8ea6..ad0d9f257 100644 --- a/crates/vt/src/session/cache/mod.rs +++ b/crates/vt/src/session/cache/mod.rs @@ -39,6 +39,7 @@ use wincode::{ error::{ReadResult, WriteResult}, }; +pub use self::remote::NO_BACKOFF_ENV as REMOTE_CACHE_NO_BACKOFF_ENV; use self::remote::{ReadError, RemoteClients, RemoteUploads, Restore, UploadError}; use super::{ event::RunKind, @@ -575,6 +576,14 @@ impl Validation { impl ExecutionCache { #[tracing::instrument(level = "debug", skip_all)] pub fn load_from_path(path: &AbsolutePath) -> anyhow::Result { + Self::load_from_path_with_no_backoff(path, false) + } + + #[tracing::instrument(level = "debug", skip_all)] + pub fn load_from_path_with_no_backoff( + path: &AbsolutePath, + no_backoff: bool, + ) -> anyhow::Result { tracing::info!("Creating task cache directory at {}", path.as_path().display()); std::fs::create_dir_all(path)?; @@ -601,7 +610,7 @@ impl ExecutionCache { Ok(Self { conn: Mutex::new(conn), dir: path.to_absolute_path_buf(), - remote_clients: RemoteClients::default(), + remote_clients: RemoteClients::from_no_backoff(no_backoff), uploads: RemoteUploads::default(), }) } diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index 0f3999249..fa0bfdd4d 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -48,6 +48,12 @@ use super::{ Comparison, TaskCacheConfig, archive, deserialize_cache, serialize_cache, }; +/// If set, remote cache retries use zero backoff delay while keeping +/// production attempt counts and circuit-breaker thresholds. Internal: tests +/// set this so retry and circuit-breaker scenarios run deterministically +/// without sleeping. +pub const NO_BACKOFF_ENV: &str = "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF"; + /// Maximum number of concurrent remote cache uploads in flight per endpoint. /// /// Bounding uploads per endpoint shapes bursts against backends with @@ -372,6 +378,10 @@ impl Default for RemoteClients { } impl RemoteClients { + pub(super) fn from_no_backoff(no_backoff: bool) -> Self { + Self::with_retry(if no_backoff { RetryConfig::NO_BACKOFF } else { RetryConfig::DEFAULT }) + } + fn with_retry(retry: RetryConfig) -> Self { Self { clients: Mutex::new(FxHashMap::default()), retry } } @@ -759,19 +769,7 @@ mod tests { /// Zero-delay retry config with production attempt counts so tests /// exercise the full retry loop without sleeping. - const FAST_RETRY: RetryConfig = RetryConfig { - read: RetryPolicy { - base_delay: Duration::ZERO, - max_delay: Duration::ZERO, - ..RetryPolicy::READ - }, - store: RetryPolicy { - base_delay: Duration::ZERO, - max_delay: Duration::ZERO, - ..RetryPolicy::STORE - }, - ..RetryConfig::DEFAULT - }; + const FAST_RETRY: RetryConfig = RetryConfig::NO_BACKOFF; /// Single-attempt retry config for tests that expect immediate failure. const NO_RETRY: RetryConfig = RetryConfig { diff --git a/crates/vt/src/session/cache/remote/retry.rs b/crates/vt/src/session/cache/remote/retry.rs index 15f83343d..a2ab47c52 100644 --- a/crates/vt/src/session/cache/remote/retry.rs +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -113,6 +113,24 @@ impl RetryConfig { outage_threshold: OUTAGE_FAILURE_THRESHOLD, outage_cooldown: OUTAGE_COOLDOWN, }; + /// Zero-delay retry configuration with production attempt counts and + /// circuit-breaker thresholds, for deterministic tests without backoff + /// sleeps. + pub const NO_BACKOFF: Self = Self { + read: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + max_retry_after: Duration::ZERO, + ..RetryPolicy::READ + }, + store: RetryPolicy { + base_delay: Duration::ZERO, + max_delay: Duration::ZERO, + max_retry_after: Duration::ZERO, + ..RetryPolicy::STORE + }, + ..Self::DEFAULT + }; } /// Shared cooldown gate for `429 Too Many Requests` responses. diff --git a/crates/vt/src/session/mod.rs b/crates/vt/src/session/mod.rs index 16a8d596d..3f94046c9 100644 --- a/crates/vt/src/session/mod.rs +++ b/crates/vt/src/session/mod.rs @@ -10,7 +10,7 @@ use std::{ffi::OsStr, fmt::Debug, io::IsTerminal, rc::Rc, sync::Arc}; use anyhow::Context as _; pub use cache::{CacheMiss, Change, Comparison}; -use cache::{ExecutionCache, FileCheck}; +use cache::{ExecutionCache, FileCheck, REMOTE_CACHE_NO_BACKOFF_ENV}; use event::RunKind; use once_cell::sync::OnceCell; pub use reporter::ExitStatus; @@ -655,7 +655,11 @@ impl<'a> Session<'a> { /// /// Returns an error if the cache database cannot be loaded or created. pub fn cache(&self) -> anyhow::Result<&ExecutionCache> { - self.cache.get_or_try_init(|| ExecutionCache::load_from_path(&self.cache_path)) + let no_backoff = + self.envs.contains_key(EnvName::from_ref(OsStr::new(REMOTE_CACHE_NO_BACKOFF_ENV))); + self.cache.get_or_try_init(|| { + ExecutionCache::load_from_path_with_no_backoff(&self.cache_path, no_backoff) + }) } pub fn workspace_path(&self) -> Arc { diff --git a/crates/vt_bin/Cargo.toml b/crates/vt_bin/Cargo.toml index 3ad2c7986..930ba58b1 100644 --- a/crates/vt_bin/Cargo.toml +++ b/crates/vt_bin/Cargo.toml @@ -17,9 +17,12 @@ path = "src/vtt/main.rs" [dependencies] anyhow = { workspace = true } +ciborium = { workspace = true } ctrlc = { workspace = true } libc = { workspace = true } notify = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_bytes = { workspace = true } vt_pty_terminal_test_client = { workspace = true } async-trait = { workspace = true } clap = { workspace = true, features = ["derive"] } diff --git a/crates/vt_bin/src/vtt/main.rs b/crates/vt_bin/src/vtt/main.rs index 652835535..6738a5b4f 100644 --- a/crates/vt_bin/src/vtt/main.rs +++ b/crates/vt_bin/src/vtt/main.rs @@ -16,6 +16,7 @@ mod grep_file; mod hold_reads; mod list_dir; mod mkdir; +mod mock_remote_cache; mod pipe_stdin; mod pipe_stdout; mod print; @@ -41,7 +42,7 @@ fn main() { if args.len() < 2 { eprintln!("Usage: vtt [args...]"); eprintln!( - "Subcommands: barrier, check-tty, cp, exit, exit-on-ctrlc, fs, grep-file, hold-reads, list-dir, mkdir, pipe-stdin, pipe-stdout, print, print-color, print-cwd, print-env, print-file, read-link, read-stdin, replace-file-content, rm, small_dev_shm, stalled-remote-cache, stat-file, stat-many, symlink, touch-file, write-file" + "Subcommands: barrier, check-tty, cp, exit, exit-on-ctrlc, fs, grep-file, hold-reads, list-dir, mkdir, mock-remote-cache, pipe-stdin, pipe-stdout, print, print-color, print-cwd, print-env, print-file, read-link, read-stdin, replace-file-content, rm, small_dev_shm, stalled-remote-cache, stat-file, stat-many, symlink, touch-file, write-file" ); std::process::exit(1); } @@ -63,6 +64,7 @@ fn main() { "hold-reads" => hold_reads::run(&args[2..]), "list-dir" => list_dir::run(&args[2..]), "mkdir" => mkdir::run(&args[2..]), + "mock-remote-cache" => mock_remote_cache::run(&args[2..]), "pipe-stdin" => pipe_stdin::run(&args[2..]), "pipe-stdout" => pipe_stdout::run(&args[2..]), "print" => { diff --git a/crates/vt_bin/src/vtt/mock_remote_cache.rs b/crates/vt_bin/src/vtt/mock_remote_cache.rs new file mode 100644 index 000000000..cc38b23fa --- /dev/null +++ b/crates/vt_bin/src/vtt/mock_remote_cache.rs @@ -0,0 +1,672 @@ +use std::{ + collections::{BTreeMap, VecDeque}, + fmt::Write as _, + io::{Read as _, Write as _}, + net::{Shutdown, TcpListener, TcpStream}, + path::PathBuf, + sync::{Arc, Condvar, Mutex}, +}; + +const BASE_PATH: &str = "/projects/test"; + +/// `mock-remote-cache [options...] [...]` +/// +/// Runs `` with `VP_REMOTE_CACHE_URL` pointing at an in-process +/// loopback HTTP/1.1 remote cache server, then prints the recorded requests to +/// stderr and exits with the command's exit code. +/// +/// Options: +/// - `--state-dir `: Persist stored entries and blobs in `/state.cbor` +/// across invocations. +/// - `--fault =`: Inject a one-shot fault on `` (`/fetch`, +/// `/store`, or `/blob`). Multiple `--fault` flags for the same route are +/// consumed in FIFO order. Supported `` values: `503`, `429`, `drop`, +/// and `truncate` (for `/blob`). +/// - `--always-fail =`: Always apply `` to ``. +/// - `--hold-stores `: Hold incoming `POST /store` responses until `` +/// stores are simultaneously in flight (and `--release-after-fetches` has +/// been satisfied), then release them without sleeping. +/// - `--release-after-fetches `: Minimum number of `POST /fetch` requests +/// required before releasing held `POST /store` responses. +/// - `--summary`: Print sorted per-outcome counts (and `max_concurrent_stores` +/// when `--hold-stores` is set) instead of individual request lines. +pub fn run(args: &[String]) -> Result<(), Box> { + let mut args = args; + let mut state_dir: Option = None; + let mut faults: BTreeMap> = BTreeMap::new(); + let mut always_fail: BTreeMap = BTreeMap::new(); + let mut hold_stores: usize = 0; + let mut release_after_fetches: usize = 0; + let mut summary = false; + + loop { + match args { + [flag, dir, rest @ ..] if flag == "--state-dir" => { + state_dir = Some(PathBuf::from(dir)); + args = rest; + } + [flag, spec, rest @ ..] if flag == "--fault" => { + let (route, fault) = parse_fault_spec(spec)?; + faults.entry(route).or_default().push_back(fault); + args = rest; + } + [flag, spec, rest @ ..] if flag == "--always-fail" => { + let (route, fault) = parse_fault_spec(spec)?; + always_fail.insert(route, fault); + args = rest; + } + [flag, count, rest @ ..] if flag == "--hold-stores" => { + hold_stores = count.parse()?; + args = rest; + } + [flag, count, rest @ ..] if flag == "--release-after-fetches" => { + release_after_fetches = count.parse()?; + args = rest; + } + [flag, rest @ ..] if flag == "--summary" => { + summary = true; + args = rest; + } + _ => break, + } + } + + let [program, command_args @ ..] = args else { + return Err( + "Usage: vtt mock-remote-cache [--state-dir ] [--fault =]... [--always-fail =]... [--hold-stores ] [--release-after-fetches ] [--summary] [args...]" + .into(), + ); + }; + + let storage = match &state_dir { + Some(dir) => load_state(dir)?, + None => StoredState::default(), + }; + + let server = Arc::new(Server { + state_dir, + state: Mutex::new(ServerState { storage, faults, always_fail, log: Vec::new() }), + barrier: ( + Mutex::new(BarrierState { + hold_target: hold_stores, + release_after_fetches, + in_flight: 0, + max_in_flight: 0, + fetches: 0, + released: false, + }), + Condvar::new(), + ), + }); + + ctrlc::set_handler(|| {})?; + + let listener = TcpListener::bind("127.0.0.1:0")?; + let endpoint = std::format!("http://{}{BASE_PATH}", listener.local_addr()?); + { + let server = Arc::clone(&server); + std::thread::spawn(move || { + for stream in listener.incoming().filter_map(Result::ok) { + let server = Arc::clone(&server); + std::thread::spawn(move || server.serve(stream)); + } + }); + } + + let status = std::process::Command::new(program) + .args(command_args) + .env("VP_REMOTE_CACHE_URL", endpoint) + .status()?; + + if summary { + let mut counts: BTreeMap = BTreeMap::new(); + for line in &server.state.lock().unwrap().log { + *counts.entry(line.clone()).or_default() += 1; + } + for (line, count) in counts { + eprintln!("[remote-cache] {line} x{count}"); + } + if hold_stores > 0 { + let max_in_flight = server.barrier.0.lock().unwrap().max_in_flight; + eprintln!("[remote-cache] max_concurrent_stores={max_in_flight}"); + } + } else { + for line in &server.state.lock().unwrap().log { + eprintln!("[remote-cache] {line}"); + } + } + + std::process::exit(status.code().unwrap_or(1)); +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Route { + Fetch, + Store, + Blob, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Fault { + ServiceUnavailable, + TooManyRequests, + DropConnection, + TruncateBlob, +} + +fn parse_fault_spec(spec: &str) -> Result<(Route, Fault), Box> { + let (route, kind) = spec + .split_once('=') + .ok_or_else(|| std::format!("invalid fault spec '{spec}', expected ="))?; + let route = match route { + "/fetch" => Route::Fetch, + "/store" => Route::Store, + "/blob" => Route::Blob, + _ => return Err(std::format!("unknown route '{route}'").into()), + }; + let fault = match kind { + "503" => Fault::ServiceUnavailable, + "429" => Fault::TooManyRequests, + "drop" => Fault::DropConnection, + "truncate" => Fault::TruncateBlob, + _ => return Err(std::format!("unknown fault kind '{kind}'").into()), + }; + if fault == Fault::TruncateBlob && route != Route::Blob { + return Err("truncate fault is only valid for /blob".into()); + } + Ok((route, fault)) +} + +struct Server { + state_dir: Option, + state: Mutex, + barrier: (Mutex, Condvar), +} + +struct ServerState { + storage: StoredState, + faults: BTreeMap>, + always_fail: BTreeMap, + log: Vec, +} + +struct BarrierState { + hold_target: usize, + release_after_fetches: usize, + in_flight: usize, + max_in_flight: usize, + fetches: usize, + released: bool, +} + +impl BarrierState { + const fn should_release(&self) -> bool { + self.in_flight >= self.hold_target && self.fetches >= self.release_after_fetches + } +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct StoredState { + entries: Vec, + blobs: Vec>, +} + +#[derive(serde::Serialize, serde::Deserialize)] +struct StoredEntry { + #[serde(with = "serde_bytes")] + key: Vec, + #[serde(with = "serde_bytes")] + value: Vec, + blob_id: Option, +} + +#[derive(serde::Deserialize)] +struct FetchRequest { + #[serde(with = "serde_bytes")] + key: Vec, +} + +#[derive(serde::Deserialize)] +struct StoreMetadata { + #[serde(with = "serde_bytes")] + key: Vec, + #[serde(with = "serde_bytes")] + value: Vec, +} + +#[derive(serde::Serialize)] +struct ExactResponse<'a> { + kind: &'static str, + entries: Vec>, +} + +#[derive(serde::Serialize)] +struct ResponseEntry<'a> { + #[serde(with = "serde_bytes")] + value: &'a [u8], + blob_id: Option<&'a str>, +} + +fn state_file_path(dir: &std::path::Path) -> PathBuf { + dir.join("state.cbor") +} + +fn load_state(dir: &std::path::Path) -> Result> { + let path = state_file_path(dir); + if !path.exists() { + return Ok(StoredState::default()); + } + let bytes = std::fs::read(path)?; + Ok(ciborium::from_reader(bytes.as_slice())?) +} + +fn save_state( + dir: &std::path::Path, + state: &StoredState, +) -> Result<(), Box> { + std::fs::create_dir_all(dir)?; + let mut bytes = Vec::new(); + ciborium::into_writer(state, &mut bytes)?; + std::fs::write(state_file_path(dir), bytes)?; + Ok(()) +} + +impl Server { + fn next_fault(&self, route: Route) -> Option { + let mut state = self.state.lock().unwrap(); + if let Some(&fault) = state.always_fail.get(&route) { + return Some(fault); + } + state.faults.get_mut(&route).and_then(VecDeque::pop_front) + } + + fn record(&self, method: &str, route: &str, outcome: &str) { + self.state.lock().unwrap().log.push(std::format!("{method} {route} {outcome}")); + } + + fn serve(&self, mut stream: TcpStream) { + let Some(request) = read_request(&mut stream) else { + return; + }; + let path = request.target.split_once('?').map_or(request.target.as_str(), |(p, _)| p); + let route_str = path.strip_prefix(BASE_PATH).unwrap_or(path); + + match (request.method.as_str(), route_str) { + ("POST", "/fetch") => self.handle_fetch(&mut stream, &request.body), + ("POST", "/store") => { + self.handle_store(&mut stream, request.content_type.as_deref(), &request.body); + } + ("GET", rest) if rest.starts_with("/blob/") => { + let blob_id = &rest["/blob/".len()..]; + self.handle_blob(&mut stream, rest, blob_id); + } + _ => { + self.record(&request.method, route_str, "404"); + write_response(&mut stream, "HTTP/1.1 404 Not Found", &[], b""); + } + } + } + + fn handle_fetch(&self, stream: &mut TcpStream, body: &[u8]) { + if let Some(fault) = self.next_fault(Route::Fetch) { + self.apply_fault(stream, "POST", "/fetch", fault); + return; + } + + // Notify any held stores once enough fetches have arrived. + { + let mut barrier = self.barrier.0.lock().unwrap(); + barrier.fetches += 1; + let should_notify = + barrier.hold_target > 0 && !barrier.released && barrier.should_release(); + if should_notify { + barrier.released = true; + } + drop(barrier); + if should_notify { + self.barrier.1.notify_all(); + } + } + + let Ok(fetch) = ciborium::from_reader::(body) else { + self.record("POST", "/fetch", "400"); + write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid cbor"); + return; + }; + + let response_body = { + let mut state = self.state.lock().unwrap(); + let entries: Vec> = state + .storage + .entries + .iter() + .rev() + .filter(|entry| entry.key == fetch.key) + .map(|entry| ResponseEntry { + value: &entry.value, + blob_id: entry.blob_id.as_deref(), + }) + .collect(); + if entries.is_empty() { + state.log.push("POST /fetch 404".to_owned()); + drop(state); + None + } else { + let mut encoded = Vec::new(); + ciborium::into_writer(&ExactResponse { kind: "exact", entries }, &mut encoded) + .unwrap(); + state.log.push("POST /fetch 200".to_owned()); + drop(state); + Some(encoded) + } + }; + + if let Some(encoded) = response_body { + write_response( + stream, + "HTTP/1.1 200 OK", + &[("content-type", "application/cbor")], + &encoded, + ); + } else { + write_response(stream, "HTTP/1.1 404 Not Found", &[], b""); + } + } + + fn handle_store(&self, stream: &mut TcpStream, content_type: Option<&str>, body: &[u8]) { + if let Some(fault) = self.next_fault(Route::Store) { + self.apply_fault(stream, "POST", "/store", fault); + return; + } + + let Some(parts) = content_type.and_then(|ct| parse_multipart(ct, body)) else { + self.record("POST", "/store", "400"); + write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid multipart"); + return; + }; + let Ok(metadata) = ciborium::from_reader::(parts.metadata) else { + self.record("POST", "/store", "400"); + write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid metadata"); + return; + }; + + // Hold concurrent stores on the Condvar if configured, then decrement + // `in_flight` strictly BEFORE sending the response so the client + // cannot release its semaphore permit and overlap the next store. + { + let mut barrier = self.barrier.0.lock().unwrap(); + barrier.in_flight += 1; + barrier.max_in_flight = barrier.max_in_flight.max(barrier.in_flight); + if barrier.hold_target > 0 && !barrier.released { + if barrier.should_release() { + barrier.released = true; + self.barrier.1.notify_all(); + } else { + while !barrier.released { + barrier = self.barrier.1.wait(barrier).unwrap(); + } + } + } + barrier.in_flight -= 1; + } + + { + let mut state = self.state.lock().unwrap(); + let blob_id = parts.blob.map(|blob| { + state.storage.blobs.push(blob.to_vec()); + state.storage.blobs.len().to_string() + }); + state.storage.entries.push(StoredEntry { + key: metadata.key, + value: metadata.value, + blob_id, + }); + if let Some(dir) = &self.state_dir { + save_state(dir, &state.storage).unwrap(); + } + state.log.push("POST /store 200".to_owned()); + } + + write_response(stream, "HTTP/1.1 200 OK", &[], b""); + } + + fn handle_blob(&self, stream: &mut TcpStream, route: &str, blob_id: &str) { + let fault = self.next_fault(Route::Blob); + if let Some(fault) = fault + && fault != Fault::TruncateBlob + { + self.apply_fault(stream, "GET", route, fault); + return; + } + + let blob = { + let state = self.state.lock().unwrap(); + blob_id + .parse::() + .ok() + .and_then(|id| id.checked_sub(1)) + .and_then(|idx| state.storage.blobs.get(idx).cloned()) + }; + + let Some(blob) = blob else { + self.record("GET", route, "404"); + write_response(stream, "HTTP/1.1 404 Not Found", &[], b""); + return; + }; + + if fault == Some(Fault::TruncateBlob) { + let cut = (blob.len() / 2).min(blob.len().saturating_sub(1)); + self.record("GET", route, "truncate"); + let head = std::format!( + "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", + blob.len() + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&blob[..cut]); + let _ = stream.flush(); + let _ = stream.shutdown(Shutdown::Both); + return; + } + + self.record("GET", route, "200"); + write_response(stream, "HTTP/1.1 200 OK", &[], &blob); + } + + fn apply_fault(&self, stream: &mut TcpStream, method: &str, route: &str, fault: Fault) { + match fault { + Fault::ServiceUnavailable => { + self.record(method, route, "503"); + write_response( + stream, + "HTTP/1.1 503 Service Unavailable", + &[("retry-after", "60")], + b"busy", + ); + } + Fault::TooManyRequests => { + self.record(method, route, "429"); + write_response( + stream, + "HTTP/1.1 429 Too Many Requests", + &[("retry-after", "5")], + b"rate limited", + ); + } + Fault::DropConnection => { + self.record(method, route, "drop"); + let _ = stream.shutdown(Shutdown::Both); + } + Fault::TruncateBlob => unreachable!("truncate is handled in handle_blob"), + } + } +} + +struct HttpRequest { + method: String, + target: String, + content_type: Option, + body: Vec, +} + +fn read_request(stream: &mut TcpStream) -> Option { + let mut raw = Vec::new(); + let mut buf = [0; 4096]; + let header_end = loop { + let n = stream.read(&mut buf).ok()?; + if n == 0 { + return None; + } + raw.extend_from_slice(&buf[..n]); + if let Some(pos) = raw.windows(4).position(|window| window == b"\r\n\r\n") { + break pos + 4; + } + }; + + let head = std::str::from_utf8(&raw[..header_end - 4]).ok()?; + let mut lines = head.split("\r\n"); + let request_line = lines.next()?; + let mut parts = request_line.split(' '); + let method = parts.next()?.to_owned(); + let target = parts.next()?.to_owned(); + + let mut content_length: Option = None; + let mut content_type: Option = None; + let mut chunked = false; + + for line in lines { + let Some((name, value)) = line.split_once(':') else { + continue; + }; + let name = name.trim(); + let value = value.trim(); + if name.eq_ignore_ascii_case("content-length") { + content_length = value.parse().ok(); + } else if name.eq_ignore_ascii_case("content-type") { + content_type = Some(value.to_owned()); + } else if name.eq_ignore_ascii_case("transfer-encoding") + && value.to_ascii_lowercase().contains("chunked") + { + chunked = true; + } + } + + let mut body = raw.split_off(header_end); + if let Some(expected) = content_length { + while body.len() < expected { + let n = stream.read(&mut buf).ok()?; + if n == 0 { + return None; + } + body.extend_from_slice(&buf[..n]); + } + body.truncate(expected); + } else if chunked { + body = read_chunked_body(stream, body)?; + } + + Some(HttpRequest { method, target, content_type, body }) +} + +fn read_chunked_body(stream: &mut TcpStream, mut buffered: Vec) -> Option> { + let mut decoded = Vec::new(); + let mut cursor = 0; + let mut buf = [0; 4096]; + loop { + let line_end = loop { + if let Some(rel) = buffered[cursor..].windows(2).position(|w| w == b"\r\n") { + break cursor + rel; + } + let n = stream.read(&mut buf).ok()?; + if n == 0 { + return None; + } + buffered.extend_from_slice(&buf[..n]); + }; + let size_str = std::str::from_utf8(&buffered[cursor..line_end]).ok()?; + let size_hex = size_str.split(';').next()?.trim(); + let size = usize::from_str_radix(size_hex, 16).ok()?; + cursor = line_end + 2; + if size == 0 { + return Some(decoded); + } + while buffered.len() < cursor + size + 2 { + let n = stream.read(&mut buf).ok()?; + if n == 0 { + return None; + } + buffered.extend_from_slice(&buf[..n]); + } + decoded.extend_from_slice(&buffered[cursor..cursor + size]); + cursor += size + 2; + } +} + +struct StoreParts<'a> { + metadata: &'a [u8], + blob: Option<&'a [u8]>, +} + +fn parse_multipart<'a>(content_type: &str, body: &'a [u8]) -> Option> { + let boundary = content_type.split(';').find_map(|param| { + let (name, value) = param.trim().split_once('=')?; + name.eq_ignore_ascii_case("boundary").then(|| value.trim().trim_matches('"')) + })?; + let delimiter = std::format!("--{boundary}"); + let delimiter = delimiter.as_bytes(); + + let mut metadata = None; + let mut blob = None; + let mut pos = find_subslice(body, delimiter)?; + + loop { + pos += delimiter.len(); + if body[pos..].starts_with(b"--") { + break; + } + if !body[pos..].starts_with(b"\r\n") { + return None; + } + pos += 2; + + let next = find_subslice(&body[pos..], delimiter)?; + let part = &body[pos..pos + next]; + let part = part.strip_suffix(b"\r\n").unwrap_or(part); + let head_end = find_subslice(part, b"\r\n\r\n")?; + let part_head = std::str::from_utf8(&part[..head_end]).ok()?; + let part_body = &part[head_end + 4..]; + + if part_head.contains("name=\"metadata\"") { + metadata = Some(part_body); + } else if part_head.contains("name=\"blob\"") { + blob = Some(part_body); + } + + pos += next; + } + + Some(StoreParts { metadata: metadata?, blob }) +} + +fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { + haystack.windows(needle.len()).position(|window| window == needle) +} + +fn write_response( + stream: &mut TcpStream, + status_line: &str, + headers: &[(&str, &str)], + body: &[u8], +) { + let mut head = std::format!("{status_line}\r\nconnection: close\r\n"); + for (name, value) in headers { + head.push_str(name); + head.push_str(": "); + head.push_str(value); + head.push_str("\r\n"); + } + let _ = write!(head, "content-length: {}\r\n\r\n", body.len()); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(body); + let _ = stream.flush(); + let _ = stream.shutdown(Shutdown::Both); +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/package.json new file mode 100644 index 000000000..f3cb89c49 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/package.json @@ -0,0 +1,4 @@ +{ + "name": "remote-cache-resilience", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml new file mode 100644 index 000000000..f61167222 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml @@ -0,0 +1,151 @@ +# Deterministic, zero-sleep e2e tests for remote cache resilience: transient +# retry (fetch, store, blob download), per-kind outage circuit breaking, and +# bounded concurrent uploads. All cases use `vtt mock-remote-cache` directly so +# they run in the default Rust test suite on Unix (including musl) and Windows. + +[[e2e]] +name = "retry_transient_failures" +comment = "Transient 503, 429, connection-drop, and truncated-download errors are retried across fetch, store, and blob restore." +steps = [ + { argv = [ + "vtt", + "mock-remote-cache", + "--state-dir", + ".mock-cache", + "--fault", + "/fetch=503", + "--fault", + "/fetch=drop", + "--fault", + "/store=503", + "--fault", + "/store=429", + "--fault", + "/store=drop", + "vt", + "run", + "build", + ], envs = [ + [ + "VP_REMOTE_CACHE", + "read-write", + ], + [ + "VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS", + "1", + ], + [ + "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF", + "1", + ], + ], comment = "Fetch recovers from 503 and connection drop to receive 404. Store retries 503, 429, and connection drop, re-streaming the output archive until 200." }, + [ + "vt", + "cache", + "clean", + ], + [ + "vtt", + "rm", + "-rf", + "dist", + ], + { argv = [ + "vtt", + "mock-remote-cache", + "--state-dir", + ".mock-cache", + "--fault", + "/fetch=503", + "--fault", + "/blob=503", + "--fault", + "/blob=truncate", + "vt", + "run", + "build", + ], envs = [ + [ + "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF", + "1", + ], + ], comment = "Fetch retries 503 and hits the stored entry. Blob download retries 503 and a mid-stream truncation, then restores the output." }, + { argv = [ + "vtt", + "print-file", + "dist/output.txt", + ], comment = "The retried upload and retried download restored the output file." }, + { argv = [ + "vtt", + "list-dir", + "node_modules/.vite/task-cache", + "--ext", + ".tmp", + "--recursive", + ], comment = "No temporary download file was left behind after the truncated attempt." }, +] + +[[e2e]] +name = "outage_circuit_breaker_per_kind" +comment = "Three consecutive exhausted read failures open the read circuit breaker without blocking uploads, and successful uploads do not reset read failures." +steps = [ + { argv = [ + "vtt", + "mock-remote-cache", + "--always-fail", + "/fetch=503", + "--summary", + "vt", + "run", + "step4", + ], envs = [ + [ + "VP_REMOTE_CACHE", + "read-write", + ], + [ + "VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS", + "1", + ], + [ + "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF", + "1", + ], + ], comment = "step1..step3 exhaust 3 fetch attempts each (9 total) and open the read breaker. step4 skips the fetch request, while all 4 stores succeed." }, + { argv = [ + "vt", + "run", + "--last-details", + ], comment = "step1..step3 report HTTP status 503; step4 reports remote cache temporarily unavailable; no upload warnings." }, +] + +[[e2e]] +name = "upload_concurrency_cap" +comment = "At most 4 concurrent remote cache uploads are in flight at once, and full upload slots do not block fetches." +steps = [ + { argv = [ + "vtt", + "mock-remote-cache", + "--hold-stores", + "4", + "--release-after-fetches", + "7", + "--summary", + "vt", + "run", + "t7", + ], envs = [ + [ + "VP_REMOTE_CACHE", + "read-write", + ], + [ + "VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS", + "1", + ], + [ + "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF", + "1", + ], + ], comment = "The mock server holds stores on a Condvar until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4." }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md new file mode 100644 index 000000000..308b6f374 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md @@ -0,0 +1,61 @@ +# outage_circuit_breaker_per_kind + +Three consecutive exhausted read failures open the read circuit breaker without blocking uploads, and successful uploads do not reset read failures. + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --always-fail /fetch=503 --summary vt run step4` + +step1..step3 exhaust 3 fetch attempts each (9 total) and open the read breaker. step4 skips the fetch request, while all 4 stores succeed. + +``` +$ vtt print step1 ○ cache miss: remote cache fetch failed, executing +step1 + +$ vtt print step2 ○ cache miss: remote cache fetch failed, executing +step2 + +$ vtt print step3 ○ cache miss: remote cache fetch failed, executing +step3 + +$ vtt print step4 ○ cache miss: remote cache temporarily unavailable, executing +step4 + +--- +vt run: 0/4 cache hit (0%), 4/4 successful. (Run `vt run --last-details` for full details) +[remote-cache] POST /fetch 503 x9 +[remote-cache] POST /store 200 x4 +``` + +## `vt run --last-details` + +step1..step3 report HTTP status 503; step4 reports remote cache temporarily unavailable; no upload warnings. + +``` + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 4 tasks • 0 cache hits • 4 cache misses +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] remote-cache-resilience#step1: $ vtt print step1 ✓ + → Cache miss: remote cache fetch failed + ↳ HTTP status 503 + ↳ busy + ······················································· + [2] remote-cache-resilience#step2: $ vtt print step2 ✓ + → Cache miss: remote cache fetch failed + ↳ HTTP status 503 + ↳ busy + ······················································· + [3] remote-cache-resilience#step3: $ vtt print step3 ✓ + → Cache miss: remote cache fetch failed + ↳ HTTP status 503 + ↳ busy + ······················································· + [4] remote-cache-resilience#step4: $ vtt print step4 ✓ + → Cache miss: remote cache temporarily unavailable +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md new file mode 100644 index 000000000..d6b99e150 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md @@ -0,0 +1,60 @@ +# retry_transient_failures + +Transient 503, 429, connection-drop, and truncated-download errors are retried across fetch, store, and blob restore. + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --state-dir .mock-cache --fault /fetch=503 --fault /fetch=drop --fault /store=503 --fault /store=429 --fault /store=drop vt run build` + +Fetch recovers from 503 and connection drop to receive 404. Store retries 503, 429, and connection drop, re-streaming the output archive until 200. + +``` +$ vtt write-file dist/output.txt built + +[remote-cache] POST /fetch 503 +[remote-cache] POST /fetch drop +[remote-cache] POST /fetch 404 +[remote-cache] POST /store 503 +[remote-cache] POST /store 429 +[remote-cache] POST /store drop +[remote-cache] POST /store 200 +``` + +## `vt cache clean` + +``` +``` + +## `vtt rm -rf dist` + +``` +``` + +## `VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --state-dir .mock-cache --fault /fetch=503 --fault /blob=503 --fault /blob=truncate vt run build` + +Fetch retries 503 and hits the stored entry. Blob download retries 503 and a mid-stream truncation, then restores the output. + +``` +$ vtt write-file dist/output.txt built ◉ remote cache hit, replaying + +--- +vt run: remote cache hit. +[remote-cache] POST /fetch 503 +[remote-cache] POST /fetch 200 +[remote-cache] GET /blob/1 503 +[remote-cache] GET /blob/1 truncate +[remote-cache] GET /blob/1 200 +``` + +## `vtt print-file dist/output.txt` + +The retried upload and retried download restored the output file. + +``` +built +``` + +## `vtt list-dir node_modules/.vite/task-cache --ext .tmp --recursive` + +No temporary download file was left behind after the truncated attempt. + +``` +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md new file mode 100644 index 000000000..22e8155a8 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md @@ -0,0 +1,36 @@ +# upload_concurrency_cap + +At most 4 concurrent remote cache uploads are in flight at once, and full upload slots do not block fetches. + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --hold-stores 4 --release-after-fetches 7 --summary vt run t7` + +The mock server holds stores on a Condvar until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4. + +``` +$ vtt print t1 +t1 + +$ vtt print t2 +t2 + +$ vtt print t3 +t3 + +$ vtt print t4 +t4 + +$ vtt print t5 +t5 + +$ vtt print t6 +t6 + +$ vtt print t7 +t7 + +--- +vt run: 0/7 cache hit (0%), 7/7 successful. (Run `vt run --last-details` for full details) +[remote-cache] POST /fetch 404 x7 +[remote-cache] POST /store 200 x7 +[remote-cache] max_concurrent_stores=4 +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/src/a.txt b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/src/a.txt new file mode 100644 index 000000000..ce0136250 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/src/a.txt @@ -0,0 +1 @@ +hello diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/vite-task.json new file mode 100644 index 000000000..4a3a84171 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/vite-task.json @@ -0,0 +1,97 @@ +{ + "tasks": { + "build": { + "command": "vtt write-file dist/output.txt built", + "cache": { + "input": ["src/**"], + "output": ["dist/**"] + } + }, + "step1": { + "command": "vtt print step1", + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "step2": { + "command": "vtt print step2", + "dependsOn": ["step1"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "step3": { + "command": "vtt print step3", + "dependsOn": ["step2"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "step4": { + "command": "vtt print step4", + "dependsOn": ["step3"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t1": { + "command": "vtt print t1", + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t2": { + "command": "vtt print t2", + "dependsOn": ["t1"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t3": { + "command": "vtt print t3", + "dependsOn": ["t2"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t4": { + "command": "vtt print t4", + "dependsOn": ["t3"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t5": { + "command": "vtt print t5", + "dependsOn": ["t4"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t6": { + "command": "vtt print t6", + "dependsOn": ["t5"], + "cache": { + "input": ["src/**"], + "output": [] + } + }, + "t7": { + "command": "vtt print t7", + "dependsOn": ["t6"], + "cache": { + "input": ["src/**"], + "output": [] + } + } + } +} From b8b284787ec597dbea2e18901e2d6f21c24d59b3 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:35:55 +0800 Subject: [PATCH 6/9] test(cache): move resilience e2e fault injection into remote-cache-server tap Co-authored-by: Gemini 4 Neon --- Cargo.lock | 2 - crates/vt_bin/Cargo.toml | 3 - crates/vt_bin/src/vtt/main.rs | 4 +- crates/vt_bin/src/vtt/mock_remote_cache.rs | 672 ------------------ .../remote_cache_resilience/snapshots.toml | 60 +- .../outage_circuit_breaker_per_kind.md | 12 +- .../snapshots/retry_transient_failures.md | 16 +- .../snapshots/upload_concurrency_cap.md | 14 +- packages/tools/README.md | 2 +- packages/tools/src/remote-cache/cli.ts | 113 ++- packages/tools/src/remote-cache/daemon.ts | 281 ++++++-- packages/tools/src/remote-cache/state.ts | 18 + 12 files changed, 435 insertions(+), 762 deletions(-) delete mode 100644 crates/vt_bin/src/vtt/mock_remote_cache.rs diff --git a/Cargo.lock b/Cargo.lock index 2870784c3..ec8175b57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5047,7 +5047,6 @@ dependencies = [ "anyhow", "async-trait", "cargo-platform", - "ciborium", "clap", "cow-utils", "cp_r", @@ -5060,7 +5059,6 @@ dependencies = [ "notify", "regex", "serde", - "serde_bytes", "serde_json", "shell-escape", "tempfile", diff --git a/crates/vt_bin/Cargo.toml b/crates/vt_bin/Cargo.toml index 930ba58b1..3ad2c7986 100644 --- a/crates/vt_bin/Cargo.toml +++ b/crates/vt_bin/Cargo.toml @@ -17,12 +17,9 @@ path = "src/vtt/main.rs" [dependencies] anyhow = { workspace = true } -ciborium = { workspace = true } ctrlc = { workspace = true } libc = { workspace = true } notify = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_bytes = { workspace = true } vt_pty_terminal_test_client = { workspace = true } async-trait = { workspace = true } clap = { workspace = true, features = ["derive"] } diff --git a/crates/vt_bin/src/vtt/main.rs b/crates/vt_bin/src/vtt/main.rs index 6738a5b4f..652835535 100644 --- a/crates/vt_bin/src/vtt/main.rs +++ b/crates/vt_bin/src/vtt/main.rs @@ -16,7 +16,6 @@ mod grep_file; mod hold_reads; mod list_dir; mod mkdir; -mod mock_remote_cache; mod pipe_stdin; mod pipe_stdout; mod print; @@ -42,7 +41,7 @@ fn main() { if args.len() < 2 { eprintln!("Usage: vtt [args...]"); eprintln!( - "Subcommands: barrier, check-tty, cp, exit, exit-on-ctrlc, fs, grep-file, hold-reads, list-dir, mkdir, mock-remote-cache, pipe-stdin, pipe-stdout, print, print-color, print-cwd, print-env, print-file, read-link, read-stdin, replace-file-content, rm, small_dev_shm, stalled-remote-cache, stat-file, stat-many, symlink, touch-file, write-file" + "Subcommands: barrier, check-tty, cp, exit, exit-on-ctrlc, fs, grep-file, hold-reads, list-dir, mkdir, pipe-stdin, pipe-stdout, print, print-color, print-cwd, print-env, print-file, read-link, read-stdin, replace-file-content, rm, small_dev_shm, stalled-remote-cache, stat-file, stat-many, symlink, touch-file, write-file" ); std::process::exit(1); } @@ -64,7 +63,6 @@ fn main() { "hold-reads" => hold_reads::run(&args[2..]), "list-dir" => list_dir::run(&args[2..]), "mkdir" => mkdir::run(&args[2..]), - "mock-remote-cache" => mock_remote_cache::run(&args[2..]), "pipe-stdin" => pipe_stdin::run(&args[2..]), "pipe-stdout" => pipe_stdout::run(&args[2..]), "print" => { diff --git a/crates/vt_bin/src/vtt/mock_remote_cache.rs b/crates/vt_bin/src/vtt/mock_remote_cache.rs deleted file mode 100644 index cc38b23fa..000000000 --- a/crates/vt_bin/src/vtt/mock_remote_cache.rs +++ /dev/null @@ -1,672 +0,0 @@ -use std::{ - collections::{BTreeMap, VecDeque}, - fmt::Write as _, - io::{Read as _, Write as _}, - net::{Shutdown, TcpListener, TcpStream}, - path::PathBuf, - sync::{Arc, Condvar, Mutex}, -}; - -const BASE_PATH: &str = "/projects/test"; - -/// `mock-remote-cache [options...] [...]` -/// -/// Runs `` with `VP_REMOTE_CACHE_URL` pointing at an in-process -/// loopback HTTP/1.1 remote cache server, then prints the recorded requests to -/// stderr and exits with the command's exit code. -/// -/// Options: -/// - `--state-dir `: Persist stored entries and blobs in `/state.cbor` -/// across invocations. -/// - `--fault =`: Inject a one-shot fault on `` (`/fetch`, -/// `/store`, or `/blob`). Multiple `--fault` flags for the same route are -/// consumed in FIFO order. Supported `` values: `503`, `429`, `drop`, -/// and `truncate` (for `/blob`). -/// - `--always-fail =`: Always apply `` to ``. -/// - `--hold-stores `: Hold incoming `POST /store` responses until `` -/// stores are simultaneously in flight (and `--release-after-fetches` has -/// been satisfied), then release them without sleeping. -/// - `--release-after-fetches `: Minimum number of `POST /fetch` requests -/// required before releasing held `POST /store` responses. -/// - `--summary`: Print sorted per-outcome counts (and `max_concurrent_stores` -/// when `--hold-stores` is set) instead of individual request lines. -pub fn run(args: &[String]) -> Result<(), Box> { - let mut args = args; - let mut state_dir: Option = None; - let mut faults: BTreeMap> = BTreeMap::new(); - let mut always_fail: BTreeMap = BTreeMap::new(); - let mut hold_stores: usize = 0; - let mut release_after_fetches: usize = 0; - let mut summary = false; - - loop { - match args { - [flag, dir, rest @ ..] if flag == "--state-dir" => { - state_dir = Some(PathBuf::from(dir)); - args = rest; - } - [flag, spec, rest @ ..] if flag == "--fault" => { - let (route, fault) = parse_fault_spec(spec)?; - faults.entry(route).or_default().push_back(fault); - args = rest; - } - [flag, spec, rest @ ..] if flag == "--always-fail" => { - let (route, fault) = parse_fault_spec(spec)?; - always_fail.insert(route, fault); - args = rest; - } - [flag, count, rest @ ..] if flag == "--hold-stores" => { - hold_stores = count.parse()?; - args = rest; - } - [flag, count, rest @ ..] if flag == "--release-after-fetches" => { - release_after_fetches = count.parse()?; - args = rest; - } - [flag, rest @ ..] if flag == "--summary" => { - summary = true; - args = rest; - } - _ => break, - } - } - - let [program, command_args @ ..] = args else { - return Err( - "Usage: vtt mock-remote-cache [--state-dir ] [--fault =]... [--always-fail =]... [--hold-stores ] [--release-after-fetches ] [--summary] [args...]" - .into(), - ); - }; - - let storage = match &state_dir { - Some(dir) => load_state(dir)?, - None => StoredState::default(), - }; - - let server = Arc::new(Server { - state_dir, - state: Mutex::new(ServerState { storage, faults, always_fail, log: Vec::new() }), - barrier: ( - Mutex::new(BarrierState { - hold_target: hold_stores, - release_after_fetches, - in_flight: 0, - max_in_flight: 0, - fetches: 0, - released: false, - }), - Condvar::new(), - ), - }); - - ctrlc::set_handler(|| {})?; - - let listener = TcpListener::bind("127.0.0.1:0")?; - let endpoint = std::format!("http://{}{BASE_PATH}", listener.local_addr()?); - { - let server = Arc::clone(&server); - std::thread::spawn(move || { - for stream in listener.incoming().filter_map(Result::ok) { - let server = Arc::clone(&server); - std::thread::spawn(move || server.serve(stream)); - } - }); - } - - let status = std::process::Command::new(program) - .args(command_args) - .env("VP_REMOTE_CACHE_URL", endpoint) - .status()?; - - if summary { - let mut counts: BTreeMap = BTreeMap::new(); - for line in &server.state.lock().unwrap().log { - *counts.entry(line.clone()).or_default() += 1; - } - for (line, count) in counts { - eprintln!("[remote-cache] {line} x{count}"); - } - if hold_stores > 0 { - let max_in_flight = server.barrier.0.lock().unwrap().max_in_flight; - eprintln!("[remote-cache] max_concurrent_stores={max_in_flight}"); - } - } else { - for line in &server.state.lock().unwrap().log { - eprintln!("[remote-cache] {line}"); - } - } - - std::process::exit(status.code().unwrap_or(1)); -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum Route { - Fetch, - Store, - Blob, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Fault { - ServiceUnavailable, - TooManyRequests, - DropConnection, - TruncateBlob, -} - -fn parse_fault_spec(spec: &str) -> Result<(Route, Fault), Box> { - let (route, kind) = spec - .split_once('=') - .ok_or_else(|| std::format!("invalid fault spec '{spec}', expected ="))?; - let route = match route { - "/fetch" => Route::Fetch, - "/store" => Route::Store, - "/blob" => Route::Blob, - _ => return Err(std::format!("unknown route '{route}'").into()), - }; - let fault = match kind { - "503" => Fault::ServiceUnavailable, - "429" => Fault::TooManyRequests, - "drop" => Fault::DropConnection, - "truncate" => Fault::TruncateBlob, - _ => return Err(std::format!("unknown fault kind '{kind}'").into()), - }; - if fault == Fault::TruncateBlob && route != Route::Blob { - return Err("truncate fault is only valid for /blob".into()); - } - Ok((route, fault)) -} - -struct Server { - state_dir: Option, - state: Mutex, - barrier: (Mutex, Condvar), -} - -struct ServerState { - storage: StoredState, - faults: BTreeMap>, - always_fail: BTreeMap, - log: Vec, -} - -struct BarrierState { - hold_target: usize, - release_after_fetches: usize, - in_flight: usize, - max_in_flight: usize, - fetches: usize, - released: bool, -} - -impl BarrierState { - const fn should_release(&self) -> bool { - self.in_flight >= self.hold_target && self.fetches >= self.release_after_fetches - } -} - -#[derive(Default, serde::Serialize, serde::Deserialize)] -struct StoredState { - entries: Vec, - blobs: Vec>, -} - -#[derive(serde::Serialize, serde::Deserialize)] -struct StoredEntry { - #[serde(with = "serde_bytes")] - key: Vec, - #[serde(with = "serde_bytes")] - value: Vec, - blob_id: Option, -} - -#[derive(serde::Deserialize)] -struct FetchRequest { - #[serde(with = "serde_bytes")] - key: Vec, -} - -#[derive(serde::Deserialize)] -struct StoreMetadata { - #[serde(with = "serde_bytes")] - key: Vec, - #[serde(with = "serde_bytes")] - value: Vec, -} - -#[derive(serde::Serialize)] -struct ExactResponse<'a> { - kind: &'static str, - entries: Vec>, -} - -#[derive(serde::Serialize)] -struct ResponseEntry<'a> { - #[serde(with = "serde_bytes")] - value: &'a [u8], - blob_id: Option<&'a str>, -} - -fn state_file_path(dir: &std::path::Path) -> PathBuf { - dir.join("state.cbor") -} - -fn load_state(dir: &std::path::Path) -> Result> { - let path = state_file_path(dir); - if !path.exists() { - return Ok(StoredState::default()); - } - let bytes = std::fs::read(path)?; - Ok(ciborium::from_reader(bytes.as_slice())?) -} - -fn save_state( - dir: &std::path::Path, - state: &StoredState, -) -> Result<(), Box> { - std::fs::create_dir_all(dir)?; - let mut bytes = Vec::new(); - ciborium::into_writer(state, &mut bytes)?; - std::fs::write(state_file_path(dir), bytes)?; - Ok(()) -} - -impl Server { - fn next_fault(&self, route: Route) -> Option { - let mut state = self.state.lock().unwrap(); - if let Some(&fault) = state.always_fail.get(&route) { - return Some(fault); - } - state.faults.get_mut(&route).and_then(VecDeque::pop_front) - } - - fn record(&self, method: &str, route: &str, outcome: &str) { - self.state.lock().unwrap().log.push(std::format!("{method} {route} {outcome}")); - } - - fn serve(&self, mut stream: TcpStream) { - let Some(request) = read_request(&mut stream) else { - return; - }; - let path = request.target.split_once('?').map_or(request.target.as_str(), |(p, _)| p); - let route_str = path.strip_prefix(BASE_PATH).unwrap_or(path); - - match (request.method.as_str(), route_str) { - ("POST", "/fetch") => self.handle_fetch(&mut stream, &request.body), - ("POST", "/store") => { - self.handle_store(&mut stream, request.content_type.as_deref(), &request.body); - } - ("GET", rest) if rest.starts_with("/blob/") => { - let blob_id = &rest["/blob/".len()..]; - self.handle_blob(&mut stream, rest, blob_id); - } - _ => { - self.record(&request.method, route_str, "404"); - write_response(&mut stream, "HTTP/1.1 404 Not Found", &[], b""); - } - } - } - - fn handle_fetch(&self, stream: &mut TcpStream, body: &[u8]) { - if let Some(fault) = self.next_fault(Route::Fetch) { - self.apply_fault(stream, "POST", "/fetch", fault); - return; - } - - // Notify any held stores once enough fetches have arrived. - { - let mut barrier = self.barrier.0.lock().unwrap(); - barrier.fetches += 1; - let should_notify = - barrier.hold_target > 0 && !barrier.released && barrier.should_release(); - if should_notify { - barrier.released = true; - } - drop(barrier); - if should_notify { - self.barrier.1.notify_all(); - } - } - - let Ok(fetch) = ciborium::from_reader::(body) else { - self.record("POST", "/fetch", "400"); - write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid cbor"); - return; - }; - - let response_body = { - let mut state = self.state.lock().unwrap(); - let entries: Vec> = state - .storage - .entries - .iter() - .rev() - .filter(|entry| entry.key == fetch.key) - .map(|entry| ResponseEntry { - value: &entry.value, - blob_id: entry.blob_id.as_deref(), - }) - .collect(); - if entries.is_empty() { - state.log.push("POST /fetch 404".to_owned()); - drop(state); - None - } else { - let mut encoded = Vec::new(); - ciborium::into_writer(&ExactResponse { kind: "exact", entries }, &mut encoded) - .unwrap(); - state.log.push("POST /fetch 200".to_owned()); - drop(state); - Some(encoded) - } - }; - - if let Some(encoded) = response_body { - write_response( - stream, - "HTTP/1.1 200 OK", - &[("content-type", "application/cbor")], - &encoded, - ); - } else { - write_response(stream, "HTTP/1.1 404 Not Found", &[], b""); - } - } - - fn handle_store(&self, stream: &mut TcpStream, content_type: Option<&str>, body: &[u8]) { - if let Some(fault) = self.next_fault(Route::Store) { - self.apply_fault(stream, "POST", "/store", fault); - return; - } - - let Some(parts) = content_type.and_then(|ct| parse_multipart(ct, body)) else { - self.record("POST", "/store", "400"); - write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid multipart"); - return; - }; - let Ok(metadata) = ciborium::from_reader::(parts.metadata) else { - self.record("POST", "/store", "400"); - write_response(stream, "HTTP/1.1 400 Bad Request", &[], b"invalid metadata"); - return; - }; - - // Hold concurrent stores on the Condvar if configured, then decrement - // `in_flight` strictly BEFORE sending the response so the client - // cannot release its semaphore permit and overlap the next store. - { - let mut barrier = self.barrier.0.lock().unwrap(); - barrier.in_flight += 1; - barrier.max_in_flight = barrier.max_in_flight.max(barrier.in_flight); - if barrier.hold_target > 0 && !barrier.released { - if barrier.should_release() { - barrier.released = true; - self.barrier.1.notify_all(); - } else { - while !barrier.released { - barrier = self.barrier.1.wait(barrier).unwrap(); - } - } - } - barrier.in_flight -= 1; - } - - { - let mut state = self.state.lock().unwrap(); - let blob_id = parts.blob.map(|blob| { - state.storage.blobs.push(blob.to_vec()); - state.storage.blobs.len().to_string() - }); - state.storage.entries.push(StoredEntry { - key: metadata.key, - value: metadata.value, - blob_id, - }); - if let Some(dir) = &self.state_dir { - save_state(dir, &state.storage).unwrap(); - } - state.log.push("POST /store 200".to_owned()); - } - - write_response(stream, "HTTP/1.1 200 OK", &[], b""); - } - - fn handle_blob(&self, stream: &mut TcpStream, route: &str, blob_id: &str) { - let fault = self.next_fault(Route::Blob); - if let Some(fault) = fault - && fault != Fault::TruncateBlob - { - self.apply_fault(stream, "GET", route, fault); - return; - } - - let blob = { - let state = self.state.lock().unwrap(); - blob_id - .parse::() - .ok() - .and_then(|id| id.checked_sub(1)) - .and_then(|idx| state.storage.blobs.get(idx).cloned()) - }; - - let Some(blob) = blob else { - self.record("GET", route, "404"); - write_response(stream, "HTTP/1.1 404 Not Found", &[], b""); - return; - }; - - if fault == Some(Fault::TruncateBlob) { - let cut = (blob.len() / 2).min(blob.len().saturating_sub(1)); - self.record("GET", route, "truncate"); - let head = std::format!( - "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: {}\r\n\r\n", - blob.len() - ); - let _ = stream.write_all(head.as_bytes()); - let _ = stream.write_all(&blob[..cut]); - let _ = stream.flush(); - let _ = stream.shutdown(Shutdown::Both); - return; - } - - self.record("GET", route, "200"); - write_response(stream, "HTTP/1.1 200 OK", &[], &blob); - } - - fn apply_fault(&self, stream: &mut TcpStream, method: &str, route: &str, fault: Fault) { - match fault { - Fault::ServiceUnavailable => { - self.record(method, route, "503"); - write_response( - stream, - "HTTP/1.1 503 Service Unavailable", - &[("retry-after", "60")], - b"busy", - ); - } - Fault::TooManyRequests => { - self.record(method, route, "429"); - write_response( - stream, - "HTTP/1.1 429 Too Many Requests", - &[("retry-after", "5")], - b"rate limited", - ); - } - Fault::DropConnection => { - self.record(method, route, "drop"); - let _ = stream.shutdown(Shutdown::Both); - } - Fault::TruncateBlob => unreachable!("truncate is handled in handle_blob"), - } - } -} - -struct HttpRequest { - method: String, - target: String, - content_type: Option, - body: Vec, -} - -fn read_request(stream: &mut TcpStream) -> Option { - let mut raw = Vec::new(); - let mut buf = [0; 4096]; - let header_end = loop { - let n = stream.read(&mut buf).ok()?; - if n == 0 { - return None; - } - raw.extend_from_slice(&buf[..n]); - if let Some(pos) = raw.windows(4).position(|window| window == b"\r\n\r\n") { - break pos + 4; - } - }; - - let head = std::str::from_utf8(&raw[..header_end - 4]).ok()?; - let mut lines = head.split("\r\n"); - let request_line = lines.next()?; - let mut parts = request_line.split(' '); - let method = parts.next()?.to_owned(); - let target = parts.next()?.to_owned(); - - let mut content_length: Option = None; - let mut content_type: Option = None; - let mut chunked = false; - - for line in lines { - let Some((name, value)) = line.split_once(':') else { - continue; - }; - let name = name.trim(); - let value = value.trim(); - if name.eq_ignore_ascii_case("content-length") { - content_length = value.parse().ok(); - } else if name.eq_ignore_ascii_case("content-type") { - content_type = Some(value.to_owned()); - } else if name.eq_ignore_ascii_case("transfer-encoding") - && value.to_ascii_lowercase().contains("chunked") - { - chunked = true; - } - } - - let mut body = raw.split_off(header_end); - if let Some(expected) = content_length { - while body.len() < expected { - let n = stream.read(&mut buf).ok()?; - if n == 0 { - return None; - } - body.extend_from_slice(&buf[..n]); - } - body.truncate(expected); - } else if chunked { - body = read_chunked_body(stream, body)?; - } - - Some(HttpRequest { method, target, content_type, body }) -} - -fn read_chunked_body(stream: &mut TcpStream, mut buffered: Vec) -> Option> { - let mut decoded = Vec::new(); - let mut cursor = 0; - let mut buf = [0; 4096]; - loop { - let line_end = loop { - if let Some(rel) = buffered[cursor..].windows(2).position(|w| w == b"\r\n") { - break cursor + rel; - } - let n = stream.read(&mut buf).ok()?; - if n == 0 { - return None; - } - buffered.extend_from_slice(&buf[..n]); - }; - let size_str = std::str::from_utf8(&buffered[cursor..line_end]).ok()?; - let size_hex = size_str.split(';').next()?.trim(); - let size = usize::from_str_radix(size_hex, 16).ok()?; - cursor = line_end + 2; - if size == 0 { - return Some(decoded); - } - while buffered.len() < cursor + size + 2 { - let n = stream.read(&mut buf).ok()?; - if n == 0 { - return None; - } - buffered.extend_from_slice(&buf[..n]); - } - decoded.extend_from_slice(&buffered[cursor..cursor + size]); - cursor += size + 2; - } -} - -struct StoreParts<'a> { - metadata: &'a [u8], - blob: Option<&'a [u8]>, -} - -fn parse_multipart<'a>(content_type: &str, body: &'a [u8]) -> Option> { - let boundary = content_type.split(';').find_map(|param| { - let (name, value) = param.trim().split_once('=')?; - name.eq_ignore_ascii_case("boundary").then(|| value.trim().trim_matches('"')) - })?; - let delimiter = std::format!("--{boundary}"); - let delimiter = delimiter.as_bytes(); - - let mut metadata = None; - let mut blob = None; - let mut pos = find_subslice(body, delimiter)?; - - loop { - pos += delimiter.len(); - if body[pos..].starts_with(b"--") { - break; - } - if !body[pos..].starts_with(b"\r\n") { - return None; - } - pos += 2; - - let next = find_subslice(&body[pos..], delimiter)?; - let part = &body[pos..pos + next]; - let part = part.strip_suffix(b"\r\n").unwrap_or(part); - let head_end = find_subslice(part, b"\r\n\r\n")?; - let part_head = std::str::from_utf8(&part[..head_end]).ok()?; - let part_body = &part[head_end + 4..]; - - if part_head.contains("name=\"metadata\"") { - metadata = Some(part_body); - } else if part_head.contains("name=\"blob\"") { - blob = Some(part_body); - } - - pos += next; - } - - Some(StoreParts { metadata: metadata?, blob }) -} - -fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { - haystack.windows(needle.len()).position(|window| window == needle) -} - -fn write_response( - stream: &mut TcpStream, - status_line: &str, - headers: &[(&str, &str)], - body: &[u8], -) { - let mut head = std::format!("{status_line}\r\nconnection: close\r\n"); - for (name, value) in headers { - head.push_str(name); - head.push_str(": "); - head.push_str(value); - head.push_str("\r\n"); - } - let _ = write!(head, "content-length: {}\r\n\r\n", body.len()); - let _ = stream.write_all(head.as_bytes()); - let _ = stream.write_all(body); - let _ = stream.flush(); - let _ = stream.shutdown(Shutdown::Both); -} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml index f61167222..9d2ed3fff 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml @@ -1,17 +1,23 @@ # Deterministic, zero-sleep e2e tests for remote cache resilience: transient # retry (fetch, store, blob download), per-kind outage circuit breaking, and -# bounded concurrent uploads. All cases use `vtt mock-remote-cache` directly so -# they run in the default Rust test suite on Unix (including musl) and Windows. +# bounded concurrent uploads. These run against the real Cloudflare Worker +# backend through `remote-cache-server`'s tap proxy, so they are ignored by +# default and skipped on musl (like `remote_cache`). [[e2e]] name = "retry_transient_failures" comment = "Transient 503, 429, connection-drop, and truncated-download errors are retried across fetch, store, and blob restore." +cfg = 'not(target_env = "musl")' +ignore = true steps = [ + [ + "remote-cache-server", + "start", + ], { argv = [ - "vtt", - "mock-remote-cache", - "--state-dir", - ".mock-cache", + "remote-cache-server", + "run", + "--github-actions", "--fault", "/fetch=503", "--fault", @@ -51,10 +57,8 @@ steps = [ "dist", ], { argv = [ - "vtt", - "mock-remote-cache", - "--state-dir", - ".mock-cache", + "remote-cache-server", + "run", "--fault", "/fetch=503", "--fault", @@ -83,15 +87,26 @@ steps = [ ".tmp", "--recursive", ], comment = "No temporary download file was left behind after the truncated attempt." }, + [ + "remote-cache-server", + "stop", + ], ] [[e2e]] name = "outage_circuit_breaker_per_kind" comment = "Three consecutive exhausted read failures open the read circuit breaker without blocking uploads, and successful uploads do not reset read failures." +cfg = 'not(target_env = "musl")' +ignore = true steps = [ + [ + "remote-cache-server", + "start", + ], { argv = [ - "vtt", - "mock-remote-cache", + "remote-cache-server", + "run", + "--github-actions", "--always-fail", "/fetch=503", "--summary", @@ -117,15 +132,26 @@ steps = [ "run", "--last-details", ], comment = "step1..step3 report HTTP status 503; step4 reports remote cache temporarily unavailable; no upload warnings." }, + [ + "remote-cache-server", + "stop", + ], ] [[e2e]] name = "upload_concurrency_cap" comment = "At most 4 concurrent remote cache uploads are in flight at once, and full upload slots do not block fetches." +cfg = 'not(target_env = "musl")' +ignore = true steps = [ + [ + "remote-cache-server", + "start", + ], { argv = [ - "vtt", - "mock-remote-cache", + "remote-cache-server", + "run", + "--github-actions", "--hold-stores", "4", "--release-after-fetches", @@ -147,5 +173,9 @@ steps = [ "VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF", "1", ], - ], comment = "The mock server holds stores on a Condvar until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4." }, + ], comment = "The tap holds stores until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4." }, + [ + "remote-cache-server", + "stop", + ], ] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md index 308b6f374..4ab839941 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md @@ -2,7 +2,12 @@ Three consecutive exhausted read failures open the read circuit breaker without blocking uploads, and successful uploads do not reset read failures. -## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --always-fail /fetch=503 --summary vt run step4` +## `remote-cache-server start` + +``` +``` + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 remote-cache-server run --github-actions --always-fail /fetch=503 --summary vt run step4` step1..step3 exhaust 3 fetch attempts each (9 total) and open the read breaker. step4 skips the fetch request, while all 4 stores succeed. @@ -59,3 +64,8 @@ Task Details: → Cache miss: remote cache temporarily unavailable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` + +## `remote-cache-server stop` + +``` +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md index d6b99e150..83c8261f6 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md @@ -2,7 +2,12 @@ Transient 503, 429, connection-drop, and truncated-download errors are retried across fetch, store, and blob restore. -## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --state-dir .mock-cache --fault /fetch=503 --fault /fetch=drop --fault /store=503 --fault /store=429 --fault /store=drop vt run build` +## `remote-cache-server start` + +``` +``` + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 remote-cache-server run --github-actions --fault /fetch=503 --fault /fetch=drop --fault /store=503 --fault /store=429 --fault /store=drop vt run build` Fetch recovers from 503 and connection drop to receive 404. Store retries 503, 429, and connection drop, re-streaming the output archive until 200. @@ -28,7 +33,7 @@ $ vtt write-file dist/output.txt built ``` ``` -## `VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --state-dir .mock-cache --fault /fetch=503 --fault /blob=503 --fault /blob=truncate vt run build` +## `VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 remote-cache-server run --fault /fetch=503 --fault /blob=503 --fault /blob=truncate vt run build` Fetch retries 503 and hits the stored entry. Blob download retries 503 and a mid-stream truncation, then restores the output. @@ -38,7 +43,7 @@ $ vtt write-file dist/output.txt built ◉ remote cache hit, replaying --- vt run: remote cache hit. [remote-cache] POST /fetch 503 -[remote-cache] POST /fetch 200 +[remote-cache] POST /fetch 200 exact [1] [remote-cache] GET /blob/1 503 [remote-cache] GET /blob/1 truncate [remote-cache] GET /blob/1 200 @@ -58,3 +63,8 @@ No temporary download file was left behind after the truncated attempt. ``` ``` + +## `remote-cache-server stop` + +``` +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md index 22e8155a8..d139b4b63 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md @@ -2,9 +2,14 @@ At most 4 concurrent remote cache uploads are in flight at once, and full upload slots do not block fetches. -## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 vtt mock-remote-cache --hold-stores 4 --release-after-fetches 7 --summary vt run t7` +## `remote-cache-server start` -The mock server holds stores on a Condvar until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4. +``` +``` + +## `VP_REMOTE_CACHE=read-write VP_RUN_INTERNAL_HIDE_PENDING_UPLOADS=1 VP_RUN_INTERNAL_REMOTE_CACHE_NO_BACKOFF=1 remote-cache-server run --github-actions --hold-stores 4 --release-after-fetches 7 --summary vt run t7` + +The tap holds stores until 4 are concurrently in flight and all 7 fetches have arrived, proving reads are unblocked and max_concurrent_stores stays capped at 4. ``` $ vtt print t1 @@ -34,3 +39,8 @@ vt run: 0/7 cache hit (0%), 7/7 successful. (Run `vt run --last-details` for ful [remote-cache] POST /store 200 x7 [remote-cache] max_concurrent_stores=4 ``` + +## `remote-cache-server stop` + +``` +``` diff --git a/packages/tools/README.md b/packages/tools/README.md index 354a82bb3..e54fc0ecc 100644 --- a/packages/tools/README.md +++ b/packages/tools/README.md @@ -13,7 +13,7 @@ remote-cache-server stop An E2E case starts its own backend in its first step and stops it in its last, so the backend keeps its state for the whole case. Each subcommand works in the current directory, the case's directory: - `remote-cache-server start [--entries-per-key N]` starts the backend in the background on free loopback ports and returns once it's ready. The namespace keeps the newest `N` entries of each key, or the Worker's default of 8. The backend runs in its own session and doesn't use the terminal, so the step can finish and Ctrl-C in later steps doesn't reach it. It writes its endpoint, `http://127.0.0.1:/projects/test`, to `remote-cache/server.json`, and its output to `remote-cache/server.log`. -- `remote-cache-server run [--github-actions] COMMAND [ARGS...]` runs the command with `VP_REMOTE_CACHE_URL` set to the endpoint. The fixed base path gives the endpoint a namespace path. With `--github-actions`, the command runs as if in a GitHub Actions job with `id-token: write`: `ACTIONS_ID_TOKEN_REQUEST_URL` points to the backend's stand-in for GitHub's token service, and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` defaults to `main-push`. The command inherits stdio and handles Ctrl-C, which `run` ignores. `run` exits with the command's exit code. +- `remote-cache-server run [--github-actions] [--fault ROUTE=KIND]... [--always-fail ROUTE=KIND]... [--hold-stores N] [--release-after-fetches N] [--summary] COMMAND [ARGS...]` runs the command with `VP_REMOTE_CACHE_URL` set to the endpoint. The fixed base path gives the endpoint a namespace path. With `--github-actions`, the command runs as if in a GitHub Actions job with `id-token: write`: `ACTIONS_ID_TOKEN_REQUEST_URL` points to the backend's stand-in for GitHub's token service, and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` defaults to `main-push`. Optional tap overrides apply only to that run: `--fault` injects one-shot faults in FIFO order per route (`/fetch`, `/store`, `/blob`) with kind `503`, `429`, `drop`, or `truncate` (`/blob` only); `--always-fail` applies a fault to every request on that route; `--hold-stores` / `--release-after-fetches` holds `POST /store` requests before forwarding until `N` are concurrently in flight and enough `POST /fetch` requests have arrived; `--summary` prints sorted per-outcome counts (plus `max_concurrent_stores`). The command inherits stdio and handles Ctrl-C, which `run` ignores. `run` exits with the command's exit code. - `remote-cache-server corrupt-blob NUMBER` overwrites a stored blob, numbered as in the request lines, with other bytes. - `remote-cache-server expire-entry [--before-download] NUMBER` makes the entry whose blob has that number expire now, as if its retention had passed. Nothing removes it, as before the Worker's scheduled cleanup. With `--before-download`, the entry expires when its blob is next requested instead, before the tap forwards the request, as if its retention passed between a fetch and the download. - `remote-cache-server stop` stops the backend. It fails if the backend answered a request with a 5xx status or couldn't be reached. diff --git a/packages/tools/src/remote-cache/cli.ts b/packages/tools/src/remote-cache/cli.ts index dcafd0a6e..55f91f184 100755 --- a/packages/tools/src/remote-cache/cli.ts +++ b/packages/tools/src/remote-cache/cli.ts @@ -8,10 +8,19 @@ import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import crossSpawn from 'cross-spawn'; import { defaultRequestToken } from './github.ts'; -import { logFile, serverFile, stateDirectory, type ServerInfo } from './state.ts'; +import { + logFile, + serverFile, + stateDirectory, + type FaultKind, + type FaultRoute, + type FaultRule, + type RunConfig, + type ServerInfo, +} from './state.ts'; const usage = - 'Usage: remote-cache-server start [--entries-per-key N] | run [--github-actions] COMMAND [ARGS...] | corrupt-blob NUMBER | expire-entry [--before-download] NUMBER | stop'; + 'Usage: remote-cache-server start [--entries-per-key N] | run [--github-actions] [--fault ROUTE=KIND]... [--always-fail ROUTE=KIND]... [--hold-stores N] [--release-after-fetches N] [--summary] COMMAND [ARGS...] | corrupt-blob NUMBER | expire-entry [--before-download] NUMBER | stop'; const directory = resolve(stateDirectory); function fail(message: string): never { @@ -30,22 +39,36 @@ function readInfo(): ServerInfo { * POST to the backend's control server and return the JSON response. A 404 * fails with `notFound`. */ -function control(info: ServerInfo, path: string, notFound = 'unknown request'): Promise { +function control( + info: ServerInfo, + path: string, + notFound = 'unknown request', + body?: unknown, +): Promise { return new Promise((resolve) => { const unreachable = (error: Error) => fail(`the backend is unreachable (${error.message}). See ${logFile(stateDirectory)}.`); - const call = request(`${info.control}${path}`, { method: 'POST', agent: false }, (response) => { - if (response.statusCode === 404) fail(notFound); - if (response.statusCode !== 200) { - fail(`the backend failed (${response.statusCode}). See ${logFile(stateDirectory)}.`); - } - const chunks: Buffer[] = []; - response.on('data', (chunk: Buffer) => chunks.push(chunk)); - response.on('end', () => resolve(JSON.parse(Buffer.concat(chunks).toString()) as T)); - response.on('error', unreachable); - }); + const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body)); + const headers = + payload === undefined + ? undefined + : { 'content-type': 'application/json', 'content-length': String(payload.length) }; + const call = request( + `${info.control}${path}`, + { method: 'POST', agent: false, ...(headers === undefined ? {} : { headers }) }, + (response) => { + if (response.statusCode === 404) fail(notFound); + if (response.statusCode !== 200) { + fail(`the backend failed (${response.statusCode}). See ${logFile(stateDirectory)}.`); + } + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer) => chunks.push(chunk)); + response.on('end', () => resolve(JSON.parse(Buffer.concat(chunks).toString()) as T)); + response.on('error', unreachable); + }, + ); call.on('error', unreachable); - call.end(); + call.end(payload); }); } @@ -89,11 +112,69 @@ async function start(argv: string[]): Promise { daemon.unref(); } +function parseFaultSpec(spec: string | undefined): FaultRule { + if (spec === undefined) fail(usage); + const sep = spec.indexOf('='); + if (sep === -1) fail(`invalid fault spec '${spec}', expected =`); + const route = spec.slice(0, sep); + const kind = spec.slice(sep + 1); + if (route !== '/fetch' && route !== '/store' && route !== '/blob') { + fail(`unknown route '${route}'`); + } + if (kind !== '503' && kind !== '429' && kind !== 'drop' && kind !== 'truncate') { + fail(`unknown fault kind '${kind}'`); + } + if (kind === 'truncate' && route !== '/blob') { + fail('truncate fault is only valid for /blob'); + } + return { route: route as FaultRoute, kind: kind as FaultKind }; +} + +function parsePositiveInt(value: string | undefined): number { + if (value === undefined || !/^[1-9]\d*$/.test(value)) fail(usage); + return Number(value); +} + async function run(argv: string[]): Promise { - const githubActions = argv[0] === '--github-actions'; - const [command, ...args] = githubActions ? argv.slice(1) : argv; + let githubActions = false; + const faults: FaultRule[] = []; + const alwaysFail: FaultRule[] = []; + let holdStores = 0; + let releaseAfterFetches = 0; + let summary = false; + let index = 0; + while (index < argv.length) { + const arg = argv[index]!; + if (arg === '--github-actions') { + githubActions = true; + index += 1; + } else if (arg === '--fault') { + faults.push(parseFaultSpec(argv[index + 1])); + index += 2; + } else if (arg === '--always-fail') { + alwaysFail.push(parseFaultSpec(argv[index + 1])); + index += 2; + } else if (arg === '--hold-stores') { + holdStores = parsePositiveInt(argv[index + 1]); + index += 2; + } else if (arg === '--release-after-fetches') { + releaseAfterFetches = parsePositiveInt(argv[index + 1]); + index += 2; + } else if (arg === '--summary') { + summary = true; + index += 1; + } else { + break; + } + } + const [command, ...args] = argv.slice(index); if (command === undefined) fail(usage); const info = readInfo(); + const hasRunConfig = faults.length > 0 || alwaysFail.length > 0 || holdStores > 0 || summary; + if (hasRunConfig) { + const config: RunConfig = { faults, alwaysFail, holdStores, releaseAfterFetches, summary }; + await control(info, '/configure', 'unknown request', config); + } const env: NodeJS.ProcessEnv = { ...process.env, VP_REMOTE_CACHE_URL: info.url }; if (githubActions) { // As in a GitHub Actions job with `id-token: write`. diff --git a/packages/tools/src/remote-cache/daemon.ts b/packages/tools/src/remote-cache/daemon.ts index 709d867a2..580e52e0d 100644 --- a/packages/tools/src/remote-cache/daemon.ts +++ b/packages/tools/src/remote-cache/daemon.ts @@ -12,7 +12,14 @@ import { import type { AddressInfo } from 'node:net'; import { startBackend } from './backend.ts'; import { createSigningKey, repository } from './github.ts'; -import { basePath, serverFile, type ServerInfo } from './state.ts'; +import { + basePath, + serverFile, + type FaultKind, + type FaultRoute, + type RunConfig, + type ServerInfo, +} from './state.ts'; // The process that `remote-cache-server start` leaves running for one e2e case. // It serves the backend at the endpoint through a tap that forwards requests @@ -45,9 +52,73 @@ const anomalies: string[] = []; const blobs: string[] = []; /** The blobs whose entries expire when the blob is next requested. */ const expireBeforeDownload = new Set(); +/** Per-run FIFO fault queues configured by `POST /configure`. */ +const faults = new Map(); +/** Per-run permanent faults configured by `POST /configure`. */ +const alwaysFail = new Map(); + +interface StoreGate { + holdTarget: number; + releaseAfterFetches: number; + inFlight: number; + maxInFlight: number; + fetches: number; + released: boolean; + waiters: Array<() => void>; +} + +let storeGate: StoreGate | undefined; +let summaryMode = false; let lastUse = Date.now(); let stopping = false; +function matchFaultRoute(route: string): FaultRoute | undefined { + if (route === '/fetch' || route === '/store') return route; + if (route.startsWith('/blob/')) return '/blob'; + return undefined; +} + +function nextFault(route: string): FaultKind | undefined { + const faultRoute = matchFaultRoute(route); + if (faultRoute === undefined) return undefined; + return alwaysFail.get(faultRoute) ?? faults.get(faultRoute)?.shift(); +} + +function releaseStoreGateIfReady(): void { + if ( + storeGate !== undefined && + !storeGate.released && + storeGate.inFlight >= storeGate.holdTarget && + storeGate.fetches >= storeGate.releaseAfterFetches + ) { + storeGate.released = true; + for (const wake of storeGate.waiters.splice(0)) wake(); + } +} + +function resetRunConfig(): void { + faults.clear(); + alwaysFail.clear(); + if (storeGate !== undefined) { + storeGate.released = true; + for (const wake of storeGate.waiters.splice(0)) wake(); + storeGate = undefined; + } + summaryMode = false; +} + +function summarizeRequests(taken: string[], maxConcurrentStores: number | undefined): string[] { + const counts = new Map(); + for (const line of taken) counts.set(line, (counts.get(line) ?? 0) + 1); + const lines = [...counts.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([line, count]) => `${line} x${count}`); + if (maxConcurrentStores !== undefined) { + lines.push(`max_concurrent_stores=${maxConcurrentStores}`); + } + return lines; +} + function endToEnd(headers: IncomingHttpHeaders): IncomingHttpHeaders { return Object.fromEntries(Object.entries(headers).filter(([name]) => !hopByHop.has(name))); } @@ -93,19 +164,52 @@ const tap = createServer((request, response) => { const path = new URL(request.url ?? '/', 'http://localhost').pathname; const route = path.startsWith(basePath) ? path.slice(basePath.length) : path; const label = `${request.method} ${numbered(route)}`; + const fault = nextFault(route); + if (fault !== undefined && fault !== 'truncate') { + // Drain the full request body before replying or closing so the client + // never sees a write-side reset before reading the injected status. + request.resume(); + request.on('end', () => { + if (fault === '503') { + requests.push(`${label} 503`); + response.writeHead(503, { + 'retry-after': '60', + connection: 'close', + 'content-length': '4', + }); + response.end('busy'); + } else if (fault === '429') { + requests.push(`${label} 429`); + response.writeHead(429, { + 'retry-after': '5', + connection: 'close', + 'content-length': '12', + }); + response.end('rate limited'); + } else { + requests.push(`${label} drop`); + response.destroy(); + } + }); + return; + } + if (route === '/fetch' && storeGate !== undefined) { + storeGate.fetches += 1; + releaseStoreGateIfReady(); + } const id = /^\/blob\/(.+)$/.exec(route)?.[1]; if (id !== undefined && expireBeforeDownload.delete(id)) { // The client sent this request after the fetch's response, so the entry // expires between the two. backend.expireEntry(id).then( - () => pass(request, response, route, label), + () => pass(request, response, route, label, fault === 'truncate'), (error: unknown) => { anomalies.push(`${label} failed to expire its entry: ${String(error)}`); response.writeHead(502).end(); }, ); } else { - pass(request, response, route, label); + pass(request, response, route, label, fault === 'truncate'); } }); @@ -115,68 +219,154 @@ function pass( response: ServerResponse, route: string, label: string, + truncateBlob: boolean, ): void { let clientGone = false; let backendReply: IncomingMessage | undefined; - const upstream = forward( - `${backend.origin}${request.url}`, - { method: request.method!, headers: endToEnd(request.headers) }, - (reply) => { - backendReply = reply; - const status = reply.statusCode!; - if (status >= 500) anomalies.push(`${label} got ${status} from the backend`); - response.writeHead(status, endToEnd(reply.headers)); - // Fetch and store responses are CBOR maps with the kind and entries, or - // the blob ID. - const chunks: Buffer[] = []; - if ((route === '/fetch' || route === '/store') && status === 200) { - reply.on('data', (chunk: Buffer) => chunks.push(chunk)); - } - reply.pipe(response); - response.on('finish', () => { - const fields = chunks.length > 0 ? cborFields(Buffer.concat(chunks)) : {}; - const blobId = fields['blob_id']; - if (route === '/store' && typeof blobId === 'string') blobs.push(blobId); - const kind = route === '/fetch' ? fields['kind'] : undefined; - const entries = route === '/fetch' ? entryBlobs(fields['entries']) : undefined; - requests.push( - [label, status, kind, entries].filter((part) => part !== undefined).join(' '), - ); - }); - }, - ); - upstream.on('error', (error) => { - // The Worker rejects an upload by its headers, answering before it reads - // the body, and then closes the connection, which can reset it after the - // answer. - if (clientGone || backendReply?.complete) return; - anomalies.push(`${label} failed: ${error.message}`); - if (response.headersSent) response.destroy(); - else response.writeHead(502).end(); - }); + let upstream: ReturnType | undefined; + const activeGate = route === '/store' ? storeGate : undefined; + let countedInFlight = false; + const releaseInFlight = () => { + if (countedInFlight && activeGate !== undefined) { + countedInFlight = false; + activeGate.inFlight -= 1; + } + }; + // The client can disconnect before the response ends, e.g. after Ctrl-C. response.on('close', () => { if (response.writableFinished) return; clientGone = true; - upstream.destroy(); + releaseInFlight(); + upstream?.destroy(); }); - // Send the body once it has all arrived, so it goes out with the headers + + // Buffer the body once it has all arrived, so it goes out with the headers // before the Worker can answer. Sending part of it after a rejection fails // if the connection was reset, and that can lose the answer before it's // read. const body: Buffer[] = []; request.on('data', (chunk: Buffer) => body.push(chunk)); - request.on('end', () => upstream.end(Buffer.concat(body))); + request.on('end', () => { + void forwardBuffered(Buffer.concat(body)); + }); + + async function forwardBuffered(payload: Buffer): Promise { + if (clientGone) return; + if (activeGate !== undefined) { + activeGate.inFlight += 1; + activeGate.maxInFlight = Math.max(activeGate.maxInFlight, activeGate.inFlight); + countedInFlight = true; + releaseStoreGateIfReady(); + if (!activeGate.released) { + await new Promise((resolve) => { + activeGate.waiters.push(resolve); + }); + } + if (clientGone) { + releaseInFlight(); + return; + } + } + upstream = forward( + `${backend.origin}${request.url}`, + { method: request.method!, headers: endToEnd(request.headers) }, + (reply) => { + backendReply = reply; + const status = reply.statusCode!; + if (status >= 500) anomalies.push(`${label} got ${status} from the backend`); + if (truncateBlob && status === 200) { + const blobChunks: Buffer[] = []; + reply.on('data', (chunk: Buffer) => blobChunks.push(chunk)); + reply.on('end', () => { + const full = Buffer.concat(blobChunks); + const cut = Math.min(Math.floor(full.length / 2), Math.max(0, full.length - 1)); + requests.push(`${label} truncate`); + response.writeHead(200, { + 'content-length': String(full.length), + connection: 'close', + }); + response.write(full.subarray(0, cut), () => { + response.destroy(); + }); + }); + return; + } + // Decrement in-flight count strictly before writing headers so the + // client cannot release its upload slot and overlap the next store. + releaseInFlight(); + response.writeHead(status, endToEnd(reply.headers)); + // Fetch and store responses are CBOR maps with the kind and entries, or + // the blob ID. + const chunks: Buffer[] = []; + if ((route === '/fetch' || route === '/store') && status === 200) { + reply.on('data', (chunk: Buffer) => chunks.push(chunk)); + } + reply.pipe(response); + response.on('finish', () => { + const fields = chunks.length > 0 ? cborFields(Buffer.concat(chunks)) : {}; + const blobId = fields['blob_id']; + if (route === '/store' && typeof blobId === 'string') blobs.push(blobId); + const kind = route === '/fetch' ? fields['kind'] : undefined; + const entries = route === '/fetch' ? entryBlobs(fields['entries']) : undefined; + requests.push( + [label, status, kind, entries].filter((part) => part !== undefined).join(' '), + ); + }); + }, + ); + upstream.on('error', (error) => { + releaseInFlight(); + // The Worker rejects an upload by its headers, answering before it reads + // the body, and then closes the connection, which can reset it after the + // answer. + if (clientGone || backendReply?.complete) return; + anomalies.push(`${label} failed: ${error.message}`); + if (response.headersSent) response.destroy(); + else response.writeHead(502).end(); + }); + upstream.end(payload); + } } const control = createServer((request, response) => { lastUse = Date.now(); - request.resume(); const reply = (value: unknown) => { response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify(value)); }; const url = new URL(request.url ?? '/', 'http://localhost'); + if (request.method === 'POST' && request.url === '/configure') { + const chunks: Buffer[] = []; + request.on('data', (chunk: Buffer) => chunks.push(chunk)); + request.on('end', () => { + const config = JSON.parse(Buffer.concat(chunks).toString()) as RunConfig; + resetRunConfig(); + for (const rule of config.faults) { + const queue = faults.get(rule.route) ?? []; + queue.push(rule.kind); + faults.set(rule.route, queue); + } + for (const rule of config.alwaysFail) { + alwaysFail.set(rule.route, rule.kind); + } + if (config.holdStores > 0) { + storeGate = { + holdTarget: config.holdStores, + releaseAfterFetches: config.releaseAfterFetches, + inFlight: 0, + maxInFlight: 0, + fetches: 0, + released: false, + waiters: [], + }; + } + summaryMode = config.summary; + reply(null); + }); + return; + } + request.resume(); if (request.method === 'GET' && url.pathname === '/token') { // The request token stands for the workflow run, as in GitHub Actions. const requestToken = /^Bearer (.+)$/.exec(request.headers.authorization ?? '')?.[1]; @@ -192,7 +382,10 @@ const control = createServer((request, response) => { const [, change, number] = /^\/(corrupt-blob|expire-entry|expire-before-download)\/(\d+)$/.exec(request.url ?? '') ?? []; if (request.method === 'POST' && request.url === '/take') { - reply(requests.splice(0)); + const taken = requests.splice(0); + const lines = summaryMode ? summarizeRequests(taken, storeGate?.maxInFlight) : taken; + resetRunConfig(); + reply(lines); } else if (request.method === 'POST' && number !== undefined) { const id = blobs[Number(number) - 1]; if (id === undefined) { diff --git a/packages/tools/src/remote-cache/state.ts b/packages/tools/src/remote-cache/state.ts index a4e1b67e2..6a0f55c39 100644 --- a/packages/tools/src/remote-cache/state.ts +++ b/packages/tools/src/remote-cache/state.ts @@ -16,6 +16,24 @@ export interface ServerInfo { tokenRequestUrl: string; } +export type FaultRoute = '/fetch' | '/store' | '/blob'; + +export type FaultKind = '503' | '429' | 'drop' | 'truncate'; + +export interface FaultRule { + route: FaultRoute; + kind: FaultKind; +} + +/** Per-`run` tap overrides configured before spawning a command and cleared on `/take`. */ +export interface RunConfig { + faults: FaultRule[]; + alwaysFail: FaultRule[]; + holdStores: number; + releaseAfterFetches: number; + summary: boolean; +} + export function serverFile(directory: string): string { return join(directory, 'server.json'); } From 83e8f9a79157e37621f71627e61b272e4c108ef0 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:44:17 +0800 Subject: [PATCH 7/9] fix(cache): keep download handle join on cancel and lower fetch timeout to 10s Co-authored-by: Gemini 4 Neon --- crates/vt/src/session/cache/remote.rs | 57 +++++++++------ crates/vt/src/session/cache/remote/retry.rs | 78 +++++++++++++++++---- crates/vt_remote_cache/README.md | 2 +- crates/vt_remote_cache/src/lib.rs | 6 +- 4 files changed, 106 insertions(+), 37 deletions(-) diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index fa0bfdd4d..b4e630d67 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -96,6 +96,10 @@ impl RetryableError for UploadError { fn unavailable() -> Self { Self::Unavailable } + + fn cancelled() -> Self { + Self::Interrupted + } } /// Why no entry could be read from the remote cache. It's a cache miss, and @@ -152,6 +156,10 @@ impl RetryableError for ReadError { fn unavailable() -> Self { Self::Unavailable } + + fn cancelled() -> Self { + Self::Cancelled + } } impl ReadError { @@ -302,16 +310,21 @@ impl RemoteEndpoint { secondary_key: &[u8], cancel_token: &CancellationToken, ) -> Result, ReadError> { - cancel_token - .run_until_cancelled(retry::run( - "fetch", - self.retry.read, - &self.read_rate_limit, - &self.read_outage, - || async { self.client.fetch(key, secondary_key).await.map_err(ReadError::Fetch) }, - )) - .await - .ok_or(ReadError::Cancelled)? + retry::run( + "fetch", + self.retry.read, + &self.read_rate_limit, + &self.read_outage, + cancel_token, + || async { + cancel_token + .run_until_cancelled(self.client.fetch(key, secondary_key)) + .await + .ok_or(ReadError::Cancelled)? + .map_err(ReadError::Fetch) + }, + ) + .await } async fn download_checked( @@ -320,16 +333,18 @@ impl RemoteEndpoint { path: &AbsolutePath, cancel_token: &CancellationToken, ) -> Result<(), ReadError> { - cancel_token - .run_until_cancelled(retry::run( - "download", - self.retry.read, - &self.read_rate_limit, - &self.read_outage, - || download_once(&self.client, blob_id, path, cancel_token), - )) - .await - .ok_or(ReadError::Cancelled)? + // Do not wrap `download_once` in `run_until_cancelled`: `download_once` + // handles `cancel_token` itself so it always joins the blocking archive + // check task and closes the `.tmp` file handle before returning. + retry::run( + "download", + self.retry.read, + &self.read_rate_limit, + &self.read_outage, + cancel_token, + || download_once(&self.client, blob_id, path, cancel_token), + ) + .await } async fn store( @@ -345,11 +360,13 @@ impl RemoteEndpoint { if !queued.is_zero() { tracing::debug!(?queued, "acquired remote cache upload slot"); } + let never_cancel = CancellationToken::new(); let result = retry::run( "store", self.retry.store, &self.store_rate_limit, &self.store_outage, + &never_cancel, || async { self.client .store(key, secondary_key, value, blob) diff --git a/crates/vt/src/session/cache/remote/retry.rs b/crates/vt/src/session/cache/remote/retry.rs index a2ab47c52..6f380e395 100644 --- a/crates/vt/src/session/cache/remote/retry.rs +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -9,6 +9,7 @@ use std::{ }; use tokio::time::Instant; +use tokio_util::sync::CancellationToken; use vt_remote_cache::RetryHint; /// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response. @@ -41,6 +42,8 @@ pub(super) trait RetryableError: Debug { fn retry_action(&self) -> RetryAction; /// Error returned when the outage circuit breaker is open. fn unavailable() -> Self; + /// Error returned when `cancel_token` cancels a wait between attempts. + fn cancelled() -> Self; } /// Retry parameters for one kind of remote cache operation. @@ -325,12 +328,19 @@ impl Drop for OutagePermit<'_> { } } -/// Run `attempt_fn` through `outage`, `rate_limit`, and `policy`. +/// Run `attempt_fn` through `outage`, `rate_limit`, and `policy`, stopping if +/// `cancel_token` is cancelled before an attempt or during a retry wait. +/// +/// `attempt_fn` is NOT dropped mid-execution by `cancel_token` here; callers +/// that need cleanup on cancellation (such as joining a blocking file-writer +/// task before deleting a temporary file) honor `cancel_token` inside +/// `attempt_fn` and return an error classified as [`RetryAction::Cancelled`]. pub(super) async fn run( operation: &'static str, policy: RetryPolicy, rate_limit: &RateLimit, outage: &OutageBreaker, + cancel_token: &CancellationToken, mut attempt_fn: F, ) -> Result where @@ -338,6 +348,9 @@ where F: FnMut() -> Fut, Fut: Future>, { + if cancel_token.is_cancelled() { + return Err(E::cancelled()); + } let Some(permit) = outage.enter() else { tracing::debug!(operation, "skipping remote cache request while circuit is open"); return Err(E::unavailable()); @@ -348,7 +361,9 @@ where let started = Instant::now(); let total_attempts = policy.max_retries.saturating_add(1); for attempt in 0..total_attempts { - rate_limit.wait().await; + if cancel_token.run_until_cancelled(rate_limit.wait()).await.is_none() { + return Err(E::cancelled()); + } match attempt_fn().await { Ok(value) => { permit.finish(OutageOutcome::Healthy); @@ -411,7 +426,9 @@ where ?error, "retrying remote cache request" ); - sleep(backoff).await; + if cancel_token.run_until_cancelled(sleep(backoff)).await.is_none() { + return Err(E::cancelled()); + } } }, } @@ -477,6 +494,10 @@ mod tests { fn unavailable() -> Self { Self::Outage } + + fn cancelled() -> Self { + Self::Cancelled + } } fn expire_open(breaker: &OutageBreaker) { @@ -564,23 +585,54 @@ mod tests { let policy = RetryPolicy { max_retries: 0, base_delay: Duration::ZERO, ..RetryPolicy::READ }; + let cancel = CancellationToken::new(); + // Open the circuit with one outage failure. - let err = run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, || async { - Err(TestError::Outage) - }) - .await - .unwrap_err(); + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Outage) + }) + .await + .unwrap_err(); assert_eq!(err, TestError::Outage); assert!(breaker.enter().is_none()); // Expire cooldown and cancel the half-open probe: circuit must stay open. expire_open(&breaker); - let err = run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, || async { - Err(TestError::Cancelled) - }) - .await - .unwrap_err(); + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Cancelled) + }) + .await + .unwrap_err(); assert_eq!(err, TestError::Cancelled); assert!(breaker.enter().is_none()); } + + #[tokio::test] + async fn cancel_stops_retry_backoff_promptly() { + let breaker = OutageBreaker::new(3, Duration::from_secs(30)); + let rate_limit = RateLimit::default(); + let policy = RetryPolicy { + max_retries: 2, + base_delay: Duration::from_secs(30), + max_delay: Duration::from_secs(30), + max_elapsed: Duration::from_secs(60), + ..RetryPolicy::READ + }; + let cancel = CancellationToken::new(); + let cancel_on_attempt = cancel.clone(); + let attempts = std::sync::atomic::AtomicU32::new(0); + + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || { + attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + cancel_on_attempt.cancel(); + async { Err(TestError::Outage) } + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Cancelled); + assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1); + } } diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index 62d5caca4..b23fc2fac 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -16,6 +16,6 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error::retry_hint` classifies failures into `RetryHint::{Permanent, Transient, RateLimited { retry_after }, Outage}` to inform those policies. -reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 20-second per-attempt timeout. +reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 10-second per-attempt timeout. `Error` names the kind of failure: an invalid endpoint, a client that couldn't be created, a blob file that couldn't be read, credentials that couldn't be obtained, a network error (including timeouts and responses that end early), a status other than 200 (or 404, for a fetch), or a malformed fetch response. Its messages contain no OS-specific details, so they can be shown to users as is. The details are in the source: the underlying error, the parse error for an endpoint that isn't a URL, or the message in an error response's body. Network errors leave out the request URL, since the endpoint may contain credentials, such as a token in its query. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index d030f4ecc..60e4a6209 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -31,9 +31,9 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const READ_TIMEOUT: Duration = Duration::from_secs(60); /// Total timeout for a single `POST /fetch` request. Fetches transfer small -/// metadata payloads, so bounding them more tightly lets a hung lookup retry -/// or fall back quickly instead of stalling a task for [`READ_TIMEOUT`]. -const FETCH_TIMEOUT: Duration = Duration::from_secs(20); +/// metadata payloads, so bounding them to 10s lets a hung lookup retry once +/// within the caller's read retry budget instead of stalling for `READ_TIMEOUT`. +const FETCH_TIMEOUT: Duration = Duration::from_secs(10); /// Idle timeout for pooled HTTP/1.1 keep-alive connections, kept below typical /// NAT and edge proxy idle cutoffs to reduce stale-socket resets on reuse. From 4b5fb175b8275f821f942f7983d547481b20e011 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:53:45 +0800 Subject: [PATCH 8/9] fix(cache): keep local failures neutral in outage breaker and tighten retry bounds Co-authored-by: Gemini 4 Neon --- crates/vt/src/session/cache/mod.rs | 1 - crates/vt/src/session/cache/remote.rs | 25 ++++---- crates/vt/src/session/cache/remote/retry.rs | 71 ++++++++++++++++++--- crates/vt_remote_cache/README.md | 2 +- crates/vt_remote_cache/src/lib.rs | 24 ++++--- packages/tools/src/remote-cache/cli.ts | 3 + packages/tools/src/remote-cache/daemon.ts | 3 + 7 files changed, 99 insertions(+), 30 deletions(-) diff --git a/crates/vt/src/session/cache/mod.rs b/crates/vt/src/session/cache/mod.rs index ad0d9f257..49908b24f 100644 --- a/crates/vt/src/session/cache/mod.rs +++ b/crates/vt/src/session/cache/mod.rs @@ -574,7 +574,6 @@ impl Validation { } impl ExecutionCache { - #[tracing::instrument(level = "debug", skip_all)] pub fn load_from_path(path: &AbsolutePath) -> anyhow::Result { Self::load_from_path_with_no_backoff(path, false) } diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index b4e630d67..0e87d493e 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -88,7 +88,7 @@ impl RetryableError for UploadError { Self::Remote(err) => RetryAction::Failed(err.retry_hint()), Self::Interrupted => RetryAction::Cancelled, Self::Encode(_) | Self::Compress(_) | Self::TooLarge | Self::Unavailable => { - RetryAction::Failed(RetryHint::Permanent) + RetryAction::Failed(RetryHint::Local) } } } @@ -142,14 +142,14 @@ impl RetryableError for ReadError { match self { Self::Fetch(err) | Self::Download(err) => RetryAction::Failed(err.retry_hint()), Self::Cancelled => RetryAction::Cancelled, + Self::WriteArchive(_) | Self::Encode(_) | Self::Unavailable => { + RetryAction::Failed(RetryHint::Local) + } Self::CorruptValue(_) | Self::CorruptKey(_) | Self::MismatchedBlob | Self::CorruptArchive(_) - | Self::WriteArchive(_) - | Self::Validate(_) - | Self::Encode(_) - | Self::Unavailable => RetryAction::Failed(RetryHint::Permanent), + | Self::Validate(_) => RetryAction::Failed(RetryHint::Permanent), } } @@ -1573,7 +1573,7 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let remote_config = anonymous(&vt_str::format!("http://{}/projects/test", listener.local_addr().unwrap())); - let cooldown = Duration::from_millis(80); + let cooldown = Duration::from_millis(200); let retry = RetryConfig { read: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.read }, store: RetryPolicy { max_retries: 0, max_retry_after: cooldown, ..FAST_RETRY.store }, @@ -1589,6 +1589,7 @@ mod tests { }); let clients = RemoteClients::with_retry(retry); + let rate_limited_at = Instant::now(); let err = prepare_upload(&clients, &remote_config).unwrap().await.unwrap_err(); assert!( matches!(err, UploadError::Remote(ref r) if matches!(r.retry_hint(), RetryHint::RateLimited { .. })), @@ -1597,7 +1598,6 @@ mod tests { let key = cache_key(ResolvedGlobConfig::default_auto()); let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); - let fetch_start = Instant::now(); assert_eq!( clients .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) @@ -1605,18 +1605,19 @@ mod tests { .unwrap(), None ); + // Fetch must complete well before the store's 200 ms cooldown elapses. assert!( - fetch_start.elapsed() < Duration::from_millis(50), + rate_limited_at.elapsed() < Duration::from_millis(150), "store 429 should not stall fetch: {:?}", - fetch_start.elapsed() + rate_limited_at.elapsed() ); - let store_start = Instant::now(); + // Peer store must wait until the full 200 ms cooldown measured from the 429. prepare_upload(&clients, &remote_config).unwrap().await.unwrap(); assert!( - store_start.elapsed() >= Duration::from_millis(40), + rate_limited_at.elapsed() >= Duration::from_millis(180), "peer store did not wait for shared 429 cooldown: {:?}", - store_start.elapsed() + rate_limited_at.elapsed() ); server.join().unwrap(); } diff --git a/crates/vt/src/session/cache/remote/retry.rs b/crates/vt/src/session/cache/remote/retry.rs index 6f380e395..374177e43 100644 --- a/crates/vt/src/session/cache/remote/retry.rs +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -12,8 +12,13 @@ use tokio::time::Instant; use tokio_util::sync::CancellationToken; use vt_remote_cache::RetryHint; -/// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response. -pub(super) const MAX_RETRY_AFTER: Duration = Duration::from_secs(10); +/// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response +/// for read operations on the task critical path. +pub(super) const MAX_READ_RETRY_AFTER: Duration = Duration::from_secs(2); + +/// Maximum `Retry-After` delay honored on a `429 Too Many Requests` response +/// for background store operations. +pub(super) const MAX_STORE_RETRY_AFTER: Duration = Duration::from_secs(10); /// Maximum extra jitter added when waking from a shared `429` cooldown so /// concurrent waiters do not fire in lockstep. @@ -72,7 +77,7 @@ impl RetryPolicy { max_retries: 2, base_delay: Duration::from_millis(250), max_delay: Duration::from_secs(5), - max_retry_after: MAX_RETRY_AFTER, + max_retry_after: MAX_READ_RETRY_AFTER, max_elapsed: Duration::from_secs(15), }; /// Retry policy for `POST /store` uploads: up to 3 retries (4 attempts @@ -82,7 +87,7 @@ impl RetryPolicy { max_retries: 3, base_delay: Duration::from_millis(500), max_delay: Duration::from_secs(10), - max_retry_after: MAX_RETRY_AFTER, + max_retry_after: MAX_STORE_RETRY_AFTER, max_elapsed: Duration::from_secs(60), }; @@ -370,10 +375,10 @@ where return Ok(value); } Err(error) => match error.retry_action() { - RetryAction::Cancelled => { - // Drop `permit` without finishing so cancelling a probe - // re-opens the cooldown and cancelling a normal request - // does not reset consecutive failures. + RetryAction::Cancelled | RetryAction::Failed(RetryHint::Local) => { + // Drop `permit` without finishing so cancelling or failing + // locally before contacting the endpoint re-opens a probe + // cooldown and does not reset consecutive outage failures. return Err(error); } RetryAction::Failed(RetryHint::Permanent) => { @@ -412,6 +417,7 @@ where let outcome = match hint { RetryHint::Outage => OutageOutcome::Outage, RetryHint::Transient + | RetryHint::Local | RetryHint::Permanent | RetryHint::RateLimited { .. } => OutageOutcome::Healthy, }; @@ -480,6 +486,7 @@ mod tests { #[derive(Debug, PartialEq, Eq)] enum TestError { Outage, + Local, Cancelled, } @@ -487,6 +494,7 @@ mod tests { fn retry_action(&self) -> RetryAction { match self { Self::Outage => RetryAction::Failed(RetryHint::Outage), + Self::Local => RetryAction::Failed(RetryHint::Local), Self::Cancelled => RetryAction::Cancelled, } } @@ -635,4 +643,51 @@ mod tests { assert_eq!(err, TestError::Cancelled); assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1); } + + #[tokio::test] + async fn local_failure_does_not_reset_failures_or_close_probe() { + let breaker = OutageBreaker::new(2, Duration::from_secs(30)); + let rate_limit = RateLimit::default(); + let policy = + RetryPolicy { max_retries: 0, base_delay: Duration::ZERO, ..RetryPolicy::READ }; + let cancel = CancellationToken::new(); + + // One outage failure followed by a pre-request local failure must not reset count. + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Outage) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Outage); + + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Local) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Local); + + // Second outage failure opens the circuit immediately. + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Outage) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Outage); + assert!(breaker.enter().is_none()); + + // Expire cooldown: a local failure during the half-open probe must re-open the circuit. + expire_open(&breaker); + let err = + run::<(), TestError, _, _>("test", policy, &rate_limit, &breaker, &cancel, || async { + Err(TestError::Local) + }) + .await + .unwrap_err(); + assert_eq!(err, TestError::Local); + assert!(breaker.enter().is_none()); + } } diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index b23fc2fac..c75430348 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -14,7 +14,7 @@ Client for the [remote cache server API](https://github.com/voidzero-dev/vite-ta `Client::store` sends a multipart request: a CBOR `metadata` part with the key, secondary key, and value as byte strings, and an optional `blob` part streamed from a file. The response body isn't decoded. -Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error::retry_hint` classifies failures into `RetryHint::{Permanent, Transient, RateLimited { retry_after }, Outage}` to inform those policies. +Only HTTP 200 counts as success for every operation, except that a fetch also accepts 404 as no match. Redirects aren't followed, so a redirect fails like any other status. Each method sends a single request and leaves retry, rate-limit, circuit-breaker, and concurrency policies to the caller; `Error::retry_hint` classifies failures into `RetryHint::{Local, Permanent, Transient, RateLimited { retry_after }, Outage}` to inform those policies. reqwest configures TLS. It uses the process's default rustls crypto provider, which the client installs as ring unless one is already installed, and verifies certificates with the operating system's verifier. Requests always use pooled HTTP/1.1 keep-alive connections (with a 30-second pool idle timeout and reqwest's default 15-second TCP keep-alive) so concurrent uploads and reads use independent sockets. Requests go through the proxy set in `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY`, except for hosts in `NO_PROXY`. Without those variables, the system proxy settings are used on macOS and Windows. Connections time out after 10 seconds. Reads time out after 60 seconds, and until the response headers arrive, that limit also covers sending the request; fetches have a 10-second per-attempt timeout. diff --git a/crates/vt_remote_cache/src/lib.rs b/crates/vt_remote_cache/src/lib.rs index 60e4a6209..5f9df2ebd 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -87,9 +87,13 @@ pub enum Error { /// failed remote cache request. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RetryHint { - /// Permanent or local failure that should not be retried (such as `4xx` - /// other than `408`/`429`, `501`/`505`/`511`, auth, blob I/O, or malformed - /// responses). + /// Failed locally before a request reached the endpoint (invalid endpoint, + /// HTTP client construction, local blob read, or auth failure). Should not + /// be retried and carries no signal about endpoint health. + Local, + /// Permanent response from the endpoint (such as `4xx` other than + /// `408`/`429`, `501`/`505`/`511`, or a malformed response). Should not be + /// retried, and indicates the endpoint is reachable. Permanent, /// Transient failure (`408 Request Timeout`) that can be retried with /// per-request backoff without counting toward a backend outage breaker. @@ -120,11 +124,10 @@ impl Error { 500 | 502..=504 | 506..=510 | 512..=599 => RetryHint::Outage, _ => RetryHint::Permanent, }, - Self::InvalidEndpoint(_) - | Self::HttpClient(_) - | Self::ReadBlob(_) - | Self::Auth(_) - | Self::MalformedResponse(_) => RetryHint::Permanent, + Self::MalformedResponse(_) => RetryHint::Permanent, + Self::InvalidEndpoint(_) | Self::HttpClient(_) | Self::ReadBlob(_) | Self::Auth(_) => { + RetryHint::Local + } } } } @@ -607,6 +610,11 @@ mod tests { let err = status_err(code, None); assert_eq!(err.retry_hint(), RetryHint::Permanent, "{code} should be permanent"); } + assert_eq!(Error::InvalidEndpoint(None).retry_hint(), RetryHint::Local); + assert_eq!( + Error::ReadBlob(std::io::Error::from(std::io::ErrorKind::NotFound)).retry_hint(), + RetryHint::Local + ); } fn client_for(listener: &TcpListener) -> Client { diff --git a/packages/tools/src/remote-cache/cli.ts b/packages/tools/src/remote-cache/cli.ts index 55f91f184..4e9027b57 100755 --- a/packages/tools/src/remote-cache/cli.ts +++ b/packages/tools/src/remote-cache/cli.ts @@ -169,6 +169,9 @@ async function run(argv: string[]): Promise { } const [command, ...args] = argv.slice(index); if (command === undefined) fail(usage); + if (releaseAfterFetches > 0 && holdStores === 0) { + fail('--release-after-fetches requires --hold-stores'); + } const info = readInfo(); const hasRunConfig = faults.length > 0 || alwaysFail.length > 0 || holdStores > 0 || summary; if (hasRunConfig) { diff --git a/packages/tools/src/remote-cache/daemon.ts b/packages/tools/src/remote-cache/daemon.ts index 580e52e0d..1719751c3 100644 --- a/packages/tools/src/remote-cache/daemon.ts +++ b/packages/tools/src/remote-cache/daemon.ts @@ -434,6 +434,9 @@ async function stop(): Promise { process.exit(0); } +// Keep pooled connections alive past the client's 30 s pool idle timeout so a +// slow gap between requests never races Node's 5 s default keep-alive cutoff. +tap.keepAliveTimeout = 60_000; const controlOrigin = `http://127.0.0.1:${await listen(control)}`; const info: ServerInfo = { url: `http://127.0.0.1:${await listen(tap)}${basePath}`, From 2bdf5b83a3125f8bc503b2f87b96a9ac407bca51 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:58:56 +0800 Subject: [PATCH 9/9] fix(cache): treat post-200 WriteArchive as healthy in read outage breaker Co-authored-by: Gemini 4 Neon --- crates/vt/src/session/cache/remote.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index 0e87d493e..8a276adbf 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -142,10 +142,11 @@ impl RetryableError for ReadError { match self { Self::Fetch(err) | Self::Download(err) => RetryAction::Failed(err.retry_hint()), Self::Cancelled => RetryAction::Cancelled, - Self::WriteArchive(_) | Self::Encode(_) | Self::Unavailable => { - RetryAction::Failed(RetryHint::Local) - } - Self::CorruptValue(_) + Self::Encode(_) | Self::Unavailable => RetryAction::Failed(RetryHint::Local), + // `WriteArchive` happens only after `GET /blob` returned `200 OK`, + // so the endpoint is healthy and should close a half-open probe. + Self::WriteArchive(_) + | Self::CorruptValue(_) | Self::CorruptKey(_) | Self::MismatchedBlob | Self::CorruptArchive(_)