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.23"
version = "0.2.24"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
80 changes: 64 additions & 16 deletions app/src/domain/lenient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ use std::{fmt::Display, str::FromStr};

use serde::{Deserialize, Deserializer, de::Error};

#[derive(Deserialize)]
#[serde(untagged)]
enum NumberOrString<T> {
Number(T),
String(String),
}

fn read<T: FromStr>(v: NumberOrString<T>) -> Result<T, String>
/// 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<T: FromStr>(v: &serde_json::Value) -> Result<T, String>
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}")),
}
}

Expand All @@ -30,10 +31,10 @@ where
pub fn number<'de, D, T>(d: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + FromStr,
T: FromStr,
T::Err: Display,
{
read(NumberOrString::<T>::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`).
Expand All @@ -43,12 +44,12 @@ where
pub fn optional<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + FromStr,
T: FromStr,
T::Err: Display,
{
match Option::<NumberOrString<T>>::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),
}
}

Expand All @@ -64,6 +65,23 @@ mod tests {
threshold: Option<f64>,
}

/// 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::<Body>(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::<Body>(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();
Expand All @@ -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));
}
}
19 changes: 18 additions & 1 deletion app/src/mcp/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,31 @@ pub struct ProjectArgs {
pub project: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
#[derive(Debug, JsonSchema)]
pub struct UpdateProjectArgs {
/// `org/project`. Optional with a project token.
pub project: Option<String>,
#[serde(flatten)]
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: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
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.
Expand Down
35 changes: 35 additions & 0 deletions app/tests/api_builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f64>)> = 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(())
}
20 changes: 19 additions & 1 deletion crates/visualci-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -247,6 +247,24 @@ pub enum Threshold {
ByGlob(BTreeMap<String, f64>),
}

/// 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: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::Error;
fn float<E: Error>(v: &serde_json::Value) -> Result<f64, E> {
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::<Result<_, _>>().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 {
Expand Down
Loading