Skip to content

Commit cd4bf50

Browse files
authored
app/: new images are fingerprinted 8 at a time, decoded off the runtime's threads and written back in batches; a finished render wakes only the builds waiting on it (incident 4 Dec 2026) (#171)
1 parent d33bc70 commit cd4bf50

9 files changed

Lines changed: 411 additions & 42 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎app/.env.example‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,14 @@ VISUALCI_STRIPE_WEBHOOK_SECRET=
348348
# Secret. The platform ranges check's token.
349349
# VISUALCI_PLATFORM_ADDRESSES_HEARTBEAT_TOKEN=
350350

351+
######################################################################################################################
352+
# Build processing
353+
######################################################################################################################
354+
355+
# How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a thread of
356+
# its own, off the threads that serve requests and keep locks alive.
357+
# VISUALCI_FINGERPRINT_CONCURRENCY=8
358+
351359
######################################################################################################################
352360
# Laravel Rust
353361
######################################################################################################################

‎app/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ laravel_cache = { package = "laravel-rust-cache", version = "=0.1.4", default-fe
2626
# The same axum Laravel Rust runs on, for extractors (auth::Principal)
2727
axum = "0.8"
2828
base64 = "0.22"
29+
# Bounded concurrent downloads (domain::blobs::fingerprint_files)
30+
futures-util = "0.3"
2931
hex = "0.4"
3032
oauth-provider = "0.1.4"
3133
oauth-provider-laravel = { version = "=0.1.2", features = ["postgres"] }

‎app/src/config.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ pub struct Config {
5050
pub limits: Limits,
5151
#[settings(nested)]
5252
pub heartbeats: Heartbeats,
53+
#[settings(nested)]
54+
pub processing: Processing,
5355
}
5456

5557
/// S3-compatible storage for uploads, rendered pages and diff images: R2 in production, RustFS or MinIO in
@@ -363,6 +365,16 @@ pub struct Limits {
363365
pub oauth_unused_clients_ceiling: i64,
364366
}
365367

368+
/// Processing builds (the worker).
369+
#[derive(Clone, Settings)]
370+
#[settings(title = "Build processing")]
371+
pub struct Processing {
372+
/// How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a
373+
/// thread of its own, off the threads that serve requests and keep locks alive.
374+
#[env("VISUALCI_FINGERPRINT_CONCURRENCY", default = 8)]
375+
pub fingerprint_concurrency: usize,
376+
}
377+
366378
/// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no
367379
/// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing.
368380
#[derive(Clone, Settings)]
@@ -592,6 +604,7 @@ pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env)
592604
.set(settings.live.clone())
593605
.set(settings.limits.clone())
594606
.set(settings.heartbeats.clone())
607+
.set(settings.processing.clone())
595608
.set(settings);
596609
}
597610

‎app/src/domain/blobs.rs‎

Lines changed: 114 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
//! Blob records: what's stored under each SHA-256, whether its bytes have arrived, and an image's size and pixel
22
//! fingerprint (cached on first use).
33
4+
use std::collections::HashMap;
5+
6+
use futures_util::stream::{self, StreamExt};
47
use laravel::db;
58
use laravel::model::update;
69

@@ -148,22 +151,119 @@ pub async fn put(store: &BlobStore, bytes: Vec<u8>, content_type: &str) -> larav
148151
Ok(blob)
149152
}
150153

154+
/// An image file's pixel fingerprint, width and height.
155+
pub type ImageInfo = (String, u32, u32);
156+
157+
/// Decode an image and fingerprint its pixels. CPU-bound, so it runs on the blocking pool ([`decode`]): it gets only
158+
/// the bytes, and calls nothing that needs the app's context (the database, the cache, `laravel::now()`).
159+
fn decode_image(sha256: &str, bytes: &[u8]) -> Result<ImageInfo, String> {
160+
let image = visualci_core::image_hash::decode(bytes).map_err(|e| format!("{sha256}: {e}"))?.to_rgba8();
161+
let fp = visualci_core::image_hash::fingerprint_rgba(&image);
162+
let (w, h) = image.dimensions();
163+
Ok((fp, w, h))
164+
}
165+
166+
/// [`decode_image`] off the async runtime's threads, so a large image (or hundreds of them) never stalls the other
167+
/// work on the runtime, such as the processing lock's heartbeat.
168+
async fn decode(sha256: String, bytes: Vec<u8>) -> Result<ImageInfo, String> {
169+
tokio::task::spawn_blocking(move || decode_image(&sha256, &bytes))
170+
.await
171+
.map_err(|e| format!("decoding the image stopped: {e}"))?
172+
}
173+
174+
/// Fingerprint image files: up to `concurrency` downloads (`fetch`) at a time, in the calling task, each file decoded
175+
/// on the blocking pool. Each file's fingerprint and size, or why it couldn't be read.
176+
pub async fn fingerprint_files<F, Fut>(
177+
shas: Vec<String>,
178+
concurrency: usize,
179+
fetch: F,
180+
) -> HashMap<String, Result<ImageInfo, String>>
181+
where
182+
F: Fn(String) -> Fut,
183+
Fut: Future<Output = laravel::Result<Vec<u8>>>,
184+
{
185+
stream::iter(shas)
186+
.map(|sha| {
187+
let fetched = fetch(sha.clone());
188+
async move {
189+
let info = match fetched.await {
190+
Ok(bytes) => decode(sha.clone(), bytes).await,
191+
Err(e) => Err(e.to_string()),
192+
};
193+
(sha, info)
194+
}
195+
})
196+
.buffer_unordered(concurrency.max(1))
197+
.collect()
198+
.await
199+
}
200+
201+
/// Each image blob's pixel fingerprint and size: the one on its row, or computed from the file
202+
/// ([`fingerprint_files`], `VISUALCI_FINGERPRINT_CONCURRENCY` at a time) and written to the rows in a few statements.
203+
/// A fingerprint already on a row stays (only a missing size is added).
204+
///
205+
/// # Errors
206+
/// On a database error. A file that can't be downloaded or decoded is its own `Err` in the map.
207+
pub async fn image_infos(
208+
blobs: Vec<Blob>,
209+
store: &BlobStore,
210+
) -> laravel::Result<HashMap<String, Result<ImageInfo, String>>> {
211+
let mut infos = HashMap::new();
212+
let mut known: HashMap<String, Option<String>> = HashMap::new();
213+
for blob in blobs {
214+
match (&blob.pixel_fingerprint, blob.width, blob.height) {
215+
(Some(fp), Some(w), Some(h)) => {
216+
infos.insert(blob.sha256.clone(), Ok((fp.clone(), dimension(w), dimension(h))));
217+
}
218+
_ => {
219+
known.insert(blob.sha256.clone(), blob.pixel_fingerprint.clone());
220+
}
221+
}
222+
}
223+
if known.is_empty() {
224+
return Ok(infos);
225+
}
226+
let concurrency = laravel::config().section::<crate::config::Processing>().fingerprint_concurrency;
227+
let shas: Vec<String> = known.keys().cloned().collect();
228+
let computed = fingerprint_files(shas, concurrency, |sha| async move { store.get(&sha).await }).await;
229+
let mut rows: Vec<(String, String, i32, i32)> = Vec::new();
230+
for (sha, info) in computed {
231+
let info = info.map(|(fp, w, h)| (known.get(&sha).cloned().flatten().unwrap_or(fp), w, h));
232+
if let Ok((fp, w, h)) = &info {
233+
rows.push((
234+
sha.clone(),
235+
fp.clone(),
236+
i32::try_from(*w).unwrap_or(i32::MAX),
237+
i32::try_from(*h).unwrap_or(i32::MAX),
238+
));
239+
}
240+
if let Err(e) = &info {
241+
tracing::warn!(blob = %sha, error = %e, "an image file couldn't be fingerprinted");
242+
}
243+
infos.insert(sha, info);
244+
}
245+
for chunk in rows.chunks(5_000) {
246+
db::query!(
247+
"UPDATE blobs b SET pixel_fingerprint = COALESCE(b.pixel_fingerprint, v.fingerprint), width = v.width, \
248+
height = v.height, updated_at = now() \
249+
FROM (VALUES {...chunk(0, 1, 2, 3)}) AS v (sha256, fingerprint, width, height) WHERE b.sha256 = v.sha256"
250+
)
251+
.update()
252+
.await?;
253+
}
254+
Ok(infos)
255+
}
256+
257+
fn dimension(n: i32) -> u32 {
258+
u32::try_from(n).unwrap_or(0)
259+
}
260+
151261
/// The image's pixel fingerprint and size, computed (and cached on the row) on first use.
152262
///
153263
/// # Errors
154264
/// When the blob is missing or isn't an image.
155-
pub async fn image_info(mut blob: Blob, store: &BlobStore) -> laravel::Result<(String, u32, u32)> {
156-
if let (Some(fp), Some(w), Some(h)) = (&blob.pixel_fingerprint, blob.width, blob.height) {
157-
return Ok((fp.clone(), u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0)));
158-
}
159-
let bytes = store.get(&blob.sha256).await?;
160-
let image = visualci_core::image_hash::decode(&bytes)
161-
.map_err(|e| laravel::Error::msg(format!("{}: {e}", blob.sha256)))?
162-
.to_rgba8();
163-
let fp = visualci_core::image_hash::fingerprint_rgba(&image);
164-
let (w, h) = image.dimensions();
165-
let pixel_fingerprint = Some(fp.clone());
166-
let (width, height) = (Some(i32::try_from(w).unwrap_or(i32::MAX)), Some(i32::try_from(h).unwrap_or(i32::MAX)));
167-
update!(blob { pixel_fingerprint, width, height }).await?;
168-
Ok((fp, w, h))
265+
pub async fn image_info(blob: Blob, store: &BlobStore) -> laravel::Result<ImageInfo> {
266+
let sha = blob.sha256.clone();
267+
let mut infos = image_infos(vec![blob], store).await?;
268+
infos.remove(&sha).unwrap_or_else(|| Err(format!("{sha}: not read"))).map_err(laravel::Error::msg)
169269
}

‎app/src/domain/processing.rs‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result<Build> {
331331
}
332332

333333
/// Images sent without a fingerprint (sc-8999) take their blob's pixel fingerprint before anything compares them,
334-
/// computed from the file (and kept on the blob, [`super::blobs::image_info`]) where the blob has none yet: a new file,
334+
/// computed from the file (and kept on the blob, [`super::blobs::image_infos`]) where the blob has none yet: a new file,
335335
/// or a re-encoded one with the same pixels, which stays its own blob under its own hash. Each file is decoded once,
336336
/// outside any transaction, and the snapshots are updated in one statement. A file that isn't an image fails its
337337
/// snapshots, as comparing it would.
@@ -356,17 +356,23 @@ async fn fill_image_fingerprints(
356356
shas.sort_unstable();
357357
shas.dedup();
358358
let mut found: HashMap<String, Result<String, String>> = HashMap::new();
359+
let mut unread = Vec::new();
359360
for chunk in shas.chunks(10_000) {
360361
for blob in crate::models::Blob::query().filter(crate::models::Blob::sha256.is_in(chunk.to_vec())).get().await?
361362
{
362-
let sha = blob.sha256.clone();
363-
let fingerprint = match blob.pixel_fingerprint.clone() {
364-
Some(fp) => Ok(fp),
365-
None => super::blobs::image_info(blob, store).await.map(|(fp, _, _)| fp).map_err(|e| e.to_string()),
366-
};
367-
found.insert(sha, fingerprint);
363+
match blob.pixel_fingerprint.clone() {
364+
Some(fp) => {
365+
found.insert(blob.sha256.clone(), Ok(fp));
366+
}
367+
None => unread.push(blob),
368+
}
368369
}
369370
}
371+
// New files are downloaded a few at a time and decoded off the runtime's threads (incident, 4 Dec 2026: one at a
372+
// time on the runtime, a new project's first build held the only worker for minutes).
373+
for (sha, info) in super::blobs::image_infos(unread, store).await? {
374+
found.insert(sha, info.map(|(fp, _, _)| fp));
375+
}
370376
let mut rows: Vec<(i64, String)> = Vec::new();
371377
for snapshot in snapshots.iter_mut().filter(|s| needs(s)) {
372378
match snapshot.source_blob.as_ref().and_then(|b| found.get(b)) {
@@ -458,8 +464,10 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
458464
.filter(|s| s.render_id.is_none() && s.state != "removed")
459465
.filter_map(|s| s.source_blob.clone())
460466
.collect();
467+
let started = std::time::Instant::now();
461468
let missing = super::blobs::confirm_uploads(store, &needed).await?;
462469
fill_image_fingerprints(&mut snapshots, &missing, store).await?;
470+
let fingerprints_ms = started.elapsed().as_millis();
463471

464472
let mut waiting = false;
465473
for snapshot in &mut snapshots {
@@ -520,6 +528,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
520528
return Ok(false);
521529
}
522530

531+
let compare_started = std::time::Instant::now();
523532
let mut seen = HashSet::new();
524533
for mut snapshot in snapshots {
525534
seen.insert((snapshot.name.clone(), snapshot.platform.clone()));
@@ -536,6 +545,9 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
536545
}
537546
}
538547

548+
let compare_ms = compare_started.elapsed().as_millis();
549+
let finish_started = std::time::Instant::now();
550+
539551
// What the build didn't send: a subset build (CI skipped the jobs whose inputs didn't change) and the groups that
540552
// matched their baselines carry it forward unchanged; anything else was removed.
541553
let carry = groups::carry(&build).await?;
@@ -660,7 +672,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
660672
// The conclusion, in one short transaction of database work only, under the build's advisory lock (a review takes
661673
// it too): still processing (another run may have concluded it), it's charged, its unchanged groups are read from
662674
// the builds that hold them, and it's concluded, all or nothing.
663-
Box::pin(db::transaction(async |_| {
675+
let concluded = Box::pin(db::transaction(async |_| {
664676
lock(id).await?;
665677
let mut build = Build::find_or_fail(id).await?;
666678
if build.state != "processing" {
@@ -689,7 +701,18 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
689701
}
690702
Ok(true)
691703
}))
692-
.await
704+
.await;
705+
// Where a slow run's time went: uploads and fingerprints, comparing, and the rest up to the conclusion.
706+
tracing::info!(
707+
build = id,
708+
snapshots = seen.len(),
709+
fingerprints_ms,
710+
compare_ms,
711+
finish_ms = finish_started.elapsed().as_millis(),
712+
total_ms = started.elapsed().as_millis(),
713+
"processed a build"
714+
);
715+
concluded
693716
}
694717

695718
/// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged).

‎app/src/domain/renders.rs‎

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -225,29 +225,27 @@ pub async fn fail_exhausted_claims() -> laravel::Result<Vec<Render>> {
225225
Ok(failed)
226226
}
227227

228-
/// Process again every build waiting on this render: renders are per project, so that's the project's processing builds
229-
/// (the ones whose snapshots use it, and the ones waiting for their base's PDF to be drawn again with their own
230-
/// renderer settings). Processing a build that's still waiting does nothing.
228+
/// Process again every build waiting on this render: the processing builds with a snapshot drawn by it, and, for a
229+
/// render drawing a base's PDF again with a head's renderer settings (`redraw_base` in processing), the project's
230+
/// processing builds with a document of the same name and platform as a snapshot of that file. Not every processing
231+
/// build in the project: on 4 Dec 2026 that queued `ProcessBuild` for each of them about three times a second.
232+
/// Processing a build that's still waiting does nothing.
231233
///
232234
/// # Errors
233235
/// On a database or queue error.
234236
pub async fn wake_waiting(render: &Render) -> laravel::Result<()> {
235-
let render_id = render.id;
236-
let rows = match render.project_id {
237-
Some(project_id) => {
238-
db::query!("SELECT id FROM builds WHERE project_id = {project_id} AND state = 'processing'")
239-
.select()
240-
.await?
241-
}
242-
None => {
243-
db::query!(
244-
"SELECT DISTINCT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \
245-
WHERE s.render_id = {render_id} AND b.state = 'processing'"
246-
)
247-
.select()
248-
.await?
249-
}
250-
};
237+
let (render_id, project_id, blob) = (render.id, render.project_id, render.source_blob.as_str());
238+
let rows = db::query!(
239+
"SELECT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \
240+
WHERE b.state = 'processing' AND s.render_id = {render_id} \
241+
UNION \
242+
SELECT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \
243+
WHERE b.state = 'processing' AND b.project_id = {project_id} AND s.kind = 'document' \
244+
AND (s.name, s.platform) IN ( \
245+
SELECT o.name, o.platform FROM snapshots o WHERE o.source_blob = {blob} AND o.kind = 'document')"
246+
)
247+
.select()
248+
.await?;
251249
for build_id in rows.iter().filter_map(|r| r.try_get::<i64>("id").ok()) {
252250
crate::jobs::process_build::ProcessBuild { build_id }.dispatch().await?;
253251
}

0 commit comments

Comments
 (0)