Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions app/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,14 @@ VISUALCI_STRIPE_WEBHOOK_SECRET=
# Secret. The platform ranges check's token.
# VISUALCI_PLATFORM_ADDRESSES_HEARTBEAT_TOKEN=

######################################################################################################################
# Build processing
######################################################################################################################

# How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a thread of
# its own, off the threads that serve requests and keep locks alive.
# VISUALCI_FINGERPRINT_CONCURRENCY=8

######################################################################################################################
# Laravel Rust
######################################################################################################################
Expand Down
2 changes: 2 additions & 0 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ laravel_cache = { package = "laravel-rust-cache", version = "=0.1.4", default-fe
# The same axum Laravel Rust runs on, for extractors (auth::Principal)
axum = "0.8"
base64 = "0.22"
# Bounded concurrent downloads (domain::blobs::fingerprint_files)
futures-util = "0.3"
hex = "0.4"
oauth-provider = "0.1.4"
oauth-provider-laravel = { version = "=0.1.2", features = ["postgres"] }
Expand Down
13 changes: 13 additions & 0 deletions app/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ pub struct Config {
pub limits: Limits,
#[settings(nested)]
pub heartbeats: Heartbeats,
#[settings(nested)]
pub processing: Processing,
}

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

/// Processing builds (the worker).
#[derive(Clone, Settings)]
#[settings(title = "Build processing")]
pub struct Processing {
/// How many new image files one build's processing downloads and fingerprints at once. Each is decoded on a
/// thread of its own, off the threads that serve requests and keep locks alive.
#[env("VISUALCI_FINGERPRINT_CONCURRENCY", default = 8)]
pub fingerprint_concurrency: usize,
}

/// Each scheduled job pushes its result to a [Gatus](https://gatus.io) external endpoint, so a run that failed, or no
/// run at all, alerts. Each pair is the endpoint's URL and its token; a job without a URL pushes nothing.
#[derive(Clone, Settings)]
Expand Down Expand Up @@ -592,6 +604,7 @@ pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env)
.set(settings.live.clone())
.set(settings.limits.clone())
.set(settings.heartbeats.clone())
.set(settings.processing.clone())
.set(settings);
}

Expand Down
128 changes: 114 additions & 14 deletions app/src/domain/blobs.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Blob records: what's stored under each SHA-256, whether its bytes have arrived, and an image's size and pixel
//! fingerprint (cached on first use).

use std::collections::HashMap;

use futures_util::stream::{self, StreamExt};
use laravel::db;
use laravel::model::update;

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

/// An image file's pixel fingerprint, width and height.
pub type ImageInfo = (String, u32, u32);

/// Decode an image and fingerprint its pixels. CPU-bound, so it runs on the blocking pool ([`decode`]): it gets only
/// the bytes, and calls nothing that needs the app's context (the database, the cache, `laravel::now()`).
fn decode_image(sha256: &str, bytes: &[u8]) -> Result<ImageInfo, String> {
let image = visualci_core::image_hash::decode(bytes).map_err(|e| format!("{sha256}: {e}"))?.to_rgba8();
let fp = visualci_core::image_hash::fingerprint_rgba(&image);
let (w, h) = image.dimensions();
Ok((fp, w, h))
}

/// [`decode_image`] off the async runtime's threads, so a large image (or hundreds of them) never stalls the other
/// work on the runtime, such as the processing lock's heartbeat.
async fn decode(sha256: String, bytes: Vec<u8>) -> Result<ImageInfo, String> {
tokio::task::spawn_blocking(move || decode_image(&sha256, &bytes))
.await
.map_err(|e| format!("decoding the image stopped: {e}"))?
}

/// Fingerprint image files: up to `concurrency` downloads (`fetch`) at a time, in the calling task, each file decoded
/// on the blocking pool. Each file's fingerprint and size, or why it couldn't be read.
pub async fn fingerprint_files<F, Fut>(
shas: Vec<String>,
concurrency: usize,
fetch: F,
) -> HashMap<String, Result<ImageInfo, String>>
where
F: Fn(String) -> Fut,
Fut: Future<Output = laravel::Result<Vec<u8>>>,
{
stream::iter(shas)
.map(|sha| {
let fetched = fetch(sha.clone());
async move {
let info = match fetched.await {
Ok(bytes) => decode(sha.clone(), bytes).await,
Err(e) => Err(e.to_string()),
};
(sha, info)
}
})
.buffer_unordered(concurrency.max(1))
.collect()
.await
}

/// Each image blob's pixel fingerprint and size: the one on its row, or computed from the file
/// ([`fingerprint_files`], `VISUALCI_FINGERPRINT_CONCURRENCY` at a time) and written to the rows in a few statements.
/// A fingerprint already on a row stays (only a missing size is added).
///
/// # Errors
/// On a database error. A file that can't be downloaded or decoded is its own `Err` in the map.
pub async fn image_infos(
blobs: Vec<Blob>,
store: &BlobStore,
) -> laravel::Result<HashMap<String, Result<ImageInfo, String>>> {
let mut infos = HashMap::new();
let mut known: HashMap<String, Option<String>> = HashMap::new();
for blob in blobs {
match (&blob.pixel_fingerprint, blob.width, blob.height) {
(Some(fp), Some(w), Some(h)) => {
infos.insert(blob.sha256.clone(), Ok((fp.clone(), dimension(w), dimension(h))));
}
_ => {
known.insert(blob.sha256.clone(), blob.pixel_fingerprint.clone());
}
}
}
if known.is_empty() {
return Ok(infos);
}
let concurrency = laravel::config().section::<crate::config::Processing>().fingerprint_concurrency;
let shas: Vec<String> = known.keys().cloned().collect();
let computed = fingerprint_files(shas, concurrency, |sha| async move { store.get(&sha).await }).await;
let mut rows: Vec<(String, String, i32, i32)> = Vec::new();
for (sha, info) in computed {
let info = info.map(|(fp, w, h)| (known.get(&sha).cloned().flatten().unwrap_or(fp), w, h));
if let Ok((fp, w, h)) = &info {
rows.push((
sha.clone(),
fp.clone(),
i32::try_from(*w).unwrap_or(i32::MAX),
i32::try_from(*h).unwrap_or(i32::MAX),
));
}
if let Err(e) = &info {
tracing::warn!(blob = %sha, error = %e, "an image file couldn't be fingerprinted");
}
infos.insert(sha, info);
}
for chunk in rows.chunks(5_000) {
db::query!(
"UPDATE blobs b SET pixel_fingerprint = COALESCE(b.pixel_fingerprint, v.fingerprint), width = v.width, \
height = v.height, updated_at = now() \
FROM (VALUES {...chunk(0, 1, 2, 3)}) AS v (sha256, fingerprint, width, height) WHERE b.sha256 = v.sha256"
)
.update()
.await?;
}
Ok(infos)
}

fn dimension(n: i32) -> u32 {
u32::try_from(n).unwrap_or(0)
}

/// The image's pixel fingerprint and size, computed (and cached on the row) on first use.
///
/// # Errors
/// When the blob is missing or isn't an image.
pub async fn image_info(mut blob: Blob, store: &BlobStore) -> laravel::Result<(String, u32, u32)> {
if let (Some(fp), Some(w), Some(h)) = (&blob.pixel_fingerprint, blob.width, blob.height) {
return Ok((fp.clone(), u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0)));
}
let bytes = store.get(&blob.sha256).await?;
let image = visualci_core::image_hash::decode(&bytes)
.map_err(|e| laravel::Error::msg(format!("{}: {e}", blob.sha256)))?
.to_rgba8();
let fp = visualci_core::image_hash::fingerprint_rgba(&image);
let (w, h) = image.dimensions();
let pixel_fingerprint = Some(fp.clone());
let (width, height) = (Some(i32::try_from(w).unwrap_or(i32::MAX)), Some(i32::try_from(h).unwrap_or(i32::MAX)));
update!(blob { pixel_fingerprint, width, height }).await?;
Ok((fp, w, h))
pub async fn image_info(blob: Blob, store: &BlobStore) -> laravel::Result<ImageInfo> {
let sha = blob.sha256.clone();
let mut infos = image_infos(vec![blob], store).await?;
infos.remove(&sha).unwrap_or_else(|| Err(format!("{sha}: not read"))).map_err(laravel::Error::msg)
}
41 changes: 32 additions & 9 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result<Build> {
}

/// Images sent without a fingerprint (sc-8999) take their blob's pixel fingerprint before anything compares them,
/// computed from the file (and kept on the blob, [`super::blobs::image_info`]) where the blob has none yet: a new file,
/// computed from the file (and kept on the blob, [`super::blobs::image_infos`]) where the blob has none yet: a new file,
/// or a re-encoded one with the same pixels, which stays its own blob under its own hash. Each file is decoded once,
/// outside any transaction, and the snapshots are updated in one statement. A file that isn't an image fails its
/// snapshots, as comparing it would.
Expand All @@ -356,17 +356,23 @@ async fn fill_image_fingerprints(
shas.sort_unstable();
shas.dedup();
let mut found: HashMap<String, Result<String, String>> = HashMap::new();
let mut unread = Vec::new();
for chunk in shas.chunks(10_000) {
for blob in crate::models::Blob::query().filter(crate::models::Blob::sha256.is_in(chunk.to_vec())).get().await?
{
let sha = blob.sha256.clone();
let fingerprint = match blob.pixel_fingerprint.clone() {
Some(fp) => Ok(fp),
None => super::blobs::image_info(blob, store).await.map(|(fp, _, _)| fp).map_err(|e| e.to_string()),
};
found.insert(sha, fingerprint);
match blob.pixel_fingerprint.clone() {
Some(fp) => {
found.insert(blob.sha256.clone(), Ok(fp));
}
None => unread.push(blob),
}
}
}
// New files are downloaded a few at a time and decoded off the runtime's threads (incident, 4 Dec 2026: one at a
// time on the runtime, a new project's first build held the only worker for minutes).
for (sha, info) in super::blobs::image_infos(unread, store).await? {
found.insert(sha, info.map(|(fp, _, _)| fp));
}
let mut rows: Vec<(i64, String)> = Vec::new();
for snapshot in snapshots.iter_mut().filter(|s| needs(s)) {
match snapshot.source_blob.as_ref().and_then(|b| found.get(b)) {
Expand Down Expand Up @@ -458,8 +464,10 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
.filter(|s| s.render_id.is_none() && s.state != "removed")
.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 fingerprints_ms = started.elapsed().as_millis();

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

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

let compare_ms = compare_started.elapsed().as_millis();
let finish_started = std::time::Instant::now();

// 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; anything else was removed.
let carry = groups::carry(&build).await?;
Expand Down Expand Up @@ -660,7 +672,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
// 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 |_| {
let concluded = Box::pin(db::transaction(async |_| {
lock(id).await?;
let mut build = Build::find_or_fail(id).await?;
if build.state != "processing" {
Expand Down Expand Up @@ -689,7 +701,18 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
}
Ok(true)
}))
.await
.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
}

/// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged).
Expand Down
36 changes: 17 additions & 19 deletions app/src/domain/renders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,29 +225,27 @@ pub async fn fail_exhausted_claims() -> laravel::Result<Vec<Render>> {
Ok(failed)
}

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