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
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"plugins": [
{
"name": "visualci",
"version": "0.1.68",
"version": "0.1.71",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": {
"name": "DocSpring",
Expand Down
10 changes: 8 additions & 2 deletions app/src/domain/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,13 +372,19 @@ pub async fn finalize_shard(build: Build, shard: Option<i32>, allow_empty: bool)
)
.update()
.await?;
db::query!(
let finalized = db::query!(
"UPDATE builds SET state = 'processing', finalized_at = now(), updated_at = now() \
WHERE id = {id} AND state = 'receiving' AND jsonb_array_length(shards_finalized) >= shard_total"
)
.update()
.await?;
Build::find_or_fail(id).await
let build = Build::find_or_fail(id).await?;
// An empty rerun whose suite's earlier build was never finalized finalizes and follows that build.
if finalized > 0 {
super::reruns::adopt(&build).await?;
return Build::find_or_fail(id).await;
}
Ok(build)
}
.await;
result.or_else(server)
Expand Down
2 changes: 2 additions & 0 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,8 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
if earlier.iter().any(|w| w == LOCAL_FINISHED) {
warnings.push(LOCAL_FINISHED.to_string());
}
// So does a build an empty rerun finalized.
warnings.extend(earlier.iter().filter(|w| w.starts_with(super::reruns::ADOPTED_PREFIX)).cloned());
let has_base = !base_snapshots.is_empty();

let warnings = serde_json::json!(warnings);
Expand Down
123 changes: 123 additions & 0 deletions app/src/domain/reruns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
//! of the same project, suite (`name`), environment, commit and branch has been finalized and wasn't itself empty. While
//! that build is still processing, the empty one waits, processing, and concludes when it does.
//!
//! When no earlier build was finalized, the first workflow may have stopped before finalizing it: its suite's jobs sent
//! their snapshots, then another job failed, and the job that finalizes never ran. The rerun carries the suite's jobs
//! over without running them, so its build is empty, and the earlier build is still `receiving`, or already failed:
//! given up on after the hour, or closed when its GitHub Actions run failed. The empty build then finalizes that build
//! (reopening a failed one) and follows it, on being finalized itself ([`unfinished`], [`adopt`]): only one of the same
//! project, suite, environment, commit and branch that was sent snapshots and, while receiving, has had nothing arrive
//! for [`ADOPT_AFTER_MINUTES`], so a workflow still uploading is never cut short.
//!
//! A build that was sent exactly what such an earlier build was sent follows it too (case studies, 9b): a workflow run
//! for both `push` and `pull_request` sends the same snapshots of the same commit twice, and comparing them again would
//! only charge for the same result. Exactly: the same snapshots (name, platform, environment, kind, contents, settings
Expand All @@ -20,6 +28,7 @@ use laravel::db;
use laravel::model::update;

use super::builds::EMPTY_BUILD;
use super::processing;
use crate::models::Build;

/// The warning on a build that was sent no snapshots and follows an earlier one.
Expand All @@ -31,6 +40,21 @@ pub fn covered_warning(number: i32) -> String {
)
}

/// How long nothing must have arrived for an unfinished earlier build before an empty rerun finalizes it.
pub const ADOPT_AFTER_MINUTES: i32 = 5;

/// How [`adopted_warning`] starts: processing keeps it.
pub const ADOPTED_PREFIX: &str = "Finalized by build #";

/// The warning on an unfinished build that an empty rerun finalized.
#[must_use]
pub fn adopted_warning(number: i32) -> String {
format!(
"{ADOPTED_PREFIX}{number}: this run's jobs sent their snapshots but the job that finalizes never ran (a \
failed job before it?), and build #{number}, a rerun of the failed jobs, sent this suite nothing."
)
}

/// The warning on a build that was sent the same snapshots as an earlier one and follows it.
#[must_use]
pub fn twin_warning(number: i32) -> String {
Expand Down Expand Up @@ -84,6 +108,105 @@ pub async fn covering(build: &Build) -> laravel::Result<Option<Build>> {
Ok(found.into_iter().next())
}

/// The unfinished build an empty CI build would finalize and follow, when no finalized build covers it: the newest
/// earlier CI build of the same project, suite, environment, commit and branch that follows no build, was sent at least
/// one snapshot, and either is still receiving, with nothing arriving for [`ADOPT_AFTER_MINUTES`] (no snapshot or bundle
/// upload, and no bundle still being sent or unpacked), or failed only because it was never finalized: given up on
/// after the hour ([`processing::ABANDONED`]) or closed when its GitHub Actions run failed
/// ([`processing::run_ended_error`]).
///
/// # Errors
/// On a database error.
pub async fn unfinished(build: &Build) -> laravel::Result<Option<Build>> {
if build.mode != "ci" {
return Ok(None);
}
let (id, project_id, name, environment, sha, branch) = (
build.id,
build.project_id,
build.name.as_str(),
build.environment.as_str(),
build.commit_sha.as_str(),
build.branch.as_str(),
);
let (minutes, abandoned, run_ended) = (ADOPT_AFTER_MINUTES, processing::ABANDONED, run_ended_pattern());
let found: Vec<Build> = db::query!(
"SELECT b.* FROM builds b WHERE b.project_id = {project_id} AND b.name = {name} \
AND b.environment = {environment} AND b.commit_sha = {sha} AND b.branch = {branch} AND b.mode = 'ci' \
AND b.id < {id} AND b.covered_by_build_id IS NULL \
AND EXISTS (SELECT 1 FROM snapshots s WHERE s.build_id = b.id AND NOT s.carried_forward \
AND s.state <> 'removed' AND s.platform <> 'visualci') \
AND ((b.state = 'receiving' \
AND NOT EXISTS (SELECT 1 FROM bundle_uploads u WHERE u.build_id = b.id \
AND u.state IN ('pending', 'uploaded', 'unpacking')) \
AND GREATEST(b.updated_at, \
COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at), \
COALESCE((SELECT MAX(u.updated_at) FROM bundle_uploads u WHERE u.build_id = b.id), b.created_at)) \
< now() - make_interval(mins => {minutes})) \
OR (b.state = 'failed' AND b.finalized_at IS NULL \
AND (b.error = {abandoned} OR b.error LIKE {run_ended}))) \
ORDER BY b.id DESC LIMIT 1"
)
.select_as()
.await?;
Ok(found.into_iter().next())
}

/// A `LIKE` pattern for every [`processing::run_ended_error`].
fn run_ended_pattern() -> String {
let error = processing::run_ended_error("failed", "%");
let start = error.split(" failed, ").next().unwrap_or_default();
format!("{start} %")
}

/// When an empty CI build is finalized and no finalized build covers its commit, but an [`unfinished`] one does: it
/// follows that build, which is finalized with [`adopted_warning`] and queued. Called on finalizing, before the empty
/// build is processed, so [`follow`] finds it following and the two are processed one after the other.
///
/// # Errors
/// On a database or queue error.
pub async fn adopt(build: &Build) -> laravel::Result<()> {
if build.mode != "ci" || build.state != "processing" || build.covered_by_build_id.is_some() {
return Ok(());
}
if sent(build.id).await? > 0 || covering(build).await?.is_some() {
return Ok(());
}
let Some(earlier) = unfinished(build).await? else { return Ok(()) };
// A failed build is reopened: its error, conclusion and review state are processing's to set again.
let (id, state, warning) = (earlier.id, earlier.state.as_str(), adopted_warning(build.number));
let finalized = db::query!(
"UPDATE builds SET state = 'processing', finalized_at = now(), updated_at = now(), \
error = NULL, error_code = NULL, conclusion = NULL, review_state = 'none', completed_at = NULL, \
shards_finalized = COALESCE((SELECT jsonb_agg(n) FROM generate_series(0, shard_total - 1) AS n), '[]'), \
warnings = warnings || jsonb_build_array({warning}::TEXT) \
WHERE id = {id} AND state = {state} AND covered_by_build_id IS NULL AND finalized_at IS NULL RETURNING id"
)
.select()
.await?;
if finalized.is_empty() {
// Finalized, expired or adopted meanwhile: processing decides what the empty build does.
return Ok(());
}
let mut me = build.clone();
let warnings = with_warning(&me, earlier.number, true);
update!(me { covered_by_build_id: Some(earlier.id), warnings }).await?;
tracing::info!(
build_id = id,
by = build.id,
from = state,
"an empty rerun finalized the unfinished build of its commit"
);
// Within a request (finalizing through the API or MCP): never wait on Stripe for an automatic reload (sc-9146).
let earlier = processing::stop_if_out_of_credits_without_reloading(Build::find_or_fail(id).await?).await?;
if earlier.state == "processing" {
crate::jobs::process_build::ProcessBuild { build_id: id }.dispatch().await?;
} else {
crate::events::BuildChanged { build_id: id }.dispatch().await?;
}
Ok(())
}

/// The earlier build this CI build is the other half of, when a workflow runs on both `push` and `pull_request`: the
/// newest earlier CI build of the same project, suite, environment, commit, branch, visualci.yml, base branch, subset
/// and shards that was finalized, wasn't empty and follows no build itself, whose sent snapshots are this build's,
Expand Down
121 changes: 121 additions & 0 deletions app/tests/reruns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,124 @@ async fn a_second_run_that_sent_the_same_snapshots_follows_the_first(app: Applic
assert_eq!(build(4).await?.covered_by_build_id, None);
Ok(())
}

/// The first workflow's pdf jobs sent their snapshots, then another job failed and the finalizing job never ran: the
/// pdf build is still receiving. The rerun of the failed jobs carries the pdf jobs over without running them, so its pdf
/// build is empty: it finalizes the unfinished build and follows it (DocSpring PR #1482, builds 144 and 153).
#[laravel::test]
async fn an_empty_rerun_finalizes_the_unfinished_build_of_its_commit(app: Application) -> laravel::Result<()> {
Box::pin(adopting(app)).await
}

async fn adopting(app: Application) -> laravel::Result<()> {
use app::domain::reruns::adopted_warning;
fixtures::blob_store().await?;
let token = project_token().await?;
let pdf = |commit, nonce| Run { name: "pdf", commit, branch: "main", nonce };

// #1: sent, never finalized, quiet for 6 minutes. #2: the rerun, empty.
send(&app, &token, &pdf("c1", "workflow-1-pdf"), &[("invoice.png", RED), ("receipt.png", BLUE)]).await;
quiet(build(1).await?.id).await?;
let rerun = run(&app, &token, &pdf("c1", "workflow-2-pdf"), &[]).await;
let first = build(1).await?;
assert_eq!(first.state, "completed", "{first:?}");
let first_warnings: Vec<String> = serde_json::from_value(first.warnings.clone()).unwrap_or_default();
assert!(first_warnings.contains(&adopted_warning(2)), "{first_warnings:?}");
assert_eq!(app::domain::snapshots::of_build(first.id).await?.len(), 2);
assert_eq!(rerun["state"], "completed", "{rerun}");
assert_eq!(rerun["passed"], true, "{rerun}");
assert_eq!(rerun["error"], Value::Null, "{rerun}");
assert!(warnings(&rerun).contains(&covered_warning(1)), "{rerun}");
assert_eq!(build(2).await?.covered_by_build_id, Some(first.id));
assert_eq!(check(2).await?.1, check(1).await?.1);

// #3 sent a minute ago (a workflow still uploading): an empty #4 doesn't cut it short, and fails as empty.
send(&app, &token, &pdf("c2", "workflow-3-pdf"), &[("invoice.png", RED)]).await;
let empty = run(&app, &token, &pdf("c2", "workflow-4-pdf"), &[]).await;
assert_eq!(empty["error"], EMPTY_BUILD, "{empty}");
assert_eq!(build(3).await?.state, "receiving");
assert_eq!(build(4).await?.covered_by_build_id, None);
Ok(())
}

/// The first workflow's build already failed because it was never finalized (given up on at the hour, or closed when
/// its GitHub Actions run failed): the empty rerun reopens it and follows it. A build that failed for another reason,
/// or one with a bundle still on its way, is left alone.
#[laravel::test]
async fn an_empty_rerun_reopens_a_build_that_failed_unfinished(app: Application) -> laravel::Result<()> {
Box::pin(reopening(app)).await
}

async fn reopening(app: Application) -> laravel::Result<()> {
fixtures::blob_store().await?;
let token = project_token().await?;
let pdf = |commit, nonce| Run { name: "pdf", commit, branch: "main", nonce };

// #1 was given up on at the hour, and #3 closed when its GitHub Actions run failed: their empty reruns, #2 and #4,
// reopen them, finalize them and follow them.
send(&app, &token, &pdf("c3", "workflow-1-pdf"), &[("invoice.png", RED)]).await;
let id = build(1).await?.id;
db::query!(
"UPDATE builds SET updated_at = now() - interval '61 minutes', created_at = now() - interval '62 minutes' \
WHERE id = {id}"
)
.update()
.await?;
db::query!("UPDATE snapshots SET updated_at = now() - interval '61 minutes' WHERE build_id = {id}")
.update()
.await?;
assert_eq!(app::domain::processing::expire_abandoned(Some(build(1).await?.project_id)).await?, 1);
assert_eq!(build(1).await?.state, "failed");
let rerun = run(&app, &token, &pdf("c3", "workflow-2-pdf"), &[]).await;
let reopened = build(1).await?;
assert_eq!((reopened.state.as_str(), reopened.error.as_deref()), ("completed", None), "{reopened:?}");
assert_eq!(rerun["state"], "completed", "{rerun}");
assert_eq!(rerun["error"], Value::Null, "{rerun}");
assert_eq!(build(2).await?.covered_by_build_id, Some(reopened.id));

send(&app, &token, &pdf("c4", "workflow-3-pdf"), &[("invoice.png", RED)]).await;
let (id, error) = (build(3).await?.id, app::domain::processing::run_ended_error("cancelled", "https://x/runs/3"));
db::query!("UPDATE builds SET state = 'failed', conclusion = 'failed', error = {error} WHERE id = {id}")
.update()
.await?;
let rerun = run(&app, &token, &pdf("c4", "workflow-4-pdf"), &[]).await;
assert_eq!(build(3).await?.state, "completed");
assert_eq!(rerun["error"], Value::Null, "{rerun}");

// #5 failed for another reason: it stays failed, and its empty rerun #6 fails as empty.
send(&app, &token, &pdf("c5", "workflow-5-pdf"), &[("invoice.png", RED)]).await;
let id = build(5).await?.id;
db::query!("UPDATE builds SET state = 'failed', conclusion = 'failed', error = 'boom' WHERE id = {id}")
.update()
.await?;
let empty = run(&app, &token, &pdf("c5", "workflow-6-pdf"), &[]).await;
assert_eq!(empty["error"], EMPTY_BUILD, "{empty}");
assert_eq!(build(5).await?.state, "failed");

// #7 is quiet, but a bundle is still on its way: its empty rerun #8 leaves it alone.
send(&app, &token, &pdf("c6", "workflow-7-pdf"), &[("invoice.png", RED)]).await;
let id = build(7).await?.id;
quiet(id).await?;
db::query!(
"INSERT INTO bundle_uploads (pid, build_id, object_key, entries, files, compressed_bytes, unpacked_bytes, \
updated_at) VALUES (gen_random_uuid(), {id}, 'k', '[]', 1, 1, 1, now() - interval '6 minutes')"
)
.update()
.await?;
let empty = run(&app, &token, &pdf("c6", "workflow-8-pdf"), &[]).await;
assert_eq!(empty["error"], EMPTY_BUILD, "{empty}");
assert_eq!(build(7).await?.state, "receiving");
Ok(())
}

/// Nothing has arrived for this build for 6 minutes.
async fn quiet(id: i64) -> laravel::Result<()> {
db::query!(
"UPDATE builds SET updated_at = now() - interval '6 minutes', created_at = now() - interval '7 minutes' \
WHERE id = {id}"
)
.update()
.await?;
db::query!("UPDATE snapshots SET updated_at = now() - interval '6 minutes' WHERE build_id = {id}").update().await?;
Ok(())
}
1 change: 1 addition & 0 deletions frontend/content/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ What changed in VisualCI for the people and agents using it, newest first. Dates

- **Gallery libraries 0.3.0:** dimensions. Theme and size become two of a gallery's dimensions, and the `dimensions` option adds your own (a language, a plan) or changes theirs (a high-contrast theme, a tablet size). The words in a screenshot's name pick its values, in any order. A switch with four values or more is a drop-down list that follows the WAI-ARIA select-only combobox pattern. A screen without the chosen language shows its first, a screen without the chosen size is hidden, and every screen needs every theme. The "Screenshots by VisualCI" line is off by default; `credit: true` shows it. The markup's attributes change (`data-vg-for`, `data-vg-shown`), so update the JS library with the server libraries. [Dimensions](/docs/gallery/options/#dimensions)
- Docs links to headings with an apostrophe work: a heading like "Choose what's public" is at `#choose-whats-public`, where the page used to give it `#choose-what-39-s-public`. The Ruby gem's documentation link goes to the RSpec screenshots page.
- A rerun of only the failed jobs no longer fails a suite as empty when the first run's finalizing job never ran: the rerun's empty build finalizes the first run's build, once nothing has arrived for it for 5 minutes (or after VisualCI gave up on it), and shows its result. [CircleCI](/docs/ci/circleci/#rerunning-failed-jobs)
- **Gallery libraries 0.2.2, for React, Next.js, Docusaurus, VitePress and MkDocs:** `visualci-gallery-react` (a server component for Next.js's app router), `visualci-gallery-docusaurus`, `visualci-gallery-vitepress`, and an MkDocs plugin in the `visualci-gallery` Python package. Each renders the gallery into the page when the site builds, and fails the build when the manifest can't be read. [Gallery guides](/docs/gallery/#show-it-on-your-site)
- **CLI 0.2.29: a gallery without CI.** `visualci publish <folder>` pushes a full set of screenshots from your laptop (or any machine) as a build in the builds list; once it's approved on the default branch, the gallery serves it. `gallery.environment` in visualci.yml names the environment a gallery shows, and `build create --environment` sets a build's. [Publish from your laptop](/docs/gallery/without-ci/)
- **Gallery thumbnails:** each published screenshot wider than 640 px gets a 640 px WebP thumbnail at a stable URL beside it (`<name>.thumb.webp`), and the manifest lists it with each screenshot's size in bytes, so a page can show small cards and preload by size. [Gallery](/docs/gallery/)
Expand Down
Loading
Loading