diff --git a/Cargo.lock b/Cargo.lock index baca7349..f47e5ec6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5026,7 +5026,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.26" +version = "0.2.27" dependencies = [ "anyhow", "base64 0.22.1", @@ -5043,7 +5043,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.26" +version = "0.2.27" dependencies = [ "globset", "hex", @@ -5063,7 +5063,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.26" +version = "0.2.27" dependencies = [ "anyhow", "image", @@ -5078,7 +5078,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.26" +version = "0.2.27" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index e6962071..3f24a92f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.26" +version = "0.2.27" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index 7dd08b7d..959d0d46 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -446,6 +446,7 @@ impl Seeder<'_> { format: None, meta: serde_json::json!({}), ignore: None, + error: None, } }; let size_of = |bytes: &[u8]| i64::try_from(bytes.len()).unwrap_or(i64::MAX); diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 41bb955b..1d3e02c8 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -585,6 +585,15 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> for mut snapshot in snapshots { seen.insert((snapshot.name.clone(), snapshot.platform.clone())); if snapshot.state == "failed" { + // A failure stands for the version it was compared with (baselines: approving it keeps that baseline), and + // its page shows that version beside the error: a test that crashed (sc-9177) or a file that never came. + let key = (snapshot.name.clone(), snapshot.platform.clone()); + if let Some(base) = base_snapshots.get(&key) + && snapshot.base_snapshot_id != Some(base.id) + { + let base_snapshot_id = Some(base.id); + update!(snapshot { base_snapshot_id }).await?; + } continue; } // Out of credits part-way through a large build: stop between batches rather than compare the rest diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index 55bea9fd..e3559233 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -25,15 +25,19 @@ pub struct SnapshotParams { pub name: String, #[serde(default)] pub platform: String, + /// `document`, `image` or `text`. A failure ([`Self::error`]) may leave it out: it's then a document. + #[serde(default)] pub kind: String, /// Documents: the PDF fingerprint. Images: the pixel fingerprint. Text: the SHA-256 of the text. Optional /// (sc-8999): without it, the server uses the one it computed for the file, or computes it once the file arrives. #[serde(default)] pub fingerprint: Option, - /// SHA-256 of the file's bytes. + /// SHA-256 of the file's bytes. Not with [`Self::error`]. + #[serde(default)] pub sha256: String, - #[serde(deserialize_with = "super::lenient::number")] + #[serde(default, deserialize_with = "super::lenient::number")] pub size: i64, + #[serde(default)] pub content_type: String, #[serde(default, deserialize_with = "super::lenient::optional")] pub threshold: Option, @@ -48,8 +52,16 @@ pub struct SnapshotParams { /// Ignore rules set in the test, for this snapshot only: `{json_paths, text_patterns}`. #[serde(default)] pub ignore: Option, + /// The test crashed before it wrote the file (sc-9177): the snapshot is failed with this message, in place under + /// its own name, so the build shows it as failed rather than removed. Sent with no file (`sha256`, `size` and + /// `content_type` left out). Approving it keeps the previous baseline. + #[serde(default)] + pub error: Option, } +/// The longest failure message a client may send ([`SnapshotParams::error`]). +pub const MAX_ERROR_BYTES: usize = 16 * 1024; + /// Part of the error for a snapshot name sent twice to one build with different content (the API answers 409). pub const ALREADY_UPLOADED: &str = "already uploaded to this build"; @@ -61,9 +73,6 @@ impl SnapshotParams { if self.name.trim().is_empty() || self.name.len() > 500 { return Err(format!("snapshot name must be 1 to 500 characters: {:?}", self.name)); } - if self.content_type.is_empty() || self.content_type.len() > 255 { - return Err(format!("{}: content_type must be 1 to 255 characters", self.name)); - } if self.meta.to_string().len() > 16 * 1024 { return Err(format!("{}: meta must be under 16 KB", self.name)); } @@ -73,9 +82,24 @@ impl SnapshotParams { if self.platform == CONFIG_PLATFORM { return Err(format!("{}: the platform {CONFIG_PLATFORM:?} is reserved", self.name)); } - if !KINDS.contains(&self.kind.as_str()) { + if !KINDS.contains(&self.kind()) { return Err(format!("{}: kind must be one of {KINDS:?}", self.name)); } + if let Some(error) = &self.error { + if error.trim().is_empty() || error.len() > MAX_ERROR_BYTES { + return Err(format!("{}: error must be 1 to {MAX_ERROR_BYTES} bytes", self.name)); + } + if !self.sha256.is_empty() || self.size != 0 || !self.content_type.is_empty() { + return Err(format!( + "{}: a failure (error) has no file: leave out sha256, size and content_type", + self.name + )); + } + return Ok(()); + } + if self.content_type.is_empty() || self.content_type.len() > 255 { + return Err(format!("{}: content_type must be 1 to 255 characters", self.name)); + } // Images are served back (the gallery, on the app's own origin): only image types, never one a browser would // run. if self.kind == "image" && !IMAGE_TYPES.contains(&self.content_type.as_str()) { @@ -112,9 +136,15 @@ impl SnapshotParams { Ok(()) } + /// The snapshot's kind: a failure sent without one is a document. + #[must_use] + pub fn kind(&self) -> &str { + if self.kind.is_empty() && self.error.is_some() { "document" } else { &self.kind } + } + /// A text snapshot's format: the explicit one, else from the content type, else from the name's extension. pub fn text_format(&self) -> Option { - (self.kind == "text") + (self.kind() == "text") .then(|| Format::detect(self.format.as_deref(), Some(&self.content_type), Some(&self.name))) } } @@ -182,7 +212,7 @@ struct Row<'a> { kind: &'a str, format: Option, fingerprint: String, - sha256: &'a str, + sha256: Option<&'a str>, render_id: Option, engine: &'a Option, threshold: Option, @@ -190,6 +220,8 @@ struct Row<'a> { meta: serde_json::Value, ignore_rules: serde_json::Value, environment: String, + state: &'static str, + error: Option<&'a str>, } /// Record a snapshot in a build: [`register_all`] for one, with its row. @@ -252,6 +284,7 @@ pub async fn register_all( let files: Vec = params .iter() + .filter(|p| p.error.is_none()) .map(|p| super::blobs::NewBlob { sha256: p.sha256.clone(), size: p.size, content_type: p.content_type.clone() }) .collect(); let blobs = super::blobs::register_many(&files).await?; @@ -260,7 +293,11 @@ pub async fn register_all( .map(|p| { p.fingerprint .clone() - .or_else(|| super::blobs::known_fingerprint(&p.kind, blobs.get(&p.sha256), &p.sha256)) + .or_else(|| { + p.error + .is_none() + .then(|| super::blobs::known_fingerprint(p.kind(), blobs.get(&p.sha256), &p.sha256))? + }) .unwrap_or_default() }) .collect(); @@ -270,14 +307,14 @@ pub async fn register_all( .iter() .zip(&fingerprints) .zip(&renderer_keys) - .filter(|((p, fp), _)| p.kind == "document" && !fp.is_empty()) + .filter(|((p, fp), _)| p.kind() == "document" && p.error.is_none() && !fp.is_empty()) .map(|((_, fp), key)| (fp.clone(), key.clone())) .collect(); wanted.sort_unstable(); wanted.dedup(); let renders = usable_renders(build.project_id, &wanted).await?; let render_of = |i: usize| -> Option { - (params[i].kind == "document" && !fingerprints[i].is_empty()) + (params[i].kind() == "document" && params[i].error.is_none() && !fingerprints[i].is_empty()) .then(|| renders.get(&(fingerprints[i].clone(), renderer_keys[i].clone())).copied()) .flatten() }; @@ -295,17 +332,19 @@ pub async fn register_all( group_key: grouping.key(&p.name), name: &p.name, platform: &p.platform, - kind: &p.kind, + kind: p.kind(), format: p.text_format().map(|f| f.as_str().to_string()), fingerprint: fingerprints[i].clone(), - sha256: &p.sha256, + sha256: p.error.is_none().then_some(p.sha256.as_str()), render_id: render_of(i), engine: &p.engine, threshold: p.threshold, aa: p.ignore_anti_aliasing, meta: if p.meta.is_null() { serde_json::json!({}) } else { p.meta.clone() }, ignore_rules: serde_json::to_value(p.ignore.clone().unwrap_or_default()).unwrap_or_default(), - environment: super::environments::for_kind(&p.kind, &build.environment), + environment: super::environments::for_kind(p.kind(), &build.environment), + state: if p.error.is_some() { "failed" } else { "pending" }, + error: p.error.as_deref(), } }) .collect(); @@ -316,17 +355,18 @@ pub async fn register_all( for chunk in rows.chunks(2_000) { let returned = db::query!( "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, \ - source_blob, render_id, engine, threshold, ignore_anti_aliasing, meta, ignore_rules, environment) \ + source_blob, render_id, engine, threshold, ignore_anti_aliasing, meta, ignore_rules, environment, state, \ + error) \ VALUES {...chunk(pid, build_id, group_key, name, platform, kind, format, fingerprint, sha256, render_id, \ - engine, threshold, aa, meta, ignore_rules, environment)} \ + engine, threshold, aa, meta, ignore_rules, environment, state, error)} \ ON CONFLICT (build_id, name, platform) DO UPDATE SET kind = EXCLUDED.kind, format = EXCLUDED.format, \ source_fingerprint = EXCLUDED.source_fingerprint, source_blob = EXCLUDED.source_blob, \ render_id = EXCLUDED.render_id, engine = EXCLUDED.engine, threshold = EXCLUDED.threshold, \ ignore_anti_aliasing = EXCLUDED.ignore_anti_aliasing, meta = EXCLUDED.meta, \ ignore_rules = EXCLUDED.ignore_rules, environment = EXCLUDED.environment, state = EXCLUDED.state, \ matched_environment = NULL, baseline_id = NULL, group_key = EXCLUDED.group_key, carried_forward = false, \ - base_snapshot_id = NULL, review = NULL, error = NULL, updated_at = now() \ - WHERE snapshots.carried_forward OR snapshots.source_blob = EXCLUDED.source_blob \ + base_snapshot_id = NULL, review = NULL, error = EXCLUDED.error, updated_at = now() \ + WHERE snapshots.carried_forward OR snapshots.source_blob IS NOT DISTINCT FROM EXCLUDED.source_blob \ RETURNING name, platform" ) .select() @@ -346,7 +386,7 @@ pub async fn register_all( Registered { name: p.name.clone(), platform: p.platform.clone(), - needs_upload: render_of(i).is_none() && !uploaded, + needs_upload: params[i].error.is_none() && render_of(i).is_none() && !uploaded, } }) .collect())) diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index d97ab748..adf0cd6c 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -1970,6 +1970,7 @@ impl VisualCi { format: f.format.clone(), meta: f.meta.clone().unwrap_or(serde_json::Value::Null), ignore: f.ignore.clone(), + error: None, }) .collect(); if build.state != "receiving" { diff --git a/app/tests/processing.rs b/app/tests/processing.rs index 37bba405..8f9d84c8 100644 --- a/app/tests/processing.rs +++ b/app/tests/processing.rs @@ -549,3 +549,61 @@ async fn a_stored_fractional_threshold_by_glob_validates_and_applies(app: Applic assert_eq!(done["warnings"], json!([]), "{done}"); Ok(()) } + +#[laravel::test] +async fn a_test_that_crashed_shows_its_snapshot_failed_in_place_and_keeps_the_baseline( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + let (red, green) = ([255, 0, 0], [0, 200, 0]); + run(&app, &token, "c1", "c0", &[("invoices/acme.png", red), ("invoices/globex.png", green)]).await; + + // #2: the test that draws acme crashed. Its snapshot is sent as a failure, with no file, under its own name. + let id = send(&app, &token, "c2", "c1", &[("invoices/globex.png", green)]).await; + let snapshots = |entry: Value| { + app.post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [entry] })) + }; + // A failure has no file, and says what went wrong. + let with_file = json!({ "name": "invoices/acme.png", "kind": "image", "error": "boom", "sha256": "ab".repeat(32), + "size": 3, "content_type": "image/png" }); + snapshots(with_file).await.assert_status(400); + snapshots(json!({ "name": "invoices/acme.png", "error": " " })).await.assert_status(400); + let error = "AttributeError: 'NoneType' object has no attribute 'total'"; + let failure = json!({ "name": "invoices/acme.png", "kind": "image", "error": error }); + let answer = snapshots(failure.clone()).await; + answer.assert_ok(); + assert_eq!(answer.json()["snapshots"][0]["upload_url"], Value::Null, "nothing to upload"); + snapshots(failure).await.assert_ok(); // a retried request + let done = finalize(&app, &token, &id).await; + + let one = build_number(1).await?; + let base = Snapshot::query() + .filter(Snapshot::build_id.eq(one.id) & Snapshot::name.eq("invoices/acme.png")) + .first() + .await? + .expect("#1's acme"); + let two = build_number(2).await?; + let acme = Snapshot::query() + .filter(Snapshot::build_id.eq(two.id) & Snapshot::name.eq("invoices/acme.png")) + .first() + .await? + .expect("#2's acme"); + assert_eq!(acme.state, "failed", "failed in place, not removed"); + assert_eq!(acme.error.as_deref(), Some(error)); + assert_eq!(acme.source_blob, None); + assert_eq!(acme.base_snapshot_id, Some(base.id), "its page shows the version it would have been compared with"); + assert_eq!((done["stats"]["failed"].as_i64(), done["stats"]["removed"].as_i64()), (Some(1), Some(0)), "{done}"); + assert_eq!(done["conclusion"], "failed", "{done}"); + let project = app::models::Project::find_or_fail(two.project_id).await?; + let (_, conclusion, title) = app::forge::checks::check_state(&two, &project, None); + assert_eq!((conclusion.as_deref(), title.as_str()), (Some("failure"), "1 snapshot failed")); + + // #3: the test is fixed and draws acme as before: it compares with #1's, which the failure never replaced. + let third = run(&app, &token, "c3", "c2", &[("invoices/acme.png", red), ("invoices/globex.png", green)]).await; + assert_eq!(third["conclusion"], "unchanged", "{third}"); + Ok(()) +} diff --git a/clients/circleci-orb/orb.yml b/clients/circleci-orb/orb.yml index 2d9daaf7..d62f00fd 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.26" - description: The CLI release to install, such as 0.2.26. Pin it, so a new release never changes a build. + default: "0.2.27" + description: The CLI release to install, such as 0.2.27. 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.26" + default: "0.2.27" steps: - install: version: << parameters.version >> @@ -117,7 +117,7 @@ commands: default: false version: type: string - default: "0.2.26" + default: "0.2.27" steps: - install: version: << parameters.version >> @@ -160,7 +160,7 @@ jobs: default: false version: type: string - default: "0.2.26" + default: "0.2.27" steps: - install: version: << parameters.version >> diff --git a/clients/github-action/action.yml b/clients/github-action/action.yml index 466ab2eb..6f8a7f4e 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.26" + default: "0.2.27" 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-cli/src/client.rs b/crates/visualci-cli/src/client.rs index 893dfc5e..879a380f 100644 --- a/crates/visualci-cli/src/client.rs +++ b/crates/visualci-cli/src/client.rs @@ -121,6 +121,26 @@ pub struct Snapshot { pub content: Option>, /// Text: values to ignore in this snapshot only, `{json_paths, text_patterns}`. pub ignore: Option, + /// The test crashed before it wrote the file (`visualci fail`, or a manifest entry with `error` and no `path`): + /// sent with this message and no file, so the build shows the snapshot as failed under its own name. + pub error: Option, + /// A failure's kind (`document`, `image` or `text`): else from the name's extension, else a document. + pub kind: Option, +} + +/// A failure's kind: the one given, else from the name's extension (`.png` an image, `.json` text), else a document. +#[must_use] +pub fn failure_kind(name: &str, given: Option<&str>) -> String { + if let Some(kind) = given { + return kind.to_string(); + } + let ext = Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); + match ext.as_str() { + "png" | "jpg" | "jpeg" | "webp" | "gif" => "image", + "txt" | "json" | "html" | "htm" | "md" | "xml" | "csv" | "yaml" | "yml" => "text", + _ => "document", + } + .to_string() } impl Client { @@ -656,6 +676,10 @@ pub struct GroupCheck { /// # Errors /// When the file can't be read or classified. pub fn registration(s: &Snapshot) -> Result<(serde_json::Value, Vec)> { + if let Some(error) = &s.error { + let kind = failure_kind(&s.name, s.kind.as_deref()); + return Ok((json!({ "name": s.name, "platform": s.platform, "kind": kind, "error": error }), Vec::new())); + } let bytes = match &s.content { Some(c) => c.clone(), None => std::fs::read(&s.path).with_context(|| format!("reading {}", s.path.display()))?, @@ -1324,7 +1348,8 @@ mod tests { .map(|s| { json!({ "name": s["name"], "platform": s["platform"], "content_type": s["content_type"], - "upload_url": format!("{base}/blobs/{}", s["sha256"].as_str().unwrap()), + // As the server: no upload for a failure, which has no file. + "upload_url": s["sha256"].as_str().map(|sha| format!("{base}/blobs/{sha}")), }) }) .collect(); @@ -1356,6 +1381,8 @@ mod tests { format: None, content: None, ignore: None, + error: None, + kind: None, } }) .collect() @@ -1371,6 +1398,41 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn a_failure_is_sent_with_its_message_and_no_file() { + let failure = Snapshot { + name: "invoices/acme".into(), + platform: String::new(), + path: PathBuf::from("/no/such/file.pdf"), + threshold: None, + engine: None, + format: None, + content: None, + ignore: None, + error: Some("AttributeError: boom".into()), + kind: None, + }; + let (params, bytes) = registration(&failure).unwrap(); + assert_eq!( + params, + json!({ "name": "invoices/acme", "platform": "", "kind": "document", "error": "AttributeError: boom" }) + ); + assert!(bytes.is_empty(), "nothing is read or uploaded"); + let (url, puts) = server_and_store(Vec::new()); + let (registered, uploaded) = api_client(&url).add_snapshots("b1", &[failure]).unwrap(); + assert_eq!((registered, uploaded), (1, 0)); + assert_eq!(puts.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[test] + fn a_failures_kind_comes_from_its_name_unless_given() { + assert_eq!(failure_kind("home/desktop.PNG", None), "image"); + assert_eq!(failure_kind("api/orders.json", None), "text"); + assert_eq!(failure_kind("invoices/acme", None), "document"); + assert_eq!(failure_kind("invoices/acme.pdf", None), "document"); + assert_eq!(failure_kind("home/desktop", Some("image")), "image"); + } + #[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())); @@ -1413,6 +1475,8 @@ mod tests { format: None, content, ignore: None, + error: None, + kind: None, }; let mut snaps = Vec::new(); for i in 0..40u32 { @@ -1475,6 +1539,8 @@ mod tests { format: None, content: None, ignore: None, + error: None, + kind: None, }) .collect() }; diff --git a/crates/visualci-cli/src/main.rs b/crates/visualci-cli/src/main.rs index 42107742..6528446b 100644 --- a/crates/visualci-cli/src/main.rs +++ b/crates/visualci-cli/src/main.rs @@ -139,7 +139,9 @@ enum Command { paths: Vec, /// A file listing snapshots, as a JSON array or JSON Lines: `{"name", "path", "platform"?, "threshold"?, /// "engine"?, "format"?, "ignore"?}`. Used by client libraries and test helpers, which choose names - /// themselves. `ignore` (`{"json_paths": [...], "text_patterns": [...]}`) applies to that snapshot only. + /// themselves. `ignore` (`{"json_paths": [...], "text_patterns": [...]}`) applies to that snapshot only. A test + /// that crashed before writing its file sends `{"name", "error", "kind"?}` with no `path`: the snapshot shows + /// as failed under its own name. #[arg(long)] manifest: Option, /// The build (default $VISUALCI_BUILD_ID). @@ -153,6 +155,30 @@ enum Command { #[command(flatten)] connection: Connection, }, + /// Report that a test crashed before it wrote a snapshot's file: the build shows the snapshot as failed under its + /// own name, with this message beside the last approved version, instead of "removed". The build fails, as it does + /// for a file that never arrived. + /// + /// visualci fail invoices/acme --message "AttributeError: 'NoneType' object has no attribute 'total'" + Fail { + /// The snapshot's name, as the test would have sent it. + name: String, + /// What went wrong: the error and, ideally, where. + #[arg(long, required_unless_present = "message_file", conflicts_with = "message_file")] + message: Option, + /// Read the message from this file (a stack trace, the test's output). + #[arg(long)] + message_file: Option, + /// `document`, `image` or `text`. Default: from the name's extension, else a document. + #[arg(long)] + kind: Option, + #[arg(long, default_value = "")] + platform: String, + #[arg(long)] + build: Option, + #[command(flatten)] + connection: Connection, + }, /// Add one file to a build under the given name. Snapshot { name: String, @@ -677,6 +703,33 @@ fn run() -> Result<()> { 0 }); } + Command::Fail { name, message, message_file, kind, platform, build, connection } => { + let client = Client::from_env(connection.api_url, connection.token, connection.project)?; + let message = match (message, message_file) { + (Some(m), _) => m, + (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("reading {}", f.display()))?, + (None, None) => bail!("give --message or --message-file"), + }; + // The server keeps the message's first 16 KB: a stack trace's top is the part that matters. + let message = truncate_bytes(message.trim(), 16 * 1024).to_string(); + if message.is_empty() { + bail!("the message is empty: say what went wrong"); + } + let s = Snapshot { + name, + platform, + path: PathBuf::new(), + threshold: None, + engine: None, + format: None, + content: None, + ignore: None, + error: Some(message), + kind, + }; + client.add_snapshots(&build_id(build)?, std::slice::from_ref(&s))?; + eprintln!("{} reported as failed", s.name); + } Command::Snapshot { name, file, build, snapshot, connection } => { let client = Client::from_env(connection.api_url, connection.token, connection.project)?; let s = Snapshot { @@ -688,6 +741,8 @@ fn run() -> Result<()> { format: snapshot.format, content: None, ignore: None, + error: None, + kind: None, }; let (_, uploaded) = client.add_snapshots(&build_id(build)?, &[s])?; eprintln!("1 snapshot, {uploaded} uploaded"); @@ -847,20 +902,27 @@ 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); + // Failures have no file to hash: left out of the manifest, their groups no longer match, and they're always sent. + let files: Vec = snapshots.iter().filter(|s| s.error.is_none()).cloned().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))), + || format!("hashed {} snapshots for the group check", files.len()), + || client::par_map(&files, |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 { + if let Some(n) = check.same_as_build + && files.len() == snapshots.len() + { eprintln!("{} snapshots: nothing changed since build #{n}", snapshots.len()); return Ok(()); } let grouping = group_depth .map_or(visualci_core::manifest::Grouping::default(), |d| visualci_core::manifest::Grouping::Depth(d as usize)); let changed: std::collections::HashSet<&str> = check.changed.iter().map(String::as_str).collect(); - let send: Vec = - snapshots.iter().filter(|s| changed.contains(grouping.key(&s.name).as_str())).cloned().collect(); + let send: Vec = snapshots + .iter() + .filter(|s| s.error.is_some() || changed.contains(grouping.key(&s.name).as_str())) + .cloned() + .collect(); let (registered, uploaded) = if send.is_empty() { (0, 0) } else { client.add_snapshots(build_id, &send)? }; eprintln!( "{} snapshots: {} of {} groups unchanged; {registered} sent, {uploaded} uploaded", @@ -1083,6 +1145,8 @@ fn snapshots_for(paths: &[PathBuf], options: &SnapshotOptions) -> Result Result Result, + /// The test crashed before writing the file: the snapshot is sent as failed with this message. + #[serde(default)] + error: Option, + /// A failure's kind (`document`, `image` or `text`). + #[serde(default)] + kind: Option, #[serde(default)] platform: String, threshold: Option, @@ -1148,19 +1222,31 @@ fn read_manifest(path: &Path) -> Result> { } } } - Ok(deduped + deduped .into_iter() - .map(|e| Snapshot { - name: e.name, - platform: e.platform, - path: e.path, - threshold: e.threshold, - engine: e.engine, - format: e.format, - content: None, - ignore: e.ignore, + .enumerate() + .map(|(i, e)| { + let path = match (e.path, &e.error) { + (Some(_), Some(_)) => bail!("{} entry {}: give either path or error, not both", path.display(), i + 1), + (None, None) => { + bail!("{} entry {}: give the file's path, or error when it wasn't made", path.display(), i + 1) + } + (path, _) => path.unwrap_or_default(), + }; + Ok(Snapshot { + name: e.name, + platform: e.platform, + path, + threshold: e.threshold, + engine: e.engine, + format: e.format, + content: None, + ignore: e.ignore, + error: e.error, + kind: e.kind, + }) }) - .collect()) + .collect() } fn print_build(client: &Client, build: &client::Build) -> Result<()> { @@ -1291,10 +1377,51 @@ fn fonts_differ_only(a: &Path, b: &Path) -> bool { matches!((without(a), without(b)), (Some(x), Some(y)) if x == y) } +/// The longest start of `text` that fits in `max` bytes, cut at a character boundary. +fn truncate_bytes(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_manifest_entry_with_an_error_and_no_path_is_a_failure() { + let dir = std::env::temp_dir().join(format!("visualci-manifest-fail-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let manifest = dir.join("manifest.jsonl"); + std::fs::write( + &manifest, + "{\"name\": \"invoices/acme\", \"path\": \"acme.pdf\"}\n{\"name\": \"invoices/globex\", \"error\": \"boom\", \"kind\": \"document\"}\n", + ) + .unwrap(); + let snapshots = read_manifest(&manifest).unwrap(); + assert_eq!(snapshots[0].error, None); + assert_eq!(snapshots[0].path, PathBuf::from("acme.pdf")); + assert_eq!((snapshots[1].error.as_deref(), snapshots[1].kind.as_deref()), (Some("boom"), Some("document"))); + + std::fs::write(&manifest, "{\"name\": \"a\", \"path\": \"a.pdf\", \"error\": \"boom\"}\n").unwrap(); + assert!(format!("{:#}", read_manifest(&manifest).unwrap_err()).contains("not both")); + std::fs::write(&manifest, "{\"name\": \"a\"}\n").unwrap(); + assert!(format!("{:#}", read_manifest(&manifest).unwrap_err()).contains("give the file's path")); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_long_message_is_cut_at_a_character() { + assert_eq!(truncate_bytes("héllo", 2), "h"); + assert_eq!(truncate_bytes("héllo", 3), "hé"); + assert_eq!(truncate_bytes("hi", 10), "hi"); + } + #[test] fn names_saved_images_by_their_label() { assert_eq!( diff --git a/frontend/content/docs/pdfs.md b/frontend/content/docs/pdfs.md index 8760f96d..8ce7a381 100644 --- a/frontend/content/docs/pdfs.md +++ b/frontend/content/docs/pdfs.md @@ -58,6 +58,16 @@ For each changed page, `get_snapshot` (and the web app) shows: - lines that moved to another page, the usual sign of a page-break bug; - inserted and removed pages, next to an empty slot on the other side. +## When the code under test crashes + +A test that crashes doesn't write its PDF, and a snapshot that isn't sent shows as removed. Report the crash under the snapshot's own name instead, with what went wrong: + +```sh +visualci fail invoices/acme --message "AttributeError: 'NoneType' object has no attribute 'total'" +``` + +The build then shows `invoices/acme` as **failed**, with your message beside the last approved version, and the build fails with "1 snapshot failed", as it does for a PDF that never arrived. The last approved version stays the baseline: once the test is fixed, its PDF is compared with that. `--message-file` reads a stack trace from a file. A test helper that writes a manifest adds `{"name": "invoices/acme", "error": "..."}` with no `path`. + ## Two PDFs, once To compare two PDFs without setting anything up, [Compare two PDFs](/tools/compare-pdfs/) runs the same comparison in your browser, and the files are never uploaded. diff --git a/frontend/content/docs/reference/api.md b/frontend/content/docs/reference/api.md index 6a942b14..0176a1f3 100644 --- a/frontend/content/docs/reference/api.md +++ b/frontend/content/docs/reference/api.md @@ -54,6 +54,8 @@ All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer The response lists each snapshot with an `upload_url`. PUT the file's bytes there with its `content_type`, within 15 minutes (register again for a fresh link). `upload_url` is `null` when VisualCI already has the file. A file can be at most 64 MiB, and its bytes must match its `sha256`: anything else is discarded and reported missing. +A test that crashed before it wrote its file sends the snapshot with `error` and no file: `{"name": "invoice_typical", "kind": "document", "error": "AttributeError: ..."}` (`kind` defaults to `document`; leave out `sha256`, `size` and `content_type`). The build shows the snapshot as `failed` with that error, under its own name, instead of `removed`, and the build fails. The error is at most 16 KB. The last approved version stays the baseline. + A name (with its platform) is one snapshot per build. Registering it again with the same file is fine (a retried job does), but other content under a name already in the build is refused with `409 Conflict` naming the snapshot: names must be unique across a build's jobs and shards. ## Finalize diff --git a/frontend/content/docs/reference/cli.md b/frontend/content/docs/reference/cli.md index 2493a753..aa3b373e 100644 --- a/frontend/content/docs/reference/cli.md +++ b/frontend/content/docs/reference/cli.md @@ -38,7 +38,7 @@ Adds files or directories of them to a build: PDFs, PNG, JPEG and WebP images, a | `--threshold <0..1>` | 0 is exact; above 0, the colour difference below which two pixels count as the same. | | `--engine pdfbox\|mutool` | The renderer for these PDFs. Default: the project's. | | `--format text\|json\|html` | How text files are compared. Default: from each file's extension, else plain text. | -| `--manifest ` | A JSON array or JSON Lines of `{"name", "path", "platform"?, "threshold"?, "engine"?, "format"?, "ignore"?}`, for test helpers that choose names themselves. `ignore` is `{"json_paths": [...], "text_patterns": [...]}` for that snapshot only. | +| `--manifest ` | A JSON array or JSON Lines of `{"name", "path", "platform"?, "threshold"?, "engine"?, "format"?, "ignore"?}`, for test helpers that choose names themselves. `ignore` is `{"json_paths": [...], "text_patterns": [...]}` for that snapshot only. A test that crashed before writing its file adds `{"name", "error", "kind"?}` with no `path`, as `visualci fail` does. | | `--allow-empty` | Succeed when there's nothing to upload. Without it, an upload that finds no snapshot files is an error. | `upload` sends each image by its file's SHA-256 alone, without decoding it: a file VisualCI already has isn't uploaded, @@ -54,6 +54,18 @@ were unchanged. `VISUALCI_GROUPS=0` turns this off, and `VISUALCI_GROUPS=1` uses `visualci snapshot ` adds one file under the given name. It takes the same options as `upload`, except `--manifest`. +## visualci fail + +`visualci fail --message ""` reports that a test crashed before it wrote a snapshot's file. The build shows the snapshot as failed under its own name, with the message beside the last approved version, instead of as removed, and the build fails. The last approved version stays the baseline. + +| Option | | +| --- | --- | +| `--message ` | What went wrong. | +| `--message-file ` | Read the message from a file instead, such as a stack trace. Messages over 16 KB are cut. | +| `--kind ` | `document`, `image` or `text`. Default: from the name's extension (`.png` an image, `.json` text), else a document. | +| `--platform ` | The snapshot's platform, as its file would have been sent. | +| `--build ` | The build (default `$VISUALCI_BUILD_ID`). | + ## visualci compare `visualci compare ` compares some snapshots of a build before it's finalized, so a local test run can check each test's snapshots as the test makes them. It prints each changed or new snapshot with its environment and link, such as `invoice_typical (local-mac) changed: https://app.visualci.com/…`, and exits 1 when there's any. diff --git a/frontend/content/docs/screenshots.md b/frontend/content/docs/screenshots.md index a08da325..934f29fc 100644 --- a/frontend/content/docs/screenshots.md +++ b/frontend/content/docs/screenshots.md @@ -36,6 +36,16 @@ The threshold is the colour difference (0 to 1) below which two pixels count as Screenshots that differ between runs of the same commit show up as changes. [Deterministic screenshots](/docs/screenshots/deterministic/) covers the usual causes (the clock, randomness, fonts, animations, the network) and how to pin each one. +## When the code under test crashes + +A test that crashes before its screenshot shows that snapshot as removed. Report the crash under the snapshot's name instead: + +```sh +visualci fail checkout/desktop --kind image --message "TimeoutError: waiting for #pay" +``` + +The build shows `checkout/desktop` as **failed**, with your message beside the last approved screenshot, and the build fails with "1 snapshot failed". The last approved screenshot stays the baseline. A name ending in `.png`, `.jpg` or `.webp` is an image without `--kind`. A test helper that writes a manifest adds `{"name": "checkout/desktop", "kind": "image", "error": "..."}` with no `path`. + ## Your test tool - [Playwright](/docs/screenshots/playwright/) diff --git a/skills/visualci-pdfs/SKILL.md b/skills/visualci-pdfs/SKILL.md index 9d972434..cb2d471d 100644 --- a/skills/visualci-pdfs/SKILL.md +++ b/skills/visualci-pdfs/SKILL.md @@ -63,6 +63,16 @@ For each changed page, `get_snapshot` (and the web app) shows: - lines that moved to another page, the usual sign of a page-break bug; - inserted and removed pages, next to an empty slot on the other side. +## When the code under test crashes + +A test that crashes doesn't write its PDF, and a snapshot that isn't sent shows as removed. Report the crash under the snapshot's own name instead, with what went wrong: + +```sh +visualci fail invoices/acme --message "AttributeError: 'NoneType' object has no attribute 'total'" +``` + +The build then shows `invoices/acme` as **failed**, with your message beside the last approved version, and the build fails with "1 snapshot failed", as it does for a PDF that never arrived. The last approved version stays the baseline: once the test is fixed, its PDF is compared with that. `--message-file` reads a stack trace from a file. A test helper that writes a manifest adds `{"name": "invoices/acme", "error": "..."}` with no `path`. + ## Two PDFs, once To compare two PDFs without setting anything up, [Compare two PDFs](https://visualci.com/tools/compare-pdfs/) runs the same comparison in your browser, and the files are never uploaded.