From 59514cf4a65e1e363644eff73c4db31542cc79e7 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 19:07:34 +1300 Subject: [PATCH 1/2] app/: a pull request build compares with its base branch's approved build, and a base is only ever an approved build (sc-9247) Two baseline bugs from the daisyUI case study: 1. A PR build compared with the default branch, never the PR's base branch. Builds now record `base_branch` (the API's and MCP create_build's `base_branch`; the CLI sends it in a follow-up, once this server is live). The anchor falls back to the base branch's newest approved build before the default branch's, and the base branch counts like the default branch in the anchor walk, local environments' rows, the exact-match passes and the inherited-changes note. 2. The anchor took the nearest ancestor commit's completed build whatever its review, so a rerun of a PR's commit anchored on its own pending build and compared with whatever that build had been compared with. The anchor is now only ever an approved (or auto-approved) build, never a pending, rejected or failed one, and never an empty build that follows another (sc-9044's reruns). Per-snapshot approvals of pending builds still count through the baselines table; `inherited` finds the unreviewed base-branch build on the PR's history itself. --- .../2026_12_07_000000_build_base_branch.rs | 9 + app/src/domain/baselines.rs | 103 ++++++++--- app/src/domain/builds.rs | 10 ++ app/src/domain/compare.rs | 20 ++- app/src/domain/demo.rs | 1 + app/src/domain/inherited.rs | 21 ++- app/src/mcp/args.rs | 3 + app/src/mcp/mod.rs | 3 +- app/src/models/builds.rs | 3 + app/tests/baselines.rs | 170 +++++++++++++++++- .../tools-list-project-token.json | 9 +- .../tools-list-user-token.json | 9 +- docs/design.md | 34 +++- frontend/content/docs/reference/api.md | 3 +- 14 files changed, 332 insertions(+), 66 deletions(-) create mode 100644 app/database/migrations/2026_12_07_000000_build_base_branch.rs diff --git a/app/database/migrations/2026_12_07_000000_build_base_branch.rs b/app/database/migrations/2026_12_07_000000_build_base_branch.rs new file mode 100644 index 00000000..6a57b2cd --- /dev/null +++ b/app/database/migrations/2026_12_07_000000_build_base_branch.rs @@ -0,0 +1,9 @@ +//! 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<()> { + tx.query("ALTER TABLE builds ADD COLUMN base_branch TEXT").unprepared().await?; + Ok(()) +} diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index 0ed736b9..733b966b 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -2,17 +2,21 @@ //! //! 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 counts as the default branch does for it: its CI approvals are the pull request's starting point. //! //! 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 @@ -42,32 +46,72 @@ pub fn ancestry(build: &Build) -> Vec { commits } -/// The anchor build: the nearest ancestor commit's completed CI build of this suite, else the default branch's latest -/// approved CI build. -/// -/// # Errors -/// On a database error. -pub async fn anchor(build: &Build, project: &Project) -> laravel::Result> { +/// 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. +#[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).unwrap_or(&project.default_branch) +} + +/// The branches whose CI approvals a build starts from besides its own: its base branch and the default branch. +fn starting_branches<'a>(build: &'a Build, project: &'a Project) -> Vec<&'a str> { + let mut out = vec![base_branch(build, project)]; + if out[0] != project.default_branch { + out.push(&project.default_branch); + } + out +} + +/// The nearest ancestor commit's completed CI build of this suite, whatever its review: approved builds only when +/// `approved_only`. 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_on_ancestry(build: &Build, approved_only: bool) -> laravel::Result> { let commits = ancestry(build); let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); let candidates: Vec = 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 commit_sha IN ({...commits}) AND covered_by_build_id IS NULL \ + AND (NOT {approved_only} OR review_state IN ('approved', 'auto_approved')) 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())); + 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> { + if let Some(best) = nearest_on_ancestry(build, true).await? { + return Ok(Some(best)); } - let default_branch = project.default_branch.as_str(); - let fallback: Option = 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" - ) - .select_one_as() - .await?; - Ok(fallback) + let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); + for branch in starting_branches(build, project) { + let newest: Option = 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 completed CI build whatever its review (for [`super::inherited`]: a pull request +/// built on top of an unreviewed base-branch build). +/// +/// # Errors +/// On a database error. +pub async fn nearest(build: &Build) -> laravel::Result> { + nearest_on_ancestry(build, false).await } /// What a build says about one snapshot's approved state. @@ -130,10 +174,11 @@ async fn effective( for_build: &Build, project: &Project, ) -> laravel::Result> { - // 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 and default branches. let ancestors: HashSet = ancestry(for_build).into_iter().collect(); + let starting = starting_branches(for_build, project); let counts = |b: &Build| { - ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || b.branch == project.default_branch + ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || starting.contains(&b.branch.as_str()) }; let mut out = HashMap::new(); let mut pending: Option> = None; @@ -199,17 +244,17 @@ pub async fn resolve( // Approvals newer than the anchor: 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. + // own branch; on the base and default branches 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()); + let starting: Vec = starting_branches(build, project).into_iter().map(str::to_string).collect(); + let (project_id, build_name, id, branch) = (build.project_id, build.name.as_str(), build.id, build.branch.as_str()); let rows: Vec = 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' \ 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 ({...starting}) AND mode = 'ci'))) \ ) ORDER BY id" ) .select_as() diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index fb622008..4f236949 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -27,6 +27,10 @@ pub struct CreateParams { pub branch: String, #[serde(default, deserialize_with = "super::lenient::optional")] pub pr_number: Option, + /// 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, /// Ancestor commits, nearest first, for finding the baseline. #[serde(default)] pub parent_commits: Vec, @@ -142,6 +146,11 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option 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 that's the build's own branch names nothing. + let base_branch = params.base_branch.clone().filter(|b| !b.is_empty() && *b != params.branch); if params.name.trim().is_empty() || params.name.len() > 100 { return invalid("name must be 1 to 100 characters"); } @@ -208,6 +217,7 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option = db::query!( @@ -228,7 +229,8 @@ async fn page_state( WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} \ AND s.source_fingerprint = {fingerprint} AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ AND (bl.branch = (SELECT branch FROM builds WHERE id = {build_id}) \ - OR (bl.mode = 'ci' AND bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}))) \ + OR (bl.mode = 'ci' AND (bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}) \ + OR bl.branch = (SELECT base_branch FROM builds WHERE id = {build_id})))) \ AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) LIMIT 1" @@ -258,8 +260,9 @@ async fn page_state( } // Approved before: a current baseline, in any environment, on the build's own branch or the default branch, with // exactly this image for this snapshot: its own environment's first, then CI's. Covers other environments (a Linux - // agent's screenshot that matches the approved Mac one passes). Another branch's approvals never count: a pull - // request's reach the default branch only at its merge (`baselines::record_merge`). + // agent's screenshot that matches the approved Mac one passes). The build's base branch (its pull request's target) + // counts as the default branch does. Another branch's approvals never count: a pull request's reach its base branch + // only at its merge (`baselines::record_merge`). let image = head.image.as_str(); let environment = snapshot.environment.as_str(); let approved: Option = db::query!( @@ -268,7 +271,8 @@ async fn page_state( WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} AND p.head_image = {image} \ AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ AND (bl.branch = (SELECT branch FROM builds WHERE id = {build_id}) \ - OR (bl.mode = 'ci' AND bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}))) \ + OR (bl.mode = 'ci' AND (bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}) \ + OR bl.branch = (SELECT base_branch FROM builds WHERE id = {build_id})))) \ AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index de168255..4d80e429 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -393,6 +393,7 @@ impl Seeder<'_> { commit: commit.to_string(), branch: branch.to_string(), pr_number, + base_branch: None, parent_commits: parents.iter().map(ToString::to_string).collect(), mode: "ci".to_string(), name: "default".to_string(), diff --git a/app/src/domain/inherited.rs b/app/src/domain/inherited.rs index 7ed52d08..8b53a8c1 100644 --- a/app/src/domain/inherited.rs +++ b/app/src/domain/inherited.rs @@ -1,6 +1,7 @@ -//! Changes a pull request build only inherited from its base branch. When the default branch's newest build (the one a -//! PR build is compared on top of) is still waiting for review, its changes aren't baselines yet, so every PR build -//! made after it shows them again: a reviewer can't tell the PR's own changes from main's backlog (2 Dec 2026, PR 3: +//! Changes a pull request build only inherited from its base branch. When the base branch's newest build on the PR's +//! history (the default branch's, unless the PR names another base) is still waiting for review, its changes aren't +//! baselines yet, and the PR build compares with the approved build underneath it, so every PR build made after it +//! shows them again: a reviewer can't tell the PR's own changes from main's backlog (2 Dec 2026, PR 3: //! 98 changes, none of them the PR's). A PR build's change that's exactly the base build's unreviewed change (the same //! snapshot, the same new content) is marked inherited, and the build says "N changes are already on main and //! unreviewed (build #X)". Approval and the check still go by approved baselines: this only says where a change came @@ -35,18 +36,20 @@ impl Inherited { } } -/// The build's changes that are its base build's unreviewed changes, when its base is an unreviewed build of the -/// default branch and this build isn't on that branch. `None` when there are none. +/// The build's changes that are an unreviewed base-branch build's unreviewed changes: the nearest build on its history +/// is one of the base branch's (`baselines::base_branch`), still waiting for review and newer than the build it was +/// compared with, and this build isn't on that branch. `None` when there are none. /// /// # Errors /// On a database error. pub async fn of_build(build: &Build, project: &Project) -> laravel::Result> { - if build.branch == project.default_branch { + let base_branch = super::baselines::base_branch(build, project); + if build.branch == base_branch { return Ok(None); } - let Some(base_id) = build.base_build_id else { return Ok(None) }; - let Some(base) = Build::find(base_id).await? else { return Ok(None) }; - if base.branch != project.default_branch || base.review_state != "pending" { + let Some(base) = super::baselines::nearest(build).await? else { return Ok(None) }; + let newer = build.base_build_id.is_none_or(|compared_with| base.id > compared_with); + if base.branch != base_branch || base.review_state != "pending" || !newer || base.id > build.id { return Ok(None); } // The base build's changes that nobody has approved, by snapshot. diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs index 5d8fa794..63130b37 100644 --- a/app/src/mcp/args.rs +++ b/app/src/mcp/args.rs @@ -364,6 +364,9 @@ pub struct CreateBuildArgs { pub commit: String, pub branch: String, pub pr_number: Option, + /// The branch the pull request merges into: the build compares with what it approved. Default: the project's + /// default branch. + pub base_branch: Option, /// Ancestor commits, nearest first, for finding the baseline. #[serde(default)] pub parent_commits: Vec, diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index ab1bbe55..2c72b021 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -1839,7 +1839,7 @@ impl VisualCi { } #[tool( - description = "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the baseline from the branch's ancestors (or the default branch).", + description = "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the approved baseline from the branch's ancestors, else the pull request's base branch (`base_branch`), else the default branch.", annotations(title = "Create build", read_only_hint = false, destructive_hint = false, open_world_hint = false) )] async fn create_build( @@ -1853,6 +1853,7 @@ impl VisualCi { commit: args.commit, branch: args.branch, pr_number: args.pr_number, + base_branch: args.base_branch, parent_commits: args.parent_commits, mode: args.mode.unwrap_or_else(|| "ci".into()), name: args.name.unwrap_or_else(|| "default".into()), diff --git a/app/src/models/builds.rs b/app/src/models/builds.rs index 94d887c2..d9efb2f9 100644 --- a/app/src/models/builds.rs +++ b/app/src/models/builds.rs @@ -16,6 +16,9 @@ pub struct Build { pub commit_sha: String, pub branch: String, pub pr_number: Option, + /// The branch the pull request merges into, as CI named it (`None` without a pull request, or when CI didn't say): + /// the build compares with what it approved (`baselines::base_branch`). + pub base_branch: Option, #[default] /// Ancestor commits, nearest first, at most 200: JSON until laravel/rust-framework#527 (PostgreSQL arrays). pub parent_commits: Json>, diff --git a/app/tests/baselines.rs b/app/tests/baselines.rs index 2ce816be..3def61d3 100644 --- a/app/tests/baselines.rs +++ b/app/tests/baselines.rs @@ -2,7 +2,7 @@ //! request branch's first build waits for review, and a branch's approvals reach the default branch only when its pull //! request merges (`baselines::record_merge`, at the merge commit). A build never takes another branch's approvals. -use app::domain::{baselines, reviews}; +use app::domain::{baselines, inherited, reviews}; use app::models::{Build, Project}; use app::testing::fixtures; use laravel::db; @@ -18,6 +18,7 @@ fn png(rgb: [u8; 3]) -> Vec { const RED: [u8; 3] = [255, 0, 0]; const GREEN: [u8; 3] = [0, 255, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; struct World { project: Project, @@ -51,7 +52,20 @@ impl World { files: &[(&str, [u8; 3])], ) -> Build { // Boxed: the test's own future would otherwise outgrow a test thread's stack. - Box::pin(self.build_inner(app, commit, branch, parents, files)).await + Box::pin(self.build_inner(app, commit, branch, None, parents, files)).await + } + + /// [`World::build`] for a pull request into `base`. + async fn build_into( + &self, + app: &Application, + commit: &str, + branch: &str, + base: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + Box::pin(self.build_inner(app, commit, branch, Some(base), parents, files)).await } async fn build_inner( @@ -59,17 +73,25 @@ impl World { app: &Application, commit: &str, branch: &str, + base: Option<&str>, parents: &[&str], files: &[(&str, [u8; 3])], ) -> Build { let auth = format!("Bearer {}", self.token); - let created = app - .post("/api/v1/builds") - .header("authorization", &auth) - .json(json!({ "commit": commit, "branch": branch, "parent_commits": parents })) - .await; + let mut body = json!({ "commit": commit, "branch": branch, "parent_commits": parents }); + if let Some(base) = base { + body["base_branch"] = json!(base); + body["pr_number"] = json!(1); + } + let created = app.post("/api/v1/builds").header("authorization", &auth).json(body).await; created.assert_ok(); let id = created.json()["id"].as_str().unwrap().to_string(); + if files.is_empty() { + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + assert_eq!(done.json()["state"], "completed", "{}", done.text()); + let pid: laravel::str::Uuid = id.parse().unwrap(); + return Build::query().filter(Build::pid.eq(pid)).first().await.unwrap().unwrap(); + } let mut list = Vec::new(); let mut bodies = Vec::new(); for (name, rgb) in files { @@ -201,3 +223,137 @@ async fn a_squash_merged_pull_requests_approvals_reach_the_default_branch_at_the assert_eq!(after.conclusion.as_deref(), Some("unchanged"), "{:?}", states(&after).await?); Ok(()) } + +/// sc-9247: a pull request into a release branch compares with what the release branch approved, not the default +/// branch's baseline, even with no ancestry in common that VisualCI can see (a shallow checkout sends none). +#[laravel::test] +async fn a_pull_request_into_a_release_branch_compares_with_the_release_branchs_approved_build( + app: Application, +) -> laravel::Result<()> { + let w = world().await?; + let m1 = w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + assert_eq!(m1.review_state, "auto_approved"); + // release-1 moved on from main: its home page is green, approved there. + let r1 = w.build(&app, "r1", "release-1", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + let r1 = w.approve(r1).await; + assert_eq!(r1.review_state, "approved"); + // main moves on too, differently. + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", BLUE), ("web/about", RED)]).await; + w.approve(m2).await; + + // The pull request into release-1 changes only the about page. + let pr = w.build_into(&app, "f1", "fix", "release-1", &[], &[("web/home", GREEN), ("web/about", GREEN)]).await; + assert_eq!(pr.base_build_id, Some(r1.id), "compared with release-1's approved build, not main's"); + assert_eq!( + states(&pr).await?, + vec![("web/about".into(), "changed".into()), ("web/home".into(), "unchanged".into())], + "only the pull request's own change" + ); + Ok(()) +} + +/// sc-9247 (the daisyUI case study): with nothing approved on the default branch, a re-run of a pull request's commit +/// compared with the pull request's own earlier, unapproved build, which hid what the pull request changes behind the +/// versions that build happened to be compared with. A base is only ever an approved build. +#[laravel::test] +async fn a_rerun_never_compares_with_its_own_unapproved_build(app: Application) -> laravel::Result<()> { + let w = world().await?; + let m1 = w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + assert_eq!(m1.review_state, "auto_approved"); + let first = w.build(&app, "p1", "feature", &[], &[("web/home", GREEN), ("web/about", RED)]).await; + assert_eq!((first.review_state.as_str(), first.base_build_id), ("pending", Some(m1.id))); + + // The project's default branch becomes one with no builds, and the job runs again on the same commit. + let project_id = w.project.id; + db::query!("UPDATE projects SET default_branch = 'master' WHERE id = {project_id}").update().await?; + let again = w.build(&app, "p1", "feature", &[], &[("web/home", GREEN), ("web/about", RED)]).await; + assert_ne!(again.base_build_id, Some(first.id), "never its own pending build"); + assert_eq!(again.base_build_id, None, "nothing approved to compare with"); + assert_eq!( + states(&again).await?, + vec![("web/about".into(), "added".into()), ("web/home".into(), "added".into())], + "everything still waits for review: added, not compared with what the pending build was compared with" + ); + assert_eq!(again.review_state, "pending"); + Ok(()) +} + +/// A pending build on the pull request's own branch is never the base: the next build on the branch compares with the +/// approved build underneath, and still shows the change nobody approved. +#[laravel::test] +async fn a_pending_build_on_the_branch_is_never_the_base(app: Application) -> laravel::Result<()> { + let w = world().await?; + let m1 = w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let f1 = + w.build_into(&app, "f1", "feature", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + assert_eq!(f1.review_state, "pending"); + let f2 = w + .build_into(&app, "f2", "feature", "main", &["f1", "m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]) + .await; + assert_eq!(f2.base_build_id, Some(m1.id), "the approved build, not the branch's pending one"); + assert_eq!( + states(&f2).await?, + vec![("web/about".into(), "unchanged".into()), ("web/home".into(), "changed".into())] + ); + + // Approving part of a pending build still counts for the branch's next build: the approval is a baseline row. + let (name, f2_id) = ("web/home", f2.id); + let home: i64 = + db::query!("SELECT id FROM snapshots WHERE build_id = {f2_id} AND name = {name}").scalar().await?.unwrap(); + let all = app::domain::snapshots::of_build(f2.id).await?; + let approved: Vec<&app::models::Snapshot> = all.iter().filter(|s| s.id == home).collect(); + baselines::record(&f2, &approved, None, None, "review").await?; + let f3 = w + .build_into( + &app, + "f3", + "feature", + "main", + &["f2", "f1", "m1", "m0"], + &[("web/home", GREEN), ("web/about", RED)], + ) + .await; + assert_eq!(f3.conclusion.as_deref(), Some("unchanged"), "{:?}", states(&f3).await?); + Ok(()) +} + +/// A pull request built on top of the default branch's unreviewed build compares with the approved build underneath, +/// and still says which of its changes are that build's own unreviewed ones. +#[laravel::test] +async fn a_pull_request_on_an_unreviewed_main_build_marks_the_inherited_changes( + app: Application, +) -> laravel::Result<()> { + let w = world().await?; + let m1 = w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + assert_eq!(m2.review_state, "pending"); + let pr = w + .build_into(&app, "f1", "feature", "main", &["m2", "m1", "m0"], &[("web/home", GREEN), ("web/about", BLUE)]) + .await; + assert_eq!(pr.base_build_id, Some(m1.id)); + assert_eq!(states(&pr).await?, vec![("web/about".into(), "changed".into()), ("web/home".into(), "changed".into())]); + let found = inherited::of_build(&pr, &w.project).await?.expect("main's unreviewed change is marked"); + assert_eq!((found.build, found.snapshot_ids.len()), (m2.number, 1)); + Ok(()) +} + +/// A rerun of only the failed jobs leaves an empty build that follows the earlier build of its commit (sc-9044) and +/// shows its review state, approved included. It holds no snapshots, so it's never what a later build compares with: +/// that's the build it follows. +#[laravel::test] +async fn a_build_that_follows_another_is_never_the_base(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let f1 = + w.build_into(&app, "f1", "feature", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + let f1 = w.approve(f1).await; + let follower = w.build_into(&app, "f1", "feature", "main", &["m1", "m0"], &[]).await; + assert_eq!((follower.covered_by_build_id, follower.review_state.as_str()), (Some(f1.id), "approved")); + + let f2 = w + .build_into(&app, "f2", "feature", "main", &["f1", "m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]) + .await; + assert_eq!(f2.base_build_id, Some(f1.id), "the build it follows, not the empty follower"); + assert_eq!(f2.conclusion.as_deref(), Some("unchanged"), "{:?}", states(&f2).await?); + Ok(()) +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index 90e4a5de..766e7842 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -83,11 +83,18 @@ "readOnlyHint": false, "title": "Create build" }, - "description": "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the baseline from the branch's ancestors (or the default branch).", + "description": "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the approved baseline from the branch's ancestors, else the pull request's base branch (`base_branch`), else the default branch.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { + "base_branch": { + "description": "The branch the pull request merges into: the build compares with what it approved. Default: the project's\ndefault branch.", + "type": [ + "string", + "null" + ] + }, "branch": { "type": "string" }, diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index 90e4a5de..766e7842 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -83,11 +83,18 @@ "readOnlyHint": false, "title": "Create build" }, - "description": "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the baseline from the branch's ancestors (or the default branch).", + "description": "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the approved baseline from the branch's ancestors, else the pull request's base branch (`base_branch`), else the default branch.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "properties": { + "base_branch": { + "description": "The branch the pull request merges into: the build compares with what it approved. Default: the project's\ndefault branch.", + "type": [ + "string", + "null" + ] + }, "branch": { "type": "string" }, diff --git a/docs/design.md b/docs/design.md index b0e27a0a..8bcd5264 100644 --- a/docs/design.md +++ b/docs/design.md @@ -212,20 +212,35 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of ## Baselines and review - **Baselines are per snapshot**, in two layers (`domain::baselines`): - 1. The **anchor**: the nearest ancestor commit's completed CI build of the suite (else the default branch's latest - approved one). Every build records every snapshot, so the anchor has each one's approved state at that commit: an - approved change is its new version, an unapproved change the version it was compared with, an unchanged snapshot - itself. The anchor is the build shown as "compared with #N", and its approved visualci.yml is what a config - change is compared with. + 1. The **anchor**: the nearest ancestor commit's approved CI build of the suite, else the newest approved one on the + build's **base branch** (`builds.base_branch`: the branch its pull request merges into, the API's and MCP + `create_build`'s `base_branch`), else on the default branch. Every build records + every snapshot, so the anchor has each one's approved state at that commit. The anchor is the build shown as + "compared with #N", and its approved visualci.yml is what a config change is compared with. **Only an approved + build is ever an anchor** (approved in review, or approved on its own: the default branch's first build, or one + with no changes); never a pending, rejected or failed one, the pull request's own earlier run included. A pending + anchor once stood for whatever it had been compared with: a rerun of a pull request's commit compared with its + own unreviewed build, and so with a branch that wasn't the default any more, hiding the pull request's changes + (sc-9247, the daisyUI case study). An empty build that follows another (`covered_by_build_id`, a rerun of failed + jobs) is never an anchor either: it mirrors that build's review state but holds no snapshots, and that build is on + the same commit. Per-snapshot approvals of a pending build aren't lost: they're rows in + `baselines`, laid on top below. 2. **Approvals since** (`baselines` table, one row per approved change or removal, with build, commit, branch, environment and mode): rows newer than the anchor are laid on top, CI approvals on the build's ancestry and any approval on its own branch. Approving three of four changes keeps those three. Rejecting withdraws the rows. + For local environments, CI approvals on the base and default branches count too. 3. **Merges**: the GitHub App's `pull_request` webhook (`/webhooks/github`) copies a merged pull request's current CI approvals to the base branch at the merge commit (rows with approval `merged`). They count for builds whose history has the merge commit and whose anchor doesn't, so a squash merge doesn't ask for the same approvals again, and a later approval on the base branch wins. Installation events keep projects' installations current. This is the only way a pull request's approvals reach its base branch: a build never takes approvals from a branch outside its history. +- **A pull request compares with its base branch.** A pull request into a release branch, a stacked pull request, or + a fork whose default branch differs compares with what its base branch approved (the merge-base's approved build when + the history reaches it, else the base branch's newest approved build), not the default branch's baseline; the + default branch only when nothing names a base or the base branch has no approved build. For that build the base + branch counts as the default branch does: in the anchor's walk back, local environments' rows and the exact-match + passes (sc-9247: a PR into `replay/c1e1e11-base` compared with the default branch's daisyUI 5.8.3). - **Nothing becomes a baseline unreviewed.** A CI build with nothing to compare against is approved on its own only on the project's default branch (`projects.default_branch`): that first build is the baseline. A pull request branch's first build with no base waits for review like any change, and its approval reaches the default branch at @@ -236,8 +251,8 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of laptop's approved PDFs and text, with "approved locally by … on …" on the snapshot. From a working tree with uncommitted changes, an approval sets only that environment's screenshots. A local build can't use the `ci` environment, nor a CI build a `local-*` one. Exact-match passes (an image or text approved in another environment) - use only current rows: CI approvals on the default branch or the build's own branch's, not superseded, never - another branch's. + use only current rows: CI approvals on the default branch, the build's base branch or the build's own branch's, not + superseded, never another branch's. - **Environments**: `ci`, `local-mac`, `local-linux` (the CLI detects them: a CI provider or `CI=true` means `ci`, else the OS; `VISUALCI_ENVIRONMENT` overrides). Only client-made images (screenshots) keep a set per environment; documents are rendered on VisualCI's servers and text is the same everywhere, so they share one set @@ -256,8 +271,9 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of PR's build changed and approved (the same box, the same old and new pixels) points at that build (`snapshots.matches_build_id`, `domain::matching`, found while processing): "matches PR #8's approved change", a hint that approves nothing; `review` with `only: "matching"` approves those (sc-8785). -- A pull request build compared on top of an unreviewed default-branch build shows that build's changes again. Those - that are exactly the base build's unreviewed change (the same snapshot and new content) are marked +- A pull request build on top of an unreviewed base-branch build (the nearest build on its history, newer than the + approved anchor it's compared with) shows that build's changes again. Those that are exactly that build's unreviewed + change (the same snapshot and new content) are marked (`domain::inherited`, `on_main_unreviewed`) and the build says "N changes are already on main and unreviewed (build #X)", linking there. Approval and the check still go by approved baselines (sc-8770). - Partial approval per snapshot. "Accept as variant" adds the image to the name's variants without replacing the diff --git a/frontend/content/docs/reference/api.md b/frontend/content/docs/reference/api.md index 14a4bf7a..6a942b14 100644 --- a/frontend/content/docs/reference/api.md +++ b/frontend/content/docs/reference/api.md @@ -16,6 +16,7 @@ All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer "commit": "3f9c2e1…", "branch": "add-tax-breakdown", "pr_number": 412, + "base_branch": "main", "parent_commits": ["a81b0c4…", "77de2f9…"], "mode": "ci", "name": "default", @@ -25,7 +26,7 @@ All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer } ``` -`commit` and `branch` are required. `parent_commits` are ancestor commits, nearest first, for finding the baseline. Builds created with the same `nonce` are the same build. `config` is the repository's [`visualci.yml`](/docs/reference/config/) as JSON: its fields override the project's settings for this build, and a build with an invalid one is refused. The response is a build (below). +`commit` and `branch` are required. `parent_commits` are ancestor commits, nearest first, for finding the baseline: the build compares with the approved build of the nearest one. `base_branch` is the branch a pull request merges into: without an approved build in the history sent, the build compares with that branch's newest approved build, and with the default branch's when it names none or that branch has none. Only an approved build is ever compared with. Builds created with the same `nonce` are the same build. `config` is the repository's [`visualci.yml`](/docs/reference/config/) as JSON: its fields override the project's settings for this build, and a build with an invalid one is refused. The response is a build (below). ## Add snapshots From c6ce072c6065ec6f311fa1b1dd5a77eea5dc4e14 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 19:37:32 +1300 Subject: [PATCH 2/2] app/: review fixes for sc-9247: approvals nearer than the anchor's commit count, base_branch only on PR builds, the default branch only through history when a base is named, inherited looks on the base branch itself --- .../2026_12_07_000000_build_base_branch.rs | 3 +- app/src/domain/baselines.rs | 111 ++++++++++---- app/src/domain/builds.rs | 7 +- app/src/domain/compare.rs | 34 +++-- app/src/domain/inherited.rs | 31 ++-- app/tests/baselines.rs | 136 +++++++++++++++++- docs/design.md | 24 ++-- 7 files changed, 277 insertions(+), 69 deletions(-) diff --git a/app/database/migrations/2026_12_07_000000_build_base_branch.rs b/app/database/migrations/2026_12_07_000000_build_base_branch.rs index 6a57b2cd..03b935c0 100644 --- a/app/database/migrations/2026_12_07_000000_build_base_branch.rs +++ b/app/database/migrations/2026_12_07_000000_build_base_branch.rs @@ -4,6 +4,7 @@ use laravel::db::AnyTransaction; pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { - tx.query("ALTER TABLE builds ADD COLUMN base_branch TEXT").unprepared().await?; + // 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(()) } diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index 733b966b..6e8351b2 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -16,7 +16,8 @@ //! 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. A pull request's base -//! branch counts as the default branch does for it: its CI approvals are the pull request's starting point. +//! 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 @@ -47,31 +48,43 @@ pub fn ancestry(build: &Build) -> Vec { } /// 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. +/// 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).unwrap_or(&project.default_branch) + 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 a build starts from besides its own: its base branch and the default branch. -fn starting_branches<'a>(build: &'a Build, project: &'a Project) -> Vec<&'a str> { - let mut out = vec![base_branch(build, project)]; - if out[0] != project.default_branch { - out.push(&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 { + 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 completed CI build of this suite, whatever its review: approved builds only when -/// `approved_only`. 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_on_ancestry(build: &Build, approved_only: bool) -> laravel::Result> { +/// 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> { let commits = ancestry(build); let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); let candidates: Vec = 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 (NOT {approved_only} OR review_state IN ('approved', 'auto_approved')) ORDER BY id DESC" + AND review_state IN ('approved', 'auto_approved') ORDER BY id DESC" ) .select_as() .await?; @@ -86,11 +99,13 @@ async fn nearest_on_ancestry(build: &Build, approved_only: bool) -> laravel::Res /// # Errors /// On a database error. pub async fn anchor(build: &Build, project: &Project) -> laravel::Result> { - if let Some(best) = nearest_on_ancestry(build, true).await? { + 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); - for branch in starting_branches(build, project) { + 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 = 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 \ @@ -105,13 +120,37 @@ pub async fn anchor(build: &Build, project: &Project) -> laravel::Result laravel::Result> { - nearest_on_ancestry(build, false).await +pub async fn nearest_pending_on(build: &Build, branch: &str) -> laravel::Result> { + let commits = ancestry(build); + let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); + let candidates: Vec = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \ + 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?; + 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 { + let (project_id, name) = (build.project_id, build.name.as_str()); + let found: Option = db::query!( + "SELECT 1 FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' AND branch = {branch} \ + LIMIT 1" + ) + .scalar() + .await?; + Ok(found.is_some()) } /// What a build says about one snapshot's approved state. @@ -174,12 +213,12 @@ async fn effective( for_build: &Build, project: &Project, ) -> laravel::Result> { - // Only builds on the resolving build's history count: its ancestors, its branch, its base and default branches. + // 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 = ancestry(for_build).into_iter().collect(); - let starting = starting_branches(for_build, project); - let counts = |b: &Build| { - ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || starting.contains(&b.branch.as_str()) - }; + 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> = None; let mut seen = HashSet::new(); @@ -240,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 = 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 base and default branches only CI approvals count for other branches. - let history = ancestry(build); - let starting: Vec = starting_branches(build, project).into_iter().map(str::to_string).collect(); + // 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 = 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 IN ({...starting}) AND mode = 'ci'))) \ + OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch IN ({...trusted}) AND mode = 'ci'))) \ ) ORDER BY id" ) .select_as() @@ -269,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); diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index 4f236949..ec4961c5 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -149,8 +149,11 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option 255 || b.chars().any(char::is_control)) { return invalid("base_branch must be at most 255 characters"); } - // A base branch that's the build's own branch names nothing. - let base_branch = params.base_branch.clone().filter(|b| !b.is_empty() && *b != params.branch); + // 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"); } diff --git a/app/src/domain/compare.rs b/app/src/domain/compare.rs index bf1d7137..9d5bc6d7 100644 --- a/app/src/domain/compare.rs +++ b/app/src/domain/compare.rs @@ -13,10 +13,10 @@ use crate::models::{Blob, IgnoredChange, Project, Snapshot, Variant}; use crate::storage::BlobStore; /// The exact-match passes below take a baseline row `bl` only when it's current for the snapshot's build: the same -/// suite, a CI approval on the default branch or the build's base branch (its pull request's target), or one from the -/// build's own branch (local approvals count on their own branch only, and another branch's never count), and not -/// superseded by a later approval of the same snapshot on the same branch and environment. (Rejected approvals are -/// deleted.) +/// suite, a CI approval on the build's base branch (`baselines::base_branch`: its pull request's target, else the +/// default branch) or on the default branch at a commit in the build's history, or one from the build's own branch +/// (local approvals count on their own branch only, and another branch's never count), and not superseded by a later +/// approval of the same snapshot on the same branch and environment. (Rejected approvals are deleted.) /// The snapshot's pages: a document's rendered pages, or an image or a text as a single page. /// /// # Errors @@ -221,16 +221,19 @@ async fn page_state( if base.text == head.text { return Ok(("unchanged", None, None)); } - // Exactly this text was approved for this snapshot on the build's own, base or default branch (in + // Exactly this text was approved for this snapshot on the build's own or base branch (in // another environment, or before a change since): it passes, as an image would. let fingerprint = snapshot.source_fingerprint.as_str(); let approved: Option = db::query!( "SELECT 1 FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} \ AND s.source_fingerprint = {fingerprint} AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ - AND (bl.branch = (SELECT branch FROM builds WHERE id = {build_id}) \ - OR (bl.mode = 'ci' AND (bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}) \ - OR bl.branch = (SELECT base_branch FROM builds WHERE id = {build_id})))) \ + AND EXISTS (SELECT 1 FROM builds b JOIN projects pr ON pr.id = b.project_id WHERE b.id = {build_id} \ + AND (bl.branch = b.branch OR (bl.mode = 'ci' AND ( \ + bl.branch = CASE WHEN b.pr_number IS NOT NULL AND COALESCE(b.base_branch, '') NOT IN ('', b.branch) \ + AND b.branch <> pr.default_branch THEN b.base_branch ELSE pr.default_branch END \ + OR (bl.branch = pr.default_branch AND (bl.commit_sha = b.commit_sha \ + OR b.parent_commits @> jsonb_build_array(bl.commit_sha))))))) \ AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) LIMIT 1" @@ -260,9 +263,9 @@ async fn page_state( } // Approved before: a current baseline, in any environment, on the build's own branch or the default branch, with // exactly this image for this snapshot: its own environment's first, then CI's. Covers other environments (a Linux - // agent's screenshot that matches the approved Mac one passes). The build's base branch (its pull request's target) - // counts as the default branch does. Another branch's approvals never count: a pull request's reach its base branch - // only at its merge (`baselines::record_merge`). + // agent's screenshot that matches the approved Mac one passes). The build's base branch (its pull request's target, + // else the default branch) counts, and the default branch through the build's history. Another branch's approvals + // never count: a pull request's reach its base branch only at its merge (`baselines::record_merge`). let image = head.image.as_str(); let environment = snapshot.environment.as_str(); let approved: Option = db::query!( @@ -270,9 +273,12 @@ async fn page_state( JOIN snapshots s ON s.id = bl.snapshot_id JOIN snapshot_pages p ON p.snapshot_id = s.id \ WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} AND p.head_image = {image} \ AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ - AND (bl.branch = (SELECT branch FROM builds WHERE id = {build_id}) \ - OR (bl.mode = 'ci' AND (bl.branch = (SELECT default_branch FROM projects WHERE id = {project_id}) \ - OR bl.branch = (SELECT base_branch FROM builds WHERE id = {build_id})))) \ + AND EXISTS (SELECT 1 FROM builds b JOIN projects pr ON pr.id = b.project_id WHERE b.id = {build_id} \ + AND (bl.branch = b.branch OR (bl.mode = 'ci' AND ( \ + bl.branch = CASE WHEN b.pr_number IS NOT NULL AND COALESCE(b.base_branch, '') NOT IN ('', b.branch) \ + AND b.branch <> pr.default_branch THEN b.base_branch ELSE pr.default_branch END \ + OR (bl.branch = pr.default_branch AND (bl.commit_sha = b.commit_sha \ + OR b.parent_commits @> jsonb_build_array(bl.commit_sha))))))) \ AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ diff --git a/app/src/domain/inherited.rs b/app/src/domain/inherited.rs index 8b53a8c1..1916d7a1 100644 --- a/app/src/domain/inherited.rs +++ b/app/src/domain/inherited.rs @@ -36,21 +36,36 @@ impl Inherited { } } -/// The build's changes that are an unreviewed base-branch build's unreviewed changes: the nearest build on its history -/// is one of the base branch's (`baselines::base_branch`), still waiting for review and newer than the build it was -/// compared with, and this build isn't on that branch. `None` when there are none. +/// The build's changes that are an unreviewed base-branch build's unreviewed changes: the nearest build of the base +/// branch (`baselines::base_branch`, or the default branch when the named one has no builds) on this build's history +/// that's still waiting for review, when it's nearer than the approved build this one was compared with, and this +/// build isn't on that branch. The pull request's own earlier builds don't count. `None` when there are none. /// /// # Errors /// On a database error. pub async fn of_build(build: &Build, project: &Project) -> laravel::Result> { - let base_branch = super::baselines::base_branch(build, project); + let named = super::baselines::base_branch(build, project); + let base_branch = if named == project.default_branch || super::baselines::branch_has_builds(build, named).await? { + named + } else { + project.default_branch.as_str() + }; if build.branch == base_branch { return Ok(None); } - let Some(base) = super::baselines::nearest(build).await? else { return Ok(None) }; - let newer = build.base_build_id.is_none_or(|compared_with| base.id > compared_with); - if base.branch != base_branch || base.review_state != "pending" || !newer || base.id > build.id { - return Ok(None); + let Some(base) = super::baselines::nearest_pending_on(build, base_branch).await? else { return Ok(None) }; + // Nearer than the anchor in this build's history (or, at the same commit, newer): else the anchor already holds + // whatever was approved since. + if let Some(anchor) = match build.base_build_id { + Some(id) => Build::find(id).await?, + None => None, + } { + let history = super::baselines::ancestry(build); + let at = |sha: &str| history.iter().position(|c| c == sha).unwrap_or(usize::MAX); + let (pending_at, anchor_at) = (at(&base.commit_sha), at(&anchor.commit_sha)); + if pending_at > anchor_at || (pending_at == anchor_at && base.id < anchor.id) { + return Ok(None); + } } // The base build's changes that nobody has approved, by snapshot. let pending: HashMap<(String, String), Snapshot> = super::snapshots::of_build(base.id) diff --git a/app/tests/baselines.rs b/app/tests/baselines.rs index 3def61d3..93604592 100644 --- a/app/tests/baselines.rs +++ b/app/tests/baselines.rs @@ -65,7 +65,20 @@ impl World { parents: &[&str], files: &[(&str, [u8; 3])], ) -> Build { - Box::pin(self.build_inner(app, commit, branch, Some(base), parents, files)).await + Box::pin(self.build_inner(app, commit, branch, Some((base, Some(1))), parents, files)).await + } + + /// [`World::build`] for a push (no pull request) that names a base branch anyway. + async fn build_naming( + &self, + app: &Application, + commit: &str, + branch: &str, + base: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + Box::pin(self.build_inner(app, commit, branch, Some((base, None)), parents, files)).await } async fn build_inner( @@ -73,15 +86,18 @@ impl World { app: &Application, commit: &str, branch: &str, - base: Option<&str>, + // The base branch it names, and its pull request. + base: Option<(&str, Option)>, parents: &[&str], files: &[(&str, [u8; 3])], ) -> Build { let auth = format!("Bearer {}", self.token); let mut body = json!({ "commit": commit, "branch": branch, "parent_commits": parents }); - if let Some(base) = base { + if let Some((base, pr)) = base { body["base_branch"] = json!(base); - body["pr_number"] = json!(1); + if let Some(pr) = pr { + body["pr_number"] = json!(pr); + } } let created = app.post("/api/v1/builds").header("authorization", &auth).json(body).await; created.assert_ok(); @@ -357,3 +373,115 @@ async fn a_build_that_follows_another_is_never_the_base(app: Application) -> lar assert_eq!(f2.conclusion.as_deref(), Some("unchanged"), "{:?}", states(&f2).await?); Ok(()) } + +/// Review of #178: a pull request build approved in part before the default branch built its parent commit keeps +/// those approvals when its next build anchors on that later (higher-id) build: an approval is newer than the anchor +/// when its commit is nearer in the build's history, whatever its id. +#[laravel::test] +async fn a_partial_approval_survives_a_later_anchor_on_an_older_commit(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + // The pull request changes the home page and removes the about page. + let p1 = w.build_into(&app, "p1", "feature", "main", &["m2", "m1", "m0"], &[("web/home", GREEN)]).await; + assert_eq!(states(&p1).await?, vec![("web/about".into(), "removed".into()), ("web/home".into(), "changed".into())]); + // The reviewer approves only the removal (a removal has no image for an exact match to find). + let all = app::domain::snapshots::of_build(p1.id).await?; + let about: Vec<&app::models::Snapshot> = all.iter().filter(|s| s.name == "web/about").collect(); + baselines::record(&p1, &about, None, None, "review").await?; + // main builds the pull request's parent commit afterwards, and it's approved (nothing changed). + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", RED), ("web/about", RED)]).await; + assert_eq!(m2.review_state, "auto_approved"); + assert!(m2.id > p1.id); + + let p2 = w.build_into(&app, "p2", "feature", "main", &["p1", "m2", "m1", "m0"], &[("web/home", GREEN)]).await; + assert_eq!(p2.base_build_id, Some(m2.id)); + assert_eq!( + states(&p2).await?, + vec![("web/home".into(), "changed".into())], + "the approved removal stays approved; the home page still waits" + ); + Ok(()) +} + +/// Review of #178: a push build (no pull request) that names a base branch takes nothing from it: an unmerged branch's +/// approval mustn't pass a change on main. +#[laravel::test] +async fn a_push_build_naming_a_base_branch_takes_nothing_from_it(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let x = w.build(&app, "x1", "feature-x", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + w.approve(x).await; + let m2 = w + .build_naming(&app, "m2", "main", "feature-x", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]) + .await; + assert_eq!(m2.base_branch, None, "not stored without a pull request"); + assert_eq!( + states(&m2).await?, + vec![("web/about".into(), "unchanged".into()), ("web/home".into(), "changed".into())], + "feature-x's approval doesn't pass main's change" + ); + Ok(()) +} + +/// Review of #178: a pull request into release-1 takes the default branch's approvals only through its history, never +/// a newer main approval that release-1 doesn't have. +#[laravel::test] +async fn a_pull_request_into_a_release_branch_ignores_mains_newer_approvals(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let r1 = w.build(&app, "r1", "release-1", &["m1", "m0"], &[("web/home", RED), ("web/about", RED)]).await; + assert_eq!(r1.review_state, "auto_approved"); + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + w.approve(m2).await; + + let pr = w + .build_into(&app, "f1", "fix", "release-1", &["r1", "m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]) + .await; + assert_eq!(pr.base_build_id, Some(r1.id)); + assert_eq!( + states(&pr).await?, + vec![("web/about".into(), "unchanged".into()), ("web/home".into(), "changed".into())], + "main approved green at a commit release-1 doesn't have: still a change for release-1" + ); + Ok(()) +} + +/// Review of #178: from a pull request's second build on, its own earlier build is nearer in its history than the +/// base branch's unreviewed build; the inherited changes are still found on the base branch itself. +#[laravel::test] +async fn inherited_changes_are_found_from_the_pull_requests_second_build_on(app: Application) -> laravel::Result<()> { + let w = world().await?; + let m1 = w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + assert_eq!(m2.review_state, "pending"); + w.build_into(&app, "f1", "feature", "main", &["m2", "m1", "m0"], &[("web/home", GREEN), ("web/about", BLUE)]).await; + let f2 = w + .build_into( + &app, + "f2", + "feature", + "main", + &["f1", "m2", "m1", "m0"], + &[("web/home", GREEN), ("web/about", BLUE)], + ) + .await; + assert_eq!(f2.base_build_id, Some(m1.id)); + let found = inherited::of_build(&f2, &w.project).await?.expect("main's unreviewed change is still marked"); + assert_eq!((found.build, found.snapshot_ids.len()), (m2.number, 1)); + Ok(()) +} + +/// Review of #178: a base branch with no builds at all (a wrong name, or one VisualCI never built) leaves the inherited +/// changes to the default branch, as the anchor falls back to it. +#[laravel::test] +async fn inherited_falls_back_to_the_default_branch_for_an_unbuilt_base(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "m1", "main", &["m0"], &[("web/home", RED), ("web/about", RED)]).await; + let m2 = w.build(&app, "m2", "main", &["m1", "m0"], &[("web/home", GREEN), ("web/about", RED)]).await; + let pr = w + .build_into(&app, "f1", "feature", "develop", &["m2", "m1", "m0"], &[("web/home", GREEN), ("web/about", BLUE)]) + .await; + let found = inherited::of_build(&pr, &w.project).await?.expect("main's unreviewed change is marked"); + assert_eq!((found.build, found.snapshot_ids.len()), (m2.number, 1)); + Ok(()) +} diff --git a/docs/design.md b/docs/design.md index 8bcd5264..cb2d904b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -214,7 +214,8 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of - **Baselines are per snapshot**, in two layers (`domain::baselines`): 1. The **anchor**: the nearest ancestor commit's approved CI build of the suite, else the newest approved one on the build's **base branch** (`builds.base_branch`: the branch its pull request merges into, the API's and MCP - `create_build`'s `base_branch`), else on the default branch. Every build records + `create_build`'s `base_branch`; ignored without a pull request or on the default branch), else on the default + branch. Every build records every snapshot, so the anchor has each one's approved state at that commit. The anchor is the build shown as "compared with #N", and its approved visualci.yml is what a config change is compared with. **Only an approved build is ever an anchor** (approved in review, or approved on its own: the default branch's first build, or one @@ -227,8 +228,10 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of `baselines`, laid on top below. 2. **Approvals since** (`baselines` table, one row per approved change or removal, with build, commit, branch, environment and mode): rows newer than the anchor are laid on top, CI approvals on the build's ancestry and any - approval on its own branch. Approving three of four changes keeps those three. Rejecting withdraws the rows. - For local environments, CI approvals on the base and default branches count too. + approval on its own branch. "Newer" is by id, or by commit: an approval at a commit nearer than the anchor's in + the build's history counts even when the anchor was built later (a PR build approved in part before main built its + parent commit). Approving three of four changes keeps those three. Rejecting withdraws the rows. For local + environments, CI approvals on the base branch (and the default branch when the anchor came from it) count too. 3. **Merges**: the GitHub App's `pull_request` webhook (`/webhooks/github`) copies a merged pull request's current CI approvals to the base branch at the merge commit (rows with approval `merged`). They count for builds whose history has the merge commit and whose anchor doesn't, so a squash merge doesn't ask for the same approvals @@ -239,8 +242,10 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of a fork whose default branch differs compares with what its base branch approved (the merge-base's approved build when the history reaches it, else the base branch's newest approved build), not the default branch's baseline; the default branch only when nothing names a base or the base branch has no approved build. For that build the base - branch counts as the default branch does: in the anchor's walk back, local environments' rows and the exact-match - passes (sc-9247: a PR into `replay/c1e1e11-base` compared with the default branch's daisyUI 5.8.3). + branch takes the default branch's place in the anchor's walk back, local environments' rows and the exact-match + passes, and the default branch's approvals count only through the build's history (a PR into release-1 never + passes on main's newer approval). (sc-9247: a PR into `replay/c1e1e11-base` compared with the default branch's + daisyUI 5.8.3.) - **Nothing becomes a baseline unreviewed.** A CI build with nothing to compare against is approved on its own only on the project's default branch (`projects.default_branch`): that first build is the baseline. A pull request branch's first build with no base waits for review like any change, and its approval reaches the default branch at @@ -251,8 +256,8 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of laptop's approved PDFs and text, with "approved locally by … on …" on the snapshot. From a working tree with uncommitted changes, an approval sets only that environment's screenshots. A local build can't use the `ci` environment, nor a CI build a `local-*` one. Exact-match passes (an image or text approved in another environment) - use only current rows: CI approvals on the default branch, the build's base branch or the build's own branch's, not - superseded, never another branch's. + use only current rows: CI approvals on the build's base branch (else the default branch), the default branch's at a + commit in its history, or the build's own branch's, not superseded, never another branch's. - **Environments**: `ci`, `local-mac`, `local-linux` (the CLI detects them: a CI provider or `CI=true` means `ci`, else the OS; `VISUALCI_ENVIRONMENT` overrides). Only client-made images (screenshots) keep a set per environment; documents are rendered on VisualCI's servers and text is the same everywhere, so they share one set @@ -271,8 +276,9 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of PR's build changed and approved (the same box, the same old and new pixels) points at that build (`snapshots.matches_build_id`, `domain::matching`, found while processing): "matches PR #8's approved change", a hint that approves nothing; `review` with `only: "matching"` approves those (sc-8785). -- A pull request build on top of an unreviewed base-branch build (the nearest build on its history, newer than the - approved anchor it's compared with) shows that build's changes again. Those that are exactly that build's unreviewed +- A pull request build on top of an unreviewed base-branch build (the base branch's nearest pending build on its + history, nearer than the approved anchor it's compared with; the default branch's when the named base branch has no + builds) shows that build's changes again. Those that are exactly that build's unreviewed change (the same snapshot and new content) are marked (`domain::inherited`, `on_main_unreviewed`) and the build says "N changes are already on main and unreviewed (build #X)", linking there. Approval and the check still go by approved baselines (sc-8770).