From c3349ae1926a19f75c128e8d8f4579e80dac7f78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 29 Oct 2026 21:35:43 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf(ci):=20a=20cancelled=20or=20re?= =?UTF-8?q?queued=20job=20no=20longer=20throws=20away=20the=20build=20cach?= =?UTF-8?q?e:=20a=20hit=20used=20to=20move=20the=20entry=20into=20the=20jo?= =?UTF-8?q?b's=20workspace=20and=20only=20a=20finished=20job=20put=20it=20?= =?UTF-8?q?back,=20so=20cancelling=20run=20#108=20and=20the=20memory=20req?= =?UTF-8?q?ueue=20in=20#109=20left=20main=20with=20a=20cold=20cache=20and?= =?UTF-8?q?=20a=20full=20recompile=20of=20674=20crates;=20now=20a=20hit=20?= =?UTF-8?q?copies=20the=20entry=20(cp=20--reflink=3Dauto)=20and=20only=20a?= =?UTF-8?q?=20job=20that=20succeeds=20or=20fails=20replaces=20it,=20severa?= =?UTF-8?q?l=20jobs=20can=20read=20one=20entry=20at=20once,=20and=20copies?= =?UTF-8?q?=20hold=20a=20read=20lock=20so=20a=20save=20or=20eviction=20can?= =?UTF-8?q?not=20swap=20the=20entry=20halfway;=20forge's=20own=20CI=20cach?= =?UTF-8?q?es=20CARGO=5FHOME=20in=20the=20workspace=20too,=20so=20a=20run?= =?UTF-8?q?=20downloads=20only=20new=20crates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .forge/ci.toml | 9 +- crates/forge-runner/src/cache.rs | 161 +++++++++---------------------- docs/ci.md | 5 +- 3 files changed, 56 insertions(+), 119 deletions(-) diff --git a/.forge/ci.toml b/.forge/ci.toml index de74939..d08af2f 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -18,7 +18,8 @@ tags = ["v*"] [jobs.test] image = "docker.io/library/rust:1" # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo. -env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } +# CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones. +env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home" } # main.rs holds the whole forge-web crate, so `cargo test` compiles it twice: the `forge` binary # (the e2e tests run it) and its unit-test harness, ~3.4 GB of rustc each. Built in parallel they # hit the runner's box cap and got OOM-killed now and then. The e2e build makes the binary first, @@ -27,14 +28,14 @@ run = """ cargo test --workspace --no-run --test e2e cargo test --workspace """ -cache = ["target"] +cache = ["target", ".cargo-home"] timeout_minutes = 120 [jobs.build] image = "docker.io/library/rust:1" needs = ["test"] # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). -env = { CARGO_INCREMENTAL = "0" } +env = { CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home" } run = """ cargo build --profile dist -p forge-web -p forge-runner ARCH=$(uname -m) @@ -43,7 +44,7 @@ cp target/dist/forge-runner forge-runner-$ARCH-linux sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS """ artifacts = ["forge-*-linux", "SHA256SUMS"] -cache = ["target"] +cache = ["target", ".cargo-home"] timeout_minutes = 120 [release] diff --git a/crates/forge-runner/src/cache.rs b/crates/forge-runner/src/cache.rs index 4ee8715..f5e46c7 100644 --- a/crates/forge-runner/src/cache.rs +++ b/crates/forge-runner/src/cache.rs @@ -1,13 +1,15 @@ //! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`). //! When it finishes, those paths move out of its workspace into an entry. The next job for the -//! same repo, job name and cache key moves them back in. +//! same repo, job name and cache key gets a copy, so the entry stays as it is until a finished +//! job replaces it. A cancelled or lost job never touches it. //! //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids //! never start with one: //! - `/` is one entry. It holds `p0`, `p1`, ... for the cached //! paths, `manifest.json` (the workspace path of each `pN`) and `meta.json`. -//! - `.new-`, `.old-` and `.inuse-` are one job's scratch dirs. A crashed job can -//! leave them behind, and [`CacheStore::sweep_stale`] removes them at startup. +//! - `.new-` and `.old-` are one job's scratch dirs. A crashed job can leave them behind, +//! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-` is swept too: older +//! runners moved an entry there while a job used it. //! //! A restore never fails a job. A failure is logged and the job runs without the cache. @@ -77,8 +79,9 @@ pub struct CacheStore { max_bytes: u64, idmap: IdMap, helper: PathBuf, - /// Held while an entry is claimed, installed or evicted, so jobs never race on one. - lock: tokio::sync::Mutex<()>, + /// Read while an entry is copied into a workspace, written while one is installed or evicted, + /// so a copy never sees its entry swapped or removed halfway. + lock: tokio::sync::RwLock<()>, /// The last save stamp, so entries saved in the same nanosecond still order by save time. last_stamp: AtomicU64, } @@ -92,7 +95,7 @@ impl CacheStore { max_bytes, idmap, helper, - lock: tokio::sync::Mutex::new(()), + lock: tokio::sync::RwLock::new(()), last_stamp: AtomicU64::new(0), } } @@ -132,23 +135,17 @@ impl CacheStore { } }; - if !job.cache_key.is_empty() { - let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); - match self.claim(&job.job_id, &entry).await { - Ok(Some(inuse)) => { - let size = self - .restore_claimed(&inuse, workspace, &wanted, &mut lines) - .await; - lines.push(format!( - "runner: cache hit {} ({})", - job.cache_key, - human(size) - )); - return lines; - } - Ok(None) => {} - Err(e) => lines.push(format!("runner: cache restore failed: {e}")), - } + if !job.cache_key.is_empty() + && let Some(size) = self + .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines) + .await + { + lines.push(format!( + "runner: cache hit {} ({})", + job.cache_key, + human(size) + )); + return lines; } for key in &job.cache_restore_keys { @@ -156,9 +153,11 @@ impl CacheStore { continue; } if self - .restore_fallback(job, key, workspace, &wanted, &mut lines) + .restore_from(job, key, workspace, &wanted, &mut lines) .await + .is_some() { + lines.push(format!("runner: cache restored from fallback {key}")); return lines; } } @@ -193,59 +192,26 @@ impl CacheStore { lines } - /// Moves a claimed entry's wanted paths into the workspace. Returns the entry size. A path - /// that fails is logged and the rest still restore. - async fn restore_claimed( - &self, - inuse: &Path, - workspace: &Path, - wanted: &[PathBuf], - lines: &mut Vec, - ) -> u64 { - let size = match read_meta(inuse) { - Some(meta) => meta.size_bytes, - None => dir_size(inuse).await, - }; - let manifest = match read_manifest(inuse) { - Ok(manifest) => manifest, - Err(e) => { - lines.push(format!("runner: cache restore failed: {e}")); - return size; - } - }; - for (k, rel) in selected(&manifest, wanted, lines) { - let src = inuse.join(format!("p{k}")); - match move_into(workspace, &rel, &src).await { - Ok(true) => {} - Ok(false) => lines.push(skipped(&rel)), - Err(e) => lines.push(format!( - "runner: cache restore failed for {}: {e}", - rel.display() - )), - } - } - size - } - - /// Copies the fallback entry's wanted paths into the workspace. The fallback entry is never - /// moved. Returns true when at least one path was restored. - async fn restore_fallback( + /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is. + /// Returns the entry size when at least one path was restored. + async fn restore_from( &self, job: &JobAssignment, key: &str, workspace: &Path, wanted: &[PathBuf], lines: &mut Vec, - ) -> bool { + ) -> Option { + let _guard = self.lock.read().await; let source = self.entry_dir(&job.repo, &job.job_name, key); if !is_dir(&source) { - return false; + return None; } let manifest = match read_manifest(&source) { Ok(manifest) => manifest, Err(e) => { lines.push(format!("runner: cache restore failed: {e}")); - return false; + return None; } }; let mut restored = 0usize; @@ -261,10 +227,12 @@ impl CacheStore { } } if restored == 0 { - return false; + return None; } - lines.push(format!("runner: cache restored from fallback {key}")); - true + Some(match read_meta(&source) { + Some(meta) => meta.size_bytes, + None => dir_size(&source).await, + }) } /// Builds the new entry in `.new-` and installs it over the old one. Caller has checked @@ -317,7 +285,7 @@ impl CacheStore { let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); let old = self.scratch(".old-", &job.job_id); { - let _guard = self.lock.lock().await; + let _guard = self.lock.write().await; self.remove(&old).await?; let had_old = is_dir(&entry); if had_old { @@ -340,22 +308,6 @@ impl CacheStore { Ok(()) } - /// Moves the entry to this job's `.inuse` dir, so no other job can take it. `None` means there - /// is no entry, or another job got it first. - async fn claim(&self, job_id: &str, entry: &Path) -> Result, CacheError> { - let _guard = self.lock.lock().await; - if !is_dir(entry) { - return Ok(None); - } - let inuse = self.scratch(".inuse-", job_id); - self.remove(&inuse).await?; - match tokio::fs::rename(entry, &inuse).await { - Ok(()) => Ok(Some(inuse)), - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e.into()), - } - } - /// Removes the least recently saved entries until the total is within the cap. The caller /// holds the lock. Returns how many entries went. async fn evict(&self) -> Result { @@ -587,18 +539,6 @@ fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result Ok(exists_no_follow(&path).then_some(path)) } -/// Moves `src` to `workspace/rel`. Returns false when the checkout already has something there. -async fn move_into(workspace: &Path, rel: &Path, src: &Path) -> Result { - let Some(dest) = workspace_path(workspace, rel, true)? else { - return Ok(false); - }; - if exists_no_follow(&dest) { - return Ok(false); - } - tokio::fs::rename(src, &dest).await?; - Ok(true) -} - /// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place. /// Returns false when the checkout already has something there. async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result { @@ -803,7 +743,7 @@ mod tests { } #[tokio::test] - async fn hit_moves_the_entry_and_hides_it_while_in_use() { + async fn hit_copies_and_only_a_finished_job_replaces_the_entry() { let dir = tempfile::tempdir().expect("tempdir"); let store = store(dir.path(), 1 << 30); let first = job("job_a", "ref:refs/heads/main", &[], &["target"]); @@ -825,25 +765,20 @@ mod tests { "{lines:?}" ); assert_eq!(read(&ws2.join("target/a.txt")), "one"); - assert!( - !entry_of(&store, "ref:refs/heads/main").exists(), - "a hit moves the entry" - ); - assert!(store.root.join(".inuse-job_b").is_dir()); - // Another job for the same key finds nothing while the first one holds the entry. + // A cancelled job leaves the entry as it was. + fs::write(ws2.join("target/a.txt"), "half").expect("write"); + store.save(&second, Outcome::Cancelled, &ws2).await; + let entry = entry_of(&store, "ref:refs/heads/main"); + assert_eq!(read(&entry.join("p0/a.txt")), "one"); + + // Another job hits the same entry, and its finished save replaces it. let third = job("job_c", "ref:refs/heads/main", &[], &["target"]); let ws3 = empty_workspace(dir.path(), "ws_c"); - assert_eq!( - store.restore(&third, &ws3).await, - vec!["runner: cache miss".to_owned()] - ); - assert!(!ws3.join("target").exists()); - - // The finished job's scratch dir is gone, and its save puts the entry back. - store.save(&second, Outcome::Success, &ws2).await; - assert!(!store.root.join(".inuse-job_b").exists()); - assert!(entry_of(&store, "ref:refs/heads/main").is_dir()); + store.restore(&third, &ws3).await; + fs::write(ws3.join("target/a.txt"), "two").expect("write"); + store.save(&third, Outcome::Success, &ws3).await; + assert_eq!(read(&entry.join("p0/a.txt")), "two"); } #[tokio::test] diff --git a/docs/ci.md b/docs/ci.md index fbad61d..ba52ee8 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -740,8 +740,9 @@ or a pull request. Two jobs never share a cache, and two repos never do either. - A pull request run writes only its own cache, keyed by the pull request number. It reads its base branch's cache, then the default branch's cache. A pull request never writes a branch cache, so a change under review cannot leave a cache that a later build of `main` will use. -- When a branch is reused, its cache is moved to the new run, not copied. Only one run owns it at a - time. +- A run gets a copy of its cache, so several runs can use one cache at once. A job that succeeds + or fails replaces the cache with its own. A job that is cancelled, errors or is requeued leaves + it as it was. - The runner caps the total size of its caches. When the cap is reached, the least recently used entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`.