: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): reduce diff processing overhead (#72179)
Paul D'Ambraa985445843f9
diff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.pyindex cfb24f28c2aa..f6a3bc24441d 100644--- a/products/visual_review/backend/diffing.py+++ b/products/visual_review/backend/diffing.py@@ -9,10 +9,13 @@ Called by the Celery task; all business logic lives here.from uuid import UUID+from django.db.models import Q+import structlogfrom blake3 import blake3from pixelhog import thumbnail as pixelhog_thumbnail+from .db import WRITER_DBfrom .diff import THUMB_HEIGHT, THUMB_WIDTH, CompareResult, compare_imagesfrom .diff_metadata import DiffMetadatafrom .facade.enums import ChangeKind, ClassificationReason, SnapshotResult, ToleratedReason@@ -124,7 +127,7 @@ def _store_diff()-def _diff_snapshot(snapshot: RunSnapshot) -> None:+def _diff_snapshot(snapshot: RunSnapshot) -> bool:"""Compare snapshot against baseline; classify and store diff metrics.Classification (in priority order):@@ -157,7 +160,7 @@ def _diff_snapshot(snapshot: RunSnapshot) -> None:has_baseline=baseline_bytes is not None,has_current=current_bytes is not None,)- return+ return Falseresult = compare_images(baseline_bytes, current_bytes)@@ -166,7 +169,7 @@ def _diff_snapshot(snapshot: RunSnapshot) -> None:kind = classify_compare_result(result)if kind is not None:_store_diff(snapshot, result, kind)- return+ return True# Both tiers below threshold — genuine noise, reclassify and cache for future runssnapshot.result = SnapshotResult.UNCHANGED@@ -201,6 +204,7 @@ def _diff_snapshot(snapshot: RunSnapshot) -> None:"diff_percentage": result.diff_percentage,},)+ return Truedef _generate_thumbnail_for_new(snapshot: RunSnapshot) -> None:@@ -239,16 +243,43 @@ def _generate_thumbnail_for_new(snapshot: RunSnapshot) -> None:artifact.save(update_fields=["thumbnail"])-def process_diffs(run_id: UUID) -> None:+def count_processed_diffs(run_id: UUID) -> int:+ return (+ RunSnapshot.objects.using(WRITER_DB)+ .filter(run_id=run_id)+ .filter(+ ~Q(change_kind="")+ | Q(+ result=SnapshotResult.UNCHANGED,+ classification_reason=ClassificationReason.BELOW_THRESHOLD,+ )+ )+ .count()+ )+++def process_diffs(run_id: UUID) -> int:"""Process diffs for all changed snapshots in a run.Uses single-pass comparison (pixelmatch + SSIM + thumbnail) to classifyeach snapshot and generate thumbnails for the grid view."""- from . import logic-- snapshots = logic.get_run_snapshots(run_id)+ snapshots = (+ RunSnapshot.objects.using(WRITER_DB)+ .filter(run_id=run_id)+ .filter(+ Q(+ result=SnapshotResult.NEW,+ current_artifact__isnull=False,+ current_artifact__thumbnail__isnull=True,+ )+ | Q(result=SnapshotResult.CHANGED, change_kind="", diff_artifact__isnull=True)+ )+ .select_related("run", "current_artifact", "baseline_artifact")+ .iterator(chunk_size=100)+ )+ diffed_count = 0for snapshot in snapshots:if snapshot.result == SnapshotResult.NEW and snapshot.current_artifact:@@ -261,7 +292,8 @@ def process_diffs(run_id: UUID) -> None:continuetry:- _diff_snapshot(snapshot)+ if _diff_snapshot(snapshot):+ diffed_count += 1except Exception as e:logger.warning("visual_review.snapshot_diff_failed",@@ -269,3 +301,5 @@ def process_diffs(run_id: UUID) -> None:identifier=snapshot.identifier,error=str(e),)++ return diffed_countdiff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex af8cc3b9ae37..b68ce1056630 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport reimport htmlfrom collections import Counter-from collections.abc import Iterable, Mapping+from collections.abc import Iterable, Iterator, Mappingfrom dataclasses import dataclassfrom datetime import datetimefrom typing import TYPE_CHECKING@@ -61,6 +61,19 @@ from .storage import ArtifactStoragelogger = structlog.get_logger(__name__)+ARTIFACT_HASH_BATCH_SIZE = 500+++def _iter_batches(values: Iterable[str], batch_size: int) -> Iterator[list[str]]:+ batch: list[str] = []+ for value in values:+ batch.append(value)+ if len(batch) == batch_size:+ yield batch+ batch = []+ if batch:+ yield batch+class RepoNotFoundError(Exception):pass@@ -195,9 +208,11 @@ def get_or_create_artifact(def find_missing_hashes(repo_id: UUID, hashes: list[str]) -> list[str]:"""Return hashes that don't exist as artifacts in the repo."""- existing = set(- Artifact.objects.filter(repo_id=repo_id, content_hash__in=hashes).values_list("content_hash", flat=True)- )+ existing: set[str] = set()+ for hash_batch in _iter_batches(hashes, ARTIFACT_HASH_BATCH_SIZE):+ existing.update(+ Artifact.objects.filter(repo_id=repo_id, content_hash__in=hash_batch).values_list("content_hash", flat=True)+ )return [h for h in hashes if h not in existing]@@ -972,32 +987,39 @@ def verify_uploads_and_create_artifacts(run_id: UUID) -> int:"""from .hashing import ImageTooLargeError, hash_image- run = get_run_with_snapshots(run_id)+ run = get_run(run_id)repo_id = run.repo_idstorage = ArtifactStorage(str(repo_id))# Collect all unique hashes we expect, keyed by the CLI-claimed value.# The claim is treated as a lookup key only — verification below produces# the server-computed hash that becomes authoritative.- expected_hashes: dict[str, dict] = {}- for snapshot in run.snapshots.all():- if snapshot.current_hash and snapshot.current_hash not in expected_hashes:- expected_hashes[snapshot.current_hash] = {- "width": snapshot.current_width,- "height": snapshot.current_height,+ expected_hashes: dict[str, dict[str, int | None]] = {}+ snapshots = run.snapshots.values_list("current_hash", "current_width", "current_height", "baseline_hash")+ for current_hash, current_width, current_height, baseline_hash in snapshots.iterator(chunk_size=1000):+ if current_hash and current_hash not in expected_hashes:+ expected_hashes[current_hash] = {+ "width": current_width,+ "height": current_height,}- if snapshot.baseline_hash and snapshot.baseline_hash not in expected_hashes:- expected_hashes[snapshot.baseline_hash] = {+ if baseline_hash and baseline_hash not in expected_hashes:+ expected_hashes[baseline_hash] = {"width": None,"height": None,}+ existing_hashes: set[str] = set()+ for hash_batch in _iter_batches(expected_hashes, ARTIFACT_HASH_BATCH_SIZE):+ existing_hashes.update(+ Artifact.objects.filter(repo_id=repo_id, content_hash__in=hash_batch).values_list("content_hash", flat=True)+ )+# Pass 1: read + hash all new uploads. Skip existing artifacts. Fail loudly# on any hash mismatch, decode error, or missing upload before any Artifact# row is written.- verified: list[tuple[str, bytes, dict]] = []+ verified: list[tuple[str, int, dict[str, int | None]]] = []for claimed_hash, metadata in expected_hashes.items():- if get_artifact(repo_id, claimed_hash):+ if claimed_hash in existing_hashes:continuepng_bytes = storage.read(claimed_hash)@@ -1052,28 +1074,26 @@ def verify_uploads_and_create_artifacts(run_id: UUID) -> int:f"Upload integrity check failed: claimed {claimed_hash[:16]}… but image hashes to {actual_hash[:16]}…")- verified.append((actual_hash, png_bytes, metadata))+ verified.append((actual_hash, len(png_bytes), metadata))# Pass 2: create Artifact rows from verified server-computed hashes only.# The claimed hash isn't used past this point.- created_count = 0- for actual_hash, png_bytes, metadata in verified:- storage_path = storage._key(actual_hash)- artifact, created = get_or_create_artifact(+ artifacts = [+ Artifact(repo_id=repo_id,content_hash=actual_hash,- storage_path=storage_path,+ storage_path=storage._key(actual_hash),width=metadata.get("width"),height=metadata.get("height"),- size_bytes=len(png_bytes),+ size_bytes=size_bytes,team_id=run.team_id,)+ for actual_hash, size_bytes, metadata in verified+ ]+ Artifact.objects.bulk_create(artifacts, batch_size=ARTIFACT_HASH_BATCH_SIZE, ignore_conflicts=True)+ link_artifacts_to_snapshots(repo_id, set(expected_hashes), run_id=run_id)- if created:- created_count += 1- link_artifact_to_snapshots(repo_id, actual_hash)-- return created_count+ return len(artifacts)def _stamp_quarantine(run: Run) -> None:@@ -1215,7 +1235,7 @@ def finish_processing(run_id: UUID, error_message: str = "") -> Run:return run-def capture_run_processing_metrics(run_id: UUID, *, outcome: str) -> None:+def capture_run_processing_metrics(run_id: UUID, *, outcome: str, diffed_count: int) -> None:"""Emit a product-analytics event for a finished diff-processing run.Records run volume and how many snapshots actually needed a pixel@@ -1250,9 +1270,7 @@ def capture_run_processing_metrics(run_id: UUID, *, outcome: str) -> None:"new_count": run.new_count,"removed_count": run.removed_count,"tolerated_match_count": run.tolerated_match_count,- # Snapshots that actually ran a pixel comparison — the cost the- # content-hash dedup and tolerance cache are meant to keep near zero.- "diffed_count": run.changed_count,+ "diffed_count": diffed_count,"reviewable_count": run.changed_count + run.new_count + run.removed_count,}@@ -1261,6 +1279,7 @@ def capture_run_processing_metrics(run_id: UUID, *, outcome: str) -> None:distinct_id=run.repo.repo_full_name or str(run.repo_id),event="vr_run_processed",properties=properties,+ uuid=run.id,)except Exception:logger.warning("visual_review.metrics_capture_failed", run_id=str(run_id), exc_info=True)@@ -2976,28 +2995,45 @@ def update_snapshot_diff(return snapshot-def link_artifact_to_snapshots(repo_id: UUID, content_hash: str) -> int:+def link_artifacts_to_snapshots(repo_id: UUID, content_hashes: set[str], *, run_id: UUID | None = None) -> int:"""- After an artifact is uploaded, link it to any pending snapshots.+ After artifacts are uploaded, link them to any pending snapshots.Returns number of snapshots updated."""- artifact = get_artifact(repo_id, content_hash)- if not artifact:+ if not content_hashes:return 0- # Link as current artifact where hash matches but artifact not linked- current_updated = RunSnapshot.objects.filter(- run__repo_id=repo_id,- current_hash=content_hash,- current_artifact__isnull=True,- ).update(current_artifact=artifact)-- # Link as baseline artifact where hash matches but artifact not linked- baseline_updated = RunSnapshot.objects.filter(- run__repo_id=repo_id,- baseline_hash=content_hash,- baseline_artifact__isnull=True,- ).update(baseline_artifact=artifact)-- return current_updated + baseline_updated+ updated = 0+ for hash_batch in _iter_batches(content_hashes, ARTIFACT_HASH_BATCH_SIZE):+ artifact_id = Artifact.objects.filter(+ repo_id=repo_id,+ content_hash=db_models.OuterRef("current_hash"),+ ).values("id")[:1]+ current_snapshots = RunSnapshot.objects.filter(+ run__repo_id=repo_id,+ current_hash__in=hash_batch,+ current_artifact__isnull=True,+ )+ if run_id is not None:+ current_snapshots = current_snapshots.filter(run_id=run_id)+ updated += current_snapshots.update(current_artifact_id=db_models.Subquery(artifact_id))++ artifact_id = Artifact.objects.filter(+ repo_id=repo_id,+ content_hash=db_models.OuterRef("baseline_hash"),+ ).values("id")[:1]+ baseline_snapshots = RunSnapshot.objects.filter(+ run__repo_id=repo_id,+ baseline_hash__in=hash_batch,+ baseline_artifact__isnull=True,+ )+ if run_id is not None:+ baseline_snapshots = baseline_snapshots.filter(run_id=run_id)+ updated += baseline_snapshots.update(baseline_artifact_id=db_models.Subquery(artifact_id))++ return updated+++def link_artifact_to_snapshots(repo_id: UUID, content_hash: str) -> int:+ return link_artifacts_to_snapshots(repo_id, {content_hash})diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex a1eb3fbd039b..b3de0c9b28d2 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -43,11 +43,12 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:from posthog.egress.github.transport import GitHubRateLimitErrorfrom .. import logic- from ..diffing import process_diffs+ from ..diffing import count_processed_diffs, process_diffsrun_uuid = UUID(run_id)outcome = "completed"retrying = False+ diffed_count = 0# Phase timings go to OTel spans (where is time spent); counts go to the# vr_run_processed event (how many runs, how many diffs).@@ -59,8 +60,9 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:with TRACER.start_as_current_span("visual_review.verify_uploads"):logic.verify_uploads_and_create_artifacts(run_uuid)- with TRACER.start_as_current_span("visual_review.process_diffs"):- process_diffs(run_uuid)+ with TRACER.start_as_current_span("visual_review.process_diffs") as diff_span:+ diffed_count = process_diffs(run_uuid)+ diff_span.set_attribute("visual_review.attempt_diffed_count", diffed_count)with TRACER.start_as_current_span("visual_review.finish_processing"):logic.finish_processing(run_uuid)@@ -96,7 +98,12 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:span.set_attribute("visual_review.outcome", outcome)# Skip on retry: the run isn't terminal yet and will emit on its next attempt.if not retrying:- logic.capture_run_processing_metrics(run_uuid, outcome=outcome)+ try:+ cumulative_diffed_count = count_processed_diffs(run_uuid)+ except Exception:+ logger.warning("visual_review.diff_count_failed", run_id=run_id, exc_info=True)+ cumulative_diffed_count = diffed_count+ logic.capture_run_processing_metrics(run_uuid, outcome=outcome, diffed_count=cumulative_diffed_count)@shared_task(diff --git a/products/visual_review/backend/tests/test_gating.py b/products/visual_review/backend/tests/test_gating.pyindex 1fac3edcec1c..7fd10f2b4f97 100644--- a/products/visual_review/backend/tests/test_gating.py+++ b/products/visual_review/backend/tests/test_gating.py@@ -18,6 +18,8 @@ covers the entire state space.import pytest+from parameterized import parameterized+from products.visual_review.backend import logicfrom products.visual_review.backend.facade import apifrom products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResult@@ -32,21 +34,21 @@ RESULT_ENUM = {}# fmt: off-# (result, action, gate_passes, expected_changed_count)+# (name, result, action, gate_passes, expected_changed_count)# gate_passes: True when unresolved=0 (action resolves the change or result is unchanged)# expected_changed_count: raw classifier count on the Run model (excludes quarantined only)GATE_CASES = [- pytest.param("unchanged", None, True, 0, id="unchanged"),- pytest.param("changed", None, False, 1, id="changed-unresolved"),- pytest.param("changed", "quarantine", True, 0, id="changed-quarantined"),- pytest.param("changed", "tolerate", True, 1, id="changed-tolerated"),- pytest.param("changed", "approve", True, 1, id="changed-approved"),- pytest.param("new", None, False, 0, id="new-unresolved"),- pytest.param("new", "quarantine", True, 0, id="new-quarantined"),- pytest.param("new", "approve", True, 0, id="new-approved"),- pytest.param("removed", None, False, 0, id="removed-unresolved"),- pytest.param("removed", "quarantine", True, 0, id="removed-quarantined"),- pytest.param("removed", "approve", True, 0, id="removed-approved"),+ ("unchanged", "unchanged", None, True, 0),+ ("changed_unresolved", "changed", None, False, 1),+ ("changed_quarantined", "changed", "quarantine", True, 0),+ ("changed_tolerated", "changed", "tolerate", True, 1),+ ("changed_approved", "changed", "approve", True, 1),+ ("new_unresolved", "new", None, False, 0),+ ("new_quarantined", "new", "quarantine", True, 0),+ ("new_approved", "new", "approve", True, 0),+ ("removed_unresolved", "removed", None, False, 0),+ ("removed_quarantined", "removed", "quarantine", True, 0),+ ("removed_approved", "removed", "approve", True, 0),]# fmt: on@@ -128,22 +130,22 @@ class TestGatingInvariants:return run- @pytest.mark.parametrize("result, action, expected_gate_passes, expected_changed_count", GATE_CASES)- def test_gate_outcome(self, result, action, expected_gate_passes, expected_changed_count):+ @parameterized.expand(GATE_CASES)+ def test_gate_outcome(self, _name, result, action, expected_gate_passes, expected_changed_count):run = self._build_run(result, action)recompute_result = logic.recompute_run(run.id, team_id=self.team.id)gate_passes = recompute_result["unresolved"] == 0assert gate_passes is expected_gate_passes- @pytest.mark.parametrize("result, action, _expected_gate, expected_changed_count", GATE_CASES)- def test_raw_counts_reflect_classifier_truth(self, result, action, _expected_gate, expected_changed_count):+ @parameterized.expand(GATE_CASES)+ def test_raw_counts_reflect_classifier_truth(self, _name, result, action, _expected_gate, expected_changed_count):run = self._build_run(result, action)logic.recompute_run(run.id, team_id=self.team.id)run.refresh_from_db()assert run.changed_count == expected_changed_count- @pytest.mark.parametrize("result, action, _expected_gate, _expected_changed", GATE_CASES)- def test_result_not_mutated_by_action_or_recompute(self, result, action, _expected_gate, _expected_changed):+ @parameterized.expand(GATE_CASES)+ def test_result_not_mutated_by_action_or_recompute(self, _name, result, action, _expected_gate, _expected_changed):run = self._build_run(result, action)logic.recompute_run(run.id, team_id=self.team.id)@@ -151,8 +153,8 @@ class TestGatingInvariants:snapshot.refresh_from_db()assert snapshot.result == RESULT_ENUM[result]- @pytest.mark.parametrize("result, action, _expected_gate, _expected_changed", GATE_CASES)- def test_recompute_is_idempotent(self, result, action, _expected_gate, _expected_changed):+ @parameterized.expand(GATE_CASES)+ def test_recompute_is_idempotent(self, _name, result, action, _expected_gate, _expected_changed):run = self._build_run(result, action)logic.recompute_run(run.id, team_id=self.team.id)diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.pyindex e1ec1811ecaf..354096413420 100644--- a/products/visual_review/backend/tests/test_logic.py+++ b/products/visual_review/backend/tests/test_logic.py@@ -4,9 +4,14 @@ from datetime import timedeltaimport pytest+from django.db import connections+from django.test.utils import CaptureQueriesContextfrom django.utils import timezone+from parameterized import parameterized+from products.visual_review.backend import logic+from products.visual_review.backend.db import WRITER_DBfrom products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, RunStatus, RunType, SnapshotResultfrom products.visual_review.backend.models import Repo, Run, RunSnapshotfrom products.visual_review.backend.tests.conftest import PRODUCT_DATABASES@@ -2430,6 +2435,69 @@ class TestVerifyUploadsAndCreateArtifacts:assert artifact is not Noneassert artifact.content_hash == server_hashassert artifact.size_bytes == len(png)+ snapshot = RunSnapshot.objects.get(run=run)+ assert snapshot.current_artifact_id == artifact.id++ def test_verification_query_count_does_not_grow_per_hash(self, repo, mocker):+ from products.visual_review.backend.hashing import hash_image++ def create_run_with_images(count: int, color_offset: int) -> tuple[Run, dict[str, bytes]]:+ images: dict[str, bytes] = {}+ snapshots: list[dict[str, str]] = []+ for index in range(count):+ png = self._png((color_offset + index, 20, 30, 255))+ content_hash = hash_image(png)+ images[content_hash] = png+ snapshots.append({"identifier": f"Card-{color_offset}-{index}", "content_hash": content_hash})++ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha=f"sha-{count}-{color_offset}",+ branch="main",+ pr_number=None,+ snapshots=snapshots,+ )+ return run, images++ single_run, single_images = create_run_with_images(1, 10)+ mock_read = mocker.patch(+ "products.visual_review.backend.storage.ArtifactStorage.read",+ side_effect=lambda content_hash: single_images.get(content_hash),+ )+ with CaptureQueriesContext(connections[WRITER_DB]) as single_queries:+ logic.verify_uploads_and_create_artifacts(single_run.id)++ scaled_run, scaled_images = create_run_with_images(5, 100)+ mock_read.side_effect = lambda content_hash: scaled_images.get(content_hash)+ with CaptureQueriesContext(connections[WRITER_DB]) as scaled_queries:+ logic.verify_uploads_and_create_artifacts(scaled_run.id)++ assert len(scaled_queries) <= len(single_queries)++ def test_verification_relinks_existing_artifacts_across_hash_batches(self, repo, mocker):+ from products.visual_review.backend.hashing import hash_image++ mocker.patch.object(logic, "ARTIFACT_HASH_BATCH_SIZE", 2)+ snapshots: list[dict[str, str]] = []+ for index, color in enumerate([(10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255)]):+ content_hash = hash_image(self._png(color))+ logic.get_or_create_artifact(repo.id, content_hash, f"visual_review/{content_hash}")+ snapshots.append({"identifier": f"Card-{index}", "content_hash": content_hash})++ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="sha-retry",+ branch="main",+ pr_number=None,+ snapshots=snapshots,+ )++ assert logic.verify_uploads_and_create_artifacts(run.id) == 0+ assert RunSnapshot.objects.filter(run=run, current_artifact__isnull=False).count() == 3def test_hash_mismatch_raises_and_persists_no_artifacts(self, repo, mocker):# Two snapshots: first verifies cleanly, second has a mismatched claim.@@ -2941,14 +3009,13 @@ class TestApprovalComment:cell = logic._image_cell("https://cdn.example/full", "after")assert cell == f'<img src="https://cdn.example/full" width="{logic._COMMENT_IMAGE_WIDTH}" alt="after">'- @pytest.mark.parametrize(- "identifier,expected",+ @parameterized.expand([- ("a|b", "`a\\|b`"), # pipes escaped so the cell stays intact- ("a`b", "`ab`"), # backticks stripped so the code span isn't closed early+ ("pipe", "a|b", "`a\\|b`"), # pipes escaped so the cell stays intact+ ("backtick", "a`b", "`ab`"), # backticks stripped so the code span isn't closed early],)- def test_snapshot_name_cell_escapes_markdown(self, identifier, expected):+ def test_snapshot_name_cell_escapes_markdown(self, _name, identifier, expected):assert logic._snapshot_name_cell(identifier) == expecteddef test_snapshot_name_cell_collapses_control_characters(self):diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.pyindex 76a75d5cbffc..1805c42869ae 100644--- a/products/visual_review/backend/tests/test_tasks.py+++ b/products/visual_review/backend/tests/test_tasks.py@@ -1,15 +1,29 @@"""Tests for visual_review Celery tasks."""+import io+from contextlib import contextmanager+import pytest+from posthog.test.base import BaseTestfrom unittest.mock import patch-from products.visual_review.backend import logic+from parameterized import parameterized+from PIL import Image++from products.visual_review.backend import diffing, logicfrom products.visual_review.backend.diffing import process_diffsfrom products.visual_review.backend.facade import apifrom products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem-from products.visual_review.backend.facade.enums import RunStatus, RunType, SnapshotResult+from products.visual_review.backend.facade.enums import (+ ChangeKind,+ ClassificationReason,+ RunStatus,+ RunType,+ SnapshotResult,+)+from products.visual_review.backend.models import RunSnapshotfrom products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -62,6 +76,28 @@ class TestProcessRunDiffs:assert run.status == RunStatus.FAILEDassert "Something went wrong" in (run.error_message or "")+ def test_metrics_event_uses_run_id_as_uuid(self, repo, mocker):+ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="metrics-uuid",+ branch="main",+ pr_number=None,+ snapshots=[],+ )+ capture = mocker.Mock()++ @contextmanager+ def scoped_capture():+ yield capture++ mocker.patch.object(logic, "ph_scoped_capture", scoped_capture)++ logic.capture_run_processing_metrics(run.id, outcome="completed", diffed_count=0)++ assert capture.call_args.kwargs["uuid"] == run.id+def test_emits_metrics_event_on_success(self, repo):create_result = api.create_run(CreateRunInput(@@ -74,11 +110,16 @@ class TestProcessRunDiffs:team_id=repo.team_id,)- with patch("products.visual_review.backend.logic.capture_run_processing_metrics") as capture:+ with (+ patch("products.visual_review.backend.diffing.process_diffs", return_value=0),+ patch("products.visual_review.backend.diffing.count_processed_diffs", return_value=3),+ patch("products.visual_review.backend.logic.capture_run_processing_metrics") as capture,+ ):process_run_diffs(repo.team_id, str(create_result.run_id))capture.assert_called_once()assert capture.call_args.kwargs["outcome"] == "completed"+ assert capture.call_args.kwargs["diffed_count"] == 3def test_emits_metrics_event_on_failure(self, repo):create_result = api.create_run(@@ -94,6 +135,7 @@ class TestProcessRunDiffs:with (patch("products.visual_review.backend.diffing.process_diffs", side_effect=Exception("boom")),+ patch("products.visual_review.backend.diffing.count_processed_diffs", side_effect=Exception("count boom")),patch("products.visual_review.backend.logic.capture_run_processing_metrics") as capture,):with pytest.raises(Exception, match="boom"):@@ -102,6 +144,7 @@ class TestProcessRunDiffs:# Metrics still emitted on the failure path, and the real error is not masked.capture.assert_called_once()assert capture.call_args.kwargs["outcome"] == "failed"+ assert capture.call_args.kwargs["diffed_count"] == 0def testprocess_diffs_skips_unchanged(self, repo):# Create artifact that exists for both baseline and current@@ -158,6 +201,27 @@ class TestProcessRunDiffs:assert len(snapshots) == 1assert snapshots[0].result == SnapshotResult.NEW+ def testprocess_diffs_skips_new_with_existing_thumbnail(self, repo, mocker):+ thumbnail, _ = logic.get_or_create_artifact(repo.id, "thumb_hash", "visual_review/thumb_hash")+ current, _ = logic.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")+ current.thumbnail = thumbnail+ current.save(update_fields=["thumbnail"])+ create_result = api.create_run(+ CreateRunInput(+ repo_id=repo.id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="main",+ snapshots=[SnapshotManifestItem(identifier="NewComponent", content_hash="new_hash")],+ baseline_hashes={},+ ),+ team_id=repo.team_id,+ )+ generate_thumbnail = mocker.patch("products.visual_review.backend.diffing._generate_thumbnail_for_new")++ assert process_diffs(create_result.run_id) == 0+ generate_thumbnail.assert_not_called()+def testprocess_diffs_attempts_diff_for_changed(self, repo):# Create baseline artifactlogic.get_or_create_artifact(@@ -196,13 +260,111 @@ class TestProcessRunDiffs:# Process - should attempt to diff but fail because artifacts aren't in storagewith patch("products.visual_review.backend.diffing.logger") as mock_logger:- process_diffs(create_result.run_id)+ diffed_count = process_diffs(create_result.run_id)+ assert diffed_count == 0# Check that warning was logged about missing artifactsmock_logger.warning.assert_called()call_args = [call[0][0] for call in mock_logger.warning.call_args_list]assert any("diff_skipped_missing_artifact" in arg for arg in call_args)+ def testprocess_diffs_does_not_repeat_completed_comparisons(self, repo, mocker):+ def png(color: tuple[int, int, int, int]) -> bytes:+ image = Image.new("RGBA", (10, 10), color)+ buffer = io.BytesIO()+ image.save(buffer, format="PNG")+ return buffer.getvalue()++ stored_bytes = {+ "old_hash": png((255, 0, 0, 255)),+ "new_hash": png((0, 0, 255, 255)),+ }+ logic.get_or_create_artifact(repo.id, "old_hash", "visual_review/old_hash")+ logic.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")+ create_result = api.create_run(+ CreateRunInput(+ repo_id=repo.id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="main",+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],+ baseline_hashes={"Button": "old_hash"},+ ),+ team_id=repo.team_id,+ )+ with (+ patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"Button": "old_hash"}, 0),+ ),+ patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay"),+ ):+ logic.complete_run(create_result.run_id)++ mocker.patch(+ "products.visual_review.backend.storage.ArtifactStorage.read",+ autospec=True,+ side_effect=lambda _storage, content_hash: stored_bytes.get(content_hash),+ )+ mocker.patch(+ "products.visual_review.backend.storage.ArtifactStorage.write",+ autospec=True,+ side_effect=lambda _storage, content_hash, content: (+ stored_bytes.setdefault(content_hash, content) and f"visual_review/{content_hash}"+ ),+ )+ compare_images = mocker.spy(diffing, "compare_images")++ assert process_diffs(create_result.run_id) == 1+ assert process_diffs(create_result.run_id) == 0+ assert compare_images.call_count == 1+++class TestCountProcessedDiffs(VisualReviewTeamScopedTestMixin, BaseTest):+ databases = PRODUCT_DATABASES++ @parameterized.expand(+ [+ (+ "persisted_changed",+ {"result": SnapshotResult.CHANGED, "change_kind": ChangeKind.PIXEL},+ 1,+ ),+ (+ "below_threshold_unchanged",+ {+ "result": SnapshotResult.UNCHANGED,+ "classification_reason": ClassificationReason.BELOW_THRESHOLD,+ },+ 1,+ ),+ (+ "exact_unchanged",+ {+ "result": SnapshotResult.UNCHANGED,+ "classification_reason": ClassificationReason.EXACT,+ },+ 0,+ ),+ ("new", {"result": SnapshotResult.NEW}, 0),+ ("incomplete_changed", {"result": SnapshotResult.CHANGED, "change_kind": ""}, 0),+ ]+ )+ def test_from_persisted_state(self, _name: str, snapshot_fields: dict[str, object], expected: int) -> None:+ repo = api.create_repo(team_id=self.team.id, repo_external_id=99999, repo_full_name="org/test")+ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha=f"count-{_name}",+ branch=f"count-{_name}",+ pr_number=None,+ snapshots=[{"identifier": _name, "content_hash": f"hash-{_name}"}],+ )+ RunSnapshot.objects.filter(run=run).update(**snapshot_fields)++ assert diffing.count_processed_diffs(run.id) == expected+@pytest.mark.django_db(databases=PRODUCT_DATABASES)class TestPostApprovalCommentTask: