From f2d6a67a407556bd0bf2f7242bfa6973e7b6358c Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 12:20:08 +0000 Subject: [PATCH] Processing: smaller stack frames, so tests run at the default stack (no RUST_MIN_STACK) A debug build gives every temporary of an async fn its own slot in its poll's stack frame, a future it boxes at once included: `process` was one ~270 KB frame and `run` ~130 KB. Tests run queued jobs inline (a sync queue), so builds are processed inside the request that finalized them and inside each other, and the deepest tests needed up to 2080 KB, past the test threads' 2 MB. - `process` is now steps of their own (prepare, confirm, find_bases, compare_all, fill_in, warnings_of, settle), and `run` too (charge_before_run, process_exclusively, after_run). - `domain::boxed(|| step(..))` builds a step's future in a frame of its own, so the caller's frame holds a pointer. Used for those steps, `exclusive`, the conclusion's calls, carry-forward's compare, and finalize's dispatches and adopt. - .cargo/config.toml's `[env] RUST_MIN_STACK` is gone. The deepest test now needs 1576 KB; the whole suite passes at 1664 KB. --- .cargo/config.toml | 8 - app/src/domain/mod.rs | 11 ++ app/src/domain/processing.rs | 304 ++++++++++++++++++++++++----------- app/src/http/api/builds.rs | 20 ++- 4 files changed, 238 insertions(+), 105 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index f124eea45..b0620be38 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -2,11 +2,3 @@ # build has no randomness without JavaScript glue. Fingerprints and diffs never use it, so it's left unsupported. [target.wasm32-unknown-unknown] rustflags = ['--cfg', 'getrandom_backend="unsupported"'] - -# Tests run queued jobs and event listeners inline (a sync queue), so a build's processing can process another build -# inside it (a merge commit's build woken when the pull request's head build concludes). A debug build's `process` -# keeps a large frame on the stack (about 0.5 MB per nested run): the deepest test needs about 2.5 MB, past the 2 MB -# test threads get by default. Keep this tight, so a new deep stack still fails here. Release builds use far smaller -# frames, and production runs each job on its own. -[env] -RUST_MIN_STACK = "4194304" diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 8c2acc96d..bc6a8ac6c 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -35,3 +35,14 @@ pub mod reviews; pub mod shutdown; pub mod snapshots; pub mod summary; + +/// `Box::pin(make())`, with the future built in this function's stack frame rather than the caller's. +/// +/// A debug build gives every temporary of an async fn its own slot in its poll's stack frame, a future it boxes at once +/// included, so an async fn that awaits many steps has a frame the size of all of them. Built here, the caller's frame +/// holds a pointer. Tests run queued jobs and event listeners inline (a sync queue), so a build's processing runs inside +/// the request that finalized it, and a merge commit's build inside its pull request's (`processing::finished`): use +/// this for the steps on that path, which overflowed the test threads' 2 MB stacks when they were built in place. +pub fn boxed(make: impl FnOnce() -> F) -> std::pin::Pin> { + Box::pin(make()) +} diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs index 2543ce093..bc6fb2b4f 100644 --- a/app/src/domain/processing.rs +++ b/app/src/domain/processing.rs @@ -8,6 +8,7 @@ use laravel::model::update; use visualci_core::manifest::{self, Entry}; use super::baselines::{self, Resolved}; +use super::boxed; use super::build_settings::{BuildSettings, CONFIG_INVALID, ConfigInvalid, Source}; use super::builds::{ CREDITS_PER_GROUP_CHECK, CREDITS_PER_IMAGE_DIFF, CREDITS_PER_RENDERED_PAGE, CREDITS_PER_SNAPSHOT_CHECK, @@ -117,7 +118,7 @@ where 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 + boxed(|| 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. @@ -186,52 +187,75 @@ where /// 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. /// +/// Its steps are built in frames of their own ([`boxed`]), as [`process`]'s are: a sync queue (tests) runs the builds +/// it starts (a previous build it adopts, the merge commit builds `finished` wakes) inside this one, so its frame is +/// on the stack once per nested run. +/// /// # 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" { + let Some(build) = boxed(|| charge_before_run(id)).await? else { 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; + boxed(|| drop_unneeded_renders(id)).await?; + return boxed(|| finished(id, build.project_id)).await; } // A subset build whose branch's previous build of the suite went quiet while this one waited finalizes it now // (sc-9763), outside the build's lock: that build's processing may run at once, and its result reaches this one. - if let Some(adopted) = Box::pin(super::reruns::adopt_on_branch(&build)).await? { - Box::pin(super::reruns::start(id, adopted)).await?; + if let Some(adopted) = boxed(|| super::reruns::adopt_on_branch(&build)).await? { + boxed(|| super::reruns::start(id, adopted)).await?; + } + let result = boxed(|| process_exclusively(id, store, renderer_version)).await; + boxed(|| after_run(id, build.project_id, result)).await +} + +/// [`run`]'s first step: charge what the build has used so far ([`charge`] is its own short transaction), so the +/// organization's row is locked only while it's charged, and what's charged stays charged if the run fails. Then stop it +/// when its organization is out of credits. `None` when the build isn't processing. +async fn charge_before_run(id: i64) -> laravel::Result> { + let build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(None); } + 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. + Ok(Some(stop_if_out_of_credits(Build::find_or_fail(id).await?).await?)) +} + +/// [`process`] the build under [`exclusive`]: whether it concluded. When another run holds it, leave a note and try +/// once more. +async fn process_exclusively(id: i64, store: &BlobStore, renderer_version: &str) -> laravel::Result { + use laravel::time::ToSpan; 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 + boxed(|| 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; + let mut result = boxed(|| 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, AGAIN_MINUTES.minutes()).await?; - result = Box::pin(exclusive(id, 0, work)).await; + result = boxed(|| exclusive(id, 0, work)).await; } + result +} + +/// [`run`]'s last step, on how processing went: finish a concluded build, queue again one a shutdown stopped, and fail +/// one that failed. +async fn after_run(id: i64, project_id: i64, result: laravel::Result) -> laravel::Result<()> { match result { - Ok(true) => finished(id, build.project_id).await?, + Ok(true) => boxed(|| finished(id, project_id)).await?, Ok(false) => { tracing::debug!(build_id = id, "build waiting for renders, or a merged pull request's build"); // Some of its snapshots may have been compared: its page shows the progress - crate::live::tell(build.project_id, Some(id)).await; + crate::live::tell(project_id, Some(id)).await; } Err(e) if e.is::() => { tracing::info!(build_id = id, "another run is processing the build; it runs it again when it's done"); @@ -755,9 +779,13 @@ async fn fill_document_fingerprint(snapshot: &mut Snapshot) -> laravel::Result<( /// 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. /// +/// Its steps are async fns of their own, each boxed where it's called: keep them apart. A debug build gives every +/// temporary of an async fn its own stack slot, so this was one ~270 KB stack frame when it was one function, and a sync +/// queue (tests) nests runs (a merge commit's build is processed inside its pull request's, via `finished`), which +/// overflowed the test threads' 2 MB stacks. Split, only the running step's frame is on the stack. +/// /// # Errors /// On a database or storage error. -#[allow(clippy::too_many_lines)] pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> laravel::Result { if build.state != "processing" { return Ok(build.state == "completed"); @@ -766,33 +794,94 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> let settings = match BuildSettings::new(&project, &build) { Ok(s) => s, Err(invalid) => { - fail_for_config(build, &invalid).await?; + boxed(|| fail_for_config(build, &invalid)).await?; return Ok(true); } }; - let id = build.id; + let cx = &Steps { build: &build, settings: &settings, store, renderer_version }; + if let Some(done) = boxed(|| prepare(cx)).await? { + return Ok(done); + } + let Some(Confirmed { snapshots, started, fingerprints_ms }) = boxed(|| confirm(cx)).await? else { + return Ok(false); + }; + let Some(mut bases) = boxed(|| find_bases(cx, &snapshots)).await? else { + return Ok(false); + }; + let compare_started = std::time::Instant::now(); + let Some(seen) = boxed(|| compare_all(cx, snapshots, &bases)).await? else { + // Stopped part-way: out of credits. + return Ok(true); + }; + let compare_ms = compare_started.elapsed().as_millis(); + let finish_started = std::time::Instant::now(); + let unreviewed = boxed(|| fill_in(cx, &seen, &bases)).await?; + let warnings = boxed(|| warnings_of(cx, &mut bases, unreviewed.as_ref())).await?; + let base_build_id = bases.anchor.as_ref().map(|a| a.id); + let has_base = !bases.base_snapshots.is_empty(); + // It carried a change from the branch's previous build, which never finished: it waits for a review. + let hold = unreviewed.as_ref().is_some_and(|u| u.unfinished.is_some()) || bases.merge.hold; + let concluded = boxed(|| settle(build.id, &project.default_branch, base_build_id, has_base, hold, warnings)).await; + // Where a slow run's time went: uploads and fingerprints, comparing, and the rest up to the conclusion. + tracing::info!( + build = build.id, + snapshots = seen.len(), + fingerprints_ms, + compare_ms, + finish_ms = finish_started.elapsed().as_millis(), + total_ms = started.elapsed().as_millis(), + "processed a build" + ); + concluded +} + +/// What every step of [`process`] works on. +struct Steps<'a> { + build: &'a Build, + settings: &'a BuildSettings<'a>, + store: &'a BlobStore, + renderer_version: &'a str, +} + +/// [`process`]'s first step: `Some` when the build is done with for now (whether it concluded), before any snapshot is +/// looked at. +async fn prepare(cx: &Steps<'_>) -> laravel::Result> { + let (build, id) = (cx.build, cx.build.id); // Its bundle uploads (sc-8868): wait while one is being unpacked (the unpacking runs the build again), and fail // with the reason when one was refused. match super::bundles::readiness(id).await? { super::bundles::Readiness::Ready => {} - super::bundles::Readiness::Waiting => return Ok(false), + super::bundles::Readiness::Waiting => return Ok(Some(false)), super::bundles::Readiness::Refused(error) => { - fail_for_bundle(build, error).await?; - return Ok(true); + fail_for_bundle(build.clone(), error).await?; + return Ok(Some(true)); } } // The "visualci.yml" item is worked out again below. db::query!("DELETE FROM snapshots WHERE build_id = {id} AND platform = 'visualci'").delete().await?; // A CI build sent nothing, on a commit an earlier build of its suite compared (a rerun of only the failed jobs): // it shows that build's result rather than failing as empty. - if let Some(done) = Box::pin(super::reruns::follow(&build)).await? { - return Ok(done); + if let Some(done) = Box::pin(super::reruns::follow(build)).await? { + return Ok(Some(done)); } // A subset build waits for the branch's previous build of its suite to conclude: its rows say which snapshots this // build didn't send still carry an unreviewed change (sc-9763). - if super::reruns::waits_for_previous(&build).await? { - return Ok(false); + if super::reruns::waits_for_previous(build).await? { + return Ok(Some(false)); } + Ok(None) +} + +/// The build's snapshots with their uploads confirmed and their renders done ([`confirm`]). +struct Confirmed { + snapshots: Vec, + started: std::time::Instant, + fingerprints_ms: u128, +} + +/// Confirm the uploads the build needs and queue its renders: `None` while a render is outstanding. +async fn confirm(cx: &Steps<'_>) -> laravel::Result> { + let id = cx.build.id; let mut snapshots: Vec = Snapshot::query() .filter(Snapshot::build_id.eq(id)) .order_by(Snapshot::name.asc()) @@ -807,8 +896,8 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> .filter_map(|s| s.source_blob.clone()) .collect(); let started = std::time::Instant::now(); - let missing = super::blobs::confirm_uploads(store, &needed).await?; - fill_image_fingerprints(&mut snapshots, &missing, store).await?; + let missing = super::blobs::confirm_uploads(cx.store, &needed).await?; + fill_image_fingerprints(&mut snapshots, &missing, cx.store).await?; let fingerprints_ms = started.elapsed().as_millis(); let mut waiting = false; @@ -823,8 +912,8 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> mark_failed(snapshot, "the PDF was never uploaded").await?; continue; } - let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); - let render = queue_render(project.id, &key, snapshot).await?; + let key = cx.settings.renderer_key(snapshot.engine.as_deref(), cx.renderer_version); + let render = queue_render(cx.settings.project.id, &key, snapshot).await?; let render_id = Some(render.id); update!(snapshot { render_id }).await?; } @@ -841,13 +930,28 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> mark_failed(snapshot, "the file was never uploaded").await?; } } - if waiting { - return Ok(false); - } + Ok((!waiting).then_some(Confirmed { snapshots, started, fingerprints_ms })) +} + +/// What the build is compared with ([`find_bases`]). +struct Bases { + /// The anchor build ("compared with #N"). + anchor: Option, + /// Each snapshot's baseline row. + baseline_rows: HashMap, + /// Each snapshot's base as resolved, before it was drawn again. + originals: HashMap, + /// Each snapshot's base, drawn the way the head is. + base_snapshots: HashMap, + carry: groups::Carry, + merge: FromMerges, +} - // Each snapshot's own baseline, and the anchor build ("compared with #N"). - let (resolved, anchor) = baselines::resolve(&build, &project).await?; - let base_build_id = anchor.as_ref().map(|a| a.id); +/// Each snapshot's own baseline, the anchor build, and what the pull requests merged at this commit bring: `None` while +/// a base is being drawn again, or a merged pull request's build is still running. +async fn find_bases(cx: &Steps<'_>, snapshots: &[Snapshot]) -> laravel::Result> { + let (build, settings, id) = (cx.build, cx.settings, cx.build.id); + let (resolved, anchor) = boxed(|| baselines::resolve(build, settings.project)).await?; let baseline_rows: HashMap<(String, String), i64> = resolved.iter().filter_map(|(k, r)| r.row.as_ref().map(|row| (k.clone(), row.id))).collect(); let originals: HashMap<(String, String), Snapshot> = @@ -855,10 +959,11 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> let mut base_snapshots: HashMap<(String, String), Snapshot> = resolved.into_iter().map(|(key, r)| (key, r.snapshot)).collect(); + let mut waiting = false; for snapshot in snapshots.iter().filter(|s| s.state != "failed") { let key = (snapshot.name.clone(), snapshot.platform.clone()); if let Some(base) = base_snapshots.get(&key) { - match redraw_base(&settings, renderer_version, snapshot, base).await? { + match redraw_base(settings, cx.renderer_version, snapshot, base).await? { Redraw::Ready(b) => { base_snapshots.insert(key, *b); } @@ -869,16 +974,15 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> // What the build didn't send: a subset build (CI skipped the jobs whose inputs didn't change) and the groups that // matched their baselines carry it forward unchanged, save what a pull request merged at this commit changed // without a review ([`from_merges`]); anything else was removed. - let carry = groups::carry(&build).await?; - let grouping = groups::grouping(build.group_depth); + let carry = groups::carry(build).await?; let sent: HashSet = snapshots.iter().map(|s| (s.name.clone(), s.platform.clone())).collect(); - let mut merge = Box::pin(from_merges(&build, &carry, &sent, &base_snapshots)).await?; + let mut merge = boxed(|| from_merges(build, &carry, &sent, &base_snapshots)).await?; if merge.waiting { - return Ok(false); + return Ok(None); } for (key, theirs) in &merge.carried { if let Some(base) = base_snapshots.get(key) { - match redraw_like(&settings, id, theirs, base).await? { + match redraw_like(settings, id, theirs, base).await? { Redraw::Ready(b) => { merge.bases.insert(key.clone(), *b); } @@ -886,11 +990,13 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } } } - if waiting { - return Ok(false); - } + Ok((!waiting).then_some(Bases { anchor, baseline_rows, originals, base_snapshots, carry, merge })) +} - let compare_started = std::time::Instant::now(); +/// Compare each snapshot the build sent with its base. Returns the keys it saw, or `None` when the organization ran +/// out of credits part-way and the build stopped. +async fn compare_all(cx: &Steps<'_>, snapshots: Vec, bases: &Bases) -> laravel::Result>> { + let (id, base_snapshots) = (cx.build.id, &bases.base_snapshots); let mut seen = HashSet::new(); let page_counts = document_page_counts(id).await?; let (mut compared, mut next_check) = (0usize, CREDIT_CHECK_EVERY); @@ -918,23 +1024,33 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> compared += page_counts.get(&snapshot.id).copied().unwrap_or(1).max(1); if compared >= next_check { next_check = compared + CREDIT_CHECK_EVERY; - if Box::pin(stop_part_way(&build)).await? { - return Ok(true); + if boxed(|| stop_part_way(cx.build)).await? { + return Ok(None); } } let key = (snapshot.name.clone(), snapshot.platform.clone()); - 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?, + match boxed(|| compare(&mut snapshot, cx.store, cx.settings, base_snapshots.get(&key))).await { + Ok(()) => set_baseline_id(&mut snapshot, bases.baseline_rows.get(&key).copied()).await?, Err(e) => { tracing::warn!(build = id, snapshot = snapshot.id, error = %e, "comparing a snapshot failed"); mark_failed(&mut snapshot, &format!("comparison failed: {e}")).await?; } } } + Ok(Some(seen)) +} - let compare_ms = compare_started.elapsed().as_millis(); - let finish_started = std::time::Instant::now(); - +/// After comparing: carry forward or source what the build didn't send, and record what it removed. Returns what it +/// carried from the branch's previous build without a review (sc-9763), for the warnings and the conclusion. +#[allow(clippy::too_many_lines)] +async fn fill_in( + cx: &Steps<'_>, + seen: &HashSet, + bases: &Bases, +) -> laravel::Result> { + let (build, settings, store, id) = (cx.build, cx.settings, cx.store, cx.build.id); + let grouping = groups::grouping(build.group_depth); + let Bases { baseline_rows, originals, base_snapshots, carry, merge, .. } = bases; let sent_keys: HashSet = seen.iter().map(|(name, _)| grouping.key(name)).collect(); let mut carried: BTreeMap> = BTreeMap::new(); let mut removed: Vec<(String, String)> = Vec::new(); @@ -952,7 +1068,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } // A subset build's skipped snapshots that the branch's previous build changed or added without an approval carry // that version, compared with the baseline, rather than the baseline itself: it still needs a review (sc-9763). - let mut unreviewed = super::reruns::unreviewed_carry(&build, &seen, &carry).await?; + let mut unreviewed = super::reruns::unreviewed_carry(build, seen, carry).await?; // At a merge commit, what a merged pull request's build covered stands as the pull request's head left it (even // when that's the baseline its approval made), not as the branch's older unreviewed version, nor its rejection. if let Some(u) = unreviewed.as_mut() { @@ -1026,10 +1142,10 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> let theirs = from_branch.and_then(|rows| rows.get(key)).filter(|s| s.state != "removed"); let Some(source) = merge.carried.get(key).or(theirs).or(base) else { continue }; let compared_with = merge.bases.get(key).or(base); - Box::pin(carry_forward(&build, &settings, store, source, compared_with)).await?; + boxed(|| carry_forward(build, settings, store, source, compared_with)).await?; } } - Box::pin(approve_merged(&build, &merge)).await?; + boxed(|| approve_merged(build, merge)).await?; for (name, platform) in &removed { let Some(base) = base_snapshots.get(&(name.clone(), platform.clone())) else { continue }; let pid = laravel::str::uuid7(); @@ -1052,17 +1168,27 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> if let Some(unreviewed) = &unreviewed { super::reruns::keep_rejections(id, unreviewed).await?; } + Ok(unreviewed) +} +/// The build's warnings, for its conclusion. +async fn warnings_of( + cx: &Steps<'_>, + bases: &mut Bases, + unreviewed: Option<&super::reruns::UnreviewedCarry>, +) -> laravel::Result { + let (build, settings, store, id) = (cx.build, cx.settings, cx.store, cx.build.id); + let project = settings.project; + let Bases { anchor, merge, .. } = bases; // The file's settings: a loosening ci_mode it can't use, ignore rules that matched nothing, and whether they hide // more than the base build's (then the build gets a "visualci.yml" item to review). let mut warnings = settings.config_warnings(); - if let Some(u) = unreviewed.as_ref().filter(|u| !u.rows.is_empty()) { + if let Some(u) = unreviewed.filter(|u| !u.rows.is_empty()) { warnings.push(super::reruns::unreviewed_carry_warning(u.rows.len(), u.number)); } - if let Some(number) = unreviewed.as_ref().and_then(|u| u.unfinished) { + if let Some(number) = unreviewed.and_then(|u| u.unfinished) { warnings.push(super::reruns::unfinished_previous_warning(number)); } - let hold = unreviewed.as_ref().is_some_and(|u| u.unfinished.is_some()); let rows = super::snapshots::of_build(id).await?; // What the merged pull requests brought that comes out as a change here, by the build it came from. for pr_build in &merge.builds { @@ -1095,17 +1221,17 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } // Compare the settings with the anchor's approved ones: when the anchor's own visualci.yml item wasn't approved, // with the settings that item was compared with. - if let Some(a) = &anchor { + if let Some(a) = anchor.as_ref() { let base = approved_settings_build(a.clone()).await?; // A base whose own file no longer validates can't say what it hid: compare with the project's settings, and // say so in the build's warnings. - let base_settings = BuildSettings::new(&project, &base).unwrap_or_else(|invalid| { + let base_settings = BuildSettings::new(project, &base).unwrap_or_else(|invalid| { warnings.push(format!( "Build #{}'s visualci.yml, which this build's settings are compared with, no longer validates ({}), \ so they were compared with the project's settings instead.", base.number, invalid.reason )); - BuildSettings::of_project(&project) + BuildSettings::of_project(project) }); if settings.hides_more_than(&base_settings) { let base_item = Snapshot::query() @@ -1125,7 +1251,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> // Changes made only of changes merged pull requests approved say so (a hint). A failure here costs the hint, never // the build. - if let Err(e) = super::matching::mark(store, &build).await { + if let Err(e) = super::matching::mark(store, build).await { tracing::warn!(build = id, error = %e, "matching approved changes"); } @@ -1136,14 +1262,21 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } // So does a build an empty rerun finalized. warnings.extend(earlier.iter().filter(|w| w.starts_with(super::reruns::ADOPTED_PREFIX)).cloned()); - let has_base = !base_snapshots.is_empty(); - - let warnings = serde_json::json!(warnings); + Ok(serde_json::json!(warnings)) +} - // 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. - let concluded = Box::pin(db::transaction(async |_| { +/// 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. Returns whether it concluded. +async fn settle( + id: i64, + default_branch: &str, + base_build_id: Option, + has_base: bool, + hold: bool, + warnings: serde_json::Value, +) -> laravel::Result { + Box::pin(db::transaction(async |_| { lock(id).await?; let mut build = Build::find_or_fail(id).await?; if build.state != "processing" { @@ -1151,7 +1284,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> } // 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?; + boxed(|| 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'" @@ -1165,27 +1298,16 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> let warnings = warnings.clone(); update!(build { warnings }).await?; - let build = conclude(build, &project.default_branch, base_build_id, has_base, sent, hold || merge.hold).await?; + let build = boxed(|| conclude(build, default_branch, base_build_id, has_base, sent, hold)).await?; if build.review_state == "auto_approved" { // Nothing to review (or the default branch'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?; + boxed(|| baselines::record(&build, &changes, None, None, "auto")).await?; } Ok(true) })) - .await; - // Where a slow run's time went: uploads and fingerprints, comparing, and the rest up to the conclusion. - tracing::info!( - build = id, - snapshots = seen.len(), - fingerprints_ms, - compare_ms, - finish_ms = finish_started.elapsed().as_millis(), - total_ms = started.elapsed().as_millis(), - "processed a build" - ); - concluded + .await } /// Carry a snapshot the build didn't send into it as its own row, compared with its base: the base itself (unchanged), @@ -1235,7 +1357,7 @@ async fn carry_forward( if inserted == 0 && !(carried.carried_forward && carried.state == "pending") { return Ok(()); } - if let Err(e) = compare(&mut carried, store, settings, base).await { + if let Err(e) = boxed(|| compare(&mut carried, store, settings, 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?; } diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 039d16ac9..777c99a78 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; use super::{ApiError, ApiProject, Body}; use crate::auth::{Principal, Via}; +use crate::domain::boxed; use crate::domain::build_settings::BuildSettings; use crate::domain::builds::{self as domain, CreateParams, Stats}; use crate::domain::snapshots::SnapshotParams; @@ -348,25 +349,32 @@ pub async fn finalize( }; let was_receiving = build.state == "receiving"; let allow_empty = params.allow_empty || params.empty_reason.is_some(); - let build = domain::finalize_shard(build, params.shard, allow_empty).await.map_err(ApiError::from)?; + // The steps that can process the build (a sync queue, in tests, runs it inside this request) are built in + // frames of their own ([`boxed`]), so this one stays small. + let build = + boxed(|| domain::finalize_shard(build, params.shard, allow_empty)).await.map_err(ApiError::from)?; let build = if was_receiving { - crate::domain::processing::stop_if_out_of_credits_without_reloading(build).await? + boxed(|| crate::domain::processing::stop_if_out_of_credits_without_reloading(build)).await? } else { build }; if was_receiving && build.state == "processing" { // An empty rerun whose suite's earlier build was never finalized, or a skipped build whose branch's // previous build was left unfinished, finalizes that build: it's processed first (`reruns::adopt`). - if let Some(adopted) = Box::pin(crate::domain::reruns::adopt(&build)).await? { + if let Some(adopted) = boxed(|| crate::domain::reruns::adopt(&build)).await? { if crate::domain::reruns::ready(build.id, adopted).await? { - crate::jobs::process_build::ProcessBuild { build_id: adopted }.dispatch().await?; + boxed(|| { + crate::jobs::process_build::ProcessBuild { build_id: adopted }.dispatch().into_future() + }) + .await?; } crate::domain::reruns::started(build.id).await?; } crate::live::tell(project.id, Some(build.id)).await; - crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await?; + boxed(|| crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().into_future()) + .await?; } else if was_receiving && build.state == "failed" { - crate::events::BuildChanged { build_id: build.id }.dispatch().await?; + boxed(|| crate::events::BuildChanged { build_id: build.id }.dispatch().into_future()).await?; } // The job may have run already (a synchronous queue): answer with the build as it is now. let build = Build::find(build.id).await?.unwrap_or(build);