diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 1fc82c54..03c53958 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -81,9 +81,17 @@ pub async fn lock(build_id: i64) -> laravel::Result<()> { Ok(()) } -/// How long [`exclusive`] holds a build at most: longer than `ProcessBuild`'s 15-minute timeout, so a run never -/// outlives its lock. A run that stops early releases it at once, even when its worker kills it. -pub const HOLD_MINUTES: i64 = 20; +/// How long [`exclusive`] holds a build without hearing from its run. A live run renews it every +/// [`HEARTBEAT_SECONDS`]; a run that ends releases it, and one whose worker was killed (a deploy, an out-of-memory +/// kill) stops renewing it, so the build is free again within this time and the sweep runs it again. (A lock held for a +/// whole run's timeout kept a killed run's build stuck for 20 minutes.) +pub const HOLD_SECONDS: i64 = 120; + +/// How often a run renews its hold on the build. +const HEARTBEAT_SECONDS: u64 = 30; + +/// How long the note to run a build again lasts ([`run`]): longer than any run. +const AGAIN_MINUTES: i64 = 20; /// How long a processing job waits for another run of the same build. Then it leaves that run a note to process the /// build again when it's done ([`exclusive`]), rather than hold a worker while it waits. @@ -104,14 +112,55 @@ fn again_key(build_id: i64) -> String { /// # Errors /// [`laravel::cache::LockTimeout`] when another run holds the build for longer than `wait_seconds`, or `work`'s error. pub async fn exclusive(build_id: i64, wait_seconds: i64, work: F) -> laravel::Result +where + F: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + let timing = Hold { seconds: HOLD_SECONDS, heartbeat: std::time::Duration::from_secs(HEARTBEAT_SECONDS) }; + exclusive_with(build_id, wait_seconds, timing, work).await +} + +/// How long [`exclusive`] holds a build, and how often it renews the hold. Tests use shorter ones. +#[derive(Clone, Copy, Debug)] +pub struct Hold { + pub seconds: i64, + pub heartbeat: std::time::Duration, +} + +/// [`exclusive`] with its timing given. +/// +/// # Errors +/// As [`exclusive`]. +pub async fn exclusive_with(build_id: i64, wait_seconds: i64, hold: Hold, work: F) -> laravel::Result where F: FnOnce() -> Fut, Fut: std::future::Future>, { use laravel::time::ToSpan; - let out = laravel::cache::lock(&format!("builds.process:{build_id}"), HOLD_MINUTES.minutes())? + let lock = laravel::cache::lock(&format!("builds.process:{build_id}"), hold.seconds.seconds())?; + let out = lock .block(wait_seconds.seconds()) - .get(work) + .get(|| async { + // Renew the hold while the work runs, so it lapses soon after a killed worker stops renewing it. + let heartbeat = async { + loop { + tokio::time::sleep(hold.heartbeat).await; + match lock.refresh().await { + Ok(true) => {} + Ok(false) => tracing::warn!(build_id, "the build's processing lock lapsed during a run"), + Err(e) => tracing::warn!(build_id, error = %e, "renewing the build's processing lock failed"), + } + } + }; + let work = work(); + tokio::pin!(heartbeat, work); + loop { + tokio::select! { + out = &mut work => break out, + _ = &mut heartbeat => {} + } + } + }) .await; if !matches!(&out, Err(e) if e.is::()) && laravel::cache::pull::(&again_key(build_id)).await?.is_some() @@ -158,7 +207,7 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la if busy(&result) { // Leave the note first, then try once more: either this run takes the build, or whoever holds it now finds // the note when it releases it. - laravel::cache::put(&again_key(id), true, HOLD_MINUTES.minutes()).await?; + laravel::cache::put(&again_key(id), true, AGAIN_MINUTES.minutes()).await?; result = Box::pin(exclusive(id, 0, work)).await; } match result { diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs index 4fd28de7..8594f92b 100644 --- a/app/src/jobs/process_build.rs +++ b/app/src/jobs/process_build.rs @@ -12,9 +12,19 @@ pub struct ProcessBuild { pub build_id: i64, } -// A big build downloads, decodes and diffs thousands of images: 15 minutes, well within the build's processing lock -// (`processing::HOLD_MINUTES`), so the lock always outlives the run that holds it. -#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds(), timeout = 15.minutes())] +// A big build downloads, decodes and diffs thousands of images: 15 minutes. The build's processing lock is renewed +// while the run works (`processing::HOLD_SECONDS`), so it outlasts a live run and lapses soon after a killed one. +// Tried again when a run is cut off (its worker killed by a deploy, or the timeout): a run that fails part-way marks +// the build failed itself and doesn't come back here. The first retry waits out a killed run's hold on the build +// (`processing::HOLD_SECONDS`). The sweep re-runs builds stuck in processing as well. +#[job( + name = "builds.process", + debounce_for = 3.seconds(), + max_wait = 30.seconds(), + timeout = 15.minutes(), + tries = 3, + backoff = [3.minutes(), 5.minutes()] +)] impl ProcessBuild { fn debounce_id(&self) -> i64 { self.build_id diff --git a/app/tests/processing_lock.rs b/app/tests/processing_lock.rs new file mode 100644 index 00000000..54dc3bba --- /dev/null +++ b/app/tests/processing_lock.rs @@ -0,0 +1,45 @@ +//! The build's processing lock (`processing::exclusive`): a live run renews its hold for as long as it works, and a +//! run whose worker was killed stops renewing it, so the build is free again soon after. (On 3 Dec 2026 a deploy killed +//! a run holding a 20-minute lock, and its build sat in processing until the lock expired.) + +use std::time::Duration; + +use app::domain::processing::{self, Hold}; +use laravel::testing::prelude::*; +use laravel::time::ToSpan; + +const SHORT: Hold = Hold { seconds: 2, heartbeat: Duration::from_millis(400) }; + +#[laravel::test] +async fn a_live_run_keeps_the_build_for_longer_than_its_hold(_app: Application) -> laravel::Result<()> { + let build_id = 9_000_001; + // A run that works for twice its hold: another run trying meanwhile still finds the build taken. + let run = processing::exclusive_with(build_id, 0, SHORT, || async { + tokio::time::sleep(Duration::from_secs(4)).await; + Ok(()) + }); + let other = async { + tokio::time::sleep(Duration::from_secs(3)).await; + processing::exclusive_with(build_id, 0, SHORT, || async { Ok(()) }).await + }; + let (first, second) = tokio::join!(run, other); + first?; + let err = second.expect_err("the build is still held, 3 s into a 2 s hold"); + assert!(err.is::(), "{err}"); + // Once the run ends, the build is free. + processing::exclusive_with(build_id, 0, SHORT, || async { Ok(()) }).await?; + Ok(()) +} + +#[laravel::test] +async fn a_killed_runs_hold_lapses(_app: Application) -> laravel::Result<()> { + let build_id = 9_000_002; + // A run whose worker died: it took the build and never renewed or released it. + let dead = laravel::cache::lock(&format!("builds.process:{build_id}"), 2.seconds())?; + assert!(dead.acquire().await?, "the dead run took the build"); + let err = processing::exclusive_with(build_id, 0, SHORT, || async { Ok(()) }).await.expect_err("still held"); + assert!(err.is::(), "{err}"); + tokio::time::sleep(Duration::from_secs(3)).await; + processing::exclusive_with(build_id, 0, SHORT, || async { Ok(()) }).await?; + Ok(()) +} diff --git a/docs/design-storage.md b/docs/design-storage.md index 10dc9b76..9aeb06e4 100644 --- a/docs/design-storage.md +++ b/docs/design-storage.md @@ -269,12 +269,14 @@ retention. - unique jobs per (kind, build); - per-organization fairness, so one huge build can't starve everyone else. The render queue already has per-project fairness. -- In app/, one run processes a build at a time under a lock in the cache store (`processing::exclusive`, held at - most 20 minutes; `builds.process` times out after 15), never a long transaction: storage requests, decoding and +- In app/, one run processes a build at a time under a lock in the cache store (`processing::exclusive`, held for + 2 minutes and renewed every 30 s while the run works, so a killed worker's build is free again within 2 minutes; + `builds.process` times out after 15), never a long transaction: storage requests, decoding and diffing hold no database connection or row lock, per-snapshot results commit as they go and are safe to write 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. + 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. - 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.