Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(visual-review): honor source PR tombstones on merge-queue branches (#75420)

Thomas Obermüllerb8980ef8aa8c
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index fb38358e7e8b..0880f1f670d6 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -578,7 +578,8 @@ def _resolve_baselines_with_merge_base(
if not merge_base_baseline:
return branch_baseline, 0
- tombstoned = _tombstoned_identifiers(repo, run_type, branch)
+ source_pr_number = _verified_merge_queue_source_pr(github, repo.repo_full_name, branch)
+ tombstoned = _tombstoned_identifiers(repo, run_type, branch, source_pr_number=source_pr_number)
healable_merge_base = {k: v for k, v in merge_base_baseline.items() if k not in tombstoned}
healed = set(healable_merge_base) - set(branch_baseline)
@@ -599,7 +600,64 @@ def _resolve_baselines_with_merge_base(
return merged, len(healed)
-def _tombstoned_identifiers(repo: Repo, run_type: str, branch: str) -> set[str]:
+_MERGE_QUEUE_BRANCH_RE = re.compile(r"^trunk-merge/pr-(?P<pr_number>\d+)/")
+
+
+def _verified_merge_queue_source_pr(github: GitHubIntegration, repo_full_name: str, branch: str) -> int | None:
+ """Source PR number for a merge-queue branch, verified against GitHub.
+
+ Merge-queue branches (``trunk-merge/pr-<n>/<uuid>``) are freshly
+ minted per attempt, so tombstones recorded on the source PR would
+ never apply — every queue attempt would re-heal the removed entries
+ and fail the gate. Queue branches therefore also honor the source
+ PR's tombstones.
+
+ The branch name is client-supplied, though, so parsing it alone must
+ not grant cross-PR tombstone inheritance: a caller with a write token
+ could name a branch after an unrelated PR to inherit its approved
+ removals. Require the claimed PR's head commit to be an ancestor of
+ the queue branch — inheriting a PR's approvals then means actually
+ testing that PR's code, which is exactly what Trunk's queue branches
+ do (they merge the PR into the base branch). Fails closed to
+ branch-only scoping.
+ """
+ match = _MERGE_QUEUE_BRANCH_RE.match(branch)
+ if not match:
+ return None
+ pr_number = int(match.group("pr_number"))
+
+ try:
+ response = github.api_request("GET", f"/repos/{repo_full_name}/pulls/{pr_number}")
+ except GitHubIntegrationError:
+ logger.warning("visual_review.merge_queue_source_pr_fetch_failed", repo=repo_full_name, branch=branch)
+ return None
+ if response.status_code != 200:
+ logger.warning(
+ "visual_review.merge_queue_source_pr_fetch_failed",
+ repo=repo_full_name,
+ branch=branch,
+ status=response.status_code,
+ )
+ return None
+
+ pr_head_sha = (response.json().get("head") or {}).get("sha")
+ if not pr_head_sha:
+ return None
+
+ if _get_merge_base_sha(github, repo_full_name, pr_head_sha, branch) != pr_head_sha:
+ logger.warning(
+ "visual_review.merge_queue_source_pr_unverified",
+ repo=repo_full_name,
+ branch=branch,
+ pr_number=pr_number,
+ pr_head_sha=pr_head_sha,
+ )
+ return None
+
+ return pr_number
+
+
+def _tombstoned_identifiers(repo: Repo, run_type: str, branch: str, source_pr_number: int | None = None) -> set[str]:
"""Identifiers whose latest approved outcome on this branch was REMOVED.
Healing pulls entries from merge-base back into the baseline when
@@ -610,15 +668,23 @@ def _tombstoned_identifiers(repo: Repo, run_type: str, branch: str) -> set[str]:
Uses the most recent approved decision per identifier so that a
later re-addition (approved as NEW/CHANGED) clears the tombstone.
+
+ ``source_pr_number`` widens the scope to that PR's runs — pass only a
+ server-verified value (see ``_verified_merge_queue_source_pr``), never
+ one parsed from client-supplied input alone.
"""
from django.db.models import OuterRef, Subquery
+ branch_scope = Q(run__branch=branch)
+ if source_pr_number is not None:
+ branch_scope |= Q(run__pr_number=source_pr_number)
+
latest_approved_run = (
RunSnapshot.objects.using(WRITER_DB)
.filter(
+ branch_scope,
run__repo=repo,
run__run_type=run_type,
- run__branch=branch,
run__approved=True,
review_state=ReviewState.APPROVED,
identifier=OuterRef("identifier"),
@@ -630,9 +696,9 @@ def _tombstoned_identifiers(repo: Repo, run_type: str, branch: str) -> set[str]:
return set(
RunSnapshot.objects.using(WRITER_DB)
.filter(
+ branch_scope,
run__repo=repo,
run__run_type=run_type,
- run__branch=branch,
run__approved=True,
review_state=ReviewState.APPROVED,
result=SnapshotResult.REMOVED,
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index 354096413420..938620d2882f 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -1976,6 +1976,8 @@ class TestMergeBaseBaselineHealing:
merge_base_sha="abc123",
default_branch="master",
commit_sha_baselines=None,
+ pr_head_sha=None,
+ pr_head_is_ancestor=True,
):
mock_github = mocker.MagicMock()
mock_github.integration.sensitive_config = {"access_token": "fake"}
@@ -1994,8 +1996,22 @@ class TestMergeBaseBaselineHealing:
return {k: {"hash": v} for k, v in baselines.items()}, "sha2"
return {}, None
+ pr_response = mocker.MagicMock()
+ if pr_head_sha is None:
+ pr_response.status_code = 404
+ pr_response.json.return_value = {"message": "Not Found"}
+ else:
+ pr_response.status_code = 200
+ pr_response.json.return_value = {"head": {"sha": pr_head_sha}}
+ mock_github.api_request.return_value = pr_response
+
+ def fake_merge_base(github, repo_full_name, base, head):
+ if pr_head_sha is not None and base == pr_head_sha:
+ return pr_head_sha if pr_head_is_ancestor else "unrelated-sha"
+ return merge_base_sha
+
mocker.patch("products.visual_review.backend.logic._fetch_baseline_file", side_effect=fake_fetch)
- mocker.patch("products.visual_review.backend.logic._get_merge_base_sha", return_value=merge_base_sha)
+ mocker.patch("products.visual_review.backend.logic._get_merge_base_sha", side_effect=fake_merge_base)
mocker.patch("products.visual_review.backend.logic._get_default_branch", return_value=default_branch)
mocker.patch(
"products.visual_review.backend.logic._verify_baseline_hashes", side_effect=lambda repo, hashes: hashes
@@ -2256,27 +2272,101 @@ class TestMergeBaseBaselineHealing:
assert snapshot.baseline_hash == "master_hash"
@pytest.mark.parametrize(
- "prior_branch, prior_run_type, prior_approved, prior_review_state, expect_tombstoned",
+ "run_branch, prior_branch, prior_pr_number, prior_run_type, prior_approved, prior_review_state, pr_head_sha, pr_head_is_ancestor, expect_tombstoned",
[
- ("my-branch", RunType.STORYBOOK, True, ReviewState.APPROVED, True),
- ("someone-else", RunType.STORYBOOK, True, ReviewState.APPROVED, False),
- ("my-branch", "playwright", True, ReviewState.APPROVED, False),
- ("my-branch", RunType.STORYBOOK, False, ReviewState.PENDING, False),
+ ("my-branch", "my-branch", None, RunType.STORYBOOK, True, ReviewState.APPROVED, None, True, True),
+ ("my-branch", "someone-else", None, RunType.STORYBOOK, True, ReviewState.APPROVED, None, True, False),
+ ("my-branch", "my-branch", None, "playwright", True, ReviewState.APPROVED, None, True, False),
+ ("my-branch", "my-branch", None, RunType.STORYBOOK, False, ReviewState.PENDING, None, True, False),
+ (
+ "trunk-merge/pr-42/0c0ffee",
+ "source-pr-branch",
+ 42,
+ RunType.STORYBOOK,
+ True,
+ ReviewState.APPROVED,
+ "pr42-head",
+ True,
+ True,
+ ),
+ (
+ "trunk-merge/pr-42/0c0ffee",
+ "source-pr-branch",
+ 43,
+ RunType.STORYBOOK,
+ True,
+ ReviewState.APPROVED,
+ "pr42-head",
+ True,
+ False,
+ ),
+ (
+ "trunk-merge/pr-42/0c0ffee",
+ "source-pr-branch",
+ 42,
+ RunType.STORYBOOK,
+ True,
+ ReviewState.APPROVED,
+ "pr42-head",
+ False,
+ False,
+ ),
+ (
+ "trunk-merge/pr-42/0c0ffee",
+ "source-pr-branch",
+ 42,
+ RunType.STORYBOOK,
+ True,
+ ReviewState.APPROVED,
+ None,
+ True,
+ False,
+ ),
+ ("my-branch", "someone-else", 42, RunType.STORYBOOK, True, ReviewState.APPROVED, None, True, False),
+ ],
+ ids=[
+ "approved_on_branch",
+ "wrong_branch",
+ "wrong_run_type",
+ "not_approved",
+ "merge_queue_source_pr",
+ "merge_queue_other_pr",
+ "merge_queue_spoofed_branch_not_ancestor",
+ "merge_queue_source_pr_not_found",
+ "pr_number_ignored_off_queue",
],
- ids=["approved_on_branch", "wrong_branch", "wrong_run_type", "not_approved"],
)
def test_tombstone_excludes_only_approved_removals_on_branch(
- self, repo, team, mocker, prior_branch, prior_run_type, prior_approved, prior_review_state, expect_tombstoned
+ self,
+ repo,
+ team,
+ mocker,
+ run_branch,
+ prior_branch,
+ prior_pr_number,
+ prior_run_type,
+ prior_approved,
+ prior_review_state,
+ pr_head_sha,
+ pr_head_is_ancestor,
+ expect_tombstoned,
):
branch_baseline: dict[str, str] = {}
merge_base_baseline = {"candidate": "h1"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+ self._mock_github(
+ mocker,
+ branch_baseline=branch_baseline,
+ merge_base_baseline=merge_base_baseline,
+ pr_head_sha=pr_head_sha,
+ pr_head_is_ancestor=pr_head_is_ancestor,
+ )
prior_run = Run.objects.create(
team_id=team.id,
repo=repo,
run_type=prior_run_type,
branch=prior_branch,
+ pr_number=prior_pr_number,
commit_sha="prior-sha",
status=RunStatus.COMPLETED,
approved=prior_approved,
@@ -2291,7 +2381,7 @@ class TestMergeBaseBaselineHealing:
review_state=prior_review_state,
)
- merged, healed = logic._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, "my-branch")
+ merged, healed = logic._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, run_branch)
if expect_tombstoned:
assert merged == {}