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 @@ -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/",
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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/",
Expand Down
2 changes: 1 addition & 1 deletion .cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion gemini-extension.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion server/frontend/content/docs/local-runs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 1 addition & 3 deletions server/src/controllers/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, &params).await.map_err(model_error)?;
let slug = org_slug(&ctx, &project).await?;
format::json(
Expand Down
4 changes: 1 addition & 3 deletions server/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, &params).await {
Ok(build) => Ok(CallToolResult::structured(self.build_json(&project, &build, true).await?)),
Err(e) => Ok(tool_error(e.to_string())),
Expand Down
62 changes: 49 additions & 13 deletions server/src/models/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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));
Expand Down Expand Up @@ -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 -- <command>` \
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<i64>,
pub finished: Vec<i64>,
}

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<i64>) -> ModelResult<Vec<i64>> {
let rows = db
pub async fn expire_abandoned(db: &impl ConnectionTrait, project_id: Option<i64>) -> ModelResult<Expired> {
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<sea_orm::QueryResult>| rows.iter().filter_map(|r| r.try_get::<i64>("", "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::<i64>("", "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) })
}
}

Expand Down
15 changes: 5 additions & 10 deletions server/src/tasks/builds_expire.rs
Original file line number Diff line number Diff line change
@@ -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]
Expand All @@ -21,23 +19,20 @@ 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::<usize, Error>(ids.len())
Ok::<usize, Error>(expired)
}
.await;
crate::heartbeat::push(
"VISUALCI_BUILDS_EXPIRE_HEARTBEAT",
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(())
}
}
26 changes: 26 additions & 0 deletions server/src/workers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>) -> Result<usize> {
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.
///
Expand Down
29 changes: 25 additions & 4 deletions server/tests/requests/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<App, _, _>(|request, ctx| async move {
use sea_orm::{ConnectionTrait, DbBackend, Statement};
use visualci_server::models::builds;
Expand All @@ -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();
Expand All @@ -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<String> = 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::<i64>::new(),
builds::Expired::default(),
"nothing else is old"
);

Expand Down
2 changes: 1 addition & 1 deletion skills/visualci-local-runs/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading