From 3b0976e22d7303c33366b8deb9aa89b271f28246 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:13:11 +0000 Subject: [PATCH] Stop a build's run on SIGTERM and queue the build again at once --- app/Cargo.toml | 6 +- app/src/domain/mod.rs | 1 + app/src/domain/processing.rs | 10 +++ app/src/domain/shutdown.rs | 57 +++++++++++++++ app/src/jobs/process_build.rs | 2 + app/tests/shutdown.rs | 132 ++++++++++++++++++++++++++++++++++ docs/design-storage.md | 4 +- 7 files changed, 210 insertions(+), 2 deletions(-) create mode 100644 app/src/domain/shutdown.rs create mode 100644 app/tests/shutdown.rs diff --git a/app/Cargo.toml b/app/Cargo.toml index a8e7989a..129fbb78 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -40,6 +40,10 @@ path = "tests/mcp_hosts.rs" name = "proxies" path = "tests/proxies.rs" +[[test]] +name = "shutdown" +path = "tests/shutdown.rs" + [dependencies] # Pinned exactly: each 0.x minor of Laravel Rust may break, and upgrades are deliberate. laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } @@ -60,7 +64,7 @@ serde_json = "1" # Names the field at fault when a visualci.yml doesn't parse (build_settings::parse_config) serde_path_to_error = "0.1" sha2 = "0.10" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal", "time"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index cfde5dd1..43e5e08a 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -29,5 +29,6 @@ pub mod renders; pub mod reruns; pub mod retention; pub mod reviews; +pub mod shutdown; pub mod snapshots; pub mod summary; diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 0da68449..41bb955b 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -231,6 +231,11 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la Err(e) if e.is::() => { tracing::info!(build_id = id, "another run is processing the build; it runs it again when it's done"); } + Err(e) if e.is::() => { + // The build's lock is released (`exclusive` has returned), so the next worker takes it straight away. + tracing::info!(build_id = id, "stopped for a shutdown; queued the build again"); + Box::pin(crate::jobs::process_build::ProcessBuild { build_id: id }.dispatch().into_future()).await?; + } Err(e) => { tracing::error!(build_id = id, error = %e, "processing a build failed"); let error = Some(e.to_string()); @@ -584,6 +589,11 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } // Out of credits part-way through a large build: stop between batches rather than compare the rest // (sc-9146). Document builds already stop between render waits, in `run`. + // A deploy is replacing this worker: stop here, and `run` queues the build again for another worker, which + // processes it from the start (comparing a snapshot again replaces its pages). + if super::shutdown::stopping() { + return Err(super::shutdown::Stopped.into()); + } compared += 1; if compared.is_multiple_of(CREDIT_CHECK_EVERY) && Box::pin(stop_part_way(&build)).await? { return Ok(true); diff --git a/app/src/domain/shutdown.rs b/app/src/domain/shutdown.rs new file mode 100644 index 00000000..a66294dc --- /dev/null +++ b/app/src/domain/shutdown.rs @@ -0,0 +1,57 @@ +//! Whether this worker is shutting down: Kubernetes sends `SIGTERM` when a rollout or a scale-down replaces the pod. +//! `queue:work` then stops taking jobs and waits for the running ones, but a large build's run can take far longer than +//! the pod's grace period, and a run killed part-way leaves its build until its hold lapses and the sweep runs it again. +//! A run that sees [`stopping`] stops between snapshots instead, releases the build and queues it again at once, so +//! another worker processes it straight away. + +use std::sync::Once; +use std::sync::atomic::{AtomicBool, Ordering}; + +static STOPPING: AtomicBool = AtomicBool::new(false); +static WATCHING: Once = Once::new(); + +/// Start listening for `SIGTERM`, once per process. Called by the jobs that check [`stopping`], so only queue workers +/// listen: a web pod's own runs (early comparisons) finish within its request's grace period. The listener runs on the +/// runtime of the first call, the worker's for the life of the process. +pub fn watch() { + WATCHING.call_once(|| { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + match signal(SignalKind::terminate()) { + Ok(mut terminate) => { + tokio::spawn(async move { + if terminate.recv().await.is_some() { + tracing::info!("SIGTERM: build runs stop between snapshots and queue their builds again"); + STOPPING.store(true, Ordering::SeqCst); + } + }); + } + Err(e) => tracing::warn!(error = %e, "can't listen for SIGTERM; build runs won't stop early"), + } + } + }); +} + +/// `true` once this process has received `SIGTERM` (after [`watch`]). +pub fn stopping() -> bool { + STOPPING.load(Ordering::SeqCst) +} + +/// Forget a `SIGTERM`, so a test can run the build again in the same process. +#[doc(hidden)] +pub fn reset() { + STOPPING.store(false, Ordering::SeqCst); +} + +/// The error a run returns when it stopped for [`stopping`]; [`super::processing::run`] queues the build again. +#[derive(Debug)] +pub struct Stopped; + +impl std::fmt::Display for Stopped { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the worker is shutting down; the build is queued again") + } +} + +impl std::error::Error for Stopped {} diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs index 9859a230..0223e066 100644 --- a/app/src/jobs/process_build.rs +++ b/app/src/jobs/process_build.rs @@ -31,6 +31,8 @@ impl ProcessBuild { } async fn handle(self) -> laravel::Result<()> { + // A deploy's SIGTERM stops the run between snapshots and queues the build again (`domain::shutdown`). + crate::domain::shutdown::watch(); let store = BlobStore::current().await?; let version = crate::http::api::builds::renderer_version(); // Boxed: a sync queue (tests) runs this inside the request that dispatched it. diff --git a/app/tests/shutdown.rs b/app/tests/shutdown.rs new file mode 100644 index 00000000..99d54de4 --- /dev/null +++ b/app/tests/shutdown.rs @@ -0,0 +1,132 @@ +//! A deploy's `SIGTERM` stops a build's run between snapshots: the run releases the build and queues it again at once, +//! and the next run finishes the build (`domain::shutdown`). Its own binary: `SIGTERM` and the stopping +//! flag are process-wide. + +use app::domain::{processing, shutdown}; +use app::jobs::process_build::ProcessBuild; +use app::models::Build; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::json; + +fn png(rgb: [u8; 3]) -> Vec { + let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +/// Create a build of these screenshots on `commit` and upload them, without finalizing it. Returns its id. +async fn send(app: &Application, auth: &str, commit: &str, parent: &str, shots: &[(String, [u8; 3])]) -> String { + let build = app + .post("/api/v1/builds") + .header("authorization", auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + build.assert_ok(); + let id = build.json()["id"].as_str().unwrap().to_string(); + let mut files = Vec::new(); + let mut snapshots = Vec::new(); + for (name, rgb) in shots { + let bytes = png(*rgb); + let image = image::load_from_memory(&bytes).unwrap().to_rgba8(); + snapshots.push(json!({ + "name": name, "kind": "image", "fingerprint": visualci_core::image_hash::fingerprint_rgba(&image), + "sha256": visualci_core::sha256_hex(&bytes), "size": bytes.len(), "content_type": "image/png" + })); + files.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", auth) + .json(json!({ "snapshots": snapshots })) + .await; + registered.assert_ok(); + let client = reqwest::Client::new(); + for (answer, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(files) { + if let Some(url) = answer["upload_url"].as_str() { + let put = client.put(url).header("content-type", "image/png").body(bytes).send().await.expect("an upload"); + assert!(put.status().is_success(), "uploading: {}", put.status()); + } + } + id +} + +async fn finalize(app: &Application, auth: &str, id: &str) { + app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", auth).await.assert_ok(); +} + +async fn compared(build_id: i64) -> laravel::Result { + Ok(db::query!("SELECT COUNT(*) FROM snapshots WHERE build_id = {build_id} AND state IN ('changed', 'unchanged')") + .scalar() + .await? + .unwrap_or(0)) +} + +#[laravel::test] +async fn a_sigterm_stops_a_run_between_snapshots_and_queues_the_build_again(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let org = fixtures::organization("sigterm").await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + let auth = format!("Bearer {token}"); + let shots = |blue: u8| -> Vec<(String, [u8; 3])> { + (0..5u8).map(|i| (format!("page-{i}.png"), [i * 40, 0, blue])).collect() + }; + + // The baseline processes inline (the sync queue), before any SIGTERM. + let base = send(&app, &auth, "c1", "c0", &shots(0)).await; + finalize(&app, &auth, &base).await; + + // The worker receives SIGTERM: the listener a ProcessBuild run starts sets the flag. + shutdown::watch(); + let pid = std::process::id().to_string(); + let killed = std::process::Command::new("kill").args(["-TERM", &pid]).status().expect("kill runs"); + assert!(killed.success()); + for _ in 0..500 { + if shutdown::stopping() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + assert!(shutdown::stopping(), "SIGTERM sets the stopping flag"); + + // Queued jobs are held, so the run below is the worker's: finalize queues it, and the test runs it. + let jobs = laravel::queue::fake(); + let head = send(&app, &auth, "c2", "c1", &shots(200)).await; + finalize(&app, &auth, &head).await; + let build = Build::query() + .filter(Build::number.eq(2)) + .filter(Build::project_id.eq(project_id)) + .first() + .await? + .expect("build 2"); + let store = app::storage::BlobStore::current().await?; + let version = app::http::api::builds::renderer_version(); + processing::run(build.id, &store, &version).await?; + + let stopped = Build::find_or_fail(build.id).await?; + assert_eq!(stopped.state, "processing", "a stopped run neither finishes nor fails the build: {:?}", stopped.error); + assert_eq!(compared(build.id).await?, 0, "it stopped before the first comparison"); + jobs.assert_pushed_times::(2); + jobs.assert_pushed_where::(|job| job.job().build_id == build.id); + // The build's lock is free for the next worker straight away, not after its hold lapses. + processing::exclusive(build.id, 0, || async { Ok(()) }).await?; + + // The next worker's run finishes the build. + shutdown::reset(); + processing::run(build.id, &store, &version).await?; + let done = Build::find_or_fail(build.id).await?; + assert_ne!(done.state, "processing", "the next run finishes the build"); + assert_ne!(done.state, "failed", "{:?}", done.error); + assert_eq!(compared(build.id).await?, 5); + Ok(()) +} diff --git a/docs/design-storage.md b/docs/design-storage.md index a99d3e1b..75761ee4 100644 --- a/docs/design-storage.md +++ b/docs/design-storage.md @@ -276,7 +276,9 @@ retention. again, and the conclusion is one short transaction under the build's advisory lock, which reviews take too. On 3 Dec 2026 a run holding one transaction for the whole build kept blob rows locked, and uploads registering those blobs waited 30 s and failed. The first version held the lock for 20 minutes, and a run killed by a deploy kept its - build stuck that long. + build stuck that long. A worker that gets `SIGTERM` (a rollout or a scale-down) doesn't wait to be killed: its run + stops between snapshots, releases the lock and queues `builds.process` again at once, so another worker takes the + build within seconds (`domain::shutdown`). - The render wake-up query scans `snapshots` twice: by `render_id`, and by `source_fingerprint` across the project. Use the render's `project_id` and the `render_id` index.