: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): match tolerated snapshot hashes in both directions (#113982)
posthog[bot]d7a48e2bfb11
diff --git a/products/visual_review/backend/classifier.py b/products/visual_review/backend/classifier.pyindex bf9b9be70644..6385de3cf275 100644--- a/products/visual_review/backend/classifier.py+++ b/products/visual_review/backend/classifier.py@@ -10,17 +10,26 @@ unchanged snapshots hits ~5 queries instead of ~8400.from django.db.models import Case, CharField, F, Value, When+from posthog.dataclasses import frozen+from .db import WRITER_DBfrom .facade.enums import ClassificationReason, ReviewState, SnapshotResultfrom .models import Artifact, Run, RunSnapshot, ToleratedHash+@frozen+class ToleratedKey:+ identifier: str+ baseline_hash: str+ current_hash: str++class SnapshotClassifier:def __init__(self,run: Run,baseline: dict[str, str],- tolerated_lookup: dict[tuple[str, str, str], ToleratedHash],+ tolerated_lookup: dict[ToleratedKey, ToleratedHash],is_partial: bool = False,):self.run = run@@ -108,7 +117,13 @@ class SnapshotClassifier:if not baseline_hash:result = SnapshotResult.NEWelse:- match = self.tolerated_lookup.get((snapshot.identifier, baseline_hash, snapshot.current_hash))+ match = self.tolerated_lookup.get(+ ToleratedKey(+ identifier=snapshot.identifier,+ baseline_hash=baseline_hash,+ current_hash=snapshot.current_hash,+ )+ )if match is not None:result = SnapshotResult.UNCHANGEDclassification_reason = ClassificationReason.TOLERATED_HASHdiff --git a/products/visual_review/backend/logic/runs.py b/products/visual_review/backend/logic/runs.pyindex 2d6877e6b181..8d37f6a78a3f 100644--- a/products/visual_review/backend/logic/runs.py+++ b/products/visual_review/backend/logic/runs.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom uuid import UUIDfrom django.db import transaction-from django.db.models import Count, F, Q+from django.db.models import Count, Ffrom django.utils import timezoneimport structlog@@ -17,9 +17,20 @@ from ..classifier import SnapshotClassifierfrom ..db import WRITER_DBfrom ..facade.contracts import CreateRunInputfrom ..facade.enums import RunStatus, SnapshotResult-from ..models import Repo, Run, RunSnapshot, ToleratedHash+from ..models import Repo, Run, RunSnapshotfrom ..storage import ArtifactStorage-from . import artifact_store, baselines, ci_status, errors, gating, quarantine_lifts, repos, run_queries, uploads+from . import (+ artifact_store,+ baselines,+ ci_status,+ errors,+ gating,+ quarantine_lifts,+ repos,+ run_queries,+ toleration,+ uploads,+)logger = structlog.get_logger(__name__)@@ -285,16 +296,9 @@ def complete_run(run_id: UUID) -> Run:run.save(using=WRITER_DB, update_fields=["metadata"])# Pre-load tolerated hashes scoped to this run's identifiers and baseline hashes- baseline_hashes_in_use = set(baseline.values())- tolerated_lookup: dict[tuple[str, str, str], ToleratedHash] = {}- if run_identifiers and baseline_hashes_in_use:- now = timezone.now()- for t in ToleratedHash.objects.filter(- repo=repo,- identifier__in=run_identifiers,- baseline_hash__in=baseline_hashes_in_use,- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)):- tolerated_lookup[(t.identifier, t.baseline_hash, t.alternate_hash)] = t+ tolerated_lookup = toleration.build_tolerated_lookup(+ repo.id, run_identifiers, set(baseline.values()), now=timezone.now()+ )# is_partial is client-supplied and only suppresses removed-baseline# detection. Never honor it on the default branch (authoritative fulldiff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.pyindex 07fd3b29ebe8..c9c6c08167e9 100644--- a/products/visual_review/backend/logic/toleration.py+++ b/products/visual_review/backend/logic/toleration.py@@ -13,6 +13,7 @@ from django.utils import timezonefrom posthog.dataclasses import frozen+from ..classifier import ToleratedKeyfrom ..db import WRITER_DBfrom ..facade.contracts import TOLERATION_PILEUP_WINDOW_DAYS, VARIANT_PILEUP_MINfrom ..facade.enums import INTENTIONAL_TOLERATE_REASONS, ActorType, ReviewState, SnapshotResult, ToleratedReason@@ -21,6 +22,33 @@ from . import errors, run_queriesfrom .run_queries import SnapshotKey+def build_tolerated_lookup(+ repo_id: UUID, identifiers: set[str], baseline_hashes: set[str], *, now: datetime+) -> dict[ToleratedKey, ToleratedHash]:+ """Active tolerations for a run, keyed by the snapshot they absorb.++ A toleration accepts a pair of renders, so it matches in both directions. Some stories+ render in two stable states, and a retry or an approval can commit either one as the+ baseline. Without the reverse key, that flip drops the toleration, and every run that+ renders the old baseline fails again.+ """+ if not identifiers or not baseline_hashes:+ return {}+ lookup: dict[ToleratedKey, ToleratedHash] = {}+ reversed_lookup: dict[ToleratedKey, ToleratedHash] = {}+ for t in ToleratedHash.objects.filter(+ Q(baseline_hash__in=baseline_hashes) | Q(alternate_hash__in=baseline_hashes),+ repo_id=repo_id,+ identifier__in=identifiers,+ ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)):+ lookup[ToleratedKey(identifier=t.identifier, baseline_hash=t.baseline_hash, current_hash=t.alternate_hash)] = t+ reversed_lookup[+ ToleratedKey(identifier=t.identifier, baseline_hash=t.alternate_hash, current_hash=t.baseline_hash)+ ] = t+ # A row recorded against the baseline in use wins over the reverse of another row.+ return {**reversed_lookup, **lookup}++@transaction.atomic(using=WRITER_DB)def mark_snapshot_as_tolerated(run_id: UUID, snapshot_id: UUID, user_id: int, team_id: int, actor: ActorType = ActorType.HUMANdiff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.pyindex 456430c8c7cb..6c9d5ec66027 100644--- a/products/visual_review/backend/models.py+++ b/products/visual_review/backend/models.py@@ -327,9 +327,10 @@ class ToleratedHash(ProductTeamModel):specific baseline and snapshot identifier, allowing future runs to skipexpensive diff processing.- Keyed by (repo, identifier, baseline_hash, content_hash) — when the- canonical baseline changes, old tolerations expire naturally because- baseline_hash no longer matches.+ Keyed by (repo, identifier, baseline_hash, content_hash). A row accepts the+ pair in both directions, so it still matches when the baseline flips to the+ alternate render. When the baseline moves to any other hash, old tolerations+ expire naturally because neither hash matches."""# nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 (UUIDModel)diff --git a/products/visual_review/backend/tests/logic/test_toleration.py b/products/visual_review/backend/tests/logic/test_toleration.pyindex 7e89574a1b9b..caabd82f7626 100644--- a/products/visual_review/backend/tests/logic/test_toleration.py+++ b/products/visual_review/backend/tests/logic/test_toleration.py@@ -117,26 +117,33 @@ class TestToleratedHashes:with pytest.raises(ValueError, match="Can only mark CHANGED"):toleration.mark_snapshot_as_tolerated(run.id, snapshot.id, user.id, repo.team_id)- def test_tolerated_hash_shortcircuits_classification(self, repo, user, mocker):- from products.visual_review.backend.models import ToleratedHash-- # Create a tolerated hash entry- ToleratedHash.objects.create(- repo=repo,- team_id=repo.team_id,- identifier="Button",- baseline_hash="old_hash",- alternate_hash="new_hash",- reason="auto_threshold",- )+ @pytest.mark.parametrize(+ "rows,expected_baseline_hash",+ [+ ([("old_hash", "new_hash")], "old_hash"),+ # The baseline flipped to the render that was tolerated, and the run rendered the old baseline.+ ([("new_hash", "old_hash")], "new_hash"),+ ([("new_hash", "old_hash"), ("old_hash", "new_hash")], "old_hash"),+ ],+ )+ def test_tolerated_hash_shortcircuits_classification(self, repo, user, mocker, rows, expected_baseline_hash):+ for baseline_hash, alternate_hash in rows:+ ToleratedHash.objects.create(+ repo=repo,+ team_id=repo.team_id,+ identifier="Button",+ baseline_hash=baseline_hash,+ alternate_hash=alternate_hash,+ reason="auto_threshold",+ )- # Run with the same hashes — should be classified UNCHANGED via cacherun = self._create_completed_run(repo, mocker)snapshot = run.snapshots.first()assert snapshot.result == SnapshotResult.UNCHANGEDassert snapshot.classification_reason == "tolerated_hash"assert snapshot.tolerated_hash_match is not None+ assert snapshot.tolerated_hash_match.baseline_hash == expected_baseline_hashdef test_tolerated_hash_expires_on_baseline_change(self, repo, user, mocker):from products.visual_review.backend.models import ToleratedHashdiff --git a/products/visual_review/backend/tests/test_classifier.py b/products/visual_review/backend/tests/test_classifier.pyindex 918cbc11797f..2693b7c2cb22 100644--- a/products/visual_review/backend/tests/test_classifier.py+++ b/products/visual_review/backend/tests/test_classifier.py@@ -4,7 +4,7 @@ import pytestfrom django.utils import timezone-from products.visual_review.backend.classifier import SnapshotClassifier+from products.visual_review.backend.classifier import SnapshotClassifier, ToleratedKeyfrom products.visual_review.backend.facade.enums import (ClassificationReason,ReviewState,@@ -12,6 +12,7 @@ from products.visual_review.backend.facade.enums import (SnapshotResult,ToleratedReason,)+from products.visual_review.backend.logic import tolerationfrom products.visual_review.backend.models import Artifact, Repo, Run, RunSnapshot, ToleratedHashfrom products.visual_review.backend.tests.conftest import PRODUCT_DATABASES@@ -239,7 +240,7 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "Button", "baseline_h", "current_h")run = _make_run(repo, [{"identifier": "Button", "current_hash": "current_h"}])- lookup = {("Button", "baseline_h", "current_h"): tolerated}+ lookup = {ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="current_h"): tolerated}result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].result == SnapshotResult.UNCHANGED@@ -251,7 +252,7 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "Button", "baseline_h", "current_h", diff_percentage=0.42)run = _make_run(repo, [{"identifier": "Button", "current_hash": "current_h"}])- lookup = {("Button", "baseline_h", "current_h"): tolerated}+ lookup = {ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="current_h"): tolerated}result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].diff_percentage == 0.42@@ -260,7 +261,7 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "Button", "baseline_h", "current_h")run = _make_run(repo, [{"identifier": "Button", "current_hash": "current_h"}])- lookup = {("Button", "baseline_h", "current_h"): tolerated}+ lookup = {ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="current_h"): tolerated}result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].diff_percentage is None@@ -269,7 +270,9 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "OtherButton", "baseline_h", "current_h")run = _make_run(repo, [{"identifier": "Button", "current_hash": "current_h"}])- lookup = {("OtherButton", "baseline_h", "current_h"): tolerated}+ lookup = {+ ToleratedKey(identifier="OtherButton", baseline_hash="baseline_h", current_hash="current_h"): tolerated+ }result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].result == SnapshotResult.CHANGED@@ -278,7 +281,9 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "Button", "different_baseline", "current_h")run = _make_run(repo, [{"identifier": "Button", "current_hash": "current_h"}])- lookup = {("Button", "different_baseline", "current_h"): tolerated}+ lookup = {+ ToleratedKey(identifier="Button", baseline_hash="different_baseline", current_hash="current_h"): tolerated+ }result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].result == SnapshotResult.CHANGED@@ -287,7 +292,9 @@ class TestToleratedHashClassification:tolerated = _make_tolerated(repo, "Button", "baseline_h", "expected_current")run = _make_run(repo, [{"identifier": "Button", "current_hash": "actual_current"}])- lookup = {("Button", "baseline_h", "expected_current"): tolerated}+ lookup = {+ ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="expected_current"): tolerated+ }result = _classify(run, {"Button": "baseline_h"}, lookup)assert result["Button"].result == SnapshotResult.CHANGED@@ -302,19 +309,8 @@ class TestToleratedHashClassification:def _build_tolerated_lookup(repo: Repo, identifiers: set[str], baseline_hashes: set[str]-) -> dict[tuple[str, str, str], ToleratedHash]:- """Mirrors the tolerated hash query in runs.complete_run."""- from django.db.models import Q-- now = timezone.now()- lookup: dict[tuple[str, str, str], ToleratedHash] = {}- for t in ToleratedHash.objects.filter(- repo=repo,- identifier__in=identifiers,- baseline_hash__in=baseline_hashes,- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)):- lookup[(t.identifier, t.baseline_hash, t.alternate_hash)] = t- return lookup+) -> dict[ToleratedKey, ToleratedHash]:+ return toleration.build_tolerated_lookup(repo.id, identifiers, baseline_hashes, now=timezone.now())@pytest.mark.django_db(databases=PRODUCT_DATABASES)@@ -333,7 +329,7 @@ class TestExpiredToleratedHashFiltering:lookup = _build_tolerated_lookup(repo, {"Button"}, {"baseline_h"})- assert len(lookup) == 0+ assert lookup == {}result = _classify(run, {"Button": "baseline_h"}, lookup)@@ -347,7 +343,9 @@ class TestExpiredToleratedHashFiltering:lookup = _build_tolerated_lookup(repo, {"Button"}, {"baseline_h"})- assert len(lookup) == 1+ assert (+ lookup[ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="current_h")] == tolerated+ )result = _classify(run, {"Button": "baseline_h"}, lookup)@@ -360,7 +358,9 @@ class TestExpiredToleratedHashFiltering:lookup = _build_tolerated_lookup(repo, {"Button"}, {"baseline_h"})- assert len(lookup) == 1+ assert (+ lookup[ToleratedKey(identifier="Button", baseline_hash="baseline_h", current_hash="current_h")] == tolerated+ )result = _classify(run, {"Button": "baseline_h"}, lookup)@@ -381,8 +381,7 @@ class TestExpiredToleratedHashFiltering:lookup = _build_tolerated_lookup(repo, {"Expired", "Active"}, {"base_e", "base_a"})- assert len(lookup) == 1- assert ("Active", "base_a", "curr_a") in lookup+ assert {key.identifier for key in lookup} == {"Active"}result = _classify(run, {"Expired": "base_e", "Active": "base_a"}, lookup)@@ -526,7 +525,7 @@ class TestMixedClassification:],)- lookup = {("Tolerated", "tol_base", "tol_curr"): tolerated}+ lookup = {ToleratedKey(identifier="Tolerated", baseline_hash="tol_base", current_hash="tol_curr"): tolerated}result = _classify(run, {"Exact": "exact_h", "Tolerated": "tol_base", "Changed": "old_h"}, lookup)assert result["Exact"].result == SnapshotResult.UNCHANGED