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..ec8175b57 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", @@ -5009,6 +4988,7 @@ dependencies = [ "derive_more", "fspy", "futures-util", + "getrandom 0.4.2", "nix 0.31.2", "once_cell", "owo-colors", 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/mod.rs b/crates/vt/src/session/cache/mod.rs index 820ad8ea6..49908b24f 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, @@ -573,8 +574,15 @@ 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 +609,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 e9864f849..8a276adbf 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -13,6 +13,8 @@ //! 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 _}, @@ -22,7 +24,7 @@ use std::{ 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; @@ -31,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; @@ -40,11 +42,25 @@ use wincode::{ error::{WriteError, WriteResult}, }; +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, }; +/// 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 +/// 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 +76,30 @@ 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 retry_action(&self) -> RetryAction { + match self { + Self::Remote(err) => RetryAction::Failed(err.retry_hint()), + Self::Interrupted => RetryAction::Cancelled, + Self::Encode(_) | Self::Compress(_) | Self::TooLarge | Self::Unavailable => { + RetryAction::Failed(RetryHint::Local) + } + } + } + + 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 @@ -91,6 +131,36 @@ 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 retry_action(&self) -> RetryAction { + match self { + Self::Fetch(err) | Self::Download(err) => RetryAction::Failed(err.retry_hint()), + Self::Cancelled => RetryAction::Cancelled, + 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(_) + | Self::Validate(_) => RetryAction::Failed(RetryHint::Permanent), + } + } + + fn unavailable() -> Self { + Self::Unavailable + } + + fn cancelled() -> Self { + Self::Cancelled + } } impl ReadError { @@ -195,28 +265,159 @@ 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> { + 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( + &self, + blob_id: &str, + path: &AbsolutePath, + cancel_token: &CancellationToken, + ) -> Result<(), ReadError> { + // 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( + &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 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) + .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( + 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 } + } + + 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 +431,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 +450,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 +487,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 +498,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,10 +591,11 @@ 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. -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, @@ -424,10 +619,21 @@ async fn download_checked( // 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. + // file is closed before the caller removes it or retries. let checked = check.await.unwrap_or_else(|err| Err(ReadError::CorruptArchive(err.into()))); - sent.ok_or(ReadError::Cancelled)?.map_err(ReadError::Download)?; - checked + 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(ReadError::Download(err)) + } + } } /// Send the blob's chunks through `sender` until the blob ends or the receiver @@ -554,7 +760,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; @@ -565,7 +776,7 @@ mod tests { remote_cache::{GithubOidcAuth, RemoteCacheAccess, Secret}, }; - use super::*; + use super::{retry::RetryPolicy, *}; use crate::session::{ cache::{Change, FileCheck, InputChangeKind}, execute::{ @@ -574,6 +785,17 @@ mod tests { }, }; + /// Zero-delay retry config with production attempt counts so tests + /// exercise the full retry loop without sleeping. + const FAST_RETRY: RetryConfig = RetryConfig::NO_BACKOFF; + + /// 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. @@ -1081,7 +1303,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 { @@ -1092,11 +1314,11 @@ mod tests { }), ..unreachable.clone() }; - let clients = RemoteClients::default(); + let clients = RemoteClients::with_retry(NO_RETRY); 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 +1330,519 @@ mod tests { } } + /// 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(); + { + 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(); + } + 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]; + // 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() + ) + .as_bytes(), + truncated_prefix, + ] + .concat(), + ); + // 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() + ) + .as_bytes(), + &archive_bytes, + ] + .concat(), + ); + }); + + let archive_name = RemoteClients::with_retry(FAST_RETRY) + .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 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(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 }, + ..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 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 { .. })), + "{err:?}" + ); + + let key = cache_key(ResolvedGlobConfig::default_auto()); + let execution_key = ExecutionCacheKey::ExecAPI(Arc::from([])); + assert_eq!( + clients + .fetch(&remote_config, &key, &execution_key, &CancellationToken::new()) + .await + .unwrap(), + None + ); + // Fetch must complete well before the store's 200 ms cooldown elapses. + assert!( + rate_limited_at.elapsed() < Duration::from_millis(150), + "store 429 should not stall fetch: {:?}", + rate_limited_at.elapsed() + ); + + // Peer store must wait until the full 200 ms cooldown measured from the 429. + prepare_upload(&clients, &remote_config).unwrap().await.unwrap(); + assert!( + rate_limited_at.elapsed() >= Duration::from_millis(180), + "peer store did not wait for shared 429 cooldown: {:?}", + rate_limited_at.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.retry_hint() == RetryHint::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.retry_hint() == RetryHint::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.retry_hint() == RetryHint::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 (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 = 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..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/src/session/cache/remote/retry.rs b/crates/vt/src/session/cache/remote/retry.rs new file mode 100644 index 000000000..374177e43 --- /dev/null +++ b/crates/vt/src/session/cache/remote/retry.rs @@ -0,0 +1,693 @@ +//! Retry policy, jittered exponential backoff, shared `429` cooldown +//! coordination, and per-kind outage circuit breakers for remote cache +//! requests. + +use std::{ + fmt::Debug, + sync::{Mutex, PoisonError}, + time::Duration, +}; + +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 +/// 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. +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); + +/// 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 { + /// 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; + /// Error returned when `cancel_token` cancels a wait between attempts. + fn cancelled() -> Self; +} + +/// Retry parameters for one kind of remote cache operation. +#[derive(Debug, Clone, Copy)] +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. + 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_READ_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_STORE_RETRY_AFTER, + max_elapsed: Duration::from_secs(60), + }; + + /// Single-attempt policy with no retries, preserving `max_retry_after` for + /// recording `429` cooldowns. + 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 remote endpoint. +#[derive(Debug, Clone, Copy)] +pub(super) 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, + }; + /// 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. +/// +/// 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(super) 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))); + } +} + +/// 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 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(super) struct OutageBreaker { + threshold: u32, + cooldown: Duration, + state: Mutex, +} + +#[derive(Debug)] +struct OutageState { + 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 { + phase: OutagePhase::Closed { failures: 0 }, + 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 = match state.phase { + OutagePhase::Closed { .. } => false, + OutagePhase::Open { until } if Instant::now() >= until => { + state.phase = OutagePhase::HalfOpen; + true + } + OutagePhase::Open { .. } | OutagePhase::HalfOpen => return None, + }; + 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(super) 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, outcome: OutageOutcome) { + if self.completed { + return; + } + let mut state = self.breaker.state.lock().unwrap_or_else(PoisonError::into_inner); + if state.generation == self.generation { + 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!( + cooldown = ?self.breaker.cooldown, + "remote cache circuit re-opened after probe failed" + ); + } + (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); + 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 && matches!(state.phase, OutagePhase::HalfOpen) { + state.phase = OutagePhase::Open { until: Instant::now() + self.breaker.cooldown }; + state.generation = state.generation.wrapping_add(1); + } + } + } +} + +/// 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 + E: RetryableError, + 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()); + }; + // 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); + for attempt in 0..total_attempts { + 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); + return Ok(value); + } + Err(error) => match error.retry_action() { + 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) => { + 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); + 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, + total_attempts, + ?cooldown, + ?error, + "retrying remote cache request after 429 cooldown" + ); + } + 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::Local + | RetryHint::Permanent + | RetryHint::RateLimited { .. } => OutageOutcome::Healthy, + }; + permit.finish(outcome); + return Err(error); + } + tracing::debug!( + operation, + attempt = attempt + 1, + total_attempts, + delay = ?backoff, + ?error, + "retrying remote cache request" + ); + if cancel_token.run_until_cancelled(sleep(backoff)).await.is_none() { + return Err(E::cancelled()); + } + } + }, + } + } + unreachable!("total_attempts is always at least 1") +} + +/// 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 super::*; + + #[derive(Debug, PartialEq, Eq)] + enum TestError { + Outage, + Local, + Cancelled, + } + + impl RetryableError for TestError { + fn retry_action(&self) -> RetryAction { + match self { + Self::Outage => RetryAction::Failed(RetryHint::Outage), + Self::Local => RetryAction::Failed(RetryHint::Local), + Self::Cancelled => RetryAction::Cancelled, + } + } + + fn unavailable() -> Self { + Self::Outage + } + + fn cancelled() -> Self { + Self::Cancelled + } + } + + 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); + 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 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 outage_breaker_opens_probes_recovers_and_handles_dropped_probes() { + let breaker = OutageBreaker::new(3, Duration::from_secs(30)); + + // Non-outage failure (e.g., 429) resets consecutive failure count. + 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(OutageOutcome::Outage); + } + assert!(breaker.enter().is_none()); + + // Expire cooldown: exactly one half-open probe is admitted. + expire_open(&breaker); + 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. + expire_open(&breaker); + breaker.enter().unwrap().finish(OutageOutcome::Outage); + assert!(breaker.enter().is_none()); + + // Successful probe closes the circuit. + expire_open(&breaker); + breaker.enter().unwrap().finish(OutageOutcome::Healthy); + 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 }; + + let cancel = CancellationToken::new(); + + // Open the circuit with one outage failure. + 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, &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); + } + + #[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/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/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..9d2ed3fff --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots.toml @@ -0,0 +1,181 @@ +# Deterministic, zero-sleep e2e tests for remote cache resilience: transient +# retry (fetch, store, blob download), per-kind outage circuit breaking, and +# 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 = [ + "remote-cache-server", + "run", + "--github-actions", + "--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 = [ + "remote-cache-server", + "run", + "--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." }, + [ + "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 = [ + "remote-cache-server", + "run", + "--github-actions", + "--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." }, + [ + "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 = [ + "remote-cache-server", + "run", + "--github-actions", + "--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 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 new file mode 100644 index 000000000..4ab839941 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/outage_circuit_breaker_per_kind.md @@ -0,0 +1,71 @@ +# 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. + +## `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. + +``` +$ 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 +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `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 new file mode 100644 index 000000000..83c8261f6 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/retry_transient_failures.md @@ -0,0 +1,70 @@ +# retry_transient_failures + +Transient 503, 429, connection-drop, and truncated-download errors are retried across fetch, store, and blob restore. + +## `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. + +``` +$ 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 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. + +``` +$ 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 exact [1] +[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. + +``` +``` + +## `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 new file mode 100644 index 000000000..d139b4b63 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/remote_cache_resilience/snapshots/upload_concurrency_cap.md @@ -0,0 +1,46 @@ +# upload_concurrency_cap + +At most 4 concurrent remote cache uploads are in flight at once, and full upload slots do not block fetches. + +## `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 --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 +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 +``` + +## `remote-cache-server stop` + +``` +``` 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": [] + } + } + } +} diff --git a/crates/vt_remote_cache/Cargo.toml b/crates/vt_remote_cache/Cargo.toml index 607665be6..bf80338ad 100644 --- a/crates/vt_remote_cache/Cargo.toml +++ b/crates/vt_remote_cache/Cargo.toml @@ -12,7 +12,6 @@ base64 = { workspace = true } bytes = { workspace = true } ciborium = { workspace = true } reqwest = { workspace = true, features = [ - "http2", "multipart", "rustls-no-provider", "stream", diff --git a/crates/vt_remote_cache/README.md b/crates/vt_remote_cache/README.md index 29c1ab722..c75430348 100644 --- a/crates/vt_remote_cache/README.md +++ b/crates/vt_remote_cache/README.md @@ -14,8 +14,8 @@ 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. +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. 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 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 5987090f8..5f9df2ebd 100644 --- a/crates/vt_remote_cache/src/lib.rs +++ b/crates/vt_remote_cache/src/lib.rs @@ -13,7 +13,7 @@ use std::{ use bytes::Bytes; use reqwest::{ Response, StatusCode, - header::{CONTENT_TYPE, HeaderMap}, + header::{CONTENT_TYPE, HeaderMap, RETRY_AFTER}, multipart::{Form, Part}, }; use serde::{Deserialize, Deserializer, Serialize}; @@ -30,6 +30,15 @@ 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` request. Fetches transfer small +/// 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. +const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(30); + /// 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. @@ -59,13 +68,70 @@ 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), } +/// 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 { + /// 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. + 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, +} + +impl Error { + /// Classify this failure for a caller's retry, rate-limit, and + /// circuit-breaker policy. + #[must_use] + pub const fn retry_hint(&self) -> RetryHint { + match self { + 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::MalformedResponse(_) => RetryHint::Permanent, + Self::InvalidEndpoint(_) | Self::HttpClient(_) | Self::ReadBlob(_) | Self::Auth(_) => { + RetryHint::Local + } + } + } +} + /// The message in the body of an error response. #[derive(Debug, thiserror::Error)] #[error("{0}")] @@ -142,6 +208,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, @@ -171,11 +240,16 @@ 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)?; @@ -205,6 +279,7 @@ impl Client { .post(self.fetch_url.clone()) .headers(headers) .header(CONTENT_TYPE, "application/cbor") + .timeout(FETCH_TIMEOUT) .body(body) .send() .await @@ -217,7 +292,11 @@ impl Client { 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"); + tracing::debug!( + bytes = body.len(), + elapsed = ?start.elapsed(), + "remote cache fetch received" + ); decode_fetched(&body).map(Some) } @@ -260,8 +339,8 @@ impl Client { 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 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); @@ -303,18 +382,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. +/// 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 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(Error::Status(status, message)) + Err(Error::Status { status, message, retry_after }) } fn network_error(err: reqwest::Error) -> Error { @@ -354,8 +442,8 @@ 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: 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. @@ -485,6 +573,50 @@ mod tests { } } + #[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); + } + + #[test] + 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, + retry_after, + }; + for code in [500, 502, 503, 504, 520, 524] { + let err = status_err(code, Some(Duration::from_secs(60))); + assert_eq!(err.retry_hint(), RetryHint::Outage, "{code} should be an outage"); + } + 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_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 { client_with_auth(listener, Arc::new(Anonymous)) } @@ -558,11 +690,25 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let client = client_for(&listener); let server = std::thread::spawn(move || { - serve_once(&listener, "HTTP/1.1 503 Service Unavailable", b"try later") + 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"); server.join().unwrap(); } @@ -629,17 +775,17 @@ mod tests { }); 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 request = server.join().unwrap(); + let blob_part = + b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; 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 = - b"name=\"blob\"\r\nContent-Type: application/octet-stream\r\n\r\narchive bytes\r\n"; - assert!(contains(&request, blob)); + assert!(contains(&request, blob_part)); } #[tokio::test] @@ -670,7 +816,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(); } @@ -772,7 +921,7 @@ 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( @@ -785,8 +934,10 @@ 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] 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..4e9027b57 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,72 @@ 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); + 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) { + 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..1719751c3 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) { @@ -241,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}`, 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'); }