Skip to content

Commit 343611b

Browse files
authored
app/: processing builds, with groups read from the build that holds them (sc-8900) (#73)
* app/: processing builds (sc-8900): baselines (the anchor, approvals since, merged pull requests), comparison page by page with page rows only for changes and texts by hash, renders and diffs cached by content, the visualci.yml item, the matching hint, carry-forward, groups read from the build that holds them (before writing, and after comparison for unchanged groups), conclude, charging per build with a group check as one credit, the out-of-credits stop, expire_abandoned; the ProcessBuild job (one run per build at a time, debounced); POST …/groups, …/compare and GET …/snapshots; BuildChanged, CreditsSpent, CreditsRanOut and BuildStoppedForCredits events for the other side's listeners * app/: review fixes for #73 (sc-8900, sc-8896): the job charges in a short transaction of its own and stops for credits outside any, so the organization's row isn't locked through a run and billing's listeners see committed data; a failed run keeps what it charged; the builds sweep every five minutes (expire abandoned builds, close idle local ones, run again builds processing with no progress for 10 minutes, fail them after 6 hours) with a heartbeat; GET /status with the data side's numbers * app/: the schedule pushes heartbeats with the app's one heartbeat module (crate::heartbeat, on main) * app/: a group is read only from a build of its own project (groups::holders joins the holder build on the project), with a test
1 parent cd0a6dd commit 343611b

21 files changed

Lines changed: 3475 additions & 0 deletions

‎app/src/console/mod.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes,
2+
//! each run pushing its result to a heartbeat so a sweep that failed or stopped running alerts.
3+
4+
use laravel::schedule::{self, Schedule};
5+
6+
// The heartbeat every scheduled task pushes to (`crate::heartbeat`).
7+
pub use crate::heartbeat;
8+
9+
#[schedule::tasks]
10+
fn schedule(schedule: &mut Schedule) {
11+
schedule.call(sweep_builds).name("builds-sweep").every_five_minutes().without_overlapping().on_one_runner();
12+
}
13+
14+
/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_SWEEP_HEARTBEAT_URL` and `_TOKEN`).
15+
/// `/status` reports `oldest_processing_seconds` and `oldest_receiving_seconds`, which stay low while it runs.
16+
async fn sweep_builds() -> laravel::Result<()> {
17+
let outcome = crate::domain::processing::sweep().await;
18+
match &outcome {
19+
Ok(swept) => tracing::info!(?swept, "builds swept"),
20+
Err(e) => tracing::error!(error = %e, "sweeping builds failed"),
21+
}
22+
heartbeat::push("VISUALCI_BUILDS_SWEEP_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)).await;
23+
outcome.map(|_| ())
24+
}

‎app/src/domain/baselines.rs‎

Lines changed: 478 additions & 0 deletions
Large diffs are not rendered by default.

‎app/src/domain/compare.rs‎

Lines changed: 346 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,346 @@
1+
//! Comparing a snapshot with its baseline, page by page, and the "visualci.yml" item.
2+
3+
use laravel::db;
4+
use laravel::model::update;
5+
use visualci_core::align::{PageOp, align_pages};
6+
use visualci_core::snapshot_text::{self, Format};
7+
8+
use super::build_settings::BuildSettings;
9+
use super::pages::{self, Page};
10+
use super::renders::RenderPage;
11+
use super::snapshots::{CONFIG_NAME, CONFIG_PLATFORM, text_format};
12+
use crate::models::{Blob, IgnoredChange, Project, Snapshot, Variant};
13+
use crate::storage::BlobStore;
14+
15+
/// The exact-match passes below take a baseline row `bl` only when it's current for the snapshot's build: the same
16+
/// suite, a CI approval or one from the build's own branch (local approvals count on their own branch only), and not
17+
/// superseded by a later approval of the same snapshot on the same branch and environment. (Rejected approvals are
18+
/// deleted.)
19+
/// The snapshot's pages: a document's rendered pages, or an image or a text as a single page.
20+
///
21+
/// # Errors
22+
/// When a render or blob is missing.
23+
pub async fn snapshot_pages(snapshot: &Snapshot, store: &BlobStore) -> laravel::Result<Vec<RenderPage>> {
24+
match snapshot.kind.as_str() {
25+
"document" => {
26+
let render_id = snapshot.render_id.ok_or_else(|| laravel::Error::msg("a document without a render"))?;
27+
let render = crate::models::Render::find_or_fail(render_id).await?;
28+
super::renders::with_text(super::renders::pages(&render)).await
29+
}
30+
"image" => {
31+
let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("an image without a file"))?;
32+
let blob =
33+
Blob::find(sha.clone()).await?.ok_or_else(|| laravel::Error::msg("the image's file is missing"))?;
34+
let (fingerprint, width, height) = super::blobs::image_info(blob, store).await?;
35+
Ok(vec![RenderPage {
36+
image: sha,
37+
image_fingerprint: fingerprint.clone(),
38+
fingerprint,
39+
width,
40+
height,
41+
text_sha: String::new(),
42+
text: String::new(),
43+
}])
44+
}
45+
_ => {
46+
let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("a text without a file"))?;
47+
let text = String::from_utf8_lossy(&store.get(&sha).await?).into_owned();
48+
Ok(vec![RenderPage {
49+
image: String::new(),
50+
image_fingerprint: String::new(),
51+
fingerprint: snapshot.source_fingerprint.clone(),
52+
width: 0,
53+
height: 0,
54+
text_sha: String::new(),
55+
text,
56+
}])
57+
}
58+
}
59+
}
60+
61+
fn page_row(
62+
position: usize,
63+
op: &str,
64+
state: &str,
65+
head: Option<(usize, &RenderPage)>,
66+
base: Option<(usize, &RenderPage)>,
67+
diff_id: Option<i64>,
68+
) -> Page {
69+
let image = |p: &RenderPage| (!p.image.is_empty()).then(|| p.image.clone());
70+
let index = |i: usize| i32::try_from(i).unwrap_or(i32::MAX);
71+
Page {
72+
position: index(position),
73+
op: op.to_string(),
74+
state: state.to_string(),
75+
head_index: head.map(|(i, _)| index(i)),
76+
base_index: base.map(|(i, _)| index(i)),
77+
head_image: head.and_then(|(_, p)| image(p)),
78+
base_image: base.and_then(|(_, p)| image(p)),
79+
head_text: head.map(|(_, p)| p.text.clone()),
80+
base_text: base.map(|(_, p)| p.text.clone()),
81+
diff_id,
82+
}
83+
}
84+
85+
async fn set_state(snapshot: &mut Snapshot, state: &str, base_id: Option<i64>) -> laravel::Result<()> {
86+
let state = state.to_string();
87+
update!(snapshot { state, base_snapshot_id: base_id, error: None }).await
88+
}
89+
90+
/// Mark a snapshot failed with the reason.
91+
///
92+
/// # Errors
93+
/// On a database error.
94+
pub async fn mark_failed(snapshot: &mut Snapshot, error: &str) -> laravel::Result<()> {
95+
let error = Some(error.to_string());
96+
update!(snapshot { state: "failed", error }).await
97+
}
98+
99+
/// Compare with the baseline snapshot (or record it as added), storing its pages unless every one is the same as the
100+
/// base's ([`pages::plain_unchanged`]). Sets the snapshot's state.
101+
///
102+
/// # Errors
103+
/// When a page can't be loaded or diffed.
104+
pub async fn compare(
105+
snapshot: &mut Snapshot,
106+
store: &BlobStore,
107+
settings: &BuildSettings<'_>,
108+
base: Option<&Snapshot>,
109+
) -> laravel::Result<()> {
110+
let project = settings.project;
111+
// Text is compared in the head's format, base and head alike, after the head's ignore rules (its build's file or
112+
// the project's, and the test's own).
113+
let rules = settings.compiled_rules(snapshot);
114+
let format = text_format(snapshot);
115+
let normalize = |mut pages: Vec<RenderPage>| {
116+
if let Some(format) = format {
117+
for p in &mut pages {
118+
p.text = snapshot_text::normalize(format, &p.text, &rules).text;
119+
}
120+
}
121+
pages
122+
};
123+
let head_pages = normalize(snapshot_pages(snapshot, store).await?);
124+
let mut rows = Vec::new();
125+
126+
let Some(base) = base else {
127+
for (i, page) in head_pages.iter().enumerate() {
128+
rows.push(page_row(i, "inserted", "changed", Some((i, page)), None, None));
129+
}
130+
pages::store(snapshot.id, rows).await?;
131+
return set_state(snapshot, "added", None).await;
132+
};
133+
134+
let base_pages = if base.kind == snapshot.kind {
135+
normalize(snapshot_pages(base, store).await?)
136+
} else {
137+
snapshot_pages(base, store).await?
138+
};
139+
let fp = |pages: &[RenderPage]| pages.iter().map(|p| p.fingerprint.clone()).collect::<Vec<_>>();
140+
let text = |pages: &[RenderPage]| pages.iter().map(|p| p.text.clone()).collect::<Vec<_>>();
141+
let (base_text, head_text) = (text(&base_pages), text(&head_pages));
142+
let has_text = base_text.iter().chain(&head_text).any(|t| !t.is_empty());
143+
let ops = align_pages(
144+
&fp(&base_pages),
145+
&fp(&head_pages),
146+
has_text.then_some(base_text.as_slice()),
147+
has_text.then_some(head_text.as_slice()),
148+
);
149+
150+
let options = settings.diff_options(snapshot);
151+
let (mut changed, mut ignored) = (false, false);
152+
let mut matched_environment: Option<String> = None;
153+
for (position, op) in ops.iter().enumerate() {
154+
let row = match *op {
155+
PageOp::Unchanged { base: b, head: h } => {
156+
page_row(position, "unchanged", "unchanged", Some((h, &head_pages[h])), Some((b, &base_pages[b])), None)
157+
}
158+
PageOp::Inserted { head: h } => {
159+
changed = true;
160+
page_row(position, "inserted", "changed", Some((h, &head_pages[h])), None, None)
161+
}
162+
PageOp::Removed { base: b } => {
163+
changed = true;
164+
page_row(position, "removed", "changed", None, Some((b, &base_pages[b])), None)
165+
}
166+
PageOp::Changed { base: b, head: h } => {
167+
let (bp, hp) = (&base_pages[b], &head_pages[h]);
168+
let (state, diff_id, matched) = page_state(snapshot, store, project, h, bp, hp, options).await?;
169+
if matched.is_some() {
170+
matched_environment = matched;
171+
}
172+
match state {
173+
"changed" => changed = true,
174+
"ignored" => ignored = true,
175+
_ => {}
176+
}
177+
page_row(position, "changed", state, Some((h, hp)), Some((b, bp)), diff_id)
178+
}
179+
};
180+
rows.push(row);
181+
}
182+
if pages::plain_unchanged(&rows) {
183+
pages::store(snapshot.id, Vec::new()).await?;
184+
} else {
185+
pages::store(snapshot.id, rows).await?;
186+
}
187+
let state = if changed {
188+
"changed"
189+
} else if ignored {
190+
"ignored"
191+
} else {
192+
"unchanged"
193+
};
194+
// "matched local-mac": it passed on another environment's approved image, not its own baseline.
195+
let matched_environment = if changed { None } else { matched_environment };
196+
if snapshot.matched_environment != matched_environment {
197+
update!(snapshot { matched_environment }).await?;
198+
}
199+
set_state(snapshot, state, Some(base.id)).await
200+
}
201+
202+
/// The state of a page whose fingerprint changed: identical pixels, an accepted variant, an image approved before,
203+
/// within the threshold, an ignored change, or a change. With the diff, and the other environment it matched.
204+
async fn page_state(
205+
snapshot: &Snapshot,
206+
store: &BlobStore,
207+
project: &Project,
208+
head_index: usize,
209+
base: &RenderPage,
210+
head: &RenderPage,
211+
options: visualci_core::diff::DiffOptions,
212+
) -> laravel::Result<(&'static str, Option<i64>, Option<String>)> {
213+
let (project_id, build_id) = (project.id, snapshot.build_id);
214+
let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str());
215+
if snapshot.kind == "text" {
216+
if base.text == head.text {
217+
return Ok(("unchanged", None, None));
218+
}
219+
// Exactly this text was approved for this snapshot elsewhere in the project (a squash-merged pull request's
220+
// branch): it passes, as an image would.
221+
let fingerprint = snapshot.source_fingerprint.as_str();
222+
let approved: Option<i32> = db::query!(
223+
"SELECT 1 FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \
224+
WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} \
225+
AND s.source_fingerprint = {fingerprint} AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \
226+
AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \
227+
AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \
228+
AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \
229+
AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) LIMIT 1"
230+
)
231+
.scalar()
232+
.await?;
233+
return Ok((if approved.is_some() { "variant" } else { "changed" }, None, None));
234+
}
235+
if base.image == head.image
236+
|| (!head.image_fingerprint.is_empty() && base.image_fingerprint == head.image_fingerprint)
237+
{
238+
return Ok(("unchanged", None, None));
239+
}
240+
let page_index = i32::try_from(head_index).unwrap_or(i32::MAX);
241+
let is_variant = Variant::query()
242+
.filter(
243+
Variant::project_id.eq(project_id)
244+
& Variant::name.eq(name)
245+
& Variant::platform.eq(platform)
246+
& Variant::page_index.eq(page_index)
247+
& Variant::image.eq(head.image.as_str()),
248+
)
249+
.exists()
250+
.await?;
251+
if is_variant {
252+
return Ok(("variant", None, None));
253+
}
254+
// Approved before: a current baseline, in any environment, branch or commit of the suite, with exactly this image
255+
// for this snapshot: its own environment's first, then CI's. Covers squash merges and other environments (a Linux
256+
// agent's screenshot that matches the approved Mac one passes).
257+
let image = head.image.as_str();
258+
let environment = snapshot.environment.as_str();
259+
let approved: Option<String> = db::query!(
260+
"SELECT s.environment FROM baselines bl \
261+
JOIN snapshots s ON s.id = bl.snapshot_id JOIN snapshot_pages p ON p.snapshot_id = s.id \
262+
WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} AND p.head_image = {image} \
263+
AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \
264+
AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \
265+
AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \
266+
AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \
267+
AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \
268+
ORDER BY (s.environment = {environment}) DESC, (s.environment = 'ci') DESC, bl.id DESC LIMIT 1"
269+
)
270+
.scalar()
271+
.await?;
272+
if let Some(env) = approved {
273+
let other = (env != snapshot.environment).then_some(env);
274+
return Ok(("variant", None, other));
275+
}
276+
let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options).await?;
277+
if !super::diffs::is_change(&diff) {
278+
return Ok(("within_threshold", Some(diff.id), None));
279+
}
280+
if let Some(fingerprint) = &diff.fingerprint {
281+
let is_ignored = IgnoredChange::query()
282+
.filter(
283+
IgnoredChange::project_id.eq(project_id)
284+
& IgnoredChange::name.eq(name)
285+
& IgnoredChange::platform.eq(platform)
286+
& IgnoredChange::fingerprint.eq(fingerprint.as_str()),
287+
)
288+
.exists()
289+
.await?;
290+
if is_ignored {
291+
return Ok(("ignored", Some(diff.id), None));
292+
}
293+
}
294+
Ok(("changed", Some(diff.id), None))
295+
}
296+
297+
/// Add the "visualci.yml" item to a build: a changed text snapshot whose diff is the settings that decide what counts
298+
/// as a change, base against head. It's reviewed like any change, so loosened rules can't pass unseen.
299+
///
300+
/// # Errors
301+
/// On a database error.
302+
pub async fn record_config_change(
303+
build_id: i64,
304+
base_build_id: i64,
305+
base_id: Option<i64>,
306+
base: &serde_json::Value,
307+
head: &serde_json::Value,
308+
) -> laravel::Result<Snapshot> {
309+
let text = |v: &serde_json::Value| snapshot_text::normalize(Format::Json, &v.to_string(), &Default::default()).text;
310+
let (base_text, head_text) = (text(base), text(head));
311+
let page = |t: &str| RenderPage {
312+
image: String::new(),
313+
image_fingerprint: String::new(),
314+
fingerprint: visualci_core::sha256_hex(t.as_bytes()),
315+
width: 0,
316+
height: 0,
317+
text_sha: String::new(),
318+
text: t.to_string(),
319+
};
320+
let snapshot = laravel::model::create!(Snapshot {
321+
pid: laravel::str::uuid7(),
322+
build_id: build_id,
323+
name: CONFIG_NAME,
324+
platform: CONFIG_PLATFORM,
325+
kind: "text",
326+
format: Some("json".to_string()),
327+
source_fingerprint: visualci_core::sha256_hex(head_text.as_bytes()),
328+
source_blob: None,
329+
render_id: None,
330+
engine: None,
331+
threshold: None,
332+
ignore_anti_aliasing: None,
333+
meta: serde_json::json!({ "config": true, "base_build_id": base_build_id }),
334+
state: "changed",
335+
base_snapshot_id: base_id,
336+
review: None,
337+
error: None,
338+
matched_environment: None,
339+
baseline_id: None,
340+
matches_build_id: None,
341+
})
342+
.await?;
343+
let (b, h) = (page(&base_text), page(&head_text));
344+
pages::store(snapshot.id, vec![page_row(0, "changed", "changed", Some((0, &h)), Some((0, &b)), None)]).await?;
345+
Ok(snapshot)
346+
}

0 commit comments

Comments
 (0)