diff --git a/app/database/migrations/2026_12_03_000400_diffs_used_at.rs b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs new file mode 100644 index 00000000..be42b880 --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs @@ -0,0 +1,14 @@ +//! `diffs.used_at`: when a comparison last reused the cached diff. Retention leaves the overlay of a diff reused in the +//! last day alone, since the build reusing it isn't in the prune's keep sets. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE diffs ADD COLUMN used_at timestamp with time zone; +CREATE INDEX diffs_used_at ON diffs USING btree (used_at) WHERE used_at IS NOT NULL; +"; diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index fd84e4fb..64b050e8 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -8,15 +8,18 @@ use crate::models::Blob; use crate::storage::BlobStore; /// Record a blob a client or renderer is about to upload (or already has). Returns it. A blob retention marked for -/// deletion loses the mark and counts as not uploaded, so the client uploads it again; retention then leaves it. +/// deletion loses the mark and counts as not uploaded, so the client uploads it again. Registering also renews +/// `updated_at` (at most hourly), and retention doesn't mark a blob registered in the last day, so a file a build is +/// about to name is never deleted under it. /// /// # Errors /// On a database error. pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::Result { db::query!( "INSERT INTO blobs (sha256, size, content_type) VALUES ({sha256}, {size}, {content_type}) \ - ON CONFLICT (sha256) DO UPDATE SET deleting = false, uploaded_at = NULL, updated_at = now() \ - WHERE blobs.deleting" + ON CONFLICT (sha256) DO UPDATE SET deleting = false, updated_at = now(), \ + uploaded_at = CASE WHEN blobs.deleting THEN NULL ELSE blobs.uploaded_at END \ + WHERE blobs.deleting OR blobs.updated_at < now() - interval '1 hour'" ) .insert() .await?; diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs index 5760ac22..2ab1e0a1 100644 --- a/app/src/domain/diffs.rs +++ b/app/src/domain/diffs.rs @@ -31,6 +31,18 @@ async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result< .await } +/// Note that a comparison reuses this diff now (at most once an hour): retention leaves its overlay alone for a day +/// after. +async fn mark_used(diff_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE diffs SET used_at = now() \ + WHERE id = {diff_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + Ok(()) +} + /// The diff of two images, computed (with its overlay stored as a blob) on first use. A diff whose overlay retention /// deleted is computed again, and keeps its row. /// @@ -44,7 +56,10 @@ pub async fn find_or_compute( ) -> laravel::Result { let key = options_key(&options); let stale = match find(base_image, head_image, &key).await? { - Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => return Ok(diff), + Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => { + mark_used(diff.id).await?; + return Ok(diff); + } other => other, }; let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); diff --git a/app/src/domain/downloads.rs b/app/src/domain/downloads.rs index 355788ff..b090ce67 100644 --- a/app/src/domain/downloads.rs +++ b/app/src/domain/downloads.rs @@ -273,13 +273,54 @@ fn path_part(name: &str) -> String { .join("/") } -/// A snapshot's directory, suffixed `~2`, `~3`… when another snapshot's name made safe gave the same one (`a:b` and -/// `a?b` are both `a_b`). -fn unique_dir(used: &mut std::collections::HashSet, dir: String) -> String { - if used.insert(dir.clone()) { - return dir; +/// The archive's paths so far, so every snapshot and page directory is one of its own. Names made safe can meet (`a:b` +/// and `a?b` are both `a_b`), a snapshot can be named like another's page (`x/page-2` beside page 2 of `x`), and a name +/// can be another's file (`x/head.png` beside `x`'s head image). A directory that would meet one already used, as a +/// directory or as a file, or whose files would meet a directory, is suffixed `~2`, `~3`… (the manifest names each +/// snapshot's paths). +#[derive(Default)] +struct Layout { + /// Snapshot and page directories handed out. + taken: std::collections::HashSet, + /// Every directory above a path handed out. + parents: std::collections::HashSet, + /// Files a directory handed out may hold: `/.`. + files: std::collections::HashSet, +} + +const EXTENSIONS: &[&str] = &["png", "jpg", "webp"]; + +fn ancestors(path: &str) -> impl Iterator { + path.char_indices().filter(|(_, c)| *c == '/').map(move |(i, _)| &path[..i]) +} + +impl Layout { + fn planned_files(dir: &str) -> impl Iterator + '_ { + SIDES.iter().flat_map(move |side| EXTENSIONS.iter().map(move |ext| format!("{dir}/{side}.{ext}"))) + } + + /// Whether `dir` can be handed out, holding files (`with_files`) or only page directories. + fn free(&self, dir: &str, with_files: bool) -> bool { + !self.taken.contains(dir) + && !self.files.contains(dir) + && !ancestors(dir).any(|a| self.files.contains(a)) + && (!with_files || Self::planned_files(dir).all(|f| !self.taken.contains(&f) && !self.parents.contains(&f))) + } + + /// Hand out `dir`, or the first `dir~N` that's free. + fn take(&mut self, dir: &str, with_files: bool) -> String { + let chosen = if self.free(dir, with_files) { + dir.to_string() + } else { + (2..).map(|n| format!("{dir}~{n}")).find(|d| self.free(d, with_files)).unwrap_or_else(|| dir.to_string()) + }; + self.parents.extend(ancestors(&chosen).map(str::to_string)); + if with_files { + self.files.extend(Self::planned_files(&chosen)); + } + self.taken.insert(chosen.clone()); + chosen } - (2..).map(|n| format!("{dir}~{n}")).find(|d| used.insert(d.clone())).unwrap_or(dir) } fn extension(bytes: &[u8]) -> &'static str { @@ -344,18 +385,20 @@ async fn write_archive( let mut files = 0i32; let mut entries = Vec::new(); let result: Result<(), String> = async { - let mut used = std::collections::HashSet::new(); + let mut layout = Layout::default(); for s in &chosen { let mut dir = path_part(&s.name); if !s.platform.is_empty() { dir = format!("{dir}@{}", path_part(&s.platform)); } - dir = unique_dir(&mut used, dir); let pages = pages_of.get(&s.id).map(Vec::as_slice).unwrap_or_default(); let several = pages.len() > 1; + // A single page's files go in the snapshot's directory; several pages each get one beneath it. + let dir = layout.take(&dir, !several); let mut listed = Vec::new(); for p in pages { - let page_dir = if several { format!("{dir}/page-{}", p.position + 1) } else { dir.clone() }; + let page_dir = + if several { layout.take(&format!("{dir}/page-{}", p.position + 1), true) } else { dir.clone() }; let diff = p.diff_id.and_then(|id| diffs.get(&id)); let result = diff.and_then(super::diffs::result); let regions = result.as_ref().map(|r| r.regions.as_slice()).unwrap_or_default(); @@ -457,12 +500,42 @@ mod tests { #[test] fn names_that_become_the_same_path_get_their_own_directories() { - let mut used = std::collections::HashSet::new(); - let dirs: Vec = - ["a:b", "a?b", "a_b", "c"].iter().map(|n| unique_dir(&mut used, path_part(n))).collect(); + let mut layout = Layout::default(); + let dirs: Vec = ["a:b", "a?b", "a_b", "c"].iter().map(|n| layout.take(&path_part(n), true)).collect(); assert_eq!(dirs, ["a_b", "a_b~2", "a_b~3", "c"]); } + #[test] + fn a_snapshot_named_like_another_snapshots_page_gets_its_own_directory() { + // Page 2 of the two-page `x`, then a one-page snapshot named `x/page-2`. + let mut layout = Layout::default(); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2"]); + assert_eq!(layout.take("x/page-2", true), "x/page-2~2"); + + // The other way round: the one-page `x/page-2` first, then the two-page `x`. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/page-2", true), "x/page-2"); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2~2"]); + } + + #[test] + fn a_snapshot_named_like_another_snapshots_file_gets_its_own_directory() { + // `x`'s head image is `x/head.png`: a snapshot named `x/head.png` can't be a directory there. + let mut layout = Layout::default(); + assert_eq!(layout.take("x", true), "x"); + assert_eq!(layout.take("x/head.png", true), "x/head.png~2"); + // And the other way round: once `x/head.png` is a directory, `x` can't hold a file of that name. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/head.png", true), "x/head.png"); + assert_eq!(layout.take("x", true), "x~2"); + // Directories that only share a parent are fine. + assert_eq!(layout.take("x/other", true), "x/other"); + } + #[test] fn a_filter_fills_its_defaults_and_refuses_what_it_does_not_know() { let f = Filter::default().normalized().unwrap(); diff --git a/app/src/domain/retention.rs b/app/src/domain/retention.rs index 395e6e52..d700956b 100644 --- a/app/src/domain/retention.rs +++ b/app/src/domain/retention.rs @@ -234,17 +234,25 @@ async fn candidates(days: i32) -> laravel::Result { /// - a render goes only once no snapshot names it, and its snapshots' links go only when they're over a day old; /// - a text goes only while it's over a day old (storing it again renews that) and no render reused in the last day /// names it; -/// - a blob is marked `deleting` (rows locked, skipping any a registration holds), then its object is deleted and the -/// row with it, each under the row's lock and only while it's still marked. Registering the hash again clears the -/// mark and has the file uploaded again ([`super::blobs::register`]), so a build reusing the file keeps it. +/// - an overlay goes only when its diff wasn't reused in the last day; +/// - a blob is marked `deleting` (rows locked, skipping any a registration holds) unless something registered it in the +/// last day or anything names it, then its object is deleted and the row with it, under the row's lock, only while +/// it's still marked and still unnamed. Registering the hash clears the mark and has the file uploaded again +/// ([`super::blobs::register`]), so a build reusing the file keeps it. Marks left over (a skipped row, a store that +/// refused) are cleared at the end of the batch, and any from a run that stopped are cleared at the start: no mark +/// outlives its run. /// /// With `dry_run`, only count. /// /// # Errors -/// On a database error. A failed store delete is counted in the report, not returned: the blob stays marked, so it -/// counts as not uploaded until it's registered again or the next prune deletes it. +/// On a database error. A failed store delete is counted in the report, not returned: the blob stays, and the next +/// prune tries again. pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> laravel::Result { let grace = TEXT_GRACE_HOURS; + // Marks a run that stopped part way left behind (prunes never overlap: the schedule runs one at a time). + if !dry_run { + db::query!("UPDATE blobs SET deleting = false WHERE deleting").update().await?; + } let found = candidates(days).await?; let mut report = Report::default(); if dry_run { @@ -295,11 +303,18 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav ) .update() .await?; - db::query!("UPDATE diffs SET overlay_blob = NULL WHERE overlay_blob IN ({...shas})").update().await?; + db::query!( + "UPDATE diffs SET overlay_blob = NULL \ + WHERE overlay_blob IN ({...shas}) AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace}))" + ) + .update() + .await?; let rows = db::query!( "UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ( \ SELECT b.sha256 FROM blobs b WHERE b.sha256 IN ({...shas}) \ + AND b.updated_at < now() - make_interval(hours => {grace}) \ AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.source_blob = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM diffs d WHERE d.overlay_blob = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM renders r WHERE r.source_blob = b.sha256) \ AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ WHERE r.used_at >= now() - make_interval(hours => {grace}) AND pg->>'image' = b.sha256) \ @@ -314,8 +329,8 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav .collect()) }) .await?; - for (sha256, size) in marked { - match delete_marked(store, &sha256).await? { + for (sha256, size) in &marked { + match delete_marked(store, sha256).await? { Deleted::Yes => { report.blobs += 1; report.bytes += size; @@ -324,6 +339,13 @@ pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> larav Deleted::StoreFailed => report.store_errors += 1, } } + // No mark outlives its run: what wasn't deleted (named again, locked by a registration, or the store refused) + // is a blob like any other again. Waits for a registration holding a row. + let left: Vec = marked.into_iter().map(|(s, _)| s).collect(); + for chunk in left.chunks(BATCH) { + let chunk = chunk.to_vec(); + db::query!("UPDATE blobs SET deleting = false WHERE sha256 IN ({...chunk}) AND deleting").update().await?; + } } Ok(report) } @@ -348,6 +370,20 @@ async fn delete_marked(store: Option<&BlobStore>, sha256: &str) -> laravel::Resu if locked.is_none() { return Ok(Deleted::KeptForNow); } + // Named since it was marked (a snapshot or diff committed after a registration that found it uploaded, or a page + // image of a render reused since): it stays. + let named: Option = db::query!( + "SELECT 1::BIGINT WHERE EXISTS (SELECT 1 FROM snapshots WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM renders WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM diffs WHERE overlay_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ + WHERE r.used_at >= now() - interval '24 hours' AND pg->>'image' = {sha256})" + ) + .scalar() + .await?; + if named.is_some() { + return Ok(Deleted::KeptForNow); + } if let Some(store) = store && let Err(e) = store.delete(sha256).await { diff --git a/app/src/http/renderer.rs b/app/src/http/renderer.rs index 25439664..cf68e3df 100644 --- a/app/src/http/renderer.rs +++ b/app/src/http/renderer.rs @@ -177,8 +177,13 @@ pub async fn uploads(Params(id): Params, headers: HeaderMap, body: axum::bo let blob = crate::domain::blobs::register(&f.sha256, f.size, &f.content_type).await?; if crate::domain::blobs::is_uploaded(&blob) { // Already stored (perhaps another tenant's): the renderer shows it drew the same PNG by uploading the - // bytes to a key of this render's own, checked when it completes. - urls.insert(f.sha256.clone(), store.upload_url_for_key(&renders::proof_key(id, &f.sha256)).into()); + // bytes to a key of this render's own, checked when it completes. The URL takes exactly the declared + // size. + let size = u64::try_from(f.size).unwrap_or_default(); + urls.insert( + f.sha256.clone(), + store.upload_url_for_key(&renders::proof_key(id, &f.sha256), size).into(), + ); kinds.insert(f.sha256.clone(), "proof".into()); } else { urls.insert(f.sha256.clone(), store.upload_url(&f.sha256)?.into()); diff --git a/app/src/models/diffs.rs b/app/src/models/diffs.rs index 784795b5..0643fe17 100644 --- a/app/src/models/diffs.rs +++ b/app/src/models/diffs.rs @@ -16,4 +16,6 @@ pub struct Diff { pub overlay_blob: Option, pub created_at: Timestamp, pub updated_at: Timestamp, + /// When a comparison last reused it (retention leaves its overlay alone for a day after). + pub used_at: Option, } diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs index a65c87b6..a5c3eb13 100644 --- a/app/src/storage/blobs.rs +++ b/app/src/storage/blobs.rs @@ -163,10 +163,14 @@ impl BlobStore { Ok((!too_big && hex::encode(hasher.finalize()) == sha256).then_some(read)) } - /// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes. + /// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes. The + /// size is part of the signature (`Content-Length`), so the URL takes exactly that many bytes and nothing larger. #[must_use] - pub fn upload_url_for_key(&self, key: &str) -> String { - self.public_bucket.put_object(Some(&self.credentials), key).sign(UPLOAD_TTL).to_string() + pub fn upload_url_for_key(&self, key: &str, size: u64) -> String { + let length = size.to_string(); + let mut action = self.public_bucket.put_object(Some(&self.credentials), key); + action.headers_mut().insert("content-length", length.as_str()); + action.sign(UPLOAD_TTL).to_string() } /// Store bytes under their SHA-256 and return it. diff --git a/app/tests/renderer.rs b/app/tests/renderer.rs index a9d39513..ac7560ef 100644 --- a/app/tests/renderer.rs +++ b/app/tests/renderer.rs @@ -286,9 +286,19 @@ async fn completion_checked(app: Application) -> laravel::Result<()> { r.assert_ok(); assert_eq!(r.json()["state"], "failed"); - // Drawn for real (the same PNG, uploaded to the proof key): done. + // Drawn for real (the same PNG, uploaded to the proof key): done. The proof URL takes exactly the declared size. let (render_id, claim_token) = fresh().await; let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await; + let mut larger = theirs.clone(); + larger.extend_from_slice(&[0; 1024]); + let refused_upload = reqwest::Client::new() + .put(urls[&their_sha].as_str().unwrap()) + .header("content-type", "image/png") + .body(larger) + .send() + .await + .unwrap(); + assert!(!refused_upload.status().is_success(), "a larger body is refused: {}", refused_upload.status()); put(urls[&their_sha].as_str().unwrap(), theirs.clone(), "image/png").await; let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; assert_eq!(r.json()["state"], "done", "{}", r.text()); diff --git a/app/tests/retention.rs b/app/tests/retention.rs index 1bc9202a..df9f962b 100644 --- a/app/tests/retention.rs +++ b/app/tests/retention.rs @@ -74,7 +74,7 @@ async fn age(build: &Build) -> laravel::Result<()> { .update() .await?; db::query!( - "UPDATE blobs SET created_at = now() - interval '200 days' \ + "UPDATE blobs SET created_at = now() - interval '200 days', updated_at = now() - interval '200 days' \ WHERE sha256 IN (SELECT source_blob FROM snapshots WHERE build_id = {id})" ) .update() @@ -261,8 +261,9 @@ async fn registered_while_marked(app: Application) -> laravel::Result<()> { async fn a_prune_deletes_in_batches(_app: Application) -> laravel::Result<()> { let n = i64::try_from(retention::BATCH).unwrap() + 5; db::query!( - "INSERT INTO blobs (sha256, size, content_type, created_at) \ - SELECT encode(sha256(i::text::bytea), 'hex'), 1, 'image/png', now() - interval '200 days' \ + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + SELECT encode(sha256(i::text::bytea), 'hex'), 1, 'image/png', now() - interval '200 days', \ + now() - interval '200 days' \ FROM generate_series(1, {n}) i" ) .insert() @@ -275,3 +276,70 @@ async fn a_prune_deletes_in_batches(_app: Application) -> laravel::Result<()> { assert_eq!(left, Some(0)); Ok(()) } + +/// An old blob, unnamed by any kept build: `n` picks its hash. +async fn old_blob(n: u32) -> laravel::Result { + let sha = visualci_core::sha256_hex(format!("old blob {n}").as_bytes()); + db::query!( + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + VALUES ({sha}, 1, 'image/png', now() - interval '200 days', now() - interval '200 days')" + ) + .insert() + .await?; + Ok(sha) +} + +/// A cached diff a comparison reused in the last day keeps its overlay (the build reusing it isn't in the keep sets); +/// one nobody reused loses it. +#[laravel::test] +async fn a_recently_reused_diff_keeps_its_overlay(_app: Application) -> laravel::Result<()> { + let (used, unused) = (old_blob(1).await?, old_blob(2).await?); + for (n, overlay, used_at) in [(1, &used, "now()"), (2, &unused, "NULL")] { + let (base, head) = (format!("base{n}"), format!("head{n}")); + let recent = used_at == "now()"; + db::query!( + "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ + result, overlay_blob, used_at) \ + VALUES ({base}, {head}, 'k', 1, 0.1, false, '{{}}', {overlay}, CASE WHEN {recent} THEN now() END)" + ) + .insert() + .await?; + } + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let overlays: Vec> = db::query!("SELECT overlay_blob FROM diffs ORDER BY base_image") + .select() + .await? + .iter() + .map(|r| r.try_get::>("overlay_blob").unwrap()) + .collect(); + assert_eq!(overlays, [Some(used.clone()), None]); + assert!(Blob::query().filter(Blob::sha256.eq(used)).first().await?.is_some(), "the reused overlay stays"); + assert!(Blob::query().filter(Blob::sha256.eq(unused)).first().await?.is_none(), "the other goes"); + Ok(()) +} + +/// No mark outlives its run: a mark a stopped run left behind is cleared, and so is one on a blob that turns out to be +/// kept; a blob registered in the last day isn't marked at all. +#[laravel::test] +async fn no_deleting_mark_outlives_its_prune(app: Application) -> laravel::Result<()> { + Box::pin(no_mark_outlives(app)).await +} + +async fn no_mark_outlives(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + // A kept build's blob, marked by a run that stopped. + let kept = build(&app, &token, "kept", [7, 7, 7]).await; + let kept_sha = blob_of(&kept).await.unwrap().sha256; + db::query!("UPDATE blobs SET deleting = true WHERE sha256 = {kept_sha}").update().await?; + // An old blob a client registered just now (the snapshot naming it not yet committed). + let registered = old_blob(3).await?; + app::domain::blobs::register(®istered, 1, "image/png").await?; + + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let marked: Option = db::query!("SELECT COUNT(*) FROM blobs WHERE deleting").scalar().await?; + assert_eq!(marked, Some(0), "no mark left"); + assert!(blob_of(&kept).await.is_some_and(|b| b.uploaded_at.is_some()), "the kept blob is still uploaded"); + assert!(Blob::query().filter(Blob::sha256.eq(registered)).first().await?.is_some(), "registered just now: kept"); + Ok(()) +}