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
18 changes: 15 additions & 3 deletions app/src/domain/baselines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,10 @@ pub async fn local_notes(ids: &[i64]) -> laravel::Result<HashMap<i64, String>> {
}

/// Where a snapshot's new version was already approved: the same name and platform, the same content (its
/// fingerprint), approved in a review on another branch. A hint for the reviewer: it approves nothing.
/// fingerprint), approved in a review in another build of the suite, on another branch or on this one (an earlier run
/// before a rebase), and not rejected since in a later build of that branch. A hint for the reviewer: it approves
/// nothing. On its own branch a CI build carries such an approval itself when the reviewer saw exactly that change
/// (`super::carried_approvals`); the hint covers the rest.
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct ApprovedElsewhere {
pub branch: String,
Expand All @@ -626,7 +629,8 @@ pub struct ApprovedElsewhere {
}

/// For a build's changed and added snapshots, and those that passed by matching an approval elsewhere, the newest
/// matching approval on another branch, by snapshot id. Changes are always the build's own rows.
/// matching approval in another build of the suite (any branch, this one included), by snapshot id. Changes are always
/// the build's own rows.
///
/// # Errors
/// On a database error.
Expand All @@ -638,14 +642,22 @@ pub async fn approved_elsewhere(build_id: i64) -> laravel::Result<HashMap<i64, A
JOIN builds b ON b.id = s.build_id \
JOIN baselines bl ON bl.project_id = b.project_id AND bl.build_name = b.name AND bl.name = s.name \
AND bl.platform = s.platform \
AND bl.approval = 'review' AND bl.branch <> b.branch AND bl.snapshot_id IS NOT NULL \
AND bl.approval = 'review' AND bl.build_id <> b.id AND bl.snapshot_id IS NOT NULL \
JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \
AND s.source_fingerprint <> '' \
JOIN builds b2 ON b2.id = bl.build_id \
LEFT JOIN users u ON u.id = bl.approved_by \
LEFT JOIN reviews r ON r.id = bl.review_id \
WHERE s.build_id = {build_id} AND (s.state IN ('changed', 'added') \
OR EXISTS (SELECT 1 FROM snapshot_pages p WHERE p.snapshot_id = s.id AND p.state = 'variant')) \
AND NOT EXISTS ( \
SELECT 1 FROM snapshots s3 JOIN builds b3 ON b3.id = s3.build_id \
JOIN reviews r3 ON r3.build_id = b3.id AND r3.action = 'reject' \
AND r3.snapshot_ids @> jsonb_build_array(s3.id) \
WHERE b3.project_id = b.project_id AND b3.name = b.name AND b3.branch = bl.branch \
AND s3.name = s.name AND s3.platform = s.platform \
AND s3.source_fingerprint = s.source_fingerprint AND s3.review = 'rejected' \
AND r3.created_at > bl.created_at) \
ORDER BY s.id, bl.created_at DESC"
)
.select()
Expand Down
156 changes: 156 additions & 0 deletions app/src/domain/carried_approvals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//! Approvals a branch's CI build carries from an earlier build of the same branch (DocSpring PR #1487): after a rebase,
//! the anchor moves to a newer default-branch build and the branch's own earlier approvals stop counting as baselines
//! (`baselines::resolve` takes only those newer than the anchor), so the same change would wait for the same review
//! again. When the reviewer already saw exactly this content, its approval carries:
//!
//! - an added snapshot, when its content (the fingerprint: a PDF's, or an image's pixels) is identical to a snapshot
//! approved in an earlier build;
//! - a changed snapshot, only when both its content and its base's are identical to an approved changed snapshot's: the
//! reviewer saw this very diff.
//!
//! Only within one suite of one project, on one branch and environment, in CI mode, and only an approval that still
//! stands:
//!
//! - it's still the branch's newest approved version of that snapshot: once the branch approved something else for it
//! (a fix of a change approved by mistake), going back is a regression, and waits for review;
//! - it wasn't withdrawn (rejected later in its own build, which deletes its baseline rows), nor, for a carried
//! approval, the review it came from;
//! - nobody rejected that content on the branch after it was approved (by when the review was made, not which
//! build it was in: an older pending build can be rejected after a newer one was approved).
//!
//! A snapshot with an open comment thread on the branch isn't carried (a review couldn't approve it either), and a
//! build with a failed snapshot carries nothing. A rejection doesn't carry: the snapshot waits for review as usual.
//! Other branches' approvals stay a hint (`baselines::approved_elsewhere`).
//!
//! A carried approval is a baseline row with approval `carried`, the original approver and the original review's id,
//! and the snapshot reads as approved. When every change in the build carried, the build concludes approved.

use std::collections::BTreeMap;

use laravel::db;

use crate::models::{Build, Snapshot};

/// Carry earlier approvals on the build's branch to its matching added and changed snapshots. Runs once, in the
/// conclusion's transaction, before the build concludes. Returns how many snapshots it approved.
///
/// # Errors
/// On a database error.
pub async fn apply(build: &Build) -> laravel::Result<usize> {
if build.mode != "ci" {
return Ok(0);
}
let id = build.id;
// A build that concludes failed is reviewed for nothing.
let failed: Option<i32> =
db::query!("SELECT 1 FROM snapshots WHERE build_id = {id} AND state = 'failed' LIMIT 1").scalar().await?;
if failed.is_some() {
return Ok(0);
}
let rows = db::query!(
"SELECT DISTINCT ON (s.id) s.id AS snapshot_id, s.name, s.platform, bl.approved_by, bl.review_id \
FROM snapshots s \
JOIN builds b ON b.id = s.build_id \
JOIN builds b2 ON b2.project_id = b.project_id AND b2.name = b.name AND b2.branch = b.branch \
AND b2.environment = b.environment AND b2.mode = 'ci' AND b2.id < b.id \
JOIN snapshots s2 ON s2.build_id = b2.id AND s2.name = s.name AND s2.platform = s.platform \
AND s2.environment = s.environment AND s2.source_fingerprint = s.source_fingerprint \
AND s2.state IN ('added', 'changed') AND s2.review = 'approved' \
JOIN baselines bl ON bl.build_id = b2.id AND bl.snapshot_id = s2.id AND bl.approval IN ('review', 'carried') \
LEFT JOIN snapshots base ON base.id = s.base_snapshot_id \
LEFT JOIN snapshots base2 ON base2.id = s2.base_snapshot_id \
WHERE s.build_id = {id} AND s.platform <> 'visualci' AND s.review IS NULL AND NOT s.sourced \
AND s.source_fingerprint <> '' \
AND (s.state = 'added' \
OR (s.state = 'changed' AND s2.state = 'changed' AND base.source_fingerprint <> '' \
AND base.source_fingerprint = base2.source_fingerprint)) \
AND (bl.approval = 'review' OR (bl.review_id IS NOT NULL AND EXISTS ( \
SELECT 1 FROM baselines o WHERE o.project_id = bl.project_id AND o.build_name = bl.build_name \
AND o.name = bl.name AND o.platform = bl.platform AND o.environment = bl.environment \
AND o.branch = bl.branch AND o.review_id = bl.review_id AND o.approval = 'review'))) \
AND NOT EXISTS ( \
SELECT 1 FROM baselines later LEFT JOIN snapshots ls ON ls.id = later.snapshot_id \
WHERE later.project_id = b.project_id AND later.build_name = b.name AND later.branch = b.branch \
AND later.name = bl.name AND later.platform = bl.platform AND later.environment = bl.environment \
AND later.id > bl.id AND later.build_id <> b.id \
AND (ls.id IS NULL OR ls.source_fingerprint <> s.source_fingerprint)) \
AND NOT EXISTS ( \
SELECT 1 FROM snapshots s3 JOIN builds b3 ON b3.id = s3.build_id \
JOIN reviews r3 ON r3.build_id = b3.id AND r3.action = 'reject' \
AND r3.snapshot_ids @> jsonb_build_array(s3.id) \
WHERE b3.project_id = b.project_id AND b3.name = b.name AND b3.branch = b.branch \
AND b3.environment = b.environment AND b3.mode = 'ci' AND b3.id <> b.id \
AND s3.name = s.name AND s3.platform = s.platform AND s3.source_fingerprint = s.source_fingerprint \
AND s3.review = 'rejected' AND r3.created_at > bl.created_at) \
ORDER BY s.id, b2.id DESC, bl.id DESC"
)
.select()
.await?;
let mut found = Vec::new();
for r in rows {
let key = (r.try_get::<String>("name")?, r.try_get::<String>("platform")?);
let approval = (r.try_get::<Option<i64>>("approved_by")?, r.try_get::<Option<i64>>("review_id")?);
found.push((key, approval, r.try_get::<i64>("snapshot_id")?));
}
// An open comment thread blocks approving its snapshot (`reviews::review`): it needs an answer first.
let keys: Vec<(String, String)> = found.iter().map(|(k, _, _)| k.clone()).collect();
let open = super::comments::open_on(build.project_id, &build.branch, &keys).await?;
let blocked = |k: &(String, String)| open.iter().any(|t| t.snapshot_name == k.0 && t.platform == k.1);
// Grouped by the approval they carry: its approver and review.
let mut by_approval: BTreeMap<(Option<i64>, Option<i64>), Vec<i64>> = BTreeMap::new();
for (key, approval, snapshot_id) in found {
if !blocked(&key) {
by_approval.entry(approval).or_default().push(snapshot_id);
}
}
let mut carried = 0;
for ((approved_by, review_id), ids) in by_approval {
db::query!("UPDATE snapshots SET review = 'approved', updated_at = now() WHERE id IN ({...ids})")
.update()
.await?;
let snapshots = Snapshot::query().filter(Snapshot::id.is_in(ids)).get().await?;
let refs: Vec<&Snapshot> = snapshots.iter().collect();
super::baselines::record(build, &refs, approved_by, review_id, "carried").await?;
carried += snapshots.len();
}
Ok(carried)
}

/// What a build carried, for its check: "Approved earlier on this branch by Ada Lovelace (build #12)", one line per
/// approval it carried, or `None` when it carried nothing.
///
/// # Errors
/// On a database error.
pub async fn summary(build_id: i64) -> laravel::Result<Option<String>> {
let rows = db::query!(
"SELECT DISTINCT ON (o.number, r.id) o.number, COUNT(*) OVER (PARTITION BY o.number, r.id) AS n, \
u.name AS approver, r.source, r.client_name, r.agent, r.token_name \
FROM baselines bl \
LEFT JOIN reviews r ON r.id = bl.review_id \
LEFT JOIN builds o ON o.id = r.build_id \
LEFT JOIN users u ON u.id = bl.approved_by \
WHERE bl.build_id = {build_id} AND bl.approval = 'carried' \
ORDER BY o.number, r.id"
)
.select()
.await?;
let mut lines = Vec::new();
for r in rows {
let person: Option<String> = r.try_get("approver")?;
let who = match r.try_get::<Option<String>>("source")? {
Some(source) => super::reviews::by(
&source,
r.try_get::<Option<String>>("client_name")?.as_deref(),
r.try_get::<Option<String>>("agent")?.as_deref(),
r.try_get::<Option<String>>("token_name")?.as_deref(),
person.as_deref(),
),
None => person.unwrap_or_else(|| "someone".to_string()),
};
let n: i64 = r.try_get("n")?;
let changes = if n == 1 { "1 change".to_string() } else { format!("{n} changes") };
let build = r.try_get::<Option<i32>>("number")?.map(|n| format!(" (build #{n})")).unwrap_or_default();
lines.push(format!("{changes} approved earlier on this branch by {who}{build}."));
}
Ok((!lines.is_empty()).then(|| lines.join(" ")))
}
1 change: 1 addition & 0 deletions app/src/domain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod blobs;
pub mod build_settings;
pub mod builds;
pub mod bundles;
pub mod carried_approvals;
pub mod changeset;
pub mod comments;
pub mod compare;
Expand Down
7 changes: 5 additions & 2 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,8 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
.await?
.unwrap_or(0);
groups::source_unchanged(&build).await?;
// Changes this branch already approved in an earlier build, content for content (after a rebase).
super::carried_approvals::apply(&build).await?;

let warnings = warnings.clone();
update!(build { warnings }).await?;
Expand Down Expand Up @@ -1293,9 +1295,10 @@ async fn conclude(
// wait for review: approving one sets the baseline for its branch and environment.
let first_on_default = build.mode == "ci" && !has_base && build.branch == default_branch;
// A carried (or removed) change the branch's previous build had rejected keeps its rejection
// (`reruns::keep_rejections`): nothing else in a build being concluded has been reviewed.
// (`reruns::keep_rejections`): carried approvals are the only other review a build being concluded has.
let rejected = all.iter().any(|s| is_change(s) && s.review.as_deref() == Some("rejected"));
// Every change already approved: a merged pull request's version it approved (`approve_merged`).
// Every change already approved: a merged pull request's version it approved (`approve_merged`), or an earlier
// approval on the branch carried (`carried_approvals`). Approved as it stands.
let approved = all.iter().filter(|s| is_change(s)).all(|s| s.review.as_deref() == Some("approved"));
let review_state = match conclusion {
"failed" => "none",
Expand Down
4 changes: 4 additions & 0 deletions app/src/forge/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ async fn own_check(build: &Build, project: &Project, org: &Organization) -> lara
summary.push_str(&format!(" {note}"));
}
}
// Changes approved by carrying an approval from an earlier build of the branch (after a rebase)
if let Some(carried) = crate::domain::carried_approvals::summary(build.id).await? {
summary.push_str(&format!("\n\n{carried}"));
}
// What changed, from the comparison
if let Some(line) = crate::domain::summary::summary_line(build).await? {
summary = format!("{line}\n\n{summary}");
Expand Down
4 changes: 2 additions & 2 deletions app/src/mcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,7 @@ impl VisualCi {
}

#[tool(
description = "A build's status and its snapshots that need attention, 30 at a time (offset and limit page through; longer lists also come grouped by state and name prefix) (changed, added, removed, failed), with how many pages changed in each, the largest change first (order: name to sort by name), and approved_elsewhere when the same new version was already approved on another branch (a hint: it approves nothing). Unchanged snapshots are only counted unless include_unchanged is set. `config` is the visualci.yml the build was sent (null when it had none: the project's settings applied). `flaky: true` marks a change whose content flipped back and forth over the branch's recent builds: often something that differs between runs (the time, an animation, a late font) rather than a real change, so check it before approving, and make the test deterministic. On a pull request's build, `on_main_unreviewed: true` marks a change that's the default branch's own unreviewed change (its newest build, still waiting for review, has it too), and `inherited` counts them: review those on main's build. `matches` marks a change made only of changes a merged pull request approved (two PRs that changed the same screen and merged separately): approve those with `review` and `only: \"matching\"`.",
description = "A build's status and its snapshots that need attention, 30 at a time (offset and limit page through; longer lists also come grouped by state and name prefix) (changed, added, removed, failed), with how many pages changed in each, the largest change first (order: name to sort by name), and approved_elsewhere when the same new version was already approved in another build, on another branch or earlier on this one (a hint: it approves nothing; on its own branch a CI build carries an earlier approval of the same added content, or of the same change over the same base, by itself). Unchanged snapshots are only counted unless include_unchanged is set. `config` is the visualci.yml the build was sent (null when it had none: the project's settings applied). `flaky: true` marks a change whose content flipped back and forth over the branch's recent builds: often something that differs between runs (the time, an animation, a late font) rather than a real change, so check it before approving, and make the test deterministic. On a pull request's build, `on_main_unreviewed: true` marks a change that's the default branch's own unreviewed change (its newest build, still waiting for review, has it too), and `inherited` counts them: review those on main's build. `matches` marks a change made only of changes a merged pull request approved (two PRs that changed the same screen and merged separately): approve those with `review` and `only: \"matching\"`.",
annotations(title = "Get build", read_only_hint = true, idempotent_hint = true, open_world_hint = false)
)]
async fn get_build(
Expand Down Expand Up @@ -1220,7 +1220,7 @@ impl VisualCi {
// How big the change is: the largest share of a page (or of the lines) that changed, and how many
// pixels (or lines). The list puts the biggest first.
"change": sizes.get(&s.id),
// The same new version was already approved on another branch: a hint, it approves nothing here.
// The same new version was already approved in another build (another branch, or earlier on this one): a hint.
"approved_elsewhere": elsewhere.get(&s.id).map(|e| {
let mut v = json!(e);
v["url"] = json!(snapshot_url(e));
Expand Down
Loading
Loading