: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): fail merge-queue runs that drop live baselines (#109982)
Julian Bezdc4a9d5fa55e
diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex db83e4149adc..5ee4e7fdd8be 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -222,6 +222,7 @@ Add `--tolerate-drift` to report the drift and still exit 0. Use it on the defau- **`review`** (default) — approvable. Backend posts PR comment prompts; UI surfaces it under "needs review"; CLI gates on unapproved changes.- **`observe`** — tracking only. Backend rejects approval attempts; no PR comment; excluded from "needs review". The commit status is posted green (`success`, "Tracking only…") to a separate, non-gating `… (tracking)` context — never the gating `PostHog Visual Review / {run_type}` one. `purpose` is client-supplied, so greening the gating context would let an observe run bypass branch protection on a PR head SHA; the separate context keeps observe runs informational-only (like `(partial)` runs). The UI hides all approval affordances. Use on master pushes and merge-queue branches, where there's no PR to approve.The commit status never gates, but the exit code of `vr run complete` still does, and that is where a caller chooses. A merge-queue branch renders the tree about to land, so it lets drift fail the job. Master passes `--tolerate-drift` instead.+ A merge-queue run does not heal its baseline file. When the file lacks an entry the merge-base has for a story the run still renders, the merge would delete that baseline from master, so the run fails with the missing identifiers. Restore the entries from master's baseline file and queue the PR again. `vr run complete` exits 1 for a failed run. Only an observe run under `--tolerate-drift` warns and exits 0 instead, so the failure gates the queue but not a master push.### PR commentsdiff --git a/products/visual_review/backend/logic/baselines.py b/products/visual_review/backend/logic/baselines.pyindex 1011a9b69881..527e07ea9843 100644--- a/products/visual_review/backend/logic/baselines.py+++ b/products/visual_review/backend/logic/baselines.py@@ -136,12 +136,13 @@ def _resolve_baselines_with_merge_base(rewrites the full file, and git rebase replays it destructively).Branch entries win on conflict so approvals are preserved.- On a merge-queue branch, healing is limited to identifiers this run- rendered. An entry missing from the branch baseline whose story still- renders is the rebase loss above. An entry missing from both is one the+ A merge-queue branch heals nothing, because the tested file is the one+ that lands. An entry missing for a story the run did not render is one thebranch deleted on purpose, and restoring it only manufactures a REMOVEDthat no one on a queue branch can approve, so it reds the batch and every- pull request sharing it until the deleting one lands.+ pull request sharing it until the deleting one lands. An entry missing for+ a story that still renders would delete a live baseline on merge, so it+ raises BaselineEntriesLostError and the run fails.Ordinary branches keep healing everything, because there the REMOVED isthe review gate: it is how a reviewer is asked to confirm that a story@@ -211,6 +212,13 @@ def _resolve_baselines_with_merge_base(healed = set(healable_merge_base) - set(branch_baseline)merged = {**healable_merge_base, **branch_baseline}+ # The name check only adds failures, so trusting an unverified name cannot skip a gate.+ if on_merge_queue_branch or github_api._MERGE_QUEUE_BRANCH_RE.match(branch):+ # Raw key sets, not `healed`: a tombstoned story that renders again still needs its baseline.+ lost = (set(merge_base_baseline) - set(branch_baseline)) & rendered_identifiers+ if lost:+ raise errors.BaselineEntriesLostError(sorted(lost))+if healed or tombstoned:logger.info("visual_review.baseline_healed",diff --git a/products/visual_review/backend/logic/errors.py b/products/visual_review/backend/logic/errors.pyindex 95947d75588e..940ec5056974 100644--- a/products/visual_review/backend/logic/errors.py+++ b/products/visual_review/backend/logic/errors.py@@ -39,6 +39,24 @@ class HashIntegrityError(Exception):pass+class BaselineEntriesLostError(Exception):+ """A merge-queue branch's baseline file lacks entries for stories that still render.++ The queue tests the tree that lands, so the merge would delete these entries from the+ default branch. Every later full run would then report the stories as new.+ """++ def __init__(self, identifiers: list[str]) -> None:+ self.identifiers = identifiers+ shown = ", ".join(identifiers[:10])+ more = f" and {len(identifiers) - 10} more" if len(identifiers) > 10 else ""+ super().__init__(+ f"The baseline file is missing {len(identifiers)} entries for stories that still render: "+ f"{shown}{more}. Merging would delete them from the default branch. Restore them in the "+ "baseline file from the default branch, then queue the pull request again."+ )++class StaleRunError(Exception):"""Approval blocked because a newer run exists for this PR."""diff --git a/products/visual_review/backend/logic/runs.py b/products/visual_review/backend/logic/runs.pyindex 778228bd283e..ece88ea43e9e 100644--- a/products/visual_review/backend/logic/runs.py+++ b/products/visual_review/backend/logic/runs.py@@ -273,6 +273,13 @@ def complete_run(run_id: UUID) -> Run:# Roll back to PENDING so the caller can retry after the limit resetsRun.objects.filter(id=run_id).update(status=RunStatus.PENDING)raise+ except errors.BaselineEntriesLostError as e:+ from ..tasks.tasks import emit_run_processing_metrics # noqa: PLC0415 — avoids the logic/tasks circular import++ logger.warning("visual_review.baseline_entries_lost", run_id=str(run_id), count=len(e.identifiers))+ finish_processing(run_id, error_message=str(e))+ emit_run_processing_metrics.delay(run.team_id, str(run_id), "baseline_entries_lost", 0)+ return run_queries.get_run(run_id)if healed_count:run.metadata["baseline_healed_from_merge_base"] = healed_countrun.save(using=WRITER_DB, update_fields=["metadata"])diff --git a/products/visual_review/backend/tests/logic/test_baselines.py b/products/visual_review/backend/tests/logic/test_baselines.pyindex 439a77875c6c..8def28aa4a05 100644--- a/products/visual_review/backend/tests/logic/test_baselines.py+++ b/products/visual_review/backend/tests/logic/test_baselines.py@@ -309,10 +309,10 @@ class TestMergeBaseBaselineHealing:assert merged == {"A": "h1", "B": "h2"}assert healed == 0- def test_deleted_branch_still_heals_because_compare_uses_the_commit(self, repo, mocker):+ def test_deleted_branch_still_compares_against_the_merge_base_via_the_commit(self, repo, mocker):# The compare API is asked from the same ref the baseline was read at.- # Asking by branch name 404s once the batch resolves, and healing would- # then switch off exactly on the branches that need it.+ # Asking by branch name 404s once the batch resolves, and the lost entry+ # below would then go unnoticed on exactly the branches that land.self._mock_github(mocker,branch_baseline={},@@ -321,16 +321,16 @@ class TestMergeBaseBaselineHealing:commit_sha_baselines={"batch-sha": {"kept": "h1"}},)- merged, healed = baselines._resolve_baselines_with_merge_base(- repo,- "storybook",- "trunk-merge/pr-4242/0c2f75d8",- rendered_identifiers={"kept", "lost-to-rebase"},- commit_sha="batch-sha",- )+ with pytest.raises(errors.BaselineEntriesLostError) as exc_info:+ baselines._resolve_baselines_with_merge_base(+ repo,+ "storybook",+ "trunk-merge/pr-4242/0c2f75d8",+ rendered_identifiers={"kept", "lost-to-rebase"},+ commit_sha="batch-sha",+ )- assert merged == {"kept": "h1", "lost-to-rebase": "h2"}- assert healed == 1+ assert exc_info.value.identifiers == ["lost-to-rebase"]def test_falls_back_on_merge_base_failure(self, repo, mocker):branch_baseline = {"A": "h1"}@@ -487,10 +487,16 @@ class TestMergeBaseBaselineHealing:assert run.new_count == 0assert run.changed_count == 0- def test_merge_queue_batch_deleting_a_story_reports_no_removals(self, repo, mocker):- # The batch tree has the story and its entry gone; the merge base still has- # both. Healing used to restore the entry, and a queue run has no reviewer to- # approve the removal, so every co-batched PR failed until the deleter merged.+ @pytest.mark.parametrize(+ ("rendered", "expected_status"),+ [+ # The batch deleted the story and its entry: nothing to approve, nothing to fail.+ (["kept"], RunStatus.COMPLETED),+ # The story still renders but its entry is gone: merging would delete a live baseline.+ (["kept", "doomed"], RunStatus.FAILED),+ ],+ )+ def test_merge_queue_batch_missing_an_entry(self, repo, mocker, rendered, expected_status):batch_branch = "trunk-merge/pr-4242/0c2f75d8-0c2f-4c2f-8c2f-0c2f75d80c2f"master_baseline = {"kept": "h1", "doomed": "h2"}batch_baseline = {"kept": "h1"}@@ -503,8 +509,8 @@ class TestMergeBaseBaselineHealing:)artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="h2", storage_path="p/h2")- # The batch renders everything except the story it deleted.run, _ = runs.create_run(CreateRunInput(repo_id=repo.id,@@ -512,7 +518,10 @@ class TestMergeBaseBaselineHealing:commit_sha="batch-sha",branch=batch_branch,pr_number=None,- snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],+ snapshots=[+ SnapshotManifestItem(identifier=identifier, content_hash=master_baseline[identifier])+ for identifier in rendered+ ],),team_id=repo.team_id,)@@ -521,9 +530,9 @@ class TestMergeBaseBaselineHealing:runs.complete_run(run.id)run.refresh_from_db()+ assert run.status == expected_statusassert run.removed_count == 0- assert run.new_count == 0- assert run.changed_count == 0+ assert ("doomed" in run.error_message) == (expected_status == RunStatus.FAILED)def test_healing_detects_changed_when_hash_differs(self, repo, mocker):"""Healed entry with different hash shows as changed, not new."""@@ -661,6 +670,15 @@ class TestMergeBaseBaselineHealing:review_state=prior_review_state,)+ if run_branch.startswith("trunk-merge/"):+ # The candidate still renders, so a queue branch missing its entry would delete it on+ # merge. A tombstone does not excuse that: a story that renders needs its baseline.+ with pytest.raises(errors.BaselineEntriesLostError):+ baselines._resolve_baselines_with_merge_base(+ repo, RunType.STORYBOOK, run_branch, rendered_identifiers={"candidate"}+ )+ return+merged, healed = baselines._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, run_branch, rendered_identifiers={"candidate"})diff --git a/products/visual_review/cli/src/outcome.test.ts b/products/visual_review/cli/src/outcome.test.tsindex 36cb36834c2d..02ab2ac0332c 100644--- a/products/visual_review/cli/src/outcome.test.ts+++ b/products/visual_review/cli/src/outcome.test.ts@@ -3,11 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { VisualReviewClient, type Run } from './client.js'import { reportRunOutcome } from './outcome.js'-function run(summary: Partial<Run['summary']> = {}): Run {+function run(summary: Partial<Run['summary']> = {}, fields: Partial<Run> = {}): Run {return {id: 'run-1',branch: 'master',+ status: 'completed',summary: { total: 10, unchanged: 10, changed: 0, new: 0, removed: 0, unresolved: 0, ...summary },+ ...fields,} as Run}@@ -108,17 +110,27 @@ describe('reportRunOutcome', () => {expect(output).toContain('No visual changes')})- it('fails a failed run even though nothing counts as unresolved', async () => {- const exitCode = await reportRunOutcome(- client,- { ...run({ unresolved: 0 }), status: 'failed', error_message: 'hash mismatch' } as Run,- 'https://vr.example.com/run-1',- 'review'- )-- expect(exitCode).toBe(1)- expect(output).toContain('Run failed: hash mismatch')- })+ // --tolerate-drift is for observe drift on master. It must not pass a failed gating review run.+ it.each([+ { purpose: 'observe', tolerateDrift: false, exitCode: 1 },+ { purpose: 'review', tolerateDrift: true, exitCode: 1 },+ { purpose: 'observe', tolerateDrift: true, exitCode: 0 },+ ])(+ 'exits $exitCode for a failed $purpose run with tolerateDrift=$tolerateDrift',+ async ({ purpose, tolerateDrift, exitCode }) => {+ const result = await reportRunOutcome(+ client,+ run({}, { status: 'failed', error_message: 'The baseline file is missing 8 entries.' }),+ 'https://vr.example.com/run-1',+ purpose,+ tolerateDrift+ )++ expect(result).toBe(exitCode)+ expect(output).toContain('Run failed: The baseline file is missing 8 entries.')+ expect(output).not.toContain('No visual changes')+ }+ )it('still reports when the snapshot listing fails', async () => {vi.spyOn(client, 'getRunSnapshots').mockRejectedValue(new Error('boom'))diff --git a/products/visual_review/cli/src/outcome.ts b/products/visual_review/cli/src/outcome.tsindex 10fc8c1493a8..b46f7288054e 100644--- a/products/visual_review/cli/src/outcome.ts+++ b/products/visual_review/cli/src/outcome.ts@@ -88,9 +88,10 @@ export async function reportRunOutcome(const changes = s.changed + s.new + s.removed// A failed run counts nothing as unresolved, so the counts below would pass it.+ // --tolerate-drift exempts only observe runs (master pushes), never a gating review run.if (run.status === 'failed') {log(`[run:${runId}] Run failed: ${run.error_message ?? 'no error recorded'} — review at: ${reviewUrl}`)- return tolerateDrift ? 0 : 1+ return tolerateDrift && purpose === 'observe' ? 0 : 1}if (purpose === 'observe') {