diff --git a/app/database/migrations/2026_12_03_000000_blob_pdf_fingerprints.rs b/app/database/migrations/2026_12_03_000000_blob_pdf_fingerprints.rs new file mode 100644 index 00000000..ee5d1be4 --- /dev/null +++ b/app/database/migrations/2026_12_03_000000_blob_pdf_fingerprints.rs @@ -0,0 +1,9 @@ +//! A PDF blob's fingerprint (sc-8999), as the renderer computes it from the file in its sandbox: a client may send only +//! a file's SHA-256, and a later run that sends the same file is matched by its hash with no upload. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query("ALTER TABLE blobs ADD COLUMN pdf_fingerprint text").unprepared().await?; + Ok(()) +} diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index ea784c48..0ed736b9 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -465,6 +465,7 @@ pub async fn approved_elsewhere(build_id: i64) -> laravel::Result b.branch AND bl.snapshot_id IS NOT NULL \ JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \ + AND s.source_fingerprint <> '' \ JOIN builds b2 ON b2.id = bl.build_id \ LEFT JOIN users u ON u.id = bl.approved_by \ LEFT JOIN reviews r ON r.id = bl.review_id \ diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index 64b050e8..88a6a2c4 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -26,6 +26,52 @@ pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::R Blob::find_or_fail(sha256.to_string()).await } +/// A file a client is about to name: its hash, size and content type. +pub struct NewBlob { + pub sha256: String, + pub size: i64, + pub content_type: String, +} + +/// [`register`] for many files at once, in two statements whatever their number: the upsert, and one read of every row +/// back, by hash. A hash listed twice is registered once, with its first size and content type. +/// +/// # Errors +/// On a database error. +pub async fn register_many(files: &[NewBlob]) -> laravel::Result> { + let mut seen = std::collections::HashSet::new(); + let files: Vec<&NewBlob> = files.iter().filter(|f| seen.insert(f.sha256.as_str())).collect(); + let mut out = std::collections::HashMap::with_capacity(files.len()); + // Three bindings a file: well inside PostgreSQL's 65,535. + for chunk in files.chunks(10_000) { + db::query!( + "INSERT INTO blobs (sha256, size, content_type) VALUES {...chunk(sha256, size, content_type)} \ + 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?; + let shas: Vec = chunk.iter().map(|f| f.sha256.clone()).collect(); + out.extend( + Blob::query().filter(Blob::sha256.is_in(shas)).get().await?.into_iter().map(|b| (b.sha256.clone(), b)), + ); + } + Ok(out) +} + +/// The source fingerprint a snapshot of this kind gets from its blob, when the server knows it: an image's pixel +/// fingerprint, a PDF's fingerprint (the renderer's), and a text's SHA-256 (always known). +#[must_use] +pub fn known_fingerprint(kind: &str, blob: Option<&Blob>, sha256: &str) -> Option { + match kind { + "text" => Some(sha256.to_string()), + "image" => blob.and_then(|b| b.pixel_fingerprint.clone()), + "document" => blob.and_then(|b| b.pdf_fingerprint.clone()), + _ => None, + } +} + #[must_use] pub fn is_uploaded(blob: &Blob) -> bool { blob.uploaded_at.is_some() && !blob.deleting @@ -44,18 +90,36 @@ pub async fn existing(shas: &[String]) -> laravel::Result laravel::Result> { + let mut rows = std::collections::HashMap::new(); + for chunk in hashes.chunks(10_000) { + rows.extend( + Blob::query() + .filter(Blob::sha256.is_in(chunk.to_vec())) + .get() + .await? + .into_iter() + .map(|b| (b.sha256.clone(), b)), + ); + } let mut missing = Vec::new(); + let mut checked = std::collections::HashSet::new(); for sha256 in hashes { - let Some(mut blob) = Blob::find(sha256.clone()).await? else { + let Some(blob) = rows.get_mut(sha256) else { missing.push(sha256.clone()); continue; }; - if is_uploaded(&blob) { + if is_uploaded(blob) { + continue; + } + // A hash listed twice is checked once. + if !checked.insert(sha256.clone()) { + missing.push(sha256.clone()); continue; } if let Some(size) = store.verify(sha256).await? { diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index 72595cc8..9ef421e7 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -426,7 +426,7 @@ impl Seeder<'_> { name: name.to_string(), platform: if kind == "image" { "chrome-linux".to_string() } else { String::new() }, kind: kind.to_string(), - fingerprint, + fingerprint: Some(fingerprint), sha256, size, content_type: content_type.to_string(), @@ -481,7 +481,7 @@ impl Seeder<'_> { let render = super::renders::find_or_queue(project.id, &fingerprint, &renderer_key, &blob.sha256).await?; if render.state != "done" { - super::renders::complete(render, &rendered).await?; + super::renders::complete(render, &rendered, None).await?; } params(name, "document", fingerprint, blob.sha256, blob.size, "application/pdf") } diff --git a/app/src/domain/groups.rs b/app/src/domain/groups.rs index cb982922..bfe8fdfd 100644 --- a/app/src/domain/groups.rs +++ b/app/src/domain/groups.rs @@ -44,6 +44,11 @@ pub struct CheckParams { /// The shard sending these groups, for a sharded build: groups must not span shards. #[serde(default)] pub shard: Option, + /// What an image's entry hashes (sc-8999): `fingerprint` (the default: its pixel fingerprint, which published CLIs + /// decode every image for), or `sha256` (its file's hash, so the client decodes nothing). Documents and texts hash + /// their fingerprints either way. + #[serde(default)] + pub image_hash: Option, } /// The server's answer. @@ -60,11 +65,23 @@ pub struct Checked { /// A stored snapshot as a manifest entry: the same fields, normalized the same way, as the CLI hashes. #[must_use] pub fn entry_of(s: &Snapshot) -> Entry { + entry_with(s, false) +} + +/// [`entry_of`], with an image's entry naming its file's SHA-256 instead of its pixel fingerprint when +/// `images_by_sha256` (a client that sent `image_hash: sha256`). +#[must_use] +pub fn entry_with(s: &Snapshot, images_by_sha256: bool) -> Entry { + let fingerprint = if images_by_sha256 && s.kind == "image" { + s.source_blob.clone().unwrap_or_default() + } else { + s.source_fingerprint.clone() + }; Entry { name: s.name.clone(), platform: s.platform.clone(), kind: s.kind.clone(), - fingerprint: s.source_fingerprint.clone(), + fingerprint, format: s.format.clone(), engine: s.engine.clone(), threshold: s.threshold, @@ -89,11 +106,20 @@ pub async fn check(build: &Build, project: &Project, params: &CheckParams) -> la if build.group_depth.is_some() && build.group_depth != params.group_depth { return Ok(Err("every shard must group names the same way (group_depth)".into())); } + let images_by_sha256 = match params.image_hash.as_deref() { + None | Some("fingerprint") => false, + Some("sha256") => true, + Some(other) => return Ok(Err(format!("image_hash must be fingerprint or sha256, not {other:?}"))), + }; let grouping = grouping(params.group_depth); // The baseline's side, from the server's own rows: each snapshot's approved version. let (resolved, anchor) = super::baselines::resolve(build, project).await?; - let entries: Vec = - resolved.values().map(|r| &r.snapshot).filter(|s| s.platform != CONFIG_PLATFORM).map(entry_of).collect(); + let entries: Vec = resolved + .values() + .map(|r| &r.snapshot) + .filter(|s| s.platform != CONFIG_PLATFORM) + .map(|s| entry_with(s, images_by_sha256)) + .collect(); let baseline_groups: HashMap = manifest::groups(&entries, grouping).into_iter().map(|g| (g.key, g.hash)).collect(); let manifest_matched = !entries.is_empty() diff --git a/app/src/domain/inherited.rs b/app/src/domain/inherited.rs index 7be92c55..7ed52d08 100644 --- a/app/src/domain/inherited.rs +++ b/app/src/domain/inherited.rs @@ -68,7 +68,9 @@ pub async fn of_build(build: &Build, project: &Project) -> laravel::Result laravel::Result { Ok(build) } +/// Images sent without a fingerprint (sc-8999) take their blob's pixel fingerprint before anything compares them, +/// computed from the file (and kept on the blob, [`super::blobs::image_info`]) where the blob has none yet: a new file, +/// or a re-encoded one with the same pixels, which stays its own blob under its own hash. Each file is decoded once, +/// outside any transaction, and the snapshots are updated in one statement. A file that isn't an image fails its +/// snapshots, as comparing it would. +/// +/// # Errors +/// On a database or storage error. +async fn fill_image_fingerprints( + snapshots: &mut [Snapshot], + missing: &[String], + store: &BlobStore, +) -> laravel::Result<()> { + let needs = |s: &Snapshot| { + s.kind == "image" + && s.source_fingerprint.is_empty() + && !matches!(s.state.as_str(), "failed" | "removed") + && s.source_blob.as_ref().is_some_and(|b| !missing.contains(b)) + }; + let mut shas: Vec = snapshots.iter().filter(|s| needs(s)).filter_map(|s| s.source_blob.clone()).collect(); + if shas.is_empty() { + return Ok(()); + } + shas.sort_unstable(); + shas.dedup(); + let mut found: HashMap> = HashMap::new(); + for chunk in shas.chunks(10_000) { + for blob in crate::models::Blob::query().filter(crate::models::Blob::sha256.is_in(chunk.to_vec())).get().await? + { + let sha = blob.sha256.clone(); + let fingerprint = match blob.pixel_fingerprint.clone() { + Some(fp) => Ok(fp), + None => super::blobs::image_info(blob, store).await.map(|(fp, _, _)| fp).map_err(|e| e.to_string()), + }; + found.insert(sha, fingerprint); + } + } + let mut rows: Vec<(i64, String)> = Vec::new(); + for snapshot in snapshots.iter_mut().filter(|s| needs(s)) { + match snapshot.source_blob.as_ref().and_then(|b| found.get(b)) { + Some(Ok(fp)) => { + snapshot.source_fingerprint.clone_from(fp); + rows.push((snapshot.id, fp.clone())); + } + Some(Err(e)) => mark_failed(snapshot, &format!("the image couldn't be read: {e}")).await?, + None => mark_failed(snapshot, "the file was never uploaded").await?, + } + } + for chunk in rows.chunks(10_000) { + db::query!( + "UPDATE snapshots s SET source_fingerprint = v.fingerprint, updated_at = now() \ + FROM (VALUES {...chunk(0, 1)}) AS v (id, fingerprint) WHERE s.id = v.id" + ) + .update() + .await?; + } + Ok(()) +} + +/// Queue (or find) a document's render. A PDF sent without a fingerprint (sc-8999) takes its blob's, from an earlier +/// render of the file; a file never drawn before is drawn under its own hash (the same bytes always draw the same), and +/// the renderer reports its fingerprint ([`super::renders::complete`]). +/// +/// # Errors +/// On a database error. +async fn queue_render(project_id: i64, renderer: &str, snapshot: &mut Snapshot) -> laravel::Result { + let blob = snapshot.source_blob.clone().unwrap_or_default(); + if snapshot.source_fingerprint.is_empty() + && let Some(source_fingerprint) = crate::models::Blob::find(blob.clone()).await?.and_then(|b| b.pdf_fingerprint) + { + update!(snapshot { source_fingerprint }).await?; + } + let key = if snapshot.source_fingerprint.is_empty() { blob.clone() } else { snapshot.source_fingerprint.clone() }; + super::renders::find_or_queue(project_id, &key, renderer, &blob).await +} + +/// Once a document's render is done: a PDF sent without a fingerprint takes the one the renderer reported for its +/// file, or the file's hash when it reported none (an older renderer), as the CLI fingerprints a PDF it can't parse. +/// +/// # Errors +/// On a database error. +async fn fill_document_fingerprint(snapshot: &mut Snapshot) -> laravel::Result<()> { + if !snapshot.source_fingerprint.is_empty() { + return Ok(()); + } + let blob = snapshot.source_blob.clone().unwrap_or_default(); + let reported = crate::models::Blob::find(blob.clone()).await?.and_then(|b| b.pdf_fingerprint); + let source_fingerprint = reported.unwrap_or(blob); + update!(snapshot { source_fingerprint }).await +} + /// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done, /// compare and conclude. Returns whether the build concluded (false while renders are outstanding). The caller holds /// [`exclusive`]; this runs outside any transaction, so storage requests, decoding and diffing never hold a database @@ -336,6 +427,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> .filter_map(|s| s.source_blob.clone()) .collect(); let missing = super::blobs::confirm_uploads(store, &needed).await?; + fill_image_fingerprints(&mut snapshots, &missing, store).await?; let mut waiting = false; for snapshot in &mut snapshots { @@ -349,16 +441,14 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> mark_failed(snapshot, "the PDF was never uploaded").await?; continue; } - let blob = snapshot.source_blob.clone().unwrap_or_default(); let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); - let render = - super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render = queue_render(project.id, &key, snapshot).await?; let render_id = Some(render.id); update!(snapshot { render_id }).await?; } let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; match render.state.as_str() { - "done" => {} + "done" => fill_document_fingerprint(snapshot).await?, "failed" => { let error = format!("rendering failed: {}", render.error.unwrap_or_default()); mark_failed(snapshot, &error).await?; @@ -896,7 +986,7 @@ pub async fn compare_now( } } let settings = BuildSettings::new(&project, build); - let snapshots: Vec = super::snapshots::of_build(build.id) + let mut snapshots: Vec = super::snapshots::of_build(build.id) .await? .into_iter() .filter(|s| wanted.iter().any(|(n, p)| *n == s.name && *p == s.platform)) @@ -907,6 +997,7 @@ pub async fn compare_now( let needed: Vec = snapshots.iter().filter(|s| s.render_id.is_none()).filter_map(|s| s.source_blob.clone()).collect(); let missing = super::blobs::confirm_uploads(store, &needed).await?; + fill_image_fingerprints(&mut snapshots, &missing, store).await?; let (resolved, _) = baselines::resolve(build, &project).await?; let mut out = Vec::with_capacity(snapshots.len()); for mut snapshot in snapshots { @@ -916,16 +1007,14 @@ pub async fn compare_now( } if snapshot.kind == "document" { if snapshot.render_id.is_none() { - let blob = snapshot.source_blob.clone().unwrap_or_default(); let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); - let render = - super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render = queue_render(project.id, &key, &mut snapshot).await?; let render_id = Some(render.id); update!(snapshot { render_id }).await?; } let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; match render.state.as_str() { - "done" => {} + "done" => fill_document_fingerprint(&mut snapshot).await?, "failed" => { let error = format!("rendering failed: {}", render.error.unwrap_or_default()); mark_failed(&mut snapshot, &error).await?; diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs index 40e0aa42..8f08558a 100644 --- a/app/src/domain/renders.rs +++ b/app/src/domain/renders.rs @@ -102,11 +102,70 @@ pub async fn mark_used(render_id: i64) -> laravel::Result<()> { Ok(()) } -/// Record a render's pages: their texts go to `texts`, and the pages keep the hashes. +/// [`mark_used`] for many renders, in one statement. /// /// # Errors /// On a database error. -pub async fn complete(mut render: Render, pages: &[RenderPage]) -> laravel::Result { +pub async fn mark_all_used(ids: &[i64]) -> laravel::Result<()> { + for chunk in ids.chunks(10_000) { + db::query!( + "UPDATE renders SET used_at = now() \ + WHERE id IN ({...chunk}) AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + } + Ok(()) +} + +/// The PDF's fingerprint, as the renderer computed it from the file it drew (sc-8999): kept on the source blob, where +/// it has none yet, so a later run naming the file only by its hash is matched with no upload. A render queued under +/// the file's hash (a snapshot sent without a fingerprint, [`super::processing`]) moves to its fingerprint, unless the +/// project already has a render under it, so later runs that send the fingerprint find it. +/// +/// # Errors +/// On a database error. +async fn record_document_fingerprint(render: &mut Render, fingerprint: &str) -> laravel::Result<()> { + if !is_hex_sha256(fingerprint) { + return Ok(()); + } + let (id, blob) = (render.id, render.source_blob.as_str()); + db::query!("UPDATE blobs SET pdf_fingerprint = {fingerprint} WHERE sha256 = {blob} AND pdf_fingerprint IS NULL") + .update() + .await?; + if render.source_fingerprint != render.source_blob || render.source_fingerprint == fingerprint { + return Ok(()); + } + let moved = db::query!( + "UPDATE renders SET source_fingerprint = {fingerprint}, updated_at = now() WHERE id = {id} \ + AND NOT EXISTS (SELECT 1 FROM renders o WHERE o.project_id IS NOT DISTINCT FROM renders.project_id \ + AND o.source_fingerprint = {fingerprint} AND o.renderer = renders.renderer)" + ) + .update() + .await; + match moved { + Ok(n) if n > 0 => render.source_fingerprint = fingerprint.to_string(), + Ok(_) => {} + // Another render took the fingerprint meanwhile: this one stays under the file's hash. + Err(e) if db::is_unique_violation(&e) => {} + Err(e) => return Err(e), + } + Ok(()) +} + +/// Record a render's pages: their texts go to `texts`, and the pages keep the hashes. With the PDF's fingerprint, when +/// the renderer reports it ([`record_document_fingerprint`]). +/// +/// # Errors +/// On a database error. +pub async fn complete( + mut render: Render, + pages: &[RenderPage], + document_fingerprint: Option<&str>, +) -> laravel::Result { + if let Some(fingerprint) = document_fingerprint { + record_document_fingerprint(&mut render, fingerprint).await?; + } let bodies: Vec<&str> = pages.iter().map(|p| p.text.as_str()).collect(); let shas = crate::storage::texts::store(&bodies).await?; // Each page image's size, as the renderer measured it, where its blob doesn't have one yet: get_snapshot and the diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index 6265e571..55bea9fd 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -1,10 +1,12 @@ //! Snapshots: one named item in a build (a document, an image or a text), and how it compares with its baseline. +use std::collections::{HashMap, HashSet}; + use laravel::db; use serde::Deserialize; use visualci_core::snapshot_text::{Format, IgnoreRules}; -use crate::models::{Build, Render, Snapshot}; +use crate::models::{Build, Snapshot}; pub const KINDS: &[&str] = &["document", "image", "text"]; @@ -24,8 +26,10 @@ pub struct SnapshotParams { #[serde(default)] pub platform: String, pub kind: String, - /// Documents: the PDF fingerprint. Images: the pixel fingerprint. Text: the SHA-256 of the text. - pub fingerprint: String, + /// Documents: the PDF fingerprint. Images: the pixel fingerprint. Text: the SHA-256 of the text. Optional + /// (sc-8999): without it, the server uses the one it computed for the file, or computes it once the file arrives. + #[serde(default)] + pub fingerprint: Option, /// SHA-256 of the file's bytes. pub sha256: String, #[serde(deserialize_with = "super::lenient::number")] @@ -84,7 +88,7 @@ impl SnapshotParams { crate::storage::blobs::MAX_BLOB_BYTES )); } - if !hex64(&self.sha256) || !hex64(&self.fingerprint) { + if !hex64(&self.sha256) || self.fingerprint.as_deref().is_some_and(|f| !hex64(f)) { return Err(format!("{}: sha256 and fingerprint must be lowercase hex SHA-256 digests", self.name)); } if let Some(e) = &self.engine @@ -122,30 +126,73 @@ pub struct Registration { pub needs_upload: bool, } -/// A usable render of this source with these settings, if one exists: done, queued or rendering. +/// A snapshot [`register_all`] recorded. +pub struct Registered { + pub name: String, + pub platform: String, + /// Upload the file: its blob isn't stored yet and no render of it exists. + pub needs_upload: bool, +} + +/// The usable renders (done, queued or rendering) among these (source fingerprint, renderer) pairs of a project, in +/// one query, each noted as reused. /// /// # Errors /// On a database error. -pub async fn usable_render(project_id: i64, fingerprint: &str, renderer: &str) -> laravel::Result> { - let found = Render::query() - .filter( - Render::project_id.eq(project_id) - & Render::source_fingerprint.eq(fingerprint) - & Render::renderer.eq(renderer) - & Render::state.ne("failed"), +pub async fn usable_renders( + project_id: i64, + wanted: &[(String, String)], +) -> laravel::Result> { + let mut out = HashMap::new(); + for chunk in wanted.chunks(10_000) { + let rows = db::query!( + "SELECT r.id, r.source_fingerprint, r.renderer FROM renders r \ + JOIN (VALUES {...chunk(0, 1)}) AS w (fingerprint, renderer) \ + ON r.source_fingerprint = w.fingerprint AND r.renderer = w.renderer \ + WHERE r.project_id = {project_id} AND r.state <> 'failed'" ) - .first() + .select() .await?; - // Reused: retention leaves its images and texts alone while this build is new. - if let Some(r) = &found { - super::renders::mark_used(r.id).await?; + for r in rows { + out.insert((r.try_get("source_fingerprint")?, r.try_get("renderer")?), r.try_get::("id")?); + } } - Ok(found) + // Reused: retention leaves their images and texts alone while this build is new. + let ids: Vec = out.values().copied().collect(); + super::renders::mark_all_used(&ids).await?; + Ok(out) } -/// Record a snapshot in a build (replacing one with the same name and platform), and say whether its file must be -/// uploaded. The same name twice with the same file is a retry and fine; other content is a naming bug in the suite -/// (two jobs or shards sending one name), refused with [`ALREADY_UPLOADED`] in the message. +fn conflict(params: &SnapshotParams) -> String { + let platform = if params.platform.is_empty() { String::new() } else { format!(" ({})", params.platform) }; + format!( + "{}{platform} was {ALREADY_UPLOADED} with other content: snapshot names must be unique across a build's jobs \ + and shards", + params.name + ) +} + +/// One snapshot row as [`register_all`] writes it. +struct Row<'a> { + pid: laravel::str::Uuid, + build_id: i64, + group_key: String, + name: &'a str, + platform: &'a str, + kind: &'a str, + format: Option, + fingerprint: String, + sha256: &'a str, + render_id: Option, + engine: &'a Option, + threshold: Option, + aa: Option, + meta: serde_json::Value, + ignore_rules: serde_json::Value, + environment: String, +} + +/// Record a snapshot in a build: [`register_all`] for one, with its row. /// /// # Errors /// `Ok(Err(message))` for a conflict; `Err` on a database error. @@ -155,63 +202,154 @@ pub async fn register( renderer_version: &str, params: &SnapshotParams, ) -> laravel::Result> { - let renderer_key = settings.renderer_key(params.engine.as_deref(), renderer_version); - let render = if params.kind == "document" { - usable_render(build.project_id, ¶ms.fingerprint, &renderer_key).await? - } else { - None + let registered = match register_all(build, settings, renderer_version, std::slice::from_ref(params)).await? { + Ok(r) => r, + Err(message) => return Ok(Err(message)), }; - let blob = super::blobs::register(¶ms.sha256, params.size, ¶ms.content_type).await?; - let needs_upload = render.is_none() && !super::blobs::is_uploaded(&blob); + let needs_upload = registered.first().is_some_and(|r| r.needs_upload); + let snapshot = Snapshot::query() + .filter( + Snapshot::build_id.eq(build.id) + & Snapshot::name.eq(params.name.as_str()) + & Snapshot::platform.eq(params.platform.as_str()), + ) + .first() + .await? + .ok_or_else(|| laravel::Error::msg("the registered snapshot wasn't saved"))?; + Ok(Ok(Registration { snapshot, needs_upload })) +} - let pid = laravel::str::uuid7(); - let build_id = build.id; - let group_key = super::groups::grouping(build.group_depth).key(¶ms.name); - let format = params.text_format().map(|f| f.as_str().to_string()); - let render_id = render.as_ref().map(|r| r.id); - let meta = if params.meta.is_null() { serde_json::json!({}) } else { params.meta.clone() }; - let ignore_rules = serde_json::to_value(params.ignore.clone().unwrap_or_default()).unwrap_or_default(); - let environment = super::environments::for_kind(¶ms.kind, &build.environment); - let (name, platform, kind, fingerprint, sha256, engine, threshold, aa) = ( - ¶ms.name, - ¶ms.platform, - ¶ms.kind, - ¶ms.fingerprint, - ¶ms.sha256, - ¶ms.engine, - params.threshold, - params.ignore_anti_aliasing, - ); - // One statement, so two shards racing with different files can't both win: the update applies only over a row - // carried forward or holding the same file (a retried job), and no row back means another file already has the name. - let saved: Option = db::query!( - "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \ - render_id, engine, threshold, ignore_anti_aliasing, meta, ignore_rules, environment, state, \ - matched_environment, baseline_id) \ - VALUES ({pid}, {build_id}, {group_key}, {name}, {platform}, {kind}, {format}, {fingerprint}, {sha256}, \ - {render_id}, {engine}, {threshold}, {aa}, {meta}, {ignore_rules}, {environment}, 'pending', NULL, NULL) \ - ON CONFLICT (build_id, name, platform) DO UPDATE SET kind = EXCLUDED.kind, format = EXCLUDED.format, \ - source_fingerprint = EXCLUDED.source_fingerprint, source_blob = EXCLUDED.source_blob, \ - render_id = EXCLUDED.render_id, engine = EXCLUDED.engine, threshold = EXCLUDED.threshold, \ - ignore_anti_aliasing = EXCLUDED.ignore_anti_aliasing, meta = EXCLUDED.meta, \ - ignore_rules = EXCLUDED.ignore_rules, environment = EXCLUDED.environment, state = EXCLUDED.state, \ - matched_environment = NULL, baseline_id = NULL, group_key = EXCLUDED.group_key, carried_forward = false, \ - base_snapshot_id = NULL, review = NULL, error = NULL, updated_at = now() \ - WHERE snapshots.carried_forward OR snapshots.source_blob = EXCLUDED.source_blob \ - RETURNING id" - ) - .scalar() - .await?; - let Some(id) = saved else { - let platform = if params.platform.is_empty() { String::new() } else { format!(" ({})", params.platform) }; - return Ok(Err(format!( - "{}{platform} was {ALREADY_UPLOADED} with other content: snapshot names must be unique across a build's \ - jobs and shards", - params.name - ))); +/// Record snapshots in a build (each replacing one with the same name and platform), and say for each, in the order +/// sent, whether its file must be uploaded. The same name twice with the same file is a retry and fine; other content +/// is a naming bug in the suite (two jobs or shards sending one name), refused with [`ALREADY_UPLOADED`] in the message. +/// +/// A snapshot sent without a fingerprint (sc-8999) takes the one its blob has: an image's pixel fingerprint, a PDF's +/// (from the renderer that drew it), a text's SHA-256. A blob the server hasn't fingerprinted yet leaves it empty, and +/// processing fills it in once the file has arrived ([`super::processing`]). +/// +/// The same few statements whatever the number of snapshots: the blobs' upsert and read, one query for the documents' +/// renders (and one noting those reused), and the snapshots' upsert. +/// +/// # Errors +/// `Ok(Err(message))` for a conflict; `Err` on a database error. +pub async fn register_all( + build: &Build, + settings: &super::build_settings::BuildSettings<'_>, + renderer_version: &str, + params: &[SnapshotParams], +) -> laravel::Result, String>> { + // A name sent twice in one request: once with the same file is a retry (the last one is written), with another + // file a conflict. + let mut last: HashMap<(&str, &str), usize> = HashMap::new(); + for (i, p) in params.iter().enumerate() { + if let Some(&j) = last.get(&(p.name.as_str(), p.platform.as_str())) + && params[j].sha256 != p.sha256 + { + return Ok(Err(conflict(p))); + } + last.insert((p.name.as_str(), p.platform.as_str()), i); + } + + let files: Vec = params + .iter() + .map(|p| super::blobs::NewBlob { sha256: p.sha256.clone(), size: p.size, content_type: p.content_type.clone() }) + .collect(); + let blobs = super::blobs::register_many(&files).await?; + let fingerprints: Vec = params + .iter() + .map(|p| { + p.fingerprint + .clone() + .or_else(|| super::blobs::known_fingerprint(&p.kind, blobs.get(&p.sha256), &p.sha256)) + .unwrap_or_default() + }) + .collect(); + let renderer_keys: Vec = + params.iter().map(|p| settings.renderer_key(p.engine.as_deref(), renderer_version)).collect(); + let mut wanted: Vec<(String, String)> = params + .iter() + .zip(&fingerprints) + .zip(&renderer_keys) + .filter(|((p, fp), _)| p.kind == "document" && !fp.is_empty()) + .map(|((_, fp), key)| (fp.clone(), key.clone())) + .collect(); + wanted.sort_unstable(); + wanted.dedup(); + let renders = usable_renders(build.project_id, &wanted).await?; + let render_of = |i: usize| -> Option { + (params[i].kind == "document" && !fingerprints[i].is_empty()) + .then(|| renders.get(&(fingerprints[i].clone(), renderer_keys[i].clone())).copied()) + .flatten() }; - let snapshot = Snapshot::find_or_fail(id).await?; - Ok(Ok(Registration { snapshot, needs_upload })) + + let grouping = super::groups::grouping(build.group_depth); + let mut order: Vec = last.values().copied().collect(); + order.sort_unstable(); + let rows: Vec> = order + .iter() + .map(|&i| { + let p = ¶ms[i]; + Row { + pid: laravel::str::uuid7(), + build_id: build.id, + group_key: grouping.key(&p.name), + name: &p.name, + platform: &p.platform, + kind: &p.kind, + format: p.text_format().map(|f| f.as_str().to_string()), + fingerprint: fingerprints[i].clone(), + sha256: &p.sha256, + render_id: render_of(i), + engine: &p.engine, + threshold: p.threshold, + aa: p.ignore_anti_aliasing, + meta: if p.meta.is_null() { serde_json::json!({}) } else { p.meta.clone() }, + ignore_rules: serde_json::to_value(p.ignore.clone().unwrap_or_default()).unwrap_or_default(), + environment: super::environments::for_kind(&p.kind, &build.environment), + } + }) + .collect(); + // One statement a chunk, so two shards racing with different files can't both win: the update applies only over a + // row carried forward or holding the same file (a retried job), and a row not returned means another file already + // has the name. + let mut saved: HashSet<(String, String)> = HashSet::with_capacity(rows.len()); + for chunk in rows.chunks(2_000) { + let returned = db::query!( + "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, \ + source_blob, render_id, engine, threshold, ignore_anti_aliasing, meta, ignore_rules, environment) \ + VALUES {...chunk(pid, build_id, group_key, name, platform, kind, format, fingerprint, sha256, render_id, \ + engine, threshold, aa, meta, ignore_rules, environment)} \ + ON CONFLICT (build_id, name, platform) DO UPDATE SET kind = EXCLUDED.kind, format = EXCLUDED.format, \ + source_fingerprint = EXCLUDED.source_fingerprint, source_blob = EXCLUDED.source_blob, \ + render_id = EXCLUDED.render_id, engine = EXCLUDED.engine, threshold = EXCLUDED.threshold, \ + ignore_anti_aliasing = EXCLUDED.ignore_anti_aliasing, meta = EXCLUDED.meta, \ + ignore_rules = EXCLUDED.ignore_rules, environment = EXCLUDED.environment, state = EXCLUDED.state, \ + matched_environment = NULL, baseline_id = NULL, group_key = EXCLUDED.group_key, carried_forward = false, \ + base_snapshot_id = NULL, review = NULL, error = NULL, updated_at = now() \ + WHERE snapshots.carried_forward OR snapshots.source_blob = EXCLUDED.source_blob \ + RETURNING name, platform" + ) + .select() + .await?; + for r in returned { + saved.insert((r.try_get("name")?, r.try_get("platform")?)); + } + } + if let Some(&i) = order.iter().find(|&&i| !saved.contains(&(params[i].name.clone(), params[i].platform.clone()))) { + return Ok(Err(conflict(¶ms[i]))); + } + Ok(Ok(params + .iter() + .map(|p| { + let i = last[&(p.name.as_str(), p.platform.as_str())]; + let uploaded = blobs.get(¶ms[i].sha256).is_some_and(super::blobs::is_uploaded); + Registered { + name: p.name.clone(), + platform: p.platform.clone(), + needs_upload: render_of(i).is_none() && !uploaded, + } + }) + .collect())) } /// Every snapshot of a build, its own and those it reads from earlier builds (`effective_snapshots`), by name and diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index ab0e40e8..09ebd0d1 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -185,7 +185,9 @@ struct SnapshotsResponse { snapshots: Vec, } -/// `POST /api/v1/builds/{pid}/snapshots`: register up to 1000 snapshots, with an upload URL for each new file. +/// `POST /api/v1/builds/{pid}/snapshots`: register up to 1000 snapshots, with an upload URL for each new file. Each +/// names its file's SHA-256, with its fingerprint or without it (sc-8999): published CLIs send it, and newer ones send +/// only the hash for images, which the server fingerprints itself. pub async fn add_snapshots( auth: Result, Params(pid): Params, @@ -207,19 +209,20 @@ pub async fn add_snapshots( } let settings = BuildSettings::new(&project, &build); let version = renderer_version(); - let mut snapshots = Vec::with_capacity(params.snapshots.len()); // Every snapshot is checked before any is written. for p in ¶ms.snapshots { p.validate().map_err(ApiError::bad_request)?; } - for p in ¶ms.snapshots { - let registration = crate::domain::snapshots::register(&build, &settings, &version, p) - .await? - .map_err(ApiError::conflict)?; + // All of them at once: the same few statements for 1 snapshot or 1000 (sc-8999). + let registered = crate::domain::snapshots::register_all(&build, &settings, &version, ¶ms.snapshots) + .await? + .map_err(ApiError::conflict)?; + let mut snapshots = Vec::with_capacity(registered.len()); + for (r, p) in registered.into_iter().zip(¶ms.snapshots) { snapshots.push(SnapshotUpload { - name: registration.snapshot.name.clone(), - platform: registration.snapshot.platform.clone(), - upload_url: if registration.needs_upload { Some(store.upload_url(&p.sha256)?) } else { None }, + upload_url: if r.needs_upload { Some(store.upload_url(&p.sha256)?) } else { None }, + name: r.name, + platform: r.platform, content_type: p.content_type.clone(), }); } diff --git a/app/src/http/renderer.rs b/app/src/http/renderer.rs index 14f575c7..af1b4abd 100644 --- a/app/src/http/renderer.rs +++ b/app/src/http/renderer.rs @@ -251,6 +251,9 @@ struct CompleteParams { #[serde(default)] pages: Vec, error: Option, + /// The PDF's fingerprint, as the renderer computed it from the file (sc-8999). Older renderers don't send it. + #[serde(default)] + document_fingerprint: Option, } /// `POST /internal/renderer/renders/{id}/complete`: the render's pages (their images uploaded first), or its error. @@ -284,7 +287,7 @@ pub async fn complete(Params(id): Params, headers: HeaderMap, body: axum::b } else if let Some(problem) = check_images(&store, &render, ¶ms.pages).await? { renders::fail(render, &problem).await? } else { - renders::complete(render, ¶ms.pages).await? + renders::complete(render, ¶ms.pages, params.document_fingerprint.as_deref()).await? }; renders::wake_waiting(&result).await?; Ok::<_, laravel::Error>(Ok(json!({ "state": result.state }))) diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 4eca5753..69487bd6 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -1908,7 +1908,7 @@ impl VisualCi { name: f.name.clone(), platform: f.platform.clone(), kind: (*kind).to_string(), - fingerprint: fingerprint.clone(), + fingerprint: Some(fingerprint.clone()), sha256: visualci_core::sha256_hex(bytes), size: i64::try_from(bytes.len()).unwrap_or(i64::MAX), content_type: (*content_type).to_string(), @@ -1933,12 +1933,12 @@ impl VisualCi { let version = renderer_version(); let store = BlobStore::current().await.map_err(internal)?; let mut out = Vec::new(); - for (p, (bytes, _, _, content_type)) in params.iter().zip(decoded) { - let r = refuse!(snaps::register(&build, &settings, &version, p)); + let registered = refuse!(snaps::register_all(&build, &settings, &version, ¶ms)); + for (r, (bytes, _, _, content_type)) in registered.into_iter().zip(decoded) { if r.needs_upload { domain::blobs::put(&store, bytes, content_type).await.map_err(internal)?; } - out.push(json!({ "name": r.snapshot.name, "platform": r.snapshot.platform, "stored": r.needs_upload })); + out.push(json!({ "name": r.name, "platform": r.platform, "stored": r.needs_upload })); } Ok(structured(json!({ "build": build.number, "snapshots": out }))) } diff --git a/app/src/models/blobs.rs b/app/src/models/blobs.rs index 1576d24e..e637a2bc 100644 --- a/app/src/models/blobs.rs +++ b/app/src/models/blobs.rs @@ -10,6 +10,8 @@ pub struct Blob { pub content_type: String, pub uploaded_at: Option, pub pixel_fingerprint: Option, + /// A PDF's fingerprint, reported by the renderer that drew it (`visualci_core::pdf`). + pub pdf_fingerprint: Option, pub width: Option, pub height: Option, pub created_at: Timestamp, diff --git a/app/tests/fingerprints.rs b/app/tests/fingerprints.rs new file mode 100644 index 00000000..11770984 --- /dev/null +++ b/app/tests/fingerprints.rs @@ -0,0 +1,449 @@ +//! Snapshots sent by their file's SHA-256 alone (sc-8999): the server answers known or unknown per file, computes an +//! image's pixel fingerprint and a PDF's fingerprint (from its renderer) for new files, keeps a re-encoded file as its +//! own blob with the same fingerprint, and registers known files in the same few queries however many there are. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use app::models::{Blob, Build, Render, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const RENDERER: &str = "Bearer renderer-test-token"; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// A 16x16 PNG of one colour, as RGBA. +fn png(rgb: [u8; 3]) -> Vec { + let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +/// The same pixels as [`png`], encoded differently (RGB, no alpha channel): other bytes, the same fingerprint, as after +/// a browser upgrade. +fn reencoded(rgb: [u8; 3]) -> Vec { + let image = image::RgbImage::from_pixel(16, 16, image::Rgb(rgb)); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +fn pixel_fingerprint(bytes: &[u8]) -> String { + visualci_core::image_hash::fingerprint_bytes(bytes).expect("an image") +} + +async fn put(url: &str, bytes: Vec, content_type: &str) { + let r = reqwest::Client::new().put(url).header("content-type", content_type).body(bytes).send().await.unwrap(); + assert!(r.status().is_success(), "uploading: {}", r.status()); +} + +async fn create(app: &Application, token: &str, commit: &str, parent: &str) -> String { + let created = app + .post("/api/v1/builds") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + created.assert_ok(); + created.json()["id"].as_str().unwrap().to_string() +} + +/// Register these snapshots (each with its bytes) and upload the files the server asks for. Returns the answer. +async fn register(app: &Application, token: &str, id: &str, snapshots: Vec<(Value, Vec)>) -> Value { + let (params, files): (Vec, Vec>) = snapshots.into_iter().unzip(); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "snapshots": params })) + .await; + registered.assert_ok(); + let answer = registered.json().clone(); + for (a, bytes) in answer["snapshots"].as_array().unwrap().iter().zip(files) { + if let Some(url) = a["upload_url"].as_str() { + put(url, bytes, a["content_type"].as_str().unwrap()).await; + } + } + answer +} + +async fn finalize(app: &Application, token: &str, id: &str) -> Value { + let done = + app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", format!("Bearer {token}")).await; + done.assert_ok(); + done.json().clone() +} + +/// An image snapshot as a CLI that doesn't decode sends it: no fingerprint. +fn image_by_sha(name: &str, bytes: &[u8]) -> (Value, Vec) { + let params = json!({ + "name": name, "kind": "image", "sha256": visualci_core::sha256_hex(bytes), "size": bytes.len(), + "content_type": "image/png" + }); + (params, bytes.to_vec()) +} + +fn upload_urls(answer: &Value) -> Vec { + answer["snapshots"].as_array().unwrap().iter().map(|s| s["upload_url"].is_string()).collect() +} + +async fn snapshot(number: i32, name: &str) -> laravel::Result { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + Ok(app::domain::snapshots::named_in_build(build.id, name).await?.into_iter().next().expect("the snapshot")) +} + +#[laravel::test] +async fn a_known_file_needs_no_upload_and_an_unknown_one_does(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let (known, unknown) = (png([1, 2, 3]), png([4, 5, 6])); + app::domain::blobs::put(&store, known.clone(), "image/png").await?; + let id = create(&app, &token, "c1", "c0").await; + let answer = register(&app, &token, &id, vec![image_by_sha("known", &known), image_by_sha("new", &unknown)]).await; + assert_eq!(upload_urls(&answer), vec![false, true], "{answer}"); + // Neither file has a fingerprint yet: processing computes them once the files have arrived. + assert_eq!(snapshot(1, "known").await?.source_fingerprint, ""); + let done = finalize(&app, &token, &id).await; + assert_eq!(done["state"], "completed", "{done}"); + for (name, bytes) in [("known", &known), ("new", &unknown)] { + let s = snapshot(1, name).await?; + assert_eq!((s.state.as_str(), s.source_fingerprint.clone()), ("added", pixel_fingerprint(bytes)), "{name}"); + let blob = Blob::find(visualci_core::sha256_hex(bytes)).await?.expect("the blob"); + assert_eq!(blob.pixel_fingerprint, Some(pixel_fingerprint(bytes)), "{name}: kept on the blob"); + } + Ok(()) +} + +#[laravel::test] +async fn the_server_fingerprints_a_new_image_and_a_later_run_matches_it_by_hash( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let red = png([255, 0, 0]); + + let id = create(&app, &token, "c1", "c0").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![image_by_sha("home", &red)]).await), vec![true]); + let first = finalize(&app, &token, &id).await; + assert_eq!(first["state"], "completed", "{first}"); + + // The same file again: no upload, its fingerprint is filled in at registration, and it compares unchanged. + let id = create(&app, &token, "c2", "c1").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![image_by_sha("home", &red)]).await), vec![false]); + assert_eq!(snapshot(2, "home").await?.source_fingerprint, pixel_fingerprint(&red)); + let second = finalize(&app, &token, &id).await; + assert_eq!((second["state"].as_str(), second["conclusion"].as_str()), (Some("completed"), Some("unchanged"))); + Ok(()) +} + +#[laravel::test] +async fn a_reencoded_image_is_its_own_blob_with_the_same_fingerprint(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let (before, after) = (png([0, 120, 200]), reencoded([0, 120, 200])); + assert_ne!(before, after, "the re-encoded file has other bytes"); + assert_eq!(pixel_fingerprint(&before), pixel_fingerprint(&after), "and the same pixels"); + + let id = create(&app, &token, "c1", "c0").await; + register(&app, &token, &id, vec![image_by_sha("home", &before)]).await; + finalize(&app, &token, &id).await; + + // The browser was upgraded: new bytes, uploaded and kept under their own hash, compared unchanged. + let id = create(&app, &token, "c2", "c1").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![image_by_sha("home", &after)]).await), vec![true]); + let second = finalize(&app, &token, &id).await; + assert_eq!((second["state"].as_str(), second["conclusion"].as_str()), (Some("completed"), Some("unchanged"))); + let (old, new) = (visualci_core::sha256_hex(&before), visualci_core::sha256_hex(&after)); + let blobs = Blob::query().filter(Blob::sha256.is_in(vec![old.clone(), new.clone()])).get().await?; + assert_eq!(blobs.len(), 2, "both files are kept"); + assert!(blobs.iter().all(|b| b.pixel_fingerprint == Some(pixel_fingerprint(&before))), "with one fingerprint"); + + // Later runs send the new bytes: matched by their hash, with no upload. + let id = create(&app, &token, "c3", "c2").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![image_by_sha("home", &after)]).await), vec![false]); + let third = finalize(&app, &token, &id).await; + assert_eq!(third["conclusion"], "unchanged", "{third}"); + Ok(()) +} + +#[laravel::test] +async fn a_fingerprint_sent_with_the_file_is_still_used(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let green = png([0, 200, 0]); + let with_fingerprint = |name: &str| { + let (mut params, bytes) = image_by_sha(name, &green); + params["fingerprint"] = json!(pixel_fingerprint(&green)); + (params, bytes) + }; + let id = create(&app, &token, "c1", "c0").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![with_fingerprint("home")]).await), vec![true]); + assert_eq!(snapshot(1, "home").await?.source_fingerprint, pixel_fingerprint(&green)); + assert_eq!(finalize(&app, &token, &id).await["state"], "completed"); + let id = create(&app, &token, "c2", "c1").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![with_fingerprint("home")]).await), vec![false]); + assert_eq!(finalize(&app, &token, &id).await["conclusion"], "unchanged"); + + // A fingerprint that isn't a hex SHA-256 is still refused. + let id = create(&app, &token, "c3", "c2").await; + let (mut bad, _) = image_by_sha("home", &green); + bad["fingerprint"] = json!("nope"); + let refused = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "snapshots": [bad] })) + .await; + refused.assert_status(400); + assert!(refused.text().contains("sha256 and fingerprint must be lowercase hex"), "{}", refused.text()); + Ok(()) +} + +/// Count every query the app runs while `counting` is set. +fn count_queries() -> (Arc, Arc) { + let (counting, count) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicUsize::new(0))); + let (on, n) = (counting.clone(), count.clone()); + db::listen(move |_| { + if on.load(Ordering::SeqCst) { + n.fetch_add(1, Ordering::SeqCst); + } + }); + (counting, count) +} + +#[laravel::test] +async fn registering_known_files_takes_the_same_queries_for_ten_or_a_hundred(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let files: Vec> = (0..100u8).map(|i| png([i, 255 - i, 7])).collect(); + for bytes in &files { + let blob = app::domain::blobs::put(&store, bytes.clone(), "image/png").await?; + app::domain::blobs::image_info(blob, &store).await?; + } + let (counting, count) = count_queries(); + let mut queries = Vec::new(); + for (n, commit) in [(10, "c1"), (100, "c2")] { + let id = create(&app, &token, commit, "c0").await; + let snapshots: Vec<(Value, Vec)> = + files.iter().take(n).enumerate().map(|(i, b)| image_by_sha(&format!("suite/{i:03}"), b)).collect(); + count.store(0, Ordering::SeqCst); + counting.store(true, Ordering::SeqCst); + let answer = register(&app, &token, &id, snapshots).await; + counting.store(false, Ordering::SeqCst); + assert_eq!(upload_urls(&answer), vec![false; n], "every file is known"); + queries.push(count.load(Ordering::SeqCst)); + } + println!("registering 10 known files: {} queries; 100: {}", queries[0], queries[1]); + assert_eq!(queries[0], queries[1], "the query count doesn't grow with the number of snapshots"); + assert!(queries[1] < 20, "{} queries", queries[1]); + // Their fingerprints came from the blobs, at registration. + let s = snapshot(2, "suite/099").await?; + assert_eq!(s.source_fingerprint, pixel_fingerprint(&files[99])); + Ok(()) +} + +// PDFs: the renderer computes the fingerprint from the file in its sandbox, and reports it when it completes. + +/// A PDF document snapshot sent by its hash alone. +fn pdf_by_sha(name: &str, bytes: &[u8]) -> (Value, Vec) { + let params = json!({ + "name": name, "kind": "document", "sha256": visualci_core::sha256_hex(bytes), "size": bytes.len(), + "content_type": "application/pdf" + }); + (params, bytes.to_vec()) +} + +/// Claim the next render, upload its one page and complete it, reporting `document_fingerprint`. Returns its id. +async fn render_next(app: &Application, page_png: &[u8], document_fingerprint: &str) -> i64 { + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + claimed.assert_ok(); + let job = claimed.json()["job"].clone(); + let (id, claim) = (job["id"].as_i64().expect("a render to claim"), job["token"].as_str().unwrap().to_string()); + let sha = visualci_core::sha256_hex(page_png); + let uploads = app + .post(format!("/internal/renderer/renders/{id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ "files": [{ "sha256": sha, "size": page_png.len(), "content_type": "image/png" }] })) + .await; + uploads.assert_ok(); + if let Some(url) = uploads.json()["upload_urls"][&sha].as_str() { + put(url, page_png.to_vec(), "image/png").await; + } + let page = json!({ + "image": sha, "image_fingerprint": pixel_fingerprint(page_png), "fingerprint": "e".repeat(64), + "width": 16, "height": 16, "text": "Invoice" + }); + let done = app + .post(format!("/internal/renderer/renders/{id}/complete")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ "pages": [page], "document_fingerprint": document_fingerprint })) + .await; + done.assert_ok(); + assert_eq!(done.json()["state"], "done"); + id +} + +#[laravel::test] +async fn the_renderer_fingerprints_a_pdf_and_later_runs_match_it_by_hash(app: Application) -> laravel::Result<()> { + Box::pin(pdf_fingerprints(app)).await +} + +async fn pdf_fingerprints(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let page = png([30, 30, 30]); + // What the PDF draws, the same in both files: only the bytes (a creation date) differ. + let drawn = "d".repeat(64); + let (pdf, pdf_again) = (b"%PDF-1.4 invoice, made Monday".to_vec(), b"%PDF-1.4 invoice, made Tuesday".to_vec()); + let (sha, sha_again) = (visualci_core::sha256_hex(&pdf), visualci_core::sha256_hex(&pdf_again)); + + // #1: a new file is uploaded and drawn under its own hash; the renderer reports its fingerprint, which the blob, + // the render and the snapshot take. + let id = create(&app, &token, "c1", "c0").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![pdf_by_sha("invoice", &pdf)]).await), vec![true]); + assert_eq!(finalize(&app, &token, &id).await["state"], "processing", "waiting for its render"); + let queued = Render::query().first().await?.expect("a render"); + assert_eq!(queued.source_fingerprint, sha, "drawn under the file's hash"); + let render_id = render_next(&app, &page, &drawn).await; + assert_eq!(Blob::find(sha.clone()).await?.and_then(|b| b.pdf_fingerprint), Some(drawn.clone())); + assert_eq!(Render::find_or_fail(render_id).await?.source_fingerprint, drawn, "the render moved to its fingerprint"); + let first = snapshot(1, "invoice").await?; + assert_eq!((first.state.as_str(), first.source_fingerprint.as_str()), ("added", drawn.as_str())); + + // #2: the same file: no upload, the render found by the blob's fingerprint, unchanged. + let id = create(&app, &token, "c2", "c1").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![pdf_by_sha("invoice", &pdf)]).await), vec![false]); + let second = snapshot(2, "invoice").await?; + assert_eq!((second.source_fingerprint.as_str(), second.render_id), (drawn.as_str(), Some(render_id))); + assert_eq!(finalize(&app, &token, &id).await["conclusion"], "unchanged"); + + // #3: the same drawing in other bytes: uploaded and kept as its own blob, drawn once under its hash (the project + // already has a render under the fingerprint, which stays), and unchanged. + let id = create(&app, &token, "c3", "c2").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![pdf_by_sha("invoice", &pdf_again)]).await), vec![true]); + assert_eq!(finalize(&app, &token, &id).await["state"], "processing"); + let again_id = render_next(&app, &page, &drawn).await; + assert_eq!(Render::find_or_fail(again_id).await?.source_fingerprint, sha_again); + assert_eq!(Blob::find(sha_again.clone()).await?.and_then(|b| b.pdf_fingerprint), Some(drawn.clone())); + let third = snapshot(3, "invoice").await?; + assert_eq!((third.state.as_str(), third.source_fingerprint.as_str()), ("unchanged", drawn.as_str())); + assert!(Blob::find(sha.clone()).await?.is_some(), "the first file is kept"); + + // #4: the new bytes again: matched by their hash, with no upload and no render. + let id = create(&app, &token, "c4", "c3").await; + assert_eq!(upload_urls(®ister(&app, &token, &id, vec![pdf_by_sha("invoice", &pdf_again)]).await), vec![false]); + assert_eq!(finalize(&app, &token, &id).await["conclusion"], "unchanged"); + assert_eq!(Render::query().count().await?, 2, "no third render"); + Ok(()) +} + +#[laravel::test] +async fn a_renderer_that_reports_no_fingerprint_leaves_the_files_hash(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let pdf = b"%PDF-1.4 from an older renderer".to_vec(); + let sha = visualci_core::sha256_hex(&pdf); + let id = create(&app, &token, "c1", "c0").await; + register(&app, &token, &id, vec![pdf_by_sha("invoice", &pdf)]).await; + finalize(&app, &token, &id).await; + // An older renderer: its completion has no document_fingerprint. + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + let job = claimed.json()["job"].clone(); + let (render_id, claim) = (job["id"].as_i64().unwrap(), job["token"].as_str().unwrap().to_string()); + let page = png([1, 1, 1]); + let page_sha = visualci_core::sha256_hex(&page); + let uploads = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ "files": [{ "sha256": page_sha, "size": page.len(), "content_type": "image/png" }] })) + .await; + if let Some(url) = uploads.json()["upload_urls"][&page_sha].as_str() { + put(url, page.clone(), "image/png").await; + } + app.post(format!("/internal/renderer/renders/{render_id}/complete")) + .header("authorization", RENDERER) + .header("x-render-token", &claim) + .json(json!({ "pages": [{ "image": page_sha, "image_fingerprint": pixel_fingerprint(&page), + "fingerprint": "e".repeat(64), "width": 16, "height": 16, "text": "" }] })) + .await + .assert_ok(); + let s = snapshot(1, "invoice").await?; + assert_eq!((s.state.as_str(), s.source_fingerprint.as_str()), ("added", sha.as_str())); + assert_eq!(Blob::find(sha).await?.and_then(|b| b.pdf_fingerprint), None); + Ok(()) +} + +#[laravel::test] +async fn groups_can_name_images_by_their_files_hash(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let shot = png([9, 9, 9]); + let id = create(&app, &token, "c1", "c0").await; + register(&app, &token, &id, vec![image_by_sha("suite/home/hero/desktop", &shot)]).await; + finalize(&app, &token, &id).await; + + // The client hashes the image's entry by its file's SHA-256 and says so. + let entry = visualci_core::manifest::Entry { + name: "suite/home/hero/desktop".into(), + platform: String::new(), + kind: "image".into(), + fingerprint: visualci_core::sha256_hex(&shot), + format: None, + engine: None, + threshold: None, + ignore_anti_aliasing: None, + ignore: json!({ "json_paths": [], "text_patterns": [] }), + }; + let groups: Vec = visualci_core::manifest::groups(std::slice::from_ref(&entry), Default::default()) + .into_iter() + .map(|g| json!({ "key": g.key, "hash": g.hash, "count": g.count })) + .collect(); + let id = create(&app, &token, "c2", "c1").await; + let checked = app + .post(format!("/api/v1/builds/{id}/groups")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "groups": groups, "image_hash": "sha256" })) + .await; + checked.assert_ok(); + assert_eq!(checked.json()["unchanged"], json!(["suite/home"]), "{}", checked.json()); + + // Hashed the published CLIs' way (by pixel fingerprint) without saying so, the same entry doesn't match. + let id = create(&app, &token, "c3", "c1").await; + let mismatched = app + .post(format!("/api/v1/builds/{id}/groups")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "groups": groups })) + .await; + assert_eq!(mismatched.json()["changed"], json!(["suite/home"]), "{}", mismatched.json()); + let refused = app + .post(format!("/api/v1/builds/{id}/groups")) + .header("authorization", format!("Bearer {token}")) + .json(json!({ "groups": [], "image_hash": "md5" })) + .await; + refused.assert_status(400); + Ok(()) +} diff --git a/crates/visualci-renderer/src/main.rs b/crates/visualci-renderer/src/main.rs index e3ec7044..6b54a766 100644 --- a/crates/visualci-renderer/src/main.rs +++ b/crates/visualci-renderer/src/main.rs @@ -167,9 +167,9 @@ async fn main() -> Result<()> { eprintln!("render {id}: {} at {} dpi", job.engine, job.dpi); let result = tokio::time::timeout(RENDER_TIMEOUT, render(&api, &job)).await; let body = match result { - Ok(Ok(pages)) => { + Ok(Ok((pages, document_fingerprint))) => { eprintln!("render {id}: {} pages", pages.len()); - serde_json::json!({ "pages": pages }) + serde_json::json!({ "pages": pages, "document_fingerprint": document_fingerprint }) } Ok(Err(e)) => { eprintln!("render {id} failed: {e:#}"); @@ -202,7 +202,9 @@ fn chrono_now() -> String { format!("{:?}", std::time::SystemTime::now()) } -async fn render(api: &Api, job: &Job) -> Result> { +/// Draw the job's PDF: its pages, and the document's fingerprint as the CLI computes it (the server keeps it on the +/// PDF's blob, so a later run can send the file's hash alone). +async fn render(api: &Api, job: &Job) -> Result<(Vec, String)> { let dir = tempfile::tempdir()?; let pdf_path = dir.path().join("source.pdf"); // Read in chunks and stop at the limit, rather than take whatever the bucket sends into memory first. @@ -277,7 +279,7 @@ async fn render(api: &Api, job: &Job) -> Result> { .with_context(|| format!("uploading page image {sha}"))?; } } - Ok(pages) + Ok((pages, fingerprint.document)) } /// Rasterize every page. Returns the PNG paths in page order. diff --git a/docs/design-storage.md b/docs/design-storage.md index 9aeb06e4..b020909c 100644 --- a/docs/design-storage.md +++ b/docs/design-storage.md @@ -282,6 +282,13 @@ retention. ### Caches keyed by content +- **Blobs** carry what the server learned from their bytes (sc-8999): an image's size and pixel fingerprint + (`blobs::image_info`), and a PDF's fingerprint as its renderer reported it (`pdf_fingerprint`, set once). Only + server-computed values go there, never a client's claim, since blobs are shared by every project. A snapshot sent by + its file's hash alone takes its fingerprint from them. Registering a request's snapshots reads all their blobs in + one query and writes the snapshots in one statement, and confirming a build's uploads reads its blob rows in one + query, asking the store only about files not yet confirmed. + - **Renders:** `(project_id, source_fingerprint, renderer)`, where the renderer key holds the engine, DPI and version. Deliberately per project: the fingerprint is the client's word, and another account's render under it must never be compared. Page text moves to `texts`. diff --git a/docs/design.md b/docs/design.md index a1324b7a..7f360e0b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -65,7 +65,7 @@ self-hostable version. ``` client (CLI / Ruby gem / JS SDK) 1. POST /builds {project, commit, branch, pr, parents, mode} - 2. POST /builds/:id/snapshots [{name, source: {kind, fingerprint, size}, threshold?, meta}] (batched) + 2. POST /builds/:id/snapshots [{name, kind, sha256, fingerprint?, size, threshold?, meta}] (batched) ← per snapshot: "known" | "upload": presigned R2 URL 3. PUT only the sources the server lacks (PDF bytes, DOM snapshot bundle, PNG) 4. POST /builds/:id/finalize (or once per shard; the build closes when all shards finish) @@ -78,15 +78,30 @@ client 9. --wait: poll or stream until done; exit code by mode (see CI behaviour) ``` -Fingerprints for step 2 are computed on the client with the same open-source library the server uses (Rust, -compiled into the CLI and the Ruby gem's native extension or WASM), so a hash hit never uploads a byte. +Step 2 names each file by its SHA-256, and the fingerprint is optional (sc-8999). Unchanged screenshots are +byte-identical from run to run, so the file's hash finds them: the client needn't decode every image to fingerprint +it. The server answers per file whether it has it, and for a file it has, the snapshot takes the fingerprint stored +on its blob. For a new file, the server computes the fingerprint once the bytes arrive and keeps it on the blob: an +image's pixel fingerprint when processing starts (`processing::fill_image_fingerprints`, outside any transaction, one +statement for the snapshots), and a PDF's fingerprint from the renderer, which computes it from the file in its +sandbox and reports it with the pages (a PDF it has no fingerprint for yet is drawn under its file's hash, and the +render moves to the fingerprint when the project has none under it). A re-encoded file (the same pixels in new bytes, +after a browser upgrade) is uploaded once and kept as its own blob under its own hash, with the same fingerprint, so it +compares unchanged and later runs match it by hash with no upload or decode. Blobs are never merged by fingerprint. + +The CLI still fingerprints PDFs (with the same open-source library the server and renderer use): a PDF's bytes change +on every run (creation dates, IDs) while what it draws doesn't, so the fingerprint saves an upload and a render. Older +CLIs send every fingerprint, and the server takes them as they are. Registration costs the same few statements for 1 +snapshot or 1,000 (the blobs' upsert and read, one renders query, the snapshots' upsert). ### Large suites: manifest and group hashes (sc-8868) A run of 500 or more snapshots (the CLI decides; `VISUALCI_GROUPS` overrides) first sends `POST /builds/:id/groups`: a hash of the whole run and one hash per group of names (a name's group is its path without the last two segments, or its first `group_depth` segments). Hashes come from `visualci_core::manifest`, over each snapshot's name, -platform, kind, fingerprint and comparison settings, so the CLI and the server compute them the same way. The +platform, kind, fingerprint and comparison settings, so the CLI and the server compute them the same way. A client +that doesn't decode images sends `image_hash: sha256`, and an image's entry then holds its file's SHA-256 on both +sides. The server computes the baseline's side from its own rows (`baselines::resolve`), never from a client's claim, records each group in `build_groups` and answers which groups differ. The client sends only those groups' files. @@ -120,7 +135,8 @@ run 1 in all; changed groups' snapshots are charged as usual. A group can be sen hash(normalized HTML, sorted manifest, viewport, device scale factor, color scheme, user agent class). Resources are uploaded content-addressed, so only the new ones go up. - **Image** (client-rendered): `sha256` of the decoded RGBA pixels plus dimensions, not the file bytes, so PNG - encoder differences don't matter. Tagged with `platform` (`ios-26.1/iphone-16`), which is part of the snapshot's + encoder differences don't matter. The server computes it from the uploaded file (`vci-img-1`); clients send the + file's hash. Tagged with `platform` (`ios-26.1/iphone-16`), which is part of the snapshot's baseline key. ### Renderers @@ -308,7 +324,7 @@ and JSON diffs, contact sheets), and the build's summary line is computed from t ``` POST /v1/builds → {build_id, upload_mode} -POST /v1/builds/:id/snapshots [{name, kind, source:{type, fingerprint, bytes}, pages?, platform?, threshold?, meta}] +POST /v1/builds/:id/snapshots [{name, kind, sha256, fingerprint?, size, platform?, threshold?, meta}] → [{name, status: known|upload, upload:{url, fields}}] POST /v1/builds/:id/shards/:n/finalize POST /v1/builds/:id/finalize @@ -447,8 +463,8 @@ review is the publish step. Only images from the `ci` environment are published. - Blobs, renders and diffs are deduplicated globally by SHA256, as Argos does. - Customer documents are untrusted input: they're parsed and rendered only on the render node, under gVisor, with - no network. The fingerprint parser runs in the same sandbox on the server (client-side hashing is for the client's - own files). Each claimed render gets its own token (its uploads and completion need it), the engines run with a + no network. The renderer computes a PDF's fingerprint in the same sandbox and reports it with the pages + (client-side hashing is for the client's own files). Each claimed render gets its own token (its uploads and completion need it), the engines run with a cleared environment, the download is capped as it streams, and a pixel budget is checked before drawing: at most 110 megapixels a page, 2,500 a document and 2,000 pages at the job's DPI (`visualci-renderer`'s `budget`, sc-8726). - Its own namespace, default-deny NetworkPolicies, its own CNPG cluster and R2 bucket (the cluster's per-product rules). diff --git a/server/frontend/content/docs/reference/api.md b/server/frontend/content/docs/reference/api.md index 9c7b5394..1c1288ba 100644 --- a/server/frontend/content/docs/reference/api.md +++ b/server/frontend/content/docs/reference/api.md @@ -48,7 +48,7 @@ All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer ``` - `kind` is `document` (a PDF), `image` or `text`. -- `fingerprint` is the PDF fingerprint for documents, the pixel fingerprint for images, and the SHA-256 of the text for text. `visualci fingerprint ` prints the first two. +- `sha256` is the SHA-256 of the file's bytes. `fingerprint` is optional: the PDF fingerprint for documents, the pixel fingerprint for images, and the SHA-256 of the text for text (`visualci fingerprint ` prints the first two). Without it, VisualCI uses the fingerprint it computed for the file before, or computes it once the file is uploaded. Sending a PDF's fingerprint saves an upload when only its bytes changed (a new creation date). - Optional: `threshold`, `ignore_anti_aliasing`, `engine` (`pdfbox` or `mutool`), `format` (`text`, `json` or `html`; without it the content type decides), `ignore` (`{"json_paths": [...], "text_patterns": [...]}`, set in the test, for this snapshot only). The response lists each snapshot with an `upload_url`. PUT the file's bytes there with its `content_type`, within 15 minutes (register again for a fresh link). `upload_url` is `null` when VisualCI already has the file. A file can be at most 64 MiB, and its bytes must match its `sha256`: anything else is discarded and reported missing.