diff --git a/Cargo.lock b/Cargo.lock index b523e5b7..74d595ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5010,6 +5010,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "serde_path_to_error", "sha2 0.10.9", "snapshot-diff", "sqlx", diff --git a/app/Cargo.toml b/app/Cargo.toml index 344cd324..69910c8e 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -31,6 +31,8 @@ hmac = "0.12" jsonwebtoken = "9" serde = { version = "1", features = ["derive"] } serde_json = "1" +# Names the field at fault when a visualci.yml doesn't parse (build_settings::parse_config) +serde_path_to_error = "0.1" sha2 = "0.10" tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } diff --git a/app/src/domain/build_settings.rs b/app/src/domain/build_settings.rs index b25f2f13..d14fc890 100644 --- a/app/src/domain/build_settings.rs +++ b/app/src/domain/build_settings.rs @@ -51,15 +51,100 @@ fn strictness(mode: &str) -> usize { MODES.iter().position(|m| *m == mode).unwrap_or(0) } +/// `error_code` of a build that failed because its stored `visualci.yml` no longer validates. +pub const CONFIG_INVALID: &str = "config_invalid"; + +/// A build's stored `visualci.yml` that no longer validates: one an earlier version accepted that a later, stricter +/// one refuses, or one a parsing bug refuses. The build's settings can't be known, so nothing falls back to the +/// project's quietly: processing fails the build with this message, early comparisons and uploads refuse with it, and +/// pages that show an already-compared build add it to the build's warnings ([`warnings_of`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConfigInvalid { + /// The parser's message, naming the field: `threshold: a threshold is a number, not "x"`. + pub reason: String, +} + +impl std::fmt::Display for ConfigInvalid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "visualci.yml no longer validates: {}; send the build again", self.reason) + } +} + +impl std::error::Error for ConfigInvalid {} + +/// Parse a `visualci.yml` sent as JSON, with a message that names the field at fault (`threshold: …`, +/// `pdf.dpi: …`). Creation and every later read of a stored config use this, so they agree. +/// +/// # Errors +/// The first problem, prefixed with the path to the field when it's not the top level. +pub fn parse_config(value: &serde_json::Value) -> Result { + let config: Config = serde_path_to_error::deserialize(value.clone()).map_err(|e| { + let path = e.path().to_string(); + let inner = e.into_inner(); + if path == "." { inner.to_string() } else { format!("{path}: {inner}") } + })?; + config.validate()?; + Ok(config) +} + +/// A build's stored `visualci.yml`, parsed: `Ok(None)` when it was sent none. +/// +/// # Errors +/// When the stored file no longer validates. +pub fn stored_config(build: &Build) -> Result, ConfigInvalid> { + match &build.config { + Some(v) if !v.is_null() => parse_config(v).map(Some).map_err(|reason| ConfigInvalid { reason }), + _ => Ok(None), + } +} + +/// The warnings to show with a build: the ones stored when it was created and processed, and, when its stored +/// `visualci.yml` no longer validates and the build didn't already fail for it, that problem first. Used by every view +/// of a build (the API and MCP answers, the build's page, its check), so a build compared before its file stopped +/// validating says so wherever it's read. +#[must_use] +pub fn warnings_of(build: &Build) -> Vec { + let mut out: Vec = serde_json::from_value(build.warnings.clone()).unwrap_or_default(); + if build.error_code.as_deref() != Some(CONFIG_INVALID) + && let Err(e) = stored_config(build) + { + out.insert( + 0, + format!( + "visualci.yml no longer validates: {}. This build was compared before the file stopped validating, \ + and is now shown with the project's settings; send the build again to compare it with a valid file.", + e.reason + ), + ); + } + out +} + impl<'a> BuildSettings<'a> { - pub fn new(project: &'a Project, build: &Build) -> Self { - // The config was validated when the build was created; one that no longer parses (a later, stricter version) - // is treated as absent rather than failing the build. - let config = build.config.as_ref().and_then(|v| { - Config::from_json(v) - .inspect_err(|e| tracing::warn!(build = build.id, error = %e, "stored config no longer validates")) - .ok() - }); + /// The settings a build runs with. Every path that compares, registers or uploads uses this and refuses (or fails + /// the build) on the error. + /// + /// # Errors + /// When the build's stored `visualci.yml` no longer validates. + pub fn new(project: &'a Project, build: &Build) -> Result { + Ok(Self::with_config(project, stored_config(build)?)) + } + + /// The settings for showing a build that has already been compared or has failed: its own, or when its stored + /// `visualci.yml` no longer validates, the project's. That case is never silent: [`warnings_of`] adds the problem to + /// the build's warnings in every view, and a build processed since fails with it. Never use this to compare. + #[must_use] + pub fn shown(project: &'a Project, build: &Build) -> Self { + Self::with_config(project, stored_config(build).unwrap_or(None)) + } + + /// The project's settings alone, as for a build sent without a `visualci.yml`. + #[must_use] + pub fn of_project(project: &'a Project) -> Self { + Self::with_config(project, None) + } + + fn with_config(project: &'a Project, config: Option) -> Self { let (source, scoped) = match config.as_ref().and_then(|c| c.ignore.clone()) { Some(rules) => (Source::File, rules), None => (Source::Project, super::projects::ignore_rules(project)), @@ -251,7 +336,7 @@ impl<'a> BuildSettings<'a> { /// # Errors /// A message that starts with `visualci.yml:`. pub fn validate_config(value: &serde_json::Value) -> Result { - let config = Config::from_json(value).map_err(|e| format!("visualci.yml: {e}"))?; + let config = parse_config(value).map_err(|e| format!("visualci.yml: {e}"))?; serde_json::to_value(config).map_err(|e| format!("visualci.yml: {e}")) } diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index aedcfb46..bf6a5081 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -241,7 +241,11 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option settings.config_warnings(), + Err(invalid) => vec![invalid.to_string()], + }; if let Some(w) = repository_warning(project, &build) { warnings.push(w); } diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index a897b856..de168255 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -409,7 +409,7 @@ impl Seeder<'_> { Err(Err(e)) => Err(e), }; let build = outcome(super::builds::create(project, ¶ms, None).await)?; - let settings = BuildSettings::new(project, &build); + let settings = BuildSettings::new(project, &build).map_err(error)?; for item in items { let snapshot = self.snapshot(project, item).await?; snapshot.validate().map_err(error)?; diff --git a/app/src/domain/gallery.rs b/app/src/domain/gallery.rs index d4ecc1ec..2c2c8dd6 100644 --- a/app/src/domain/gallery.rs +++ b/app/src/domain/gallery.rs @@ -12,7 +12,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use laravel::db::{self, Json}; -use visualci_core::config::{Config, Gallery}; +use visualci_core::config::Gallery; use crate::models::{Blob, Build, Organization, Project}; @@ -79,9 +79,15 @@ async fn newest_builds(project: &Project) -> laravel::Result> { Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect()) } -/// The gallery a build's visualci.yml asks for, if any. +/// The gallery a build's visualci.yml asks for, if any. A file that no longer validates has none: the public page can't +/// show why, so it's logged as an error, and the build's warnings say so to its members +/// ([`super::build_settings::warnings_of`]). fn gallery_of(build: &Build) -> Option { - build.config.as_ref().and_then(|c| Config::from_json(c).ok()).and_then(|c| c.gallery) + super::build_settings::stored_config(build) + .inspect_err(|e| tracing::error!(build = build.id, error = %e, "no gallery: the stored visualci.yml no longer validates")) + .ok() + .flatten() + .and_then(|c| c.gallery) } /// How long a computed gallery is reused when nothing it depends on changed. diff --git a/app/src/domain/pages.rs b/app/src/domain/pages.rs index 9a9bb614..6994f38d 100644 --- a/app/src/domain/pages.rs +++ b/app/src/domain/pages.rs @@ -255,6 +255,7 @@ async fn normalized_text( slot.insert((build, project)); } let (build, project) = &settings_of[&snapshot.build_id]; - let rules = BuildSettings::new(project, build).compiled_rules(snapshot); + // Shown, not compared again: a file that no longer validates is in the build's warnings. + let rules = BuildSettings::shown(project, build).compiled_rules(snapshot); Ok(visualci_core::snapshot_text::normalize(format, &raw, &rules).text) } diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index aa74f1c3..e05ad248 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -8,7 +8,7 @@ use laravel::model::update; use visualci_core::manifest::{self, Entry}; use super::baselines::{self, Resolved}; -use super::build_settings::{BuildSettings, Source}; +use super::build_settings::{BuildSettings, CONFIG_INVALID, ConfigInvalid, Source}; use super::builds::{ CREDITS_PER_GROUP_CHECK, CREDITS_PER_IMAGE_DIFF, CREDITS_PER_RENDERED_PAGE, CREDITS_PER_SNAPSHOT_CHECK, CREDITS_PER_TEXT_DIFF, EMPTY_BUILD, Stats, @@ -232,6 +232,28 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la Ok(()) } +/// Fail a processing build whose stored `visualci.yml` no longer validates, rather than compare it with settings it +/// wasn't sent: its `error` names the field and the problem (shown by get_build, its page and its check's title), and +/// its queued renders that nothing else waits on are dropped. +/// +/// # Errors +/// On a database error. +async fn fail_for_config(mut build: Build, invalid: &ConfigInvalid) -> laravel::Result<()> { + tracing::warn!(build = build.id, reason = %invalid.reason, "stored visualci.yml no longer validates; failing the build"); + let error = Some(invalid.to_string()); + let completed_at = Some(laravel::now().timestamp()); + update!(build { + state: "failed", + conclusion: Some("failed".to_string()), + review_state: "none", + error_code: Some(CONFIG_INVALID.to_string()), + error, + completed_at, + }) + .await?; + drop_unneeded_renders(build.id).await +} + /// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { if let Some(project) = Project::find(project_id).await? { @@ -413,7 +435,13 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> return Ok(build.state == "completed"); } let project = Project::find_or_fail(build.project_id).await?; - let settings = BuildSettings::new(&project, &build); + let settings = match BuildSettings::new(&project, &build) { + Ok(s) => s, + Err(invalid) => { + fail_for_config(build, &invalid).await?; + return Ok(true); + } + }; let id = build.id; // The "visualci.yml" item is worked out again below. db::query!("DELETE FROM snapshots WHERE build_id = {id} AND platform = 'visualci'").delete().await?; @@ -588,7 +616,16 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> // with the settings that item was compared with. if let Some(a) = &anchor { let base = approved_settings_build(a.clone()).await?; - let base_settings = BuildSettings::new(&project, &base); + // A base whose own file no longer validates can't say what it hid: compare with the project's settings, and + // say so in the build's warnings. + let base_settings = BuildSettings::new(&project, &base).unwrap_or_else(|invalid| { + warnings.push(format!( + "Build #{}'s visualci.yml, which this build's settings are compared with, no longer validates ({}), \ + so they were compared with the project's settings instead.", + base.number, invalid.reason + )); + BuildSettings::of_project(&project) + }); if settings.hides_more_than(&base_settings) { let base_item = Snapshot::query() .filter(Snapshot::build_id.eq(base.id) & Snapshot::platform.eq(CONFIG_PLATFORM)) @@ -1038,7 +1075,10 @@ pub async fn compare_now( ))); } } - let settings = BuildSettings::new(&project, build); + let settings = match BuildSettings::new(&project, build) { + Ok(s) => s, + Err(invalid) => return Ok(Err(invalid.to_string())), + }; let mut snapshots: Vec = super::snapshots::of_build(build.id) .await? .into_iter() diff --git a/app/src/forge/checks.rs b/app/src/forge/checks.rs index 72f0d4a3..c339c26d 100644 --- a/app/src/forge/checks.rs +++ b/app/src/forge/checks.rs @@ -8,7 +8,7 @@ use laravel::queue::{Attempt, Queueable, job}; use super::report::{self, Check, RateLimited}; -use crate::domain::build_settings::BuildSettings; +use crate::domain::build_settings::{self, BuildSettings}; use crate::domain::builds::stats; use crate::models::{Build, Organization, Project}; @@ -57,7 +57,7 @@ pub fn check_state(build: &Build, project: &Project, superseded_by: Option) // Its pull request was closed without merging, or its branch deleted ("completed", _, "closed") => done("neutral", "Closed without review".to_string()), ("completed", _, _) if build.mode == "local" => done("neutral", format!("{changes} changes (local run)")), - ("completed", _, _) if BuildSettings::new(project, build).ci_mode() == "strict" => { + ("completed", _, _) if BuildSettings::shown(project, build).ci_mode() == "strict" => { done("failure", format!("{changes} changes to review")) } ("completed", _, _) => ("in_progress".to_string(), None, format!("{changes} changes waiting for review")), @@ -96,6 +96,15 @@ pub async fn check_for(build: &Build, project: &Project, org: &Organization) -> if let Some(line) = crate::domain::summary::summary_line(build).await? { summary = format!("{line}\n\n{summary}"); } + // Why it failed as a whole, in full (the title has its first clause), and what to point out about its settings + if build.state == "failed" + && let Some(error) = &build.error + { + summary.push_str(&format!("\n\n**Error:** {error}")); + } + for warning in build_settings::warnings_of(build) { + summary.push_str(&format!("\n\n**Warning:** {warning}")); + } if status == "in_progress" && build.state == "completed" { summary = format!("{summary}\n\n{}", review_hint(&org.slug, &project.slug, build.number)); } diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 820b382c..8fe86bca 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -63,7 +63,7 @@ pub struct BuildResponse { impl BuildResponse { #[must_use] pub fn new(build: &Build, project: &Project, organization: &Organization) -> Self { - let settings = BuildSettings::new(project, build); + let settings = BuildSettings::shown(project, build); Self { id: build.pid, number: build.number, @@ -76,7 +76,7 @@ impl BuildResponse { stats: domain::stats(build), error: build.error.clone(), url: format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, build.number), - warnings: serde_json::from_value(build.warnings.clone()).unwrap_or_default(), + warnings: crate::domain::build_settings::warnings_of(build), reviewable: domain::reviewable(build), blocked: None, } @@ -208,7 +208,7 @@ pub async fn add_snapshots( build.number, build.state ))); } - let settings = BuildSettings::new(&project, &build); + let settings = BuildSettings::new(&project, &build).map_err(|e| ApiError::bad_request(e.to_string()))?; let version = renderer_version(); // Every snapshot is checked before any is written. for p in ¶ms.snapshots { diff --git a/app/src/http/ui/builds.rs b/app/src/http/ui/builds.rs index 1c81d159..7439f7f9 100644 --- a/app/src/http/ui/builds.rs +++ b/app/src/http/ui/builds.rs @@ -186,9 +186,9 @@ pub async fn show_build(auth: Auth, Params((org, project, number)): Params } let mut summary = build_summary(&build, member); summary["base_build_number"] = json!(base_number); - summary["ci_mode"] = json!(BuildSettings::new(project, &build).ci_mode()); + summary["ci_mode"] = json!(BuildSettings::shown(project, &build).ci_mode()); summary["config"] = json!(build.config); - summary["warnings"] = build.warnings.clone(); + summary["warnings"] = json!(domain::build_settings::warnings_of(&build)); summary["error"] = json!(build.error); // What changed, computed from the comparison. summary["summary"] = json!(domain::summary::summary_line(&build).await?); @@ -238,7 +238,8 @@ pub async fn show_snapshot( (Some("previous"), Some((b, s))) => Some((b, s)), _ => None, }; - let settings = BuildSettings::new(project, &build); + // A view of a compared build: a file that no longer validates is in the build's warnings. + let settings = BuildSettings::shown(project, &build); let shown = match against { Some((_, earlier)) => { let options = settings.diff_options(&snapshot); diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 2a1b3426..ab1bbe55 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -1213,8 +1213,8 @@ impl VisualCi { out["config"] = json!(build.config); // What changed, computed from the comparison ("invoice: page 1 changed (2 regions); 3 added"). out["summary"] = json!(domain::summary::summary_line(&build).await.map_err(internal)?); - out["warnings"] = build.warnings.clone(); - out["ci_mode"] = json!(BuildSettings::new(&project, &build).ci_mode()); + out["warnings"] = json!(domain::build_settings::warnings_of(&build)); + out["ci_mode"] = json!(BuildSettings::shown(&project, &build).ci_mode()); if paged { out["groups"] = json!( groups @@ -1326,7 +1326,8 @@ impl VisualCi { } let snapshot = need!(Self::find_snapshot(&build, key, &args.platform)); let store = BlobStore::current().await.map_err(internal)?; - let settings = BuildSettings::new(&project, &build); + // A view of a compared build: a file that no longer validates is in the build's warnings. + let settings = BuildSettings::shown(&project, &build); let earlier = match args.against.as_deref().map(str::trim) { None | Some("" | "baseline") => None, Some(other) => { @@ -1936,7 +1937,10 @@ impl VisualCi { return Ok(tool_error(e)); } } - let settings = BuildSettings::new(&project, &build); + let settings = match BuildSettings::new(&project, &build) { + Ok(s) => s, + Err(e) => return Ok(tool_error(e.to_string())), + }; let version = renderer_version(); let store = BlobStore::current().await.map_err(internal)?; let mut out = Vec::new(); diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/create_build.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/create_build.json index 576a512a..1acf89b9 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/create_build.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/create_build.json @@ -15,7 +15,7 @@ "result": { "content": [ { - "text": "visualci.yml: missing field `snapshots`", + "text": "visualci.yml: ignore[0]: missing field `snapshots`", "type": "text" } ], diff --git a/app/tests/groups.rs b/app/tests/groups.rs index 14897237..56b80e13 100644 --- a/app/tests/groups.rs +++ b/app/tests/groups.rs @@ -23,7 +23,7 @@ async fn a_group_is_read_only_from_a_build_of_its_own_project(_app: Application) "name": "suite/home", "kind": "text", "fingerprint": "c".repeat(64), "sha256": "d".repeat(64), "size": 2, "content_type": "text/plain", }))?; - let settings = BuildSettings::new(&mine, &holder); + let settings = BuildSettings::new(&mine, &holder).expect("the stored config validates"); let row = snapshots::register(&holder, &settings, "1", &snapshot).await?.expect("registered").snapshot; let id = row.id; db::query!("UPDATE snapshots SET state = 'unchanged' WHERE id = {id}").update().await?; diff --git a/app/tests/masks.rs b/app/tests/masks.rs index b4510aa9..ac38f9b1 100644 --- a/app/tests/masks.rs +++ b/app/tests/masks.rs @@ -178,8 +178,8 @@ async fn masked_areas(app: Application) -> laravel::Result<()> { Some(json!({ "ignore": [{ "snapshots": "web/**", "rects": [{ "x": 0, "y": 0, "width": 8, "height": 4 }] }] })); let project = app::models::Project::find_or_fail(project_id).await?; let (with, without) = ( - app::domain::build_settings::BuildSettings::new(&project, &plain), - app::domain::build_settings::BuildSettings::new(&project, &without), + app::domain::build_settings::BuildSettings::new(&project, &plain).expect("the stored config validates"), + app::domain::build_settings::BuildSettings::new(&project, &without).expect("the stored config validates"), ); assert!(with.hides_more_than(&without)); assert!(!without.hides_more_than(&with)); diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index a5a9eacb..be512177 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -320,7 +320,7 @@ async fn get_build_pages_long_lists_and_get_snapshot_finds_a_unique_name_without params.extend((0..5).map(|i| snap(format!("api/{i}"), ""))); params.push(snap("twice".into(), "chrome")); params.push(snap("twice".into(), "firefox")); - let settings = BuildSettings::new(&project, &build); + let settings = BuildSettings::new(&project, &build).expect("the stored config validates"); for p in ¶ms { snapshots::register(&build, &settings, "test", p).await?.expect("registered"); } @@ -972,7 +972,7 @@ async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { })) .unwrap() }; - let settings = BuildSettings::new(&project, &build); + let settings = BuildSettings::new(&project, &build).expect("the stored config validates"); let mut regs = Vec::new(); for p in [text("api/invoice", Some(json!({ "json_paths": ["$.in_test"] }))), text("other", None)] { p.validate().unwrap(); @@ -1028,7 +1028,7 @@ async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { let number = i32::try_from(loose["number"].as_i64().unwrap()).unwrap(); let loose = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(number)).first().await?.unwrap(); - assert_eq!(BuildSettings::new(&project, &loose).ci_mode(), "strict"); + assert_eq!(BuildSettings::new(&project, &loose).expect("the stored config validates").ci_mode(), "strict"); assert!(loose.warnings.to_string().contains("only make the mode"), "{}", loose.warnings); // A file that hides more than its base's needs review; one that hides less doesn't. @@ -1042,10 +1042,10 @@ async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { let higher = make(json!({ "ignore": [{ "snapshots": "api/**", "json_paths": ["$.a"] }], "threshold": 0.3 })); let fewer = make(json!({ "ignore": [], "threshold": 0.05 })); let (b, w, h, l) = ( - BuildSettings::new(&project, &base), - BuildSettings::new(&project, &wider), - BuildSettings::new(&project, &higher), - BuildSettings::new(&project, &fewer), + BuildSettings::new(&project, &base).expect("the stored config validates"), + BuildSettings::new(&project, &wider).expect("the stored config validates"), + BuildSettings::new(&project, &higher).expect("the stored config validates"), + BuildSettings::new(&project, &fewer).expect("the stored config validates"), ); assert!(w.hides_more_than(&b)); assert!(h.hides_more_than(&b)); @@ -1057,7 +1057,7 @@ async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { // A build without a file uses the project's settings. call(&app, TEST, t, "create_build", json!({ "commit": "def", "branch": "main" })).await; let plain = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(3)).first().await?.unwrap(); - let settings = BuildSettings::new(&project, &plain); + let settings = BuildSettings::new(&project, &plain).expect("the stored config validates"); let other = app::domain::snapshots::register(&plain, &settings, "test", &text("other", None)).await?.unwrap().snapshot; assert_eq!(settings.ci_mode(), "strict"); diff --git a/app/tests/processing.rs b/app/tests/processing.rs index bb3e5e3e..3109e873 100644 --- a/app/tests/processing.rs +++ b/app/tests/processing.rs @@ -304,3 +304,162 @@ async fn an_upload_registering_a_blob_does_not_wait_for_a_build_processing_it(ap assert_eq!(blob.sha256, sha); Ok(()) } + +/// Write a build's stored visualci.yml straight to the database: creation refuses a bad one, so this is how a config +/// stored by an earlier version (or a parsing bug) reaches processing. +async fn store_config(pid: &str, config: &Value) -> laravel::Result<()> { + let config = config.to_string(); + db::query!("UPDATE builds SET config = {config}::jsonb WHERE pid::text = {pid}").update().await?; + Ok(()) +} + +async fn build_number(number: i32) -> laravel::Result { + Ok(Build::query().filter(Build::number.eq(number)).first().await?.expect("the build")) +} + +/// Call an MCP tool with a project token and return its structured answer. +async fn mcp(app: &Application, token: &str, tool: &str, args: Value) -> Value { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + .json( + json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } }), + ) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let body = response.json().clone(); + assert!(!body["result"]["isError"].as_bool().unwrap_or(false), "{tool}: {body}"); + body["result"]["structuredContent"].clone() +} + +/// A stored visualci.yml that no longer validates is never dropped quietly: processing fails the build with the field +/// and the problem, early comparisons and uploads refuse with the same message, every view of the build shows it, and +/// a build compared before its file stopped validating says so in its warnings. +#[laravel::test] +async fn a_stored_config_that_no_longer_validates_fails_the_build_and_names_the_field( + 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]); + + // Creation still refuses a bad file, naming the field. + let refused = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "c0", "branch": "main", "config": { "threshold": "not a number" } })) + .await; + assert_eq!(refused.status().as_u16(), 400, "{}", refused.json()); + let description = refused.json()["description"].as_str().unwrap_or_default().to_string(); + assert!(description.starts_with("visualci.yml: threshold: a threshold is a number"), "{description}"); + + // #1: a valid file processes as before. + let one = send(&app, &token, "c1", "c0", &[("home.png", red)]).await; + store_config(&one, &json!({ "threshold": 0.1, "ci_mode": "wait" })).await?; + let done = finalize(&app, &token, &one).await; + assert_eq!(done["state"], "completed", "{done}"); + assert!(done["error"].is_null(), "{done}"); + assert_eq!(done["warnings"], json!([]), "{done}"); + assert_eq!(done["ci_mode"], "wait", "{done}"); + + // #2: a threshold that isn't a number. Early comparisons and uploads refuse; finalizing fails the build. + let two = send(&app, &token, "c2", "c1", &[("home.png", green)]).await; + store_config(&two, &json!({ "threshold": "not a number" })).await?; + let expected = "visualci.yml no longer validates: threshold: a threshold is a number, not \"not a number\"; send \ + the build again"; + let compared = app + .post(format!("/api/v1/builds/{two}/compare")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ "name": "home.png" }] })) + .await; + assert_eq!(compared.status().as_u16(), 400, "{}", compared.json()); + assert_eq!(compared.json()["description"], expected); + let added = app + .post(format!("/api/v1/builds/{two}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "other.png", "kind": "image", "fingerprint": "0", "sha256": "0".repeat(64), "size": 1, + "content_type": "image/png" + }] })) + .await; + assert_eq!(added.status().as_u16(), 400, "{}", added.json()); + assert_eq!(added.json()["description"], expected); + let done = finalize(&app, &token, &two).await; + assert_eq!(done["state"], "failed", "{done}"); + assert_eq!(done["error"], expected, "{done}"); + let build = build_number(2).await?; + assert_eq!(build.error_code.as_deref(), Some("config_invalid")); + assert_eq!(build.conclusion.as_deref(), Some("failed")); + assert!(build.completed_at.is_some()); + // get_build says why, once (not again in its warnings). + let got = mcp(&app, &token, "get_build", json!({ "build": "2" })).await; + assert_eq!(got["state"], "failed", "{got}"); + assert_eq!(got["error"], expected, "{got}"); + assert_eq!(got["warnings"], json!([]), "{got}"); + // The check fails with the message as its title, and the summary has it in full. + let project = app::models::Project::find_or_fail(build.project_id).await?; + let org = app::models::Organization::find_or_fail(project.organization_id).await?; + let (status, conclusion, title) = app::forge::checks::check_state(&build, &project, None); + assert_eq!((status.as_str(), conclusion.as_deref()), ("completed", Some("failure"))); + assert!(title.starts_with("visualci.yml no longer validates: threshold: a threshold is a number"), "{title}"); + let check = app::forge::checks::check_for(&build, &project, &org).await?; + assert!(check.summary.contains(&format!("**Error:** {expected}")), "{}", check.summary); + + // #3: an unknown key under a struct that denies them names the key and where it is. + let three = send(&app, &token, "c3", "c1", &[("home.png", green)]).await; + store_config(&three, &json!({ "pdf": { "dpi": 150, "colour": "red" } })).await?; + let done = finalize(&app, &token, &three).await; + assert_eq!(done["state"], "failed", "{done}"); + let error = done["error"].as_str().unwrap_or_default(); + assert!(error.starts_with("visualci.yml no longer validates: pdf"), "{error}"); + assert!(error.contains("unknown field `colour`"), "{error}"); + + // #1, compared before its file stopped validating (a later, stricter version): every view says so. + store_config(&one, &json!({ "threshold": 2 })).await?; + let shown = app.get(format!("/api/v1/builds/{one}")).header("authorization", &auth).await; + shown.assert_ok(); + let warning = shown.json()["warnings"][0].as_str().unwrap_or_default().to_string(); + assert!(warning.starts_with("visualci.yml no longer validates: threshold must be between 0 and 1"), "{warning}"); + let got = mcp(&app, &token, "get_build", json!({ "build": "1" })).await; + assert_eq!(got["warnings"][0], warning, "{got}"); + let check = app::forge::checks::check_for(&build_number(1).await?, &project, &org).await?; + assert!(check.summary.contains(&format!("**Warning:** {warning}")), "{}", check.summary); + + // #4: a valid file whose base (#1) no longer validates is compared with the project's settings, and says so. + let four = send(&app, &token, "c4", "c1", &[("home.png", red)]).await; + store_config(&four, &json!({ "threshold": 0.05 })).await?; + let done = finalize(&app, &token, &four).await; + assert_eq!(done["state"], "completed", "{done}"); + let warnings = done["warnings"].to_string(); + assert!(warnings.contains("Build #1's visualci.yml, which this build's settings are compared with"), "{warnings}"); + Ok(()) +} + +/// fleetlayer's and quietdeck's stored file (`threshold: {"**": 0.1}`), read as raw JSON from the database under the +/// app's build, where serde_json's `arbitrary_precision` is on: it validates, the threshold applies to every snapshot, +/// and the build processes. Failing on a stored file must never fail theirs. +#[laravel::test] +async fn a_stored_fractional_threshold_by_glob_validates_and_applies(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let one = send(&app, &token, "c1", "c0", &[("home.png", [255, 0, 0])]).await; + let raw = r#"{"threshold": {"**": 0.1}}"#; + db::query!("UPDATE builds SET config = {raw}::jsonb WHERE pid::text = {one}").update().await?; + let build = build_number(1).await?; + let project_id = build.project_id; + // The project's own threshold differs, so the file's is the one in force. + db::query!("UPDATE projects SET threshold = 0 WHERE id = {project_id}").update().await?; + let project = app::models::Project::find_or_fail(project_id).await?; + let settings = + app::domain::build_settings::BuildSettings::new(&project, &build).expect("the stored file validates"); + assert_eq!(settings.review_settings()["threshold"], json!({ "**": 0.1 })); + let snapshot = app::domain::snapshots::of_build(build.id).await?.into_iter().next().expect("a snapshot"); + assert!(snapshot.threshold.is_none()); + assert!((settings.diff_options(&snapshot).threshold - 0.1).abs() < f64::EPSILON); + let done = finalize(&app, &token, &one).await; + assert_eq!(done["state"], "completed", "{done}"); + assert_eq!(done["warnings"], json!([]), "{done}"); + Ok(()) +} diff --git a/docs/design.md b/docs/design.md index 3f0dfc75..f8fd9300 100644 --- a/docs/design.md +++ b/docs/design.md @@ -57,7 +57,7 @@ self-hostable version. | Variant | An extra accepted image for a name (a flaky render). Matching any variant counts as a match | | Diff | `(base image key, head image key, diff settings) → score, changed-pixel count, mask, bounding boxes, fingerprint`. Cached, so the same pair is never diffed twice | | Ignore rule | A diff fingerprint accepted as noise for one snapshot name (Argos's model), with an optional "after N occurrences". For text snapshots, a project's JSON paths and regular expressions whose matches are ignored; for images, masked areas (`region`, `rects`) left out of the diff | -| Config | `visualci.yml` in the repository, validated by the CLI and the server and stored on the build (`builds.config`). Each build uses its own commit's file; fields it sets (ignore rules, thresholds by glob, PDF engine and DPI, CI mode) override the project's settings for that build (`domain::build_settings`) | +| Config | `visualci.yml` in the repository, validated by the CLI and the server and stored on the build (`builds.config`). Each build uses its own commit's file; fields it sets (ignore rules, thresholds by glob, PDF engine and DPI, CI mode) override the project's settings for that build (`domain::build_settings`). A stored file that no longer validates (a later, stricter version, or a parsing bug) is never treated as absent: processing fails the build with `error_code` `config_invalid` and an error naming the field, early comparisons and uploads refuse with the same message, and views of a build compared before its file stopped validating add it to the build's warnings | | Review | Approve or reject a build, or individual snapshots. Approval moves the baseline | ## The pipeline