From 2321e060e0fea272a5d51ac138a5ec022f7eb71b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 21:44:06 +1300 Subject: [PATCH] A snapshot sent twice with other content is a 409 (sc-8844): registering a name (with its platform) already in the build with the same file is still fine (a retried job), but other content is refused with 409 Conflict naming the snapshot, instead of silently replacing it: two jobs or shards sending one name is a naming bug in the suite. Processing a build twice (a retried or doubled job) no longer fails on the snapshots it carries forward or marks removed (docspring/docspring's pdf build #6 ended in a duplicate-key error). Docs: CircleCI, API and CLI references; plugin 0.1.37 --- server/frontend/content/docs/ci/circleci.md | 2 + server/frontend/content/docs/reference/api.md | 2 + server/frontend/content/docs/reference/cli.md | 2 +- server/src/controllers/api.rs | 4 ++ server/src/models/builds.rs | 43 ++++++++++++++++--- server/src/models/snapshots.rs | 22 ++++++++++ server/tests/requests/api.rs | 42 ++++++++++++++++++ skills/visualci-circleci/SKILL.md | 2 + 8 files changed, 112 insertions(+), 7 deletions(-) diff --git a/server/frontend/content/docs/ci/circleci.md b/server/frontend/content/docs/ci/circleci.md index 0d920847..fa294361 100644 --- a/server/frontend/content/docs/ci/circleci.md +++ b/server/frontend/content/docs/ci/circleci.md @@ -45,6 +45,8 @@ The build is compared once every shard has finalized. The [Ruby helpers](/docs/s If some containers can be skipped (for example, tests split by changed files), add `--subset` when creating the build, so snapshots that weren't sent aren't counted as removed. +Snapshot names must be unique across the build's jobs and containers. Sending the same file under a name again is fine (a job that's run again does it), but two containers sending different content under one name is refused with a 409 that names the snapshot: give each test's snapshot a name of its own. + ## Orb A VisualCI orb (`visualci/visualci`) is coming. It will turn the steps above into `visualci/upload` and `visualci/finalize`. Until it's published, use the steps above. diff --git a/server/frontend/content/docs/reference/api.md b/server/frontend/content/docs/reference/api.md index ff13e597..f752ea49 100644 --- a/server/frontend/content/docs/reference/api.md +++ b/server/frontend/content/docs/reference/api.md @@ -53,6 +53,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 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 `POST /api/v1/builds/{id}/finalize`, with an empty body or `{"shard": 0}`. VisualCI compares the build once every shard has finalized. The response is the build. A build that was sent no snapshots fails; send `"allow_empty": true` when it's empty on purpose. diff --git a/server/frontend/content/docs/reference/cli.md b/server/frontend/content/docs/reference/cli.md index d5e4d922..5634b744 100644 --- a/server/frontend/content/docs/reference/cli.md +++ b/server/frontend/content/docs/reference/cli.md @@ -19,7 +19,7 @@ Creates a build and prints its id. Export it as `VISUALCI_BUILD_ID`. | --- | --- | | `--name ` | A suite's name, for several suites in one project. Each name has its own builds and baselines. Default `default`. | | `--shards ` | How many parallel shards will finalize this build. Default 1. | -| `--nonce ` | Shards that create the build with the same nonce get the same build back. | +| `--nonce ` | Shards that create the build with the same nonce get the same build back. Their snapshot names must be unique across the shards: two sending different files under one name is refused. | | `--subset` | The build has only some of the project's snapshots: missing ones are carried forward, not removed. | | `--mode ci\|local` | Default: `ci` when the CLI detects a CI provider (or `CI=true`), else `local`. Local builds get no GitHub check; approving their changes sets the baselines for their branch. | diff --git a/server/src/controllers/api.rs b/server/src/controllers/api.rs index cdb5c291..ca7c26fd 100644 --- a/server/src/controllers/api.rs +++ b/server/src/controllers/api.rs @@ -195,6 +195,10 @@ async fn own_build(ctx: &AppContext, project: &projects::Model, pid: Uuid) -> Re fn model_error(e: ModelError) -> Error { match e { + // A snapshot name sent twice to one build with different content: a conflict, not a bad request. + ModelError::Message(m) if m.contains(snapshots::ALREADY_UPLOADED) => { + Error::CustomError(axum::http::StatusCode::CONFLICT, loco_rs::controller::ErrorDetail::new("conflict", m)) + } ModelError::Message(m) => Error::BadRequest(m), ModelError::EntityNotFound => Error::NotFound, other => Error::Model(other), diff --git a/server/src/models/builds.rs b/server/src/models/builds.rs index 5c6389f8..f938eabd 100644 --- a/server/src/models/builds.rs +++ b/server/src/models/builds.rs @@ -618,15 +618,36 @@ impl Model { state: Set("pending".to_string()), carried_forward: Set(true), ..Default::default() + }; + // A second run of this processing (the job retried, or run twice at once) finds the row there already. + let inserted = snapshots::Entity::insert(carried) + .on_conflict( + sea_orm::sea_query::OnConflict::columns([ + snapshots::snapshots::Column::BuildId, + snapshots::snapshots::Column::Name, + snapshots::snapshots::Column::Platform, + ]) + .do_nothing() + .to_owned(), + ) + .exec_without_returning(db) + .await?; + if inserted == 0 { + continue; } - .insert(db) - .await?; + let carried = snapshots::Entity::find() + .filter(snapshots::snapshots::Column::BuildId.eq(self.id)) + .filter(snapshots::snapshots::Column::Name.eq(name.clone())) + .filter(snapshots::snapshots::Column::Platform.eq(platform.clone())) + .one(db) + .await? + .ok_or_else(|| Error::string("the carried snapshot wasn't saved"))?; if let Err(e) = carried.clone().compare(db, store, &settings, Some(base_snapshot)).await { tracing::warn!(build = self.id, snapshot = carried.id, error = %e, "carrying a snapshot forward failed"); carried.into_active_model().mark_failed(db, &format!("comparison failed: {e}")).await?; } } else { - snapshots::ActiveModel { + let removed = snapshots::ActiveModel { pid: Set(Uuid::new_v4()), build_id: Set(self.id), name: Set(name.clone()), @@ -640,9 +661,19 @@ impl Model { base_snapshot_id: Set(Some(base_snapshot.id)), baseline_id: Set(baseline_rows.get(&(name.clone(), platform.clone())).copied()), ..Default::default() - } - .insert(db) - .await?; + }; + snapshots::Entity::insert(removed) + .on_conflict( + sea_orm::sea_query::OnConflict::columns([ + snapshots::snapshots::Column::BuildId, + snapshots::snapshots::Column::Name, + snapshots::snapshots::Column::Platform, + ]) + .do_nothing() + .to_owned(), + ) + .exec_without_returning(db) + .await?; } } diff --git a/server/src/models/snapshots.rs b/server/src/models/snapshots.rs index ad3e1e2f..bfb0c91b 100644 --- a/server/src/models/snapshots.rs +++ b/server/src/models/snapshots.rs @@ -58,6 +58,9 @@ pub struct SnapshotParams { pub ignore: Option, } +/// 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"; + impl SnapshotParams { /// # Errors /// A message for the client when a field is invalid. @@ -155,6 +158,25 @@ impl Model { renderer_version: &str, params: &SnapshotParams, ) -> ModelResult { + // The same name twice in one build: the same file again is a retry (a CI job run again) and fine; other + // content is a naming bug in the suite (two jobs or shards sending one name), so it's refused, not overwritten. + let earlier = Entity::find() + .filter(snapshots::Column::BuildId.eq(build.id)) + .filter(snapshots::Column::Name.eq(params.name.clone())) + .filter(snapshots::Column::Platform.eq(params.platform.clone())) + .one(db) + .await?; + if let Some(e) = earlier + && !e.carried_forward + && e.source_blob.as_deref() != Some(params.sha256.as_str()) + { + let platform = if params.platform.is_empty() { String::new() } else { format!(" ({})", params.platform) }; + return Err(ModelError::Message(format!( + "{}{platform} was {ALREADY_UPLOADED} with other content: snapshot names must be unique across a \ + build's jobs and shards", + params.name + ))); + } let renderer_key = settings.renderer_key(params.engine.as_deref(), renderer_version); let render = if params.kind == "document" { renders::Model::find_usable(db, build.project_id, ¶ms.fingerprint, &renderer_key).await? diff --git a/server/tests/requests/api.rs b/server/tests/requests/api.rs index 661e32f1..c7ed3d81 100644 --- a/server/tests/requests/api.rs +++ b/server/tests/requests/api.rs @@ -120,6 +120,48 @@ async fn shards_with_the_same_nonce_share_a_build() { .await; } +/// The same snapshot name twice in one build: the same file again is a retry and fine; other content is a naming bug +/// in the suite (two jobs or shards sending one name), so it's a 409 naming the snapshot, never a silent overwrite +/// (docspring/docspring's pdf build #6 ended in a database error instead, 1 Dec 2026). +#[tokio::test] +#[serial] +async fn a_snapshot_sent_twice_with_other_content_is_a_conflict() { + request::(|request, ctx| async move { + let auth = format!("Bearer {}", project_token(&ctx).await); + let build: serde_json::Value = request + .post("/api/v1/builds") + .add_header("authorization", auth.clone()) + .json(&build_params(None)) + .await + .json(); + let id = build["id"].as_str().unwrap().to_string(); + let send = |sha: char| { + let body = serde_json::json!({ "snapshots": [{ + "name": "invoice", "platform": "chrome", "kind": "image", "fingerprint": "b".repeat(64), + "sha256": sha.to_string().repeat(64), "size": 10, "content_type": "image/png" + }]}); + let (request, auth, id) = (&request, auth.clone(), id.clone()); + async move { + request + .post(&format!("/api/v1/builds/{id}/snapshots")) + .add_header("authorization", auth) + .json(&body) + .await + } + }; + assert_eq!(send('a').await.status_code(), 200); + assert_eq!(send('a').await.status_code(), 200, "the same file again (a retried job) is fine"); + let other = send('c').await; + assert_eq!(other.status_code(), 409, "{}", other.text()); + assert!( + other.text().contains("invoice (chrome) was already uploaded to this build with other content"), + "{}", + other.text() + ); + }) + .await; +} + #[tokio::test] #[serial] async fn registers_snapshots_and_asks_for_new_files() { diff --git a/skills/visualci-circleci/SKILL.md b/skills/visualci-circleci/SKILL.md index aa495f96..7b6b8119 100644 --- a/skills/visualci-circleci/SKILL.md +++ b/skills/visualci-circleci/SKILL.md @@ -50,6 +50,8 @@ The build is compared once every shard has finalized. The [Ruby helpers](https:/ If some containers can be skipped (for example, tests split by changed files), add `--subset` when creating the build, so snapshots that weren't sent aren't counted as removed. +Snapshot names must be unique across the build's jobs and containers. Sending the same file under a name again is fine (a job that's run again does it), but two containers sending different content under one name is refused with a 409 that names the snapshot: give each test's snapshot a name of its own. + ## Orb A VisualCI orb (`visualci/visualci`) is coming. It will turn the steps above into `visualci/upload` and `visualci/finalize`. Until it's published, use the steps above.