Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -20,6 +20,11 @@ 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"
# 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"
Expand Down
7 changes: 3 additions & 4 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ImageInfo, String> {
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
Expand Down
18 changes: 3 additions & 15 deletions app/src/domain/diffs.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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()))?
Expand Down
92 changes: 65 additions & 27 deletions app/src/domain/matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, lock_whole_decodes};

use crate::models::{Build, Diff, Snapshot, SnapshotPage};
use crate::storage::BlobStore;
Expand Down Expand Up @@ -54,38 +56,58 @@ async fn page_changes(snapshot_id: i64) -> laravel::Result<Vec<PageChange>> {
}

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<String, Option<RgbaImage>>,
cache: HashMap<String, Option<Arc<Vec<u8>>>>,
}

impl Images<'_> {
async fn get(&mut self, sha: &str) -> Option<&RgbaImage> {
async fn get(&mut self, sha: &str) -> Option<Arc<Vec<u8>>> {
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<bool, RowsFailed> {
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)
};
// 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.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)
}
}
true
}

/// Whether every region of `ours` is a region `theirs` changed, from the same old pixels to the same new ones.
Expand All @@ -97,9 +119,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, &regions)).await.unwrap_or(false);
if !same {
return false;
}
}
Expand Down Expand Up @@ -147,6 +171,8 @@ pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result<usize> {
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() {
Expand Down Expand Up @@ -184,18 +210,30 @@ pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result<usize> {
mod tests {
use super::*;

fn png(img: &image::RgbaImage) -> Vec<u8> {
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]));
}
}

Expand Down
Loading