diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 33a9c495..81dc2053 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.55", + "version": "0.1.56", "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/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 485ee845..34e3d713 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.55", + "version": "0.1.56", "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/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 411a8753..838b09ee 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.55", + "version": "0.1.56", "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" diff --git a/Cargo.lock b/Cargo.lock index b523e5b7..e02d9ae0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.24" +version = "0.2.25" dependencies = [ "anyhow", "base64 0.22.1", @@ -5040,7 +5040,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.24" +version = "0.2.25" dependencies = [ "globset", "hex", @@ -5060,7 +5060,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.24" +version = "0.2.25" dependencies = [ "anyhow", "image", @@ -5075,7 +5075,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.24" +version = "0.2.25" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index 8dc4cac2..28186e85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/crates/visualci-cli/src/client.rs b/crates/visualci-cli/src/client.rs index 9e34a318..991352ac 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -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}; @@ -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 = 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)> = 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, String)> = Vec::new(); + for (((r, p), bytes), s) in results.iter().zip(¶ms).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), @@ -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(()) }) @@ -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; @@ -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() { @@ -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 @@ -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) -> (String, std::sync::Arc) { + 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 { + 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]); diff --git a/crates/visualci-cli/src/main.rs b/crates/visualci-cli/src/main.rs index 7f698058..42107742 100644 --- a/crates/visualci-cli/src/main.rs +++ b/crates/visualci-cli/src/main.rs @@ -1220,7 +1220,8 @@ fn pdfs_in(dir: &Path) -> Result> { fn compare_runs(first: &Path, second: &Path) -> Result { 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()); @@ -1235,6 +1236,8 @@ fn compare_runs(first: &Path, second: &Path) -> Result { 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 = fa .pages @@ -1255,9 +1258,20 @@ fn compare_runs(first: &Path, second: &Path) -> Result { 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}"); @@ -1268,7 +1282,13 @@ fn compare_runs(first: &Path, second: &Path) -> Result { 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)] diff --git a/crates/visualci-core/src/pdf.rs b/crates/visualci-core/src/pdf.rs index aa5e9912..ecd8a794 100644 --- a/crates/visualci-core/src/pdf.rs +++ b/crates/visualci-core/src/pdf.rs @@ -10,6 +10,10 @@ //! Page fingerprints are also the alignment key for multi-page diffs: an inserted page is one insertion in the //! sequence of page fingerprints, not N changed pages. //! +//! Embedded TrueType and OpenType font programs (`FontFile2`, `FontFile3`) are hashed with the times and checksums +//! in their `head` table zeroed: fontTools, which WeasyPrint, fpdf2 and others use to subset fonts, stamps the time +//! it saves each subset into `head.modified`, and that changes two checksums with it (sc-9164). +//! //! A fingerprint that changes when nothing visible changed only costs a render (identical renders still deduplicate //! by image hash). A fingerprint that stays the same when the drawing changed would hide a regression, so when in //! doubt this hashes more, not less. @@ -21,7 +25,10 @@ use lopdf::{Dictionary, Document, Object, ObjectId, Stream}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -/// Bumped whenever the algorithm changes, so old fingerprints never match new ones. +/// Bumped whenever a change could let two PDFs that draw differently share a fingerprint, so fingerprints from +/// before it never match ones from after. A change that only makes fewer things count (sc-9164's font timestamps) +/// keeps it: an old fingerprint can then only equal a new one for PDFs that draw the same, and only PDFs the change +/// touches get new fingerprints. pub const ALGORITHM: &str = "vci-pdf-1"; /// How the fingerprint was computed. @@ -77,7 +84,18 @@ pub fn fingerprint_bytes(bytes: &[u8]) -> PdfFingerprint { } } +/// The document fingerprint with every embedded font program left out (their dictionaries, names and widths still +/// count): equal for two PDFs whose drawing is the same and whose embedded fonts differ, which `compare-runs` reports +/// as fonts that differ only in their data. `None` when the PDF can't be parsed. +pub fn fingerprint_without_font_programs(bytes: &[u8]) -> Option { + drawn_fingerprint_with(bytes, FontPrograms::Omitted).ok().map(|(document, _)| document) +} + fn drawn_fingerprint(bytes: &[u8]) -> Result<(String, Vec), String> { + drawn_fingerprint_with(bytes, FontPrograms::Normalized) +} + +fn drawn_fingerprint_with(bytes: &[u8], fonts: FontPrograms) -> Result<(String, Vec), String> { let mut doc = Document::load_mem(bytes).map_err(|e| e.to_string())?; if doc.is_encrypted() { // Most encrypted PDFs in the wild have an empty user password (permissions only). @@ -87,7 +105,7 @@ fn drawn_fingerprint(bytes: &[u8]) -> Result<(String, Vec), String> { if page_ids.is_empty() { return Err("no pages".to_string()); } - let mut hasher = Hasher::new(&doc); + let mut hasher = Hasher::new(&doc, fonts); let pages: Vec = page_ids.iter().map(|id| hex::encode(hasher.page(*id))).collect(); let mut h = Sha256::new(); @@ -130,15 +148,29 @@ const INHERITED_KEYS: &[&[u8]] = &[b"Resources", b"MediaBox", b"CropBox", b"Rota const ANNOT_HIDDEN: i64 = 1 << 1; const ANNOT_NO_VIEW: i64 = 1 << 5; +/// The keys of a font descriptor that hold an embedded font program that may be an sfnt (TrueType or OpenType). +/// `FontFile` (Type 1) has no `head` table and is hashed as it is. +const SFNT_FONT_KEYS: &[&[u8]] = &[b"FontFile2", b"FontFile3"]; + +/// How embedded font programs are hashed. +#[derive(Clone, Copy, PartialEq, Eq)] +enum FontPrograms { + /// Their bytes, with the sfnt `head` table's times and checksums zeroed ([`normalize_sfnt`]). + Normalized, + /// Not at all: a marker stands in for each. + Omitted, +} + struct Hasher<'a> { doc: &'a Document, + fonts: FontPrograms, memo: HashMap, in_progress: HashSet, } impl<'a> Hasher<'a> { - fn new(doc: &'a Document) -> Self { - Self { doc, memo: HashMap::new(), in_progress: HashSet::new() } + fn new(doc: &'a Document, fonts: FontPrograms) -> Self { + Self { doc, fonts, memo: HashMap::new(), in_progress: HashSet::new() } } fn page(&mut self, page_id: ObjectId) -> [u8; 32] { @@ -363,12 +395,48 @@ impl<'a> Hasher<'a> { put_len(h, entries.len()); for (key, value) in entries { put_name(h, key); - self.feed(h, value); + if SFNT_FONT_KEYS.contains(&key.as_slice()) { + self.feed_font_program(h, value); + } else { + self.feed(h, value); + } + } + } + + /// An embedded font program, normalized ([`normalize_sfnt`]) or left out. A referenced one is hashed as + /// [`Self::feed`] hashes a reference, so a program the normalization doesn't change (a CFF font, or an sfnt + /// without a usable `head` table) hashes as it did before sc-9164. Not memoized: the font descriptor that holds + /// it is. + fn feed_font_program(&mut self, h: &mut Sha256, value: &Object) { + if self.fonts == FontPrograms::Omitted { + h.update(b"font-program"); + return; + } + match value { + Object::Stream(stream) => self.feed_stream_as(h, stream, true), + Object::Reference(id) => match self.doc.get_object(*id) { + Ok(Object::Stream(stream)) => { + let stream = stream.clone(); + let mut inner = Sha256::new(); + self.feed_stream_as(&mut inner, &stream, true); + h.update(b"R"); + h.update(inner.finalize()); + } + _ => self.feed(h, value), + }, + other => self.feed(h, other), } } fn feed_stream(&mut self, h: &mut Sha256, stream: &Stream) { - let (data, decoded) = stream_data(stream); + self.feed_stream_as(h, stream, false); + } + + fn feed_stream_as(&mut self, h: &mut Sha256, stream: &Stream, font_program: bool) { + let (mut data, decoded) = stream_data(stream); + if font_program && decoded { + normalize_sfnt(&mut data); + } h.update(b"stream"); let skipped: &[&[u8]] = if decoded { &[b"Filter", b"DecodeParms"] } else { &[] }; self.feed_dict(h, &stream.dict, skipped); @@ -389,6 +457,42 @@ fn stream_data(stream: &Stream) -> (Vec, bool) { } } +/// Zero what fontTools rewrites each time it saves a font subset, in an sfnt (TrueType or OpenType) font program: +/// `head.modified`, `head.checkSumAdjustment` (a checksum of the whole font) and the table directory's checksum of +/// `head`. Every other byte, the glyphs and metrics above all, still counts. The data is untrusted: anything that +/// isn't a well-formed sfnt with a complete `head` table (a CFF font, a font collection, a truncated directory or +/// table) is left as it is, and nothing here can panic. +fn normalize_sfnt(data: &mut [u8]) { + const HEAD_MAGIC: u32 = 0x5F0F_3CF5; + let u16_at = |d: &[u8], at: usize| d.get(at..at + 2).map(|b| u16::from_be_bytes([b[0], b[1]])); + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])); + let Some(version) = data.get(..4) else { return }; + if !matches!(version, [0, 1, 0, 0] | b"true" | b"OTTO") { + return; + } + let Some(tables) = u16_at(data, 4) else { return }; + // A directory that claims more tables than the data holds isn't a font to trust. + if 12 + usize::from(tables) * 16 > data.len() { + return; + } + // The table records: tag, checksum, offset, length (16 bytes each), after the 12-byte header. + let head_record = (0..usize::from(tables)).map(|i| 12 + i * 16).find(|&at| data.get(at..at + 4) == Some(b"head")); + let Some(record) = head_record else { return }; + let (Some(offset), Some(length)) = (u32_at(data, record + 8), u32_at(data, record + 12)) else { return }; + let (Ok(offset), Ok(length)) = (usize::try_from(offset), usize::try_from(length)) else { return }; + // head: version, fontRevision, checkSumAdjustment (8), magicNumber (12), flags, unitsPerEm, created (20), + // modified (28..36), and more after it. + if length < 36 || offset.checked_add(36).is_none_or(|end| end > data.len()) { + return; + } + if u32_at(data, offset + 12) != Some(HEAD_MAGIC) { + return; + } + data[record + 4..record + 8].fill(0); + data[offset + 8..offset + 12].fill(0); + data[offset + 28..offset + 36].fill(0); +} + fn put_len(h: &mut Sha256, len: usize) { h.update((len as u64).to_le_bytes()); } @@ -474,6 +578,197 @@ mod tests { out } + /// A synthetic TrueType subset: an sfnt with a `head` table (saved at `modified`) and a `glyf` table holding + /// `glyphs`, with real table checksums and `checkSumAdjustment`, as fontTools writes them. + fn truetype_subset(modified: u64, glyphs: &[u8]) -> Vec { + fn checksum(data: &[u8]) -> u32 { + data.chunks(4).fold(0u32, |sum, c| { + let mut word = [0u8; 4]; + word[..c.len()].copy_from_slice(c); + sum.wrapping_add(u32::from_be_bytes(word)) + }) + } + let mut head = Vec::new(); + head.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // version + head.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // fontRevision + head.extend_from_slice(&0u32.to_be_bytes()); // checkSumAdjustment, filled in below + head.extend_from_slice(&0x5F0F_3CF5u32.to_be_bytes()); // magicNumber + head.extend_from_slice(&0x000Bu16.to_be_bytes()); // flags + head.extend_from_slice(&1000u16.to_be_bytes()); // unitsPerEm + head.extend_from_slice(&3_600_000_000u64.to_be_bytes()); // created + head.extend_from_slice(&modified.to_be_bytes()); // modified + head.extend_from_slice(&[0, 0, 0, 0, 0x03, 0xE8, 0x03, 0xE8]); // xMin, yMin, xMax, yMax + head.extend_from_slice(&[0, 0, 0, 3, 0, 2, 0, 0, 0, 0]); // macStyle .. glyphDataFormat + let mut glyf = glyphs.to_vec(); + let tables: [(&[u8; 4], &mut Vec); 2] = [(b"glyf", &mut glyf), (b"head", &mut head)]; + let mut font = Vec::new(); + font.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + font.extend_from_slice(&2u16.to_be_bytes()); + font.extend_from_slice(&[0, 32, 0, 1, 0, 0]); // searchRange, entrySelector, rangeShift + let mut offset = 12 + 16 * tables.len(); + let mut bodies = Vec::new(); + for (tag, data) in tables { + font.extend_from_slice(tag); + font.extend_from_slice(&checksum(data).to_be_bytes()); + font.extend_from_slice(&(offset as u32).to_be_bytes()); + font.extend_from_slice(&(data.len() as u32).to_be_bytes()); + while data.len() % 4 != 0 { + data.push(0); + } + offset += data.len(); + bodies.extend_from_slice(data); + } + font.extend_from_slice(&bodies); + let adjustment = 0xB1B0_AFBAu32.wrapping_sub(checksum(&font)); + let head_at = 12 + 32 + glyf_len(glyphs.len()); + font[head_at + 8..head_at + 12].copy_from_slice(&adjustment.to_be_bytes()); + font + } + + fn glyf_len(len: usize) -> usize { + len.div_ceil(4) * 4 + } + + /// A one-page PDF drawing "Hello" in an embedded TrueType font (`FontFile2`, Flate-compressed). + fn pdf_with_font(font_program: &[u8], date: &str) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let mut file = Stream::new(dictionary! { "Length1" => font_program.len() as i64 }, font_program.to_vec()); + file.compress().unwrap(); + let file_id = doc.add_object(file); + let descriptor_id = doc.add_object(dictionary! { + "Type" => "FontDescriptor", + "FontName" => "ABCDEF+DejaVuSans", + "Flags" => 32, + "FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], + "ItalicAngle" => 0, + "Ascent" => 800, + "Descent" => -200, + "CapHeight" => 700, + "StemV" => 80, + "FontFile2" => file_id, + }); + let font_id = doc.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "TrueType", + "BaseFont" => "ABCDEF+DejaVuSans", + "FirstChar" => 72, + "LastChar" => 72, + "Widths" => vec![600.into()], + "FontDescriptor" => descriptor_id, + }); + let content = Content { + operations: vec![ + Operation::new("BT", vec![]), + Operation::new("Tf", vec!["F1".into(), 24.into()]), + Operation::new("Tj", vec![Object::string_literal("Hello")]), + Operation::new("ET", vec![]), + ], + }; + let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap())); + let page_id = doc.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "Contents" => content_id, + "Resources" => dictionary! { "Font" => dictionary! { "F1" => font_id } }, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + }); + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1 }), + ); + let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + let info_id = doc.add_object(dictionary! { "CreationDate" => Object::string_literal(date) }); + doc.trailer.set("Root", catalog_id); + doc.trailer.set("Info", info_id); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out + } + + #[test] + fn ignores_the_time_a_font_subset_was_saved() { + let glyphs = b"glyph outlines for H, e, l and o"; + let first = truetype_subset(3_900_000_000, glyphs); + let second = truetype_subset(3_900_000_042, glyphs); + // The subsets differ in head.modified, head.checkSumAdjustment and the directory's head checksum. + let differing = first.iter().zip(&second).filter(|(a, b)| a != b).count(); + assert!((3..=12).contains(&differing), "{differing}"); + let a = fingerprint_bytes(&pdf_with_font(&first, "D:20261204100000Z")); + let b = fingerprint_bytes(&pdf_with_font(&second, "D:20261204100500Z")); + assert_eq!(a.method, Method::Drawn); + assert_ne!(a.bytes_sha256, b.bytes_sha256); + assert_eq!(a.document, b.document); + assert_eq!(a.pages, b.pages); + } + + #[test] + fn a_font_with_other_glyphs_still_changes_the_fingerprint() { + let a = fingerprint_bytes(&pdf_with_font(&truetype_subset(3_900_000_000, b"glyph outlines, H e l o"), "D:1")); + let b = fingerprint_bytes(&pdf_with_font(&truetype_subset(3_900_000_000, b"glyph outlines, H e l 0"), "D:1")); + assert_ne!(a.document, b.document); + assert_ne!(a.pages, b.pages); + // The drawing is the same apart from the font program, which compare-runs reports as such. + let without = |pdf: &[u8]| fingerprint_without_font_programs(pdf).unwrap(); + assert_eq!( + without(&pdf_with_font(&truetype_subset(1, b"glyph outlines, H e l o"), "D:1")), + without(&pdf_with_font(&truetype_subset(1, b"glyph outlines, H e l 0"), "D:1")) + ); + } + + #[test] + fn a_font_program_left_unchanged_hashes_as_it_did() { + // A CFF font (FontFile3 /Type1C) isn't an sfnt: normalizing leaves it as it is. + let mut cff = b"\x01\x00\x04\x02CFF data".to_vec(); + let before = cff.clone(); + normalize_sfnt(&mut cff); + assert_eq!(cff, before); + } + + #[test] + fn malformed_fonts_are_left_alone_without_panicking() { + let good = truetype_subset(3_900_000_000, b"glyphs"); + let mut cases: Vec> = vec![ + Vec::new(), + b"true".to_vec(), + good[..10].to_vec(), // header cut short + good[..20].to_vec(), // directory cut short + good[..good.len() - 30].to_vec(), // head table cut short + ]; + // So many tables claimed that the directory runs off the end. + let mut many = good.clone(); + many[4..6].copy_from_slice(&u16::MAX.to_be_bytes()); + cases.push(many); + // head's offset past the end, and one that overflows. + for offset in [u32::MAX, u32::MAX - 10, 10_000] { + let mut bad = good.clone(); + let record = 12 + 16; // glyf comes first + bad[record + 8..record + 12].copy_from_slice(&offset.to_be_bytes()); + cases.push(bad); + } + // head too short to hold modified, and a wrong magic number. + let mut short = good.clone(); + short[12 + 16 + 12..12 + 16 + 16].copy_from_slice(&20u32.to_be_bytes()); + cases.push(short); + let mut magic = good.clone(); + let head_at = 12 + 32 + glyf_len(6); + magic[head_at + 12] ^= 0xFF; + cases.push(magic); + for case in &mut cases { + let before = case.clone(); + normalize_sfnt(case); + assert_eq!(*case, before); + } + // A well-formed one is normalized. + let mut normalized = good.clone(); + normalize_sfnt(&mut normalized); + assert_ne!(normalized, good); + // And PDFs embedding the malformed ones still fingerprint. + for case in &cases { + assert_eq!(fingerprint_bytes(&pdf_with_font(case, "D:1")).method, Method::Drawn); + } + } + #[test] fn ignores_dates_ids_and_subset_tags() { let a = fingerprint_bytes(&sample_pdf("Hello", "AAAA", "D:20260101000000Z", "ABCDEF")); diff --git a/frontend/content/docs/pdfs.md b/frontend/content/docs/pdfs.md index a4547e91..8760f96d 100644 --- a/frontend/content/docs/pdfs.md +++ b/frontend/content/docs/pdfs.md @@ -47,6 +47,8 @@ Each page is fingerprinted too, so pages are matched by content instead of by po `visualci compare-runs ` checks that your PDFs' fingerprints are stable: run your tests twice, then compare the two output directories. It exits 1 when a fingerprint differs, which usually means the PDF draws something that changes on every run, such as the current time. +Embedded fonts count too, apart from the time a font subsetter stamps into each font it saves (the `head` table's modification time and the checksums that follow from it), which the fingerprint leaves out. When `compare-runs` reports PDFs that draw the same but whose embedded fonts still differ, the generator is writing something else that changes into its fonts: set `SOURCE_DATE_EPOCH` (for example `SOURCE_DATE_EPOCH=0`) when you generate them. WeasyPrint, fpdf2 and other tools that subset fonts with fontTools honour it, and so do many other generators for their creation dates. + ## What a change looks like For each changed page, `get_snapshot` (and the web app) shows: diff --git a/gemini-extension.json b/gemini-extension.json index f7255ffb..92ca0765 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.55", + "version": "0.1.56", "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.", "mcpServers": { "visualci": { diff --git a/skills/visualci-pdfs/SKILL.md b/skills/visualci-pdfs/SKILL.md index 29a5cf3a..9d972434 100644 --- a/skills/visualci-pdfs/SKILL.md +++ b/skills/visualci-pdfs/SKILL.md @@ -52,6 +52,8 @@ Each page is fingerprinted too, so pages are matched by content instead of by po `visualci compare-runs ` checks that your PDFs' fingerprints are stable: run your tests twice, then compare the two output directories. It exits 1 when a fingerprint differs, which usually means the PDF draws something that changes on every run, such as the current time. +Embedded fonts count too, apart from the time a font subsetter stamps into each font it saves (the `head` table's modification time and the checksums that follow from it), which the fingerprint leaves out. When `compare-runs` reports PDFs that draw the same but whose embedded fonts still differ, the generator is writing something else that changes into its fonts: set `SOURCE_DATE_EPOCH` (for example `SOURCE_DATE_EPOCH=0`) when you generate them. WeasyPrint, fpdf2 and other tools that subset fonts with fontTools honour it, and so do many other generators for their creation dates. + ## What a change looks like For each changed page, `get_snapshot` (and the web app) shows: