forge
Explore
Log in

Don't you dare go Hollow

Per-branch build cache kept on the runner

Browse files at this commit

fabd8b33292eed0ce5428cb42149fecdf152fa16Ahmet Kaan GümüşParent: 98b537a
  • perf
    • per-branch build cache kept on the runner
Show full message
⚡ perf(ci): per-branch build cache kept on the runner

- Jobs list workspace paths to keep with `cache = ["target"]`.
- The runner moves a same-branch entry into the checkout and back after the run; a new
  branch starts from a copy of its base or default branch entry.
- The server picks the scope from the run's trigger: pushes write `ref:<ref>`, pull requests
  only `pr:<n>`, so a PR can never seed the cache a deploy build reuses.
- `cache_max_gib` (default 20, 0 = off) evicts the least recently saved entries.

🐛 deploy: exit 75 is a deliberate restart, not a failure. Without SuccessExitStatus the
OnFailure rollback ran on every self-update and restored the previous binary.
crates/forge-ci/src/config.rsmodified+156 -0
@@ -29,6 +29,10 @@ pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
2929 pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360;
3030 /// Longest workflow `name`, in characters, after trimming.
3131 pub const MAX_WORKFLOW_NAME_CHARS: usize = 40;
32+/// Largest number of `cache` entries in one job.
33+pub const MAX_CACHE_ENTRIES: usize = 8;
34+/// Longest `cache` entry, in characters.
35+pub const MAX_CACHE_PATH_CHARS: usize = 200;
3236
3337 /// A parsed and validated workflow.
3438 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -88,6 +92,9 @@ pub struct JobSpec {
8892 /// Runner labels; every label must be present on the runner.
8993 #[serde(default)]
9094 pub runs_on: Vec<String>,
95+ /// Workspace-relative directories to keep between runs, e.g. `"target"`. See docs/ci.md, Cache.
96+ #[serde(default)]
97+ pub cache: Vec<String>,
9198 #[serde(default = "default_timeout_minutes")]
9299 pub timeout_minutes: u32,
93100 #[serde(default = "default_network")]
@@ -296,6 +303,71 @@ fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> {
296303 .map_err(|e| invalid(&e.to_string()))
297304 }
298305
306+/// Checks the `cache` entries of one job: at most [`MAX_CACHE_ENTRIES`], each a valid
307+/// [`validate_cache_path`], and no duplicates.
308+fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> {
309+ if entries.len() > MAX_CACHE_ENTRIES {
310+ return Err(ConfigError::TooManyCacheEntries {
311+ job: job.to_string(),
312+ count: entries.len(),
313+ max: MAX_CACHE_ENTRIES,
314+ });
315+ }
316+ let mut seen = BTreeSet::new();
317+ for path in entries {
318+ validate_cache_path(job, path)?;
319+ if !seen.insert(path.as_str()) {
320+ return Err(ConfigError::DuplicateCachePath {
321+ job: job.to_string(),
322+ path: path.clone(),
323+ });
324+ }
325+ }
326+ Ok(())
327+}
328+
329+/// A cache path is a workspace-relative directory: non-empty, at most [`MAX_CACHE_PATH_CHARS`]
330+/// characters, no leading `/`, no `\`, no empty, `.` or `..` components, no `.git` component, no
331+/// glob characters and no control characters.
332+fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> {
333+ let invalid = |reason: &str| ConfigError::InvalidCachePath {
334+ job: job.to_string(),
335+ path: path.to_string(),
336+ reason: reason.to_string(),
337+ };
338+ if path.is_empty() {
339+ return Err(invalid("must not be empty"));
340+ }
341+ if path.chars().count() > MAX_CACHE_PATH_CHARS {
342+ return Err(invalid(&format!(
343+ "must be at most {MAX_CACHE_PATH_CHARS} characters"
344+ )));
345+ }
346+ if path.starts_with('/') {
347+ return Err(invalid("must be relative"));
348+ }
349+ if path.contains('\\') {
350+ return Err(invalid("must not contain a backslash"));
351+ }
352+ if path.chars().any(|c| "*?[]{}".contains(c)) {
353+ return Err(invalid("must not contain glob characters"));
354+ }
355+ if path.chars().any(char::is_control) {
356+ return Err(invalid("must not contain control characters"));
357+ }
358+ for part in path.split('/') {
359+ match part {
360+ "" => return Err(invalid("must not contain empty components")),
361+ "." | ".." => return Err(invalid("must not contain \".\" or \"..\" components")),
362+ _ if part.eq_ignore_ascii_case(".git") => {
363+ return Err(invalid("must not be inside .git"));
364+ }
365+ _ => {}
366+ }
367+ }
368+ Ok(())
369+}
370+
299371 fn validate_job(
300372 name: &str,
301373 job: &JobSpec,
@@ -349,6 +421,7 @@ fn validate_job(
349421 });
350422 }
351423 }
424+ validate_cache(name, &job.cache)?;
352425 if !TIMEOUT_RANGE_MINUTES.contains(&job.timeout_minutes) {
353426 return Err(ConfigError::InvalidTimeout {
354427 job: name.to_string(),
@@ -589,6 +662,89 @@ artifacts = ["target/release/forge"]
589662 assert!(matches!(err_of(&text), ConfigError::InvalidRunsOn { .. }));
590663 }
591664
665+ #[test]
666+ fn cache_defaults_to_empty() {
667+ assert!(
668+ parse_config(&job_toml("")).unwrap().jobs["build"]
669+ .cache
670+ .is_empty()
671+ );
672+ }
673+
674+ #[test]
675+ fn cache_accepts_relative_directories() {
676+ let text = job_toml("cache = [\"target\", \".cargo-home\", \"a/b/c\"]");
677+ assert_eq!(
678+ parse_config(&text).unwrap().jobs["build"].cache,
679+ vec![
680+ "target".to_string(),
681+ ".cargo-home".to_string(),
682+ "a/b/c".to_string()
683+ ]
684+ );
685+ let at_limit = "x".repeat(MAX_CACHE_PATH_CHARS);
686+ let text = job_toml(&format!("cache = [{at_limit:?}]"));
687+ assert!(parse_config(&text).is_ok());
688+ }
689+
690+ #[test]
691+ fn cache_rejects_bad_paths() {
692+ let long = "x".repeat(MAX_CACHE_PATH_CHARS + 1);
693+ let bad = [
694+ "".to_string(),
695+ "/abs".to_string(),
696+ "a\\b".to_string(),
697+ "..".to_string(),
698+ "a/../b".to_string(),
699+ "./target".to_string(),
700+ ".".to_string(),
701+ "a//b".to_string(),
702+ "target/".to_string(),
703+ ".git".to_string(),
704+ ".git/objects".to_string(),
705+ "sub/.GIT/x".to_string(),
706+ "target/*".to_string(),
707+ "t?rget".to_string(),
708+ "[t]".to_string(),
709+ "{a,b}".to_string(),
710+ long,
711+ ];
712+ // A control character, written as a TOML escape.
713+ let text = job_toml(r#"cache = ["a\u0007b"]"#);
714+ assert!(matches!(
715+ err_of(&text),
716+ ConfigError::InvalidCachePath { .. }
717+ ));
718+ for path in bad {
719+ let text = job_toml(&format!("cache = [{path:?}]"));
720+ assert!(
721+ matches!(err_of(&text), ConfigError::InvalidCachePath { .. }),
722+ "cache path {path:?} should be rejected"
723+ );
724+ }
725+ }
726+
727+ #[test]
728+ fn cache_rejects_duplicates_and_too_many_entries() {
729+ let text = job_toml("cache = [\"target\", \"target\"]");
730+ assert!(matches!(
731+ err_of(&text),
732+ ConfigError::DuplicateCachePath { .. }
733+ ));
734+ let entries: Vec<String> = (0..=MAX_CACHE_ENTRIES).map(|i| format!("d{i}")).collect();
735+ let text = job_toml(&format!("cache = {entries:?}"));
736+ assert_eq!(
737+ err_of(&text),
738+ ConfigError::TooManyCacheEntries {
739+ job: "build".into(),
740+ count: MAX_CACHE_ENTRIES + 1,
741+ max: MAX_CACHE_ENTRIES
742+ }
743+ );
744+ let text = job_toml(&format!("cache = {:?}", &entries[..MAX_CACHE_ENTRIES]));
745+ assert!(parse_config(&text).is_ok());
746+ }
747+
592748 #[test]
593749 fn timeout_validation() {
594750 assert_eq!(
crates/forge-ci/src/error.rsmodified+17 -0
@@ -54,6 +54,23 @@ pub enum ConfigError {
5454 #[error("job {job:?}: timeout_minutes must be between 1 and 360, got {value}")]
5555 InvalidTimeout { job: String, value: u32 },
5656
57+ #[error("job {job:?}: invalid cache path {path:?}: {reason}")]
58+ InvalidCachePath {
59+ job: String,
60+ path: String,
61+ reason: String,
62+ },
63+
64+ #[error("job {job:?}: cache lists {count} entries, the limit is {max}")]
65+ TooManyCacheEntries {
66+ job: String,
67+ count: usize,
68+ max: usize,
69+ },
70+
71+ #[error("job {job:?}: duplicate cache path {path:?}")]
72+ DuplicateCachePath { job: String, path: String },
73+
5774 #[error("invalid {kind} glob {pattern:?}: {reason}")]
5875 InvalidTriggerGlob {
5976 kind: &'static str,
crates/forge-ci/src/proto.rsmodified+44 -0
@@ -72,6 +72,16 @@ pub struct JobAssignment {
7272 pub artifacts: Vec<String>,
7373 pub timeout_minutes: u32,
7474 pub network: bool,
75+ /// Workspace-relative directories to cache, already validated. Empty when the job has no cache.
76+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
77+ pub cache: Vec<String>,
78+ /// The cache scope this job may write, e.g. `ref:refs/heads/main` or `pr:12`. Empty means the
79+ /// runner neither restores nor saves a cache for this job. The runner namespaces it by repo and job.
80+ #[serde(default, skip_serializing_if = "String::is_empty")]
81+ pub cache_key: String,
82+ /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written.
83+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
84+ pub cache_restore_keys: Vec<String>,
7585 }
7686
7787 impl fmt::Debug for JobAssignment {
@@ -91,6 +101,9 @@ impl fmt::Debug for JobAssignment {
91101 .field("artifacts", &self.artifacts)
92102 .field("timeout_minutes", &self.timeout_minutes)
93103 .field("network", &self.network)
104+ .field("cache", &self.cache)
105+ .field("cache_key", &self.cache_key)
106+ .field("cache_restore_keys", &self.cache_restore_keys)
94107 .finish()
95108 }
96109 }
@@ -145,6 +158,34 @@ mod tests {
145158 assert_eq!(back, req);
146159 }
147160
161+ #[test]
162+ fn cache_fields_are_omitted_when_empty() {
163+ let job = JobAssignment {
164+ job_id: "j1".into(),
165+ job_token: "t".into(),
166+ repo: "o/r".into(),
167+ clone_url: "https://example.test/o/r.git".into(),
168+ commit: "abc".into(),
169+ git_ref: "refs/heads/main".into(),
170+ job_name: "lint".into(),
171+ image: "i".into(),
172+ run: "true".into(),
173+ env: BTreeMap::new(),
174+ secrets: BTreeMap::new(),
175+ artifacts: vec![],
176+ timeout_minutes: 60,
177+ network: true,
178+ cache: vec![],
179+ cache_key: String::new(),
180+ cache_restore_keys: vec![],
181+ };
182+ let json = serde_json::to_string(&job).unwrap();
183+ assert!(!json.contains("cache"), "{json}");
184+ // An older server's reply, without the cache fields, still parses.
185+ let back: JobAssignment = serde_json::from_str(&json).unwrap();
186+ assert_eq!(back, job);
187+ }
188+
148189 #[test]
149190 fn debug_redacts_secrets() {
150191 let mut secrets = BTreeMap::new();
@@ -164,6 +205,9 @@ mod tests {
164205 artifacts: vec![],
165206 timeout_minutes: 60,
166207 network: true,
208+ cache: vec![],
209+ cache_key: String::new(),
210+ cache_restore_keys: vec![],
167211 };
168212 let dbg = format!("{job:?}");
169213 assert!(!dbg.contains("hunter2-value"));
crates/forge-runner/src/cache.rsadded+1077 -0
@@ -0,0 +1,1077 @@
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 the
3+//! same repo, job name and cache key moves them back in.
4+//!
5+//! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids
6+//! never start with one:
7+//! - `<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+//! - `.new-<job>`, `.old-<job>` and `.inuse-<job>` are one job's scratch dirs. A crashed job can
10+//! leave them behind, and [`CacheStore::sweep_stale`] removes them at startup.
11+//!
12+//! A restore never fails a job. A failure is logged and the job runs without the cache.
13+
14+use std::fs;
15+use std::io;
16+use std::path::{Component, Path, PathBuf};
17+use std::process::Stdio;
18+use std::sync::atomic::{AtomicU64, Ordering};
19+use std::time::{Duration, SystemTime, UNIX_EPOCH};
20+
21+use forge_ci::proto::{JobAssignment, Outcome};
22+use serde::{Deserialize, Serialize};
23+use sha2::{Digest, Sha256};
24+use tokio::process::Command;
25+
26+use crate::sandbox::idmap::{IdMap, remove_tree};
27+
28+/// Most paths one job may cache.
29+const MAX_PATHS: usize = 32;
30+/// Longest cached path, in bytes.
31+const MAX_PATH_LEN: usize = 512;
32+/// Longest cache key, in bytes.
33+const MAX_KEY_LEN: usize = 256;
34+/// Longest `cp` stderr kept for a log line, in characters.
35+const MAX_STDERR: usize = 500;
36+const MANIFEST: &str = "manifest.json";
37+const META: &str = "meta.json";
38+const SCRATCH_PREFIXES: [&str; 3] = [".inuse-", ".new-", ".old-"];
39+
40+/// Errors from the build cache. They are logged to the job, never returned to the forge.
41+#[derive(Debug, thiserror::Error)]
42+pub enum CacheError {
43+ #[error("cache io: {0}")]
44+ Io(#[from] io::Error),
45+ #[error("cache path {path:?} refused: {reason}")]
46+ Path { path: String, reason: &'static str },
47+ #[error("{} is a symlink, not following it", .0.display())]
48+ Symlink(PathBuf),
49+ #[error("{} is not a directory", .0.display())]
50+ NotDir(PathBuf),
51+ #[error("cp failed: {0}")]
52+ Copy(String),
53+}
54+
55+/// What `meta.json` records about one entry.
56+#[derive(Debug, Serialize, Deserialize)]
57+struct Meta {
58+ repo: String,
59+ job: String,
60+ key: String,
61+ /// When the entry was saved, in Unix nanoseconds. Eviction removes the oldest first.
62+ saved_at: u64,
63+ size_bytes: u64,
64+}
65+
66+/// One entry found while evicting.
67+struct Found {
68+ path: PathBuf,
69+ size: u64,
70+ saved_at: u64,
71+}
72+
73+/// The build cache of one runner. Shared by every job the runner runs.
74+pub struct CacheStore {
75+ root: PathBuf,
76+ /// The cap on the total size of all entries. Zero means the cache is off.
77+ max_bytes: u64,
78+ idmap: IdMap,
79+ helper: PathBuf,
80+ /// Held while an entry is claimed, installed or evicted, so jobs never race on one.
81+ lock: tokio::sync::Mutex<()>,
82+ /// The last save stamp, so entries saved in the same nanosecond still order by save time.
83+ last_stamp: AtomicU64,
84+}
85+
86+impl CacheStore {
87+ /// `root` holds the entries and `max_bytes` caps their total size. `idmap` and `helper` remove
88+ /// dirs whose files may be owned by subordinate ids (see [`remove_tree`]).
89+ pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self {
90+ Self {
91+ root,
92+ max_bytes,
93+ idmap,
94+ helper,
95+ lock: tokio::sync::Mutex::new(()),
96+ last_stamp: AtomicU64::new(0),
97+ }
98+ }
99+
100+ /// Removes the scratch dirs of jobs that crashed. Call once at startup, before any job runs.
101+ pub async fn sweep_stale(&self) -> Result<(), CacheError> {
102+ let mut dir = match tokio::fs::read_dir(&self.root).await {
103+ Ok(dir) => dir,
104+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
105+ Err(e) => return Err(e.into()),
106+ };
107+ let mut stale = Vec::new();
108+ while let Some(entry) = dir.next_entry().await? {
109+ if is_scratch(&entry.file_name().to_string_lossy()) {
110+ stale.push(entry.path());
111+ }
112+ }
113+ for path in stale {
114+ tracing::info!(path = %path.display(), "removing scratch dir of a crashed job");
115+ self.remove(&path).await?;
116+ }
117+ Ok(())
118+ }
119+
120+ /// Puts the job's cached paths into `workspace` before the run. Returns the job log lines.
121+ /// Never fails: a failed restore is logged and the job runs uncached.
122+ pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec<String> {
123+ let mut lines = Vec::new();
124+ if job.cache.is_empty() || self.max_bytes == 0 {
125+ return lines;
126+ }
127+ let wanted = match validate_paths(&job.cache) {
128+ Ok(wanted) => wanted,
129+ Err(e) => {
130+ lines.push(format!("runner: cache skipped: {e}"));
131+ return lines;
132+ }
133+ };
134+
135+ if !job.cache_key.is_empty() {
136+ let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);
137+ match self.claim(&job.job_id, &entry).await {
138+ Ok(Some(inuse)) => {
139+ let size = self
140+ .restore_claimed(&inuse, workspace, &wanted, &mut lines)
141+ .await;
142+ lines.push(format!(
143+ "runner: cache hit {} ({})",
144+ job.cache_key,
145+ human(size)
146+ ));
147+ return lines;
148+ }
149+ Ok(None) => {}
150+ Err(e) => lines.push(format!("runner: cache restore failed: {e}")),
151+ }
152+ }
153+
154+ for key in &job.cache_restore_keys {
155+ if key.is_empty() || key.len() > MAX_KEY_LEN {
156+ continue;
157+ }
158+ if self
159+ .restore_fallback(job, key, workspace, &wanted, &mut lines)
160+ .await
161+ {
162+ return lines;
163+ }
164+ }
165+ lines.push("runner: cache miss".to_owned());
166+ lines
167+ }
168+
169+ /// Moves the job's cached paths out of `workspace` into the entry for `job.cache_key`. Only a
170+ /// finished job saves, with Success or Failure. Returns the job log lines. Never fails. The
171+ /// job's scratch dirs are always removed, whatever happened.
172+ pub async fn save(
173+ &self,
174+ job: &JobAssignment,
175+ outcome: Outcome,
176+ workspace: &Path,
177+ ) -> Vec<String> {
178+ let mut lines = Vec::new();
179+ let finished = matches!(outcome, Outcome::Success | Outcome::Failure);
180+ if finished && self.max_bytes > 0 && !job.cache.is_empty() && !job.cache_key.is_empty() {
181+ match validate_paths(&job.cache) {
182+ Ok(paths) => {
183+ if let Err(e) = self.save_paths(job, workspace, &paths, &mut lines).await {
184+ lines.push(format!("runner: cache not saved: {e}"));
185+ }
186+ }
187+ Err(e) => lines.push(format!("runner: cache not saved: {e}")),
188+ }
189+ }
190+ if let Err(e) = self.remove_scratch(&job.job_id).await {
191+ tracing::warn!(job_id = %job.job_id, error = %e, "cannot remove cache scratch dirs");
192+ }
193+ lines
194+ }
195+
196+ /// Moves a claimed entry's wanted paths into the workspace. Returns the entry size. A path
197+ /// that fails is logged and the rest still restore.
198+ async fn restore_claimed(
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,
234+ job: &JobAssignment,
235+ key: &str,
236+ workspace: &Path,
237+ wanted: &[PathBuf],
238+ lines: &mut Vec<String>,
239+ ) -> bool {
240+ let source = self.entry_dir(&job.repo, &job.job_name, key);
241+ if !is_dir(&source) {
242+ return false;
243+ }
244+ let manifest = match read_manifest(&source) {
245+ Ok(manifest) => manifest,
246+ Err(e) => {
247+ lines.push(format!("runner: cache restore failed: {e}"));
248+ return false;
249+ }
250+ };
251+ let mut restored = 0usize;
252+ for (k, rel) in selected(&manifest, wanted, lines) {
253+ let src = source.join(format!("p{k}"));
254+ match copy_into(workspace, &rel, &src).await {
255+ Ok(true) => restored += 1,
256+ Ok(false) => lines.push(skipped(&rel)),
257+ Err(e) => lines.push(format!(
258+ "runner: cache restore failed for {}: {e}",
259+ rel.display()
260+ )),
261+ }
262+ }
263+ if restored == 0 {
264+ return false;
265+ }
266+ lines.push(format!("runner: cache restored from fallback {key}"));
267+ true
268+ }
269+
270+ /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked
271+ /// that the outcome, key and paths allow a save.
272+ async fn save_paths(
273+ &self,
274+ job: &JobAssignment,
275+ workspace: &Path,
276+ paths: &[PathBuf],
277+ lines: &mut Vec<String>,
278+ ) -> Result<(), CacheError> {
279+ tokio::fs::create_dir_all(&self.root).await?;
280+ let new = self.scratch(".new-", &job.job_id);
281+ self.remove(&new).await?;
282+ tokio::fs::create_dir(&new).await?;
283+
284+ let mut manifest: Vec<String> = Vec::new();
285+ for rel in paths {
286+ let src = match existing_in_workspace(workspace, rel) {
287+ Ok(Some(src)) => src,
288+ Ok(None) => continue,
289+ Err(e) => {
290+ lines.push(format!("runner: cache skipped {}: {e}", rel.display()));
291+ continue;
292+ }
293+ };
294+ let dst = new.join(format!("p{}", manifest.len()));
295+ match tokio::fs::rename(&src, &dst).await {
296+ Ok(()) => manifest.push(rel.display().to_string()),
297+ Err(e) => lines.push(format!("runner: cache skipped {}: {e}", rel.display())),
298+ }
299+ }
300+ if manifest.is_empty() {
301+ self.remove(&new).await?;
302+ return Ok(());
303+ }
304+
305+ // Measured before the metadata files are written, so the size is the cached data only.
306+ let size = dir_size(&new).await;
307+ write_json(&new.join(MANIFEST), &manifest).await?;
308+ let meta = Meta {
309+ repo: job.repo.clone(),
310+ job: job.job_name.clone(),
311+ key: job.cache_key.clone(),
312+ saved_at: self.stamp(),
313+ size_bytes: size,
314+ };
315+ write_json(&new.join(META), &meta).await?;
316+
317+ let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key);
318+ let old = self.scratch(".old-", &job.job_id);
319+ {
320+ let _guard = self.lock.lock().await;
321+ self.remove(&old).await?;
322+ let had_old = is_dir(&entry);
323+ if had_old {
324+ tokio::fs::rename(&entry, &old).await?;
325+ }
326+ if let Err(e) = tokio::fs::rename(&new, &entry).await {
327+ if had_old {
328+ // Put the previous entry back, so a failed save loses nothing.
329+ let _ = tokio::fs::rename(&old, &entry).await;
330+ }
331+ return Err(e.into());
332+ }
333+ match self.evict().await {
334+ Ok(0) => {}
335+ Ok(removed) => tracing::info!(removed, "cache entries evicted"),
336+ Err(e) => tracing::warn!(error = %e, "cache eviction failed"),
337+ }
338+ }
339+ lines.push(format!("runner: cache saved ({})", human(size)));
340+ Ok(())
341+ }
342+
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 caller
360+ /// holds the lock. Returns how many entries went.
361+ async fn evict(&self) -> Result<usize, CacheError> {
362+ let mut entries = self.list_entries().await?;
363+ let mut total = entries
364+ .iter()
365+ .fold(0u64, |sum, e| sum.saturating_add(e.size));
366+ entries.sort_by_key(|e| e.saved_at);
367+ let mut removed = 0;
368+ for entry in entries {
369+ if total <= self.max_bytes {
370+ break;
371+ }
372+ self.remove(&entry.path).await?;
373+ total = total.saturating_sub(entry.size);
374+ removed += 1;
375+ }
376+ Ok(removed)
377+ }
378+
379+ /// Every entry under the root. An entry without a readable `meta.json` is sized by walking it,
380+ /// and its save time is the dir's mtime.
381+ async fn list_entries(&self) -> Result<Vec<Found>, CacheError> {
382+ let mut found = Vec::new();
383+ let mut dir = match tokio::fs::read_dir(&self.root).await {
384+ Ok(dir) => dir,
385+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(found),
386+ Err(e) => return Err(e.into()),
387+ };
388+ while let Some(item) = dir.next_entry().await? {
389+ let name = item.file_name().to_string_lossy().into_owned();
390+ let path = item.path();
391+ if !is_entry_name(&name) || !is_dir(&path) {
392+ continue;
393+ }
394+ let entry = match read_meta(&path) {
395+ Some(meta) => Found {
396+ path,
397+ size: meta.size_bytes,
398+ saved_at: meta.saved_at,
399+ },
400+ None => {
401+ let saved_at = fs::metadata(&path)
402+ .and_then(|m| m.modified())
403+ .ok()
404+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
405+ .map_or(0, nanos);
406+ Found {
407+ size: dir_size(&path).await,
408+ path,
409+ saved_at,
410+ }
411+ }
412+ };
413+ found.push(entry);
414+ }
415+ Ok(found)
416+ }
417+
418+ /// A save time in Unix nanoseconds, larger than every earlier one from this store.
419+ fn stamp(&self) -> u64 {
420+ let now = nanos(
421+ SystemTime::now()
422+ .duration_since(UNIX_EPOCH)
423+ .unwrap_or_default(),
424+ );
425+ let mut prev = self.last_stamp.load(Ordering::SeqCst);
426+ loop {
427+ let next = now.max(prev.saturating_add(1));
428+ match self
429+ .last_stamp
430+ .compare_exchange(prev, next, Ordering::SeqCst, Ordering::SeqCst)
431+ {
432+ Ok(_) => return next,
433+ Err(actual) => prev = actual,
434+ }
435+ }
436+ }
437+
438+ fn entry_dir(&self, repo: &str, job_name: &str, key: &str) -> PathBuf {
439+ self.root.join(entry_name(repo, job_name, key))
440+ }
441+
442+ fn scratch(&self, prefix: &str, job_id: &str) -> PathBuf {
443+ self.root.join(format!("{prefix}{job_id}"))
444+ }
445+
446+ /// Removes all of one job's scratch dirs. Missing ones are fine.
447+ async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> {
448+ for prefix in SCRATCH_PREFIXES {
449+ self.remove(&self.scratch(prefix, job_id)).await?;
450+ }
451+ Ok(())
452+ }
453+
454+ /// Removes a file or dir tree, through the id map so subuid-owned files go too. Blocking work
455+ /// runs off the async runtime.
456+ async fn remove(&self, path: &Path) -> Result<(), CacheError> {
457+ let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned());
458+ tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper))
459+ .await
460+ .map_err(io::Error::other)??;
461+ Ok(())
462+ }
463+}
464+
465+/// Checks one cached path from the forge, and again on the runner. It must be a relative path
466+/// with no empty, `.`, `..` or `.git` parts.
467+pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> {
468+ let refuse = |reason: &'static str| CacheError::Path {
469+ path: path.to_owned(),
470+ reason,
471+ };
472+ if path.is_empty() {
473+ return Err(refuse("empty"));
474+ }
475+ if path.len() > MAX_PATH_LEN {
476+ return Err(refuse("too long"));
477+ }
478+ if path.contains(['\0', '\\']) {
479+ return Err(refuse("contains NUL or backslash"));
480+ }
481+ if path.starts_with('/') {
482+ return Err(refuse("absolute"));
483+ }
484+ let mut out = PathBuf::new();
485+ for part in path.split('/') {
486+ match part {
487+ "" | "." => return Err(refuse("empty or . part")),
488+ ".." => return Err(refuse("contains ..")),
489+ part if part.eq_ignore_ascii_case(".git") => return Err(refuse(".git is not cached")),
490+ part => out.push(part),
491+ }
492+ }
493+ Ok(out)
494+}
495+
496+/// Checks the whole list: at most [`MAX_PATHS`] paths, each valid, and none inside another.
497+pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> {
498+ if paths.len() > MAX_PATHS {
499+ return Err(CacheError::Path {
500+ path: format!("{} paths", paths.len()),
501+ reason: "too many cache paths",
502+ });
503+ }
504+ let parsed = paths
505+ .iter()
506+ .map(|p| validate_path(p))
507+ .collect::<Result<Vec<_>, _>>()?;
508+ for (i, a) in parsed.iter().enumerate() {
509+ for b in &parsed[i + 1..] {
510+ if a.starts_with(b) || b.starts_with(a) {
511+ return Err(CacheError::Path {
512+ path: a.display().to_string(),
513+ reason: "overlaps another cache path",
514+ });
515+ }
516+ }
517+ }
518+ Ok(parsed)
519+}
520+
521+/// The manifest entries the job asked for, as (index, path). An entry that fails validation is
522+/// logged and dropped.
523+fn selected(
524+ manifest: &[String],
525+ wanted: &[PathBuf],
526+ lines: &mut Vec<String>,
527+) -> Vec<(usize, PathBuf)> {
528+ let mut out = Vec::new();
529+ for (k, raw) in manifest.iter().enumerate() {
530+ match validate_path(raw) {
531+ Ok(rel) if wanted.contains(&rel) => out.push((k, rel)),
532+ Ok(_) => {}
533+ Err(e) => lines.push(format!("runner: cache skipped: {e}")),
534+ }
535+ }
536+ out
537+}
538+
539+/// The workspace path for `rel`. Missing parent dirs are created when `create` is set. Each parent
540+/// is checked one component at a time, and a symlink there is refused, never followed. Returns
541+/// `None` when a parent is missing and `create` is not set.
542+fn workspace_path(
543+ workspace: &Path,
544+ rel: &Path,
545+ create: bool,
546+) -> Result<Option<PathBuf>, CacheError> {
547+ if !fs::symlink_metadata(workspace)?.is_dir() {
548+ return Err(CacheError::NotDir(workspace.to_owned()));
549+ }
550+ let mut cur = workspace.to_owned();
551+ let parent = rel.parent().unwrap_or(Path::new(""));
552+ for part in parent.components() {
553+ let Component::Normal(name) = part else {
554+ return Err(CacheError::Path {
555+ path: rel.display().to_string(),
556+ reason: "not a plain relative path",
557+ });
558+ };
559+ cur.push(name);
560+ match fs::symlink_metadata(&cur) {
561+ Ok(meta) if meta.file_type().is_symlink() => return Err(CacheError::Symlink(cur)),
562+ Ok(meta) if meta.is_dir() => {}
563+ Ok(_) => return Err(CacheError::NotDir(cur)),
564+ Err(e) if e.kind() == io::ErrorKind::NotFound => {
565+ if !create {
566+ return Ok(None);
567+ }
568+ fs::create_dir(&cur)?;
569+ }
570+ Err(e) => return Err(e.into()),
571+ }
572+ }
573+ let Some(name) = rel.file_name() else {
574+ return Err(CacheError::Path {
575+ path: rel.display().to_string(),
576+ reason: "no file name",
577+ });
578+ };
579+ Ok(Some(cur.join(name)))
580+}
581+
582+/// The workspace path of `rel` when something exists there. `None` when nothing does.
583+fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>, CacheError> {
584+ let Some(path) = workspace_path(workspace, rel, false)? else {
585+ return Ok(None);
586+ };
587+ Ok(exists_no_follow(&path).then_some(path))
588+}
589+
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.
603+/// Returns false when the checkout already has something there.
604+async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {
605+ let Some(dest) = workspace_path(workspace, rel, true)? else {
606+ return Ok(false);
607+ };
608+ if exists_no_follow(&dest) {
609+ return Ok(false);
610+ }
611+ let output = Command::new("cp")
612+ .args(["-a", "--reflink=auto", "--"])
613+ .arg(src)
614+ .arg(&dest)
615+ .stdin(Stdio::null())
616+ .stdout(Stdio::null())
617+ .stderr(Stdio::piped())
618+ .kill_on_drop(true)
619+ .output()
620+ .await?;
621+ if output.status.success() {
622+ return Ok(true);
623+ }
624+ // A partial copy must not stay in the checkout.
625+ let _ = plain_remove(&dest).await;
626+ let stderr: String = String::from_utf8_lossy(&output.stderr)
627+ .chars()
628+ .take(MAX_STDERR)
629+ .collect();
630+ Err(CacheError::Copy(stderr.trim().to_owned()))
631+}
632+
633+/// Removes a file, symlink or dir tree the runner owns. The checkout is never subuid-owned at
634+/// this point, so no id map is needed.
635+async fn plain_remove(path: &Path) -> io::Result<()> {
636+ match fs::symlink_metadata(path) {
637+ Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await,
638+ Ok(_) => tokio::fs::remove_file(path).await,
639+ Err(e) => Err(e),
640+ }
641+}
642+
643+fn read_meta(dir: &Path) -> Option<Meta> {
644+ let bytes = fs::read(dir.join(META)).ok()?;
645+ serde_json::from_slice(&bytes).ok()
646+}
647+
648+fn read_manifest(dir: &Path) -> Result<Vec<String>, CacheError> {
649+ let bytes = fs::read(dir.join(MANIFEST))?;
650+ serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e)))
651+}
652+
653+async fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), CacheError> {
654+ let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
655+ tokio::fs::write(path, bytes).await?;
656+ Ok(())
657+}
658+
659+/// The total size of the files under `root`. Symlinks count as links and are never followed.
660+/// Unreadable dirs count as empty. Runs off the async runtime.
661+async fn dir_size(root: &Path) -> u64 {
662+ let root = root.to_owned();
663+ tokio::task::spawn_blocking(move || tree_size(&root))
664+ .await
665+ .unwrap_or(0)
666+}
667+
668+fn tree_size(root: &Path) -> u64 {
669+ let mut total = 0u64;
670+ let mut stack = vec![root.to_owned()];
671+ while let Some(dir) = stack.pop() {
672+ let Ok(entries) = fs::read_dir(&dir) else {
673+ continue;
674+ };
675+ for entry in entries.flatten() {
676+ let Ok(meta) = fs::symlink_metadata(entry.path()) else {
677+ continue;
678+ };
679+ if meta.is_dir() {
680+ stack.push(entry.path());
681+ } else {
682+ total = total.saturating_add(meta.len());
683+ }
684+ }
685+ }
686+ total
687+}
688+
689+/// The entry directory name for one job's cache key. Hashing keeps key text out of paths.
690+fn entry_name(repo: &str, job_name: &str, key: &str) -> String {
691+ let mut hash = Sha256::new();
692+ hash.update(repo.as_bytes());
693+ hash.update([0u8]);
694+ hash.update(job_name.as_bytes());
695+ hash.update([0u8]);
696+ hash.update(key.as_bytes());
697+ hex::encode(hash.finalize())
698+}
699+
700+/// Whether a dir name is an entry: 64 lowercase hex digits.
701+fn is_entry_name(name: &str) -> bool {
702+ name.len() == 64
703+ && name
704+ .bytes()
705+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
706+}
707+
708+fn is_scratch(name: &str) -> bool {
709+ SCRATCH_PREFIXES.iter().any(|p| name.starts_with(p))
710+}
711+
712+fn is_dir(path: &Path) -> bool {
713+ fs::symlink_metadata(path).is_ok_and(|m| m.is_dir())
714+}
715+
716+fn exists_no_follow(path: &Path) -> bool {
717+ fs::symlink_metadata(path).is_ok()
718+}
719+
720+fn nanos(d: Duration) -> u64 {
721+ u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)
722+}
723+
724+fn skipped(rel: &Path) -> String {
725+ format!(
726+ "runner: cache skipped {}: already in the checkout",
727+ rel.display()
728+ )
729+}
730+
731+/// A size for log lines, such as `3.1 GiB`.
732+fn human(bytes: u64) -> String {
733+ const KIB: f64 = 1024.0;
734+ let b = bytes as f64;
735+ if b >= KIB * KIB * KIB {
736+ format!("{:.1} GiB", b / (KIB * KIB * KIB))
737+ } else if b >= KIB * KIB {
738+ format!("{:.1} MiB", b / (KIB * KIB))
739+ } else {
740+ format!("{:.1} KiB", b / KIB)
741+ }
742+}
743+
744+#[cfg(test)]
745+mod tests {
746+ use std::collections::BTreeMap;
747+ use std::os::unix::fs::symlink;
748+
749+ use super::*;
750+
751+ fn job(job_id: &str, key: &str, restore: &[&str], cache: &[&str]) -> JobAssignment {
752+ JobAssignment {
753+ job_id: job_id.to_owned(),
754+ job_token: "tok_secret_value".to_owned(),
755+ repo: "tahinli/forge".to_owned(),
756+ clone_url: "https://forge.example/tahinli/forge.git".to_owned(),
757+ commit: "a".repeat(40),
758+ git_ref: "refs/heads/main".to_owned(),
759+ job_name: "build".to_owned(),
760+ image: "docker.io/library/alpine:3".to_owned(),
761+ run: "true".to_owned(),
762+ env: BTreeMap::new(),
763+ secrets: BTreeMap::new(),
764+ artifacts: Vec::new(),
765+ timeout_minutes: 5,
766+ network: false,
767+ cache: cache.iter().map(|s| (*s).to_owned()).collect(),
768+ cache_key: key.to_owned(),
769+ cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(),
770+ }
771+ }
772+
773+ fn store(dir: &Path, max_bytes: u64) -> CacheStore {
774+ CacheStore::new(
775+ dir.join(".cache"),
776+ max_bytes,
777+ IdMap::single(),
778+ PathBuf::from("/unused-helper"),
779+ )
780+ }
781+
782+ /// A workspace `dir/<name>` holding `target/a.txt` with `body`.
783+ fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf {
784+ let ws = dir.join(name);
785+ fs::create_dir_all(ws.join("target")).expect("mkdir");
786+ fs::write(ws.join("target/a.txt"), body).expect("write");
787+ ws
788+ }
789+
790+ fn empty_workspace(dir: &Path, name: &str) -> PathBuf {
791+ let ws = dir.join(name);
792+ fs::create_dir_all(&ws).expect("mkdir");
793+ ws
794+ }
795+
796+ fn entry_of(store: &CacheStore, key: &str) -> PathBuf {
797+ store.entry_dir("tahinli/forge", "build", key)
798+ }
799+
800+ fn read(path: &Path) -> String {
801+ fs::read_to_string(path).expect("read")
802+ }
803+
804+ #[tokio::test]
805+ async fn hit_moves_the_entry_and_hides_it_while_in_use() {
806+ let dir = tempfile::tempdir().expect("tempdir");
807+ let store = store(dir.path(), 1 << 30);
808+ let first = job("job_a", "ref:refs/heads/main", &[], &["target"]);
809+ let ws1 = workspace(dir.path(), "ws_a", "one");
810+ let saved = store.save(&first, Outcome::Success, &ws1).await;
811+ assert!(
812+ saved.iter().any(|l| l.starts_with("runner: cache saved")),
813+ "{saved:?}"
814+ );
815+ assert!(!ws1.join("target").exists(), "save moves the path out");
816+
817+ let second = job("job_b", "ref:refs/heads/main", &[], &["target"]);
818+ let ws2 = empty_workspace(dir.path(), "ws_b");
819+ let lines = store.restore(&second, &ws2).await;
820+ assert!(
821+ lines
822+ .iter()
823+ .any(|l| l.starts_with("runner: cache hit ref:refs/heads/main")),
824+ "{lines:?}"
825+ );
826+ assert_eq!(read(&ws2.join("target/a.txt")), "one");
827+ assert!(
828+ !entry_of(&store, "ref:refs/heads/main").exists(),
829+ "a hit moves the entry"
830+ );
831+ assert!(store.root.join(".inuse-job_b").is_dir());
832+
833+ // Another job for the same key finds nothing while the first one holds the entry.
834+ let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);
835+ let ws3 = empty_workspace(dir.path(), "ws_c");
836+ assert_eq!(
837+ store.restore(&third, &ws3).await,
838+ vec!["runner: cache miss".to_owned()]
839+ );
840+ assert!(!ws3.join("target").exists());
841+
842+ // The finished job's scratch dir is gone, and its save puts the entry back.
843+ store.save(&second, Outcome::Success, &ws2).await;
844+ assert!(!store.root.join(".inuse-job_b").exists());
845+ assert!(entry_of(&store, "ref:refs/heads/main").is_dir());
846+ }
847+
848+ #[tokio::test]
849+ async fn fallback_copies_and_leaves_the_fallback_entry() {
850+ let dir = tempfile::tempdir().expect("tempdir");
851+ let store = store(dir.path(), 1 << 30);
852+ let main = job("job_a", "ref:refs/heads/main", &[], &["target"]);
853+ store
854+ .save(
855+ &main,
856+ Outcome::Success,
857+ &workspace(dir.path(), "ws_a", "main"),
858+ )
859+ .await;
860+
861+ let pr = job("job_b", "pr:12", &["ref:refs/heads/main"], &["target"]);
862+ let ws = empty_workspace(dir.path(), "ws_b");
863+ let lines = store.restore(&pr, &ws).await;
864+ assert!(
865+ lines.contains(&"runner: cache restored from fallback ref:refs/heads/main".to_owned()),
866+ "{lines:?}"
867+ );
868+ assert_eq!(read(&ws.join("target/a.txt")), "main");
869+ assert_eq!(
870+ read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
871+ "main"
872+ );
873+ }
874+
875+ #[tokio::test]
876+ async fn save_replaces_the_entry_and_leaves_no_scratch() {
877+ let dir = tempfile::tempdir().expect("tempdir");
878+ let store = store(dir.path(), 1 << 30);
879+ let first = job("job_1", "ref:refs/heads/main", &[], &["target"]);
880+ store
881+ .save(
882+ &first,
883+ Outcome::Success,
884+ &workspace(dir.path(), "ws1", "v1"),
885+ )
886+ .await;
887+ let second = job("job_2", "ref:refs/heads/main", &[], &["target"]);
888+ store
889+ .save(
890+ &second,
891+ Outcome::Failure,
892+ &workspace(dir.path(), "ws2", "v2"),
893+ )
894+ .await;
895+
896+ let entry = entry_of(&store, "ref:refs/heads/main");
897+ assert_eq!(read(&entry.join("p0/a.txt")), "v2");
898+ let names: Vec<String> = fs::read_dir(&store.root)
899+ .expect("read_dir")
900+ .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
901+ .collect();
902+ assert_eq!(
903+ names,
904+ vec![
905+ entry
906+ .file_name()
907+ .expect("name")
908+ .to_string_lossy()
909+ .into_owned()
910+ ]
911+ );
912+ }
913+
914+ #[tokio::test]
915+ async fn save_never_writes_restore_keys() {
916+ let dir = tempfile::tempdir().expect("tempdir");
917+ let store = store(dir.path(), 1 << 30);
918+ let main = job("job_m", "ref:refs/heads/main", &[], &["target"]);
919+ store
920+ .save(
921+ &main,
922+ Outcome::Success,
923+ &workspace(dir.path(), "ws_m", "main"),
924+ )
925+ .await;
926+
927+ let pr = job("job_p", "pr:12", &["ref:refs/heads/main"], &["target"]);
928+ store
929+ .save(&pr, Outcome::Success, &workspace(dir.path(), "ws_p", "pr"))
930+ .await;
931+ assert_eq!(read(&entry_of(&store, "pr:12").join("p0/a.txt")), "pr");
932+ assert_eq!(
933+ read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
934+ "main"
935+ );
936+
937+ // A job whose own key is empty saves nothing, even with restore keys listed.
938+ let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]);
939+ store
940+ .save(
941+ &none,
942+ Outcome::Success,
943+ &workspace(dir.path(), "ws_n", "none"),
944+ )
945+ .await;
946+ assert_eq!(
947+ read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")),
948+ "main"
949+ );
950+ }
951+
952+ #[tokio::test]
953+ async fn cancelled_or_errored_runs_do_not_save() {
954+ let dir = tempfile::tempdir().expect("tempdir");
955+ let store = store(dir.path(), 1 << 30);
956+ let j = job("job_x", "ref:refs/heads/main", &[], &["target"]);
957+ for outcome in [Outcome::Cancelled, Outcome::Error] {
958+ let ws = workspace(dir.path(), &format!("ws_{outcome:?}"), "x");
959+ let lines = store.save(&j, outcome, &ws).await;
960+ assert!(lines.is_empty(), "{lines:?}");
961+ assert!(
962+ ws.join("target/a.txt").exists(),
963+ "the files stay in the workspace"
964+ );
965+ }
966+ assert!(!entry_of(&store, "ref:refs/heads/main").exists());
967+ }
968+
969+ #[tokio::test]
970+ async fn eviction_removes_the_least_recently_saved_entry() {
971+ let dir = tempfile::tempdir().expect("tempdir");
972+ // Each entry holds 1000 bytes. The cap fits two of them.
973+ let store = store(dir.path(), 2500);
974+ for key in ["k1", "k2", "k3"] {
975+ let ws = dir.path().join(format!("ws_{key}"));
976+ fs::create_dir_all(ws.join("target")).expect("mkdir");
977+ fs::write(ws.join("target/data.bin"), vec![b'x'; 1000]).expect("write");
978+ let j = job(&format!("job_{key}"), key, &[], &["target"]);
979+ store.save(&j, Outcome::Success, &ws).await;
980+ }
981+ assert!(!entry_of(&store, "k1").exists(), "the oldest goes first");
982+ assert!(entry_of(&store, "k2").is_dir());
983+ assert!(entry_of(&store, "k3").is_dir());
984+ }
985+
986+ #[test]
987+ fn cache_paths_are_checked_again_on_the_runner() {
988+ let bad = [
989+ "../x",
990+ "a/../b",
991+ "/etc",
992+ "",
993+ ".",
994+ "a//b",
995+ "target/",
996+ ".git",
997+ "a/.git/b",
998+ "a/./b",
999+ "x\\y",
1000+ "a\0b",
1001+ ".GIT/config",
1002+ ];
1003+ for path in bad {
1004+ assert!(validate_path(path).is_err(), "{path:?} must be refused");
1005+ }
1006+ assert_eq!(
1007+ validate_path("target").expect("ok"),
1008+ PathBuf::from("target")
1009+ );
1010+ assert_eq!(
1011+ validate_path("web/node_modules").expect("ok"),
1012+ PathBuf::from("web/node_modules")
1013+ );
1014+ assert!(validate_paths(&["target".to_owned(), "target/debug".to_owned()]).is_err());
1015+ }
1016+
1017+ #[tokio::test]
1018+ async fn a_symlinked_parent_is_refused_and_not_followed() {
1019+ let dir = tempfile::tempdir().expect("tempdir");
1020+ let store = store(dir.path(), 1 << 30);
1021+ let outside = dir.path().join("outside");
1022+ fs::create_dir_all(&outside).expect("mkdir");
1023+
1024+ let ws1 = dir.path().join("ws1");
1025+ fs::create_dir_all(ws1.join("build/out")).expect("mkdir");
1026+ fs::write(ws1.join("build/out/f"), "x").expect("write");
1027+ let first = job("job_1", "ref:main", &[], &["build/out"]);
1028+ store.save(&first, Outcome::Success, &ws1).await;
1029+
1030+ // Restore into a checkout where `build` is a symlink out of the workspace.
1031+ let ws2 = empty_workspace(dir.path(), "ws2");
1032+ symlink(&outside, ws2.join("build")).expect("symlink");
1033+ let second = job("job_2", "ref:main", &[], &["build/out"]);
1034+ let lines = store.restore(&second, &ws2).await;
1035+ assert!(
1036+ lines
1037+ .iter()
1038+ .any(|l| l.contains("build/out") && l.contains("failed")),
1039+ "{lines:?}"
1040+ );
1041+ assert!(
1042+ !outside.join("out").exists(),
1043+ "restore must not write through the symlink"
1044+ );
1045+
1046+ // Save from a checkout with the same symlink: nothing is moved out of `outside`.
1047+ fs::create_dir_all(outside.join("out")).expect("mkdir");
1048+ let ws3 = empty_workspace(dir.path(), "ws3");
1049+ symlink(&outside, ws3.join("build")).expect("symlink");
1050+ let third = job("job_3", "pr:9", &[], &["build/out"]);
1051+ let lines = store.save(&third, Outcome::Success, &ws3).await;
1052+ assert!(lines.iter().any(|l| l.contains("skipped")), "{lines:?}");
1053+ assert!(
1054+ outside.join("out").is_dir(),
1055+ "save must not move through the symlink"
1056+ );
1057+ }
1058+
1059+ #[tokio::test]
1060+ async fn stale_scratch_dirs_are_removed_at_startup() {
1061+ let dir = tempfile::tempdir().expect("tempdir");
1062+ let store = store(dir.path(), 1 << 30);
1063+ for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] {
1064+ let path = store.root.join(name);
1065+ fs::create_dir_all(&path).expect("mkdir");
1066+ fs::write(path.join("f"), "x").expect("write");
1067+ }
1068+ let keep = entry_of(&store, "ref:main");
1069+ fs::create_dir_all(&keep).expect("mkdir");
1070+
1071+ store.sweep_stale().await.expect("sweep");
1072+ for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] {
1073+ assert!(!store.root.join(name).exists(), "{name} must be removed");
1074+ }
1075+ assert!(keep.is_dir(), "entries are kept");
1076+ }
1077+}
crates/forge-runner/src/cli.rsmodified+23 -7
@@ -14,6 +14,7 @@ use forge_ci::proto::RegisterRequest;
1414 use tokio_util::sync::CancellationToken;
1515 use tracing_subscriber::EnvFilter;
1616
17+use crate::cache::CacheStore;
1718 use crate::client::ForgeClient;
1819 use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode};
1920 use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor};
@@ -207,6 +208,7 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
207208 sandbox: config::SandboxConfig::default(),
208209 registries: Vec::new(),
209210 auto_update: true,
211+ cache_max_gib: config::default_cache_max_gib(),
210212 };
211213 config::save(&path, &cfg)?;
212214 println!(
@@ -223,8 +225,14 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
223225 };
224226 let cfg = config::load(&path)?;
225227 let shutdown = CancellationToken::new();
226- let executor: Arc<dyn Executor> = match cfg.executor {
227- ExecutorKind::Podman => Arc::new(PodmanExecutor::new(cfg.limits.clone())),
228+ let cache_root = cfg.work_dir.join(".cache");
229+ let cache_cap = cfg.cache_max_gib;
230+ // The id map is what the executor's jobs run under. The cache removes its dirs with it.
231+ let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor {
232+ ExecutorKind::Podman => (
233+ Arc::new(PodmanExecutor::new(cfg.limits.clone())),
234+ IdMap::single(),
235+ ),
228236 ExecutorKind::Builtin => {
229237 // Resolved once. In subuid mode a failure here is a startup error.
230238 let map = IdMap::resolve(cfg.sandbox.userns)?;
@@ -242,14 +250,22 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
242250 .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb))
243251 .with_idmap(map.clone(), helper.clone());
244252 let jobs_dir = cfg.work_dir.join("jobs");
245- Arc::new(
253+ let executor =
246254 BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir)
247- .with_idmap(map)
248- .with_registries(&cfg.registries),
249- )
255+ .with_idmap(map.clone())
256+ .with_registries(&cfg.registries);
257+ (Arc::new(executor), map)
250258 }
251259 };
252- let runner = Runner::new(cfg, executor, RunOptions::default())?;
260+ let mut runner = Runner::new(cfg, executor, RunOptions::default())?;
261+ if cache_cap > 0 {
262+ let cache =
263+ CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?);
264+ if let Err(e) = cache.sweep_stale().await {
265+ tracing::warn!(error = %e, "cannot remove stale cache dirs");
266+ }
267+ runner = runner.with_cache(cache);
268+ }
253269 let stop = shutdown.clone();
254270 tokio::spawn(async move {
255271 if tokio::signal::ctrl_c().await.is_ok() {
crates/forge-runner/src/config.rsmodified+24 -0
@@ -135,6 +135,9 @@ pub struct RunnerConfig {
135135 /// 75 and systemd restarts it. Set `auto_update = false` to pin the binary by hand.
136136 #[serde(default = "default_auto_update")]
137137 pub auto_update: bool,
138+ /// The cap on all build caches together, in GiB. Zero turns the cache off. See `cache`.
139+ #[serde(default = "default_cache_max_gib")]
140+ pub cache_max_gib: u64,
138141 }
139142
140143 fn default_concurrency() -> usize {
@@ -149,6 +152,11 @@ fn default_keep_days() -> u32 {
149152 7
150153 }
151154
155+/// The default cap on all build caches together, in GiB.
156+pub fn default_cache_max_gib() -> u64 {
157+ 20
158+}
159+
152160 /// The default cap on one unpacked image, in GB.
153161 pub fn default_image_max_gb() -> u64 {
154162 20
@@ -169,6 +177,7 @@ impl fmt::Debug for RunnerConfig {
169177 .field("images", &self.images)
170178 .field("registries", &self.registries)
171179 .field("auto_update", &self.auto_update)
180+ .field("cache_max_gib", &self.cache_max_gib)
172181 .finish()
173182 }
174183 }
@@ -279,6 +288,7 @@ mod tests {
279288 sandbox: SandboxConfig::default(),
280289 registries: Vec::new(),
281290 auto_update: true,
291+ cache_max_gib: default_cache_max_gib(),
282292 }
283293 }
284294
@@ -352,6 +362,20 @@ mod tests {
352362 assert_eq!(config.limits.image_max_gb, 20);
353363 assert!(config.registries.is_empty());
354364 assert!(config.auto_update);
365+ assert_eq!(config.cache_max_gib, 20);
366+ }
367+
368+ #[test]
369+ fn cache_cap_can_be_set_and_turned_off() {
370+ let dir = tempfile::tempdir().expect("tempdir");
371+ let path = dir.path().join("runner.toml");
372+ std::fs::write(
373+ &path,
374+ "url = \"https://f\"\nrunner_id = \"r\"\nrunner_secret = \"s\"\nname = \"n\"\n\
375+ work_dir = \"/w\"\ncache_max_gib = 0\n",
376+ )
377+ .expect("write");
378+ assert_eq!(load(&path).expect("load").cache_max_gib, 0);
355379 }
356380
357381 #[test]
crates/forge-runner/src/executor.rsmodified+3 -0
@@ -800,6 +800,9 @@ mod tests {
800800 artifacts: Vec::new(),
801801 timeout_minutes: 5,
802802 network: false,
803+ cache: Vec::new(),
804+ cache_key: String::new(),
805+ cache_restore_keys: Vec::new(),
803806 }
804807 }
805808
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -5,6 +5,7 @@
55 //! forge's end-to-end tests can drive a runner with `HostExecutor`.
66
77 pub mod artifacts;
8+pub mod cache;
89 pub mod check;
910 pub mod cli;
1011 pub mod client;
crates/forge-runner/src/runner.rsmodified+22 -0
@@ -12,6 +12,7 @@ use tokio::time::Instant;
1212 use tokio_util::sync::CancellationToken;
1313
1414 use crate::artifacts;
15+use crate::cache::CacheStore;
1516 use crate::client::{ClientError, ForgeClient};
1617 use crate::config::RunnerConfig;
1718 use crate::executor::{ExecRequest, ExecResult, Executor};
@@ -63,6 +64,8 @@ pub struct Runner {
6364 config: Arc<RunnerConfig>,
6465 executor: Arc<dyn Executor>,
6566 options: RunOptions,
67+ /// The build cache, when it is on. See [`CacheStore`].
68+ cache: Option<Arc<CacheStore>>,
6669 }
6770
6871 impl Runner {
@@ -77,9 +80,16 @@ impl Runner {
7780 config: Arc::new(config),
7881 executor,
7982 options,
83+ cache: None,
8084 })
8185 }
8286
87+ /// Turns on the build cache for every job this runner runs.
88+ pub fn with_cache(mut self, cache: CacheStore) -> Self {
89+ self.cache = Some(Arc::new(cache));
90+ self
91+ }
92+
8393 pub fn client(&self) -> &ForgeClient {
8494 &self.client
8595 }
@@ -265,6 +275,11 @@ impl Runner {
265275 let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await;
266276 let mut result = match prepared {
267277 Ok(dir) => {
278+ if let Some(cache) = &self.cache {
279+ for line in cache.restore(&job, &dir).await {
280+ send_line(&tx, line).await;
281+ }
282+ }
268283 let result = self
269284 .executor
270285 .run(ExecRequest {
@@ -309,6 +324,13 @@ impl Runner {
309324 };
310325 }
311326
327+ // The save decides on the final outcome. It also clears the job's scratch dirs.
328+ if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) {
329+ for line in cache.save(&job, result.outcome, dir).await {
330+ send_line(&tx, line).await;
331+ }
332+ }
333+
312334 if let Some(message) = &result.message {
313335 send_line(&tx, format!("runner: {message}")).await;
314336 }
crates/forge-runner/tests/builtin.rsmodified+3 -0
@@ -83,6 +83,9 @@ fn job(run: &str) -> JobAssignment {
8383 artifacts: Vec::new(),
8484 timeout_minutes: 5,
8585 network: false,
86+ cache: Vec::new(),
87+ cache_key: String::new(),
88+ cache_restore_keys: Vec::new(),
8689 }
8790 }
8891
crates/forge-runner/tests/flow.rsmodified+4 -0
@@ -304,6 +304,9 @@ fn job(job_id: &str, commit: &str, clone_url: &str, run: &str) -> JobAssignment
304304 artifacts: vec!["dist/**".to_owned()],
305305 timeout_minutes: 5,
306306 network: false,
307+ cache: Vec::new(),
308+ cache_key: String::new(),
309+ cache_restore_keys: Vec::new(),
307310 }
308311 }
309312
@@ -322,6 +325,7 @@ fn config(url: &str, work_dir: PathBuf) -> RunnerConfig {
322325 sandbox: forge_runner::config::SandboxConfig::default(),
323326 registries: Vec::new(),
324327 auto_update: true,
328+ cache_max_gib: 0,
325329 }
326330 }
327331
crates/forge-web/src/ci/api.rsmodified+91 -0
@@ -270,6 +270,9 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssi
270270 .map_err(api::internal)?
271271 };
272272
273+ let (cache_key, cache_restore_keys) =
274+ cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
275+
273276 Ok(Some(JobAssignment {
274277 job_id: job.id,
275278 job_token,
@@ -285,9 +288,97 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssi
285288 artifacts: spec.artifacts,
286289 timeout_minutes: spec.timeout_minutes,
287290 network: spec.network,
291+ cache: spec.cache,
292+ cache_key,
293+ cache_restore_keys,
288294 }))
289295 }
290296
297+/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
298+/// branch comes from its pull request record.
299+async fn cache_scopes(
300+ state: &AppState,
301+ run: &CiRun,
302+ default_branch: &str,
303+ cache: &[String],
304+) -> Result<(String, Vec<String>), Refusal> {
305+ if cache.is_empty() {
306+ return Ok((String::new(), Vec::new()));
307+ }
308+ let pull_base = match (run.trigger.as_str(), run.pull_number) {
309+ ("pull_request", Some(number)) => state
310+ .store
311+ .pull_by_number(&run.repo_id, number)
312+ .await
313+ .map_err(api::internal)?
314+ .map(|pull| pull.base_branch),
315+ _ => None,
316+ };
317+ let scope = cache_scope(
318+ &run.trigger,
319+ &run.git_ref,
320+ run.pull_number,
321+ pull_base.as_deref(),
322+ default_branch,
323+ );
324+ Ok(match scope {
325+ Some(scope) => (scope.key, scope.restore_keys),
326+ // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
327+ None => (String::new(), Vec::new()),
328+ })
329+}
330+
331+/// The cache scope a run may write, and the read-only scopes it may restore from.
332+#[derive(Debug, Clone, PartialEq, Eq)]
333+struct CacheScope {
334+ key: String,
335+ restore_keys: Vec<String>,
336+}
337+
338+/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
339+///
340+/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
341+/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
342+/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
343+/// run reads the default branch's cache, and both fall back to nothing else.
344+fn cache_scope(
345+ trigger: &str,
346+ git_ref: &str,
347+ pull_number: Option<i64>,
348+ pull_base: Option<&str>,
349+ default_branch: &str,
350+) -> Option<CacheScope> {
351+ let default_ref = format!("ref:refs/heads/{default_branch}");
352+ match trigger {
353+ "pull_request" => {
354+ let number = pull_number?;
355+ let mut restore_keys = Vec::new();
356+ if let Some(base) = pull_base {
357+ restore_keys.push(format!("ref:refs/heads/{base}"));
358+ }
359+ if pull_base != Some(default_branch) {
360+ restore_keys.push(default_ref);
361+ }
362+ Some(CacheScope {
363+ key: format!("pr:{number}"),
364+ restore_keys,
365+ })
366+ }
367+ "push" | "tag" | "manual" | "schedule" => {
368+ let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
369+ Vec::new()
370+ } else {
371+ vec![default_ref]
372+ };
373+ Some(CacheScope {
374+ key: format!("ref:{git_ref}"),
375+ restore_keys,
376+ })
377+ }
378+ _ => None,
379+ }
380+}
381+
291382 /// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
292383 /// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
293384 async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
crates/forge-web/src/ci/api_tests.rsmodified+100 -1
@@ -11,7 +11,7 @@ use serde_json::{Value, json};
1111 use topcoat::router::request::Request;
1212 use topcoat::router::{Body, Router, to_bytes};
1313
14-use super::{artifact_key, fit_to_cap, log_path, valid_artifact_name};
14+use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name};
1515 use crate::pages::commits::test_support::{Fixture, OWNER, REPO};
1616 use crate::test_support::{app_router, test_state};
1717
@@ -899,3 +899,102 @@ async fn claim_advertises_the_binary_only_to_a_matching_target() {
899899 assert!(sent.headers.get("forge-binary-sha256").is_none());
900900 }
901901 }
902+
903+#[test]
904+fn cache_scope_for_push_on_default_branch_has_no_restore_keys() {
905+ let scope = cache_scope("push", "refs/heads/main", None, None, "main").unwrap();
906+ assert_eq!(scope.key, "ref:refs/heads/main");
907+ assert!(scope.restore_keys.is_empty());
908+}
909+
910+#[test]
911+fn cache_scope_for_push_on_branch_restores_default_branch() {
912+ let scope = cache_scope("push", "refs/heads/feature/x", None, None, "main").unwrap();
913+ assert_eq!(scope.key, "ref:refs/heads/feature/x");
914+ assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]);
915+}
916+
917+#[test]
918+fn cache_scope_for_tag_writes_its_ref_and_restores_default_branch() {
919+ let scope = cache_scope("tag", "refs/tags/v1.0", None, None, "main").unwrap();
920+ assert_eq!(scope.key, "ref:refs/tags/v1.0");
921+ assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]);
922+}
923+
924+#[test]
925+fn cache_scope_for_manual_run_uses_the_ref() {
926+ let scope = cache_scope("manual", "refs/heads/main", None, None, "main").unwrap();
927+ assert_eq!(scope.key, "ref:refs/heads/main");
928+ assert!(scope.restore_keys.is_empty());
929+}
930+
931+#[test]
932+fn cache_scope_for_pull_request_writes_only_its_pr_key() {
933+ let scope = cache_scope(
934+ "pull_request",
935+ "refs/pull/12/head",
936+ Some(12),
937+ Some("release/1.0"),
938+ "main",
939+ )
940+ .unwrap();
941+ assert_eq!(scope.key, "pr:12");
942+ assert_eq!(
943+ scope.restore_keys,
944+ vec![
945+ "ref:refs/heads/release/1.0".to_string(),
946+ "ref:refs/heads/main".to_string()
947+ ]
948+ );
949+}
950+
951+#[test]
952+fn cache_scope_for_pull_request_into_default_branch_restores_it_once() {
953+ let scope = cache_scope(
954+ "pull_request",
955+ "refs/pull/3/head",
956+ Some(3),
957+ Some("main"),
958+ "main",
959+ )
960+ .unwrap();
961+ assert_eq!(scope.key, "pr:3");
962+ assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]);
963+}
964+
965+#[test]
966+fn cache_scope_for_pull_request_with_head_named_main_still_writes_pr_key() {
967+ // A fork or same-repo PR whose head branch is called `main` must never get a `ref:` write key.
968+ let scope = cache_scope(
969+ "pull_request",
970+ "refs/pull/7/head",
971+ Some(7),
972+ Some("main"),
973+ "main",
974+ )
975+ .unwrap();
976+ assert_eq!(scope.key, "pr:7");
977+ assert!(!scope.key.starts_with("ref:"));
978+}
979+
980+#[test]
981+fn cache_scope_for_pull_request_without_base_restores_default_only() {
982+ let scope = cache_scope("pull_request", "refs/pull/9/head", Some(9), None, "main").unwrap();
983+ assert_eq!(scope.key, "pr:9");
984+ assert_eq!(scope.restore_keys, vec!["ref:refs/heads/main".to_string()]);
985+}
986+
987+#[test]
988+fn cache_scope_needs_a_pull_number_for_pull_requests_and_a_known_trigger() {
989+ assert!(
990+ cache_scope(
991+ "pull_request",
992+ "refs/pull/1/head",
993+ None,
994+ Some("main"),
995+ "main"
996+ )
997+ .is_none()
998+ );
999+ assert!(cache_scope("bogus", "refs/heads/main", None, None, "main").is_none());
1000+}
crates/forge-web/tests/ci_e2e.rsmodified+1 -0
@@ -474,6 +474,7 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker
474474 registries: Vec::new(),
475475 // The e2e runner must not replace the test binary under itself.
476476 auto_update: false,
477+ cache_max_gib: 0,
477478 };
478479 let runner =
479480 Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner");
deploy/user/forge-runner.servicemodified+4 -1
@@ -9,8 +9,11 @@ OnFailure=forge-runner-rollback.service
99
1010 [Service]
1111 ExecStart=%h/bin/forge runner run --config %h/.config/forge-runner/runner.toml
12-# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary.
12+# A self-update exits with code 75.
1313 Restart=on-failure
14+# Exit 75 is a deliberate restart into a new binary, not a failure: no OnFailure rollback.
15+SuccessExitStatus=75
16+RestartForceExitStatus=75
1417 RestartSec=10
1518 TimeoutStopSec=120
1619
deploy/user/forge.servicemodified+4 -1
@@ -10,8 +10,11 @@ OnFailure=forge-rollback.service
1010 WorkingDirectory=%h
1111 Environment=FORGE_CONFIG=%h/config/forge.toml
1212 ExecStart=%h/bin/forge serve
13-# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary.
13+# A self-update exits with code 75.
1414 Restart=on-failure
15+# Exit 75 is a deliberate restart into a new binary, not a failure: no OnFailure rollback.
16+SuccessExitStatus=75
17+RestartForceExitStatus=75
1518 RestartSec=2
1619 NoNewPrivileges=yes
1720 LimitNOFILE=65536
docs/ci.mdmodified+52 -2
@@ -4,8 +4,8 @@ forge runs CI workflows defined in `.forge/ci.toml` at the root of a repository.
44 separate **runners**, which are `forge runner` on machines you control. The forge never
55 connects to a runner. Runners pull jobs over HTTPS.
66
7-What v1 has: jobs with `needs`, secrets, artifacts, live logs, commit statuses, and manual, push,
8-tag and pull request triggers. What it does not have: a cache, or YAML. The workflow file is TOML.
7+What v1 has: jobs with `needs`, secrets, artifacts, a build cache, live logs, commit statuses, and
8+manual, push, tag and pull request triggers. What it does not have: YAML. The workflow file is TOML.
99
1010 Jobs run in a rootless sandbox, with no container tool needed. The runner pulls and unpacks the
1111 image itself, and runs each job in its own container built with libcontainer, the crate behind
@@ -46,6 +46,7 @@ There must be at least one job, and at most 20.
4646 | `env` | table of string | `{}` | Plain env vars. Names match the same pattern. A secret with the same name wins. |
4747 | `artifacts` | array of string | `[]` | Relative globs in the workspace. No `..`, no leading `/`. |
4848 | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. |
49+| `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). |
4950 | `timeout_minutes` | integer | `60` | Range 1 to 360. |
5051 | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). |
5152
@@ -387,6 +388,55 @@ no heartbeat.
387388 A job with `runs_on = ["linux", "x86_64"]` is only claimed by a runner that has both labels. Jobs
388389 with no `runs_on` can go to any runner.
389390
391+### Cache
392+
393+A job can keep directories between runs, such as a Rust `target` directory:
394+
395+```toml
396+[jobs.test]
397+image = "docker.io/rust:1"
398+cache = ["target"]
399+run = "cargo test --workspace"
400+```
401+
402+Each entry is a path relative to the workspace (`/workspace`). Rules:
403+
404+- At most 8 entries per job, each at most 200 characters, with no duplicates.
405+- No leading `/`, no `\`, no `..`, no `.` components, no empty components, no glob characters
406+ (`*?[]{}`), no control characters.
407+- Nothing under `.git`.
408+
409+The runner keeps cache entries on its own disk, keyed by repo, job name and scope: a branch, a tag,
410+or a pull request. Two jobs never share a cache, and two repos never do either.
411+
412+- A push, tag or manual run writes the cache of its own ref, such as `refs/heads/main`. It reads
413+ the default branch's cache when its own ref has none, unless it is the default branch.
414+- A pull request run writes only its own cache, keyed by the pull request number. It reads its
415+ base branch's cache, then the default branch's cache. A pull request never writes a branch cache,
416+ so a change under review cannot leave a cache that a later build of `main` will use.
417+- When a branch is reused, its cache is moved to the new run, not copied. Only one run owns it at a
418+ time.
419+- The runner caps the total size of its caches. When the cap is reached, the least recently used
420+ entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`.
421+
422+A cache is a speed-up, not a source of truth. A job must still build correctly from an empty cache.
423+
424+#### Rust tip
425+
426+Cache the build directory, and optionally the cargo home:
427+
428+```toml
429+[jobs.test]
430+image = "docker.io/rust:1"
431+cache = ["target", ".cargo-home"]
432+run = """
433+export CARGO_HOME=/workspace/.cargo-home
434+cargo test --workspace
435+"""
436+```
437+
438+Setting `CARGO_HOME` to a path inside the workspace keeps the downloaded crates in the cache too.
439+
390440 ## Forge limits (`[ci]`)
391441
392442 The `[ci]` section of `forge.toml` controls CI on the forge. These are the defaults: