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
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"plugins": [
{
"name": "visualci",
"version": "0.1.53",
"version": "0.1.54",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": { "name": "DocSpring", "url": "https://visualci.com" },
"homepage": "https://visualci.com/docs/skills/",
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "visualci",
"version": "0.1.53",
"version": "0.1.54",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": { "name": "DocSpring", "url": "https://visualci.com" },
"homepage": "https://visualci.com/docs/skills/",
Expand Down
2 changes: 1 addition & 1 deletion .cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "visualci",
"displayName": "VisualCI",
"version": "0.1.53",
"version": "0.1.54",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": {
"name": "DocSpring"
Expand Down
8 changes: 4 additions & 4 deletions Cargo.lock

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

2 changes: 1 addition & 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.24"
version = "0.2.25"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
176 changes: 160 additions & 16 deletions crates/visualci-cli/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! The CI API client: builds, snapshots, uploads.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
Expand Down Expand Up @@ -280,24 +281,36 @@ impl Client {
Ok(serde_json::from_value(self.post(&format!("/api/v1/builds/{build_id}/groups"), &body)?)?)
}

/// Register snapshots and upload the files the server doesn't have. Returns (registered, uploaded files).
///
/// Each distinct file is uploaded once per run, however many snapshots hold it: the server answers an upload URL
/// for every snapshot whose file it lacks, and identical files share one content-addressed key, which the store
/// lets one client write only about once a second (sc-9174: 14 identical files written at once were refused with
/// 429, and the upload failed).
pub fn add_snapshots(&self, build_id: &str, snapshots: &[Snapshot]) -> Result<(usize, usize)> {
let mut uploaded = 0;
let mut sent: HashSet<String> = HashSet::new();
for chunk in snapshots.chunks(BATCH) {
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();
let uploads: Vec<(String, String, Vec<u8>)> = results
.iter()
.zip(files)
.filter_map(|(r, bytes)| {
let url = r["upload_url"].as_str()?.to_string();
let content_type = r["content_type"].as_str().unwrap_or("application/octet-stream").to_string();
Some((url, content_type, bytes))
})
.collect();
let mut uploads: Vec<(String, String, Vec<u8>, String)> = Vec::new();
for (((r, p), bytes), s) in results.iter().zip(&params).zip(files).zip(chunk) {
let Some(url) = r["upload_url"].as_str() else { continue };
if !sent.insert(p["sha256"].as_str().unwrap_or(url).to_string()) {
continue;
}
let content_type = r["content_type"].as_str().unwrap_or("application/octet-stream").to_string();
let file = if s.content.is_some() {
format!("{} (from {})", s.name, s.path.display())
} else {
s.path.display().to_string()
};
uploads.push((url.to_string(), content_type, bytes, file));
}
uploaded += uploads.len();
let upload_bytes: usize = uploads.iter().map(|(_, _, b)| b.len()).sum();
let upload_bytes: usize = uploads.iter().map(|(_, _, b, _)| b.len()).sum();
let count = uploads.len();
timed(
|| format!("uploaded {count} files, {} KB", upload_bytes / 1024),
Expand All @@ -307,8 +320,9 @@ impl Client {
.chunks(uploads.len().div_ceil(UPLOADS).max(1))
.map(|part| {
scope.spawn(move || -> Result<()> {
for (url, content_type, bytes) in part {
self.put_blob(url, content_type, bytes).context("uploading a snapshot")?;
for (url, content_type, bytes, file) in part {
self.put_blob(url, content_type, bytes)
.with_context(|| format!("uploading {file}"))?;
}
Ok(())
})
Expand All @@ -327,7 +341,8 @@ impl Client {

/// Upload one file to its storage URL. The store limits how fast one client may write (R2 answers 429, 3 Dec
/// 2026: a CI run's upload failed on one), and has bad moments: a 429, a 5xx or a dropped connection is tried
/// again, up to six times in all, waiting longer each time or as long as `Retry-After` asks (at most 30 s).
/// again, up to six times in all, waiting longer each time or as long as `Retry-After` asks (at most 30 s), plus up
/// to half as long again at random, so parallel uploads refused together don't all try again together.
/// `--verbose` prints each retry.
fn put_blob(&self, url: &str, content_type: &str, bytes: &[u8]) -> Result<()> {
const TRIES: u32 = 6;
Expand All @@ -337,10 +352,15 @@ impl Client {
let wait = match sent {
Ok(response) if response.status().is_success() => return Ok(()),
Ok(response) if retryable(response.status()) && attempt < TRIES => {
retry_after(&response).unwrap_or_else(|| backoff(attempt))
jitter(retry_after(&response).unwrap_or_else(|| backoff(attempt)))
}
Ok(response) if retryable(response.status()) => {
bail!("the store refused it {TRIES} times, the last with {}", response.status())
}
Ok(response) => bail!("the store refused it with {}", response.status()),
Err(e) if (e.is_timeout() || e.is_connect() || e.is_request()) && attempt < TRIES => {
jitter(backoff(attempt))
}
Ok(response) => return Err(response.error_for_status().unwrap_err().into()),
Err(e) if (e.is_timeout() || e.is_connect() || e.is_request()) && attempt < TRIES => backoff(attempt),
Err(e) => return Err(e.into()),
};
if verbose() {
Expand Down Expand Up @@ -902,6 +922,13 @@ fn backoff(attempt: u32) -> Duration {
Duration::from_millis(500 * 2u64.pow((attempt - 1).min(4)))
}

/// `wait` and up to half as long again, at random.
fn jitter(wait: Duration) -> Duration {
use std::hash::{BuildHasher, Hasher};
let random = std::collections::hash_map::RandomState::new().build_hasher().finish();
wait + wait.mul_f64((random % 1000) as f64 / 2000.0)
}

#[cfg(test)]
mod tests {
/// A storage server for one test: answers each PUT with the next status in `statuses` (then 200), and counts
Expand Down Expand Up @@ -1151,6 +1178,123 @@ mod tests {
assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 6);
}

/// A VisualCI server and its store for one test: `POST /api/v1/builds/b1/snapshots` answers an upload URL for
/// every snapshot, as the server does for each whose file it lacks (identical files get the same URL), and each
/// `PUT` to the store is answered with the next status in `statuses` (then 200). Counts the PUTs.
fn server_and_store(statuses: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use std::io::{BufRead, BufReader, Read};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let puts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (count, base, statuses) = (puts.clone(), url.clone(), std::sync::Arc::new(statuses));
std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let (count, base, statuses) = (count.clone(), base.clone(), statuses.clone());
std::thread::spawn(move || {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut first = String::new();
reader.read_line(&mut first).unwrap();
let mut length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
length = v.trim().parse().unwrap();
}
if line == "\r\n" || line.is_empty() {
break;
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
if first.starts_with("PUT ") {
let n = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let status = statuses.get(n).copied().unwrap_or(200);
let _ = write!(
stream,
"HTTP/1.1 {status} X\r\nretry-after: 0\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
);
return;
}
assert!(first.starts_with("POST /api/v1/builds/b1/snapshots "), "{first}");
let request: serde_json::Value = serde_json::from_slice(&body).unwrap();
let answers: Vec<_> = request["snapshots"]
.as_array()
.unwrap()
.iter()
.map(|s| {
json!({
"name": s["name"], "platform": s["platform"], "content_type": s["content_type"],
"upload_url": format!("{base}/blobs/{}", s["sha256"].as_str().unwrap()),
})
})
.collect();
let body = json!({ "snapshots": answers }).to_string();
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
});
}
});
(url, puts)
}

/// `count` text files with the same content, as snapshots.
fn identical_files(dir: &std::path::Path, count: usize) -> Vec<Snapshot> {
std::fs::create_dir_all(dir).unwrap();
(0..count)
.map(|i| {
let path = dir.join(format!("sample-{i:02}.txt"));
std::fs::write(&path, "the same text in every file\n").unwrap();
Snapshot {
name: format!("sample-{i:02}"),
platform: "linux".into(),
path,
threshold: None,
engine: None,
format: None,
content: None,
ignore: None,
}
})
.collect()
}

#[test]
fn identical_files_are_uploaded_once() {
let dir = std::env::temp_dir().join(format!("visualci-same-{}", std::process::id()));
let (url, puts) = server_and_store(Vec::new());
let (registered, uploaded) = api_client(&url).add_snapshots("b1", &identical_files(&dir, 20)).unwrap();
assert_eq!((registered, uploaded), (20, 1));
assert_eq!(puts.load(std::sync::atomic::Ordering::SeqCst), 1);
std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn an_upload_the_store_refuses_once_succeeds_on_a_retry() {
let dir = std::env::temp_dir().join(format!("visualci-retry-{}", std::process::id()));
let (url, puts) = server_and_store(vec![429]);
let (_, uploaded) = api_client(&url).add_snapshots("b1", &identical_files(&dir, 3)).unwrap();
assert_eq!(uploaded, 1);
assert_eq!(puts.load(std::sync::atomic::Ordering::SeqCst), 2);
std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn an_upload_the_store_keeps_refusing_fails_naming_the_file() {
let dir = std::env::temp_dir().join(format!("visualci-refused-{}", std::process::id()));
let (url, puts) = server_and_store(vec![429; 10]);
let error = api_client(&url).add_snapshots("b1", &identical_files(&dir, 3)).unwrap_err();
let message = format!("{error:#}");
assert!(message.contains("sample-00.txt"), "{message}");
assert!(message.contains("6 times") && message.contains("429"), "{message}");
assert_eq!(puts.load(std::sync::atomic::Ordering::SeqCst), 6);
std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_bad_request_is_not_tried_again() {
let (url, seen) = store(vec![403]);
Expand Down
26 changes: 23 additions & 3 deletions crates/visualci-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1220,7 +1220,8 @@ fn pdfs_in(dir: &Path) -> Result<BTreeMap<String, PathBuf>> {
fn compare_runs(first: &Path, second: &Path) -> Result<bool> {
let a = pdfs_in(first)?;
let b = pdfs_in(second)?;
let (mut same_bytes, mut same_drawn, mut differ, mut unparsed) = (0, 0, Vec::new(), Vec::new());
let (mut same_bytes, mut same_drawn, mut differ, mut fonts_only, mut unparsed) =
(0, 0, Vec::new(), Vec::new(), Vec::new());
for (name, path_a) in &a {
let Some(path_b) = b.get(name) else {
println!("only in {}: {name}", first.display());
Expand All @@ -1235,6 +1236,8 @@ fn compare_runs(first: &Path, second: &Path) -> Result<bool> {
same_bytes += 1;
} else if fa.document == fb.document {
same_drawn += 1;
} else if fonts_differ_only(path_a, path_b) {
fonts_only.push(name.clone());
} else {
let pages: Vec<String> = fa
.pages
Expand All @@ -1255,9 +1258,20 @@ fn compare_runs(first: &Path, second: &Path) -> Result<bool> {
for name in b.keys().filter(|n| !a.contains_key(*n)) {
println!("only in {}: {name}", second.display());
}
println!("PDFs in both runs: {}", same_bytes + same_drawn + differ.len());
println!("PDFs in both runs: {}", same_bytes + same_drawn + fonts_only.len() + differ.len());
println!(" identical bytes: {same_bytes}");
println!(" different bytes, same fingerprint: {same_drawn}");
if !fonts_only.is_empty() {
println!(" same drawing, embedded fonts differ: {}", fonts_only.len());
for name in &fonts_only {
println!(" {name}");
}
println!(
" These draw the same, but their embedded font programs differ: usually a time the font subsetter \
stamps into each font. Set SOURCE_DATE_EPOCH (for example SOURCE_DATE_EPOCH=0) when generating them so \
the fonts are the same every run; otherwise each run uploads and renders them again."
);
}
println!(" different fingerprint: {}", differ.len());
for line in &differ {
println!(" {line}");
Expand All @@ -1268,7 +1282,13 @@ fn compare_runs(first: &Path, second: &Path) -> Result<bool> {
println!(" {line}");
}
}
Ok(differ.is_empty())
Ok(differ.is_empty() && fonts_only.is_empty())
}

/// Whether two PDFs with different fingerprints draw the same and differ only in their embedded font programs.
fn fonts_differ_only(a: &Path, b: &Path) -> bool {
let without = |p: &Path| std::fs::read(p).ok().and_then(|bytes| pdf::fingerprint_without_font_programs(&bytes));
matches!((without(a), without(b)), (Some(x), Some(y)) if x == y)
}

#[cfg(test)]
Expand Down
Loading
Loading