From a17fdd3549c22b5c6ceb8b8023aaca12a466b35e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 15:27:24 +0000 Subject: [PATCH 1/4] Compare tall screenshots a row at a time, and say when a worker ran out of memory (VISUALCI-PROD-SERVER-6) A 2880x14000 comparison held three or four full-size RGBA buffers at once and peaked at 665 MiB. It now reads 8-bit PNGs a row at a time (image_hash::Rows), keeps a five-row window of each image, and streams the overlay into the PNG encoder: 84 MiB, most of it the input files, with identical results and overlay pixels. Fingerprints, matching approved changes and PR comment images read rows too, and whole-image decodes (other formats) go one at a time (WHOLE_DECODES). A run that finds the previous run's mark on its build counts it as died. After three, the build fails with "the worker ran out of memory (or was killed) processing build #N", and ProcessBuild's fourth try fails the build and the job with it rather than "attempted more than its 3 tries allow". visualci-core changed: the workspace version is 0.2.30. --- Cargo.lock | 9 +- Cargo.toml | 4 +- app/src/domain/blobs.rs | 7 +- app/src/domain/diffs.rs | 18 +- app/src/domain/matching.rs | 90 ++- app/src/domain/processing.rs | 112 +++- app/src/forge/comment_images.rs | 74 ++- app/src/forge/pr_comment.rs | 2 + app/src/jobs/process_build.rs | 16 +- app/tests/processing_lock.rs | 87 +++ clients/circleci-orb/orb.yml | 10 +- clients/github-action/action.yml | 2 +- crates/visualci-core/Cargo.toml | 1 + .../visualci-core/examples/compare_memory.rs | 150 +++++ crates/visualci-core/src/diff.rs | 558 ++++++++++++++++-- crates/visualci-core/src/image_hash.rs | 264 ++++++++- crates/visualci-core/tests/peak_memory.rs | 110 ++++ 17 files changed, 1395 insertions(+), 119 deletions(-) create mode 100644 crates/visualci-core/examples/compare_memory.rs create mode 100644 crates/visualci-core/tests/peak_memory.rs diff --git a/Cargo.lock b/Cargo.lock index ddd79d659..d58e8138b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5470,7 +5470,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.29" +version = "0.2.30" dependencies = [ "anyhow", "base64 0.22.1", @@ -5487,12 +5487,13 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.29" +version = "0.2.30" dependencies = [ "globset", "hex", "image", "lopdf", + "png", "schemars", "serde", "serde_json", @@ -5507,7 +5508,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.29" +version = "0.2.30" dependencies = [ "anyhow", "image", @@ -5522,7 +5523,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.29" +version = "0.2.30" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index 4a85f16be..6c16e8dae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.29" +version = "0.2.30" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" @@ -20,6 +20,8 @@ schemars = "1" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "fs", "time", "signal"] } tempfile = "3" +# Decoding PNG screenshots a row at a time, and writing diff overlays the same way (visualci-core::image_hash::Rows) +png = "0.18" lopdf = { version = "0.47", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index 7d3a737bb..ea82b234a 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -158,10 +158,9 @@ pub type ImageInfo = (String, u32, u32); /// Decode an image and fingerprint its pixels. CPU-bound, so it runs on the blocking pool ([`decode`]): it gets only /// the bytes, and calls nothing that needs the app's context (the database, the cache, `laravel::now()`). fn decode_image(sha256: &str, bytes: &[u8]) -> Result { - let image = visualci_core::image_hash::decode(bytes).map_err(|e| format!("{sha256}: {e}"))?.to_rgba8(); - let fp = visualci_core::image_hash::fingerprint_rgba(&image); - let (w, h) = image.dimensions(); - Ok((fp, w, h)) + // Read a row at a time: eight tall screenshots at once (`VISUALCI_FINGERPRINT_CONCURRENCY`) cost a few rows each, + // not their full size (VISUALCI-PROD-SERVER-6). + visualci_core::image_hash::info(bytes).map_err(|e| format!("{sha256}: {e}")) } /// [`decode_image`] off the async runtime's threads, so a large image (or hundreds of them) never stalls the other diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs index b0522f29e..68f901cf1 100644 --- a/app/src/domain/diffs.rs +++ b/app/src/domain/diffs.rs @@ -1,7 +1,5 @@ //! Image diffs, cached by (base image, head image, options and mask): the same pair is never diffed twice. -use std::io::Cursor; - use laravel::db; use laravel::model::update; use visualci_core::config::ImageMask; @@ -84,19 +82,9 @@ pub async fn find_or_compute( }; let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); let mask = mask.clone(); - let (outcome, overlay_png) = laravel::task::spawn_blocking(move || -> Result<_, String> { - let base = visualci_core::image_hash::decode(&base_bytes).map_err(|e| e.to_string())?.to_rgba8(); - let head = visualci_core::image_hash::decode(&head_bytes).map_err(|e| e.to_string())?.to_rgba8(); - let masked = mask.resolve(base.width().max(head.width()), base.height().max(head.height())); - let (outcome, overlay) = visualci_core::diff::diff_masked(&base, &head, options, &masked); - let overlay_png = if outcome.is_identical() { - None - } else { - let mut png = Vec::new(); - overlay.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?; - Some(png) - }; - Ok((outcome, overlay_png)) + // Read a row at a time, so a tall full-page screenshot costs a few rows of memory (VISUALCI-PROD-SERVER-6). + let (outcome, overlay_png) = laravel::task::spawn_blocking(move || { + visualci_core::diff::diff_files(&base_bytes, &head_bytes, options, &mask).map_err(|e| e.to_string()) }) .await .map_err(|e| laravel::Error::msg(e.to_string()))? diff --git a/app/src/domain/matching.rs b/app/src/domain/matching.rs index baa6a5d1f..49f2f66a8 100644 --- a/app/src/domain/matching.rs +++ b/app/src/domain/matching.rs @@ -10,9 +10,11 @@ use std::collections::HashMap; -use image::RgbaImage; +use std::sync::Arc; + use laravel::db; use visualci_core::diff::{DiffResult, Region}; +use visualci_core::image_hash::{Rows, RowsFailed, WHOLE_DECODES}; use crate::models::{Build, Diff, Snapshot, SnapshotPage}; use crate::storage::BlobStore; @@ -54,38 +56,56 @@ async fn page_changes(snapshot_id: i64) -> laravel::Result> { } type Candidate = (usize, i64, i64); -/// Decoded images, by blob, so a page shared by several candidates is read once. +/// Image files, by blob, so a page shared by several candidates is downloaded once. They stay compressed: a decoded +/// full-page screenshot is 100 MB or more (VISUALCI-PROD-SERVER-6), and [`same_in_files`] reads a row at a time. struct Images<'a> { store: &'a BlobStore, - cache: HashMap>, + cache: HashMap>>>, } impl Images<'_> { - async fn get(&mut self, sha: &str) -> Option<&RgbaImage> { + async fn get(&mut self, sha: &str) -> Option>> { if !self.cache.contains_key(sha) { - let decoded = match self.store.get(sha).await { - Ok(bytes) => image::load_from_memory(&bytes).ok().map(|i| i.to_rgba8()), - Err(_) => None, - }; - self.cache.insert(sha.to_string(), decoded); + let bytes = self.store.get(sha).await.ok().map(Arc::new); + self.cache.insert(sha.to_string(), bytes); } - self.cache.get(sha).and_then(Option::as_ref) + self.cache.get(sha).cloned().flatten() } } -/// Whether two images have the same pixels inside a region (a pixel one has and the other doesn't is a difference). +/// Whether two image files have the same pixels inside every region (a pixel one has and the other doesn't is a +/// difference). False when either isn't an image. Read a row at a time ([`Rows`]), down to the lowest region. #[must_use] -pub fn same_in(a: &RgbaImage, b: &RgbaImage, r: &Region) -> bool { - for y in r.y..r.y.saturating_add(r.height) { - for x in r.x..r.x.saturating_add(r.width) { - let pa = (x < a.width() && y < a.height()).then(|| a.get_pixel(x, y)); - let pb = (x < b.width() && y < b.height()).then(|| b.get_pixel(x, y)); - if pa != pb { - return false; +pub fn same_in_files(a: &[u8], b: &[u8], regions: &[Region]) -> bool { + let compare = |a: &mut Rows<'_>, b: &mut Rows<'_>| -> Result { + let bottom = regions.iter().map(|r| r.y.saturating_add(r.height)).max().unwrap_or(0); + let (aw, bw) = (a.width() as usize, b.width() as usize); + for y in 0..bottom { + let ra = if y < a.height() { Some(a.next_row()?) } else { None }; + let rb = if y < b.height() { Some(b.next_row()?) } else { None }; + for r in regions.iter().filter(|r| y >= r.y && y < r.y.saturating_add(r.height)) { + for x in r.x as usize..r.x.saturating_add(r.width) as usize { + let pa = ra.filter(|_| x < aw).map(|row| &row[x * 4..x * 4 + 4]); + let pb = rb.filter(|_| x < bw).map(|row| &row[x * 4..x * 4 + 4]); + if pa != pb { + return Ok(false); + } + } } } + Ok(true) + }; + let (Ok(mut ra), Ok(mut rb)) = (Rows::open(a), Rows::open(b)) else { return false }; + match compare(&mut ra, &mut rb) { + Ok(same) => same, + // The streaming decoder gave up part-way through a file: decode both whole, as before. + Err(RowsFailed) => { + drop((ra, rb)); + let _whole = WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (Ok(mut ra), Ok(mut rb)) = (Rows::decoded(a), Rows::decoded(b)) else { return false }; + compare(&mut ra, &mut rb).unwrap_or(false) + } } - true } /// Whether every region of `ours` is a region `theirs` changed, from the same old pixels to the same new ones. @@ -97,9 +117,11 @@ async fn covered(images: &mut Images<'_>, ours: &PageChange, theirs: &PageChange return false; } for (a, b) in [(&ours.base_image, &theirs.base_image), (&ours.head_image, &theirs.head_image)] { - let Some(a) = images.get(a).await.cloned() else { return false }; - let Some(b) = images.get(b).await else { return false }; - if !ours.regions.iter().all(|r| same_in(&a, b, r)) { + let (Some(a), Some(b)) = (images.get(a).await, images.get(b).await) else { return false }; + let regions = ours.regions.clone(); + // Decoding is CPU-bound: off the runtime's threads. + let same = tokio::task::spawn_blocking(move || same_in_files(&a, &b, ®ions)).await.unwrap_or(false); + if !same { return false; } } @@ -147,6 +169,8 @@ pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result { let mut marked = 0; for s in changed { let Some(mut theirs) = candidates.remove(&(s.name.clone(), s.platform.clone())) else { continue }; + // A snapshot's files are its own: keep only one snapshot's at a time. + images.cache.clear(); theirs.sort_unstable(); let ours = page_changes(s.id).await?; if ours.is_empty() { @@ -184,18 +208,30 @@ pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result { mod tests { use super::*; + fn png(img: &image::RgbaImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + #[test] fn compares_pixels_inside_a_region_only() { - let mut a = RgbaImage::from_pixel(8, 8, image::Rgba([255, 255, 255, 255])); + let mut a = image::RgbaImage::from_pixel(8, 8, image::Rgba([255, 255, 255, 255])); let b = a.clone(); a.put_pixel(6, 6, image::Rgba([0, 0, 0, 255])); + let (a, b) = (png(&a), png(&b)); let inside = Region { x: 0, y: 0, width: 4, height: 4 }; let around = Region { x: 4, y: 4, width: 4, height: 4 }; - assert!(same_in(&a, &b, &inside)); - assert!(!same_in(&a, &b, &around)); + assert!(same_in_files(&a, &b, &[inside])); + assert!(!same_in_files(&a, &b, &[around])); + assert!(!same_in_files(&a, &b, &[inside, around])); // A pixel only one image has (a taller page) is a difference. - let tall = RgbaImage::from_pixel(8, 12, image::Rgba([255, 255, 255, 255])); - assert!(!same_in(&b, &tall, &Region { x: 0, y: 6, width: 8, height: 6 })); + let tall = png(&image::RgbaImage::from_pixel(8, 12, image::Rgba([255, 255, 255, 255]))); + assert!(!same_in_files(&b, &tall, &[Region { x: 0, y: 6, width: 8, height: 6 }])); + assert!(same_in_files(&b, &tall, &[Region { x: 0, y: 0, width: 8, height: 8 }])); + // A region past both images' edges compares nothing there; a file that isn't an image matches nothing. + assert!(same_in_files(&b, &b, &[Region { x: 4, y: 4, width: 40, height: 40 }])); + assert!(!same_in_files(b"not an image", &b, &[inside])); } } diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index aa5da92ba..7cc00e5c2 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -97,6 +97,103 @@ const AGAIN_MINUTES: i64 = 20; /// build again when it's done ([`exclusive`]), rather than hold a worker while it waits. pub const JOB_WAIT_SECONDS: i64 = 10; +/// How many runs of a build may die before it fails (`ProcessBuild`'s tries): a build whose runs keep killing their +/// worker (out of memory, VISUALCI-PROD-SERVER-6) fails saying so, rather than retrying for ever or failing with the +/// queue's "attempted more than its tries allow". +pub const RUNS: u32 = 3; + +/// The mark a run leaves on its build while it works, inside [`exclusive`]: a run that finds it there when it takes the +/// build knows the run before it never finished. Its worker died (ran out of memory, or was killed by a deploy or the +/// job's timeout) while holding the build, since a live run would still hold it. +fn running_key(build_id: i64) -> String { + format!("builds.process-running:{build_id}") +} + +/// How many runs of the build died before finishing ([`running_key`]). +fn died_key(build_id: i64) -> String { + format!("builds.process-died:{build_id}") +} + +/// How long the marks last: longer than any run and its retries. +const RUN_MARK_HOURS: i64 = 24; + +/// Note that a run took the build, while holding it ([`exclusive`]). Returns how many runs before it died without +/// finishing, counting the one just before when it left its mark ([`running_key`]). +/// +/// # Errors +/// On a cache error. +pub async fn note_run_start(build_id: i64) -> laravel::Result { + use laravel::time::ToSpan; + let mut died = laravel::cache::get::(&died_key(build_id)).await?.unwrap_or(0); + if laravel::cache::pull::(&running_key(build_id)).await?.is_some() { + died += 1; + laravel::cache::put(&died_key(build_id), died, RUN_MARK_HOURS.hours()).await?; + tracing::warn!( + build_id, + died, + "the previous run processing this build never finished: its worker ran out of memory or was killed" + ); + } + laravel::cache::put(&running_key(build_id), true, RUN_MARK_HOURS.hours()).await?; + Ok(died) +} + +/// Note that a run ended (it finished, waits for renders, stopped for a deploy, or failed and failed the build): it +/// didn't die. `concluded`: the build is done with, so the count of runs that died starts again. +/// +/// # Errors +/// On a cache error. +pub async fn note_run_end(build_id: i64, concluded: bool) -> laravel::Result<()> { + laravel::cache::forget(&running_key(build_id)).await?; + if concluded { + laravel::cache::forget(&died_key(build_id)).await?; + } + Ok(()) +} + +fn died_message(number: i32, died: i64) -> String { + let times = if died == 1 { "once".to_string() } else { format!("{died} times") }; + format!("the worker ran out of memory (or was killed) processing build #{number}, {times}") +} + +/// Fail a build whose processing ran out of tries (`ProcessBuild` beyond [`RUNS`]), saying why: its runs' workers died +/// ([`note_run_start`]), or else it didn't finish in its tries. Returns the error, for the job's own failure, or `None` +/// when the build isn't processing any more (its last run finished after all) or another run is processing it now. +/// +/// # Errors +/// On a database or cache error. +pub async fn give_up(build_id: i64) -> laravel::Result> { + // Under the build's processing lock: a run another job started meanwhile is live, and is left to finish. + let out = exclusive(build_id, 0, || async move { + let mut died = laravel::cache::pull::(&died_key(build_id)).await?.unwrap_or(0); + // The last run's mark: it died too (it no longer holds the build, so it isn't running). + if laravel::cache::pull::(&running_key(build_id)).await?.is_some() { + died += 1; + } + let Some(mut build) = Build::find(build_id).await? else { return Ok(None) }; + if build.state != "processing" { + return Ok(None); + } + let message = if died > 0 { + died_message(build.number, died) + } else { + format!("processing build #{} didn't finish in its {RUNS} tries", build.number) + }; + let error = Some(message.clone()); + update!(build { state: "failed", error }).await?; + Ok(Some(message)) + }) + .await; + let message = match out { + Err(e) if e.is::() => return Ok(None), + other => other?, + }; + if message.is_some() { + Box::pin(crate::events::BuildChanged { build_id }.dispatch().into_future()).await?; + } + Ok(message) +} + /// The note a job leaves when another run holds the build: run it again once that run is done. fn again_key(build_id: i64) -> String { format!("builds.process-again:{build_id}") @@ -215,8 +312,21 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la if build.state != "processing" { return Ok(false); } + // A build whose runs keep dying (out of memory) fails saying so, however its runs were queued (a retry, the + // sweep, a render finishing), rather than kill another worker. + let died = note_run_start(id).await?; + if died >= i64::from(RUNS) { + note_run_end(id, true).await?; + return Err(laravel::Error::msg(died_message(build.number, died))); + } // Boxed: processing's future is large, and the lock's own future holds it. - Box::pin(process(build, store, renderer_version)).await + let out = Box::pin(process(build, store, renderer_version)).await; + let concluded = match &out { + Ok(done) => *done, + Err(e) => !e.is::(), + }; + note_run_end(id, concluded).await?; + out }; let busy = |r: &laravel::Result| matches!(r, Err(e) if e.is::()); let mut result = Box::pin(exclusive(id, JOB_WAIT_SECONDS, work)).await; diff --git a/app/src/forge/comment_images.rs b/app/src/forge/comment_images.rs index bd565a66a..107174114 100644 --- a/app/src/forge/comment_images.rs +++ b/app/src/forge/comment_images.rs @@ -14,6 +14,7 @@ use image::{DynamicImage, GenericImageView, Rgba, RgbaImage, imageops::FilterType}; use visualci_core::diff::Region; +use visualci_core::image_hash::{Rows, RowsFailed}; /// The boxed page's width in pixels (shown at half that in the comment, so it's sharp on a high-density screen). pub const BOXED_WIDTH: u32 = 640; @@ -64,6 +65,9 @@ pub struct Images { /// `base` and `head` images, and the diff's `regions` (canvas pixels). `None` when the overlay doesn't decode. #[must_use] pub fn render(overlay: &[u8], base: Option<&[u8]>, head: Option<&[u8]>, regions: &[Region]) -> Option { + // The overlay is the one image decoded whole (it's scaled down whole); the before and after are read a row at a + // time, for the rows they're needed in ([`Rows`]): a tall page's comment once decoded four full-size images + // (VISUALCI-PROD-SERVER-6). let mut overlay = visualci_core::image_hash::decode(overlay).ok()?; // The close-up zooms in on the largest single region (a connected group of changes), not a merged box, so a // small change near others is still enlarged. Cut to where its changes begin before the moved-content step @@ -85,20 +89,24 @@ pub fn render(overlay: &[u8], base: Option<&[u8]>, head: Option<&[u8]>, regions: height: groups[0].height.saturating_sub(MOVED_BAND), ..groups[0] }; - if let Some(head) = head.and_then(|h| visualci_core::image_hash::decode(h).ok()) { - overlay = DynamicImage::ImageRgba8(unmark(overlay.to_rgba8(), &head, below)); + if let Some(head) = head.and_then(|h| Rows::open(h).ok()) { + let mut marked = std::mem::replace(&mut overlay, DynamicImage::new_rgba8(0, 0)).into_rgba8(); + // A file the streaming decoder gives up on part-way leaves the rows before unmarked; the after image was + // decoded whole for its diff already, so that doesn't happen. + let _ = unmark(&mut marked, head, below); + overlay = DynamicImage::ImageRgba8(marked); } groups[0].height = groups[0].height.min(MOVED_BAND); } let boxed = crate::mcp::images::encode(&DynamicImage::ImageRgba8(boxed(&overlay, &groups))); + drop(overlay); let closeup = largest.and_then(|largest| { - let (base, head) = - (visualci_core::image_hash::decode(base?).ok()?, visualci_core::image_hash::decode(head?).ok()?); + let (base, head) = (Rows::open(base?).ok()?, Rows::open(head?).ok()?); let canvas = (base.width().max(head.width()), base.height().max(head.height())); let area = closeup_area(largest, canvas.0, canvas.1); Some(( - crate::mcp::images::encode(&DynamicImage::ImageRgba8(closeup(&base, area))), - crate::mcp::images::encode(&DynamicImage::ImageRgba8(closeup(&head, area))), + crate::mcp::images::encode(&DynamicImage::ImageRgba8(closeup_of(crop(base, area).ok()?, area))), + crate::mcp::images::encode(&DynamicImage::ImageRgba8(closeup_of(crop(head, area).ok()?, area))), )) }); Some(Images { boxed, closeup, moved }) @@ -118,18 +126,24 @@ pub fn moved(group: &Region, width: u32, height: u32) -> bool { } /// The overlay's changed (red) pixels in `area` shown as the faded head image again, as the overlay shows unchanged -/// pixels; masked areas keep their hatching. -fn unmark(mut overlay: RgbaImage, head: &DynamicImage, area: Region) -> RgbaImage { +/// pixels; masked areas keep their hatching. The head image is read a row at a time, down to the area's last row. +fn unmark(overlay: &mut RgbaImage, mut head: Rows<'_>, area: Region) -> Result<(), RowsFailed> { let (w, h) = overlay.dimensions(); - let (hw, hh) = head.dimensions(); - for y in area.y..(area.y + area.height).min(h).min(hh) { + let (hw, hh) = (head.width(), head.height()); + let bottom = (area.y + area.height).min(h).min(hh); + for y in 0..bottom { + let row = head.next_row()?; + if y < area.y { + continue; + } for x in area.x..(area.x + area.width).min(w).min(hw) { if *overlay.get_pixel(x, y) == CHANGED { - overlay.put_pixel(x, y, faded(head.get_pixel(x, y))); + let at = x as usize * 4; + overlay.put_pixel(x, y, faded(Rgba([row[at], row[at + 1], row[at + 2], row[at + 3]]))); } } } - overlay + Ok(()) } /// An unchanged pixel in the overlay: the same fade `visualci_core::diff` gives it (private there, and the CLI's crate @@ -295,11 +309,39 @@ pub fn closeup_area(region: Region, width: u32, height: u32) -> Region { /// [`CLOSEUP_SIZE`], never reduced. Where the area runs past this image (a page that grew or shrank), it's transparent. #[must_use] pub fn closeup(img: &DynamicImage, area: Region) -> RgbaImage { - let mut cut = RgbaImage::from_pixel(area.width, area.height, Rgba([0, 0, 0, 0])); let (w, h) = img.dimensions(); - if area.x < w && area.y < h { - let part = img.crop_imm(area.x, area.y, area.width.min(w - area.x), area.height.min(h - area.y)); - image::imageops::overlay(&mut cut, &part.to_rgba8(), 0, 0); + let part = (area.x < w && area.y < h) + .then(|| img.crop_imm(area.x, area.y, area.width.min(w - area.x), area.height.min(h - area.y)).to_rgba8()); + closeup_of(part, area) +} + +/// The part of an image inside `area` (cut to the image), read a row at a time down to the area's last row: `None` +/// when the area starts past the image. +fn crop(mut rows: Rows<'_>, area: Region) -> Result, RowsFailed> { + let (w, h) = (rows.width(), rows.height()); + if area.x >= w || area.y >= h { + return Ok(None); + } + let (cw, ch) = (area.width.min(w - area.x), area.height.min(h - area.y)); + let mut part = RgbaImage::new(cw, ch); + for y in 0..area.y + ch { + let row = rows.next_row()?; + if y >= area.y { + let from = area.x as usize * 4; + let line = cw as usize * 4; + let to = (y - area.y) as usize * line; + let raw: &mut [u8] = &mut part; + raw[to..to + line].copy_from_slice(&row[from..from + line]); + } + } + Ok(Some(part)) +} + +/// [`closeup`] of the part of the image inside `area` ([`crop`]). +fn closeup_of(part: Option, area: Region) -> RgbaImage { + let mut cut = RgbaImage::from_pixel(area.width, area.height, Rgba([0, 0, 0, 0])); + if let Some(part) = part { + image::imageops::overlay(&mut cut, &part, 0, 0); } let zoom = (f64::from(CLOSEUP_SIZE) / f64::from(area.width.max(area.height))).clamp(1.0, CLOSEUP_MAX_ZOOM); let zw = (f64::from(area.width) * zoom).round().max(1.0) as u32; diff --git a/app/src/forge/pr_comment.rs b/app/src/forge/pr_comment.rs index e509413ee..c080e99be 100644 --- a/app/src/forge/pr_comment.rs +++ b/app/src/forge/pr_comment.rs @@ -310,6 +310,8 @@ async fn make_images( let Some(shown) = overlay.or_else(|| head.clone()) else { return Ok(None) }; let regions = result.regions; let rendered = tokio::task::spawn_blocking(move || { + // It decodes the overlay whole: one whole-image decode at a time in the process (VISUALCI-PROD-SERVER-6). + let _whole = visualci_core::image_hash::WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); super::comment_images::render(&shown, base.as_deref(), head.as_deref(), ®ions) }) .await diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs index 0223e0666..3c1b2c619 100644 --- a/app/src/jobs/process_build.rs +++ b/app/src/jobs/process_build.rs @@ -2,7 +2,7 @@ //! when a build's last shard finalizes, and again whenever a render it waits on finishes: dispatches for one build //! within a few seconds run once (a build of 1,000 PDFs finishing its renders together is one run, not 1,000). -use laravel::queue::{Queueable, job}; +use laravel::queue::{Attempt, Queueable, job}; use crate::domain::processing; use crate::storage::BlobStore; @@ -16,13 +16,15 @@ pub struct ProcessBuild { // while the run works (`processing::HOLD_SECONDS`), so it outlasts a live run and lapses soon after a killed one. // Tried again when a run is cut off (its worker killed by a deploy, or the timeout): a run that fails part-way marks // the build failed itself and doesn't come back here. The first retry waits out a killed run's hold on the build -// (`processing::HOLD_SECONDS`). The sweep re-runs builds stuck in processing as well. +// (`processing::HOLD_SECONDS`). The sweep re-runs builds stuck in processing as well. One try more than +// `processing::RUNS`: a run killed on its last try (out of memory) leaves the next one to fail the build saying so +// (`processing::give_up`), rather than the queue failing the job for its tries alone. #[job( name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds(), timeout = 15.minutes(), - tries = 3, + tries = 4, backoff = [90.seconds(), 5.minutes()] )] impl ProcessBuild { @@ -30,7 +32,13 @@ impl ProcessBuild { self.build_id } - async fn handle(self) -> laravel::Result<()> { + async fn handle(self, attempt: &Attempt) -> laravel::Result<()> { + if attempt.number() > processing::RUNS { + if let Some(error) = processing::give_up(self.build_id).await? { + attempt.fail(laravel::Error::msg(error)); + } + return Ok(()); + } // A deploy's SIGTERM stops the run between snapshots and queues the build again (`domain::shutdown`). crate::domain::shutdown::watch(); let store = BlobStore::current().await?; diff --git a/app/tests/processing_lock.rs b/app/tests/processing_lock.rs index 54dc3bba8..4fa86476e 100644 --- a/app/tests/processing_lock.rs +++ b/app/tests/processing_lock.rs @@ -43,3 +43,90 @@ async fn a_killed_runs_hold_lapses(_app: Application) -> laravel::Result<()> { processing::exclusive_with(build_id, 0, SHORT, || async { Ok(()) }).await?; Ok(()) } + +/// A build left processing, as a killed run leaves it. +async fn processing_build() -> laravel::Result { + use app::domain::builds::{self, CreateParams}; + let org = + app::testing::fixtures::organization(&format!("oom-{}", &laravel::str::uuid7().simple().to_string()[24..])) + .await?; + let project = app::testing::fixtures::project(&org, "web").await?; + let params: CreateParams = serde_json::from_value(serde_json::json!({ "commit": "c1", "branch": "main" }))?; + let build = builds::create(&project, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + let id = build.id; + laravel::db::query!("UPDATE builds SET state = 'processing', finalized_at = now() WHERE id = {id}") + .update() + .await?; + app::models::Build::find_or_fail(id).await +} + +/// VISUALCI-PROD-SERVER-6: a run killed for running out of memory leaves its mark, the next run that takes the build +/// counts it, and once `processing::RUNS` runs have died the build fails saying why, rather than kill another worker. +#[laravel::test] +async fn runs_that_die_are_counted_and_the_build_fails_saying_its_worker_ran_out_of_memory( + _app: Application, +) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + assert_eq!(processing::note_run_start(id).await?, 0, "the first run"); + // It died (no `note_run_end`): the next run finds its mark, and so on. + assert_eq!(processing::note_run_start(id).await?, 1); + assert_eq!(processing::note_run_start(id).await?, 2); + // The third died too: the next run (a retry, or the sweep's) fails the build instead of processing it. + let store = app::testing::fixtures::blob_store().await?; + processing::run(id, &store, "test").await?; + let failed = app::models::Build::find_or_fail(id).await?; + let want = format!("the worker ran out of memory (or was killed) processing build #{}, 3 times", build.number); + assert_eq!((failed.state.as_str(), failed.error.as_deref()), ("failed", Some(want.as_str()))); + assert_eq!(processing::note_run_start(id).await?, 0, "the count starts again"); + Ok(()) +} + +/// The job's try past `processing::RUNS` (its last allowed by `tries`) fails the build and the job with the same error: +/// the worker ran out of memory, not "attempted more than its tries allow". +#[laravel::test] +async fn a_retry_past_its_tries_fails_the_build_saying_its_worker_died(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + processing::note_run_start(id).await?; + processing::note_run_start(id).await?; + let error = processing::give_up(id).await?.expect("the build was processing"); + assert_eq!( + error, + format!("the worker ran out of memory (or was killed) processing build #{}, 2 times", build.number) + ); + let failed = app::models::Build::find_or_fail(id).await?; + assert_eq!((failed.state.as_str(), failed.error.as_deref()), ("failed", Some(error.as_str()))); + assert_eq!(processing::give_up(id).await?, None, "a build that isn't processing is left alone"); + + // Tries that ended without dying (none left a mark) say only that. + let other = processing_build().await?; + let error = processing::give_up(other.id).await?.expect("processing"); + assert_eq!(error, format!("processing build #{} didn't finish in its 3 tries", other.number)); + Ok(()) +} + +/// A run that finishes clears the marks: one killed run before it doesn't count against the build's next runs. +#[laravel::test] +async fn a_run_that_finishes_forgets_the_runs_that_died(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + processing::note_run_start(id).await?; + let store = app::testing::fixtures::blob_store().await?; + processing::run(id, &store, "test").await?; + assert_ne!(app::models::Build::find_or_fail(id).await?.state, "processing", "an empty build concludes"); + assert_eq!(processing::note_run_start(id).await?, 0); + Ok(()) +} + +/// A run another job started holds the build: the try past its tries leaves it to that run. +#[laravel::test] +async fn giving_up_leaves_a_build_another_run_is_processing(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + let live = laravel::cache::lock(&format!("builds.process:{id}"), 30.seconds())?; + assert!(live.acquire().await?, "the live run took the build"); + assert_eq!(processing::give_up(id).await?, None); + assert_eq!(app::models::Build::find_or_fail(id).await?.state, "processing"); + Ok(()) +} diff --git a/clients/circleci-orb/orb.yml b/clients/circleci-orb/orb.yml index 9e84fc092..bb3876e55 100644 --- a/clients/circleci-orb/orb.yml +++ b/clients/circleci-orb/orb.yml @@ -15,8 +15,8 @@ commands: parameters: version: type: string - default: "0.2.29" - description: The CLI release to install, such as 0.2.29. Pin it, so a new release never changes a build. + default: "0.2.30" + description: The CLI release to install, such as 0.2.30. Pin it, so a new release never changes a build. install-dir: type: string default: $HOME/.local/bin @@ -70,7 +70,7 @@ commands: description: Fail the step when VisualCI can't be reached. By default it only reports. version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> @@ -117,7 +117,7 @@ commands: default: false version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> @@ -160,7 +160,7 @@ jobs: default: false version: type: string - default: "0.2.29" + default: "0.2.30" steps: - install: version: << parameters.version >> diff --git a/clients/github-action/action.yml b/clients/github-action/action.yml index 9b49afc8f..f09e160ac 100644 --- a/clients/github-action/action.yml +++ b/clients/github-action/action.yml @@ -45,7 +45,7 @@ inputs: The visualci CLI release to install. Default: the release this tag of the action came with, so @v0 installs the newest. Pin it to keep a release from changing a build. required: false - default: "0.2.29" + default: "0.2.30" cli: description: A visualci binary to use instead of installing a release (VisualCI's own CI tests its latest CLI). required: false diff --git a/crates/visualci-core/Cargo.toml b/crates/visualci-core/Cargo.toml index 647e9fd8c..8ef5eb342 100644 --- a/crates/visualci-core/Cargo.toml +++ b/crates/visualci-core/Cargo.toml @@ -11,6 +11,7 @@ globset.workspace = true hex.workspace = true image.workspace = true lopdf.workspace = true +png.workspace = true schemars.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/visualci-core/examples/compare_memory.rs b/crates/visualci-core/examples/compare_memory.rs new file mode 100644 index 000000000..4424fa9c8 --- /dev/null +++ b/crates/visualci-core/examples/compare_memory.rs @@ -0,0 +1,150 @@ +//! Peak memory of an image comparison, for tall full-page screenshots (VISUALCI-PROD-SERVER-6). +//! +//! `cargo run --release -p visualci-core --example compare_memory -- gen [width] [height]` writes base.png and +//! head.png (a screenshot-like page and the same page with a small change); `... -- run +//! [repeats] [exact|browser]` compares them `repeats` times, each on another of eight threads (as the server's +//! blocking pool does), and prints the peak resident memory (VmHWM). Run it under `MALLOC_ARENA_MAX=2` or with +//! another allocator preloaded to compare allocators. + +use std::io::Cursor; + +use image::{Rgb, RgbImage}; +use visualci_core::diff::DiffOptions; + +fn status(field: &str) -> String { + let s = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + s.lines() + .find(|l| l.starts_with(field)) + .map(|l| l.split_whitespace().nth(1).unwrap_or("").to_string()) + .unwrap_or_default() +} + +fn mib(kb: &str) -> String { + format!("{:.0} MiB", kb.parse::().unwrap_or(0.0) / 1024.0) +} + +/// A page: white, with lines of dark "words", a few coloured blocks and a gradient band. +fn page(width: u32, height: u32) -> RgbImage { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rand = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut img = RgbImage::from_pixel(width, height, Rgb([255, 255, 255])); + let mut y = 40; + while y + 30 < height { + if rand() % 9 == 0 { + let (h, c) = (120 + (rand() % 200) as u32, Rgb([(rand() % 255) as u8, (rand() % 255) as u8, 200])); + for yy in y..(y + h).min(height) { + for x in 80..width - 80 { + img.put_pixel(x, yy, if (x / 7 + yy / 5) % 11 == 0 { Rgb([255, 255, 255]) } else { c }); + } + } + y += h + 30; + continue; + } + let mut x = 80 + (rand() % 40) as u32; + while x + 60 < width - 80 { + let w = 20 + (rand() % 90) as u32; + for yy in y..y + 14 { + for xx in x..x + w { + let v = 30 + ((xx * 31 + yy * 17) % 50) as u8; + img.put_pixel(xx, yy, Rgb([v, v, v.saturating_add(10)])); + } + } + x += w + 10 + (rand() % 8) as u32; + } + y += 28; + } + img +} + +fn png(img: &RgbImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +fn compare(base: &[u8], head: &[u8], options: DiffOptions) -> (u64, usize) { + let (outcome, overlay) = visualci_core::diff::diff_files(base, head, options, &Default::default()).unwrap(); + // OVERLAY_OUT= keeps the overlay and the result, to check two versions give the same pixels. + if let (Ok(path), Some(png)) = (std::env::var("OVERLAY_OUT"), &overlay) { + std::fs::write(&path, png).unwrap(); + std::fs::write(format!("{path}.json"), serde_json::to_string(&outcome).unwrap()).unwrap(); + } + (outcome.changed_pixels, overlay.map_or(0, |p| p.len())) +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("gen") => { + let dir = std::path::Path::new(&args[1]); + let width = args.get(2).map_or(2880, |a| a.parse().unwrap()); + let height = args.get(3).map_or(14_000, |a| a.parse().unwrap()); + let base = page(width, height); + let mut head = base.clone(); + // A changed button near the bottom and a one-pixel nudge near the top. + for y in height - 900..height - 860 { + for x in 200..600 { + head.put_pixel(x, y, Rgb([220, 40, 40])); + } + } + head.put_pixel(300, 300, Rgb([0, 0, 0])); + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("base.png"), png(&base)).unwrap(); + std::fs::write(dir.join("head.png"), png(&head)).unwrap(); + } + Some("run") => { + let base = std::fs::read(&args[1]).unwrap(); + let head = std::fs::read(&args[2]).unwrap(); + let repeats: usize = args.get(3).map_or(1, |a| a.parse().unwrap()); + let options = if args.get(4).map(String::as_str) == Some("exact") { + DiffOptions::EXACT + } else { + DiffOptions::BROWSER + }; + println!("files: {} + {} bytes; start VmHWM {}", base.len(), head.len(), mib(&status("VmHWM:"))); + let (base, head) = (std::sync::Arc::new(base), std::sync::Arc::new(head)); + let started = std::time::Instant::now(); + // Eight long-lived threads, as tokio's blocking pool keeps; each compare runs on the next one. + let workers: Vec<_> = (0..8) + .map(|_| { + let (tx, rx) = std::sync::mpsc::channel::<(std::sync::mpsc::Sender<(u64, usize)>,)>(); + let (base, head) = (base.clone(), head.clone()); + std::thread::spawn(move || { + for (reply,) in rx { + reply.send(compare(&base, &head, options)).unwrap(); + } + }); + tx + }) + .collect(); + for i in 0..repeats { + let (tx, rx) = std::sync::mpsc::channel(); + workers[i % 8].send((tx,)).unwrap(); + let (changed, overlay) = rx.recv().unwrap(); + println!( + "compare {i}: {changed} changed pixels, overlay {overlay} bytes, VmRSS {}, VmHWM {}", + mib(&status("VmRSS:")), + mib(&status("VmHWM:")) + ); + } + println!( + "{repeats} compares in {:.1}s; peak VmHWM {}", + started.elapsed().as_secs_f64(), + mib(&status("VmHWM:")) + ); + } + Some("same") => { + let a = image::open(&args[1]).unwrap().to_rgba8(); + let b = image::open(&args[2]).unwrap().to_rgba8(); + println!("same pixels: {}", a.dimensions() == b.dimensions() && a.as_raw() == b.as_raw()); + } + _ => eprintln!( + "usage: compare_memory gen [width] [height] | run [repeats] [exact|browser] | same " + ), + } +} diff --git a/crates/visualci-core/src/diff.rs b/crates/visualci-core/src/diff.rs index a90ea14a4..049f0bb85 100644 --- a/crates/visualci-core/src/diff.rs +++ b/crates/visualci-core/src/diff.rs @@ -17,6 +17,8 @@ //! they hid. use image::{Rgba, RgbaImage}; + +use crate::image_hash::{Rows, WHOLE_DECODES}; use serde::{Deserialize, Serialize}; pub const ALGORITHM: &str = "vci-diff-1"; @@ -97,27 +99,191 @@ pub fn diff_masked( options: DiffOptions, masked: &[Region], ) -> (DiffResult, RgbaImage) { - let width = base.width().max(head.width()); - let height = base.height().max(head.height()); - let mut mask = vec![false; (width as usize) * (height as usize)]; - for r in masked { - for y in r.y..(r.y.saturating_add(r.height)).min(height) { - for x in r.x..(r.x.saturating_add(r.width)).min(width) { - mask[(y * width + x) as usize] = true; + let (width, height) = (base.width().max(head.width()), base.height().max(head.height())); + let mut overlay = Vec::with_capacity(width as usize * height as usize * 4); + let result = diff_rows(&mut Whole(base), &mut Whole(head), options, masked, |row| { + overlay.extend_from_slice(row); + Ok(()) + }); + let Ok(result) = result else { unreachable!("an image in memory has every row") }; + let overlay = RgbaImage::from_raw(width, height, overlay).expect("a row for every line of the canvas"); + (result, overlay) +} + +/// Decode two image files and diff them ([`diff_masked`], with `mask` resolved against their canvas). The overlay comes +/// as a PNG, unless the images are identical. +/// +/// The images are read a row at a time ([`Rows`]) and the overlay written the same way, so a tall full-page screenshot +/// costs a few rows of memory, not three full-size images and a PNG encoder's copy (VISUALCI-PROD-SERVER-6: a +/// 2880x14000 pair took over 600 MB). Files that can't be read a row at a time are decoded whole, one comparison at a +/// time in the process ([`WHOLE_DECODES`]). The result and the overlay's pixels are exactly [`diff_masked`]'s. +/// +/// # Errors +/// When a file isn't an image [`crate::image_hash::decode`] reads (its error), or the overlay can't be encoded. +pub fn diff_files( + base: &[u8], + head: &[u8], + options: DiffOptions, + mask: &crate::config::ImageMask, +) -> Result<(DiffResult, Option>), image::ImageError> { + let whole = || WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let streamed = { + let _whole = (!Rows::streams(base) || !Rows::streams(head)).then(whole); + diff_streams(Rows::open(base)?, Rows::open(head)?, options, mask) + }; + match streamed { + Ok(done) => Ok(done), + // The streaming decoder gave up part-way through a file: decode both whole, as before, for the image crate's + // own answer (its pixels, or its error). + Err(Failed::Rows) => { + let _whole = whole(); + diff_streams(Rows::decoded(base)?, Rows::decoded(head)?, options, mask).map_err(|e| match e { + Failed::Rows => image::ImageError::IoError(std::io::Error::other("a decoded image's rows failed")), + Failed::Encode(e) => image::ImageError::IoError(e), + }) + } + Err(Failed::Encode(e)) => Err(image::ImageError::IoError(e)), + } +} + +#[derive(Debug)] +enum Failed { + Rows, + Encode(std::io::Error), +} + +fn diff_streams( + base: Rows<'_>, + head: Rows<'_>, + options: DiffOptions, + mask: &crate::config::ImageMask, +) -> Result<(DiffResult, Option>), Failed> { + let (width, height) = (base.width().max(head.width()), base.height().max(head.height())); + let masked = mask.resolve(width, height); + let mut png = Vec::new(); + let mut encoder = png::Encoder::new(&mut png, width, height); + // The image crate's PNG encoder's settings (`PngEncoder::new`), which wrote the overlays before. + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.set_compression(png::Compression::Fast); + encoder.set_filter(png::Filter::Adaptive); + let encode = |e: png::EncodingError| Failed::Encode(std::io::Error::other(e)); + let mut writer = encoder.write_header().map_err(encode)?; + let mut stream = writer.stream_writer_with_size(1 << 16).map_err(encode)?; + let result = diff_rows(&mut Window::new(base), &mut Window::new(head), options, &masked, |row| { + std::io::Write::write_all(&mut stream, row).map_err(Failed::Encode) + })?; + stream.finish().map_err(encode)?; + writer.finish().map_err(encode)?; + let identical = result.is_identical(); + Ok((result, (!identical).then_some(png))) +} + +/// An image the diff reads pixels from: whole in memory, or a window of rows read from a file. +trait Pixels { + fn width(&self) -> u32; + fn height(&self) -> u32; + /// The pixel at (x, y), inside the image, and within two rows of the row last [`Pixels::prepare`]d. + fn get(&self, x: u32, y: u32) -> Rgba; + /// Make the rows up to two below `y` readable (the anti-aliasing test looks two rows away). + fn prepare(&mut self, y: u32) -> Result<(), Failed>; +} + +struct Whole<'a>(&'a RgbaImage); + +impl Pixels for Whole<'_> { + fn width(&self) -> u32 { + self.0.width() + } + fn height(&self) -> u32 { + self.0.height() + } + fn get(&self, x: u32, y: u32) -> Rgba { + *self.0.get_pixel(x, y) + } + fn prepare(&mut self, _: u32) -> Result<(), Failed> { + Ok(()) + } +} + +/// The rows a diff of row `y` reads: `y - 2` to `y + 2`, in a ring of five. +const WINDOW: u32 = 5; + +struct Window<'a> { + rows: Rows<'a>, + buf: Vec, + /// How many rows have been read. + loaded: u32, +} + +impl<'a> Window<'a> { + fn new(rows: Rows<'a>) -> Self { + let buf = vec![0; rows.width() as usize * 4 * WINDOW as usize]; + Self { rows, buf, loaded: 0 } + } +} + +impl Pixels for Window<'_> { + fn width(&self) -> u32 { + self.rows.width() + } + fn height(&self) -> u32 { + self.rows.height() + } + fn get(&self, x: u32, y: u32) -> Rgba { + debug_assert!(y < self.loaded && y + WINDOW >= self.loaded, "row {y} outside the window"); + let line = self.rows.width() as usize * 4; + let at = (y % WINDOW) as usize * line + x as usize * 4; + Rgba([self.buf[at], self.buf[at + 1], self.buf[at + 2], self.buf[at + 3]]) + } + fn prepare(&mut self, y: u32) -> Result<(), Failed> { + let through = y.saturating_add(3).min(self.rows.height()); + let line = self.rows.width() as usize * 4; + while self.loaded < through { + let row = self.rows.next_row().map_err(|_| Failed::Rows)?; + let at = (self.loaded % WINDOW) as usize * line; + self.buf[at..at + line].copy_from_slice(row); + self.loaded += 1; + if self.loaded == self.rows.height() { + self.rows.finish().map_err(|_| Failed::Rows)?; } } + Ok(()) } - let size_changed = base.dimensions() != head.dimensions(); +} + +/// The diff, row by row: each row of the overlay goes to `out` as it's made, and only the changed-tile map (a bit for +/// each 16 px tile) is kept for the regions and fingerprint. +fn diff_rows( + base: &mut B, + head: &mut H, + options: DiffOptions, + masked: &[Region], + mut out: impl FnMut(&[u8]) -> Result<(), Failed>, +) -> Result { + let width = base.width().max(head.width()); + let height = base.height().max(head.height()); + let size_changed = (base.width(), base.height()) != (head.width(), head.height()); let max_delta = 35215.0 * options.threshold * options.threshold; let exact = options.threshold <= 0.0; - let mut overlay = RgbaImage::new(width, height); - let mut changed = vec![false; (width as usize) * (height as usize)]; + let tw = width.div_ceil(TILE); + let mut tiles = vec![false; (tw * height.div_ceil(TILE)) as usize]; + let mut mask = vec![false; width as usize]; + let mut row = vec![0u8; width as usize * 4]; let mut changed_pixels = 0u64; let mut anti_aliased_pixels = 0u64; let mut masked_pixels = 0u64; for y in 0..height { + base.prepare(y)?; + head.prepare(y)?; + mask.fill(false); + for r in masked { + if y >= r.y && y < r.y.saturating_add(r.height) { + mask[r.x.min(width) as usize..r.x.saturating_add(r.width).min(width) as usize].fill(true); + } + } for x in 0..width { let a = pixel(base, x, y); let b = pixel(head, x, y); @@ -143,13 +309,13 @@ pub fn diff_masked( // Outside one of the images: the canvas grew or shrank there. _ => (true, false), }; - let out = if mask[(y * width + x) as usize] { + let px = if mask[x as usize] { if is_changed || is_aa { masked_pixels += 1; } hatched(shown, x, y) } else if is_changed { - changed[(y * width + x) as usize] = true; + tiles[((y / TILE) * tw + x / TILE) as usize] = true; changed_pixels += 1; Rgba([255, 0, 0, 255]) } else if is_aa { @@ -158,19 +324,19 @@ pub fn diff_masked( } else { faded(shown) }; - overlay.put_pixel(x, y, out); + row[x as usize * 4..x as usize * 4 + 4].copy_from_slice(&px.0); } + out(&row)?; } let total = (width as u64 * height as u64).max(1); let (regions, fingerprint) = if changed_pixels == 0 { (Vec::new(), None) } else { - let tiles = tile_map(&changed, width, height); (regions(&tiles, width, height), Some(tile_fingerprint(&tiles, width, height))) }; - let result = DiffResult { + Ok(DiffResult { algorithm: ALGORITHM.to_string(), width, height, @@ -182,8 +348,7 @@ pub fn diff_masked( fingerprint, masked: masked.to_vec(), masked_pixels, - }; - (result, overlay) + }) } /// A masked pixel in the overlay: diagonal grey stripes over the faded image. @@ -191,8 +356,8 @@ fn hatched(p: Rgba, x: u32, y: u32) -> Rgba { if (x + y) % 12 < 3 { Rgba([112, 120, 136, 255]) } else { faded(p) } } -fn pixel(img: &RgbaImage, x: u32, y: u32) -> Option> { - (x < img.width() && y < img.height()).then(|| *img.get_pixel(x, y)) +fn pixel(img: &impl Pixels, x: u32, y: u32) -> Option> { + (x < img.width() && y < img.height()).then(|| img.get(x, y)) } fn faded(p: Rgba) -> Rgba { @@ -203,20 +368,6 @@ fn faded(p: Rgba) -> Rgba { Rgba([v, v, v, 255]) } -fn tile_map(changed: &[bool], width: u32, height: u32) -> Vec { - let tw = width.div_ceil(TILE); - let th = height.div_ceil(TILE); - let mut tiles = vec![false; (tw * th) as usize]; - for y in 0..height { - for x in 0..width { - if changed[(y * width + x) as usize] { - tiles[((y / TILE) * tw + x / TILE) as usize] = true; - } - } - } - tiles -} - fn tile_fingerprint(tiles: &[bool], width: u32, height: u32) -> String { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); @@ -322,17 +473,17 @@ fn color_delta(p1: Rgba, p2: Rgba, y_only: bool) -> f64 { if y1 > y2 { -delta } else { delta } } -fn neighbours(img: &RgbaImage, x: u32, y: u32) -> (u32, u32, u32, u32) { +fn neighbours(img: &impl Pixels, x: u32, y: u32) -> (u32, u32, u32, u32) { (x.saturating_sub(1), y.saturating_sub(1), (x + 1).min(img.width() - 1), (y + 1).min(img.height() - 1)) } /// pixelmatch's anti-aliasing test: is (x, y) in `img` likely an anti-aliased edge pixel? -fn antialiased(img: &RgbaImage, x1: u32, y1: u32, other: &RgbaImage) -> bool { +fn antialiased(img: &impl Pixels, x1: u32, y1: u32, other: &impl Pixels) -> bool { if x1 >= img.width() || y1 >= img.height() || x1 >= other.width() || y1 >= other.height() { return false; } let (x0, y0, x2, y2) = neighbours(img, x1, y1); - let centre = *img.get_pixel(x1, y1); + let centre = img.get(x1, y1); let mut zeroes = u32::from(x1 == x0 || x1 == x2 || y1 == y0 || y1 == y2); let (mut min, mut max) = (0.0f64, 0.0f64); let (mut min_at, mut max_at) = ((0, 0), (0, 0)); @@ -341,7 +492,7 @@ fn antialiased(img: &RgbaImage, x1: u32, y1: u32, other: &RgbaImage) -> bool { if x == x1 && y == y1 { continue; } - let delta = color_delta(centre, *img.get_pixel(x, y), true); + let delta = color_delta(centre, img.get(x, y), true); if delta == 0.0 { zeroes += 1; if zeroes > 2 { @@ -363,19 +514,19 @@ fn antialiased(img: &RgbaImage, x1: u32, y1: u32, other: &RgbaImage) -> bool { || (has_many_siblings(img, max_at.0, max_at.1) && has_many_siblings(other, max_at.0, max_at.1)) } -fn has_many_siblings(img: &RgbaImage, x1: u32, y1: u32) -> bool { +fn has_many_siblings(img: &impl Pixels, x1: u32, y1: u32) -> bool { if x1 >= img.width() || y1 >= img.height() { return false; } let (x0, y0, x2, y2) = neighbours(img, x1, y1); - let centre = *img.get_pixel(x1, y1); + let centre = img.get(x1, y1); let mut zeroes = u32::from(x1 == x0 || x1 == x2 || y1 == y0 || y1 == y2); for x in x0..=x2 { for y in y0..=y2 { if x == x1 && y == y1 { continue; } - if *img.get_pixel(x, y) == centre { + if img.get(x, y) == centre { zeroes += 1; } if zeroes > 2 { @@ -390,10 +541,337 @@ fn has_many_siblings(img: &RgbaImage, x1: u32, y1: u32) -> bool { mod tests { use super::*; + /// The diff as it was before it read images a row at a time (VISUALCI-PROD-SERVER-6), kept as the oracle the + /// streaming diff must match exactly. + mod reference { + use super::super::*; + + pub fn diff_masked( + base: &RgbaImage, + head: &RgbaImage, + options: DiffOptions, + masked: &[Region], + ) -> (DiffResult, RgbaImage) { + let width = base.width().max(head.width()); + let height = base.height().max(head.height()); + let mut mask = vec![false; (width as usize) * (height as usize)]; + for r in masked { + for y in r.y..(r.y.saturating_add(r.height)).min(height) { + for x in r.x..(r.x.saturating_add(r.width)).min(width) { + mask[(y * width + x) as usize] = true; + } + } + } + let size_changed = base.dimensions() != head.dimensions(); + let max_delta = 35215.0 * options.threshold * options.threshold; + let exact = options.threshold <= 0.0; + + let mut overlay = RgbaImage::new(width, height); + let mut changed = vec![false; (width as usize) * (height as usize)]; + let mut changed_pixels = 0u64; + let mut anti_aliased_pixels = 0u64; + let mut masked_pixels = 0u64; + + for y in 0..height { + for x in 0..width { + let a = pixel(base, x, y); + let b = pixel(head, x, y); + let shown = b.or(a).unwrap_or(Rgba([255, 255, 255, 255])); + let (is_changed, is_aa) = match (a, b) { + (Some(a), Some(b)) if a == b => (false, false), + (Some(a), Some(b)) => { + if exact { + (true, false) + } else { + let delta = color_delta(a, b, false); + if delta.abs() <= max_delta { + (false, false) + } else if options.ignore_anti_aliasing + && (antialiased(base, x, y, head) || antialiased(head, x, y, base)) + { + (false, true) + } else { + (true, false) + } + } + } + // Outside one of the images: the canvas grew or shrank there. + _ => (true, false), + }; + let out = if mask[(y * width + x) as usize] { + if is_changed || is_aa { + masked_pixels += 1; + } + hatched(shown, x, y) + } else if is_changed { + changed[(y * width + x) as usize] = true; + changed_pixels += 1; + Rgba([255, 0, 0, 255]) + } else if is_aa { + anti_aliased_pixels += 1; + Rgba([255, 200, 0, 255]) + } else { + faded(shown) + }; + overlay.put_pixel(x, y, out); + } + } + + let total = (width as u64 * height as u64).max(1); + let (regions, fingerprint) = if changed_pixels == 0 { + (Vec::new(), None) + } else { + let tiles = tile_map(&changed, width, height); + (regions(&tiles, width, height), Some(tile_fingerprint(&tiles, width, height))) + }; + + let result = DiffResult { + algorithm: ALGORITHM.to_string(), + width, + height, + size_changed, + changed_pixels, + changed_fraction: changed_pixels as f64 / total as f64, + anti_aliased_pixels, + regions, + fingerprint, + masked: masked.to_vec(), + masked_pixels, + }; + (result, overlay) + } + + fn pixel(img: &RgbaImage, x: u32, y: u32) -> Option> { + (x < img.width() && y < img.height()).then(|| *img.get_pixel(x, y)) + } + + fn tile_map(changed: &[bool], width: u32, height: u32) -> Vec { + let tw = width.div_ceil(TILE); + let th = height.div_ceil(TILE); + let mut tiles = vec![false; (tw * th) as usize]; + for y in 0..height { + for x in 0..width { + if changed[(y * width + x) as usize] { + tiles[((y / TILE) * tw + x / TILE) as usize] = true; + } + } + } + tiles + } + + fn neighbours(img: &RgbaImage, x: u32, y: u32) -> (u32, u32, u32, u32) { + (x.saturating_sub(1), y.saturating_sub(1), (x + 1).min(img.width() - 1), (y + 1).min(img.height() - 1)) + } + + fn antialiased(img: &RgbaImage, x1: u32, y1: u32, other: &RgbaImage) -> bool { + if x1 >= img.width() || y1 >= img.height() || x1 >= other.width() || y1 >= other.height() { + return false; + } + let (x0, y0, x2, y2) = neighbours(img, x1, y1); + let centre = *img.get_pixel(x1, y1); + let mut zeroes = u32::from(x1 == x0 || x1 == x2 || y1 == y0 || y1 == y2); + let (mut min, mut max) = (0.0f64, 0.0f64); + let (mut min_at, mut max_at) = ((0, 0), (0, 0)); + for x in x0..=x2 { + for y in y0..=y2 { + if x == x1 && y == y1 { + continue; + } + let delta = color_delta(centre, *img.get_pixel(x, y), true); + if delta == 0.0 { + zeroes += 1; + if zeroes > 2 { + return false; + } + } else if delta < min { + min = delta; + min_at = (x, y); + } else if delta > max { + max = delta; + max_at = (x, y); + } + } + } + if min == 0.0 || max == 0.0 { + return false; + } + (has_many_siblings(img, min_at.0, min_at.1) && has_many_siblings(other, min_at.0, min_at.1)) + || (has_many_siblings(img, max_at.0, max_at.1) && has_many_siblings(other, max_at.0, max_at.1)) + } + + fn has_many_siblings(img: &RgbaImage, x1: u32, y1: u32) -> bool { + if x1 >= img.width() || y1 >= img.height() { + return false; + } + let (x0, y0, x2, y2) = neighbours(img, x1, y1); + let centre = *img.get_pixel(x1, y1); + let mut zeroes = u32::from(x1 == x0 || x1 == x2 || y1 == y0 || y1 == y2); + for x in x0..=x2 { + for y in y0..=y2 { + if x == x1 && y == y1 { + continue; + } + if *img.get_pixel(x, y) == centre { + zeroes += 1; + } + if zeroes > 2 { + return true; + } + } + } + false + } + } + fn white(w: u32, h: u32) -> RgbaImage { RgbaImage::from_pixel(w, h, Rgba([255, 255, 255, 255])) } + /// A page-like image: flat blocks with soft (anti-aliased) edges, some see-through pixels, and noise. + fn sample(w: u32, h: u32, seed: u64) -> RgbaImage { + let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + let mut rand = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut img = white(w, h); + for _ in 0..(w * h / 40).max(3) { + let (x0, y0) = ((rand() % u64::from(w)) as u32, (rand() % u64::from(h)) as u32); + let (bw, bh) = (1 + (rand() % 9) as u32, 1 + (rand() % 5) as u32); + let v = (rand() % 256) as u8; + let colour = match rand() % 4 { + 0 => Rgba([v, v, v, 255]), + 1 => Rgba([v, 255 - v, 90, 255]), + 2 => Rgba([v, v, v, (rand() % 256) as u8]), + _ => Rgba([0, 0, 0, 255]), + }; + for y in y0..(y0 + bh).min(h) { + for x in x0..(x0 + bw).min(w) { + let edge = x == x0 || y == y0 || x + 1 == x0 + bw || y + 1 == y0 + bh; + let c = if edge { + let [r, g, b, a] = colour.0; + Rgba([r / 2 + 127, g / 2 + 127, b / 2 + 127, a]) + } else { + colour + }; + img.put_pixel(x, y, c); + } + } + } + img + } + + /// `base` changed: some pixels shifted by one (as anti-aliasing moves), some faintly, some blocks replaced, at the + /// canvas size given. + fn changed(base: &RgbaImage, w: u32, h: u32, seed: u64) -> RgbaImage { + let other = sample(w, h, seed + 1000); + let mut head = white(w, h); + for y in 0..h { + for x in 0..w { + let p = + if x < base.width() && y < base.height() { *base.get_pixel(x, y) } else { *other.get_pixel(x, y) }; + let pick = (x * 7 + y * 13 + seed as u32) % 97; + let p = match pick { + 0..=2 if x + 1 < base.width() && y < base.height() => *base.get_pixel(x + 1, y), + 3 => Rgba([p.0[0].saturating_sub(4), p.0[1], p.0[2], p.0[3]]), + 4 => *other.get_pixel(x, y), + _ => p, + }; + head.put_pixel(x, y, p); + } + } + head + } + + fn png_of(img: &RgbaImage, rgb: bool) -> Vec { + let mut out = Vec::new(); + if rgb { + image::DynamicImage::ImageRgba8(img.clone()) + .to_rgb8() + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + } else { + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + } + out + } + + #[test] + fn the_row_by_row_diff_matches_the_whole_image_diff_exactly() { + use crate::config::{Edges, ImageMask, Rect}; + let sizes = + [((40, 30), (40, 30)), ((37, 52), (37, 49)), ((64, 64), (70, 60)), ((1, 9), (1, 9)), ((9, 1), (9, 2))]; + let options = [ + DiffOptions::EXACT, + DiffOptions::BROWSER, + DiffOptions { threshold: 0.05, ignore_anti_aliasing: false }, + DiffOptions { threshold: 0.3, ignore_anti_aliasing: true }, + ]; + let masks = [ + ImageMask::default(), + ImageMask { edges: vec![], rects: vec![Rect { x: 5, y: 3, width: 20, height: 8 }] }, + ImageMask { + edges: vec![Edges { top: Some(4), bottom: None, left: None, right: Some(6) }], + rects: vec![Rect { x: 50, y: 50, width: 100, height: 100 }], + }, + ]; + let (mut cases, mut seen_aa, mut seen_masked, mut seen_changed) = (0, false, false, false); + for (seed, &((bw, bh), (hw, hh))) in sizes.iter().enumerate() { + let base = sample(bw, bh, seed as u64); + let head = changed(&base, hw, hh, seed as u64); + for rgb in [false, true] { + let (base_png, head_png) = (png_of(&base, rgb), png_of(&head, rgb)); + let decode = |b: &[u8]| crate::image_hash::decode(b).unwrap().to_rgba8(); + let (base_px, head_px) = (decode(&base_png), decode(&head_png)); + for o in options { + for mask in &masks { + let masked = mask.resolve(bw.max(hw), bh.max(hh)); + let (want, want_overlay) = reference::diff_masked(&base_px, &head_px, o, &masked); + let want_json = serde_json::to_string(&want).unwrap(); + seen_aa |= want.anti_aliased_pixels > 0; + seen_masked |= want.masked_pixels > 0; + seen_changed |= want.changed_pixels > 0; + + let (got, overlay) = diff_masked(&base_px, &head_px, o, &masked); + assert_eq!(serde_json::to_string(&got).unwrap(), want_json); + assert_eq!(overlay.as_raw(), want_overlay.as_raw()); + + let (got, png) = diff_files(&base_png, &head_png, o, mask).unwrap(); + assert_eq!(serde_json::to_string(&got).unwrap(), want_json, "{bw}x{bh} {o:?} {mask:?}"); + assert_eq!(png.is_some(), !want.is_identical()); + if let Some(png) = png { + assert_eq!(decode(&png).as_raw(), want_overlay.as_raw(), "{bw}x{bh} {o:?} {mask:?}"); + } + cases += 1; + } + } + } + } + assert_eq!(cases, 5 * 2 * 4 * 3); + assert!(seen_aa && seen_masked && seen_changed, "the cases cover anti-aliasing, masks and changes"); + } + + #[test] + fn identical_files_have_no_overlay_and_a_bad_file_is_the_decoders_error() { + let img = sample(30, 20, 7); + let png = png_of(&img, false); + let (r, overlay) = diff_files(&png, &png, DiffOptions::EXACT, &Default::default()).unwrap(); + assert!(r.is_identical() && overlay.is_none()); + + // A truncated PNG (in its pixels, or just its end): its header streams, the rest doesn't. The error is the image + // crate's, as before. + for n in [30, 12] { + let cut = &png[..png.len() - n]; + let want = crate::image_hash::decode(cut).map(|_| ()).unwrap_err().to_string(); + let got = + diff_files(&png, cut, DiffOptions::EXACT, &Default::default()).map(|_| ()).unwrap_err().to_string(); + assert_eq!(got, want); + } + assert!(diff_files(b"not an image", &png, DiffOptions::EXACT, &Default::default()).is_err()); + } + #[test] fn identical_images() { let (r, _) = diff(&white(40, 40), &white(40, 40), DiffOptions::EXACT); diff --git a/crates/visualci-core/src/image_hash.rs b/crates/visualci-core/src/image_hash.rs index 4e61b4da4..108d9b10a 100644 --- a/crates/visualci-core/src/image_hash.rs +++ b/crates/visualci-core/src/image_hash.rs @@ -36,7 +36,177 @@ pub fn decode(bytes: &[u8]) -> Result { /// Decode an image file (PNG, JPEG, WebP) and fingerprint its pixels. pub fn fingerprint_bytes(bytes: &[u8]) -> Result { - Ok(fingerprint_rgba(&decode(bytes)?.to_rgba8())) + Ok(info(bytes)?.0) +} + +/// An image file's pixel fingerprint (the same as [`fingerprint_rgba`] of its decoded pixels), width and height, read +/// a row at a time ([`Rows`]): a tall screenshot's fingerprint costs a few rows of memory, not the whole image. +pub fn info(bytes: &[u8]) -> Result<(String, u32, u32), image::ImageError> { + use sha2::{Digest, Sha256}; + let hash = |rows: &mut Rows<'_>| -> Result { + let mut h = Sha256::new(); + h.update(ALGORITHM.as_bytes()); + h.update(rows.width().to_le_bytes()); + h.update(rows.height().to_le_bytes()); + for _ in 0..rows.height() { + h.update(rows.next_row()?); + } + rows.finish()?; + Ok(hex::encode(h.finalize())) + }; + let mut rows = Rows::open(bytes)?; + let (width, height) = (rows.width(), rows.height()); + let fingerprint = match hash(&mut rows) { + Ok(fingerprint) => fingerprint, + // A file the streaming decoder gave up on part-way: decoded whole, as before, for the decoder's own answer. + Err(RowsFailed) => { + drop(rows); + let _whole = WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + hash(&mut Rows::decoded(bytes)?).map_err(|_| unreachable_rows())? + } + }; + Ok((fingerprint, width, height)) +} + +/// One decode of a whole image at a time in the process: the files [`Rows`] can't read a row at a time (JPEG, WebP, +/// 16-bit or interlaced PNG) take their full size in memory (a 2880x14000 page is 160 MB as RGBA), and several at once +/// could pass the worker's memory limit (VISUALCI-PROD-SERVER-6). Held for the whole of the work on the image. +pub static WHOLE_DECODES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// The streaming decoder failed part-way through a file: decode it whole instead ([`Rows::decoded`]), which gives the +/// image crate's own answer (its pixels, or its error). +#[derive(Debug)] +pub struct RowsFailed; + +fn unreachable_rows() -> image::ImageError { + image::ImageError::IoError(std::io::Error::other("a decoded image's rows failed")) +} + +/// An image file's pixels as RGBA rows, top to bottom. A PNG of 8 bits a channel, not interlaced (any screenshot a +/// browser takes) is decoded a row at a time, holding one row; anything else is decoded whole ([`decode`]) and handed +/// out a row at a time. Either way the rows are exactly `decode(bytes)?.to_rgba8()`'s, and a file [`decode`] refuses +/// (too large, not an image) is refused with its error. +pub struct Rows<'a> { + width: u32, + height: u32, + source: Source<'a>, +} + +enum Source<'a> { + Png { reader: Box>>, color: png::ColorType, row: Vec }, + Whole { image: RgbaImage, next: u32 }, +} + +impl<'a> Rows<'a> { + /// Read `bytes` a row at a time when it's a PNG that allows it, else decode it whole. + pub fn open(bytes: &'a [u8]) -> Result { + match Self::png(bytes) { + Some(rows) => Ok(rows), + None => Self::decoded(bytes), + } + } + + /// Whether [`Rows::open`] reads `bytes` a row at a time (from its header): if not, it decodes the whole image. + pub fn streams(bytes: &[u8]) -> bool { + Rows::png(bytes).is_some() + } + + /// Decode the whole image ([`decode`]) and hand it out a row at a time. + pub fn decoded(bytes: &[u8]) -> Result, image::ImageError> { + let image = decode(bytes)?.into_rgba8(); + Ok(Rows { width: image.width(), height: image.height(), source: Source::Whole { image, next: 0 } }) + } + + /// A PNG the streaming decoder reads exactly as [`decode`] would: 8 bits a channel once expanded (palettes, low bit + /// depths and transparency chunks expand, as the image crate's decoder asks), not interlaced, not animated, and + /// within [`decode`]'s limits. `None` for anything else, which [`Rows::decoded`] decodes (or refuses) as before. + fn png(bytes: &'a [u8]) -> Option { + if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + return None; + } + let limit = usize::try_from(MAX_ALLOC).unwrap_or(usize::MAX); + let mut decoder = png::Decoder::new_with_limits(std::io::Cursor::new(bytes), png::Limits { bytes: limit }); + decoder.set_transformations(png::Transformations::EXPAND); + let reader = decoder.read_info().ok()?; + let info = reader.info(); + let (width, height) = (info.width, info.height); + if info.interlaced || info.animation_control.is_some() || width > MAX_WIDTH || height > MAX_HEIGHT { + return None; + } + let (color, depth) = reader.output_color_type(); + if depth != png::BitDepth::Eight { + return None; + } + let channels: u64 = match color { + png::ColorType::Grayscale => 1, + png::ColorType::GrayscaleAlpha => 2, + png::ColorType::Rgb => 3, + png::ColorType::Rgba => 4, + png::ColorType::Indexed => return None, + }; + // The image crate refuses an image whose decoded pixels pass its allocation limit: so does this. + if u64::from(width) * u64::from(height) * channels > MAX_ALLOC { + return None; + } + let row = vec![0; width as usize * 4]; + Some(Rows { width, height, source: Source::Png { reader: Box::new(reader), color, row } }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + /// After the last row: read the rest of the image data, as the whole-image decoder does, so a file it refuses + /// (one cut short after its last row, say) fails here too. + pub fn finish(&mut self) -> Result<(), RowsFailed> { + match &mut self.source { + Source::Whole { .. } => Ok(()), + Source::Png { reader, .. } => match reader.next_row() { + Ok(None) => Ok(()), + _ => Err(RowsFailed), + }, + } + } + + /// The next row's RGBA pixels (`width * 4` bytes). Call it at most `height` times, then [`Rows::finish`]. + pub fn next_row(&mut self) -> Result<&[u8], RowsFailed> { + let width = self.width as usize; + match &mut self.source { + Source::Whole { image, next } => { + let start = *next as usize * width * 4; + *next += 1; + image.as_raw().get(start..start + width * 4).ok_or(RowsFailed) + } + Source::Png { reader, color, row } => { + let data = reader.next_row().map_err(|_| RowsFailed)?.ok_or(RowsFailed)?.data(); + let out = row.as_chunks_mut::<4>().0.iter_mut(); + match color { + png::ColorType::Grayscale if data.len() >= width => { + for (o, &l) in out.zip(data) { + *o = [l, l, l, 255]; + } + } + png::ColorType::GrayscaleAlpha if data.len() >= width * 2 => { + for (o, &[l, a]) in out.zip(data.as_chunks::<2>().0) { + *o = [l, l, l, a]; + } + } + png::ColorType::Rgb if data.len() >= width * 3 => { + for (o, &[r, g, b]) in out.zip(data.as_chunks::<3>().0) { + *o = [r, g, b, 255]; + } + } + png::ColorType::Rgba if data.len() >= width * 4 => row.copy_from_slice(&data[..width * 4]), + _ => return Err(RowsFailed), + } + Ok(row) + } + } + } } #[cfg(test)] @@ -57,6 +227,98 @@ mod tests { assert_eq!(decode(&png).unwrap().width(), 100); } + /// A PNG written by the png crate itself, for the colour types and depths the image crate doesn't write. + fn raw_png( + w: u32, + h: u32, + color: png::ColorType, + depth: png::BitDepth, + data: &[u8], + extra: impl Fn(&mut png::Encoder<'_, &mut Vec>), + ) -> Vec { + let mut out = Vec::new(); + { + let mut e = png::Encoder::new(&mut out, w, h); + e.set_color(color); + e.set_depth(depth); + extra(&mut e); + e.write_header().unwrap().write_image_data(data).unwrap(); + } + out + } + + #[test] + fn rows_are_the_decoded_pixels_for_every_kind_of_png() { + use png::{BitDepth, ColorType}; + let (w, h) = (7u32, 5u32); + let bytes = |n: usize| (0..w as usize * h as usize * n).map(|i| (i * 37 % 251) as u8).collect::>(); + let none = |_: &mut png::Encoder<'_, &mut Vec>| {}; + let cases: Vec<(&str, Vec, bool)> = vec![ + ("gray", raw_png(w, h, ColorType::Grayscale, BitDepth::Eight, &bytes(1), none), true), + ("gray+alpha", raw_png(w, h, ColorType::GrayscaleAlpha, BitDepth::Eight, &bytes(2), none), true), + ("rgb", raw_png(w, h, ColorType::Rgb, BitDepth::Eight, &bytes(3), none), true), + ("rgba", raw_png(w, h, ColorType::Rgba, BitDepth::Eight, &bytes(4), none), true), + ( + "rgb+trns", + raw_png(w, h, ColorType::Rgb, BitDepth::Eight, &bytes(3), |e| e.set_trns(vec![0, 37, 0, 74, 0, 111])), + true, + ), + ("gray 1-bit", raw_png(w, h, ColorType::Grayscale, BitDepth::One, &[0b1010_1100; 5], none), true), + ( + "palette+trns", + raw_png( + w, + h, + ColorType::Indexed, + BitDepth::Eight, + &bytes(1).iter().map(|b| b % 4).collect::>(), + |e| { + e.set_palette(vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 10, 20, 30]); + e.set_trns(vec![255, 128, 0]); + }, + ), + true, + ), + ("rgb 16-bit", raw_png(w, h, ColorType::Rgb, BitDepth::Sixteen, &bytes(6), none), false), + ]; + let mut jpeg = Vec::new(); + image::DynamicImage::ImageRgba8(RgbaImage::from_pixel(w, h, Rgba([10, 200, 30, 255]))) + .to_rgb8() + .write_to(&mut Cursor::new(&mut jpeg), ImageFormat::Jpeg) + .unwrap(); + let cases = cases.into_iter().chain([("jpeg", jpeg, false)]); + for (name, file, streams) in cases { + let want = decode(&file).unwrap().to_rgba8(); + assert_eq!(Rows::streams(&file), streams, "{name}"); + let mut rows = Rows::open(&file).unwrap(); + assert_eq!((rows.width(), rows.height()), want.dimensions(), "{name}"); + let mut got = Vec::new(); + for _ in 0..rows.height() { + got.extend_from_slice(rows.next_row().unwrap()); + } + assert_eq!(got, want.as_raw().as_slice(), "{name}"); + assert_eq!(info(&file).unwrap(), (fingerprint_rgba(&want), w, h), "{name}"); + } + } + + #[test] + fn a_file_the_streaming_decoder_refuses_gets_the_decoders_answer() { + let mut png = Vec::new(); + RgbaImage::from_pixel(40, 40, Rgba([1, 2, 3, 255])) + .write_to(&mut Cursor::new(&mut png), ImageFormat::Png) + .unwrap(); + // Cut short in its image data, and after it (no IEND): refused alike. + for cut in [30, 12] { + let cut = &png[..png.len() - cut]; + assert_eq!(info(cut).unwrap_err().to_string(), decode(cut).unwrap_err().to_string()); + } + let tall = RgbaImage::new(1, MAX_HEIGHT + 1); + let mut png = Vec::new(); + tall.write_to(&mut Cursor::new(&mut png), ImageFormat::Png).unwrap(); + assert!(!Rows::streams(&png)); + assert_eq!(info(&png).unwrap_err().to_string(), decode(&png).unwrap_err().to_string()); + } + #[test] fn same_pixels_same_fingerprint_whatever_the_encoding() { let mut img = RgbaImage::from_pixel(10, 10, Rgba([255, 255, 255, 255])); diff --git a/crates/visualci-core/tests/peak_memory.rs b/crates/visualci-core/tests/peak_memory.rs new file mode 100644 index 000000000..effae2813 --- /dev/null +++ b/crates/visualci-core/tests/peak_memory.rs @@ -0,0 +1,110 @@ +//! A tall page's comparison takes a few rows of memory, not the page (VISUALCI-PROD-SERVER-6: the worker ran out of +//! memory comparing 2880x14000 screenshots, three full-size RGBA copies and an encoder's at once). +//! +//! Its own test binary: the allocator below counts every allocation in the process, and this is its only test. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use image::{Rgb, RgbImage}; +use visualci_core::diff::{DiffOptions, diff_files}; + +struct Counting; + +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = unsafe { System.alloc(layout) }; + if !p.is_null() { + let live = LIVE.fetch_add(layout.size(), Ordering::Relaxed) + layout.size(); + PEAK.fetch_max(live, Ordering::Relaxed); + } + p + } + unsafe fn dealloc(&self, p: *mut u8, layout: Layout) { + unsafe { System.dealloc(p, layout) }; + LIVE.fetch_sub(layout.size(), Ordering::Relaxed); + } + unsafe fn realloc(&self, p: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + let q = unsafe { System.realloc(p, layout, new_size) }; + if !q.is_null() { + if new_size >= layout.size() { + let live = LIVE.fetch_add(new_size - layout.size(), Ordering::Relaxed) + new_size - layout.size(); + PEAK.fetch_max(live, Ordering::Relaxed); + } else { + LIVE.fetch_sub(layout.size() - new_size, Ordering::Relaxed); + } + } + q + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +const MIB: usize = 1024 * 1024; + +/// A full-page screenshot: white, with lines of grey "words" and a few coloured panels. +fn page(width: u32, height: u32) -> RgbImage { + let mut img = RgbImage::from_pixel(width, height, Rgb([255, 255, 255])); + for y in (40..height - 40).step_by(28) { + let panel = (y / 28) % 23 == 0; + for x in 80..width - 80 { + let word = (x / 37 + y / 28) % 5 != 0; + for dy in 0..if panel { 26 } else { 14 } { + let c = if panel { + Rgb([30, 90, 200]) + } else if word { + Rgb([60, 60, 70]) + } else { + continue; + }; + img.put_pixel(x, y + dy, c); + } + } + } + img +} + +fn png(img: &RgbImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn a_tall_pages_diff_stays_within_a_few_mebibytes() { + let (width, height) = (1440, 20_000); + let (base, head) = { + let base = page(width, height); + let mut head = base.clone(); + for y in height - 900..height - 860 { + for x in 200..600 { + head.put_pixel(x, y, Rgb([220, 40, 40])); + } + } + (png(&base), png(&head)) + }; + let before = LIVE.load(Ordering::Relaxed); + PEAK.store(before, Ordering::Relaxed); + + let (result, overlay) = diff_files(&base, &head, DiffOptions::BROWSER, &Default::default()).unwrap(); + let peak = PEAK.load(Ordering::Relaxed) - before; + let overlay = overlay.expect("a change"); + assert_eq!(result.changed_pixels, 400 * 40); + + // One RGBA copy of this page is 110 MiB, and the diff used to hold three of them and an encoder's buffer. Read a + // row at a time it holds a five-row window of each image (about 60 KB), the tile map (110 KB), the PNG decoders' + // and encoder's state (a few hundred KB) and the overlay PNG it returns, which grows by doubling (so up to twice + // its size). 8 MiB on top of that leaves room for allocator and library changes, and fails at once if a full-size + // buffer comes back. + let bound = 8 * MIB + 2 * overlay.len(); + assert!(peak < bound, "peak {:.1} MiB, bound {:.1} MiB", peak as f64 / MIB as f64, bound as f64 / MIB as f64); + eprintln!( + "peak {:.1} MiB for a {width}x{height} page, overlay {} KB", + peak as f64 / MIB as f64, + overlay.len() / 1024 + ); +} From 5394eadc3477e846344006ef0a6a9ea8ac0239b1 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 15:44:17 +0000 Subject: [PATCH 2/4] Write diff overlays byte for byte as before, and replay real comparisons against main The png crate's StreamWriter gave the same overlay pixels with different bytes (it hands each row to fdeflate in two pieces), so every diff blob's hash would have changed. visualci_core::overlay_png writes the overlay a row at a time exactly as the image crate's PngEncoder wrote it whole: the png crate's adaptive filter, one fdeflate call per filtered row, the stored fallback, one IDAT chunk, into one buffer that's never copied. The compare_memory example gains `replay `: 110 real page comparisons (visualci #1408 and #1430, docspring #229 and #230) give identical results and overlay bytes on main and on this branch. --- Cargo.lock | 2 + Cargo.toml | 3 + crates/visualci-core/Cargo.toml | 2 + .../visualci-core/examples/compare_memory.rs | 46 ++++ crates/visualci-core/src/diff.rs | 73 ++--- crates/visualci-core/src/lib.rs | 1 + crates/visualci-core/src/overlay_png.rs | 258 ++++++++++++++++++ 7 files changed, 354 insertions(+), 31 deletions(-) create mode 100644 crates/visualci-core/src/overlay_png.rs diff --git a/Cargo.lock b/Cargo.lock index d58e8138b..42aa980c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5489,6 +5489,8 @@ dependencies = [ name = "visualci-core" version = "0.2.30" dependencies = [ + "crc32fast", + "fdeflate", "globset", "hex", "image", diff --git a/Cargo.toml b/Cargo.toml index 6c16e8dae..bf13acf92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,9 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "fs tempfile = "3" # Decoding PNG screenshots a row at a time, and writing diff overlays the same way (visualci-core::image_hash::Rows) png = "0.18" +# The png crate's fast compressor, which the diff overlay is written with row by row (visualci-core::overlay_png) +fdeflate = "0.3" +crc32fast = "1" lopdf = { version = "0.47", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/crates/visualci-core/Cargo.toml b/crates/visualci-core/Cargo.toml index 8ef5eb342..726c0d666 100644 --- a/crates/visualci-core/Cargo.toml +++ b/crates/visualci-core/Cargo.toml @@ -7,6 +7,8 @@ license.workspace = true repository.workspace = true [dependencies] +crc32fast.workspace = true +fdeflate.workspace = true globset.workspace = true hex.workspace = true image.workspace = true diff --git a/crates/visualci-core/examples/compare_memory.rs b/crates/visualci-core/examples/compare_memory.rs index 4424fa9c8..e583d2fd4 100644 --- a/crates/visualci-core/examples/compare_memory.rs +++ b/crates/visualci-core/examples/compare_memory.rs @@ -77,6 +77,51 @@ fn compare(base: &[u8], head: &[u8], options: DiffOptions) -> (u64, usize) { (outcome.changed_pixels, overlay.map_or(0, |p| p.len())) } +/// Each changed page of a `download_build` archive (unpacked in `dir`, with its manifest.json), compared in exact and +/// browser mode with the page's masked areas: one JSON line each with the changed pixels, the regions, the overlay's +/// SHA-256, and whether it's the overlay production stored (the archive's diff.png). +fn replay(dir: &std::path::Path) { + use visualci_core::config::{ImageMask, Rect}; + let manifest: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("manifest.json")).unwrap()).unwrap(); + for s in manifest["snapshots"].as_array().unwrap() { + for page in s["pages"].as_array().unwrap() { + let files: Vec = + page["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + let find = |side: &str| files.iter().find(|f| f.ends_with(&format!("/{side}.png"))).map(|f| dir.join(f)); + let (Some(base), Some(head)) = (find("base"), find("head")) else { continue }; + let stored = find("diff").map(|d| visualci_core::sha256_hex(&std::fs::read(d).unwrap())); + let (base, head) = (std::fs::read(base).unwrap(), std::fs::read(head).unwrap()); + let rects = page["masked"] + .as_array() + .into_iter() + .flatten() + .map(|r| Rect { + x: r["x"].as_u64().unwrap() as u32, + y: r["y"].as_u64().unwrap() as u32, + width: r["width"].as_u64().unwrap() as u32, + height: r["height"].as_u64().unwrap() as u32, + }) + .collect(); + let mask = ImageMask { edges: vec![], rects }; + for (mode, options) in [("exact", DiffOptions::EXACT), ("browser", DiffOptions::BROWSER)] { + let (r, overlay) = visualci_core::diff::diff_files(&base, &head, options, &mask).unwrap(); + let sha = overlay.as_ref().map(|o| visualci_core::sha256_hex(o)); + println!( + "{}", + serde_json::json!({ + "snapshot": s["name"], "page": page["position"], "mode": mode, + "canvas": format!("{}x{}", r.width, r.height), "size_changed": r.size_changed, + "changed_pixels": r.changed_pixels, "anti_aliased": r.anti_aliased_pixels, + "regions": r.regions, "fingerprint": r.fingerprint, "overlay_sha256": sha, + "production_overlay": sha.is_some() && sha == stored, + }) + ); + } + } + } +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); match args.first().map(String::as_str) { @@ -138,6 +183,7 @@ fn main() { mib(&status("VmHWM:")) ); } + Some("replay") => replay(std::path::Path::new(&args[1])), Some("same") => { let a = image::open(&args[1]).unwrap().to_rgba8(); let b = image::open(&args[2]).unwrap().to_rgba8(); diff --git a/crates/visualci-core/src/diff.rs b/crates/visualci-core/src/diff.rs index 049f0bb85..37de5a74f 100644 --- a/crates/visualci-core/src/diff.rs +++ b/crates/visualci-core/src/diff.rs @@ -126,55 +126,61 @@ pub fn diff_files( options: DiffOptions, mask: &crate::config::ImageMask, ) -> Result<(DiffResult, Option>), image::ImageError> { - let whole = || WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let streamed = { - let _whole = (!Rows::streams(base) || !Rows::streams(head)).then(whole); - diff_streams(Rows::open(base)?, Rows::open(head)?, options, mask) + type Pass = Result<(DiffResult, Option>), Failed>; + let lock = || WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let streamed = |stored: bool| -> Result { + let _whole = (!Rows::streams(base) || !Rows::streams(head)).then(lock); + Ok(diff_streams(Rows::open(base)?, Rows::open(head)?, options, mask, stored)) }; - match streamed { - Ok(done) => Ok(done), - // The streaming decoder gave up part-way through a file: decode both whole, as before, for the image crate's - // own answer (its pixels, or its error). - Err(Failed::Rows) => { - let _whole = whole(); - diff_streams(Rows::decoded(base)?, Rows::decoded(head)?, options, mask).map_err(|e| match e { - Failed::Rows => image::ImageError::IoError(std::io::Error::other("a decoded image's rows failed")), - Failed::Encode(e) => image::ImageError::IoError(e), - }) + let whole = |stored: bool| -> Result { + let _whole = lock(); + Ok(diff_streams(Rows::decoded(base)?, Rows::decoded(head)?, options, mask, stored)) + }; + let (mut stored, mut decode_whole) = (false, false); + loop { + let pass = if decode_whole { whole(stored)? } else { streamed(stored)? }; + match pass { + Ok(done) => return Ok(done), + // The overlay compresses worse than storing it: written again stored, as the image crate's encoder does. + Err(Failed::TooLarge) if !stored => stored = true, + // The streaming decoder gave up part-way through a file: decode both whole, as before, for the image + // crate's own answer (its pixels, or its error). + Err(Failed::Rows) if !decode_whole => decode_whole = true, + Err(Failed::Encode(e)) => return Err(image::ImageError::IoError(e)), + Err(e) => return Err(image::ImageError::IoError(std::io::Error::other(format!("{e:?}")))), } - Err(Failed::Encode(e)) => Err(image::ImageError::IoError(e)), } } #[derive(Debug)] enum Failed { Rows, + /// The overlay compresses worse than storing it ([`crate::overlay_png::TooLarge`]). + TooLarge, Encode(std::io::Error), } +/// One pass over both files: the diff, and the overlay written as it goes (stored uncompressed when `stored`). fn diff_streams( base: Rows<'_>, head: Rows<'_>, options: DiffOptions, mask: &crate::config::ImageMask, + stored: bool, ) -> Result<(DiffResult, Option>), Failed> { + use crate::overlay_png::{OverlayPng, StoredOverlay}; let (width, height) = (base.width().max(head.width()), base.height().max(head.height())); let masked = mask.resolve(width, height); - let mut png = Vec::new(); - let mut encoder = png::Encoder::new(&mut png, width, height); - // The image crate's PNG encoder's settings (`PngEncoder::new`), which wrote the overlays before. - encoder.set_color(png::ColorType::Rgba); - encoder.set_depth(png::BitDepth::Eight); - encoder.set_compression(png::Compression::Fast); - encoder.set_filter(png::Filter::Adaptive); - let encode = |e: png::EncodingError| Failed::Encode(std::io::Error::other(e)); - let mut writer = encoder.write_header().map_err(encode)?; - let mut stream = writer.stream_writer_with_size(1 << 16).map_err(encode)?; - let result = diff_rows(&mut Window::new(base), &mut Window::new(head), options, &masked, |row| { - std::io::Write::write_all(&mut stream, row).map_err(Failed::Encode) - })?; - stream.finish().map_err(encode)?; - writer.finish().map_err(encode)?; + let (mut base, mut head) = (Window::new(base), Window::new(head)); + let (result, png) = if stored { + let mut png = StoredOverlay::new(width, height).map_err(Failed::Encode)?; + let result = diff_rows(&mut base, &mut head, options, &masked, |row| png.row(row).map_err(Failed::Encode))?; + (result, png.finish().map_err(Failed::Encode)?) + } else { + let mut png = OverlayPng::new(width, height).map_err(Failed::Encode)?; + let result = diff_rows(&mut base, &mut head, options, &masked, |row| png.row(row).map_err(Failed::Encode))?; + (result, png.finish().map_err(Failed::Encode)?.map_err(|_| Failed::TooLarge)?) + }; let identical = result.is_identical(); Ok((result, (!identical).then_some(png))) } @@ -842,7 +848,12 @@ mod tests { assert_eq!(serde_json::to_string(&got).unwrap(), want_json, "{bw}x{bh} {o:?} {mask:?}"); assert_eq!(png.is_some(), !want.is_identical()); if let Some(png) = png { - assert_eq!(decode(&png).as_raw(), want_overlay.as_raw(), "{bw}x{bh} {o:?} {mask:?}"); + // The same bytes the image crate's encoder wrote for the whole overlay before. + let mut want_png = Vec::new(); + want_overlay + .write_to(&mut std::io::Cursor::new(&mut want_png), image::ImageFormat::Png) + .unwrap(); + assert!(png == want_png, "{bw}x{bh} {o:?} {mask:?}: the overlay's bytes differ"); } cases += 1; } diff --git a/crates/visualci-core/src/lib.rs b/crates/visualci-core/src/lib.rs index e64cba1ad..3c75953c9 100644 --- a/crates/visualci-core/src/lib.rs +++ b/crates/visualci-core/src/lib.rs @@ -12,6 +12,7 @@ pub mod config; pub mod diff; pub mod image_hash; pub mod manifest; +mod overlay_png; pub mod pdf; /// Text snapshots: the `snapshot-diff` crate. pub mod snapshot_text { diff --git a/crates/visualci-core/src/overlay_png.rs b/crates/visualci-core/src/overlay_png.rs new file mode 100644 index 000000000..81431da8b --- /dev/null +++ b/crates/visualci-core/src/overlay_png.rs @@ -0,0 +1,258 @@ +//! Writing a diff overlay as a PNG a row at a time, byte for byte as the image crate's `PngEncoder` (its defaults: fast +//! compression, adaptive filter) writes the whole image with `png::Writer::write_image_data`. The png crate's own +//! `StreamWriter` hands each row to the compressor in two pieces, which compresses a little differently, so an overlay +//! it wrote wouldn't have the same bytes (or blob hash) as the one before (VISUALCI-PROD-SERVER-6). +//! +//! What `write_image_data` does for 8-bit RGBA with `DeflateCompression::FdeflateUltraFast` (png 0.18), and so this: +//! each row is filtered with the cheapest of Up, Sub, Avg and Paeth (the smallest sum of its bytes taken as signed), +//! prefixed with its filter type and compressed with fdeflate; when that comes out larger than storing the rows +//! uncompressed, they're stored (filter type 0) instead. The zlib stream goes in one IDAT chunk. + +use std::io::Cursor; + +/// RGBA: the filters look one pixel back. +const BPP: usize = 4; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Filter { + Sub = 1, + Up = 2, + Avg = 3, + Paeth = 4, +} + +fn paeth(a: u8, b: u8, c: u8) -> u8 { + let p = i16::from(a) + i16::from(b) - i16::from(c); + let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs()); + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + b + } else { + c + } +} + +fn apply(filter: Filter, previous: &[u8], current: &[u8], out: &mut [u8]) { + let n = current.len(); + // The first pixel has nothing to its left (a = c = 0). + for i in 0..BPP.min(n) { + let b = previous[i]; + out[i] = current[i].wrapping_sub(match filter { + Filter::Sub => 0, + Filter::Up | Filter::Paeth => b, + Filter::Avg => b / 2, + }); + } + if n <= BPP { + return; + } + let (cur, left) = (¤t[BPP..], ¤t[..n - BPP]); + let (up, up_left) = (&previous[BPP..], &previous[..n - BPP]); + let out = &mut out[BPP..]; + match filter { + Filter::Sub => out.iter_mut().zip(cur.iter().zip(left)).for_each(|(o, (&x, &a))| *o = x.wrapping_sub(a)), + Filter::Up => out.iter_mut().zip(cur.iter().zip(up)).for_each(|(o, (&x, &b))| *o = x.wrapping_sub(b)), + Filter::Avg => out + .iter_mut() + .zip(cur.iter().zip(left.iter().zip(up))) + .for_each(|(o, (&x, (&a, &b)))| *o = x.wrapping_sub(((u16::from(a) + u16::from(b)) / 2) as u8)), + Filter::Paeth => out + .iter_mut() + .zip(cur.iter().zip(left.iter().zip(up.iter().zip(up_left)))) + .for_each(|(o, (&x, (&a, (&b, &c))))| *o = x.wrapping_sub(paeth(a, b, c))), + } +} + +fn cost(buf: &[u8]) -> u64 { + buf.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum() +} + +/// The png crate's adaptive filter: the first of Up, Sub, Avg, Paeth with the lowest cost, ties going to the later one, +/// stopping at a cost of 0. `out` gets the filtered row. +fn adaptive(previous: &[u8], current: &[u8], out: &mut [u8]) -> Filter { + let (mut best, mut choice) = (u64::MAX, Filter::Up); + for filter in [Filter::Up, Filter::Sub, Filter::Avg, Filter::Paeth] { + apply(filter, previous, current, out); + let c = cost(out); + if c <= best { + best = c; + choice = filter; + if c == 0 { + return choice; + } + } + } + if choice != Filter::Paeth { + apply(choice, previous, current, out); + } + choice +} + +/// The file up to the image data: the PNG signature, the header chunk (8-bit RGBA, not interlaced) and the IDAT chunk's +/// length (filled in at the end) and type. The compressor writes the image data after it, into the same buffer, so the +/// finished file is never copied: the overlay is the one buffer that grows with the page's height. +fn start(width: u32, height: u32) -> Cursor> { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&width.to_be_bytes()); + ihdr.extend_from_slice(&height.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); + chunk(&mut out, b"IHDR", &ihdr); + out.extend_from_slice(&[0, 0, 0, 0]); + out.extend_from_slice(b"IDAT"); + let mut cursor = Cursor::new(out); + cursor.set_position(IDAT_DATA as u64); + cursor +} + +/// Where the IDAT chunk starts (its length), and its data. +const IDAT: usize = 8 + 12 + 13; +const IDAT_DATA: usize = IDAT + 8; + +fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&u32::try_from(data.len()).unwrap_or(u32::MAX).to_be_bytes()); + let from = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(data); + let crc = crc32fast::hash(&out[from..]); + out.extend_from_slice(&crc.to_be_bytes()); +} + +/// Close the IDAT chunk the compressor wrote into (its length and checksum) and end the file. The image data must fit +/// one chunk (2^31 - 1 bytes, an overlay of over 500 million pixels, which `decode`'s limits refuse long before). +fn end(mut out: Vec) -> std::io::Result> { + let len = out.len() - IDAT_DATA; + let len = u32::try_from(len) + .ok() + .filter(|&l| l <= u32::MAX >> 1) + .ok_or_else(|| std::io::Error::other("a diff overlay's image data is over 2 GB"))?; + out[IDAT..IDAT + 4].copy_from_slice(&len.to_be_bytes()); + let crc = crc32fast::hash(&out[IDAT + 4..]); + out.extend_from_slice(&crc.to_be_bytes()); + chunk(&mut out, b"IEND", &[]); + Ok(out) +} + +/// An overlay being written: [`OverlayPng::row`] for each row, top to bottom, then [`OverlayPng::finish`]. +pub(crate) struct OverlayPng { + width: u32, + height: u32, + previous: Vec, + /// The filter type and the filtered row, as one piece for the compressor. + line: Vec, + compressor: fdeflate::Compressor>>, +} + +/// The compressed rows came out larger than storing them: write them again with [`StoredOverlay`]. +pub(crate) struct TooLarge; + +impl OverlayPng { + pub(crate) fn new(width: u32, height: u32) -> std::io::Result { + let len = width as usize * BPP; + Ok(Self { + width, + height, + previous: vec![0; len], + line: vec![0; len + 1], + compressor: fdeflate::Compressor::new(start(width, height))?, + }) + } + + pub(crate) fn row(&mut self, row: &[u8]) -> std::io::Result<()> { + let filter = adaptive(&self.previous, row, &mut self.line[1..]); + self.line[0] = filter as u8; + self.compressor.write_data(&self.line)?; + self.previous.copy_from_slice(row); + Ok(()) + } + + /// The PNG, or [`TooLarge`] when its rows have to be stored uncompressed. + pub(crate) fn finish(self) -> std::io::Result, TooLarge>> { + let out = self.compressor.finish()?.into_inner(); + let raw = (self.width as usize * BPP + 1) * self.height as usize; + if out.len() - IDAT_DATA > fdeflate::StoredOnlyCompressor::<()>::compressed_size(raw) { + return Ok(Err(TooLarge)); + } + end(out).map(Ok) + } +} + +/// An overlay whose rows are stored uncompressed (`write_image_data`'s fallback): filter type 0 and the raw row. +pub(crate) struct StoredOverlay { + compressor: fdeflate::StoredOnlyCompressor>>, +} + +impl StoredOverlay { + pub(crate) fn new(width: u32, height: u32) -> std::io::Result { + Ok(Self { compressor: fdeflate::StoredOnlyCompressor::new(start(width, height))? }) + } + + pub(crate) fn row(&mut self, row: &[u8]) -> std::io::Result<()> { + self.compressor.write_data(&[0])?; + self.compressor.write_data(row) + } + + pub(crate) fn finish(self) -> std::io::Result> { + end(self.compressor.finish()?.into_inner()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{Rgba, RgbaImage}; + + fn image_crates_png(img: &RgbaImage) -> Vec { + let mut out = Vec::new(); + img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn rows_png(img: &RgbaImage) -> Vec { + let mut png = OverlayPng::new(img.width(), img.height()).unwrap(); + for row in img.as_raw().chunks(img.width() as usize * 4) { + png.row(row).unwrap(); + } + match png.finish().unwrap() { + Ok(png) => png, + Err(TooLarge) => { + let mut stored = StoredOverlay::new(img.width(), img.height()).unwrap(); + for row in img.as_raw().chunks(img.width() as usize * 4) { + stored.row(row).unwrap(); + } + stored.finish().unwrap() + } + } + } + + #[test] + fn the_same_bytes_as_the_image_crates_encoder() { + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut rand = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + // Flat, gradients, noise (which only stores well) and odd sizes. + let flat = RgbaImage::from_pixel(64, 40, Rgba([240, 240, 240, 255])); + let gradient = RgbaImage::from_fn(97, 61, |x, y| Rgba([(x * 3) as u8, (y * 4) as u8, (x + y) as u8, 255])); + let noise = RgbaImage::from_fn(50, 33, |_, _| { + let v = rand(); + Rgba([v as u8, (v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8]) + }); + let mixed = RgbaImage::from_fn(300, 200, |x, y| { + if (x / 20 + y / 9) % 3 == 0 { Rgba([255, 0, 0, 255]) } else { Rgba([200, 200, (x % 7) as u8 * 30, 255]) } + }); + let one = RgbaImage::from_pixel(1, 1, Rgba([1, 2, 3, 4])); + let mut compressed = OverlayPng::new(noise.width(), noise.height()).unwrap(); + for row in noise.as_raw().chunks(noise.width() as usize * 4) { + compressed.row(row).unwrap(); + } + assert!(compressed.finish().unwrap().is_err(), "noise is stored: the fallback is covered"); + for (name, img) in [("flat", flat), ("gradient", gradient), ("noise", noise), ("mixed", mixed), ("1x1", one)] { + assert_eq!(rows_png(&img), image_crates_png(&img), "{name}"); + } + } +} From 75e3f42323bb7d5391176db7e9760258b7c4a35a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 16:07:42 +0000 Subject: [PATCH 3/4] Count only real worker deaths against a build's tries Review fixes for the OOM detection: - A run's mark is a guard (RunMark): the job's timeout or a caught panic drops the run's future, and the drop clears the mark, so only a worker that dies (out of memory, SIGKILL) leaves it to be counted. - Tries that run out without a death leave the build processing for the sweep, as on main; the job still fails. Only deaths fail the build. - give_up waits JOB_WAIT_SECONDS for the build, as run does, so a dead run's hold that hasn't lapsed doesn't make it give up silently. - image_hash::info and matching::same_in_files take WHOLE_DECODES before opening a file that won't stream, as the doc says; lock_whole_decodes helper. - Tests: timed-out and panicked runs aren't deaths, the job's try past its tries with and without deaths, give_up waiting out a dead hold, and an interlaced PNG comparing as its plain twin. --- app/src/domain/matching.rs | 6 +- app/src/domain/processing.rs | 127 +++++++++++++++++-------- app/src/forge/pr_comment.rs | 2 +- app/src/jobs/process_build.rs | 10 +- app/tests/processing_lock.rs | 118 ++++++++++++++++++----- crates/visualci-core/src/diff.rs | 63 +++++++++++- crates/visualci-core/src/image_hash.rs | 14 ++- 7 files changed, 263 insertions(+), 77 deletions(-) diff --git a/app/src/domain/matching.rs b/app/src/domain/matching.rs index 49f2f66a8..fc5e25d24 100644 --- a/app/src/domain/matching.rs +++ b/app/src/domain/matching.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use laravel::db; use visualci_core::diff::{DiffResult, Region}; -use visualci_core::image_hash::{Rows, RowsFailed, WHOLE_DECODES}; +use visualci_core::image_hash::{Rows, RowsFailed, lock_whole_decodes}; use crate::models::{Build, Diff, Snapshot, SnapshotPage}; use crate::storage::BlobStore; @@ -95,13 +95,15 @@ pub fn same_in_files(a: &[u8], b: &[u8], regions: &[Region]) -> bool { } Ok(true) }; + // A file that won't stream is decoded whole by `Rows::open`. + let whole = (!Rows::streams(a) || !Rows::streams(b)).then(lock_whole_decodes); let (Ok(mut ra), Ok(mut rb)) = (Rows::open(a), Rows::open(b)) else { return false }; match compare(&mut ra, &mut rb) { Ok(same) => same, // The streaming decoder gave up part-way through a file: decode both whole, as before. Err(RowsFailed) => { drop((ra, rb)); - let _whole = WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _whole = whole.unwrap_or_else(lock_whole_decodes); let (Ok(mut ra), Ok(mut rb)) = (Rows::decoded(a), Rows::decoded(b)) else { return false }; compare(&mut ra, &mut rb).unwrap_or(false) } diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 7cc00e5c2..22ca100c0 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -103,8 +103,9 @@ pub const JOB_WAIT_SECONDS: i64 = 10; pub const RUNS: u32 = 3; /// The mark a run leaves on its build while it works, inside [`exclusive`]: a run that finds it there when it takes the -/// build knows the run before it never finished. Its worker died (ran out of memory, or was killed by a deploy or the -/// job's timeout) while holding the build, since a live run would still hold it. +/// build knows the run before it never finished, and its worker died (ran out of memory, or was killed) while holding +/// the build, since a live run would still hold it. A run that ends clears it ([`RunMark::end`]), and so does one whose +/// future is dropped (the job's timeout, a panic: [`RunMark`]'s drop), so only a worker that dies leaves it. fn running_key(build_id: i64) -> String { format!("builds.process-running:{build_id}") } @@ -117,12 +118,52 @@ fn died_key(build_id: i64) -> String { /// How long the marks last: longer than any run and its retries. const RUN_MARK_HOURS: i64 = 24; +/// A run's mark on its build ([`running_key`]), from [`note_run_start`]. [`RunMark::end`] clears it when the run ends. +/// Dropped without that (the job's timeout drops the run's future, and so does a panic), it clears the mark in a task +/// of its own: the run was cut off, its worker didn't die. Only a worker that dies (out of memory, SIGKILL) runs no +/// drop, and leaves the mark for the next run to count. +#[must_use = "end the run with `RunMark::end`"] +pub struct RunMark { + build_id: i64, + context: Option, +} + +impl RunMark { + /// The run ended: it finished, waits for renders, stopped for a deploy, or failed and failed the build. It didn't + /// die. `concluded`: the build is done with, so the count of runs that died starts again. + /// + /// # Errors + /// On a cache error. + pub async fn end(mut self, concluded: bool) -> laravel::Result<()> { + self.context = None; + laravel::cache::forget(&running_key(self.build_id)).await?; + if concluded { + laravel::cache::forget(&died_key(self.build_id)).await?; + } + Ok(()) + } +} + +impl Drop for RunMark { + fn drop(&mut self) { + let Some(context) = self.context.take() else { return }; + let build_id = self.build_id; + tracing::warn!(build_id, "a run processing this build was cut off (the job's timeout, or a panic)"); + let Ok(runtime) = tokio::runtime::Handle::try_current() else { return }; + runtime.spawn(context.scope(async move { + if let Err(e) = laravel::cache::forget(&running_key(build_id)).await { + tracing::warn!(build_id, error = %e, "clearing a cut-off run's mark failed"); + } + })); + } +} + /// Note that a run took the build, while holding it ([`exclusive`]). Returns how many runs before it died without -/// finishing, counting the one just before when it left its mark ([`running_key`]). +/// finishing, counting the one just before when it left its mark ([`running_key`]), and this run's mark. /// /// # Errors /// On a cache error. -pub async fn note_run_start(build_id: i64) -> laravel::Result { +pub async fn note_run_start(build_id: i64) -> laravel::Result<(i64, RunMark)> { use laravel::time::ToSpan; let mut died = laravel::cache::get::(&died_key(build_id)).await?.unwrap_or(0); if laravel::cache::pull::(&running_key(build_id)).await?.is_some() { @@ -135,20 +176,7 @@ pub async fn note_run_start(build_id: i64) -> laravel::Result { ); } laravel::cache::put(&running_key(build_id), true, RUN_MARK_HOURS.hours()).await?; - Ok(died) -} - -/// Note that a run ended (it finished, waits for renders, stopped for a deploy, or failed and failed the build): it -/// didn't die. `concluded`: the build is done with, so the count of runs that died starts again. -/// -/// # Errors -/// On a cache error. -pub async fn note_run_end(build_id: i64, concluded: bool) -> laravel::Result<()> { - laravel::cache::forget(&running_key(build_id)).await?; - if concluded { - laravel::cache::forget(&died_key(build_id)).await?; - } - Ok(()) + Ok((died, RunMark { build_id, context: laravel::context::Context::current() })) } fn died_message(number: i32, died: i64) -> String { @@ -156,42 +184,59 @@ fn died_message(number: i32, died: i64) -> String { format!("the worker ran out of memory (or was killed) processing build #{number}, {times}") } -/// Fail a build whose processing ran out of tries (`ProcessBuild` beyond [`RUNS`]), saying why: its runs' workers died -/// ([`note_run_start`]), or else it didn't finish in its tries. Returns the error, for the job's own failure, or `None` -/// when the build isn't processing any more (its last run finished after all) or another run is processing it now. +/// What `ProcessBuild` does past its [`RUNS`] tries ([`give_up`]). +#[derive(Debug, PartialEq, Eq)] +pub enum GaveUp { + /// Its runs' workers died: the build failed with this error, which the job fails with too. + Died(String), + /// Its tries ran out without a worker dying (errors before the run took the build, such as the database being + /// down): the build is left processing for the sweep to run again, as it was before the tries counted deaths, and + /// the job fails with this error. + Tries(String), + /// Nothing to do: the build isn't processing any more, or another run is processing it now. + Nothing, +} + +/// The try past [`RUNS`]: fail the build when its runs' workers died ([`note_run_start`]), saying so; otherwise leave it +/// for the sweep. Waits [`JOB_WAIT_SECONDS`] for the build, as [`run`] does: a dead run's hold may not have lapsed yet. /// /// # Errors /// On a database or cache error. -pub async fn give_up(build_id: i64) -> laravel::Result> { +pub async fn give_up(build_id: i64) -> laravel::Result { // Under the build's processing lock: a run another job started meanwhile is live, and is left to finish. - let out = exclusive(build_id, 0, || async move { - let mut died = laravel::cache::pull::(&died_key(build_id)).await?.unwrap_or(0); + let out = exclusive(build_id, JOB_WAIT_SECONDS, || async move { + let Some(mut build) = Build::find(build_id).await? else { return Ok(GaveUp::Nothing) }; + if build.state != "processing" { + return Ok(GaveUp::Nothing); + } + let mut died = laravel::cache::get::(&died_key(build_id)).await?.unwrap_or(0); // The last run's mark: it died too (it no longer holds the build, so it isn't running). - if laravel::cache::pull::(&running_key(build_id)).await?.is_some() { + if laravel::cache::get::(&running_key(build_id)).await?.is_some() { died += 1; } - let Some(mut build) = Build::find(build_id).await? else { return Ok(None) }; - if build.state != "processing" { - return Ok(None); + if died == 0 { + return Ok(GaveUp::Tries(format!( + "processing build #{} was tried more than its {RUNS} tries allow, without a worker dying: it's left \ + processing for the sweep", + build.number + ))); } - let message = if died > 0 { - died_message(build.number, died) - } else { - format!("processing build #{} didn't finish in its {RUNS} tries", build.number) - }; + laravel::cache::forget(&running_key(build_id)).await?; + laravel::cache::forget(&died_key(build_id)).await?; + let message = died_message(build.number, died); let error = Some(message.clone()); update!(build { state: "failed", error }).await?; - Ok(Some(message)) + Ok(GaveUp::Died(message)) }) .await; - let message = match out { - Err(e) if e.is::() => return Ok(None), + let gave_up = match out { + Err(e) if e.is::() => return Ok(GaveUp::Nothing), other => other?, }; - if message.is_some() { + if matches!(gave_up, GaveUp::Died(_)) { Box::pin(crate::events::BuildChanged { build_id }.dispatch().into_future()).await?; } - Ok(message) + Ok(gave_up) } /// The note a job leaves when another run holds the build: run it again once that run is done. @@ -314,9 +359,9 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la } // A build whose runs keep dying (out of memory) fails saying so, however its runs were queued (a retry, the // sweep, a render finishing), rather than kill another worker. - let died = note_run_start(id).await?; + let (died, mark) = note_run_start(id).await?; if died >= i64::from(RUNS) { - note_run_end(id, true).await?; + mark.end(true).await?; return Err(laravel::Error::msg(died_message(build.number, died))); } // Boxed: processing's future is large, and the lock's own future holds it. @@ -325,7 +370,7 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la Ok(done) => *done, Err(e) => !e.is::(), }; - note_run_end(id, concluded).await?; + mark.end(concluded).await?; out }; let busy = |r: &laravel::Result| matches!(r, Err(e) if e.is::()); diff --git a/app/src/forge/pr_comment.rs b/app/src/forge/pr_comment.rs index c080e99be..03642a7f7 100644 --- a/app/src/forge/pr_comment.rs +++ b/app/src/forge/pr_comment.rs @@ -311,7 +311,7 @@ async fn make_images( let regions = result.regions; let rendered = tokio::task::spawn_blocking(move || { // It decodes the overlay whole: one whole-image decode at a time in the process (VISUALCI-PROD-SERVER-6). - let _whole = visualci_core::image_hash::WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _whole = visualci_core::image_hash::lock_whole_decodes(); super::comment_images::render(&shown, base.as_deref(), head.as_deref(), ®ions) }) .await diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs index 3c1b2c619..ccb7ffe03 100644 --- a/app/src/jobs/process_build.rs +++ b/app/src/jobs/process_build.rs @@ -18,7 +18,8 @@ pub struct ProcessBuild { // the build failed itself and doesn't come back here. The first retry waits out a killed run's hold on the build // (`processing::HOLD_SECONDS`). The sweep re-runs builds stuck in processing as well. One try more than // `processing::RUNS`: a run killed on its last try (out of memory) leaves the next one to fail the build saying so -// (`processing::give_up`), rather than the queue failing the job for its tries alone. +// (`processing::give_up`), rather than the queue failing the job for its tries alone. Tries that ran out without a worker +// dying leave the build for the sweep, as before. #[job( name = "builds.process", debounce_for = 3.seconds(), @@ -34,8 +35,11 @@ impl ProcessBuild { async fn handle(self, attempt: &Attempt) -> laravel::Result<()> { if attempt.number() > processing::RUNS { - if let Some(error) = processing::give_up(self.build_id).await? { - attempt.fail(laravel::Error::msg(error)); + match processing::give_up(self.build_id).await? { + processing::GaveUp::Died(error) | processing::GaveUp::Tries(error) => { + attempt.fail(laravel::Error::msg(error)); + } + processing::GaveUp::Nothing => {} } return Ok(()); } diff --git a/app/tests/processing_lock.rs b/app/tests/processing_lock.rs index 4fa86476e..99c366b36 100644 --- a/app/tests/processing_lock.rs +++ b/app/tests/processing_lock.rs @@ -60,6 +60,20 @@ async fn processing_build() -> laravel::Result { app::models::Build::find_or_fail(id).await } +/// A run whose worker dies (out of memory, SIGKILL): it took the build, and ran neither its end nor its mark's drop. +async fn run_that_dies(build_id: i64) -> laravel::Result { + let (died, mark) = processing::note_run_start(build_id).await?; + std::mem::forget(mark); + Ok(died) +} + +/// How many runs before the next one died, ending that next one cleanly. +async fn died_before_next_run(build_id: i64) -> laravel::Result { + let (died, mark) = processing::note_run_start(build_id).await?; + mark.end(false).await?; + Ok(died) +} + /// VISUALCI-PROD-SERVER-6: a run killed for running out of memory leaves its mark, the next run that takes the build /// counts it, and once `processing::RUNS` runs have died the build fails saying why, rather than kill another worker. #[laravel::test] @@ -68,41 +82,85 @@ async fn runs_that_die_are_counted_and_the_build_fails_saying_its_worker_ran_out ) -> laravel::Result<()> { let build = processing_build().await?; let id = build.id; - assert_eq!(processing::note_run_start(id).await?, 0, "the first run"); - // It died (no `note_run_end`): the next run finds its mark, and so on. - assert_eq!(processing::note_run_start(id).await?, 1); - assert_eq!(processing::note_run_start(id).await?, 2); + assert_eq!(run_that_dies(id).await?, 0, "the first run"); + // It died: the next run finds its mark, and so on. + assert_eq!(run_that_dies(id).await?, 1); + assert_eq!(run_that_dies(id).await?, 2); // The third died too: the next run (a retry, or the sweep's) fails the build instead of processing it. let store = app::testing::fixtures::blob_store().await?; processing::run(id, &store, "test").await?; let failed = app::models::Build::find_or_fail(id).await?; let want = format!("the worker ran out of memory (or was killed) processing build #{}, 3 times", build.number); assert_eq!((failed.state.as_str(), failed.error.as_deref()), ("failed", Some(want.as_str()))); - assert_eq!(processing::note_run_start(id).await?, 0, "the count starts again"); + assert_eq!(died_before_next_run(id).await?, 0, "the count starts again"); + Ok(()) +} + +/// A run cut off by the job's timeout (its future dropped) or by a panic didn't die: its mark goes with it, and the +/// next run doesn't count it. +#[laravel::test] +async fn a_run_cut_off_by_its_timeout_or_a_panic_is_not_counted_as_dying(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + // The job's timeout: the run's future is dropped mid-run. + let run = async { + let (_, _mark) = processing::note_run_start(id).await?; + std::future::pending::<()>().await; + Ok::<(), laravel::Error>(()) + }; + assert!(tokio::time::timeout(Duration::from_millis(200), run).await.is_err(), "the run timed out"); + // The drop clears the mark in a task of its own. + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(died_before_next_run(id).await?, 0, "a run that timed out"); + // A panic: caught, as the queue catches a job's panic. + let context = laravel::context::Context::current().expect("the test's context"); + let panicked = tokio::spawn(context.scope(async move { + let (_, _mark) = processing::note_run_start(id).await.expect("the run took the build"); + panic!("the run panicked"); + })) + .await; + assert!(panicked.is_err(), "the run panicked"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(died_before_next_run(id).await?, 0, "a run that panicked"); + // A run that dies still counts. + run_that_dies(id).await?; + assert_eq!(died_before_next_run(id).await?, 1); Ok(()) } -/// The job's try past `processing::RUNS` (its last allowed by `tries`) fails the build and the job with the same error: -/// the worker ran out of memory, not "attempted more than its tries allow". +/// The job's try past `processing::RUNS` (its last allowed by `tries`), when runs died: it fails the build and the job +/// with the same error, that the worker ran out of memory, not "attempted more than its tries allow". #[laravel::test] -async fn a_retry_past_its_tries_fails_the_build_saying_its_worker_died(_app: Application) -> laravel::Result<()> { +async fn a_retry_past_its_tries_fails_the_build_saying_its_worker_died(app: Application) -> laravel::Result<()> { + use app::jobs::process_build::ProcessBuild; let build = processing_build().await?; let id = build.id; - processing::note_run_start(id).await?; - processing::note_run_start(id).await?; - let error = processing::give_up(id).await?.expect("the build was processing"); - assert_eq!( - error, - format!("the worker ran out of memory (or was killed) processing build #{}, 2 times", build.number) - ); + run_that_dies(id).await?; + run_that_dies(id).await?; + let result = app.job(ProcessBuild { build_id: id }).attempt(processing::RUNS + 1).await; + result.assert_failed(); + let error = format!("the worker ran out of memory (or was killed) processing build #{}, 2 times", build.number); + assert_eq!(result.error().map(ToString::to_string), Some(error.clone())); let failed = app::models::Build::find_or_fail(id).await?; assert_eq!((failed.state.as_str(), failed.error.as_deref()), ("failed", Some(error.as_str()))); - assert_eq!(processing::give_up(id).await?, None, "a build that isn't processing is left alone"); + assert_eq!(processing::give_up(id).await?, processing::GaveUp::Nothing, "a build that isn't processing"); + Ok(()) +} - // Tries that ended without dying (none left a mark) say only that. - let other = processing_build().await?; - let error = processing::give_up(other.id).await?.expect("processing"); - assert_eq!(error, format!("processing build #{} didn't finish in its 3 tries", other.number)); +/// Tries that ran out without a worker dying (errors before a run took the build, such as the database being down) +/// fail the job but leave the build processing for the sweep, as before the tries counted deaths. +#[laravel::test] +async fn a_retry_past_its_tries_without_deaths_leaves_the_build_for_the_sweep(app: Application) -> laravel::Result<()> { + use app::jobs::process_build::ProcessBuild; + let build = processing_build().await?; + let id = build.id; + died_before_next_run(id).await?; + let result = app.job(ProcessBuild { build_id: id }).attempt(processing::RUNS + 1).await; + result.assert_failed(); + let error = result.error().map(ToString::to_string).unwrap_or_default(); + assert!(error.contains("left processing for the sweep"), "{error}"); + let left = app::models::Build::find_or_fail(id).await?; + assert_eq!((left.state.as_str(), left.error.as_deref()), ("processing", None)); Ok(()) } @@ -111,11 +169,24 @@ async fn a_retry_past_its_tries_fails_the_build_saying_its_worker_died(_app: App async fn a_run_that_finishes_forgets_the_runs_that_died(_app: Application) -> laravel::Result<()> { let build = processing_build().await?; let id = build.id; - processing::note_run_start(id).await?; + run_that_dies(id).await?; let store = app::testing::fixtures::blob_store().await?; processing::run(id, &store, "test").await?; assert_ne!(app::models::Build::find_or_fail(id).await?.state, "processing", "an empty build concludes"); - assert_eq!(processing::note_run_start(id).await?, 0); + assert_eq!(died_before_next_run(id).await?, 0); + Ok(()) +} + +/// The try past its tries waits for a dead run's hold to lapse, as a run does, rather than give up on the build at once. +#[laravel::test] +async fn giving_up_waits_for_a_dead_runs_hold_to_lapse(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + run_that_dies(id).await?; + let dead = laravel::cache::lock(&format!("builds.process:{id}"), 2.seconds())?; + assert!(dead.acquire().await?, "the dead run's hold"); + assert!(matches!(processing::give_up(id).await?, processing::GaveUp::Died(_))); + assert_eq!(app::models::Build::find_or_fail(id).await?.state, "failed"); Ok(()) } @@ -124,9 +195,10 @@ async fn a_run_that_finishes_forgets_the_runs_that_died(_app: Application) -> la async fn giving_up_leaves_a_build_another_run_is_processing(_app: Application) -> laravel::Result<()> { let build = processing_build().await?; let id = build.id; + run_that_dies(id).await?; let live = laravel::cache::lock(&format!("builds.process:{id}"), 30.seconds())?; assert!(live.acquire().await?, "the live run took the build"); - assert_eq!(processing::give_up(id).await?, None); + assert_eq!(processing::give_up(id).await?, processing::GaveUp::Nothing); assert_eq!(app::models::Build::find_or_fail(id).await?.state, "processing"); Ok(()) } diff --git a/crates/visualci-core/src/diff.rs b/crates/visualci-core/src/diff.rs index 37de5a74f..6ce3a6b00 100644 --- a/crates/visualci-core/src/diff.rs +++ b/crates/visualci-core/src/diff.rs @@ -18,7 +18,7 @@ use image::{Rgba, RgbaImage}; -use crate::image_hash::{Rows, WHOLE_DECODES}; +use crate::image_hash::{Rows, lock_whole_decodes}; use serde::{Deserialize, Serialize}; pub const ALGORITHM: &str = "vci-diff-1"; @@ -116,7 +116,7 @@ pub fn diff_masked( /// The images are read a row at a time ([`Rows`]) and the overlay written the same way, so a tall full-page screenshot /// costs a few rows of memory, not three full-size images and a PNG encoder's copy (VISUALCI-PROD-SERVER-6: a /// 2880x14000 pair took over 600 MB). Files that can't be read a row at a time are decoded whole, one comparison at a -/// time in the process ([`WHOLE_DECODES`]). The result and the overlay's pixels are exactly [`diff_masked`]'s. +/// time in the process ([`crate::image_hash::WHOLE_DECODES`]). The result and the overlay's pixels are exactly [`diff_masked`]'s. /// /// # Errors /// When a file isn't an image [`crate::image_hash::decode`] reads (its error), or the overlay can't be encoded. @@ -127,13 +127,12 @@ pub fn diff_files( mask: &crate::config::ImageMask, ) -> Result<(DiffResult, Option>), image::ImageError> { type Pass = Result<(DiffResult, Option>), Failed>; - let lock = || WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let streamed = |stored: bool| -> Result { - let _whole = (!Rows::streams(base) || !Rows::streams(head)).then(lock); + let _whole = (!Rows::streams(base) || !Rows::streams(head)).then(lock_whole_decodes); Ok(diff_streams(Rows::open(base)?, Rows::open(head)?, options, mask, stored)) }; let whole = |stored: bool| -> Result { - let _whole = lock(); + let _whole = lock_whole_decodes(); Ok(diff_streams(Rows::decoded(base)?, Rows::decoded(head)?, options, mask, stored)) }; let (mut stored, mut decode_whole) = (false, false); @@ -883,6 +882,60 @@ mod tests { assert!(diff_files(b"not an image", &png, DiffOptions::EXACT, &Default::default()).is_err()); } + /// `img` as an interlaced (Adam7) RGBA PNG, which no encoder at hand writes. + fn interlaced_png_of(img: &RgbaImage) -> Vec { + const PASSES: [(u32, u32, u32, u32); 7] = + [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]; + let mut raw = Vec::new(); + for (x0, y0, dx, dy) in PASSES { + if x0 >= img.width() || y0 >= img.height() { + continue; + } + for y in (y0..img.height()).step_by(dy as usize) { + raw.push(0); + for x in (x0..img.width()).step_by(dx as usize) { + raw.extend_from_slice(&img.get_pixel(x, y).0); + } + } + } + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes()); + let start = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(data); + let crc = crc32fast::hash(&out[start..]); + out.extend_from_slice(&crc.to_be_bytes()); + }; + let mut header = Vec::new(); + header.extend_from_slice(&img.width().to_be_bytes()); + header.extend_from_slice(&img.height().to_be_bytes()); + header.extend_from_slice(&[8, 6, 0, 0, 1]); + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut out, b"IHDR", &header); + chunk(&mut out, b"IDAT", &fdeflate::compress_to_vec(&raw)); + chunk(&mut out, b"IEND", &[]); + out + } + + /// An interlaced PNG doesn't stream: it's decoded whole, and compares exactly as its plain twin. + #[test] + fn an_interlaced_png_compares_as_its_plain_twin() { + let (base, head) = (sample(37, 29, 3), sample(37, 29, 4)); + let interlaced = interlaced_png_of(&base); + assert!(!Rows::streams(&interlaced)); + assert_eq!(crate::image_hash::decode(&interlaced).unwrap().to_rgba8(), base, "the test's file is right"); + let want = diff_files(&png_of(&base, false), &png_of(&head, false), DiffOptions::EXACT, &Default::default()); + let got = diff_files(&interlaced, &png_of(&head, false), DiffOptions::EXACT, &Default::default()); + let (want, got) = (want.unwrap(), got.unwrap()); + assert!(!want.0.is_identical()); + assert_eq!(serde_json::to_string(&got.0).unwrap(), serde_json::to_string(&want.0).unwrap()); + assert_eq!(got.1, want.1); + assert_eq!( + crate::image_hash::info(&interlaced).unwrap(), + crate::image_hash::info(&png_of(&base, false)).unwrap() + ); + } + #[test] fn identical_images() { let (r, _) = diff(&white(40, 40), &white(40, 40), DiffOptions::EXACT); diff --git a/crates/visualci-core/src/image_hash.rs b/crates/visualci-core/src/image_hash.rs index 108d9b10a..4901d4367 100644 --- a/crates/visualci-core/src/image_hash.rs +++ b/crates/visualci-core/src/image_hash.rs @@ -54,6 +54,8 @@ pub fn info(bytes: &[u8]) -> Result<(String, u32, u32), image::ImageError> { rows.finish()?; Ok(hex::encode(h.finalize())) }; + // A file that won't stream is decoded whole by `Rows::open`. + let whole = (!Rows::streams(bytes)).then(lock_whole_decodes); let mut rows = Rows::open(bytes)?; let (width, height) = (rows.width(), rows.height()); let fingerprint = match hash(&mut rows) { @@ -61,7 +63,7 @@ pub fn info(bytes: &[u8]) -> Result<(String, u32, u32), image::ImageError> { // A file the streaming decoder gave up on part-way: decoded whole, as before, for the decoder's own answer. Err(RowsFailed) => { drop(rows); - let _whole = WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _whole = whole.unwrap_or_else(lock_whole_decodes); hash(&mut Rows::decoded(bytes)?).map_err(|_| unreachable_rows())? } }; @@ -70,9 +72,17 @@ pub fn info(bytes: &[u8]) -> Result<(String, u32, u32), image::ImageError> { /// One decode of a whole image at a time in the process: the files [`Rows`] can't read a row at a time (JPEG, WebP, /// 16-bit or interlaced PNG) take their full size in memory (a 2880x14000 page is 160 MB as RGBA), and several at once -/// could pass the worker's memory limit (VISUALCI-PROD-SERVER-6). Held for the whole of the work on the image. +/// could pass the worker's memory limit (VISUALCI-PROD-SERVER-6). Its users take it, for the whole of their work on the +/// image, before opening a file that won't stream (`!`[`Rows::streams`]), before decoding whole a file the streaming +/// decoder gave up on, and before decoding an image whole on purpose (the PR comment's overlay). Not reentrant: take it +/// once. pub static WHOLE_DECODES: std::sync::Mutex<()> = std::sync::Mutex::new(()); +/// Take [`WHOLE_DECODES`] (a panic while holding it doesn't stop the next decode). +pub fn lock_whole_decodes() -> std::sync::MutexGuard<'static, ()> { + WHOLE_DECODES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The streaming decoder failed part-way through a file: decode it whole instead ([`Rows::decoded`]), which gives the /// image crate's own answer (its pixels, or its error). #[derive(Debug)] From c1bf90770b2235550403cfd5534ac5bcf296259b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 16:17:34 +0000 Subject: [PATCH 4/4] Keep a build's outcome independent of its run marks A cache error noting a run's start or clearing its mark is logged and the run carries on: the marks are bookkeeping, and a cache error in RunMark::end could replace a finished run's Ok(true), so run() marked a finished build failed. Test: a cache that refuses the build's mark (a trigger on the cache table) still lets an empty build conclude. --- app/src/domain/processing.rs | 19 ++++++++++++++++--- app/tests/processing_lock.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 22ca100c0..97505806f 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -359,9 +359,22 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la } // A build whose runs keep dying (out of memory) fails saying so, however its runs were queued (a retry, the // sweep, a render finishing), rather than kill another worker. - let (died, mark) = note_run_start(id).await?; + // The marks are bookkeeping, best-effort: a cache error in them never decides the build's outcome. + let (died, mark) = match note_run_start(id).await { + Ok((died, mark)) => (died, Some(mark)), + Err(e) => { + tracing::warn!(build_id = id, error = %e, "noting a run's start failed: processing without its mark"); + (0, None) + } + }; + let end = |mark: Option, concluded: bool| async move { + let Some(mark) = mark else { return }; + if let Err(e) = mark.end(concluded).await { + tracing::warn!(build_id = id, error = %e, "clearing a run's mark failed"); + } + }; if died >= i64::from(RUNS) { - mark.end(true).await?; + end(mark, true).await; return Err(laravel::Error::msg(died_message(build.number, died))); } // Boxed: processing's future is large, and the lock's own future holds it. @@ -370,7 +383,7 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la Ok(done) => *done, Err(e) => !e.is::(), }; - mark.end(concluded).await?; + end(mark, concluded).await; out }; let busy = |r: &laravel::Result| matches!(r, Err(e) if e.is::()); diff --git a/app/tests/processing_lock.rs b/app/tests/processing_lock.rs index 99c366b36..bee7119ee 100644 --- a/app/tests/processing_lock.rs +++ b/app/tests/processing_lock.rs @@ -177,6 +177,40 @@ async fn a_run_that_finishes_forgets_the_runs_that_died(_app: Application) -> la Ok(()) } +/// The marks are bookkeeping: a cache that refuses them doesn't decide the build's outcome. (The cache is Postgres's +/// `cache` table; a trigger refuses this build's mark alone.) +#[laravel::test] +async fn a_cache_error_in_the_marks_does_not_fail_the_build(_app: Application) -> laravel::Result<()> { + let build = processing_build().await?; + let id = build.id; + laravel::db::query!( + "CREATE TABLE refused_cache_keys (key text PRIMARY KEY); + CREATE FUNCTION refuse_cache_keys() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + IF EXISTS (SELECT 1 FROM refused_cache_keys r WHERE NEW.key LIKE '%' || r.key) THEN + RAISE EXCEPTION 'the cache refuses %', NEW.key; + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER refuse_cache_keys BEFORE INSERT OR UPDATE ON cache FOR EACH ROW EXECUTE FUNCTION refuse_cache_keys()" + ) + .unprepared() + .await?; + let key = format!("process-running:{id}"); + laravel::db::query!("INSERT INTO refused_cache_keys (key) VALUES ({key})").update().await?; + assert!(processing::note_run_start(id).await.is_err(), "the cache refuses the mark"); + let store = app::testing::fixtures::blob_store().await?; + let out = processing::run(id, &store, "test").await; + laravel::db::query!( + "DROP TRIGGER refuse_cache_keys ON cache; DROP FUNCTION refuse_cache_keys(); DROP TABLE refused_cache_keys" + ) + .unprepared() + .await?; + out?; + let state = app::models::Build::find_or_fail(id).await?.state; + assert!(state != "processing" && state != "failed", "an empty build concludes, mark or not: {state}"); + Ok(()) +} + /// The try past its tries waits for a dead run's hold to lapse, as a run does, rather than give up on the build at once. #[laravel::test] async fn giving_up_waits_for_a_dead_runs_hold_to_lapse(_app: Application) -> laravel::Result<()> {