: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(visual-review): pin baseline fetch to commit SHA on default branch (#56328)
mendral-app[bot]7e49afe68dea
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex ed01fe8062f8..dcb54c0665ec 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -469,7 +469,9 @@ def _resolve_baselines(repo, run_type: str, branch: str) -> dict[str, str]:return _resolve_baselines_at_ref(repo, github, run_type, branch)-def _resolve_baselines_with_merge_base(repo: Repo, run_type: str, branch: str) -> tuple[dict[str, str], int]:+def _resolve_baselines_with_merge_base(+ repo: Repo, run_type: str, branch: str, commit_sha: str | None = None+) -> tuple[dict[str, str], int]:"""Fetch branch baseline merged with merge-base baseline.The branch baseline tracks approvals. The merge-base baseline@@ -480,6 +482,12 @@ def _resolve_baselines_with_merge_base(repo: Repo, run_type: str, branch: str) -Identifiers previously approved as REMOVED on this branch aretombstoned — healing would otherwise resurrect them from masterand re-flag them as removed on every subsequent run.++ When *commit_sha* is provided and the run is on the default branch,+ the baseline is fetched at that exact commit instead of the branch+ tip. This prevents a race where a newer commit updates the+ baseline file before an older commit's VR run completes.+Returns (merged_baseline, healed_count)."""try:@@ -490,9 +498,13 @@ def _resolve_baselines_with_merge_base(repo: Repo, run_type: str, branch: str) -logger.info("visual_review.no_github_integration", repo_id=str(repo.id))return {}, 0- branch_baseline = _resolve_baselines_at_ref(repo, github, run_type, branch)-default_branch = _get_default_branch(github, repo.repo_full_name)++ # On the default branch, pin the baseline to the exact commit so+ # that back-to-back pushes don't race against each other.+ baseline_ref = commit_sha if (commit_sha and branch == default_branch) else branch+ branch_baseline = _resolve_baselines_at_ref(repo, github, run_type, baseline_ref)+if branch == default_branch:return branch_baseline, 0@@ -811,8 +823,12 @@ def complete_run(run_id: UUID) -> Run:# Fetch baseline merged with merge-base to heal rebase-induced drift.# Branch baseline tracks approvals; merge-base fills entries lost when# git rebase replays a full-file bot commit destructively.+ # Pass commit_sha so default-branch runs fetch the baseline at the+ # exact commit being tested, avoiding races with concurrent pushes.try:- baseline, healed_count = _resolve_baselines_with_merge_base(repo, run.run_type, run.branch)+ baseline, healed_count = _resolve_baselines_with_merge_base(+ repo, run.run_type, run.branch, commit_sha=run.commit_sha+ )except GitHubRateLimitError:# Roll back to PENDING so the caller can retry after the limit resetsRun.objects.filter(id=run_id).update(status=RunStatus.PENDING)diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.pyindex 5570bc48eb5c..7a77b46a08f5 100644--- a/products/visual_review/backend/tests/test_logic.py+++ b/products/visual_review/backend/tests/test_logic.py@@ -351,6 +351,27 @@ class TestRunOperations:removed = run.snapshots.get(identifier="deleted")assert removed.result == SnapshotResult.REMOVED+ def test_complete_run_passes_commit_sha_to_baseline_resolution(self, repo, mocker):+ """complete_run passes run.commit_sha so default-branch baselines are pinned."""+ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="deadbeef123",+ branch="master",+ pr_number=None,+ snapshots=[{"identifier": "A", "content_hash": "h1"}],+ )++ mock_resolve = mocker.patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"A": "h1"}, 0),+ )++ logic.complete_run(run.id)++ mock_resolve.assert_called_once_with(repo, RunType.STORYBOOK, "master", commit_sha="deadbeef123")+def test_create_run_with_purpose(self, repo):run, _ = logic.create_run(repo_id=repo.id,@@ -1673,14 +1694,24 @@ class TestMergeBaseBaselineHealing:return logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test-repo")def _mock_github(- self, mocker, branch_baseline, merge_base_baseline=None, merge_base_sha="abc123", default_branch="master"+ self,+ mocker,+ branch_baseline,+ merge_base_baseline=None,+ merge_base_sha="abc123",+ default_branch="master",+ commit_sha_baselines=None,):mock_github = mocker.MagicMock()mock_github.integration.sensitive_config = {"access_token": "fake"}mock_github.access_token_expired.return_value = Falsemocker.patch("products.visual_review.backend.logic.get_github_integration_for_repo", return_value=mock_github)+ _commit_sha_baselines = commit_sha_baselines or {}+def fake_fetch(github, repo_full_name, file_path, ref):+ if ref in _commit_sha_baselines:+ return {k: {"hash": v} for k, v in _commit_sha_baselines[ref].items()}, f"sha-{ref}"if ref in ("my-branch", default_branch):return {k: {"hash": v} for k, v in branch_baseline.items()}, "sha1"if ref == merge_base_sha:@@ -1746,6 +1777,47 @@ class TestMergeBaseBaselineHealing:assert merged == baselineassert healed == 0+ @pytest.mark.parametrize(+ "commit_sha, expected_baseline",+ [+ ("deadbeef", {"A": "h1"}), # pinned to commit SHA+ (None, {"A": "h1", "B": "h2"}), # falls back to branch tip+ ],+ )+ def test_default_branch_baseline_ref(self, repo, mocker, commit_sha, expected_baseline):+ """Baseline is pinned to commit SHA when provided, otherwise falls back to branch tip."""+ branch_tip_baseline = {"A": "h1", "B": "h2"}+ commit_baseline = {"A": "h1"}+ self._mock_github(+ mocker,+ branch_baseline=branch_tip_baseline,+ default_branch="master",+ commit_sha_baselines={"deadbeef": commit_baseline},+ )++ merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "master", commit_sha=commit_sha)++ assert merged == expected_baseline+ assert healed == 0++ def test_non_default_branch_ignores_commit_sha(self, repo, mocker):+ """On non-default branches, commit_sha is ignored — branch name is used."""+ branch_baseline = {"A": "h1"}+ merge_base_baseline = {"A": "h1", "C": "h3"}+ commit_baseline = {"X": "hx"} # Should NOT be used+ self._mock_github(+ mocker,+ branch_baseline=branch_baseline,+ merge_base_baseline=merge_base_baseline,+ commit_sha_baselines={"deadbeef": commit_baseline},+ )++ merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch", commit_sha="deadbeef")++ # Should use branch baseline + merge-base healing, NOT the commit baseline+ assert merged == {"A": "h1", "C": "h3"}+ assert healed == 1+def test_falls_back_on_merge_base_failure(self, repo, mocker):branch_baseline = {"A": "h1"}self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_sha=None)@@ -1829,6 +1901,61 @@ class TestMergeBaseBaselineHealing:run.refresh_from_db()assert run.metadata.get("baseline_healed_from_merge_base") == 1+ def test_default_branch_race_condition_no_false_removals(self, repo, mocker):+ """Reproduces the race where a newer commit advances the baseline on master.++ Scenario: commit A (posthog-js upgrade) lands on master, then commit B+ (trendlines, adding 6 stories) lands right after. By the time commit A's+ VR run calls complete_run, the branch tip already points at commit B's+ baseline (with 6 extra entries). Without pinning, VR would report 6+ false "removed" snapshots. With pinning, it fetches the baseline at+ commit A's SHA and sees 0 removals.+ """+ # Commit A's baseline: 3 stories+ commit_a_baseline = {"story1": "h1", "story2": "h2", "story3": "h3"}+ # Branch tip (after commit B landed): 3 + 6 = 9 stories+ branch_tip_baseline = {+ **commit_a_baseline,+ "new1": "n1",+ "new2": "n2",+ "new3": "n3",+ "new4": "n4",+ "new5": "n5",+ "new6": "n6",+ }+ self._mock_github(+ mocker,+ branch_baseline=branch_tip_baseline,+ default_branch="master",+ commit_sha_baselines={"commit_a_sha": commit_a_baseline},+ )++ logic.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")+ logic.get_or_create_artifact(repo_id=repo.id, content_hash="h2", storage_path="p/h2")+ logic.get_or_create_artifact(repo_id=repo.id, content_hash="h3", storage_path="p/h3")++ # Commit A's run only has the 3 original stories+ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="commit_a_sha",+ branch="master",+ pr_number=None,+ snapshots=[+ {"identifier": "story1", "content_hash": "h1"},+ {"identifier": "story2", "content_hash": "h2"},+ {"identifier": "story3", "content_hash": "h3"},+ ],+ )++ logic.complete_run(run.id)++ run.refresh_from_db()+ assert run.removed_count == 0+ assert run.new_count == 0+ assert run.changed_count == 0+def test_healing_detects_changed_when_hash_differs(self, repo, mocker):"""Healed entry with different hash shows as changed, not new."""branch_baseline: dict[str, str] = {}