From 07393f502bdf83e1cad494301bac3ed4d8b0adb5 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 16:24:48 +1300 Subject: [PATCH 1/2] CLI: decode and fingerprint snapshots on every core, and --verbose timings (sc-8999) visualci upload decoded each PNG one at a time to fingerprint it: 68 s for 144 unchanged screenshots on our CI. client::registrations now fingerprints a batch across the machine's cores (std::thread::scope over chunks), in order, with the first failing file's error as before; the large-suite group check does the same. --verbose prints the time for hashing, each API call and the uploads. CLI 0.2.18. --- Cargo.lock | 10 +- Cargo.toml | 2 +- crates/visualci-cli/src/client.rs | 171 ++++++++++++++---- crates/visualci-cli/src/main.rs | 17 +- server/frontend/content/docs/reference/cli.md | 2 +- 5 files changed, 156 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 803d552f..fc7c49e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5238,7 +5238,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "visualci-cli" -version = "0.2.17" +version = "0.2.18" dependencies = [ "anyhow", "base64 0.22.1", @@ -5255,7 +5255,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.17" +version = "0.2.18" dependencies = [ "globset", "hex", @@ -5275,7 +5275,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.17" +version = "0.2.18" dependencies = [ "anyhow", "image", @@ -5290,7 +5290,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.17" +version = "0.2.18" dependencies = [ "image", "serde", @@ -5300,7 +5300,7 @@ dependencies = [ [[package]] name = "visualci_server" -version = "0.2.17" +version = "0.2.18" dependencies = [ "aes-gcm", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 68f2f156..69534cf5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*", "server", "server/migration"] [workspace.package] -version = "0.2.17" +version = "0.2.18" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/crates/visualci-cli/src/client.rs b/crates/visualci-cli/src/client.rs index c84cd560..28659ab1 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -13,6 +13,57 @@ use visualci_core::snapshot_text::Format; pub const DEFAULT_API_URL: &str = "https://api.visualci.com"; const BATCH: usize = 500; +static VERBOSE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// `--verbose`: print how long hashing, each API call and the uploads take. +pub fn set_verbose(on: bool) { + VERBOSE.store(on, std::sync::atomic::Ordering::Relaxed); +} + +fn verbose() -> bool { + VERBOSE.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Run `f`, and with `--verbose` print how long it took. +pub fn timed(label: impl FnOnce() -> String, f: impl FnOnce() -> T) -> T { + if !verbose() { + return f(); + } + let start = Instant::now(); + let out = f(); + eprintln!("visualci: {} ({} ms)", label(), start.elapsed().as_millis()); + out +} + +/// `f` over every item on all the machine's cores, results in the items' order. An error stops the run and the +/// first failing item's error (in order) is returned. +pub fn par_map(items: &[T], f: impl Fn(&T) -> Result + Sync) -> Result> { + let threads = std::thread::available_parallelism().map_or(1, std::num::NonZero::get).min(items.len()); + if threads <= 1 { + return items.iter().map(&f).collect(); + } + let f = &f; + std::thread::scope(|scope| { + let handles: Vec<_> = items + .chunks(items.len().div_ceil(threads)) + .map(|part| scope.spawn(move || part.iter().map(f).collect::>>())) + .collect(); + let mut out = Vec::with_capacity(items.len()); + for h in handles { + out.extend(h.join().map_err(|_| anyhow::anyhow!("a hashing thread panicked"))??); + } + Ok(out) + }) +} + +/// Every snapshot's registration and bytes (`registration`), decoded and fingerprinted in parallel, in order. +/// +/// # Errors +/// The first snapshot (in order) whose file can't be read or classified. +pub fn registrations(snapshots: &[Snapshot]) -> Result)>> { + timed(|| format!("hashed {} snapshots", snapshots.len()), || par_map(snapshots, registration)) +} + pub struct Client { api_url: String, token: String, @@ -106,13 +157,23 @@ impl Client { } fn post(&self, path: &str, body: &serde_json::Value) -> Result { - let response = self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body).send()?; - read(response, path) + timed( + || format!("POST {path}"), + || { + let response = self.authed(self.http.post(format!("{}{path}", self.api_url))).json(body).send()?; + read(response, path) + }, + ) } fn get(&self, path: &str) -> Result { - let response = self.authed(self.http.get(format!("{}{path}", self.api_url))).send()?; - read(response, path) + timed( + || format!("GET {path}"), + || { + let response = self.authed(self.http.get(format!("{}{path}", self.api_url))).send()?; + read(response, path) + }, + ) } /// The MCP server: `$VISUALCI_MCP_URL`, else the API's URL with its `api.` host renamed `mcp.` (production), else @@ -218,13 +279,7 @@ impl Client { pub fn add_snapshots(&self, build_id: &str, snapshots: &[Snapshot]) -> Result<(usize, usize)> { let mut uploaded = 0; for chunk in snapshots.chunks(BATCH) { - let mut files = Vec::with_capacity(chunk.len()); - let mut params = Vec::with_capacity(chunk.len()); - for s in chunk { - let (p, bytes) = registration(s)?; - params.push(p); - files.push(bytes); - } + let (params, files): (Vec<_>, Vec<_>) = registrations(chunk)?.into_iter().unzip(); let response = self.post(&format!("/api/v1/builds/{build_id}/snapshots"), &json!({ "snapshots": params }))?; let results = response["snapshots"].as_array().cloned().unwrap_or_default(); @@ -238,29 +293,36 @@ impl Client { }) .collect(); uploaded += uploads.len(); - std::thread::scope(|scope| -> Result<()> { - let handles: Vec<_> = uploads - .chunks(uploads.len().div_ceil(8).max(1)) - .map(|part| { - scope.spawn(move || -> Result<()> { - for (url, content_type, bytes) in part { - self.http - .put(url) - .header("content-type", content_type.as_str()) - .body(bytes.clone()) - .send()? - .error_for_status() - .context("uploading a snapshot")?; - } - Ok(()) - }) + let upload_bytes: usize = uploads.iter().map(|(_, _, b)| b.len()).sum(); + let count = uploads.len(); + timed( + || format!("uploaded {count} files, {} KB", upload_bytes / 1024), + || { + std::thread::scope(|scope| -> Result<()> { + let handles: Vec<_> = uploads + .chunks(uploads.len().div_ceil(8).max(1)) + .map(|part| { + scope.spawn(move || -> Result<()> { + for (url, content_type, bytes) in part { + self.http + .put(url) + .header("content-type", content_type.as_str()) + .body(bytes.clone()) + .send()? + .error_for_status() + .context("uploading a snapshot")?; + } + Ok(()) + }) + }) + .collect(); + for h in handles { + h.join().map_err(|_| anyhow::anyhow!("upload thread panicked"))??; + } + Ok(()) }) - .collect(); - for h in handles { - h.join().map_err(|_| anyhow::anyhow!("upload thread panicked"))??; - } - Ok(()) - })?; + }, + )?; } Ok((snapshots.len(), uploaded)) } @@ -596,6 +658,49 @@ fn looks_binary(head: &[u8]) -> bool { #[cfg(test)] mod tests { + #[test] + fn parallel_registrations_match_the_sequential_ones() { + let dir = std::env::temp_dir().join(format!("visualci-par-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let snap = |name: &str, path: std::path::PathBuf, content: Option>| Snapshot { + name: name.into(), + platform: "linux".into(), + path, + threshold: Some(0.1), + engine: None, + format: None, + content, + ignore: None, + }; + let mut snaps = Vec::new(); + for i in 0..40u32 { + let img = image::RgbaImage::from_fn(64, 48, |x, y| { + image::Rgba([(x * i) as u8, (y + i) as u8, (x ^ y ^ i) as u8, 255]) + }); + let path = dir.join(format!("shot-{i}.png")); + img.save(&path).unwrap(); + snaps.push(snap(&format!("shot-{i}"), path, None)); + if i % 7 == 0 { + let text = dir.join(format!("data-{i}.json")); + std::fs::write(&text, format!("{{\"i\": {i}}}")).unwrap(); + snaps.push(snap(&format!("data-{i}"), text, None)); + snaps.push(snap(&format!("inline-{i}"), dir.join("x.snap"), Some(format!("v{i}").into_bytes()))); + } + } + let sequential: Vec<_> = snaps.iter().map(|s| registration(s).unwrap()).collect(); + let parallel = registrations(&snaps).unwrap(); + assert_eq!(parallel, sequential); + // Distinct images got distinct fingerprints, so the order really was checked. + assert_ne!(parallel[0].0["fingerprint"], parallel[1].0["fingerprint"]); + + // The first failing snapshot's error, as the sequential loop gave. + snaps.insert(5, snap("missing-a", dir.join("missing-a.png"), None)); + snaps.push(snap("missing-b", dir.join("missing-b.png"), None)); + let err = format!("{:#}", registrations(&snaps).unwrap_err()); + assert!(err.contains("missing-a.png"), "{err}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn finds_the_mcp_server_from_the_api_url() { assert_eq!(super::mcp_url_for("https://api.visualci.com"), "https://mcp.visualci.com/mcp"); diff --git a/crates/visualci-cli/src/main.rs b/crates/visualci-cli/src/main.rs index d75c9e8f..7f698058 100644 --- a/crates/visualci-cli/src/main.rs +++ b/crates/visualci-cli/src/main.rs @@ -22,6 +22,9 @@ use crate::client::{Client, Snapshot}; #[derive(Parser)] #[command(name = "visualci", version, about = "Visual regression testing for documents, browsers and apps")] struct Cli { + /// Print how long hashing, each API call and the uploads take. + #[arg(long, global = true)] + verbose: bool, #[command(subcommand)] command: Command, } @@ -469,7 +472,9 @@ fn main() { } fn run() -> Result<()> { - match Cli::parse().command { + let cli = Cli::parse(); + client::set_verbose(cli.verbose); + match cli.command { Command::Fingerprint { files } => { for file in files { let value = fingerprint(&file)?; @@ -842,10 +847,10 @@ fn send_snapshots(client: &Client, build_id: &str, snapshots: &[Snapshot]) -> Re return Ok(()); } let group_depth = config_file::discover().ok().flatten().and_then(|f| f.config.group_depth); - let entries = snapshots - .iter() - .map(|s| client::registration(s).and_then(|(params, _)| client::entry_of(¶ms))) - .collect::>>()?; + let entries = client::timed( + || format!("hashed {} snapshots for the group check", snapshots.len()), + || client::par_map(snapshots, |s| client::registration(s).and_then(|(params, _)| client::entry_of(¶ms))), + )?; let check = client.check_groups(build_id, &entries, group_depth)?; if let Some(n) = check.same_as_build { eprintln!("{} snapshots: nothing changed since build #{n}", snapshots.len()); @@ -866,7 +871,7 @@ fn send_snapshots(client: &Client, build_id: &str, snapshots: &[Snapshot]) -> Re Ok(()) } -/// The device-code sign-in:/// The device-code sign-in:/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the +/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the /// browser, then keep the personal access token it gives. fn login(api: &str, no_browser: bool) -> Result<()> { let http = reqwest::blocking::Client::builder() diff --git a/server/frontend/content/docs/reference/cli.md b/server/frontend/content/docs/reference/cli.md index 366de67f..fac8bca4 100644 --- a/server/frontend/content/docs/reference/cli.md +++ b/server/frontend/content/docs/reference/cli.md @@ -5,7 +5,7 @@ description: Every visualci command and option, and the environment variables th Install it on Linux or macOS with `curl -fsSL https://visualci.com/install.sh | sh` (set `VISUALCI_VERSION=0.2.12` to pin a release, and `VISUALCI_INSTALL_DIR` for somewhere other than `/usr/local/bin`), or anywhere with Rust with `cargo install --git https://github.com/DocSpring/visualci visualci-cli`. `visualci --help` and `visualci --help` print the same options. -Every command that talks to the server takes `--token` (default `$VISUALCI_TOKEN`, a project token, else the token `visualci login` kept) and `--api-url` (default `$VISUALCI_API_URL`, else `https://api.visualci.com`). With a personal token, it also needs the project: `--project org/project`, `$VISUALCI_PROJECT`, or `project:` in visualci.yml. Errors exit with status 2. +Every command that talks to the server takes `--token` (default `$VISUALCI_TOKEN`, a project token, else the token `visualci login` kept) and `--api-url` (default `$VISUALCI_API_URL`, else `https://api.visualci.com`). With a personal token, it also needs the project: `--project org/project`, `$VISUALCI_PROJECT`, or `project:` in visualci.yml. Errors exit with status 2. `--verbose` prints how long each step takes: hashing the files, each call to the server, and the uploads. ## visualci login From 81aad919aa45a120bf3cb111e0788a504a4d9872 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 16:36:22 +1300 Subject: [PATCH 2/2] app/Cargo.lock: visualci-core 0.2.18 --- app/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Cargo.lock b/app/Cargo.lock index 6591b927..72f6c404 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -4949,7 +4949,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.17" +version = "0.2.18" dependencies = [ "globset", "hex",