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
10 changes: 10 additions & 0 deletions app/database/migrations/2026_12_07_000000_build_base_branch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! The branch a pull request build's pull request merges into (sc-9247): the build compares with what that branch
//! approved, and falls back to the default branch only when nothing names one.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
// Never queued behind a long transaction on builds (holding every query on the table up behind it).
tx.query("SET LOCAL lock_timeout = '5s'; ALTER TABLE builds ADD COLUMN base_branch TEXT").unprepared().await?;
Ok(())
}
154 changes: 124 additions & 30 deletions app/src/domain/baselines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@
//!
//! A build compares each snapshot with its own baseline, worked out in two layers:
//!
//! 1. **The anchor**: the nearest ancestor commit's completed CI build of the same suite (else the default branch's
//! latest approved one). Every build holds every snapshot (its own rows and the groups it reads from earlier builds,
//! `effective_snapshots`), so the anchor knows each one's approved state at that commit: an approved change is its
//! new version, an unapproved change is the version it was compared with, an unchanged snapshot is itself.
//! 1. **The anchor**: the nearest ancestor commit's approved CI build of the same suite, else the newest approved one
//! on the build's base branch (a pull request's target, [`base_branch`]), else on the default branch. Only an
//! approved build (or one approved on its own: the default branch's first, or one with no changes) is ever an
//! anchor: a pending build, the pull request's own earlier run included, never is, since what it was compared with
//! came from its own anchor and would hide the pull request's changes (sc-9247). Every build holds every snapshot
//! (its own rows and the groups it reads from earlier builds, `effective_snapshots`), so the anchor knows each
//! one's approved state at that commit.
//! 2. **Approvals since**: every approved change is a row in `baselines` (the snapshot, or its removal) with the
//! build, commit, branch, environment and mode it came from. Rows newer than the anchor are laid on top: CI
//! approvals on the build's ancestry, and any approval on the build's own branch. A local approval counts on its
//! own branch only, never through ancestry.
//! 3. **Merges**: a pull request's approvals reach its base branch only when it merges ([`record_merge`] copies them
//! to the merge commit), and count through that commit's place in a build's history. Nothing is taken from an
//! unrelated branch, and only the default branch's first build is approved without review.
//! unrelated branch, and only the default branch's first build is approved without review. A pull request's base
//! branch takes the default branch's place for it: its CI approvals are the pull request's starting point, and the
//! default branch's then count only through the build's history (or when the anchor came from it).
//!
//! Documents and text are the same everywhere and keep one shared set (environment `""`). Screenshots keep a set per
//! environment: CI's comes from the anchor and CI approvals; a laptop's from its own approvals on the branch (or CI
Expand Down Expand Up @@ -42,32 +47,110 @@ pub fn ancestry(build: &Build) -> Vec<String> {
commits
}

/// The anchor build: the nearest ancestor commit's completed CI build of this suite, else the default branch's latest
/// approved CI build.
/// The branch a build's changes are measured against: its pull request's base branch when CI named one, else the
/// project's default branch. A base branch counts only on a pull request's build that isn't on the default branch: a
/// push build naming one would otherwise take an unmerged branch's approvals.
#[must_use]
pub fn base_branch<'a>(build: &'a Build, project: &'a Project) -> &'a str {
build
.base_branch
.as_deref()
.filter(|b| {
!b.is_empty() && *b != build.branch && build.pr_number.is_some() && build.branch != project.default_branch
})
.unwrap_or(&project.default_branch)
}

/// The branches whose CI approvals count for a build wherever on the branch they were made: its base branch, and the
/// branch its anchor came from (the default branch, when the base branch had no approved build). The default branch's
/// other approvals count only through the build's history: a pull request into a release branch never takes the
/// default branch's newer approvals.
fn trusted_branches(build: &Build, project: &Project, anchor: Option<&Build>) -> Vec<String> {
let mut out = vec![base_branch(build, project).to_string()];
if let Some(a) = anchor
&& a.branch == project.default_branch
&& !out.contains(&a.branch)
{
out.push(a.branch.clone());
}
out
}

/// The nearest ancestor commit's approved CI build of this suite. Never the build itself, nor an empty build that
/// follows another (`domain::reruns`: it holds no snapshots, and the build it follows is on the same commit).
async fn nearest_approved(build: &Build) -> laravel::Result<Option<Build>> {
let commits = ancestry(build);
let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id);
let candidates: Vec<Build> = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \
AND state = 'completed' AND id <> {id} AND commit_sha IN ({...commits}) AND covered_by_build_id IS NULL \
AND review_state IN ('approved', 'auto_approved') ORDER BY id DESC"
)
.select_as()
.await?;
Ok(commits.iter().find_map(|c| candidates.iter().find(|b| &b.commit_sha == c)).cloned())
}

/// The anchor build: the nearest ancestor commit's approved CI build of this suite, else the newest approved CI build
/// on the build's base branch ([`base_branch`]), else on the default branch. Never a pending, rejected or failed
/// build: what one of those was compared with isn't anything anyone approved for this build. Never an empty build
/// that follows another either: it shows that build's review state but holds no snapshots.
///
/// # Errors
/// On a database error.
pub async fn anchor(build: &Build, project: &Project) -> laravel::Result<Option<Build>> {
if let Some(best) = nearest_approved(build).await? {
return Ok(Some(best));
}
let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id);
let base = base_branch(build, project);
let order = if base == project.default_branch { vec![base] } else { vec![base, project.default_branch.as_str()] };
for branch in order {
let newest: Option<Build> = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \
AND state = 'completed' AND branch = {branch} AND covered_by_build_id IS NULL \
AND review_state IN ('approved', 'auto_approved') AND id < {id} ORDER BY id DESC LIMIT 1"
)
.select_one_as()
.await?;
if newest.is_some() {
return Ok(newest);
}
}
Ok(None)
}

/// The nearest ancestor commit's CI build on `branch` that's still waiting for review, older than the build (for
/// [`super::inherited`]: a pull request built on top of an unreviewed base-branch build).
///
/// # Errors
/// On a database error.
pub async fn nearest_pending_on(build: &Build, branch: &str) -> laravel::Result<Option<Build>> {
let commits = ancestry(build);
let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id);
let candidates: Vec<Build> = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \
AND state = 'completed' AND id <> {id} AND commit_sha IN ({...commits}) ORDER BY id DESC"
AND state = 'completed' AND id < {id} AND branch = {branch} AND commit_sha IN ({...commits}) \
AND covered_by_build_id IS NULL AND review_state = 'pending' ORDER BY id DESC"
)
.select_as()
.await?;
if let Some(best) = commits.iter().find_map(|c| candidates.iter().find(|b| &b.commit_sha == c)) {
return Ok(Some(best.clone()));
}
let default_branch = project.default_branch.as_str();
let fallback: Option<Build> = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \
AND state = 'completed' AND id <> {id} AND branch = {default_branch} \
AND review_state IN ('approved', 'auto_approved') AND id < {id} ORDER BY id DESC LIMIT 1"
Ok(commits.iter().find_map(|c| candidates.iter().find(|b| &b.commit_sha == c)).cloned())
}

/// Whether the suite has any CI build on `branch`.
///
/// # Errors
/// On a database error.
pub async fn branch_has_builds(build: &Build, branch: &str) -> laravel::Result<bool> {
let (project_id, name) = (build.project_id, build.name.as_str());
let found: Option<i32> = db::query!(
"SELECT 1 FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' AND branch = {branch} \
LIMIT 1"
)
.select_one_as()
.scalar()
.await?;
Ok(fallback)
Ok(found.is_some())
}

/// What a build says about one snapshot's approved state.
Expand Down Expand Up @@ -130,11 +213,12 @@ async fn effective(
for_build: &Build,
project: &Project,
) -> laravel::Result<HashMap<(String, String), Snapshot>> {
// Only builds on the resolving build's history count: its ancestors, its branch, the default branch.
// Only builds on the resolving build's history count: its ancestors, its branch, its base branch (and the default
// branch when the anchor came from it).
let ancestors: HashSet<String> = ancestry(for_build).into_iter().collect();
let counts = |b: &Build| {
ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || b.branch == project.default_branch
};
let trusted = trusted_branches(for_build, project, Some(anchor));
let counts =
|b: &Build| ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || trusted.contains(&b.branch);
let mut out = HashMap::new();
let mut pending: Option<HashSet<(String, String)>> = None;
let mut seen = HashSet::new();
Expand Down Expand Up @@ -195,21 +279,30 @@ pub async fn resolve(
None => HashMap::new(),
};
let after = anchor.as_ref().map_or(0, |a| a.id);
let history = ancestry(build);
// Commits nearer than the anchor's in this build's history (all of it when the anchor isn't on it): an approval made
// there is newer than the anchor whatever its id. A pull request build approved in part before the default branch
// built its parent commit keeps those approvals when the next build anchors on that later build.
let anchor_at = anchor.as_ref().and_then(|a| history.iter().position(|c| c == &a.commit_sha));
let nearer: Vec<String> = history[..anchor_at.unwrap_or(history.len())].to_vec();
let nearer_or_none = if nearer.is_empty() { vec![String::new()] } else { nearer.clone() };
let nearer_set: HashSet<&String> = nearer.iter().collect();

// Approvals newer than the anchor: CI ones on the ancestry, and any on this branch. A merged pull request's
// Approvals newer than the anchor (by id, or by commit nearer in the history): CI ones on the ancestry, and any on
// this branch. A merged pull request's
// approvals count only through their merge commit's place in this build's history. For local environments also
// older ones, since the anchor (a CI build) doesn't carry their screenshots. Local approvals apply only to their
// own branch; on the default branch only CI approvals count for other branches.
let history = ancestry(build);
let (project_id, build_name, id, branch, default_branch) =
(build.project_id, build.name.as_str(), build.id, build.branch.as_str(), project.default_branch.as_str());
// own branch; on the base branch (and the default branch when the anchor came from it) only CI approvals count for
// other branches.
let trusted = trusted_branches(build, project, anchor.as_ref());
let (project_id, build_name, id, branch) = (build.project_id, build.name.as_str(), build.id, build.branch.as_str());
let rows: Vec<Baseline> = db::query!(
"SELECT * FROM baselines WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} \
AND ( \
(build_id > {after} AND approval <> 'merged' \
(approval <> 'merged' AND (build_id > {after} OR commit_sha IN ({...nearer_or_none})) \
AND ((mode = 'ci' AND commit_sha IN ({...history})) OR branch = {branch})) \
OR (approval = 'merged' AND commit_sha IN ({...history})) \
OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch = {default_branch} AND mode = 'ci'))) \
OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch IN ({...trusted}) AND mode = 'ci'))) \
) ORDER BY id"
)
.select_as()
Expand All @@ -224,7 +317,8 @@ pub async fn resolve(
// The latest row per (name, platform, environment); rows newer than the anchor or on this branch win over older
// default-branch ones.
let mut latest: HashMap<(String, String, String), Baseline> = HashMap::new();
let rank = |r: &Baseline| (r.build_id > after || r.branch == build.branch || merged_and_new(r), r.id);
let newer = |r: &Baseline| r.build_id > after || nearer_set.contains(&r.commit_sha);
let rank = |r: &Baseline| (newer(r) || r.branch == build.branch || merged_and_new(r), r.id);
// Between two merged pull requests' approvals, the nearer merge in this build's history wins (it was merged later
// on this line), whatever order the webhooks arrived in.
let nearness = |r: &Baseline| history.iter().position(|c| c == &r.commit_sha).unwrap_or(usize::MAX);
Expand Down
13 changes: 13 additions & 0 deletions app/src/domain/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ pub struct CreateParams {
pub branch: String,
#[serde(default, deserialize_with = "super::lenient::optional")]
pub pr_number: Option<i32>,
/// The branch the pull request merges into: the build compares with what it approved. Without one, the default
/// branch.
#[serde(default)]
pub base_branch: Option<String>,
/// Ancestor commits, nearest first, for finding the baseline.
#[serde(default)]
pub parent_commits: Vec<String>,
Expand Down Expand Up @@ -142,6 +146,14 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option<i6
if params.branch.len() > 255 || params.branch.chars().any(char::is_control) {
return invalid("branch must be at most 255 characters");
}
if params.base_branch.as_ref().is_some_and(|b| b.len() > 255 || b.chars().any(char::is_control)) {
return invalid("base_branch must be at most 255 characters");
}
// A base branch names nothing on a build without a pull request, on the default branch, or as the build's own
// branch: a push build mustn't take another branch's approvals (`baselines::base_branch` checks again).
let base_branch = params.base_branch.clone().filter(|b| {
!b.is_empty() && *b != params.branch && params.pr_number.is_some() && params.branch != project.default_branch
});
if params.name.trim().is_empty() || params.name.len() > 100 {
return invalid("name must be 1 to 100 characters");
}
Expand Down Expand Up @@ -208,6 +220,7 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option<i6
commit_sha: params.commit.as_str(),
branch: params.branch.as_str(),
pr_number: params.pr_number,
base_branch: base_branch.clone(),
parent_commits: Json(parents.clone()),
mode: params.mode.as_str(),
subset: params.subset,
Expand Down
Loading
Loading