diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index dcd7078f..06b497ba 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -408,10 +408,9 @@ impl Seeder<'_> { } let build = outcome(super::builds::finalize_shard(build, None, false).await)?; let id = build.id; - let concluded = Box::pin(db::transaction(async |_| { - super::processing::lock(id).await?; + let concluded = Box::pin(super::processing::exclusive(id, 300, || async { let build = Build::find_or_fail(id).await?; - super::processing::process(build, self.store, self.renderer_version).await + Box::pin(super::processing::process(build, self.store, self.renderer_version)).await })) .await?; if !concluded { diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index fe96067c..2e3457ad 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -70,7 +70,8 @@ impl Usage { } } -/// Hold the build's lock until the transaction ends: one worker (or one early comparison) works on a build at a time. +/// Hold the build's advisory lock until the transaction ends. Only short transactions take it: charging, concluding, +/// and reviews, which must not interleave with a conclusion. A whole processing run holds [`exclusive`] instead. /// /// # Errors /// On a database error. @@ -80,6 +81,113 @@ 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 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. +pub const JOB_WAIT_SECONDS: i64 = 10; + +/// The note a job leaves when another run holds the build: run it again once that run is done. +fn again_key(build_id: i64) -> String { + format!("builds.process-again:{build_id}") +} + +/// Run `work` while holding the build's processing lock, waiting up to `wait_seconds` for it (0 tries once): one +/// worker (or one early comparison, or the demo reset) works on a build at a time. The lock is a row in the cache +/// store, taken and released in statements of their own, so the work runs outside any transaction: its downloads, +/// decoding and diffing hold no database connection and no row locks, and its writes commit as they go (an upload +/// registering the same blob never waits for a run). Released when `work` ends, fails or is dropped. After releasing +/// it, a job that gave up waiting meanwhile is queued again. +/// +/// # 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>, +{ + use laravel::time::ToSpan; + let out = laravel::cache::lock(&format!("builds.process:{build_id}"), HOLD_MINUTES.minutes())? + .block(wait_seconds.seconds()) + .get(work) + .await; + if !matches!(&out, Err(e) if e.is::()) + && laravel::cache::pull::(&again_key(build_id)).await?.is_some() + { + Box::pin(crate::jobs::process_build::ProcessBuild { build_id }.dispatch().into_future()).await?; + } + out +} + +/// What `ProcessBuild` does: charge what the build used so far, stop it when its organization is out of credits, and +/// otherwise process it as far as it can go ([`process`]) under [`exclusive`]. A failure fails the build. When another +/// run holds the build past [`JOB_WAIT_SECONDS`], that run processes it again when it's done, so a render that finished +/// during it isn't missed. +/// +/// # Errors +/// On a database or queue error. +pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> laravel::Result<()> { + use laravel::time::ToSpan; + let id = build_id; + // Charge what the build has used so far ([`charge`] is its own short transaction): the organization's row is + // locked only while it's charged, and what's charged stays charged if the run fails. + let build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(()); + } + Box::pin(charge(&build)).await?; + // Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any transaction, + // so billing's listeners (an automatic reload charges the card) run on committed data. + let build = stop_if_out_of_credits(Build::find_or_fail(id).await?).await?; + if build.state == "failed" { + drop_unneeded_renders(id).await?; + return finished(id, build.project_id).await; + } + let work = move || async move { + let build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(false); + } + // Boxed: processing's future is large, and the lock's own future holds it. + Box::pin(process(build, store, renderer_version)).await + }; + let busy = |r: &laravel::Result| matches!(r, Err(e) if e.is::()); + let mut result = Box::pin(exclusive(id, JOB_WAIT_SECONDS, work)).await; + 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?; + result = Box::pin(exclusive(id, 0, work)).await; + } + match result { + Ok(true) => finished(id, build.project_id).await?, + Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"), + 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) => { + tracing::error!(build_id = id, error = %e, "processing a build failed"); + let error = Some(e.to_string()); + if let Some(mut build) = Build::find(id).await? { + update!(build { state: "failed", error }).await?; + } + crate::events::BuildChanged { build_id: id }.dispatch().await?; + } + } + Ok(()) +} + +/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. +async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { + if let Some(project) = Project::find(project_id).await? { + crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await?; + } + crate::events::BuildChanged { build_id }.dispatch().await?; + Ok(()) +} + /// A document's base, drawn the way the head is drawn. enum Redraw { Ready(Box), @@ -148,7 +256,10 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result { } /// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done, -/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). +/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). The caller holds +/// [`exclusive`]; this runs outside any transaction, so storage requests, decoding and diffing never hold a database +/// connection or a row lock (blob rows above all, which uploads register). Per-snapshot results commit as they go and +/// are safe to write again (a run killed part-way is run again); the conclusion is one short transaction at the end. /// /// # Errors /// On a database or storage error. @@ -245,7 +356,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> continue; } let key = (snapshot.name.clone(), snapshot.platform.clone()); - match compare(&mut snapshot, store, &settings, base_snapshots.get(&key)).await { + match Box::pin(compare(&mut snapshot, store, &settings, base_snapshots.get(&key))).await { Ok(()) => set_baseline_id(&mut snapshot, baseline_rows.get(&key).copied()).await?, Err(e) => { tracing::warn!(build = id, snapshot = snapshot.id, error = %e, "comparing a snapshot failed"); @@ -296,7 +407,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } for key in keys { let Some(base) = base_snapshots.get(key) else { continue }; - carry_forward(&build, &settings, store, base).await?; + Box::pin(carry_forward(&build, &settings, store, base)).await?; } } for (name, platform) in &removed { @@ -364,29 +475,41 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } let has_base = !base_snapshots.is_empty(); - // What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and whether - // it sent anything (an empty build fails). - charge(&build).await?; - let sent: i64 = db::query!( - "SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \ - AND platform <> 'visualci'" - ) - .scalar() - .await? - .unwrap_or(0); - groups::source_unchanged(&build).await?; - - let mut build = build; let warnings = serde_json::json!(warnings); - update!(build { warnings }).await?; - let build = conclude(build, base_build_id, has_base, sent).await?; - if build.review_state == "auto_approved" { - // Nothing to review (or the project's first build): its changes are the baselines now. - let all = super::snapshots::of_build(build.id).await?; - let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect(); - baselines::record(&build, &changes, None, None, "auto").await?; - } - Ok(true) + + // The conclusion, in one short transaction of database work only, under the build's advisory lock (a review takes + // it too): still processing (another run may have concluded it), it's charged, its unchanged groups are read from + // the builds that hold them, and it's concluded, all or nothing. + Box::pin(db::transaction(async |_| { + lock(id).await?; + let mut build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(build.state == "completed"); + } + // What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and + // whether it sent anything (an empty build fails). The build's advisory lock is held already. + Box::pin(charge_locked(&build)).await?; + let sent: i64 = db::query!( + "SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \ + AND platform <> 'visualci'" + ) + .scalar() + .await? + .unwrap_or(0); + groups::source_unchanged(&build).await?; + + let warnings = warnings.clone(); + update!(build { warnings }).await?; + let build = conclude(build, base_build_id, has_base, sent).await?; + if build.review_state == "auto_approved" { + // Nothing to review (or the project's first build): its changes are the baselines now. + let all = super::snapshots::of_build(build.id).await?; + let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect(); + baselines::record(&build, &changes, None, None, "auto").await?; + } + Ok(true) + })) + .await } /// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged). @@ -413,7 +536,8 @@ async fn carry_forward( base.ignore_anti_aliasing, &base.meta, ); - // A second run of this processing (the job retried, or run twice at once) finds the row there already. + // A second run of this processing (the job retried after a run that stopped part-way) finds the row there + // already: it compares it again only when that run stopped before comparing it. let inserted = db::query!( "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \ render_id, engine, ignore_rules, environment, threshold, ignore_anti_aliasing, meta, state, carried_forward) \ @@ -424,14 +548,14 @@ async fn carry_forward( .insert() .await? .rows_affected(); - if inserted == 0 { - return Ok(()); - } let mut carried = Snapshot::query() .filter(Snapshot::build_id.eq(id) & Snapshot::name.eq(name.as_str()) & Snapshot::platform.eq(platform.as_str())) .first() .await? .ok_or_else(|| laravel::Error::msg("the carried snapshot wasn't saved"))?; + if inserted == 0 && !(carried.carried_forward && carried.state == "pending") { + return Ok(()); + } if let Err(e) = compare(&mut carried, store, settings, Some(base)).await { tracing::warn!(build = id, snapshot = carried.id, error = %e, "carrying a snapshot forward failed"); mark_failed(&mut carried, &format!("comparison failed: {e}")).await?; @@ -516,6 +640,16 @@ pub async fn recount(mut build: Build) -> laravel::Result { /// # Errors /// On a database error. pub async fn charge(build: &Build) -> laravel::Result<()> { + // Its own short transaction under the build's advisory lock (a savepoint inside the conclusion's), so two charges + // of one build (a run's, an early comparison's) never both charge the same delta. + db::transaction(async |_| { + lock(build.id).await?; + charge_locked(build).await + }) + .await +} + +async fn charge_locked(build: &Build) -> laravel::Result<()> { let project = Project::find_or_fail(build.project_id).await?; let mut fresh = Build::find_or_fail(build.id).await?; let charged: Usage = serde_json::from_value(fresh.charged.clone()).unwrap_or_default(); diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index a0b33441..ab0e40e8 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -314,6 +314,10 @@ struct CompareTarget { platform: String, } +/// How long an early comparison waits for another one of the same build (a local run's parallel tests) or its +/// processing, before it answers 409 to be asked again. +const COMPARE_WAIT_SECONDS: i64 = 20; + /// `POST /api/v1/builds/{pid}/compare`: compare some snapshots of a build that's still receiving, for a local run that /// checks each test as it goes. Each comes back with its state: `pending` while its file is missing or its PDF is /// rendering (ask again), `unchanged`, `changed`, `added`, `ignored` or `failed`. @@ -332,12 +336,20 @@ pub async fn compare( } let wanted: Vec<(String, String)> = params.snapshots.into_iter().map(|t| (t.name, t.platform)).collect(); let version = renderer_version(); - let compared = laravel::db::transaction(async |_| { - crate::domain::processing::lock(build.id).await?; + // Under the build's processing lock and outside any transaction: the comparisons' downloads and diffs hold + // no database connection or row locks (uploads register the same blobs meanwhile). + let compared = crate::domain::processing::exclusive(build.id, COMPARE_WAIT_SECONDS, || async { let build = Build::find_or_fail(build.id).await?; crate::domain::processing::compare_now(&build, &store, &version, &wanted).await }) - .await? + .await + .map_err(|e| { + if e.is::() { + ApiError::conflict("the build is busy comparing other snapshots; ask again in a few seconds") + } else { + e.into() + } + })? .map_err(ApiError::bad_request)?; let missing: Vec<&str> = wanted .iter() diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs index 2204c575..4fd28de7 100644 --- a/app/src/jobs/process_build.rs +++ b/app/src/jobs/process_build.rs @@ -2,12 +2,9 @@ //! when a build's last shard finalizes, and again whenever a render it waits on finishes: dispatches for one build //! within a few seconds run once (a build of 1,000 PDFs finishing its renders together is one run, not 1,000). -use laravel::db; use laravel::queue::{Queueable, job}; use crate::domain::processing; -use crate::events::{BuildChanged, CreditsSpent}; -use crate::models::Build; use crate::storage::BlobStore; #[derive(Queueable)] @@ -15,69 +12,18 @@ pub struct ProcessBuild { pub build_id: i64, } -#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds())] +// 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())] impl ProcessBuild { fn debounce_id(&self) -> i64 { self.build_id } async fn handle(self) -> laravel::Result<()> { - let id = self.build_id; let store = BlobStore::current().await?; let version = crate::http::api::builds::renderer_version(); - // Charge what the build has used so far in a short transaction of its own: the organization's row is locked - // only while it's charged, never for a whole run, and what's charged stays charged if the run fails. - let charged = db::transaction(async |_| { - processing::lock(id).await?; - let build = Build::find_or_fail(id).await?; - if build.state == "processing" { - processing::charge(&build).await?; - } - Ok(build) - }) - .await?; - if charged.state != "processing" { - return Ok(()); - } - // Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any - // transaction, so billing's listeners (an automatic reload charges the card) run on committed data. - let build = processing::stop_if_out_of_credits(charged).await?; - if build.state == "failed" { - processing::drop_unneeded_renders(id).await?; - finished(id, build.project_id).await?; - return Ok(()); - } - // One run at a time per build (the advisory lock), all its comparison writes together. - let result = db::transaction(async |_| { - processing::lock(id).await?; - let build = Build::find_or_fail(id).await?; - if build.state != "processing" { - return Ok(false); - } - processing::process(build, &store, &version).await - }) - .await; - match result { - Ok(true) => finished(id, build.project_id).await?, - Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"), - Err(e) => { - tracing::error!(build_id = id, error = %e, "processing a build failed"); - let error = Some(e.to_string()); - if let Some(mut build) = Build::find(id).await? { - laravel::model::update!(build { state: "failed", error }).await?; - } - BuildChanged { build_id: id }.dispatch().await?; - } - } - Ok(()) + // Boxed: a sync queue (tests) runs this inside the request that dispatched it. + Box::pin(processing::run(self.build_id, &store, &version)).await } } - -/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. -async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { - if let Some(project) = crate::models::Project::find(project_id).await? { - CreditsSpent { organization_id: project.organization_id }.dispatch().await?; - } - BuildChanged { build_id }.dispatch().await?; - Ok(()) -} diff --git a/app/tests/processing.rs b/app/tests/processing.rs index 37857da5..bb3e5e3e 100644 --- a/app/tests/processing.rs +++ b/app/tests/processing.rs @@ -244,3 +244,63 @@ async fn a_build_whose_manifest_matches_writes_no_snapshots_and_is_charged_one_g assert_eq!(charges(2).await?, vec![-1], "one credit: the manifest's group check"); Ok(()) } + +/// Production, 3 Dec 2026: a build's processing held one transaction for the whole run, storage requests and diffs +/// included, and the blob rows it wrote stayed locked: an upload registering one of those blobs waited 30 seconds and +/// failed. While processing waits on the store (here a store that never answers), an upload registering one of its +/// blobs goes ahead. +#[laravel::test] +async fn an_upload_registering_a_blob_does_not_wait_for_a_build_processing_it(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "c1", "branch": "main", "parent_commits": ["c0"] })) + .await; + created.assert_ok(); + let pid = created.json()["id"].as_str().unwrap().to_string(); + // A screenshot registered and never uploaded: processing asks the store whether it arrived. + let bytes = png([255, 0, 0]); + let (sha, size) = (visualci_core::sha256_hex(&bytes), i64::try_from(bytes.len()).unwrap()); + let image = image::load_from_memory(&bytes).unwrap().to_rgba8(); + app.post(format!("/api/v1/builds/{pid}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "home/hero/desktop.png", "kind": "image", + "fingerprint": visualci_core::image_hash::fingerprint_rgba(&image), + "sha256": sha, "size": size, "content_type": "image/png" + }] })) + .await + .assert_ok(); + db::query!("UPDATE builds SET state = 'processing' WHERE pid::text = {pid}").update().await?; + let build = Build::query().filter(Build::number.eq(1)).first().await?.expect("the build"); + + // A store that accepts connections and never answers. + let silent = std::net::TcpListener::bind("127.0.0.1:0").expect("a local port"); + let stalled = app::storage::BlobStore::new(&app::config::Storage { + endpoint: format!("http://{}", silent.local_addr().expect("its address")), + public_endpoint: None, + bucket: "visualci".into(), + region: "auto".into(), + access_key_id: "visualci".into(), + secret_access_key: "visualci-dev-secret".into(), + })?; + + let mut processing = Box::pin(app::domain::processing::run(build.id, &stalled, "test")); + let upload = async { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + tokio::time::timeout(std::time::Duration::from_secs(2), app::domain::blobs::register(&sha, size, "image/png")) + .await + }; + let registered = tokio::select! { + ran = &mut processing => panic!("processing finished without waiting on the store: {ran:?}"), + registered = upload => registered, + }; + // Stop the run that's still waiting on the store: it releases the build. + drop(processing); + let blob = registered.expect("registering the blob waited for processing")?; + assert_eq!(blob.sha256, sha); + Ok(()) +} diff --git a/docs/design-storage.md b/docs/design-storage.md index a1efc3c6..10dc9b76 100644 --- a/docs/design-storage.md +++ b/docs/design-storage.md @@ -269,6 +269,12 @@ 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 + 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. - 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.