From 7ead061ed737faf4ebdfd0ac83f06a0783972264 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 00:49:42 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20artifacts=20keep=20the=20ne?= =?UTF-8?q?west=20runs=20per=20repo=20under=20a=20disk=20limit,=20and=20se?= =?UTF-8?q?lf-update=20takes=20forge-{target}=20with=20dist=5Fforge=20as?= =?UTF-8?q?=20an=20alias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- crates/forge-core/src/config.rs | 17 +++- crates/forge-core/src/server_settings.rs | 22 ++++- crates/forge-core/src/store/ci.rs | 106 +++++++++++++++++++++-- crates/forge-web/src/ci/api.rs | 14 ++- crates/forge-web/src/ci/reaper.rs | 11 ++- crates/forge-web/src/self_update.rs | 12 ++- docs/ci.md | 7 +- 8 files changed, 169 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index cb4fc4c..0fcc972 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ enabled = true repo = "Tahinli/forge" branch = "main" job = "build" -artifact = "dist_forge" +artifact = "forge-{target}" ``` Runners update by default (`auto_update = true` in `runner.toml`). Set it to `false` to pin a runner's binary by hand. diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index ecd1630..dffc211 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -272,8 +272,9 @@ pub struct SelfUpdateConfig { pub branch: String, /// The CI job that produces the artifact. pub job: String, - /// The artifact name produced by `job`. A single file. CI flattens paths, so `dist/forge` - /// is stored as `dist_forge`. + /// The artifact name produced by `job`. A single file. `{target}` is replaced with the + /// server's own `-` target (e.g. `x86_64-linux`), so the same setting works on any + /// arch. pub artifact: String, } @@ -284,7 +285,7 @@ impl Default for SelfUpdateConfig { repo: String::new(), branch: "main".into(), job: "build".into(), - artifact: "dist_forge".into(), + artifact: "forge-{target}".into(), } } } @@ -367,6 +368,12 @@ pub struct CiConfig { pub log_retention_days: u64, /// Days an artifact is kept. pub artifact_retention_days: u64, + /// Artifacts of the newest this-many runs per repo (that have artifacts) are kept; older runs + /// lose theirs. 0 keeps all. + pub artifact_keep_runs: u32, + /// Largest total size of all CI artifacts, in MiB. Past it, the oldest runs' artifacts are + /// deleted whole until the total fits. 0 is no limit. + pub artifact_max_total_mb: u64, /// Hours a runner registration token stays valid. pub registration_token_hours: u32, /// Milliseconds a runner claim waits for work before it is answered with no job. @@ -382,6 +389,8 @@ impl Default for CiConfig { max_artifacts_per_job: 50, log_retention_days: 90, artifact_retention_days: 30, + artifact_keep_runs: 10, + artifact_max_total_mb: 0, registration_token_hours: 24, claim_wait_ms: 25_000, } @@ -973,7 +982,7 @@ mod tests { assert_eq!(cfg.self_update.branch, "main", "self_update branch"); assert_eq!(cfg.self_update.job, "build", "self_update job"); assert_eq!( - cfg.self_update.artifact, "dist_forge", + cfg.self_update.artifact, "forge-{target}", "self_update artifact" ); // storage diff --git a/crates/forge-core/src/server_settings.rs b/crates/forge-core/src/server_settings.rs index 96904b4..14c5e28 100644 --- a/crates/forge-core/src/server_settings.rs +++ b/crates/forge-core/src/server_settings.rs @@ -302,6 +302,22 @@ pub static FIELDS: &[Field] = &[ "Artifact retention (days)", "", ), + f( + "ci.artifact_keep_runs", + Limits, + L, + Ty::Uint(0, 100_000), + "Artifact runs kept per repo", + "0 keeps all.", + ), + f( + "ci.artifact_max_total_mb", + Limits, + L, + Ty::Uint(0, 100_000_000), + "Artifact disk limit (MiB)", + "Oldest runs' artifacts go first. 0 is no limit.", + ), f( "ci.registration_token_hours", Limits, @@ -607,7 +623,7 @@ pub static FIELDS: &[Field] = &[ X, Ty::Text, "Self-update artifact", - "", + "{target} becomes this server's arch-os, e.g. forge-{target} is forge-x86_64-linux.", ), f( "alerts.enabled", @@ -868,6 +884,8 @@ pub fn get(cfg: &Config, key: &str) -> String { "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(), "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(), "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(), + "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs.to_string(), + "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb.to_string(), "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(), "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(), "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<()> { "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32, "ci.log_retention_days" => cfg.ci.log_retention_days = n(v), "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v), + "ci.artifact_keep_runs" => cfg.ci.artifact_keep_runs = n(v) as u32, + "ci.artifact_max_total_mb" => cfg.ci.artifact_max_total_mb = n(v), "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32, "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v), "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v), diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index df3b965..1e8ae52 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -1637,12 +1637,17 @@ impl Store { /// Retention. Jobs of runs that finished before `logs_before` and still have logs get /// `log_bytes = 0`; their ids are returned so the caller deletes the log files. Artifact rows - /// created before `artifacts_before` are deleted; their ids are returned so the caller - /// deletes the files. + /// created before `artifacts_before` are deleted. Then, per repo, the artifacts of every run + /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if + /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the + /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are + /// returned (deduplicated) so the caller deletes the files. pub async fn purge_old( &self, logs_before: &str, artifacts_before: &str, + keep_runs: u32, + max_total_bytes: u64, ) -> Result<(Vec, Vec)> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; @@ -1664,7 +1669,7 @@ impl Store { .await .map_err(db_err)?; } - let artifact_ids = fetch_all( + let mut artifact_ids = fetch_all( &tx, "SELECT id FROM ci_artifacts WHERE created_at < ?1 ORDER BY id", (artifacts_before.to_string(),), @@ -1677,6 +1682,62 @@ impl Store { ) .await .map_err(db_err)?; + + // Keep only the newest `keep_runs` runs (per repo) that still have artifacts. + if keep_runs > 0 { + let old = fetch_all( + &tx, + "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \ + WHERE j.run_id NOT IN ( \ + SELECT id FROM ( \ + SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.id DESC) \ + AS rn \ + FROM ci_runs r \ + WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \ + ON j2.id = a2.job_id WHERE j2.run_id = r.id) \ + ) WHERE rn <= ?1 \ + ) ORDER BY a.id", + (i64::from(keep_runs),), + |row| col_text(row, 0), + ) + .await?; + for id in &old { + tx.execute("DELETE FROM ci_artifacts WHERE id = ?1", (id.clone(),)) + .await + .map_err(db_err)?; + } + artifact_ids.extend(old); + } + + // Over the disk limit: drop the oldest runs' artifacts, one whole run at a time. + if max_total_bytes > 0 { + let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX); + // (artifact id, run id, size), oldest run first. + let rows = fetch_all( + &tx, + "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \ + JOIN ci_jobs j ON j.id = a.job_id ORDER BY j.run_id ASC, a.id ASC", + (), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_int(row, 2)?)), + ) + .await?; + let mut total: i64 = rows.iter().map(|row| row.2).sum(); + let mut i = 0; + while total > limit && i < rows.len() { + let run = rows[i].1.clone(); + while i < rows.len() && rows[i].1 == run { + tx.execute("DELETE FROM ci_artifacts WHERE id = ?1", (rows[i].0.clone(),)) + .await + .map_err(db_err)?; + total -= rows[i].2; + artifact_ids.push(rows[i].0.clone()); + i += 1; + } + } + } + + artifact_ids.sort(); + artifact_ids.dedup(); Ok((job_ids, artifact_ids)) } .await; @@ -3216,10 +3277,10 @@ mod tests { let later = stamp_after(Duration::from_secs(3600)); assert_eq!( - fx.store.purge_old(DAWN, DAWN).await.unwrap(), + fx.store.purge_old(DAWN, DAWN, 0, 0).await.unwrap(), (vec![], vec![]) ); - let (logs, artifacts) = fx.store.purge_old(&later, &later).await.unwrap(); + let (logs, artifacts) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); assert_eq!(logs, vec![a.id.clone()]); assert_eq!(artifacts.len(), 1); assert_eq!(job_named(&fx.store, &run.id, "a").await.log_bytes, 0); @@ -3230,10 +3291,43 @@ mod tests { .unwrap() .is_none() ); - let (logs2, artifacts2) = fx.store.purge_old(&later, &later).await.unwrap(); + let (logs2, artifacts2) = fx.store.purge_old(&later, &later, 0, 0).await.unwrap(); assert!(logs2.is_empty() && artifacts2.is_empty()); } + #[tokio::test] + async fn purge_old_keeps_newest_runs_then_fits_the_disk_limit() { + let fx = fixture().await; + let mut artifacts = Vec::new(); + for size in [10_i64, 20, 30] { + let run = create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[job("a", &[], &[])], + false, + ) + .await; + let a = job_named(&fx.store, &run.id, "a").await; + let made = fx + .store + .add_artifact(&a.id, "dist.tar", size, "ab") + .await + .unwrap(); + artifacts.push(made.id); + // ULIDs made in the same millisecond do not sort by creation order. + tokio::time::sleep(Duration::from_millis(2)).await; + } + // Keep the newest two runs: the oldest run's artifact goes. + let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); + assert_eq!(deleted, vec![artifacts[0].clone()]); + // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. + let (_, deleted) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); + assert_eq!(deleted, vec![artifacts[1].clone()]); + let (_, again) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); + assert!(again.is_empty()); + } + async fn artifacts_are_unique_per_job_and_listed(fx: &Fx) { let repo = repo_named(fx, "artifacts").await; let run = create( diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index c773b1e..313bd6e 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -835,10 +835,16 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result { )); } match upload(state, &job, name, body).await { - Ok(artifact_id) => Ok(api::json( - StatusCode::CREATED, - &json!({ "id": artifact_id, "name": name }), - )), + Ok(artifact_id) => { + // A new artifact may push the store past its disk limit. Enforce it now, not at the + // next daily purge. The request does not wait for it. + let state = state.clone(); + tokio::spawn(async move { crate::ci::reaper::purge_once(&state).await }); + Ok(api::json( + StatusCode::CREATED, + &json!({ "id": artifact_id, "name": name }), + )) + } Err(res) => Ok(*res), } } diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index 8aecc67..724bd0d 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -104,7 +104,16 @@ pub async fn purge_once(state: &AppState) -> (usize, usize) { let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60)); let logs_before = stamp_ago(day(ci.log_retention_days)); let artifacts_before = stamp_ago(day(ci.artifact_retention_days)); - let (job_ids, artifact_ids) = match state.store.purge_old(&logs_before, &artifacts_before).await + let max_total_bytes = ci.artifact_max_total_mb.saturating_mul(1024 * 1024); + let (job_ids, artifact_ids) = match state + .store + .purge_old( + &logs_before, + &artifacts_before, + ci.artifact_keep_runs, + max_total_bytes, + ) + .await { Ok(ids) => ids, Err(e) => { diff --git a/crates/forge-web/src/self_update.rs b/crates/forge-web/src/self_update.rs index 7c359ea..fcc14e1 100644 --- a/crates/forge-web/src/self_update.rs +++ b/crates/forge-web/src/self_update.rs @@ -225,13 +225,19 @@ async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> { tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping"); return Ok(()); }; + // "dist_forge" was the old default; CI no longer uploads it, so it means the arch-named binary. + let configured = match cfg.artifact.as_str() { + "dist_forge" => "forge-{target}", + other => other, + }; + let artifact_name = configured.replace("{target}", &target()); let artifact = state .store - .artifact(&job.id, &cfg.artifact) + .artifact(&job.id, &artifact_name) .await .map_err(|e| e.to_string())?; let Some(artifact) = artifact else { - tracing::info!(run_id = %run.id, artifact = %cfg.artifact, "self-update: no such artifact, skipping"); + tracing::info!(run_id = %run.id, artifact = %artifact_name, "self-update: no such artifact, skipping"); return Ok(()); }; let read = state @@ -411,7 +417,7 @@ mod tests { repo: "Tahinli/forge".into(), branch: "main".into(), job: "build".into(), - artifact: "dist_forge".into(), + artifact: "forge-{target}".into(), } } diff --git a/docs/ci.md b/docs/ci.md index f5c3b32..edd77a2 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -764,12 +764,15 @@ max_artifact_mb = 512 # per artifact max_artifacts_per_job = 50 log_retention_days = 90 artifact_retention_days = 30 +artifact_keep_runs = 10 # artifacts of the newest N runs per repo (that have any) are kept; 0 keeps all +artifact_max_total_mb = 0 # total artifact size limit; the oldest runs' artifacts go first; 0 is no limit registration_token_hours = 24 ``` -Retention runs once a day. Logs older than `log_retention_days` are deleted. The job rows stay, so +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 statuses and run pages still work. Artifacts older than `artifact_retention_days` are deleted from the -blob store. +blob store. `artifact_keep_runs` keeps only the newest runs' artifacts in each repo, and +`artifact_max_total_mb` deletes the oldest runs' artifacts, whole runs at a time, until all artifacts fit. ## Runner protocol