forge
Explore
Log in

Don't you dare go Hollow

Artifacts keep the newest runs per repo under a disk limit, and self-update takes forge-{target} with dist_forge as an alias

Browse files at this commit

7ead061ed737faf4ebdfd0ac83f06a0783972264Ahmet Kaan GümüşParent: 881b746
Some checks failed
Show checks
  • feat
    • artifacts keep the newest runs per repo under a disk limit, and self-update takes forge-{target} with dist_forge as an alias
Show full message
✨ feat: artifacts keep the newest runs per repo under a disk limit, and self-update takes forge-{target} with dist_forge as an alias
README.mdmodified+1 -1
@@ -154,7 +154,7 @@ enabled = true
154154 repo = "Tahinli/forge"
155155 branch = "main"
156156 job = "build"
157-artifact = "dist_forge"
157+artifact = "forge-{target}"
158158 ```
159159
160160 Runners update by default (`auto_update = true` in `runner.toml`). Set it to `false` to pin a runner's binary by hand.
crates/forge-core/src/config.rsmodified+13 -4
@@ -272,8 +272,9 @@ pub struct SelfUpdateConfig {
272272 pub branch: String,
273273 /// The CI job that produces the artifact.
274274 pub job: String,
275- /// The artifact name produced by `job`. A single file. CI flattens paths, so `dist/forge`
276- /// is stored as `dist_forge`.
275+ /// The artifact name produced by `job`. A single file. `{target}` is replaced with the
276+ /// server's own `<arch>-<os>` target (e.g. `x86_64-linux`), so the same setting works on any
277+ /// arch.
277278 pub artifact: String,
278279 }
279280
@@ -284,7 +285,7 @@ impl Default for SelfUpdateConfig {
284285 repo: String::new(),
285286 branch: "main".into(),
286287 job: "build".into(),
287- artifact: "dist_forge".into(),
288+ artifact: "forge-{target}".into(),
288289 }
289290 }
290291 }
@@ -367,6 +368,12 @@ pub struct CiConfig {
367368 pub log_retention_days: u64,
368369 /// Days an artifact is kept.
369370 pub artifact_retention_days: u64,
371+ /// Artifacts of the newest this-many runs per repo (that have artifacts) are kept; older runs
372+ /// lose theirs. 0 keeps all.
373+ pub artifact_keep_runs: u32,
374+ /// Largest total size of all CI artifacts, in MiB. Past it, the oldest runs' artifacts are
375+ /// deleted whole until the total fits. 0 is no limit.
376+ pub artifact_max_total_mb: u64,
370377 /// Hours a runner registration token stays valid.
371378 pub registration_token_hours: u32,
372379 /// Milliseconds a runner claim waits for work before it is answered with no job.
@@ -382,6 +389,8 @@ impl Default for CiConfig {
382389 max_artifacts_per_job: 50,
383390 log_retention_days: 90,
384391 artifact_retention_days: 30,
392+ artifact_keep_runs: 10,
393+ artifact_max_total_mb: 0,
385394 registration_token_hours: 24,
386395 claim_wait_ms: 25_000,
387396 }
@@ -973,7 +982,7 @@ mod tests {
973982 assert_eq!(cfg.self_update.branch, "main", "self_update branch");
974983 assert_eq!(cfg.self_update.job, "build", "self_update job");
975984 assert_eq!(
976- cfg.self_update.artifact, "dist_forge",
985+ cfg.self_update.artifact, "forge-{target}",
977986 "self_update artifact"
978987 );
979988 // storage
crates/forge-core/src/server_settings.rsmodified+21 -1
@@ -302,6 +302,22 @@ pub static FIELDS: &[Field] = &[
302302 "Artifact retention (days)",
303303 "",
304304 ),
305+ f(
306+ "ci.artifact_keep_runs",
307+ Limits,
308+ L,
309+ Ty::Uint(0, 100_000),
310+ "Artifact runs kept per repo",
311+ "0 keeps all.",
312+ ),
313+ f(
314+ "ci.artifact_max_total_mb",
315+ Limits,
316+ L,
317+ Ty::Uint(0, 100_000_000),
318+ "Artifact disk limit (MiB)",
319+ "Oldest runs' artifacts go first. 0 is no limit.",
320+ ),
305321 f(
306322 "ci.registration_token_hours",
307323 Limits,
@@ -607,7 +623,7 @@ pub static FIELDS: &[Field] = &[
607623 X,
608624 Ty::Text,
609625 "Self-update artifact",
610- "",
626+ "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.",
611627 ),
612628 f(
613629 "alerts.enabled",
@@ -868,6 +884,8 @@ pub fn get(cfg: &Config, key: &str) -> String {
868884 "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(),
869885 "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(),
870886 "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(),
887+ "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs.to_string(),
888+ "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb.to_string(),
871889 "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(),
872890 "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(),
873891 "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(),
@@ -980,6 +998,8 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
980998 "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32,
981999 "ci.log_retention_days" => cfg.ci.log_retention_days = n(v),
9821000 "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v),
1001+ "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs = n(v) as u32,
1002+ "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb = n(v),
9831003 "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32,
9841004 "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v),
9851005 "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v),
crates/forge-core/src/store/ci.rsmodified+100 -6
@@ -1637,12 +1637,17 @@ impl Store {
16371637
16381638 /// Retention. Jobs of runs that finished before `logs_before` and still have logs get
16391639 /// `log_bytes = 0`; their ids are returned so the caller deletes the log files. Artifact rows
1640- /// created before `artifacts_before` are deleted; their ids are returned so the caller
1641- /// deletes the files.
1640+ /// created before `artifacts_before` are deleted. Then, per repo, the artifacts of every run
1641+ /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if
1642+ /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the
1643+ /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are
1644+ /// returned (deduplicated) so the caller deletes the files.
16421645 pub async fn purge_old(
16431646 &self,
16441647 logs_before: &str,
16451648 artifacts_before: &str,
1649+ keep_runs: u32,
1650+ max_total_bytes: u64,
16461651 ) -> Result<(Vec<String>, Vec<String>)> {
16471652 let conn = self.inner.conn.lock().await;
16481653 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -1664,7 +1669,7 @@ impl Store {
16641669 .await
16651670 .map_err(db_err)?;
16661671 }
1667- let artifact_ids = fetch_all(
1672+ let mut artifact_ids = fetch_all(
16681673 &tx,
16691674 "SELECT id FROM ci_artifacts WHERE created_at < ?1 ORDER BY id",
16701675 (artifacts_before.to_string(),),
@@ -1677,6 +1682,62 @@ impl Store {
16771682 )
16781683 .await
16791684 .map_err(db_err)?;
1685+
1686+ // Keep only the newest `keep_runs` runs (per repo) that still have artifacts.
1687+ if keep_runs > 0 {
1688+ let old = fetch_all(
1689+ &tx,
1690+ "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \
1691+ WHERE j.run_id NOT IN ( \
1692+ SELECT id FROM ( \
1693+ SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.id DESC) \
1694+ AS rn \
1695+ FROM ci_runs r \
1696+ WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \
1697+ ON j2.id = a2.job_id WHERE j2.run_id = r.id) \
1698+ ) WHERE rn <= ?1 \
1699+ ) ORDER BY a.id",
1700+ (i64::from(keep_runs),),
1701+ |row| col_text(row, 0),
1702+ )
1703+ .await?;
1704+ for id in &old {
1705+ tx.execute("DELETE FROM ci_artifacts WHERE id = ?1", (id.clone(),))
1706+ .await
1707+ .map_err(db_err)?;
1708+ }
1709+ artifact_ids.extend(old);
1710+ }
1711+
1712+ // Over the disk limit: drop the oldest runs' artifacts, one whole run at a time.
1713+ if max_total_bytes > 0 {
1714+ let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX);
1715+ // (artifact id, run id, size), oldest run first.
1716+ let rows = fetch_all(
1717+ &tx,
1718+ "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \
1719+ JOIN ci_jobs j ON j.id = a.job_id ORDER BY j.run_id ASC, a.id ASC",
1720+ (),
1721+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_int(row, 2)?)),
1722+ )
1723+ .await?;
1724+ let mut total: i64 = rows.iter().map(|row| row.2).sum();
1725+ let mut i = 0;
1726+ while total > limit && i < rows.len() {
1727+ let run = rows[i].1.clone();
1728+ while i < rows.len() && rows[i].1 == run {
1729+ tx.execute("DELETE FROM ci_artifacts WHERE id = ?1", (rows[i].0.clone(),))
1730+ .await
1731+ .map_err(db_err)?;
1732+ total -= rows[i].2;
1733+ artifact_ids.push(rows[i].0.clone());
1734+ i += 1;
1735+ }
1736+ }
1737+ }
1738+
1739+ artifact_ids.sort();
1740+ artifact_ids.dedup();
16801741 Ok((job_ids, artifact_ids))
16811742 }
16821743 .await;
@@ -3216,10 +3277,10 @@ mod tests {
32163277 let later = stamp_after(Duration::from_secs(3600));
32173278
32183279 assert_eq!(
3219- fx.store.purge_old(DAWN, DAWN).await.unwrap(),
3280+ fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(),
32203281 (vec![], vec![])
32213282 );
3222- let (logs, artifacts) = fx.store.purge_old(&later, &later).await.unwrap();
3283+ let (logs, artifacts) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
32233284 assert_eq!(logs, vec![a.id.clone()]);
32243285 assert_eq!(artifacts.len(), 1);
32253286 assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0);
@@ -3230,10 +3291,43 @@ mod tests {
32303291 .unwrap()
32313292 .is_none()
32323293 );
3233- let (logs2, artifacts2) = fx.store.purge_old(&later, &later).await.unwrap();
3294+ let (logs2, artifacts2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap();
32343295 assert!(logs2.is_empty() && artifacts2.is_empty());
32353296 }
32363297
3298+ #[tokio::test]
3299+ async fn purge_old_keeps_newest_runs_then_fits_the_disk_limit() {
3300+ let fx = fixture().await;
3301+ let mut artifacts = Vec::new();
3302+ for size in [10_i64, 20, 30] {
3303+ let run = create(
3304+ &fx.store,
3305+ &fx.repo.id,
3306+ &fx.tahinli.id,
3307+ &[job("a", &[], &[])],
3308+ false,
3309+ )
3310+ .await;
3311+ let a = job_named(&fx.store, &run.id, "a").await;
3312+ let made = fx
3313+ .store
3314+ .add_artifact(&a.id, "dist.tar", size, "ab")
3315+ .await
3316+ .unwrap();
3317+ artifacts.push(made.id);
3318+ // ULIDs made in the same millisecond do not sort by creation order.
3319+ tokio::time::sleep(Duration::from_millis(2)).await;
3320+ }
3321+ // Keep the newest two runs: the oldest run's artifact goes.
3322+ let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();
3323+ assert_eq!(deleted, vec![artifacts[0].clone()]);
3324+ // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes.
3325+ let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
3326+ assert_eq!(deleted, vec![artifacts[1].clone()]);
3327+ let (_, again) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
3328+ assert!(again.is_empty());
3329+ }
3330+
32373331 async fn artifacts_are_unique_per_job_and_listed(fx: &Fx) {
32383332 let repo = repo_named(fx, "artifacts").await;
32393333 let run = create(
crates/forge-web/src/ci/api.rsmodified+10 -4
@@ -835,10 +835,16 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
835835 ));
836836 }
837837 match upload(state, &job, name, body).await {
838- Ok(artifact_id) => Ok(api::json(
839- StatusCode::CREATED,
840- &json!({ "id": artifact_id, "name": name }),
841- )),
838+ Ok(artifact_id) => {
839+ // A new artifact may push the store past its disk limit. Enforce it now, not at the
840+ // next daily purge. The request does not wait for it.
841+ let state = state.clone();
842+ tokio::spawn(async move { crate::ci::reaper::purge_once(&state).await });
843+ Ok(api::json(
844+ StatusCode::CREATED,
845+ &json!({ "id": artifact_id, "name": name }),
846+ ))
847+ }
842848 Err(res) => Ok(*res),
843849 }
844850 }
crates/forge-web/src/ci/reaper.rsmodified+10 -1
@@ -104,7 +104,16 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) {
104104 let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60));
105105 let logs_before = stamp_ago(day(ci.log_retention_days));
106106 let artifacts_before = stamp_ago(day(ci.artifact_retention_days));
107- let (job_ids, artifact_ids) = match state.store.purge_old(&logs_before, &artifacts_before).await
107+ let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024);
108+ let (job_ids, artifact_ids) = match state
109+ .store
110+ .purge_old(
111+ &logs_before,
112+ &artifacts_before,
113+ ci.artifact_keep_runs,
114+ max_total_bytes,
115+ )
116+ .await
108117 {
109118 Ok(ids) => ids,
110119 Err(e) => {
crates/forge-web/src/self_update.rsmodified+9 -3
@@ -225,13 +225,19 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> {
225225 tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping");
226226 return Ok(());
227227 };
228+ // "dist_forge" was the old default; CI no longer uploads it, so it means the arch-named binary.
229+ let configured = match cfg.artifact.as_str() {
230+ "dist_forge" => "forge-{target}",
231+ other => other,
232+ };
233+ let artifact_name = configured.replace("{target}", &target());
228234 let artifact = state
229235 .store
230- .artifact(&job.id, &cfg.artifact)
236+ .artifact(&job.id, &artifact_name)
231237 .await
232238 .map_err(|e| e.to_string())?;
233239 let Some(artifact) = artifact else {
234- tracing::info!(run_id = %run.id, artifact = %cfg.artifact, "self-update: no such artifact, skipping");
240+ tracing::info!(run_id = %run.id, artifact = %artifact_name, "self-update: no such artifact, skipping");
235241 return Ok(());
236242 };
237243 let read = state
@@ -411,7 +417,7 @@ mod tests {
411417 repo: "Tahinli/forge".into(),
412418 branch: "main".into(),
413419 job: "build".into(),
414- artifact: "dist_forge".into(),
420+ artifact: "forge-{target}".into(),
415421 }
416422 }
417423
docs/ci.mdmodified+5 -2
@@ -764,12 +764,15 @@ max_artifact_mb = 512 # per artifact
764764 max_artifacts_per_job = 50
765765 log_retention_days = 90
766766 artifact_retention_days = 30
767+artifact_keep_runs = 10 # artifacts of the newest N runs per repo (that have any) are kept; 0 keeps all
768+artifact_max_total_mb = 0 # total artifact size limit; the oldest runs' artifacts go first; 0 is no limit
767769 registration_token_hours = 24
768770 ```
769771
770-Retention runs once a day. Logs older than `log_retention_days` are deleted. The job rows stay, so
772+Retention runs once a day, and again after each artifact upload for the disk limit. Logs older than `log_retention_days` are deleted. The job rows stay, so
771773 statuses and run pages still work. Artifacts older than `artifact_retention_days` are deleted from the
772-blob store.
774+blob store. `artifact_keep_runs` keeps only the newest runs' artifacts in each repo, and
775+`artifact_max_total_mb` deletes the oldest runs' artifacts, whole runs at a time, until all artifacts fit.
773776
774777 ## Runner protocol
775778