forge
Explore
Log in

Don't you dare go Hollow

A cancelled or requeued job no longer throws away the build cache: a hit used to move the entry into the job's workspace and only a finished job put it back, so cancelling run #108 and the memory requeue in #109 left main with a cold cache and a full recompile of 674 crates

Browse files at this commit

c3349ae1926a19f75c128e8d8f4579e80dac7f78Ahmet Kaan GümüşParent: 1c2204b
All checks have passed
Show checks
  • perf
    • a cancelled or requeued job no longer throws away the build cache: a hit used to move the entry into the job's workspace and only a finished job put it back, so cancelling run #108 and the memory requeue in #109 left main with a cold cache and a full recompile of 674 crates
    • now a hit copies the entry (cp --reflink=auto) and only a job that succeeds or fails replaces it, several jobs can read one entry at once, and copies hold a read lock so a save or eviction cannot swap the entry halfway
    • forge's own CI caches CARGO_HOME in the workspace too, so a run downloads only new crates
Show full message
⚡ perf(ci): a cancelled or requeued job no longer throws away the build cache: a hit used to move the entry into the job's workspace and only a finished job put it back, so cancelling run #108 and the memory requeue in #109 left main with a cold cache and a full recompile of 674 crates; now a hit copies the entry (cp --reflink=auto) and only a job that succeeds or fails replaces it, several jobs can read one entry at once, and copies hold a read lock so a save or eviction cannot swap the entry halfway; forge's own CI caches CARGO_HOME in the workspace too, so a run downloads only new crates
.forge/ci.tomlmodified+5 -4
@@ -18,7 +18,8 @@ tags = ["v*"]
18 [jobs.test]18 [jobs.test]
19 image = "docker.io/library/rust:1"19 image = "docker.io/library/rust:1"
20 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo.20 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo.
21-env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" }21+# CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones.
22+env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home" }
22 # main.rs holds the whole forge-web crate, so `cargo test` compiles it twice: the `forge` binary23 # main.rs holds the whole forge-web crate, so `cargo test` compiles it twice: the `forge` binary
23 # (the e2e tests run it) and its unit-test harness, ~3.4 GB of rustc each. Built in parallel they24 # (the e2e tests run it) and its unit-test harness, ~3.4 GB of rustc each. Built in parallel they
24 # hit the runner's box cap and got OOM-killed now and then. The e2e build makes the binary first,25 # 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 = """
27 cargo test --workspace --no-run --test e2e28 cargo test --workspace --no-run --test e2e
28 cargo test --workspace29 cargo test --workspace
29 """30 """
30-cache = ["target"]31+cache = ["target", ".cargo-home"]
31 timeout_minutes = 12032 timeout_minutes = 120
32 33
33 [jobs.build]34 [jobs.build]
34 image = "docker.io/library/rust:1"35 image = "docker.io/library/rust:1"
35 needs = ["test"]36 needs = ["test"]
36 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit).37 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit).
37-env = { CARGO_INCREMENTAL = "0" }38+env = { CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home" }
38 run = """39 run = """
39 cargo build --profile dist -p forge-web -p forge-runner40 cargo build --profile dist -p forge-web -p forge-runner
40 ARCH=$(uname -m)41 ARCH=$(uname -m)
@@ -43,7 +44,7 @@ cp target/dist/forge-runner forge-runner-$ARCH-linux
43 sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS44 sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS
44 """45 """
45 artifacts = ["forge-*-linux", "SHA256SUMS"]46 artifacts = ["forge-*-linux", "SHA256SUMS"]
46-cache = ["target"]47+cache = ["target", ".cargo-home"]
47 timeout_minutes = 12048 timeout_minutes = 120
48 49
49 [release]50 [release]
crates/forge-runner/src/cache.rsmodified+48 -113
@@ -1,13 +1,15 @@
1 //! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`).1 //! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`).
2 //! When it finishes, those paths move out of its workspace into an entry. The next job for the2 //! When it finishes, those paths move out of its workspace into an entry. The next job for the
3-//! same repo, job name and cache key moves them back in.3+//! same repo, job name and cache key gets a copy, so the entry stays as it is until a finished
4+//! job replaces it. A cancelled or lost job never touches it.
4 //!5 //!
5 //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids6 //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids
6 //! never start with one:7 //! never start with one:
7 //! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached8 //! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached
8 //! paths, `manifest.json` (the workspace path of each `pN`) and `meta.json`.9 //! paths, `manifest.json` (the workspace path of each `pN`) and `meta.json`.
9-//! - `.new-<job>`, `.old-<job>` and `.inuse-<job>` are one job's scratch dirs. A crashed job can10+//! - `.new-<job>` and `.old-<job>` are one job's scratch dirs. A crashed job can leave them behind,
10-//! leave them behind, and [`CacheStore::sweep_stale`] removes them at startup.11+//! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-<job>` is swept too: older
12+//! runners moved an entry there while a job used it.
11 //!13 //!
12 //! A restore never fails a job. A failure is logged and the job runs without the cache.14 //! A restore never fails a job. A failure is logged and the job runs without the cache.
13 15
@@ -77,8 +79,9 @@ pub struct CacheStore {
77 max_bytes: u64,79 max_bytes: u64,
78 idmap: IdMap,80 idmap: IdMap,
79 helper: PathBuf,81 helper: PathBuf,
80- /// Held while an entry is claimed, installed or evicted, so jobs never race on one.82+ /// Read while an entry is copied into a workspace, written while one is installed or evicted,
81- lock: tokio::sync::Mutex<()>,83+ /// so a copy never sees its entry swapped or removed halfway.
84+ lock: tokio::sync::RwLock<()>,
82 /// The last save stamp, so entries saved in the same nanosecond still order by save time.85 /// The last save stamp, so entries saved in the same nanosecond still order by save time.
83 last_stamp: AtomicU64,86 last_stamp: AtomicU64,
84 }87 }
@@ -92,7 +95,7 @@ impl CacheStore {
92 max_bytes,95 max_bytes,
93 idmap,96 idmap,
94 helper,97 helper,
95- lock: tokio::sync::Mutex::new(()),98+ lock: tokio::sync::RwLock::new(()),
96 last_stamp: AtomicU64::new(0),99 last_stamp: AtomicU64::new(0),
97 }100 }
98 }101 }
@@ -132,23 +135,17 @@ impl CacheStore {
132 }135 }
133 };136 };
134 137
135- if !job.cache_key.is_empty() {138+ if !job.cache_key.is_empty()
136- let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);139+ && let Some(size) = self
137- match self.claim(&job.job_id, &entry).await {140+ .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines)
138- Ok(Some(inuse)) => {141+ .await
139- let size = self142+ {
140- .restore_claimed(&inuse, workspace, &wanted, &mut lines)143+ lines.push(format!(
141- .await;144+ "runner: cache hit {} ({})",
142- lines.push(format!(145+ job.cache_key,
143- "runner: cache hit {} ({})",146+ human(size)
144- job.cache_key,147+ ));
145- human(size)148+ return lines;
146- ));
147- return lines;
148- }
149- Ok(None) => {}
150- Err(e) => lines.push(format!("runner: cache restore failed: {e}")),
151- }
152 }149 }
153 150
154 for key in &job.cache_restore_keys {151 for key in &job.cache_restore_keys {
@@ -156,9 +153,11 @@ impl CacheStore {
156 continue;153 continue;
157 }154 }
158 if self155 if self
159- .restore_fallback(job, key, workspace, &wanted, &mut lines)156+ .restore_from(job, key, workspace, &wanted, &mut lines)
160 .await157 .await
158+ .is_some()
161 {159 {
160+ lines.push(format!("runner: cache restored from fallback {key}"));
162 return lines;161 return lines;
163 }162 }
164 }163 }
@@ -193,59 +192,26 @@ impl CacheStore {
193 lines192 lines
194 }193 }
195 194
196- /// Moves a claimed entry's wanted paths into the workspace. Returns the entry size. A path195+ /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is.
197- /// that fails is logged and the rest still restore.196+ /// Returns the entry size when at least one path was restored.
198- async fn restore_claimed(197+ async fn restore_from(
199- &self,
200- inuse: &Path,
201- workspace: &Path,
202- wanted: &[PathBuf],
203- lines: &mut Vec<String>,
204- ) -> u64 {
205- let size = match read_meta(inuse) {
206- Some(meta) => meta.size_bytes,
207- None => dir_size(inuse).await,
208- };
209- let manifest = match read_manifest(inuse) {
210- Ok(manifest) => manifest,
211- Err(e) => {
212- lines.push(format!("runner: cache restore failed: {e}"));
213- return size;
214- }
215- };
216- for (k, rel) in selected(&manifest, wanted, lines) {
217- let src = inuse.join(format!("p{k}"));
218- match move_into(workspace, &rel, &src).await {
219- Ok(true) => {}
220- Ok(false) => lines.push(skipped(&rel)),
221- Err(e) => lines.push(format!(
222- "runner: cache restore failed for {}: {e}",
223- rel.display()
224- )),
225- }
226- }
227- size
228- }
229-
230- /// Copies the fallback entry's wanted paths into the workspace. The fallback entry is never
231- /// moved. Returns true when at least one path was restored.
232- async fn restore_fallback(
233 &self,198 &self,
234 job: &JobAssignment,199 job: &JobAssignment,
235 key: &str,200 key: &str,
236 workspace: &Path,201 workspace: &Path,
237 wanted: &[PathBuf],202 wanted: &[PathBuf],
238 lines: &mut Vec<String>,203 lines: &mut Vec<String>,
239- ) -> bool {204+ ) -> Option<u64> {
205+ let _guard = self.lock.read().await;
240 let source = self.entry_dir(&job.repo, &job.job_name, key);206 let source = self.entry_dir(&job.repo, &job.job_name, key);
241 if !is_dir(&source) {207 if !is_dir(&source) {
242- return false;208+ return None;
243 }209 }
244 let manifest = match read_manifest(&source) {210 let manifest = match read_manifest(&source) {
245 Ok(manifest) => manifest,211 Ok(manifest) => manifest,
246 Err(e) => {212 Err(e) => {
247 lines.push(format!("runner: cache restore failed: {e}"));213 lines.push(format!("runner: cache restore failed: {e}"));
248- return false;214+ return None;
249 }215 }
250 };216 };
251 let mut restored = 0usize;217 let mut restored = 0usize;
@@ -261,10 +227,12 @@ impl CacheStore {
261 }227 }
262 }228 }
263 if restored == 0 {229 if restored == 0 {
264- return false;230+ return None;
265 }231 }
266- lines.push(format!("runner: cache restored from fallback {key}"));232+ Some(match read_meta(&source) {
267- true233+ Some(meta) => meta.size_bytes,
234+ None => dir_size(&source).await,
235+ })
268 }236 }
269 237
270 /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked238 /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked
@@ -317,7 +285,7 @@ impl CacheStore {
317 let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);285 let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);
318 let old = self.scratch(".old-", &job.job_id);286 let old = self.scratch(".old-", &job.job_id);
319 {287 {
320- let _guard = self.lock.lock().await;288+ let _guard = self.lock.write().await;
321 self.remove(&old).await?;289 self.remove(&old).await?;
322 let had_old = is_dir(&entry);290 let had_old = is_dir(&entry);
323 if had_old {291 if had_old {
@@ -340,22 +308,6 @@ impl CacheStore {
340 Ok(())308 Ok(())
341 }309 }
342 310
343- /// Moves the entry to this job's `.inuse` dir, so no other job can take it. `None` means there
344- /// is no entry, or another job got it first.
345- async fn claim(&self, job_id: &str, entry: &Path) -> Result<Option<PathBuf>, CacheError> {
346- let _guard = self.lock.lock().await;
347- if !is_dir(entry) {
348- return Ok(None);
349- }
350- let inuse = self.scratch(".inuse-", job_id);
351- self.remove(&inuse).await?;
352- match tokio::fs::rename(entry, &inuse).await {
353- Ok(()) => Ok(Some(inuse)),
354- Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
355- Err(e) => Err(e.into()),
356- }
357- }
358-
359 /// Removes the least recently saved entries until the total is within the cap. The caller311 /// Removes the least recently saved entries until the total is within the cap. The caller
360 /// holds the lock. Returns how many entries went.312 /// holds the lock. Returns how many entries went.
361 async fn evict(&self) -> Result<usize, CacheError> {313 async fn evict(&self) -> Result<usize, CacheError> {
@@ -587,18 +539,6 @@ fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>
587 Ok(exists_no_follow(&path).then_some(path))539 Ok(exists_no_follow(&path).then_some(path))
588 }540 }
589 541
590-/// Moves `src` to `workspace/rel`. Returns false when the checkout already has something there.
591-async fn move_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {
592- let Some(dest) = workspace_path(workspace, rel, true)? else {
593- return Ok(false);
594- };
595- if exists_no_follow(&dest) {
596- return Ok(false);
597- }
598- tokio::fs::rename(src, &dest).await?;
599- Ok(true)
600-}
601-
602 /// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place.542 /// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place.
603 /// Returns false when the checkout already has something there.543 /// Returns false when the checkout already has something there.
604 async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {544 async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {
@@ -803,7 +743,7 @@ mod tests {
803 }743 }
804 744
805 #[tokio::test]745 #[tokio::test]
806- async fn hit_moves_the_entry_and_hides_it_while_in_use() {746+ async fn hit_copies_and_only_a_finished_job_replaces_the_entry() {
807 let dir = tempfile::tempdir().expect("tempdir");747 let dir = tempfile::tempdir().expect("tempdir");
808 let store = store(dir.path(), 1 << 30);748 let store = store(dir.path(), 1 << 30);
809 let first = job("job_a", "ref:refs/heads/main", &[], &["target"]);749 let first = job("job_a", "ref:refs/heads/main", &[], &["target"]);
@@ -825,25 +765,20 @@ mod tests {
825 "{lines:?}"765 "{lines:?}"
826 );766 );
827 assert_eq!(read(&ws2.join("target/a.txt")), "one");767 assert_eq!(read(&ws2.join("target/a.txt")), "one");
828- assert!(
829- !entry_of(&store, "ref:refs/heads/main").exists(),
830- "a hit moves the entry"
831- );
832- assert!(store.root.join(".inuse-job_b").is_dir());
833 768
834- // Another job for the same key finds nothing while the first one holds the entry.769+ // A cancelled job leaves the entry as it was.
770+ fs::write(ws2.join("target/a.txt"), "half").expect("write");
771+ store.save(&second, Outcome::Cancelled, &ws2).await;
772+ let entry = entry_of(&store, "ref:refs/heads/main");
773+ assert_eq!(read(&entry.join("p0/a.txt")), "one");
774+
775+ // Another job hits the same entry, and its finished save replaces it.
835 let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);776 let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);
836 let ws3 = empty_workspace(dir.path(), "ws_c");777 let ws3 = empty_workspace(dir.path(), "ws_c");
837- assert_eq!(778+ store.restore(&third, &ws3).await;
838- store.restore(&third, &ws3).await,779+ fs::write(ws3.join("target/a.txt"), "two").expect("write");
839- vec!["runner: cache miss".to_owned()]780+ store.save(&third, Outcome::Success, &ws3).await;
840- );781+ assert_eq!(read(&entry.join("p0/a.txt")), "two");
841- assert!(!ws3.join("target").exists());
842-
843- // The finished job's scratch dir is gone, and its save puts the entry back.
844- store.save(&second, Outcome::Success, &ws2).await;
845- assert!(!store.root.join(".inuse-job_b").exists());
846- assert!(entry_of(&store, "ref:refs/heads/main").is_dir());
847 }782 }
848 783
849 #[tokio::test]784 #[tokio::test]
docs/ci.mdmodified+3 -2
@@ -740,8 +740,9 @@ or a pull request. Two jobs never share a cache, and two repos never do either.
740 - A pull request run writes only its own cache, keyed by the pull request number. It reads its740 - A pull request run writes only its own cache, keyed by the pull request number. It reads its
741 base branch's cache, then the default branch's cache. A pull request never writes a branch cache,741 base branch's cache, then the default branch's cache. A pull request never writes a branch cache,
742 so a change under review cannot leave a cache that a later build of `main` will use.742 so a change under review cannot leave a cache that a later build of `main` will use.
743-- When a branch is reused, its cache is moved to the new run, not copied. Only one run owns it at a743+- A run gets a copy of its cache, so several runs can use one cache at once. A job that succeeds
744- time.744+ or fails replaces the cache with its own. A job that is cancelled, errors or is requeued leaves
745+ it as it was.
745 - The runner caps the total size of its caches. When the cap is reached, the least recently used746 - The runner caps the total size of its caches. When the cap is reached, the least recently used
746 entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`.747 entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`.
747 748