Skip to content
Merged
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
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.26"
version = "0.2.27"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
1 change: 1 addition & 0 deletions app/src/domain/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
9 changes: 9 additions & 0 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
78 changes: 59 additions & 19 deletions app/src/domain/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
/// 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<f64>,
Expand All @@ -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<IgnoreRules>,
/// 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<String>,
}

/// 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";

Expand All @@ -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));
}
Expand All @@ -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()) {
Expand Down Expand Up @@ -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<Format> {
(self.kind == "text")
(self.kind() == "text")
.then(|| Format::detect(self.format.as_deref(), Some(&self.content_type), Some(&self.name)))
}
}
Expand Down Expand Up @@ -182,14 +212,16 @@ struct Row<'a> {
kind: &'a str,
format: Option<String>,
fingerprint: String,
sha256: &'a str,
sha256: Option<&'a str>,
render_id: Option<i64>,
engine: &'a Option<String>,
threshold: Option<f64>,
aa: Option<bool>,
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.
Expand Down Expand Up @@ -252,6 +284,7 @@ pub async fn register_all(

let files: Vec<super::blobs::NewBlob> = 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?;
Expand All @@ -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();
Expand All @@ -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<i64> {
(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()
};
Expand All @@ -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();
Expand All @@ -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()
Expand All @@ -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()))
Expand Down
1 change: 1 addition & 0 deletions app/src/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand Down
58 changes: 58 additions & 0 deletions app/tests/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
10 changes: 5 additions & 5 deletions clients/circleci-orb/orb.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 >>
Expand Down Expand Up @@ -117,7 +117,7 @@ commands:
default: false
version:
type: string
default: "0.2.26"
default: "0.2.27"
steps:
- install:
version: << parameters.version >>
Expand Down Expand Up @@ -160,7 +160,7 @@ jobs:
default: false
version:
type: string
default: "0.2.26"
default: "0.2.27"
steps:
- install:
version: << parameters.version >>
Expand Down
2 changes: 1 addition & 1 deletion clients/github-action/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading