From 7518078c87c8d970a9478968ab76a314e94d4efc Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 18:41:17 +1300 Subject: [PATCH] Local builds that are never finalized finish quietly (sc-8795): after an hour with nothing new, a local build is finalized as a subset of what arrived and compared, with a warning saying so, instead of failing like an abandoned CI build; one workers::expire_abandoned for build create (REST, MCP) and builds:expire; the local runs page says so; plugin 0.1.30 --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- gemini-extension.json | 2 +- server/frontend/content/docs/local-runs.md | 2 +- server/src/controllers/api.rs | 4 +- server/src/mcp.rs | 4 +- server/src/models/builds.rs | 62 +++++++++++++++++----- server/src/tasks/builds_expire.rs | 15 ++---- server/src/workers/mod.rs | 26 +++++++++ server/tests/requests/api.rs | 29 ++++++++-- skills/visualci-local-runs/SKILL.md | 2 +- 12 files changed, 113 insertions(+), 39 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 0dbbe7ba..09457da1 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.31", + "version": "0.1.32", "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", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 29ce2de1..adfa0daf 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.31", + "version": "0.1.32", "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", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 8703afc3..cf4cb403 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.31", + "version": "0.1.32", "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" diff --git a/gemini-extension.json b/gemini-extension.json index 4a619ace..b921712a 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.31", + "version": "0.1.32", "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.", "mcpServers": { "visualci": { diff --git a/server/frontend/content/docs/local-runs.md b/server/frontend/content/docs/local-runs.md index f109ae78..1e93ff1f 100644 --- a/server/frontend/content/docs/local-runs.md +++ b/server/frontend/content/docs/local-runs.md @@ -9,7 +9,7 @@ Snapshot files and expected images don't belong in git: VisualCI keeps the basel ## How a local run works -Outside CI, `visualci build create` makes a local build. It records the branch, your user and machine, and whether the working tree has uncommitted changes. Local builds get no GitHub check and never send notifications. +Outside CI, `visualci build create` makes a local build. It records the branch, your user and machine, and whether the working tree has uncommitted changes. Local builds get no GitHub check and never send notifications. A local build that's never finalized (a test run with nowhere to call `visualci build finalize`) isn't a failure: once nothing new has arrived for an hour, VisualCI compares what it has, as a subset, and the build says it finished that way. Each snapshot is compared with its own baseline: the one approved at the nearest ancestor commit, else your branch's latest, else the default branch's. So a rebased or force-pushed branch still finds the baselines approved on it. diff --git a/server/src/controllers/api.rs b/server/src/controllers/api.rs index 971c7d4c..cdb5c291 100644 --- a/server/src/controllers/api.rs +++ b/server/src/controllers/api.rs @@ -210,9 +210,7 @@ async fn create_build( let settings = Settings::from_context(&ctx)?; // The project's earlier builds that stopped arriving are given up on now (also every few minutes by // `builds:expire`), so they don't sit "receiving" beside this one. - for id in builds::Model::expire_abandoned(&ctx.db, Some(project.id)).await? { - crate::workers::build_changed(&ctx, id).await?; - } + crate::workers::expire_abandoned(&ctx, Some(project.id)).await?; let build = builds::Model::create(&ctx.db, &project, ¶ms).await.map_err(model_error)?; let slug = org_slug(&ctx, &project).await?; format::json( diff --git a/server/src/mcp.rs b/server/src/mcp.rs index e1cfb24c..02168e5a 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -2289,9 +2289,7 @@ impl VisualCi { environment: args.environment, environment_info: None, }; - for id in builds::Model::expire_abandoned(&self.ctx.db, Some(project.id)).await.map_err(internal)? { - crate::workers::build_changed(&self.ctx, id).await.map_err(internal)?; - } + crate::workers::expire_abandoned(&self.ctx, Some(project.id)).await.map_err(internal)?; match builds::Model::create(&self.ctx.db, &project, ¶ms).await { Ok(build) => Ok(CallToolResult::structured(self.build_json(&project, &build, true).await?)), Err(e) => Ok(tool_error(e.to_string())), diff --git a/server/src/models/builds.rs b/server/src/models/builds.rs index d9d3f00f..39c2f3c3 100644 --- a/server/src/models/builds.rs +++ b/server/src/models/builds.rs @@ -691,6 +691,11 @@ impl Model { tracing::warn!(build = self.id, error = %e, "matching approved changes"); } + // A local run the expiry finished keeps saying so. + let earlier: Vec = serde_json::from_value(self.warnings.clone()).unwrap_or_default(); + if earlier.iter().any(|w| w == LOCAL_FINISHED) { + warnings.push(LOCAL_FINISHED.to_string()); + } let has_base = !base_snapshots.is_empty(); let mut active = self.into_active_model(); active.warnings = Set(serde_json::json!(warnings)); @@ -1125,28 +1130,59 @@ pub const ABANDON_AFTER_MINUTES: i32 = 60; pub const ABANDONED: &str = "Nothing arrived for this build for an hour, so VisualCI gave up on it: the CI job most \ likely stopped (or failed) before `visualci build finalize`. Re-run the job to send a new build."; +/// The warning on a local build that was finished for its run (`expire_abandoned`): local runs often end without +/// `visualci build finalize` (a test binary has no hook at exit), so that's not a failure. +pub const LOCAL_FINISHED: &str = "Local run, finished without `visualci build finalize`: nothing new arrived for an \ +hour, so VisualCI compared what it had, as a subset (nothing counts as removed). `visualci test -- ` \ +finalizes a run when it ends."; + +/// What `expire_abandoned` did: CI builds it failed, and local builds it finished (now `processing`: the caller +/// queues their comparison). +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Expired { + pub failed: Vec, + pub finished: Vec, +} + impl Model { - /// Fail every build (of one project, or all) that's still receiving with nothing new for - /// `ABANDON_AFTER_MINUTES`: no snapshot registered, no shard finalized, no change at all. Returns their ids, so - /// their checks can say so (`workers::build_changed`). + /// Every build (of one project, or all) that's still receiving with nothing new for `ABANDON_AFTER_MINUTES`: no + /// snapshot registered, no shard finalized, no change at all. A CI build fails (its job stopped before finalizing), + /// with ABANDONED; a local build is finished as a subset of what arrived, with the LOCAL_FINISHED warning, since a + /// local run often has nowhere to finalize. Returns their ids, so their checks can say so and the finished ones + /// get compared (`workers::expire_abandoned`). /// /// # Errors /// On a database error. - pub async fn expire_abandoned(db: &impl ConnectionTrait, project_id: Option) -> ModelResult> { - let rows = db + pub async fn expire_abandoned(db: &impl ConnectionTrait, project_id: Option) -> ModelResult { + let quiet = "b.state = 'receiving' AND ($2::BIGINT IS NULL OR b.project_id = $2) \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(mins => $3)"; + let ids = + |rows: Vec| rows.iter().filter_map(|r| r.try_get::("", "id").ok()).collect(); + let failed = db .query_all_raw(Statement::from_sql_and_values( DbBackend::Postgres, - "UPDATE builds b SET state = 'failed', conclusion = 'failed', review_state = 'none', error = $1, \ - completed_at = now(), updated_at = now() \ - WHERE b.state = 'receiving' AND ($2::BIGINT IS NULL OR b.project_id = $2) \ - AND GREATEST(b.updated_at, \ - COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ - < now() - make_interval(mins => $3) \ - RETURNING b.id", + format!( + "UPDATE builds b SET state = 'failed', conclusion = 'failed', review_state = 'none', error = $1, \ + completed_at = now(), updated_at = now() \ + WHERE b.mode <> 'local' AND {quiet} RETURNING b.id" + ), [ABANDONED.into(), project_id.into(), ABANDON_AFTER_MINUTES.into()], )) .await?; - Ok(rows.iter().filter_map(|r| r.try_get::("", "id").ok()).collect()) + let finished = db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + format!( + "UPDATE builds b SET state = 'processing', subset = true, allow_empty = true, \ + warnings = b.warnings || jsonb_build_array($1::TEXT), finalized_at = now(), updated_at = now() \ + WHERE b.mode = 'local' AND {quiet} RETURNING b.id" + ), + [LOCAL_FINISHED.into(), project_id.into(), ABANDON_AFTER_MINUTES.into()], + )) + .await?; + Ok(Expired { failed: ids(failed), finished: ids(finished) }) } } diff --git a/server/src/tasks/builds_expire.rs b/server/src/tasks/builds_expire.rs index 881ad55c..d237d9bf 100644 --- a/server/src/tasks/builds_expire.rs +++ b/server/src/tasks/builds_expire.rs @@ -1,12 +1,10 @@ -//! `cargo loco task builds:expire`: fail every build that's been receiving with nothing new for an hour -//! (`builds::Model::expire_abandoned`) and conclude its check. Run every few minutes by a CronJob, which pushes its +//! `cargo loco task builds:expire`: fail every CI build that's been receiving with nothing new for an hour, and finish +//! every such local build as a subset (`workers::expire_abandoned`), and conclude their checks. Run every few minutes by a CronJob, which pushes its //! result to a Gatus heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`); `/status` reports the oldest //! receiving build as `oldest_receiving_seconds`, which stays under the hour while this runs. use loco_rs::prelude::*; -use crate::models::builds; - pub struct BuildsExpire; #[async_trait] @@ -21,15 +19,12 @@ impl Task for BuildsExpire { async fn run(&self, ctx: &AppContext, _vars: &task::Vars) -> Result<()> { let outcome = async { - let ids = builds::Model::expire_abandoned(&ctx.db, None).await?; - for id in &ids { - crate::workers::build_changed(ctx, *id).await?; - } + let expired = crate::workers::expire_abandoned(ctx, None).await?; // Emails that weren't sent at once (Postmark down, or queued where nothing could send them): the // ten-minute sweep sends them. let emails = crate::notify::deliver_pending(ctx).await?; println!("builds:expire: {emails} queued emails sent"); - Ok::(ids.len()) + Ok::(expired) } .await; crate::heartbeat::push( @@ -37,7 +32,7 @@ impl Task for BuildsExpire { outcome.as_ref().map(|_| ()).map_err(ToString::to_string), ) .await; - println!("builds:expire: {} abandoned builds failed", outcome?); + println!("builds:expire: {} abandoned builds failed or finished", outcome?); Ok(()) } } diff --git a/server/src/workers/mod.rs b/server/src/workers/mod.rs index f43c669a..942670cc 100644 --- a/server/src/workers/mod.rs +++ b/server/src/workers/mod.rs @@ -7,6 +7,32 @@ pub mod process_build; use loco_rs::prelude::*; +/// Expire the builds (of one project, or all) that stopped arriving (`builds::Model::expire_abandoned`): a failed CI +/// build's check says why, and a finished local build is compared like a finalized one (or stops, out of credits). +/// Returns how many it expired. +/// +/// # Errors +/// On a database or queue error. +pub async fn expire_abandoned(ctx: &AppContext, project_id: Option) -> Result { + let expired = crate::models::builds::Model::expire_abandoned(&ctx.db, project_id).await?; + for id in &expired.failed { + build_changed(ctx, *id).await?; + } + for id in &expired.finished { + let build = crate::models::builds::Model::find_by_id(&ctx.db, *id).await?.stop_if_out_of_credits(ctx).await?; + if build.state == "processing" { + process_build::ProcessBuildWorker::perform_later( + ctx, + process_build::ProcessBuildWorkerArgs { build_id: *id }, + ) + .await?; + } else { + build_changed(ctx, *id).await?; + } + } + Ok(expired.failed.len() + expired.finished.len()) +} + /// A build's state changed (processed, reviewed, superseded): update its check and pull request comment on the forge, /// and purge the public gallery's cached copies it makes stale. /// diff --git a/server/tests/requests/api.rs b/server/tests/requests/api.rs index e8cef3e9..661e32f1 100644 --- a/server/tests/requests/api.rs +++ b/server/tests/requests/api.rs @@ -214,7 +214,7 @@ async fn registers_snapshots_and_asks_for_new_files() { /// an error that says what happened, and its check says so too. Recent ones are left alone. #[tokio::test] #[serial] -async fn a_build_nothing_arrives_for_is_failed_after_an_hour() { +async fn after_an_hour_with_nothing_arriving_a_ci_build_fails_and_a_local_one_is_finished() { request::(|request, ctx| async move { use sea_orm::{ConnectionTrait, DbBackend, Statement}; use visualci_server::models::builds; @@ -229,13 +229,26 @@ async fn a_build_nothing_arrives_for_is_failed_after_an_hour() { let old = builds::Model::find_by_pid(&ctx.db, uuid::Uuid::parse_str(old["id"].as_str().unwrap()).unwrap()) .await .unwrap(); + // A local run that never finalized (a test binary has no hook at exit). + let mut local_params = build_params(None); + local_params["mode"] = serde_json::json!("local"); + let local: serde_json::Value = request + .post("/api/v1/builds") + .add_header("authorization", format!("Bearer {token}")) + .json(&local_params) + .await + .json(); + let local = builds::Model::find_by_pid(&ctx.db, uuid::Uuid::parse_str(local["id"].as_str().unwrap()).unwrap()) + .await + .unwrap(); + assert_eq!(local.mode, "local"); // Two hours without anything arriving. ctx.db .execute_raw(Statement::from_sql_and_values( DbBackend::Postgres, "UPDATE builds SET created_at = now() - interval '2 hours', updated_at = now() - interval '2 hours' \ - WHERE id = $1", - [old.id.into()], + WHERE id = ANY($1)", + [vec![old.id, local.id].into()], )) .await .unwrap(); @@ -255,9 +268,17 @@ async fn a_build_nothing_arrives_for_is_failed_after_an_hour() { "creating a build expires the project's abandoned ones" ); assert_eq!(old.error.as_deref(), Some(builds::ABANDONED)); + // The local one is finished as a subset of what arrived, not failed, and says why. + let local = builds::Model::find_by_id(&ctx.db, local.id).await.unwrap(); + assert_ne!(local.state, "failed", "a local run that never finalized isn't a failure"); + assert_ne!(local.state, "receiving"); + assert!(local.subset && local.allow_empty && local.finalized_at.is_some()); + assert_eq!(local.error, None); + let warnings: Vec = serde_json::from_value(local.warnings.clone()).unwrap(); + assert_eq!(warnings.last().map(String::as_str), Some(builds::LOCAL_FINISHED), "{warnings:?}"); assert_eq!( builds::Model::expire_abandoned(&ctx.db, None).await.unwrap(), - Vec::::new(), + builds::Expired::default(), "nothing else is old" ); diff --git a/skills/visualci-local-runs/SKILL.md b/skills/visualci-local-runs/SKILL.md index 781f4bce..48b85b8a 100644 --- a/skills/visualci-local-runs/SKILL.md +++ b/skills/visualci-local-runs/SKILL.md @@ -14,7 +14,7 @@ Snapshot files and expected images don't belong in git: VisualCI keeps the basel ## How a local run works -Outside CI, `visualci build create` makes a local build. It records the branch, your user and machine, and whether the working tree has uncommitted changes. Local builds get no GitHub check and never send notifications. +Outside CI, `visualci build create` makes a local build. It records the branch, your user and machine, and whether the working tree has uncommitted changes. Local builds get no GitHub check and never send notifications. A local build that's never finalized (a test run with nowhere to call `visualci build finalize`) isn't a failure: once nothing new has arrived for an hour, VisualCI compares what it has, as a subset, and the build says it finished that way. Each snapshot is compared with its own baseline: the one approved at the nearest ancestor commit, else your branch's latest, else the default branch's. So a rebased or force-pushed branch still finds the baselines approved on it.