diff --git a/Cargo.lock b/Cargo.lock index c134c0d8..1bd45293 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5023,7 +5023,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.23" +version = "0.2.24" dependencies = [ "anyhow", "base64 0.22.1", @@ -5040,7 +5040,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.23" +version = "0.2.24" dependencies = [ "globset", "hex", @@ -5060,7 +5060,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.23" +version = "0.2.24" dependencies = [ "anyhow", "image", @@ -5075,7 +5075,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.23" +version = "0.2.24" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index 697051eb..8dc4cac2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.23" +version = "0.2.24" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/app/src/domain/lenient.rs b/app/src/domain/lenient.rs index 168af7d2..63093c31 100644 --- a/app/src/domain/lenient.rs +++ b/app/src/domain/lenient.rs @@ -6,20 +6,21 @@ use std::{fmt::Display, str::FromStr}; use serde::{Deserialize, Deserializer, de::Error}; -#[derive(Deserialize)] -#[serde(untagged)] -enum NumberOrString { - Number(T), - String(String), -} - -fn read(v: NumberOrString) -> Result +/// Read the value as JSON first, then the number from it. An untagged enum (number or string) can't be used here: +/// with serde_json's `arbitrary_precision` on, which the app's dependencies turn on, a number reaches it as a private +/// map and matches neither variant, so `"threshold": 0.1` was refused. `serde_json::Value` understands that map, and its +/// numbers print exactly as sent, so parsing the text gives the same number for integers and floats alike. +fn read(v: &serde_json::Value) -> Result where T::Err: Display, { match v { - NumberOrString::Number(n) => Ok(n), - NumberOrString::String(s) => s.trim().parse().map_err(|e| format!("{s:?} isn't a number: {e}")), + serde_json::Value::Number(n) => { + let text = n.to_string(); + text.parse().map_err(|e| format!("{text} isn't a number of this kind: {e}")) + } + serde_json::Value::String(s) => s.trim().parse().map_err(|e| format!("{s:?} isn't a number: {e}")), + other => Err(format!("expected a number, or a string holding one, not {other}")), } } @@ -30,10 +31,10 @@ where pub fn number<'de, D, T>(d: D) -> Result where D: Deserializer<'de>, - T: Deserialize<'de> + FromStr, + T: FromStr, T::Err: Display, { - read(NumberOrString::::deserialize(d)?).map_err(D::Error::custom) + read(&serde_json::Value::deserialize(d)?).map_err(D::Error::custom) } /// An optional number, or a string holding one (`null` and a missing field are `None`). @@ -43,12 +44,12 @@ where pub fn optional<'de, D, T>(d: D) -> Result, D::Error> where D: Deserializer<'de>, - T: Deserialize<'de> + FromStr, + T: FromStr, T::Err: Display, { - match Option::>::deserialize(d)? { - None => Ok(None), - Some(v) => read(v).map(Some).map_err(D::Error::custom), + match serde_json::Value::deserialize(d)? { + serde_json::Value::Null => Ok(None), + v => read(&v).map(Some).map_err(D::Error::custom), } } @@ -64,6 +65,23 @@ mod tests { threshold: Option, } + /// A bare float (`"threshold": 0.1`). With serde_json's `arbitrary_precision` on (the app's dependencies turn it + /// on), an untagged enum sees a number as a private map and matches no variant: every upload with + /// `--threshold` was refused with 422 from the cutover until this test (3 Dec 2026). + #[test] + fn reads_bare_floats_and_integers() { + let b: Body = serde_json::from_str(r#"{"size": 12, "shard": 3, "threshold": 0.1}"#).unwrap(); + assert_eq!((b.size, b.shard, b.threshold), (12, Some(3), Some(0.1))); + let b: Body = serde_json::from_str(r#"{"size": 1, "threshold": 1}"#).unwrap(); + assert_eq!(b.threshold, Some(1.0)); + let b: Body = serde_json::from_str(r#"{"size": 1, "threshold": 2.5e-1}"#).unwrap(); + assert_eq!(b.threshold, Some(0.25)); + let e = serde_json::from_str::(r#"{"size": 1.5}"#).unwrap_err(); + assert!(e.to_string().contains("isn't a number of this kind"), "{e}"); + let e = serde_json::from_str::(r#"{"size": true}"#).unwrap_err(); + assert!(e.to_string().contains("expected a number"), "{e}"); + } + #[test] fn reads_numbers_and_numeric_strings() { let b: Body = serde_json::from_str(r#"{"size": "12", "shard": 3, "threshold": "0.1"}"#).unwrap(); @@ -76,3 +94,33 @@ mod tests { assert!(e.to_string().contains("\"lots\" isn't a number"), "{e}"); } } + +/// Numbers inside untagged enums and `#[serde(flatten)]` structs go through serde's buffer, which can't hold an +/// `arbitrary_precision` number. Each place that did is read through `serde_json::Value` now: these keep it so. +#[cfg(test)] +mod arbitrary_precision { + #[test] + fn a_config_threshold_reads_floats() { + let c = visualci_core::config::Config::from_json(&serde_json::json!({"threshold": 0.1})).expect("0.1"); + assert_eq!(c.threshold, Some(visualci_core::config::Threshold::All(0.1))); + let c = visualci_core::config::Config::from_json( + &serde_json::from_str(r#"{"threshold": {"screenshots/**": 0.25, "pdfs/**": 0}}"#).unwrap(), + ) + .expect("by glob"); + let Some(visualci_core::config::Threshold::ByGlob(map)) = c.threshold else { panic!("by glob") }; + assert_eq!(map.get("screenshots/**"), Some(&0.25)); + assert_eq!(map.get("pdfs/**"), Some(&0.0)); + } + + #[test] + fn update_project_args_read_numbers() { + let a: crate::mcp::args::UpdateProjectArgs = serde_json::from_str( + r#"{"project": "acme/web", "threshold": 0.1, "dpi": 150, + "ignore_rules": [{"snapshots": "ios/**", "region": {"bottom": 260}}]}"#, + ) + .expect("numbers in a flattened change"); + assert_eq!(a.project.as_deref(), Some("acme/web")); + assert_eq!((a.change.threshold, a.change.dpi), (Some(0.1), Some(150))); + assert_eq!(a.change.ignore_rules.map(|r| r.len()), Some(1)); + } +} diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs index eaf8239f..5d8fa794 100644 --- a/app/src/mcp/args.rs +++ b/app/src/mcp/args.rs @@ -74,7 +74,7 @@ pub struct ProjectArgs { pub project: Option, } -#[derive(Debug, Deserialize, JsonSchema)] +#[derive(Debug, JsonSchema)] pub struct UpdateProjectArgs { /// `org/project`. Optional with a project token. pub project: Option, @@ -82,6 +82,23 @@ pub struct UpdateProjectArgs { pub change: crate::domain::projects::SettingsChange, } +/// Read through `serde_json::Value`, not with `#[serde(flatten)]`: flatten buffers the fields, and with serde_json's +/// `arbitrary_precision` on (the app's dependencies turn it on) a buffered number can't become an `f64` or `i32`, so +/// `threshold`, `dpi` and mask sizes were refused. The schema still describes the flattened shape. +impl<'de> Deserialize<'de> for UpdateProjectArgs { + fn deserialize>(d: D) -> Result { + use serde::de::Error; + let mut value = serde_json::Value::deserialize(d)?; + let project = match value.as_object_mut().and_then(|m| m.remove("project")) { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(s)) => Some(s), + Some(other) => return Err(D::Error::custom(format!("project is `org/project`, not {other}"))), + }; + let change = serde_json::from_value(value).map_err(D::Error::custom)?; + Ok(Self { project, change }) + } +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct CreateTokenArgs { /// `org/project`. Optional with a project token. diff --git a/app/tests/api_builds.rs b/app/tests/api_builds.rs index 395d667a..44b7a662 100644 --- a/app/tests/api_builds.rs +++ b/app/tests/api_builds.rs @@ -169,3 +169,38 @@ async fn no_snapshot_is_written_when_any_in_the_request_is_invalid(app: Applicat assert_eq!(count, Some(0)); Ok(()) } + +/// `visualci upload --threshold 0.1` sends `"threshold": 0.1`, a bare float. With serde_json's `arbitrary_precision` +/// on (the app's dependencies turn it on) the lenient number reader refused it with 422 "data did not match any variant +/// of untagged enum NumberOrString", for every such upload from the cutover until this test (3 Dec 2026). +#[laravel::test] +async fn snapshots_take_a_float_threshold(app: Application) -> laravel::Result<()> { + let (token, _) = project_token("pdfs").await?; + let auth = format!("Bearer {token}"); + let build = app.post("/api/v1/builds").header("authorization", &auth).json(build_params(None)).await.json().clone(); + let id = build["id"].as_str().unwrap().to_string(); + let url = format!("/api/v1/builds/{id}/snapshots"); + for (name, threshold) in [("as-number", json!(0.1)), ("as-string", json!("0.1")), ("integer", json!(1))] { + let response = app + .post(&url) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": name, "platform": "chrome", "kind": "image", + "sha256": "d".repeat(64), "size": 10, "content_type": "image/png", "threshold": threshold + }]})) + .await; + response.assert_ok(); + } + let stored: Vec<(String, Option)> = laravel::db::query!( + "SELECT name, threshold FROM snapshots WHERE build_id = (SELECT id FROM builds WHERE pid = {id}::uuid) \ + ORDER BY name" + ) + .select_as() + .await?; + assert_eq!( + stored, + [("as-number".into(), Some(0.1)), ("as-string".into(), Some(0.1)), ("integer".into(), Some(1.0))], + "each threshold as sent" + ); + Ok(()) +} diff --git a/crates/visualci-core/src/config.rs b/crates/visualci-core/src/config.rs index 212eb464..324bd852 100644 --- a/crates/visualci-core/src/config.rs +++ b/crates/visualci-core/src/config.rs @@ -238,7 +238,7 @@ impl ImageMask { } } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)] #[serde(untagged)] pub enum Threshold { /// One threshold for every snapshot. @@ -247,6 +247,24 @@ pub enum Threshold { ByGlob(BTreeMap), } +/// Read through `serde_json::Value`, not as an untagged enum: with serde_json's `arbitrary_precision` on (the server's +/// dependencies turn it on), an untagged enum sees a number as a private map and matches neither variant, so a stored +/// `threshold: 0.1` stopped validating on the server. +impl<'de> Deserialize<'de> for Threshold { + fn deserialize>(d: D) -> Result { + use serde::de::Error; + fn float(v: &serde_json::Value) -> Result { + v.as_f64().ok_or_else(|| E::custom(format!("a threshold is a number, not {v}"))) + } + match serde_json::Value::deserialize(d)? { + serde_json::Value::Object(map) => { + map.iter().map(|(glob, v)| Ok((glob.clone(), float(v)?))).collect::>().map(Self::ByGlob) + } + v => float(&v).map(Self::All), + } + } +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct PdfConfig {