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.

chore(visual-review): split logic.py into a package to cut the agent read-set (#83673)

Julian Bez60c7f9998688
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index 4c1b0a127b0a..992642c1bada 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -31,7 +31,7 @@ Use Visual review as the concrete reference implementation:
- [products/visual_review/backend/facade/api.py](../../../products/visual_review/backend/facade/api.py)
- [products/visual_review/backend/presentation/views.py](../../../products/visual_review/backend/presentation/views.py)
- [products/visual_review/backend/presentation/serializers.py](../../../products/visual_review/backend/presentation/serializers.py)
-- [products/visual_review/backend/logic.py](../../../products/visual_review/backend/logic.py)
+- [products/visual_review/backend/logic/](../../../products/visual_review/backend/logic/)
- [products/visual_review/backend/tests/test_api.py](../../../products/visual_review/backend/tests/test_api.py)
- [products/visual_review/backend/tests/test_presentation.py](../../../products/visual_review/backend/tests/test_presentation.py)
diff --git a/products/architecture.md b/products/architecture.md
index 908098a50233..9786f0245679 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -133,6 +133,7 @@ myproduct/
apps.py
models.py # Django ORM only
logic.py # Business logic
+ logic/ # ...or a package, once logic.py outgrows one file
tasks/
__init__.py
@@ -289,6 +290,10 @@ The alternative — returning ORM objects — works until it doesn't, then you'r
Business logic lives here: validation, calculations, business rules, ORM queries.
+Start as a single `logic.py`.
+Once it outgrows one file, split it into a `logic/` package with one module per concern and mirror that split in `tests/logic/` — `products/visual_review/backend/logic/` is the reference, and `/splitting-oversized-modules` does the move.
+Import the submodule you need (`from .logic import runs`) rather than re-exporting through `__init__.py`: one binding per symbol keeps it obvious where behavior lives and keeps test patch targets on the real definition.
+
Examples:
- Deduplication rules
diff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.py
index f6a3bc24441d..858747109074 100644
--- a/products/visual_review/backend/diffing.py
+++ b/products/visual_review/backend/diffing.py
@@ -57,7 +57,7 @@ def classify_compare_result(result: CompareResult) -> ChangeKind | None:
def _store_thumbnail(snapshot: RunSnapshot, result: CompareResult) -> None:
"""Store the thumbnail artifact and link it to the current artifact."""
- from . import logic
+ from .logic import artifact_store
artifact = snapshot.current_artifact
if artifact is None or artifact.thumbnail_id is not None:
@@ -65,7 +65,7 @@ def _store_thumbnail(snapshot: RunSnapshot, result: CompareResult) -> None:
if not result.thumbnail:
return
- thumb_artifact = logic.write_artifact_bytes(
+ thumb_artifact = artifact_store.write_artifact_bytes(
repo_id=snapshot.run.repo_id,
content_hash=result.thumbnail_hash,
content=result.thumbnail,
@@ -84,12 +84,12 @@ def _store_diff(
change_kind: ChangeKind,
) -> None:
"""Upload diff artifact and update snapshot metrics + classification."""
- from . import logic
+ from .logic import artifact_store, snapshot_diffs
if not result.diff_image:
return
- diff_artifact = logic.write_artifact_bytes(
+ diff_artifact = artifact_store.write_artifact_bytes(
repo_id=snapshot.run.repo_id,
content_hash=result.diff_hash,
content=result.diff_image,
@@ -103,7 +103,7 @@ def _store_diff(
size_mismatch=result.size_mismatch,
)
- logic.update_snapshot_diff(
+ snapshot_diffs.update_snapshot_diff(
snapshot_id=snapshot.id,
diff_artifact=diff_artifact,
diff_percentage=result.diff_percentage,
@@ -143,14 +143,14 @@ def _diff_snapshot(snapshot: RunSnapshot) -> bool:
`diff_percentage` and `ssim_score` are recorded faithfully; the categorical
kind is what callers use to render. No overwriting one signal with another.
"""
- from . import logic
+ from .logic import artifact_store
repo_id = snapshot.run.repo_id
assert snapshot.baseline_artifact is not None
assert snapshot.current_artifact is not None
- baseline_bytes = logic.read_artifact_bytes(repo_id, snapshot.baseline_artifact.content_hash)
- current_bytes = logic.read_artifact_bytes(repo_id, snapshot.current_artifact.content_hash)
+ baseline_bytes = artifact_store.read_artifact_bytes(repo_id, snapshot.baseline_artifact.content_hash)
+ current_bytes = artifact_store.read_artifact_bytes(repo_id, snapshot.current_artifact.content_hash)
if not baseline_bytes or not current_bytes:
logger.warning(
@@ -209,13 +209,13 @@ def _diff_snapshot(snapshot: RunSnapshot) -> bool:
def _generate_thumbnail_for_new(snapshot: RunSnapshot) -> None:
"""Generate thumbnail for NEW snapshots (no baseline to compare against)."""
- from . import logic
+ from .logic import artifact_store
artifact = snapshot.current_artifact
if artifact is None or artifact.thumbnail_id is not None:
return
- current_bytes = logic.read_artifact_bytes(snapshot.run.repo_id, artifact.content_hash)
+ current_bytes = artifact_store.read_artifact_bytes(snapshot.run.repo_id, artifact.content_hash)
if not current_bytes:
return
@@ -230,7 +230,7 @@ def _generate_thumbnail_for_new(snapshot: RunSnapshot) -> None:
return
thumb_hash = blake3(webp_bytes).hexdigest()
- thumb_artifact = logic.write_artifact_bytes(
+ thumb_artifact = artifact_store.write_artifact_bytes(
repo_id=snapshot.run.repo_id,
content_hash=thumb_hash,
content=webp_bytes,
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 651d7965bfca..30a0b6925945 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -20,10 +20,25 @@ from uuid import UUID
from django.contrib.auth import get_user_model
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.helpers.trigram_search import search_match_type_from_instance
-from .. import logic
from ..diff_metadata import DiffMetadata
+from ..logic import (
+ approvals,
+ artifact_store,
+ baseline_overview,
+ baselines,
+ errors,
+ gating,
+ history,
+ quarantine,
+ repos,
+ run_queries,
+ runs,
+ thumbnails,
+ toleration,
+)
from . import contracts
from .enums import RunPurpose
@@ -62,16 +77,16 @@ def _sanitize_run_metadata(metadata: dict | None) -> dict:
# Re-export exceptions for callers
-RepoNotFoundError = logic.RepoNotFoundError
-RunNotFoundError = logic.RunNotFoundError
-ArtifactNotFoundError = logic.ArtifactNotFoundError
-GitHubIntegrationNotFoundError = logic.GitHubIntegrationNotFoundError
-GitHubCommitError = logic.GitHubCommitError
-GitHubRateLimitError = logic.GitHubRateLimitError
-PRSHAMismatchError = logic.PRSHAMismatchError
-StaleRunError = logic.StaleRunError
-RunNotFullyResolvedError = logic.RunNotFullyResolvedError
-BaselineFilePathNotConfiguredError = logic.BaselineFilePathNotConfiguredError
+RepoNotFoundError = errors.RepoNotFoundError
+RunNotFoundError = errors.RunNotFoundError
+ArtifactNotFoundError = errors.ArtifactNotFoundError
+GitHubIntegrationNotFoundError = errors.GitHubIntegrationNotFoundError
+GitHubCommitError = errors.GitHubCommitError
+GitHubRateLimitError = GitHubRateLimitError
+PRSHAMismatchError = errors.PRSHAMismatchError
+StaleRunError = errors.StaleRunError
+RunNotFullyResolvedError = errors.RunNotFullyResolvedError
+BaselineFilePathNotConfiguredError = errors.BaselineFilePathNotConfiguredError
# --- Converters (model -> DTO) ---
@@ -82,7 +97,7 @@ BaselineFilePathNotConfiguredError = logic.BaselineFilePathNotConfiguredError
def _to_artifact(artifact, repo_id: UUID) -> contracts.Artifact:
- download_url = logic.get_presigned_download_url(repo_id, artifact.content_hash)
+ download_url = artifact_store.get_presigned_download_url(repo_id, artifact.content_hash)
return contracts.Artifact(
id=artifact.id,
content_hash=artifact.content_hash,
@@ -168,7 +183,7 @@ def _compute_unresolved(run) -> int:
return 0
# Use prefetched snapshots if available (detail view), skip for list views
if "snapshots" in getattr(run, "_prefetched_objects_cache", {}):
- return sum(1 for s in run.snapshots.all() if logic._is_unresolved(s))
+ return sum(1 for s in run.snapshots.all() if gating._is_unresolved(s))
return 0
@@ -196,7 +211,7 @@ def _to_run(run, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = N
error_message=run.error_message or None,
created_at=run.created_at,
completed_at=run.completed_at,
- is_stale=logic.is_run_stale(run),
+ is_stale=run_queries.is_run_stale(run),
superseded_by_id=run.superseded_by_id,
approved_by=approved_by,
metadata=run.metadata or {},
@@ -221,42 +236,42 @@ def _to_repo(repo) -> contracts.Repo:
def get_repo(repo_id: UUID, team_id: int) -> contracts.Repo:
- repo = logic.get_repo(repo_id, team_id)
+ repo = repos.get_repo(repo_id, team_id)
return _to_repo(repo)
def list_repos(team_id: int) -> list[contracts.Repo]:
- projects = logic.list_repos_for_team(team_id)
+ projects = repos.list_repos_for_team(team_id)
return [_to_repo(p) for p in projects]
def create_repo(team_id: int, repo_external_id: int, repo_full_name: str) -> contracts.Repo:
- repo = logic.create_repo(team_id=team_id, repo_external_id=repo_external_id, repo_full_name=repo_full_name)
+ repo = repos.create_repo(team_id=team_id, repo_external_id=repo_external_id, repo_full_name=repo_full_name)
return _to_repo(repo)
def update_repo(input: contracts.UpdateRepoInput, team_id: int) -> contracts.Repo:
- repo = logic.update_repo(input, team_id=team_id)
+ repo = repos.update_repo(input, team_id=team_id)
return _to_repo(repo)
def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str) -> str | None:
"""Resolve a snapshot identifier to the content hash of its thumbnail, if any."""
- return logic.get_thumbnail_hash_for_identifier(repo_id, identifier)
+ return thumbnails.get_thumbnail_hash_for_identifier(repo_id, identifier)
def read_thumbnail_bytes(repo_id: UUID, content_hash: str) -> bytes | None:
"""Read the raw bytes for a thumbnail artifact from storage."""
- return logic.read_thumbnail_bytes(repo_id, content_hash)
+ return thumbnails.read_thumbnail_bytes(repo_id, content_hash)
def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:
"""Universe of identifiers with a current baseline, plus aggregates.
- Backs the snapshots overview page. See `logic.get_baselines_overview` for
+ Backs the snapshots overview page. See `baseline_overview.get_baselines_overview` for
query shape and performance notes.
"""
- raw = logic.get_baselines_overview(repo_id)
+ raw = baseline_overview.get_baselines_overview(repo_id)
# Hydrate UserBasicInfo for everyone who created an active quarantine so the
# overview can show "Quarantined by X" without a per-card fetch.
@@ -324,7 +339,7 @@ def list_runs(
branch: str | None = None,
search: str | None = None,
) -> list[contracts.Run]:
- runs = logic.list_runs_for_team(
+ runs = run_queries.list_runs_for_team(
team_id,
review_state=review_state,
repo_id=repo_id,
@@ -337,13 +352,13 @@ def list_runs(
def get_review_state_counts(team_id: int, repo_id: UUID | None = None) -> dict[str, int]:
- return logic.get_review_state_counts(team_id, repo_id=repo_id)
+ return run_queries.get_review_state_counts(team_id, repo_id=repo_id)
def create_run(input: contracts.CreateRunInput, team_id: int) -> contracts.CreateRunResult:
# Sanitize metadata at the facade boundary before handing the DTO to logic.
input = replace(input, metadata=_sanitize_run_metadata(input.metadata))
- run, uploads = logic.create_run(input, team_id=team_id)
+ run, uploads = runs.create_run(input, team_id=team_id)
upload_targets = [
contracts.UploadTarget(
@@ -370,7 +385,7 @@ def add_snapshots(input: contracts.AddSnapshotsInput, run_id: UUID, team_id: int
for s in input.snapshots
]
- added, uploads = logic.add_snapshots_to_run(
+ added, uploads = runs.add_snapshots_to_run(
run_id=run_id,
team_id=team_id,
snapshots=snapshots,
@@ -385,7 +400,7 @@ def add_snapshots(input: contracts.AddSnapshotsInput, run_id: UUID, team_id: int
def get_run(run_id: UUID, team_id: int | None = None) -> contracts.Run:
- run = logic.get_run_with_snapshots(run_id, team_id=team_id)
+ run = run_queries.get_run_with_snapshots(run_id, team_id=team_id)
user_ids = {run.approved_by_id} if run.approved_by_id else set()
user_basic_infos = _fetch_user_basic_infos(user_ids)
return _to_run(run, user_basic_infos)
@@ -396,13 +411,13 @@ def get_run_snapshots(
) -> contracts.RunSnapshots:
if not include_quarantined and team_id is None:
raise ValueError("team_id is required to exclude quarantined snapshots")
- snapshots = logic.get_run_snapshots(run_id, team_id=team_id)
+ snapshots = run_queries.get_run_snapshots(run_id, team_id=team_id)
if not snapshots:
return contracts.RunSnapshots(snapshots=[], quarantined_count=0)
repo_id = snapshots[0].run.repo_id
run_type = snapshots[0].run.run_type
quarantined_identifiers = (
- {q.identifier for q in logic.list_quarantined_identifiers(repo_id, team_id, run_type=run_type)}
+ {q.identifier for q in quarantine.list_quarantined_identifiers(repo_id, team_id, run_type=run_type)}
if team_id is not None
else set()
)
@@ -421,7 +436,7 @@ def get_run_snapshots(
def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[contracts.SnapshotHistoryEntry]:
- entries = logic.get_snapshot_history(repo_id, identifier, run_type)
+ entries = history.get_snapshot_history(repo_id, identifier, run_type)
return [
contracts.SnapshotHistoryEntry(
run_id=e.run_id,
@@ -447,12 +462,12 @@ def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[
def mark_snapshot_as_tolerated(run_id: UUID, snapshot_id: UUID, user_id: int, team_id: int) -> contracts.Snapshot:
- snapshot = logic.mark_snapshot_as_tolerated(run_id, snapshot_id, user_id, team_id)
+ snapshot = toleration.mark_snapshot_as_tolerated(run_id, snapshot_id, user_id, team_id)
return _to_snapshot(snapshot, snapshot.run.repo_id)
def get_tolerated_hashes(repo_id: UUID, identifier: str) -> list[contracts.ToleratedHashEntry]:
- entries = logic.get_tolerated_hashes_for_identifier(repo_id, identifier)
+ entries = toleration.get_tolerated_hashes_for_identifier(repo_id, identifier)
return [
contracts.ToleratedHashEntry(
id=e.id,
@@ -472,14 +487,14 @@ def complete_run(run_id: UUID, team_id: int | None = None) -> contracts.Run:
Complete a run: detect removals, verify uploads, trigger diff processing.
"""
if team_id is not None:
- logic.get_run(run_id, team_id=team_id) # validates ownership
- run = logic.complete_run(run_id)
+ run_queries.get_run(run_id, team_id=team_id) # validates ownership
+ run = runs.complete_run(run_id)
return _to_run(run)
def recompute_run(run_id: UUID, team_id: int | None = None) -> contracts.RecomputeResult:
- result = logic.recompute_run(run_id, team_id=team_id)
- run = logic.get_run_with_snapshots(run_id, team_id=team_id)
+ result = runs.recompute_run(run_id, team_id=team_id)
+ run = run_queries.get_run_with_snapshots(run_id, team_id=team_id)
return contracts.RecomputeResult(
run=_to_run(run),
counts_changed=result["counts_changed"],
@@ -496,7 +511,7 @@ def approve_snapshots(input: contracts.ApproveRunInput, team_id: int | None = No
the baseline and greening the gate) happens via finalize_run.
"""
approved_snapshots = [{"identifier": s.identifier, "new_hash": s.new_hash} for s in input.snapshots]
- run = logic.approve_snapshots(
+ run = approvals.approve_snapshots(
run_id=input.run_id,
user_id=input.user_id,
approved_snapshots=approved_snapshots,
@@ -523,7 +538,7 @@ def finalize_run(
With ``commit_to_github=False`` the server skips the commit and returns the signed
baseline YAML on ``baseline_content`` instead (for tooling that commits it itself).
"""
- run = logic.finalize_run(
+ run = approvals.finalize_run(
run_id=run_id,
user_id=user_id,
team_id=team_id,
@@ -531,7 +546,7 @@ def finalize_run(
commit_to_github=commit_to_github,
add_images_to_comment_on_pr=add_images_to_comment_on_pr,
)
- baseline_content = "" if commit_to_github else logic.build_signed_baseline(run_id, team_id=team_id)
+ baseline_content = "" if commit_to_github else baselines.build_signed_baseline(run_id, team_id=team_id)
return contracts.FinalizeResult(run=_to_run(run), baseline_content=baseline_content)
@@ -609,7 +624,7 @@ def _to_baseline_quarantine_summary(
def list_quarantined(
repo_id: UUID, team_id: int, identifier: str | None = None, run_type: str | None = None
) -> list[contracts.QuarantinedIdentifierEntry]:
- entries = logic.list_quarantined_identifiers(repo_id, team_id, identifier=identifier, run_type=run_type)
+ entries = quarantine.list_quarantined_identifiers(repo_id, team_id, identifier=identifier, run_type=run_type)
user_ids = {e.created_by_id for e in entries if e.created_by_id}
user_basic_infos = _fetch_user_basic_infos(user_ids)
return [_to_quarantined_entry(q, user_basic_infos) for q in entries]
@@ -618,7 +633,7 @@ def list_quarantined(
def quarantine_identifier(
repo_id: UUID, run_type: str, input: contracts.QuarantineInput, user_id: int, team_id: int
) -> contracts.QuarantinedIdentifierEntry:
- entry = logic.quarantine_identifier(
+ entry = quarantine.quarantine_identifier(
repo_id=repo_id,
identifier=input.identifier,
run_type=run_type,
@@ -633,8 +648,8 @@ def quarantine_identifier(
def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:
- logic.unquarantine_identifier(repo_id=repo_id, identifier=identifier, run_type=run_type, team_id=team_id)
+ quarantine.unquarantine_identifier(repo_id=repo_id, identifier=identifier, run_type=run_type, team_id=team_id)
def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
- logic.expire_quarantine_entry(entry_id=entry_id, team_id=team_id)
+ quarantine.expire_quarantine_entry(entry_id=entry_id, team_id=team_id)
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
deleted file mode 100644
index d6cbee747f45..000000000000
--- a/products/visual_review/backend/logic.py
+++ /dev/null
@@ -1,3081 +0,0 @@
-"""
-Business logic for visual_review.
-
-ORM queries, validation, calculations, business rules.
-Called by api/api.py facade. Do not call from outside this module.
-"""
-
-from __future__ import annotations
-
-import re
-import html
-from collections import Counter
-from collections.abc import Iterable, Iterator, Mapping
-from dataclasses import dataclass
-from datetime import datetime
-from typing import TYPE_CHECKING
-from urllib.parse import quote
-from uuid import UUID
-
-from django.conf import settings
-from django.db import (
- connections,
- models as db_models,
- transaction,
-)
-from django.db.models import Avg, Count, F, Q
-from django.utils import timezone
-
-import structlog
-
-if TYPE_CHECKING:
- import requests
-
- from posthog.models.integration import GitHubIntegration
-
-from posthog.dataclasses import frozen
-from posthog.egress.github.transport import GitHubRateLimitError
-from posthog.helpers.trigram_search import (
- TrigramSearchField,
- apply_trigram_search,
- drop_similar_when_exact_exists,
- normalize_search_term,
-)
-from posthog.models.github_integration_base import GitHubIntegrationError
-from posthog.ph_client import ph_scoped_capture
-
-from .classifier import SnapshotClassifier
-from .db import READER_DB, WRITER_DB
-from .diff_metadata import DiffMetadata
-from .facade.contracts import CreateRunInput, UpdateRepoInput
-from .facade.enums import (
- ChangeKind,
- ReviewDecision,
- ReviewState,
- RunPurpose,
- RunStatus,
- SnapshotResult,
- ToleratedReason,
-)
-from .models import Artifact, QuarantinedIdentifier, Repo, Run, RunSnapshot, ToleratedHash
-from .signing import sign_snapshot_hash, verify_signed_hash
-from .storage import ArtifactStorage
-
-logger = 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
-
-
-class RunNotFoundError(Exception):
- pass
-
-
-class ArtifactNotFoundError(Exception):
- pass
-
-
-class GitHubIntegrationNotFoundError(Exception):
- """Team does not have a GitHub integration configured."""
-
- pass
-
-
-class GitHubCommitError(Exception):
- """Failed to commit to GitHub."""
-
- pass
-
-
-class PRSHAMismatchError(Exception):
- """PR has new commits since this run was created."""
-
- pass
-
-
-class HashIntegrityError(Exception):
- """Uploaded image bytes do not match the claimed content hash."""
-
- pass
-
-
-class StaleRunError(Exception):
- """Approval blocked because a newer run exists for this PR."""
-
- pass
-
-
-class RunNotFullyResolvedError(Exception):
- """Finalize blocked because some changed/new snapshots are still unreviewed.
-
- Visual review is all-or-nothing: the baseline is only committed once every
- changed/new snapshot is approved or tolerated. Committing a subset is pointless
- (CI re-detects the rest on the next run) and would green the gate over unreviewed
- changes.
- """
-
- pass
-
-
-class BaselineFilePathNotConfiguredError(Exception):
- """Repo does not have a baseline file path configured for this run type."""
-
- pass
-
-
-# --- Repo Operations ---
-
-
-def get_repo(repo_id: UUID, team_id: int) -> Repo:
- try:
- return Repo.objects.get(id=repo_id, team_id=team_id)
- except Repo.DoesNotExist as e:
- raise RepoNotFoundError(f"Repo {repo_id} not found") from e
-
-
-def list_repos_for_team(team_id: int) -> list[Repo]:
- return list(Repo.objects.filter(team_id=team_id).order_by("-created_at"))
-
-
-def create_repo(team_id: int, repo_external_id: int, repo_full_name: str) -> Repo:
- return Repo.objects.create(
- team_id=team_id,
- repo_external_id=repo_external_id,
- repo_full_name=repo_full_name,
- )
-
-
-def update_repo(input: UpdateRepoInput, team_id: int) -> Repo:
- repo = get_repo(input.repo_id, team_id)
- if input.baseline_file_paths is not None:
- repo.baseline_file_paths = input.baseline_file_paths
- if input.enable_pr_comments is not None:
- repo.enable_pr_comments = input.enable_pr_comments
- repo.save()
- return repo
-
-
-# --- Artifact Operations ---
-
-
-def get_artifact(repo_id: UUID, content_hash: str) -> Artifact | None:
- return Artifact.objects.filter(repo_id=repo_id, content_hash=content_hash).first()
-
-
-def get_or_create_artifact(
- repo_id: UUID,
- content_hash: str,
- storage_path: str,
- width: int | None = None,
- height: int | None = None,
- size_bytes: int | None = None,
- team_id: int | None = None,
-) -> tuple[Artifact, bool]:
- # Resolve team_id from the repo when not provided by the caller.
- if team_id is None:
- # nosemgrep: idor-lookup-without-team — resolving team_id from repo
- team_id = Repo.objects.values_list("team_id", flat=True).get(id=repo_id)
-
- return Artifact.objects.get_or_create(
- repo_id=repo_id,
- content_hash=content_hash,
- team_id=team_id,
- defaults={
- "storage_path": storage_path,
- "width": width,
- "height": height,
- "size_bytes": size_bytes,
- },
- )
-
-
-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[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]
-
-
-def get_presigned_upload_url(repo_id: UUID, content_hash: str) -> dict | None:
- storage = ArtifactStorage(str(repo_id))
- return storage.get_presigned_upload_url(content_hash)
-
-
-def get_presigned_download_url(repo_id: UUID, content_hash: str) -> str | None:
- storage = ArtifactStorage(str(repo_id))
- return storage.get_presigned_download_url(content_hash)
-
-
-def read_artifact_bytes(repo_id: UUID, content_hash: str) -> bytes | None:
- """Read artifact content from storage."""
- storage = ArtifactStorage(str(repo_id))
- return storage.read(content_hash)
-
-
-def write_artifact_bytes(
- repo_id: UUID,
- content_hash: str,
- content: bytes,
- width: int | None = None,
- height: int | None = None,
- team_id: int | None = None,
-) -> Artifact:
- """
- Write artifact content to storage and create DB record.
- Used for server-generated artifacts like diff images.
- """
- storage = ArtifactStorage(str(repo_id))
- storage_path = storage.write(content_hash, content)
-
- # Resolve team_id from the repo when not provided by the caller.
- if team_id is None:
- # nosemgrep: idor-lookup-without-team — resolving team_id from repo
- team_id = Repo.objects.values_list("team_id", flat=True).get(id=repo_id)
-
- artifact, _ = Artifact.objects.get_or_create(
- repo_id=repo_id,
- content_hash=content_hash,
- team_id=team_id,
- defaults={
- "storage_path": storage_path,
- "width": width,
- "height": height,
- "size_bytes": len(content),
- },
- )
- return artifact
-
-
-# --- Run Operations ---
-
-
-def is_run_stale(run: Run) -> bool:
- return run.superseded_by_id is not None
-
-
-_HAS_CHANGES = Q(changed_count__gt=0) | Q(new_count__gt=0) | Q(removed_count__gt=0)
-_CURRENT = Q(superseded_by__isnull=True)
-
-_ON_PR = Q(pr_number__isnull=False)
-
-REVIEW_STATE_FILTERS: dict[str, Q] = {
- # Only PR runs need human review — master/branch pushes without a PR are just drift
- "needs_review": Q(status=RunStatus.COMPLETED)
- & _HAS_CHANGES
- & Q(approved=False)
- & _CURRENT
- & _ON_PR
- & Q(purpose=RunPurpose.REVIEW),
- "clean": (Q(status=RunStatus.COMPLETED) & ~_HAS_CHANGES) | Q(approved=True),
- "processing": Q(status=RunStatus.PROCESSING) & _CURRENT,
- "stale": Q(superseded_by__isnull=False) & Q(approved=False) & _HAS_CHANGES,
-}
-
-
-# Free-text search over the runs list uses the shared trigram helper for the
-# prose-like fields (branch, run type), where fuzzy/typo matching helps. Commit
-# SHA and PR number are matched exactly (prefix / numeric id) via extra_exact_q —
-# fuzzy matching a hex SHA or an integer is meaningless.
-RUN_SEARCH_FIELDS = (TrigramSearchField("branch"), TrigramSearchField("run_type"))
-
-
-def list_runs_for_team(
- team_id: int,
- review_state: str | None = None,
- repo_id: UUID | None = None,
- pr_number: int | None = None,
- commit_sha: str | None = None,
- branch: str | None = None,
- search: str | None = None,
-) -> db_models.QuerySet[Run]:
- qs = Run.objects.filter(team_id=team_id).select_related("repo")
- if repo_id is not None:
- qs = qs.filter(repo_id=repo_id)
- if review_state and review_state in REVIEW_STATE_FILTERS:
- qs = qs.filter(REVIEW_STATE_FILTERS[review_state])
- if pr_number is not None:
- qs = qs.filter(pr_number=pr_number)
- if commit_sha:
- qs = qs.filter(commit_sha=commit_sha)
- if branch:
- qs = qs.filter(branch=branch)
- if search and (term := normalize_search_term(search)):
- # Commit SHA matches by prefix (reviewers paste the short SHA); PR number by exact id.
- extra_exact_q = Q(commit_sha__istartswith=term)
- if term.isdigit():
- extra_exact_q |= Q(pr_number=int(term))
- return drop_similar_when_exact_exists(
- apply_trigram_search(
- qs,
- term,
- span_prefix="visual_review.runs.search",
- fields=RUN_SEARCH_FIELDS,
- extra_exact_q=extra_exact_q,
- tiebreakers=("-created_at",),
- )
- )
- return qs.order_by("-created_at")
-
-
-def get_review_state_counts(team_id: int, repo_id: UUID | None = None) -> dict[str, int]:
- qs = Run.objects.filter(team_id=team_id)
- if repo_id is not None:
- qs = qs.filter(repo_id=repo_id)
- return qs.aggregate(
- needs_review=Count("id", filter=REVIEW_STATE_FILTERS["needs_review"]),
- clean=Count("id", filter=REVIEW_STATE_FILTERS["clean"]),
- processing=Count("id", filter=REVIEW_STATE_FILTERS["processing"]),
- stale=Count("id", filter=REVIEW_STATE_FILTERS["stale"]),
- )
-
-
-def get_run(run_id: UUID, team_id: int | None = None) -> Run:
- try:
- qs = Run.objects.select_related("repo")
- if team_id is not None:
- qs = qs.filter(team_id=team_id)
- return qs.get(id=run_id)
- except Run.DoesNotExist as e:
- raise RunNotFoundError(f"Run {run_id} not found") from e
-
-
-def _get_run_for_update(run_id: UUID, team_id: int | None = None) -> Run:
- """Get a run with a row-level lock on the writer DB. Must be called inside a transaction."""
- try:
- qs = Run.objects.using(WRITER_DB).select_for_update().select_related("repo")
- if team_id is not None:
- qs = qs.filter(team_id=team_id)
- return qs.get(id=run_id)
- except Run.DoesNotExist as e:
- raise RunNotFoundError(f"Run {run_id} not found") from e
-
-
-def get_run_with_snapshots(run_id: UUID, team_id: int | None = None) -> Run:
- try:
- qs = Run.objects.prefetch_related(
- "snapshots__current_artifact",
- "snapshots__baseline_artifact",
- "snapshots__diff_artifact",
- )
- if team_id is not None:
- qs = qs.filter(team_id=team_id)
- return qs.get(id=run_id)
- except Run.DoesNotExist as e:
- raise RunNotFoundError(f"Run {run_id} not found") from e
-
-
-def _verify_baseline_hashes(repo: Repo, raw_hashes: dict[str, str]) -> dict[str, str]:
- """Verify HMAC signatures on baseline hashes from the CLI.
-
- Accepts a dict of ``{identifier: signed_hash_string}``. Returns a
- dict of ``{identifier: plain_content_hash}`` for entries with valid
- signatures. Invalid or unsigned entries are silently dropped —
- they'll be treated as having no baseline (result = NEW).
- """
- if not raw_hashes:
- return {}
-
- keys = repo.signing_keys or {}
- if not keys:
- # Legitimate baseline files only exist after the server's approval flow
- # has written one (which populates signing_keys). Reaching here means a
- # .snapshots.yml was committed before any approval — likely hand-crafted.
- # Drop every entry rather than passing it through unsigned. Snapshots
- # will classify NEW, surfacing the situation to a reviewer.
- logger.warning(
- "visual_review.baseline_no_signing_keys",
- repo_id=str(repo.id),
- entry_count=len(raw_hashes),
- )
- return {}
-
- repo_id = str(repo.id)
- verified: dict[str, str] = {}
-
- for identifier, signed_hash in raw_hashes.items():
- content_hash = verify_signed_hash(repo_id, identifier, signed_hash, keys)
- if content_hash is not None:
- verified[identifier] = content_hash
- else:
- logger.debug(
- "visual_review.baseline_hash_rejected",
- identifier=identifier,
- reason="invalid_signature",
- )
-
- return verified
-
-
-def _resolve_baselines_at_ref(repo: Repo, github: GitHubIntegration, run_type: str, ref: str) -> dict[str, str]:
- """Fetch baseline content hashes from GitHub at a specific ref (branch name or SHA).
-
- Returns a dict of identifier → content_hash (plain, not signed).
- Returns empty dict when baseline file doesn't exist.
- """
- baseline_paths = repo.baseline_file_paths or {}
- baseline_path = baseline_paths.get(run_type) or baseline_paths.get("default", ".snapshots.yml")
-
- baselines_signed, _sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, ref)
-
- return _verify_baseline_hashes(
- repo,
- {
- identifier: entry["hash"]
- for identifier, entry in baselines_signed.items()
- if isinstance(entry, dict) and "hash" in entry
- },
- )
-
-
-def _get_merge_base_sha(github: GitHubIntegration, repo_full_name: str, base: str, head: str) -> str | None:
- """Get the merge-base SHA between two refs via the GitHub Compare API."""
- try:
- response = github.api_request(
- "GET",
- f"/repos/{repo_full_name}/compare/{quote(base, safe='')}...{quote(head, safe='')}",
- )
- except GitHubIntegrationError:
- logger.warning("visual_review.merge_base_fetch_failed", repo=repo_full_name, base=base, head=head)
- return None
-
- if response.status_code != 200:
- logger.warning(
- "visual_review.merge_base_fetch_failed",
- repo=repo_full_name,
- base=base,
- head=head,
- status=response.status_code,
- )
- return None
-
- sha = response.json().get("merge_base_commit", {}).get("sha")
- if sha is None:
- logger.warning(
- "visual_review.merge_base_sha_missing_from_response",
- repo=repo_full_name,
- base=base,
- head=head,
- )
- return sha
-
-
-def _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:
- """The repo's default branch via the integration's cached verb. Falls back to 'master'."""
- try:
- return github.get_default_branch(repo_full_name)
- except GitHubRateLimitError:
- raise
- except Exception:
- logger.warning("visual_review.default_branch_fetch_failed", repo=repo_full_name)
- return "master"
-
-
-def _run_is_on_default_branch(repo: Repo, branch: str) -> bool:
- """Whether this run targets the repo's GitHub default branch.
-
- Fences the client-supplied ``is_partial`` flag: the default branch holds
- the authoritative full baseline, so a partial run there must not skip
- removed-baseline detection. Resolves the default branch server-side from
- GitHub. Returns ``False`` when it can't be determined (no integration) —
- harmless, since the baseline fetch then returns empty and removal
- detection short-circuits regardless.
- """
- try:
- github = get_github_integration_for_repo(repo)
- except Exception:
- logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
- return False
- return branch == _get_default_branch(github, repo.repo_full_name)
-
-
-def _resolve_baselines(repo, run_type: str, branch: str) -> dict[str, str]:
- """Fetch baseline content hashes from GitHub for snapshot comparison.
-
- Returns a dict of identifier → content_hash (plain, not signed).
- Returns empty dict when no GitHub integration exists or the baseline
- file is missing (first run).
- """
- try:
- github = get_github_integration_for_repo(repo)
- except Exception:
- logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
- return {}
-
- return _resolve_baselines_at_ref(repo, github, run_type, branch)
-
-
-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
- fills in entries that were lost during a rebase (the bot commit
- rewrites the full file, and git rebase replays it destructively).
-
- Branch entries win on conflict so approvals are preserved.
- Identifiers previously approved as REMOVED on this branch are
- tombstoned — healing would otherwise resurrect them from master
- and 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:
- github = get_github_integration_for_repo(repo)
- except Exception:
- logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
- return {}, 0
-
- 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
-
- merge_base_sha = _get_merge_base_sha(github, repo.repo_full_name, default_branch, branch)
- if not merge_base_sha:
- return branch_baseline, 0
-
- try:
- merge_base_baseline = _resolve_baselines_at_ref(repo, github, run_type, merge_base_sha)
- except Exception:
- logger.warning(
- "visual_review.merge_base_baseline_fetch_failed",
- repo_id=str(repo.id),
- branch=branch,
- merge_base_sha=merge_base_sha,
- )
- return branch_baseline, 0
- if not merge_base_baseline:
- return branch_baseline, 0
-
- 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)
- merged = {**healable_merge_base, **branch_baseline}
-
- if healed or tombstoned:
- logger.info(
- "visual_review.baseline_healed",
- repo_id=str(repo.id),
- branch=branch,
- healed_count=len(healed),
- branch_count=len(branch_baseline),
- merge_base_count=len(merge_base_baseline),
- merged_count=len(merged),
- tombstoned_count=len(tombstoned),
- )
-
- return merged, len(healed)
-
-
-_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
- they're missing from branch. Without tombstoning, an approved
- removal keeps reappearing: the bot commit drops it from the branch
- file, but the next run's merge-base fetch re-adds it and classifies
- it REMOVED all over again.
-
- 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__approved=True,
- review_state=ReviewState.APPROVED,
- identifier=OuterRef("identifier"),
- )
- .order_by("-run__created_at")
- .values("run__created_at")[:1]
- )
-
- return set(
- RunSnapshot.objects.using(WRITER_DB)
- .filter(
- branch_scope,
- run__repo=repo,
- run__run_type=run_type,
- run__approved=True,
- review_state=ReviewState.APPROVED,
- result=SnapshotResult.REMOVED,
- )
- .annotate(latest_approved_at=Subquery(latest_approved_run))
- .filter(run__created_at=F("latest_approved_at"))
- .values_list("identifier", flat=True)
- .distinct()
- )
-
-
-def create_run(input: CreateRunInput, team_id: int) -> tuple[Run, list[dict]]:
- """
- Create a new run with its snapshots.
-
- Returns the run and list of upload targets for missing artifacts.
- Each upload target has: content_hash, url, fields
-
- input.baseline_hashes, input.unchanged_count and input.removed_identifiers
- are deprecated and ignored: the backend fetches baselines from GitHub and
- computes everything. The fields are kept for backward compat with older
- CLI versions.
-
- input.is_partial tags the run as a subset; the classifier then leaves baseline
- identifiers we didn't touch alone instead of marking them as removed.
- """
- repo = get_repo(input.repo_id, team_id)
-
- return _create_run_inner(repo, team_id, input)
-
-
[email protected](using=WRITER_DB)
-def _create_run_inner(repo: Repo, team_id: int, input: CreateRunInput) -> tuple[Run, list[dict]]:
- # Supersede ALL old runs before inserting the new one. The unique
- # partial index on (repo, branch, run_type) WHERE superseded_by IS NULL
- # requires the slot to be free before the insert. A new CI push always
- # replaces the previous run — approved and clean runs still show up in
- # their respective UI filters via REVIEW_STATE_FILTERS.
- supersede_filter = Run.objects.using(WRITER_DB).filter(
- repo_id=repo.id,
- branch=input.branch,
- run_type=input.run_type,
- superseded_by__isnull=True,
- )
- # Collect IDs before mutating, then self-reference to clear the slot
- superseded_ids = list(supersede_filter.values_list("id", flat=True))
- if superseded_ids:
- from django.db.models import F
-
- Run.objects.using(WRITER_DB).filter(id__in=superseded_ids, team_id=team_id).update(superseded_by=F("id"))
-
- run = Run.objects.create(
- repo=repo,
- team_id=repo.team_id,
- run_type=input.run_type,
- commit_sha=input.commit_sha,
- branch=input.branch,
- pr_number=input.pr_number,
- purpose=input.purpose,
- total_snapshots=len(input.snapshots),
- metadata=input.metadata or {},
- is_partial=input.is_partial,
- )
-
- # Fix up the sentinel pointers to reference the actual new run
- if superseded_ids:
- Run.objects.using(WRITER_DB).filter(id__in=superseded_ids, team_id=team_id).update(superseded_by=run)
-
- snapshots = [
- {
- "identifier": s.identifier,
- "content_hash": s.content_hash,
- "width": s.width,
- "height": s.height,
- "metadata": dict(s.metadata) if s.metadata else {},
- }
- for s in input.snapshots
- ]
- _added, uploads = _register_snapshots(run, repo, snapshots)
- _update_run_counts(run, using=WRITER_DB)
-
- transaction.on_commit(
- lambda: _post_commit_status(run, repo, "pending", "Visual review in progress"), using=WRITER_DB
- )
-
- return run, uploads
-
-
-def _register_snapshots(
- run: Run,
- repo: Repo,
- snapshots: list[dict],
-) -> tuple[int, list[dict]]:
- """Store snapshot rows and generate upload URLs.
-
- Stores raw identifier + hash pairs. Classification (CHANGED/NEW/UNCHANGED/REMOVED)
- happens at complete_run time when the baseline is fetched once.
- Idempotent per (run, identifier) via unique constraint — safe for retries.
- """
- repo_id = repo.id
- all_hashes: set[str] = set()
- added_count = 0
-
- for snap in snapshots:
- identifier = snap["identifier"]
- current_hash = snap["content_hash"]
- all_hashes.add(current_hash)
-
- _snapshot, created = RunSnapshot.objects.get_or_create(
- run=run,
- team_id=repo.team_id,
- identifier=identifier,
- defaults={
- "current_hash": current_hash,
- "baseline_hash": "",
- "result": SnapshotResult.NEW, # Provisional — reclassified at complete time
- "current_width": snap.get("width"),
- "current_height": snap.get("height"),
- "metadata": snap.get("metadata") or {},
- },
- )
- if created:
- added_count += 1
-
- # Generate upload URLs for missing artifacts
- missing_hashes = find_missing_hashes(repo_id, list(all_hashes))
- storage = ArtifactStorage(str(repo_id))
-
- uploads = []
- for content_hash in missing_hashes:
- upload_data = storage.get_presigned_upload_url(content_hash)
- if upload_data:
- uploads.append(
- {
- "content_hash": content_hash,
- "url": upload_data["url"],
- "fields": upload_data["fields"],
- }
- )
-
- return added_count, uploads
-
-
-def _update_run_counts(run: Run, using: str | None = None) -> None:
- """Recalculate result counts from RunSnapshot rows."""
- db_alias = using or WRITER_DB
- counts = RunSnapshot.objects.using(db_alias).filter(run_id=run.id).values("result").annotate(n=Count("id"))
- by_result = {row["result"]: row["n"] for row in counts}
-
- run.changed_count = by_result.get(SnapshotResult.CHANGED, 0)
- run.new_count = by_result.get(SnapshotResult.NEW, 0)
- run.removed_count = by_result.get(SnapshotResult.REMOVED, 0)
- run.save(using=db_alias, update_fields=["changed_count", "new_count", "removed_count"])
-
-
-def add_snapshots_to_run(
- run_id: UUID,
- team_id: int,
- snapshots: list[dict],
- baseline_hashes: dict[str, str] | None = None,
- unchanged_count: int = 0,
-) -> tuple[int, list[dict]]:
- """Add a batch of snapshots to an existing run (shard-based flow).
-
- Returns (added_count, upload_targets). Idempotent — safe for retries.
- baseline_hashes is deprecated — backend fetches from GitHub.
- """
- run = get_run(run_id, team_id=team_id)
-
- if run.status != RunStatus.PENDING:
- raise ValueError(f"Can only add snapshots to pending runs (current status: {run.status})")
-
- repo = run.repo
-
- return _add_snapshots_inner(run, run_id, team_id, repo, snapshots)
-
-
[email protected](using=WRITER_DB)
-def _add_snapshots_inner(run, run_id, team_id, repo, snapshots):
- added, uploads = _register_snapshots(run, repo, snapshots)
-
- # Atomically increment total (safe for concurrent shards)
- Run.objects.using(WRITER_DB).filter(id=run_id, team_id=team_id).update(total_snapshots=F("total_snapshots") + added)
- _update_run_counts(run, using=WRITER_DB)
-
- return added, uploads
-
-
-def mark_run_processing(run_id: UUID) -> Run:
- run = get_run(run_id)
- run.status = RunStatus.PROCESSING
- run.save(update_fields=["status"])
- return run
-
-
-def complete_run(run_id: UUID) -> Run:
- """
- Complete a run: detect removals, classify snapshots, hand off to the diff task.
-
- 1. Fetches baseline from GitHub, diffs against RunSnapshot rows to find removed
- 2. Creates REMOVED RunSnapshot rows
- 3. Classifies snapshots and updates run counts
- 4. Either verifies uploads + finishes synchronously (no-change fast path) or
- enqueues process_run_diffs which verifies + diffs + finishes
-
- Idempotent: returns immediately if already processing or completed.
- """
- run = get_run(run_id)
- if run.status in (RunStatus.COMPLETED, RunStatus.PROCESSING):
- return run
-
- # Transition to PROCESSING early so late add_snapshots calls are rejected.
- # Atomic update with condition prevents race with concurrent complete calls.
- updated = Run.objects.filter(id=run_id, team_id=run.repo.team_id, status=RunStatus.PENDING).update(
- status=RunStatus.PROCESSING
- )
- if not updated:
- # Another complete_run got here first, or status changed
- return get_run(run_id)
-
- repo = run.repo
-
- # 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, commit_sha=run.commit_sha
- )
- except GitHubRateLimitError:
- # Roll back to PENDING so the caller can retry after the limit resets
- Run.objects.filter(id=run_id).update(status=RunStatus.PENDING)
- raise
- if healed_count:
- run.metadata["baseline_healed_from_merge_base"] = healed_count
- run.save(using=WRITER_DB, update_fields=["metadata"])
-
- # Pre-load tolerated hashes scoped to this run's identifiers and baseline hashes
- run_identifiers = set(run.snapshots.using(WRITER_DB).values_list("identifier", flat=True))
- 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
-
- # is_partial is client-supplied and only suppresses removed-baseline
- # detection. Never honor it on the default branch (authoritative full
- # baseline), so a token can't hide deleted snapshots from the gate. Persist
- # the correction so every downstream reader (status posting, UI) sees the
- # effective value rather than the raw client claim.
- #
- # On PR branches honoring the client is deliberate, but a partial run must
- # never satisfy the gating status context: _post_commit_status routes it to
- # a separate non-gating "(partial)" context (see there). Branch protection
- # keys off context + state, not the human-facing description, so a separate
- # context is what actually keeps a one-flag subset run from turning the gate
- # green — the description annotation alone does not.
- if run.is_partial and _run_is_on_default_branch(repo, run.branch):
- logger.warning(
- "visual_review.is_partial_ignored_on_default_branch",
- run_id=str(run.id),
- branch=run.branch,
- )
- run.is_partial = False
- run.save(using=WRITER_DB, update_fields=["is_partial"])
-
- classifier = SnapshotClassifier(run, baseline, tolerated_lookup, is_partial=run.is_partial)
- classifier.classify()
-
- # Update total and counts from actual RunSnapshot rows
- run.total_snapshots = run.snapshots.using(WRITER_DB).count()
- run.save(using=WRITER_DB, update_fields=["total_snapshots"])
- _update_run_counts(run, using=WRITER_DB)
-
- run = get_run(run_id)
-
- # No-changes fast path: verify any pending uploads synchronously, then
- # finish. Skipping verify here would silently drop uploads whenever an
- # Artifact row is missing for a hash that the baseline still points at
- # (e.g. DB cleanup removed the row but the GitHub-side baseline file
- # wasn't updated). The CLI re-uploads via find_missing_hashes, the
- # snapshot classifies as UNCHANGED, and the bytes never get checked or
- # recorded — leaving every future run requesting the same upload while
- # CI posts green.
- if run.changed_count == 0 and run.new_count == 0:
- from .tasks.tasks import emit_run_processing_metrics # noqa: PLC0415 — avoids the logic/tasks circular import
-
- try:
- verify_uploads_and_create_artifacts(run_id)
- except HashIntegrityError as e:
- logger.warning("visual_review.hash_integrity_failed", run_id=str(run_id), error=str(e))
- finish_processing(run_id, error_message=str(e))
- emit_run_processing_metrics.delay(run.team_id, str(run_id), "hash_integrity_failed", 0)
- return get_run(run_id)
- finish_processing(run_id)
- emit_run_processing_metrics.delay(run.team_id, str(run_id), "completed", 0)
- return get_run(run_id)
-
- mark_run_processing(run_id)
- from .tasks.tasks import process_run_diffs
-
- process_run_diffs.delay(run.team_id, str(run_id))
- return get_run(run_id)
-
-
-def verify_uploads_and_create_artifacts(run_id: UUID) -> int:
- """
- Verify S3 uploads, check hash integrity, and create Artifact records.
-
- For each new upload (no existing Artifact), reads the PNG bytes from S3,
- decodes to sRGB RGBA, and computes the BLAKE3 hash. The CLI-claimed hash
- is used only as a lookup key into S3 — once verified, it's discarded and
- the server-computed hash is used everywhere downstream. This ensures the
- CLI cannot (accidentally or maliciously) associate wrong hashes with image
- content.
-
- Verification runs in two passes so a late failure can't leave a partial
- set of Artifact rows behind: pass 1 reads + hashes all uploads, pass 2
- creates Artifact rows from the verified results.
-
- Raises HashIntegrityError if any upload fails verification.
-
- Returns number of artifacts created.
- """
- from .hashing import ImageTooLargeError, hash_image
-
- run = get_run(run_id)
- repo_id = run.repo_id
- storage = 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[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 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, int, dict[str, int | None]]] = []
- for claimed_hash, metadata in expected_hashes.items():
- if claimed_hash in existing_hashes:
- continue
-
- png_bytes = storage.read(claimed_hash)
- if png_bytes is None:
- # Race: complete_run fired before the CLI's S3 upload landed, or
- # the upload was never made. Log loudly so we can spot it instead
- # of silently dropping the artifact and forcing the next run to
- # re-upload the same content.
- logger.warning(
- "visual_review.upload_missing_in_s3",
- run_id=str(run_id),
- claimed_hash=claimed_hash,
- )
- continue
- if len(png_bytes) == 0:
- raise HashIntegrityError(f"Upload rejected: empty file for hash {claimed_hash[:16]}…")
-
- try:
- actual_hash = hash_image(png_bytes)
- except ImageTooLargeError as e:
- logger.exception(
- "visual_review.hash_image_too_large",
- run_id=str(run_id),
- claimed_hash=claimed_hash,
- error=str(e),
- )
- raise HashIntegrityError(f"Upload rejected: {e}") from e
- except Exception as e:
- # Pillow can raise UnidentifiedImageError, DecompressionBombError,
- # OSError, etc. Funnel everything into HashIntegrityError so the
- # task handler routes it through the structured-failure path
- # instead of celery's retry loop.
- logger.exception(
- "visual_review.hash_image_failed",
- run_id=str(run_id),
- claimed_hash=claimed_hash,
- error=str(e),
- error_type=type(e).__name__,
- )
- raise HashIntegrityError(
- f"Upload integrity check failed: could not decode image for hash {claimed_hash[:16]}…"
- ) from e
-
- if actual_hash != claimed_hash:
- logger.error(
- "visual_review.hash_integrity_failure",
- run_id=str(run_id),
- claimed_hash=claimed_hash,
- actual_hash=actual_hash,
- )
- raise HashIntegrityError(
- f"Upload integrity check failed: claimed {claimed_hash[:16]}… but image hashes to {actual_hash[:16]}…"
- )
-
- 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.
- artifacts = [
- Artifact(
- repo_id=repo_id,
- content_hash=actual_hash,
- storage_path=storage._key(actual_hash),
- width=metadata.get("width"),
- height=metadata.get("height"),
- 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)
-
- return len(artifacts)
-
-
-def _stamp_quarantine(run: Run) -> None:
- """Evaluate quarantine policy and freeze it on each snapshot."""
- now = timezone.now()
- quarantined_ids = set(
- QuarantinedIdentifier.objects.using(WRITER_DB)
- .filter(repo_id=run.repo_id, run_type=run.run_type, team_id=run.team_id)
- .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
- .values_list("identifier", flat=True)
- )
-
- if not quarantined_ids:
- run.snapshots.using(WRITER_DB).filter(is_quarantined=True).update(is_quarantined=False)
- return
-
- snapshots = run.snapshots.using(WRITER_DB)
- snapshots.filter(identifier__in=quarantined_ids, is_quarantined=False).update(is_quarantined=True)
- snapshots.filter(is_quarantined=True).exclude(identifier__in=quarantined_ids).update(is_quarantined=False)
-
-
-def _is_unresolved(s: RunSnapshot) -> bool:
- """A snapshot is unresolved if it represents a change that hasn't been dealt with."""
- if s.result == SnapshotResult.UNCHANGED:
- return False
- if s.is_quarantined:
- return False
- if s.review_state in (ReviewState.TOLERATED, ReviewState.APPROVED):
- return False
- return True
-
-
-def _approved_baseline_updates(snapshots: Iterable[RunSnapshot]) -> list[dict]:
- """The committed-baseline update set: approved changed/new snapshots, by approved hash.
-
- Derived from DB state so the commit always reflects every approval regardless of how
- many calls it took. Tolerated snapshots are excluded — toleration never updates the baseline.
- """
- return [
- {"identifier": s.identifier, "new_hash": s.approved_hash}
- for s in snapshots
- if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW)
- and not s.is_quarantined
- and s.review_state == ReviewState.APPROVED
- ]
-
-
-def _format_change_counts(changed: int, new: int, removed: int) -> str:
- """'N changed, M new, K removed', omitting zero counts; '' when all are zero."""
- parts = []
- if changed:
- parts.append(f"{changed} changed")
- if new:
- parts.append(f"{new} new")
- if removed:
- parts.append(f"{removed} removed")
- return ", ".join(parts)
-
-
-def _changes_summary(run: Run) -> str:
- """Change summary from the run's denormalized (quarantine-excluded) counts."""
- return _format_change_counts(run.changed_count, run.new_count, run.removed_count)
-
-
-def _update_counts_and_post_status(run: Run) -> int:
- """Re-stamp quarantine, recount snapshots, compute unresolved, and post commit status.
-
- Counts on the run (changed_count, new_count, removed_count) reflect the raw
- classifier output excluding quarantined snapshots. The unresolved count is
- computed separately for the commit status and CI gate — it further excludes
- tolerated and approved snapshots.
-
- Returns the unresolved count.
- """
- _stamp_quarantine(run)
-
- snapshots = list(run.snapshots.using(WRITER_DB).select_related("tolerated_hash_match").all())
-
- run.changed_count = sum(1 for s in snapshots if s.result == SnapshotResult.CHANGED and not s.is_quarantined)
- run.new_count = sum(1 for s in snapshots if s.result == SnapshotResult.NEW and not s.is_quarantined)
- run.removed_count = sum(1 for s in snapshots if s.result == SnapshotResult.REMOVED and not s.is_quarantined)
- run.tolerated_match_count = sum(
- 1
- for s in snapshots
- if s.tolerated_hash_match is not None and s.tolerated_hash_match.reason == ToleratedReason.HUMAN
- )
- run.save(
- update_fields=[
- "changed_count",
- "new_count",
- "removed_count",
- "tolerated_match_count",
- ]
- )
-
- unresolved = sum(1 for s in snapshots if _is_unresolved(s))
-
- # Approved-but-uncommitted changes still block the gate: the baseline on the PR branch
- # doesn't reflect them yet, so re-running CI would re-detect them. Only finalize commits
- # the baseline (and posts success directly), so until then the gate must stay red.
- pending_commit = 0 if run.approved else len(_approved_baseline_updates(snapshots))
-
- repo = run.repo
- if run.error_message:
- _post_commit_status(run, repo, "error", f"Visual review failed: {run.error_message[:100]}")
- elif run.purpose == RunPurpose.OBSERVE:
- # Default-branch (tracking-only) runs never gate — there's no PR to approve.
- # Report any changes as a green, informational status instead of a blocking
- # failure; the per-snapshot detail lives in the VR UI (linked via target_url).
- summary = _changes_summary(run)
- description = f"Tracking only: {summary} recorded" if summary else "Tracking only: no visual changes"
- _post_commit_status(run, repo, "success", description)
- elif unresolved > 0:
- _post_commit_status(run, repo, "failure", f"Visual changes detected: {_changes_summary(run)}")
- _post_review_prompt_comment(run, repo)
- elif pending_commit > 0:
- _post_commit_status(
- run,
- repo,
- "failure",
- f"{pending_commit} approved change(s) awaiting commit — finalize the run to update the baseline",
- )
- else:
- _post_commit_status(run, repo, "success", "No visual changes")
-
- return unresolved
-
-
-def finish_processing(run_id: UUID, error_message: str = "") -> Run:
- run = get_run_with_snapshots(run_id)
-
- run.status = RunStatus.FAILED if error_message else RunStatus.COMPLETED
- run.error_message = error_message
- run.completed_at = timezone.now()
- run.save(update_fields=["status", "error_message", "completed_at"])
-
- _update_counts_and_post_status(run)
-
- return run
-
-
-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
- comparison (changed / new / removed vs. unchanged / tolerated). That's the
- signal to tell a snapshot-determinism regression — where the changed rate
- climbs because images stop being byte-stable, so the content-hash dedup and
- tolerance cache stop absorbing work — apart from plain run-volume growth.
- Where the time goes is captured separately as OTel spans in the task.
-
- Best-effort: instrumentation must never fail or slow the task, so every
- error is swallowed — including so it can't mask a real exception when
- called from the task's ``finally``.
- """
- try:
- try:
- run = Run.objects.using(WRITER_DB).select_related("repo").get(id=run_id)
- except Run.DoesNotExist:
- return
-
- properties = {
- "run_id": str(run.id),
- "run_type": run.run_type,
- "outcome": outcome,
- "status": run.status,
- "repo": run.repo.repo_full_name,
- "branch": run.branch,
- "pr_number": run.pr_number,
- "team_id": run.team_id,
- "is_partial": run.is_partial,
- "total_snapshots": run.total_snapshots,
- "changed_count": run.changed_count,
- "new_count": run.new_count,
- "removed_count": run.removed_count,
- "tolerated_match_count": run.tolerated_match_count,
- "diffed_count": diffed_count,
- "reviewable_count": run.changed_count + run.new_count + run.removed_count,
- }
-
- with ph_scoped_capture() as capture_ph_event:
- capture_ph_event(
- 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)
-
-
[email protected](using=WRITER_DB)
-def recompute_run(run_id: UUID, team_id: int | None = None) -> dict:
- """Re-evaluate quarantine and counts, update commit status, and optionally rerun the CI job.
-
- Returns a dict with counts_changed, ci_rerun_triggered, and ci_rerun_error.
- """
- run = _get_run_for_update(run_id, team_id=team_id)
-
- if run.status != RunStatus.COMPLETED:
- raise ValueError(f"Can only recompute completed runs (current status: {run.status})")
-
- if run.approved:
- raise ValueError("Run is already approved")
-
- old_counts = (run.changed_count, run.new_count, run.removed_count)
- unresolved = _update_counts_and_post_status(run)
- new_counts = (run.changed_count, run.new_count, run.removed_count)
- counts_changed = old_counts != new_counts
-
- ci_rerun_triggered = False
- ci_rerun_error: str | None = None
-
- check_run_id = (run.metadata or {}).get("github_check_run_id")
-
- if not check_run_id:
- ci_rerun_error = "CI job ID not available (set JOB_CHECK_RUN_ID=${{ job.check_run_id }} in workflow)"
- else:
- # Stored as a string, but coerce defensively — `_rerun_github_job` calls `.isdigit()`.
- ci_rerun_triggered, ci_rerun_error = _rerun_github_job(run, str(check_run_id))
-
- return {
- "counts_changed": counts_changed,
- "unresolved": unresolved,
- "ci_rerun_triggered": ci_rerun_triggered,
- "ci_rerun_error": ci_rerun_error,
- }
-
-
-def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:
- """Rerun the visual-review CI job by its numeric ID. Returns (success, error_message).
-
- The job ID and workflow run ID both come from client-supplied run metadata
- (the CI runner has no server-verified channel today), so before calling
- GitHub we bind the rerun two ways: the job must run on this run's commit
- (``head_sha``) and must belong to the workflow run recorded at creation
- (``github_run_id``). That pins recompute to the workflow run that produced
- this visual-review run instead of letting it re-trigger any job on the
- commit. It is defense-in-depth, not an identity proof — a caller who forges
- a self-consistent metadata set can still reach sibling jobs of that run.
- """
- if not check_run_id.isdigit():
- return False, "Invalid check run ID"
-
- repo = run.repo
- if not repo.repo_full_name:
- return False, "Repo has no GitHub full name configured"
-
- expected_run_id = (run.metadata or {}).get("github_run_id")
- if not expected_run_id:
- return False, "Workflow run ID not recorded for this run"
-
- # `${{ job.check_run_id }}` doubles as the Actions job ID, so the jobs API
- # gives us head_sha and the owning workflow run (run_id) in one call.
- try:
- job_response = _github_api_request("GET", repo, f"actions/jobs/{check_run_id}")
- except Exception:
- return False, "Failed to verify CI job ownership"
-
- if job_response.status_code != 200:
- return False, f"Could not fetch CI job details (status {job_response.status_code})"
-
- try:
- job_data = job_response.json()
- except Exception:
- return False, "Failed to parse CI job response"
-
- if job_data.get("head_sha") != run.commit_sha:
- logger.warning(
- "visual_review.ci_rerun_sha_mismatch",
- run_id=str(run.id),
- check_run_id=check_run_id,
- expected_sha=run.commit_sha,
- actual_sha=job_data.get("head_sha"),
- )
- return False, "Check run does not belong to this commit"
-
- if str(job_data.get("run_id")) != str(expected_run_id):
- logger.warning(
- "visual_review.ci_rerun_workflow_mismatch",
- run_id=str(run.id),
- check_run_id=check_run_id,
- expected_workflow_run=str(expected_run_id),
- actual_workflow_run=str(job_data.get("run_id")),
- )
- return False, "CI job does not belong to this run's workflow"
-
- try:
- response = _github_api_request("POST", repo, f"actions/jobs/{check_run_id}/rerun")
- except Exception:
- return False, "Failed to trigger job rerun"
-
- if response.status_code == 201:
- logger.info(
- "visual_review.ci_job_rerun_triggered",
- run_id=str(run.id),
- check_run_id=check_run_id,
- )
- return True, None
-
- return False, f"GitHub API returned {response.status_code} when rerunning job"
-
-
-def get_github_integration_for_repo(repo: Repo):
- """Get GitHub integration for the repo's team."""
- from posthog.models.integration import GitHubIntegration, Integration
-
- integration = Integration.objects.filter(team_id=repo.team_id, kind="github").first()
-
- if not integration:
- raise GitHubIntegrationNotFoundError(f"No GitHub integration found for team {repo.team_id}")
-
- return GitHubIntegration(integration, source="visual_review")
-
-
-def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:
- """
- Look up the current full_name of a repo by its numeric GitHub ID.
-
- Used to detect renames: GET /repositories/{id} always returns the
- latest full_name even if the repo was renamed or transferred.
- Returns None if the repo is inaccessible.
- """
- response = github.api_request("GET", f"/repositories/{repo_external_id}")
- if response.status_code == 200:
- return response.json().get("full_name")
- return None
-
-
-def _github_api_request(
- method: str,
- repo: Repo,
- path: str,
- *,
- json: Mapping[str, object] | None = None,
- timeout: int = 10,
-) -> requests.Response:
- """
- Make a GitHub API request, auto-resolving renamed repos on 404.
-
- If the request returns 404 and the repo has an external ID, looks up
- the current full_name via /repositories/{id}. If it changed, updates
- the stored repo_full_name and retries once.
- """
- # Prevent path traversal — each segment must be safe
- safe_path = "/".join(quote(segment, safe="") for segment in path.split("/"))
-
- github = get_github_integration_for_repo(repo)
-
- response = github.api_request(method, f"/repos/{repo.repo_full_name}/{safe_path}", json_body=json, timeout=timeout)
-
- if response.status_code == 404 and repo.repo_external_id:
- new_full_name = _resolve_repo_by_id(github, repo.repo_external_id)
- if new_full_name and new_full_name != repo.repo_full_name:
- logger.info(
- "visual_review.repo_renamed",
- repo_id=str(repo.id),
- old_name=repo.repo_full_name,
- new_name=new_full_name,
- )
- repo.repo_full_name = new_full_name
- repo.save(update_fields=["repo_full_name"])
-
- response = github.api_request(
- method, f"/repos/{new_full_name}/{safe_path}", json_body=json, timeout=timeout
- )
-
- return response
-
-
-def _get_pr_info(github, repo_full_name: str, pr_number: int) -> dict:
- """
- Fetch PR info from GitHub.
-
- Returns dict with head_ref (branch) and head_sha.
- """
- response = github.api_request("GET", f"/repos/{repo_full_name}/pulls/{pr_number}")
-
- if response.status_code != 200:
- raise GitHubCommitError(f"Failed to fetch PR info: {response.status_code} {response.text}")
-
- pr_data = response.json()
- return {
- "head_ref": pr_data["head"]["ref"],
- "head_sha": pr_data["head"]["sha"],
- }
-
-
-def _fetch_baseline_file(
- github, repo_full_name: str, file_path: str, branch: str
-) -> tuple[dict[str, dict], str | None]:
- """
- Fetch current baseline file content from GitHub.
-
- Returns ``(snapshots_dict, file_sha)``. Snapshots dict maps
- identifier to ``{hash: "v1.kid.hash.tag"}`` (the signed format).
- If the file doesn't exist, returns ``({}, None)``.
- """
- import yaml
-
- try:
- result = github.get_file_contents(repo_full_name, file_path, ref=branch)
- except GitHubRateLimitError:
- raise
- except GitHubIntegrationError as e:
- raise GitHubCommitError(f"Failed to fetch baseline file: {e}") from e
-
- if result is None:
- return {}, None
-
- file_sha = result["sha"]
-
- parsed = yaml.safe_load(result["content"])
- if not parsed or parsed.get("version") != 1:
- return {}, file_sha
-
- raw_snapshots = parsed.get("snapshots", {})
-
- normalized: dict[str, dict] = {}
- for identifier, value in raw_snapshots.items():
- if isinstance(value, dict) and "hash" in value:
- normalized[identifier] = value
- return normalized, file_sha
-
-
-def _build_snapshots_yaml(
- repo: Repo,
- current_baselines: dict[str, dict],
- updates: list[dict],
-) -> str:
- """Build updated snapshots.yml with HMAC-signed hashes.
-
- Each snapshot value is ``{hash: "v1.<kid>.<blake3hex>.<mac>"}``
- where the MAC binds the hash to the repo and identifier.
-
- *current_baselines* maps identifier to ``{hash: signed_hash_str}``.
- *updates* is a list of ``{identifier, new_hash}`` where ``new_hash``
- is a plain content hash — it gets signed here.
- """
- import yaml
-
- kid, secret_hex = repo.get_active_signing_key()
- repo_id = str(repo.id)
-
- merged = dict(current_baselines)
- for update in updates:
- identifier = update["identifier"]
- content_hash = update["new_hash"]
- signed = sign_snapshot_hash(repo_id, identifier, content_hash, secret_hex, kid)
- merged[identifier] = {"hash": signed}
-
- sorted_snapshots = dict(sorted(merged.items()))
-
- data: dict = {
- "version": 1,
- "config": {
- "api": settings.SITE_URL,
- "team": str(repo.team_id),
- "repo": str(repo.id),
- },
- "snapshots": sorted_snapshots,
- }
-
- return yaml.dump(data, default_flow_style=False, sort_keys=False, indent=4)
-
-
-def _post_commit_status(
- run: Run,
- repo: Repo,
- state: str,
- description: str,
-) -> None:
- """
- Post a commit status to GitHub (best-effort, never raises).
-
- Uses the GitHub Commit Statuses API:
- POST /repos/{owner}/{repo}/statuses/{sha}
-
- state: "pending", "success", "failure", "error"
-
- Partial runs (is_partial, client-supplied) suppress removed-baseline
- detection on PR branches, so they must not be able to satisfy the gating
- status context that branch protection evaluates. Branch protection keys off
- the (context, state) pair, not the human-facing description, so a partial
- run is posted to a separate "PostHog Visual Review / {run_type} (partial)"
- context rather than the gating "PostHog Visual Review / {run_type}" one.
- A subset run therefore can never turn the gated context green; a reviewer
- must require the partial context explicitly to gate on partial runs. The
- description is also annotated so the disclosure is visible to humans.
- """
- if not repo.repo_full_name:
- return
-
- context = f"PostHog Visual Review / {run.run_type}"
- # Tracking-only (observe) and partial runs must never satisfy the gating context that
- # branch protection evaluates. Both purpose and is_partial are client-supplied, so an
- # observe run posted to the gating context could green a PR head SHA's required check
- # without review. Route them to a distinct, non-gating context instead.
- if run.purpose == RunPurpose.OBSERVE:
- context = f"{context} (tracking)"
- elif run.is_partial:
- context = f"{context} (partial)"
- description = f"{description} (partial run)"
-
- try:
- github = get_github_integration_for_repo(repo)
- except Exception:
- logger.debug("visual_review.status_check_skipped", run_id=str(run.id), reason="no_github_integration")
- return
-
- target_url = _run_url(run, repo)
-
- try:
- response = github.api_request(
- "POST",
- f"/repos/{repo.repo_full_name}/statuses/{run.commit_sha}",
- json_body={
- "state": state,
- "description": description[:140],
- "context": context,
- "target_url": target_url,
- },
- )
-
- if response.status_code != 201:
- logger.warning(
- "visual_review.status_check_failed",
- run_id=str(run.id),
- status_code=response.status_code,
- response=response.text[:200],
- )
- except Exception:
- logger.warning("visual_review.status_check_error", run_id=str(run.id), exc_info=True)
-
-
-def _get_coauthor_trailer(user_id: int, installation_id: str) -> str | None:
- """Return a `Co-authored-by` trailer for the approver, if they have a personal
- GitHub integration for the same installation. Returns None when no match exists.
- """
- from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
-
- user_integration = UserIntegration.objects.filter(
- user_id=user_id,
- kind=UserIntegration.IntegrationKind.GITHUB,
- integration_id=installation_id,
- ).first()
- if user_integration is None:
- return None
- return UserGitHubIntegration(user_integration).coauthor_trailer
-
-
-def _commit_baseline_to_github(
- run: Run, repo: Repo, approved_snapshots: list[dict], approver_user_id: int | None = None
-) -> dict:
- """
- Commit updated baseline file to GitHub.
-
- Raises:
- GitHubIntegrationNotFoundError: No GitHub integration for team
- PRSHAMismatchError: PR has newer commits than this run
- BaselineFilePathNotConfiguredError: No baseline path for run type
- GitHubCommitError: GitHub API error
- """
- baseline_paths = repo.baseline_file_paths or {}
- baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")
-
- if not baseline_path:
- raise BaselineFilePathNotConfiguredError(f"No baseline file path configured for run type {run.run_type}")
-
- github = get_github_integration_for_repo(repo)
-
- if run.pr_number is None:
- raise GitHubCommitError("Cannot commit to GitHub: run has no associated PR number")
-
- pr_info = _get_pr_info(github, repo.repo_full_name, run.pr_number)
-
- if pr_info["head_sha"] != run.commit_sha:
- raise PRSHAMismatchError(
- f"PR has newer commits. Expected {run.commit_sha}, got {pr_info['head_sha']}. "
- "Please re-run visual tests on the latest commit."
- )
-
- current_baselines, file_sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, pr_info["head_ref"])
-
- # Remove entries for snapshots detected as removed in this run
- removed_identifiers = set(run.snapshots.filter(result=SnapshotResult.REMOVED).values_list("identifier", flat=True))
- for identifier in removed_identifiers:
- current_baselines.pop(identifier, None)
-
- updates = [{"identifier": s["identifier"], "new_hash": s["new_hash"]} for s in approved_snapshots]
- new_content = _build_snapshots_yaml(repo, current_baselines, updates)
-
- # Use GitHubIntegration.update_file() - it expects just the repo name, not full path
- # The org comes from github.organization()
- repo_name = repo.repo_full_name.split("/")[-1] if "/" in repo.repo_full_name else repo.repo_full_name
-
- updated_count = len(updates)
- removed_count = len(removed_identifiers)
- parts = [f"{updated_count} updated"]
- if removed_count:
- parts.append(f"{removed_count} removed")
- summary = ", ".join(parts)
- commit_message = f"chore(visual): update {run.run_type} baselines\n\n{summary}\nRun: {run.id}"
-
- installation_id = github.integration.integration_id
- if approver_user_id is not None and isinstance(installation_id, str) and installation_id:
- trailer = _get_coauthor_trailer(approver_user_id, installation_id)
- if trailer:
- commit_message = f"{commit_message}\n\n{trailer}"
-
- result = github.update_file(
- repository=repo_name,
- file_path=baseline_path,
- content=new_content,
- commit_message=commit_message,
- branch=pr_info["head_ref"],
- sha=file_sha,
- )
-
- if not result.get("success"):
- raise GitHubCommitError(f"Failed to commit baseline: {result.get('error')}")
-
- run.metadata["baseline_commit_sha"] = result.get("commit_sha")
- run.save(update_fields=["metadata"])
-
- return result
-
-
-def _find_existing_comment_id(repo: Repo, pr_number: int, exclude_run_id: UUID) -> int | None:
- """Find the GitHub comment ID from a previous run on the same PR."""
- previous_run = (
- Run.objects.filter(repo=repo, pr_number=pr_number, metadata__has_key="github_comment_id")
- .exclude(id=exclude_run_id)
- .order_by("-created_at")
- .first()
- )
- if previous_run:
- value = previous_run.metadata.get("github_comment_id")
- if isinstance(value, int):
- return value
- if isinstance(value, str) and value.isdigit():
- return int(value)
- return None
-
-
-def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
- """
- Post or update a PR comment prompting reviewers to approve visual changes.
-
- One comment per PR — subsequent runs update the existing comment in place.
- Skips non-actionable runs (observe-only, stale/superseded, already commented).
- Best-effort and never raises.
- """
- if not repo.enable_pr_comments:
- return
-
- if not repo.repo_full_name or run.pr_number is None:
- return
-
- if run.purpose == RunPurpose.OBSERVE or is_run_stale(run):
- return
-
- if run.metadata.get("github_comment_id"):
- return
-
- run_url = _run_url(run, repo)
- comment_body = (
- f"👋 **Visual changes detected** for this PR.\n\n"
- f"[Review and approve in PostHog Visual Review]({run_url})\n\n"
- f"If these changes are unexpected, they may be caused by a flaky test or a "
- f"broken snapshot on master. Don't approve — rerun the job or wait for a fix."
- )
-
- try:
- existing_comment_id = _find_existing_comment_id(repo, run.pr_number, exclude_run_id=run.id)
- if existing_comment_id:
- response = _github_api_request(
- method="PATCH",
- repo=repo,
- path=f"issues/comments/{existing_comment_id}",
- json={"body": comment_body},
- )
- if response.status_code == 200:
- run.metadata["github_comment_id"] = existing_comment_id
- run.save(update_fields=["metadata"])
- return
- # Comment was deleted or inaccessible — fall through to create new one
- logger.info(
- "visual_review.pr_comment_update_failed_will_create",
- run_id=str(run.id),
- comment_id=existing_comment_id,
- status_code=response.status_code,
- )
-
- response = _github_api_request(
- method="POST",
- repo=repo,
- path=f"issues/{run.pr_number}/comments",
- json={"body": comment_body},
- )
- if response.status_code == 201:
- comment_id = response.json().get("id")
- run.metadata["github_comment_id"] = comment_id
- run.save(update_fields=["metadata"])
- else:
- logger.warning(
- "visual_review.pr_comment_failed",
- run_id=str(run.id),
- pr_number=run.pr_number,
- status_code=response.status_code,
- response=response.text[:200],
- )
- except Exception:
- logger.warning("visual_review.pr_comment_error", run_id=str(run.id), pr_number=run.pr_number, exc_info=True)
-
-
-_MARKDOWN_ESCAPE_CHARS = r"\`*_{}[]()#+-.!|<>~"
-
-
-def _escape_markdown(value: str) -> str:
- """Escape GitHub-flavored markdown control characters in user-supplied text."""
- return "".join(f"\\{c}" if c in _MARKDOWN_ESCAPE_CHARS else c for c in value)
-
-
-@dataclass(frozen=True)
-class _Approver:
- label: str
- is_github_login: bool
-
-
-# A reviewer should be able to eyeball the approved snapshots straight from the PR.
-# GitHub can't render base64 data URIs (its markdown sanitizer strips them) and the
-# user-attachments upload path needs a browser session we don't have, so we embed
-# presigned object-storage URLs and let GitHub's image proxy (camo) fetch + cache
-# them. That proxy fetch can happen well after the comment is posted, so the URL
-# must outlive the default hour — use the S3 SigV4 maximum.
-_COMMENT_IMAGE_URL_EXPIRATION = 60 * 60 * 24 * 7 # 7 days
-_COMMENT_IMAGE_WIDTH = 320
-# Keep the comment readable: show the first N snapshots and link out for the rest.
-_MAX_COMMENT_IMAGES = 8
-
-
-def _comment_image_url(repo: Repo, artifact: Artifact | None) -> str | None:
- """Presigned URL for the full-resolution snapshot image in a PR comment.
-
- Serves the original artifact (not the thumbnail) so the embedded image opens at full
- resolution when clicked — GitHub constrains the rendered size via the ``<img width>``
- attribute but links the original. Returns None when the artifact is missing or object
- storage is disabled — the caller renders an empty cell in that case.
- """
- if artifact is None:
- return None
- storage = ArtifactStorage(str(repo.id))
- return storage.get_presigned_download_url(artifact.content_hash, expiration=_COMMENT_IMAGE_URL_EXPIRATION)
-
-
-_TABLE_BREAKING_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
-
-
-def _run_url(run: Run, repo: Repo) -> str:
- """Link to the run page in PostHog."""
- return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
-
-
-def _snapshot_url(run: Run, repo: Repo, snapshot: RunSnapshot) -> str:
- """Deep link straight to a single snapshot on the run page."""
- return f"{_run_url(run, repo)}?snapshot={snapshot.id}"
-
-
-def _snapshot_name_cell(identifier: str, suffix: str = "") -> str:
- """Render a snapshot identifier as a single-line table cell (code span, pipe-safe).
-
- Identifiers come from the run manifest without newline validation, so collapse
- control characters (newlines, tabs, etc.) to spaces first — otherwise a
- malformed or user-controlled story name could break out of the table row and
- inject markdown/HTML into the comment. Then strip backticks and escape pipes so
- it stays inside the code span and the cell.
- """
- safe = _TABLE_BREAKING_CHARS_RE.sub(" ", identifier).replace("`", "").replace("|", "\\|")
- return f"`{safe}`{suffix}"
-
-
-def _snapshot_link_cell(run: Run, repo: Repo, snapshot: RunSnapshot, suffix: str = "") -> str:
- """Snapshot identifier linked to its deep link on the run page, so a reviewer can jump
- straight to that snapshot rather than the run as a whole."""
- return f"[{_snapshot_name_cell(snapshot.identifier)}]({_snapshot_url(run, repo, snapshot)}){suffix}"
-
-
-def _image_cell(url: str | None, alt: str) -> str:
- """Render an image (or an empty placeholder) for a before/after table cell.
-
- The image is constrained to ``_COMMENT_IMAGE_WIDTH`` so the table stays compact, but
- ``src`` points at the full-resolution original — GitHub opens that original when the
- image is clicked.
- """
- if not url:
- return "_(none)_"
- # Escape both attributes — a URL containing a quote would otherwise break out of src.
- src = html.escape(url, quote=True)
- return f'<img src="{src}" width="{_COMMENT_IMAGE_WIDTH}" alt="{html.escape(alt, quote=True)}">'
-
-
-_IMAGE_TABLE_HEADER = "| Snapshot | Before | After |\n| --- | --- | --- |"
-
-
-_REVIEWABLE_RESULTS = (SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult.REMOVED)
-
-
-def _reviewable_snapshot_qs(run: Run) -> db_models.QuerySet[RunSnapshot]:
- return run.snapshots.using(READER_DB).filter(result__in=_REVIEWABLE_RESULTS)
-
-
-def _postable_snapshot_qs(run: Run) -> db_models.QuerySet[RunSnapshot]:
- """Reviewable snapshots minus the ones an approval comment should not surface.
-
- Quarantined snapshots are suppressed by policy and tolerated ones are
- intentional known drift, so neither belongs in the comment.
- """
- return _reviewable_snapshot_qs(run).exclude(is_quarantined=True).exclude(review_state=ReviewState.TOLERATED)
-
-
-def _build_snapshot_image_tables(run: Run, repo: Repo) -> str:
- """Before/after image tables for the approved snapshots.
-
- Changed and removed snapshots share one table (removed ones leave the *after*
- cell empty); new snapshots get their own table (empty *before* cell). Capped
- at ``_MAX_COMMENT_IMAGES`` rows total, prioritizing changed/removed diffs;
- anything beyond links back to PostHog. Returns "" when no image could be
- resolved (e.g. object storage disabled) so the comment stays text-only.
- """
- snapshots = list(
- _postable_snapshot_qs(run)
- .select_related(
- "current_artifact",
- "baseline_artifact",
- )
- .order_by("identifier")
- )
- if not snapshots:
- return ""
-
- # Changed/removed first — they carry a baseline diff a reviewer most needs to
- # see — then new snapshots fill whatever's left of the image budget.
- changed = [s for s in snapshots if s.result in (SnapshotResult.CHANGED, SnapshotResult.REMOVED)]
- new = [s for s in snapshots if s.result == SnapshotResult.NEW]
-
- total = len(changed) + len(new)
- shown_changed = changed[:_MAX_COMMENT_IMAGES]
- shown_new = new[: max(0, _MAX_COMMENT_IMAGES - len(shown_changed))]
- shown = len(shown_changed) + len(shown_new)
-
- any_image = False
-
- def cell(artifact: Artifact | None, alt: str) -> str:
- nonlocal any_image
- url = _comment_image_url(repo, artifact)
- if url:
- any_image = True
- return _image_cell(url, alt)
-
- def row(s: RunSnapshot, before: Artifact | None) -> str:
- suffix = " _(removed)_" if s.result == SnapshotResult.REMOVED else ""
- name = _snapshot_link_cell(run, repo, s, suffix)
- return f"| {name} | {cell(before, 'before')} | {cell(s.current_artifact, 'after')} |"
-
- changed_rows = [row(s, s.baseline_artifact) for s in shown_changed]
- new_rows = [row(s, None) for s in shown_new]
-
- if not any_image:
- return ""
-
- def table(heading: str, rows: list[str]) -> str:
- return "\n".join((f"**{heading}**", "", _IMAGE_TABLE_HEADER, *rows))
-
- sections = [table(heading, rows) for heading, rows in (("Changed", changed_rows), ("New", new_rows)) if rows]
- if shown < total:
- sections.append(f"…and {total - shown} more — [view all in PostHog]({_run_url(run, repo)}).")
-
- return "\n\n".join(sections)
-
-
-def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | None, add_images: bool = False) -> str:
- """Build the markdown body of the post-approval PR comment.
-
- Always a textual summary of what changed. When ``add_images`` is set, a
- before/after table of the approved snapshot images is appended so another
- reviewer can eyeball them without leaving the PR (omitted when no image can
- be resolved).
- """
- counts = Counter(_postable_snapshot_qs(run).values_list("result", flat=True))
- suppressed_only = not counts and _reviewable_snapshot_qs(run).exists()
-
- if approver is None:
- approver_text = "a reviewer"
- elif approver.is_github_login:
- approver_text = f"@{approver.label}"
- else:
- approver_text = _escape_markdown(approver.label)
- baseline_sha = run.metadata.get("baseline_commit_sha")
- sha_text = f" — baseline updated in `{baseline_sha[:7]}`" if isinstance(baseline_sha, str) and baseline_sha else ""
-
- summary = _format_change_counts(
- counts[SnapshotResult.CHANGED], counts[SnapshotResult.NEW], counts[SnapshotResult.REMOVED]
- )
-
- sections = [
- f"✅ **Visual changes approved** by {approver_text}{sha_text}.",
- f"[View this run in PostHog]({_run_url(run, repo)})",
- ]
- if summary:
- sections.append(f"{summary}.")
- elif suppressed_only:
- sections.append("All visual changes in this run were quarantined or tolerated.")
- if add_images:
- tables = _build_snapshot_image_tables(run, repo)
- if tables:
- sections.append(tables)
-
- return "\n\n".join(sections) + "\n"
-
-
-def _resolve_approver(user_id: int | None) -> _Approver | None:
- """Resolve the approver's identity for the PR comment.
-
- Prefers a verified GitHub login (safe to mention with `@`); otherwise
- falls back to email local-part or first name, which the caller must
- treat as untrusted markdown.
- """
- if user_id is None:
- return None
-
- from posthog.models.user import User
- from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
-
- gh = (
- UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.GITHUB)
- .order_by("-created_at")
- .first()
- )
- if gh is not None:
- github_login = UserGitHubIntegration(gh).github_login
- if github_login:
- return _Approver(label=github_login, is_github_login=True)
-
- user = User.objects.filter(id=user_id).only("email", "first_name").first()
- if user is None:
- return None
- if user.email and "@" in user.email:
- return _Approver(label=user.email.split("@", 1)[0], is_github_login=False)
- if user.first_name:
- return _Approver(label=user.first_name, is_github_login=False)
- return None
-
-
-def _post_approval_comment(run: Run, repo: Repo, add_images: bool = False) -> None:
- """Update the existing PR comment in place with the approved-changes summary.
-
- Best-effort and never raises. Skips silently when the original review-prompt
- comment was never posted (no `github_comment_id` in run.metadata) — i.e.,
- when the review wasn't initiated by a human. ``add_images`` embeds the
- before/after snapshot images in the comment when the reviewer opted in.
- """
- if not repo.enable_pr_comments:
- return
-
- if not repo.repo_full_name or run.pr_number is None:
- return
-
- if run.review_decision != ReviewDecision.HUMAN_APPROVED:
- return
-
- comment_id = run.metadata.get("github_comment_id")
- if not comment_id:
- return
- if isinstance(comment_id, str) and comment_id.isdigit():
- comment_id = int(comment_id)
- if not isinstance(comment_id, int):
- return
-
- approver = _resolve_approver(run.approved_by_id)
- body = _build_approval_comment_body(run, repo, approver, add_images=add_images)
-
- try:
- response = _github_api_request(
- method="PATCH",
- repo=repo,
- path=f"issues/comments/{comment_id}",
- json={"body": body},
- timeout=15,
- )
- if response.status_code == 200:
- return
-
- # Comment was deleted or inaccessible — fall back to creating a new one
- if response.status_code == 404:
- create_response = _github_api_request(
- method="POST",
- repo=repo,
- path=f"issues/{run.pr_number}/comments",
- json={"body": body},
- timeout=15,
- )
- if create_response.status_code == 201:
- new_comment_id = create_response.json().get("id")
- if isinstance(new_comment_id, int):
- run.metadata["github_comment_id"] = new_comment_id
- run.save(update_fields=["metadata"], using=WRITER_DB)
- return
- logger.warning(
- "visual_review.approval_comment_create_failed",
- run_id=str(run.id),
- pr_number=run.pr_number,
- status_code=create_response.status_code,
- response=create_response.text[:200],
- )
- return
-
- logger.warning(
- "visual_review.approval_comment_update_failed",
- run_id=str(run.id),
- comment_id=comment_id,
- status_code=response.status_code,
- response=response.text[:200],
- )
- except GitHubRateLimitError:
- # Bubble up so the Celery task can retry with the suggested countdown.
- raise
- except Exception:
- logger.warning(
- "visual_review.approval_comment_error",
- run_id=str(run.id),
- pr_number=run.pr_number,
- exc_info=True,
- )
-
-
-def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None, add_images: bool = False) -> None:
- """Public entrypoint for the Celery task to update a PR comment after approval."""
- run = (
- Run.objects.select_related("repo")
- .using(READER_DB)
- .filter(id=run_id, **({"team_id": team_id} if team_id is not None else {}))
- .first()
- )
- if run is None:
- return
- _post_approval_comment(run, run.repo, add_images=add_images)
-
-
[email protected](using=WRITER_DB)
-def finalize_run(
- run_id: UUID,
- user_id: int,
- team_id: int | None = None,
- approve_all: bool = False,
- review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,
- commit_to_github: bool = True,
- add_images_to_comment_on_pr: bool = False,
-) -> Run:
- """Finalize a fully-reviewed run: commit the approved baseline and green the gate.
-
- All-or-nothing by design — a run finalizes only once every changed/new snapshot is
- resolved (approved, tolerated, quarantined, or removed). The committed baseline is
- derived from DB state — exactly the snapshots with ``review_state == APPROVED``, by
- their approved hash — so a tolerated snapshot keeps its existing baseline and is
- never silently overwritten, and the commit always contains the full approved set
- regardless of how many calls it took to review them.
-
- With ``approve_all=True`` every still-pending changed/new snapshot is approved first
- (tolerated ones are left untouched) — the "approve everything and ship" path. Without
- it, the run must already be fully resolved or this raises RunNotFullyResolvedError.
-
- Set ``commit_to_github=False`` for CLI auto-approve, which writes the baseline locally
- instead of pushing it to the PR branch.
-
- The post-approval PR comment is always posted (subject to the existing conditions: repo
- PR comments enabled, run initiated from a GitHub review prompt). ``add_images_to_comment_on_pr``
- only controls whether the before/after snapshot images are embedded in that comment;
- defaults false so the comment stays a text summary unless the reviewer opts in.
- """
- run = _get_run_for_update(run_id, team_id=team_id)
- repo = run.repo
-
- if run.purpose == RunPurpose.OBSERVE:
- raise ValueError("Observational runs cannot be approved")
-
- # Idempotent: a finalized run already committed and posted status — don't redo the work
- # (a second commit, status, and approval comment) on a repeat call.
- if run.approved:
- return run
-
- if run.status != RunStatus.COMPLETED:
- raise ValueError(f"Run must be completed before approval (current status: {run.status})")
-
- if is_run_stale(run):
- raise StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")
-
- # Re-evaluate quarantine so resolution accounting reflects the current policy.
- _stamp_quarantine(run)
- now = timezone.now()
-
- actionable = [
- s
- for s in run.snapshots.using(WRITER_DB).all()
- if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW) and not s.is_quarantined
- ]
-
- if approve_all:
- pending = [s for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)]
- _validate_approval(run, {s.identifier: s.current_hash for s in pending})
- for snapshot in pending:
- snapshot.review_state = ReviewState.APPROVED
- snapshot.reviewed_at = now
- snapshot.reviewed_by_id = user_id
- snapshot.approved_hash = snapshot.current_hash
- snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])
-
- # All-or-nothing: refuse to commit while any actionable snapshot is still unreviewed.
- unresolved = [
- s.identifier for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)
- ]
- if unresolved:
- raise RunNotFullyResolvedError(
- f"Cannot finalize: {len(unresolved)} snapshot(s) still need review — approve or tolerate them first: "
- f"{', '.join(sorted(unresolved)[:10])}"
- )
-
- # Commit set is derived from DB state, not a caller-supplied list, so it always reflects
- # the full approved set however many calls reviewed it.
- approved_updates = _approved_baseline_updates(actionable)
- has_removed = run.snapshots.using(WRITER_DB).filter(result=SnapshotResult.REMOVED).exists()
-
- # Commit first — before DB writes — so a GitHub failure aborts cleanly. Removed snapshots
- # also need a commit, to prune them from the baseline, even when nothing was approved.
- if commit_to_github and (approved_updates or has_removed) and run.pr_number and repo.repo_full_name:
- _commit_baseline_to_github(run, repo, approved_updates, approver_user_id=user_id)
-
- # Removed snapshots are pruned from the baseline on commit; mark them approved for cleanup.
- run.snapshots.filter(result=SnapshotResult.REMOVED).update(
- review_state=ReviewState.APPROVED,
- reviewed_at=now,
- reviewed_by_id=user_id,
- )
-
- run.approved = True
- run.review_decision = review_decision
- run.approved_at = now
- run.approved_by_id = user_id
- run.save(update_fields=["approved", "review_decision", "approved_at", "approved_by_id"])
-
- if commit_to_github:
- _post_commit_status(run, repo, "success", "Visual changes approved")
-
- if commit_to_github and review_decision == ReviewDecision.HUMAN_APPROVED:
- from .tasks.tasks import post_approval_comment
-
- run_id_str = str(run.id)
- run_team_id = run.team_id
- add_images = add_images_to_comment_on_pr
- transaction.on_commit(
- lambda: post_approval_comment.delay(run_team_id, run_id_str, add_images),
- using=WRITER_DB,
- )
-
- return run
-
-
-def build_signed_baseline(run_id: UUID, team_id: int | None = None) -> str:
- """Build the signed baseline YAML for a finalized run, without committing it.
-
- For callers that commit the baseline themselves (the CLI's auto-approve, which writes
- the file and commits via git rather than the GitHub App). Mirrors the committed set:
- the current baseline merged with the approved changed/new hashes, removed entries pruned.
- """
- run = get_run_with_snapshots(run_id, team_id=team_id)
- repo = run.repo
-
- baseline_paths = repo.baseline_file_paths or {}
- baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")
-
- github = get_github_integration_for_repo(repo)
- current_baselines, _file_sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, run.branch)
-
- snapshots = list(run.snapshots.all())
- for s in snapshots:
- if s.result == SnapshotResult.REMOVED:
- current_baselines.pop(s.identifier, None)
-
- return _build_snapshots_yaml(
- repo, current_baselines=current_baselines, updates=_approved_baseline_updates(snapshots)
- )
-
-
[email protected](using=WRITER_DB)
-def approve_snapshots(run_id: UUID, user_id: int, approved_snapshots: list[dict], team_id: int | None = None) -> Run:
- """Approve specific snapshots within a run (DB only, no GitHub commit).
-
- Used for per-snapshot "Accept change" in the UI. Does not finalize
- the run — that happens via finalize_run.
- """
- run = _get_run_for_update(run_id, team_id=team_id)
-
- if run.purpose == RunPurpose.OBSERVE:
- raise ValueError("Observational runs cannot be approved")
-
- if is_run_stale(run):
- raise StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")
-
- approvals = {s["identifier"]: s["new_hash"] for s in approved_snapshots}
- _validate_approval(run, approvals)
-
- now = timezone.now()
- for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):
- new_hash = approvals[snapshot.identifier]
- snapshot.review_state = ReviewState.APPROVED
- snapshot.reviewed_at = now
- snapshot.reviewed_by_id = user_id
- snapshot.approved_hash = new_hash
- snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])
-
- return run
-
-
-def _validate_approval(run: Run, approvals: dict[str, str]) -> None:
- """Validate snapshot identifiers, hash matches, and artifact existence."""
- repo = run.repo
-
- run_identifiers = set(run.snapshots.values_list("identifier", flat=True))
- unknown = set(approvals.keys()) - run_identifiers
- if unknown:
- raise ValueError(f"Unknown snapshot identifiers: {', '.join(sorted(unknown))}")
-
- for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):
- expected_hash = approvals[snapshot.identifier]
- if expected_hash != snapshot.current_hash:
- raise ValueError(
- f"Hash mismatch for {snapshot.identifier}: "
- f"approved {expected_hash[:12]} but current is {snapshot.current_hash[:12]}"
- )
-
- for identifier, new_hash in approvals.items():
- artifact = get_artifact(repo.id, new_hash)
- if not artifact:
- raise ArtifactNotFoundError(f"Artifact not found for hash {new_hash} (snapshot: {identifier})")
-
-
-# --- Snapshot Operations ---
-
-
-def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str) -> str | None:
- """Look up the thumbnail content hash for a snapshot identifier.
-
- Finds the most recent artifact with a thumbnail for this identifier
- across all runs. Returns the thumbnail's content_hash or None.
- """
- snapshot = (
- RunSnapshot.objects.filter(
- run__repo_id=repo_id,
- identifier=identifier,
- current_artifact__thumbnail__isnull=False,
- )
- .select_related("current_artifact__thumbnail")
- .order_by("-run__created_at")
- .first()
- )
-
- if snapshot is None:
- return None
-
- artifact = snapshot.current_artifact
- if artifact is None or artifact.thumbnail is None:
- return None
-
- return artifact.thumbnail.content_hash
-
-
-def read_thumbnail_bytes(repo_id: UUID, content_hash: str) -> bytes | None:
- storage = ArtifactStorage(str(repo_id))
- return storage.read(content_hash)
-
-
-def get_run_snapshots(run_id: UUID, team_id: int | None = None) -> list[RunSnapshot]:
- run = get_run(run_id, team_id=team_id)
- return list(
- run.snapshots.select_related("current_artifact", "baseline_artifact", "diff_artifact").order_by(
- db_models.Case(
- db_models.When(result=SnapshotResult.UNCHANGED, then=1),
- default=0,
- ),
- "identifier",
- )
- )
-
-
-# Default-branch fallback. We don't track repos' actual default branch, so we
-# include both candidates and assume nobody has both — whichever has rows wins.
-# When `trunk`/`develop`-style defaults show up, this becomes a `Repo` field.
-_DEFAULT_BRANCHES = ("master", "main")
-
-
-_SNAPSHOT_HISTORY_DEDUP_SQL = """
-WITH ordered AS (
- SELECT rs.id,
- rs.baseline_artifact_id,
- LAG(rs.baseline_artifact_id) OVER (ORDER BY r.created_at) AS prev_baseline_id,
- r.created_at
- FROM visual_review_runsnapshot rs
- JOIN visual_review_run r ON r.id = rs.run_id
- WHERE r.repo_id = %s
- AND r.run_type = %s
- AND r.branch = ANY(%s)
- AND r.status = 'completed'
- AND rs.identifier = %s
-)
-SELECT id
-FROM ordered
-WHERE prev_baseline_id IS DISTINCT FROM baseline_artifact_id
-ORDER BY created_at DESC
-"""
-
-
-def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[RunSnapshot]:
- """Baseline timeline for a snapshot identifier on the default branch.
-
- Returns one entry per *baseline transition* — every time the committed
- `.snapshots.yml` baseline actually moved. LAG-on-`baseline_artifact_id`
- (over ASC ordering) keeps the FIRST run of each baseline period, so the
- user sees the inception event plus every change since.
-
- Why LAG on `baseline_artifact_id` and not `current_artifact_id`:
- - `current_artifact_id` is the bytes captured by THIS run. Pixel jitter
- and tolerated drift produce different content_hash → different Artifact
- rows even though the *baseline* didn't move. Keying on current_ caused
- a prod regression (252 fake history events on a single tolerated-drift
- story) because the artifact alternated between near-identical hashes
- the matcher kept absorbing. LAG-on-current-with-result-filter (the
- prior fix) hid those false events but also hid genuine first-appearance
- rows whose `result=unchanged` against an existing YAML baseline.
- - `baseline_artifact_id` reflects the YAML state at run time. It only
- changes when a baseline-update PR merges. Pixel jitter and tolerated
- drift leave it untouched, so LAG dedup naturally collapses noise while
- catching every real baseline flip — without needing a `result` filter.
-
- DB-level filters:
- - branch ∈ master/main, run_type, repo: scope to default-branch runs of
- this kind
- - status=completed: drop pre-classification rows where the baseline FK
- hasn't been hydrated yet (pending/processing leave NULL baseline_artifact)
- """
- with connections[READER_DB].cursor() as cursor:
- cursor.execute(
- _SNAPSHOT_HISTORY_DEDUP_SQL,
- [str(repo_id), run_type, list(_DEFAULT_BRANCHES), identifier],
- )
- ordered_ids: list[UUID] = [row[0] for row in cursor.fetchall()]
-
- if not ordered_ids:
- return []
-
- # `id__in` doesn't preserve order, so look rows up by id and re-emit in the
- # cursor's order. Fetched count equals the deduped baseline-event count
- # (typically <20), so this hydration is cheap regardless of raw history size.
- rows_by_id: dict[UUID, RunSnapshot] = {
- row.id: row for row in RunSnapshot.objects.filter(id__in=ordered_ids).select_related("run", "current_artifact")
- }
- return [rows_by_id[rid] for rid in ordered_ids if rid in rows_by_id]
-
-
-def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
- """Universe of identifiers with a current baseline, plus aggregates.
-
- The "current baseline" universe is anchored on the latest non-superseded run
- on the default branch (master/main) for each `run_type`. One row per
- `(run_type, identifier)` — the closest thing to "what we'd compare a new
- capture against right now".
-
- Performance shape:
- - 1 query for the universe runs (one row per run_type, indexed)
- - 1 query for the universe rows (with thumbnail + artifact prefetch)
- - 2 grouped queries for tolerate counts (30d + 90d)
- - 1 grouped query for active quarantines
- - 1 grouped query for lifetime baseline-flip count
- - 2 queries for the recent-drift average (resolve last-N runs, aggregate)
- - 3 cheap aggregate queries for totals
- """
- from datetime import timedelta
-
- from .facade.contracts import BASELINE_DRIFT_RECENT_RUN_COUNT, BASELINE_OVERVIEW_MAX_ENTRIES
-
- now = timezone.now()
-
- # 1. Find the latest *completed* run on the default branch per (repo,
- # branch, run_type). Filtering on `superseded_by IS NULL` looks tempting
- # but is wrong here: a freshly started PENDING/PROCESSING master run is
- # un-superseded yet has zero (or sparse) RunSnapshots ingested, and would
- # collapse the universe to whatever it has loaded so far. `status=completed`
- # makes the universe fall through to the most recent fully-ingested run.
- universe_runs = list(
- Run.objects.filter(
- repo_id=repo_id,
- branch__in=_DEFAULT_BRANCHES,
- status=RunStatus.COMPLETED,
- )
- .order_by("repo_id", "branch", "run_type", "-created_at")
- .distinct("repo_id", "branch", "run_type")
- .only("id", "run_type", "completed_at", "created_at")
- )
- universe_run_ids = [r.id for r in universe_runs]
- if not universe_run_ids:
- return _BaselineOverviewRaw(
- entries=[],
- tolerate_30d_by_id={},
- tolerate_90d_by_id={},
- active_quarantines_by_key={},
- change_count_by_key={},
- recent_drift_by_key={},
- totals_all=0,
- totals_recent=0,
- totals_frequent=0,
- totals_quarantined=0,
- by_run_type={},
- truncated=False,
- generated_at=now,
- )
-
- # 2. Pull the universe rows. select_related the chain we need for thumbnails.
- universe_qs = (
- RunSnapshot.objects.filter(run_id__in=universe_run_ids)
- .select_related("run", "current_artifact__thumbnail")
- .only(
- "identifier",
- "metadata",
- "run__id",
- "run__run_type",
- "run__completed_at",
- "run__created_at",
- "current_artifact__width",
- "current_artifact__height",
- "current_artifact__thumbnail__content_hash",
- )
- # Stable ordering so truncation is deterministic; newest baselines first.
- .order_by("-run__completed_at", "identifier")
- )
- total_universe = universe_qs.count()
- truncated = total_universe > BASELINE_OVERVIEW_MAX_ENTRIES
- universe = list(universe_qs[:BASELINE_OVERVIEW_MAX_ENTRIES]) if truncated else list(universe_qs)
- # Per-entry aggregates (tolerate counts, sparklines) only need to cover the
- # entries we'll return. Totals must scope across the *full* universe,
- # otherwise truncation makes them undercount in misleading ways (a 6000-id
- # repo would show 0 frequently-tolerated if all of them sat past the slice).
- universe_identifiers = list({s.identifier for s in universe})
- if truncated:
- full_universe_identifiers = list(universe_qs.values_list("identifier", flat=True).distinct())
- else:
- full_universe_identifiers = universe_identifiers
-
- # 3a. Tolerate counts in 30d / 90d windows. Single grouped query each.
- # Scope to HUMAN/AGENT reasons only — AUTO_THRESHOLD rows are auto-minted
- # by the diff pipeline as a tolerated-hash cache for sub-threshold pixel
- # jitter and don't represent a deliberate "we accept this drift" decision.
- # Including them inflated the "Tolerated drift" tile with rendering noise.
- intentional_tolerate_reasons = (ToleratedReason.HUMAN, ToleratedReason.AGENT)
- tolerate_30d_by_id: dict[str, int] = {}
- tolerate_90d_by_id: dict[str, int] = {}
- if universe_identifiers:
- tol_30d_cutoff = now - timedelta(days=30)
- tol_90d_cutoff = now - timedelta(days=90)
- for identifier, count in (
- ToleratedHash.objects.filter(
- repo_id=repo_id,
- identifier__in=universe_identifiers,
- reason__in=intentional_tolerate_reasons,
- created_at__gte=tol_30d_cutoff,
- )
- .values_list("identifier")
- .annotate(c=Count("id"))
- .values_list("identifier", "c")
- ):
- tolerate_30d_by_id[identifier] = count
- for identifier, count in (
- ToleratedHash.objects.filter(
- repo_id=repo_id,
- identifier__in=universe_identifiers,
- reason__in=intentional_tolerate_reasons,
- created_at__gte=tol_90d_cutoff,
- )
- .values_list("identifier")
- .annotate(c=Count("id"))
- .values_list("identifier", "c")
- ):
- tolerate_90d_by_id[identifier] = count
-
- # 3b. Active quarantines for this repo, scoped to the universe identifiers
- # AND the run_types they live on (quarantine is per (repo, run_type, id)).
- # We hydrate the full row (not just identity) so the overview can render
- # reason / expiry / who / source-run inline without a per-card fetch.
- # `select_related("source_run")` is a single JOIN, capped by
- # `BASELINE_OVERVIEW_MAX_ENTRIES`. `Run.metadata` (JSONField) and
- # `Run.error_message` (TextField) can be large and aren't needed by the
- # summary — defer them to keep the response light.
- active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier] = {}
- if universe_identifiers:
- for q in (
- QuarantinedIdentifier.objects.filter(
- repo_id=repo_id,
- identifier__in=universe_identifiers,
- )
- .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
- .select_related("source_run")
- .defer("source_run__metadata", "source_run__error_message")
- .order_by("-created_at")
- ):
- key = (q.run_type, q.identifier)
- # Multiple active rows for the same key shouldn't happen — create
- # auto-supersedes prior — but if it does, keep the latest (sorted
- # above) and ignore the rest.
- if key not in active_quarantines_by_key:
- active_quarantines_by_key[key] = q
-
- # 3c. Per-baseline stability signals: a lifetime baseline-flip count and a
- # smoothed recent-drift average. Replaces a daily-bucket sparkline that
- # had to scan millions of RunSnapshot rows on every request (~7s, OOMed on
- # the web pod for repos with thousands of identifiers — see git history).
- # Both queries here are scoped tightly enough to finish in tens of ms:
- #
- # change_count_by_key: COUNT(*) WHERE result IN ('changed','removed')
- # across all completed master/main runs ever. Real baseline flips on
- # master leave a CHANGED/REMOVED row in the run that introduced them
- # (subsequent runs see UNCHANGED against the new YAML baseline), so
- # this count IS the number of times the YAML moved. Postgres uses
- # the `snapshot_run_result` index on (run_id, result) to bitmap-scan
- # straight to the rare event rows (~1k of millions). No window
- # function, no per-row LAG comparison.
- #
- # recent_drift_by_key: AVG(diff_percentage) over the last 10 master/
- # main completed runs per (run_type). Bounded by run count, not by
- # time window — caps the scanned set regardless of CI cadence. We
- # resolve the run IDs first (sub-ms) and aggregate via PK-indexed
- # run_id__in, otherwise the planner inlines a CTE that produces a
- # ROW_NUMBER plan over the full RunSnapshot table.
- change_count_by_key: dict[tuple[str, str], int] = {}
- recent_drift_by_key: dict[tuple[str, str], float] = {}
- if universe_identifiers:
- for identifier, run_type, c in (
- RunSnapshot.objects.filter(
- run__repo_id=repo_id,
- run__branch__in=_DEFAULT_BRANCHES,
- run__status=RunStatus.COMPLETED,
- result__in=(SnapshotResult.CHANGED, SnapshotResult.REMOVED),
- )
- .values("identifier", "run__run_type")
- .annotate(c=Count("id"))
- .values_list("identifier", "run__run_type", "c")
- ):
- change_count_by_key[(run_type, identifier)] = c
-
- # Top-N per run_type via window function. There's no pure-ORM
- # equivalent: Postgres doesn't allow filtering on a window result,
- # and a per-run_type loop balloons to thousands of queries on repos
- # where each Storybook story registers as its own run_type
- # (benchmarked: 4ms raw vs 5.6s loop on a 30k-run repo with 2154
- # run_types). The query is parameterized — every dynamic value
- # passes through %s binding, no string concatenation, table name
- # comes from the model. nosemgrep is required because the rule
- # blanket-flags any .raw() use.
- recent_run_sql = f"""
- SELECT id, run_type FROM (
- SELECT id, run_type,
- ROW_NUMBER() OVER (PARTITION BY run_type ORDER BY created_at DESC) AS rn
- FROM {Run._meta.db_table}
- WHERE repo_id = %s AND branch = ANY(%s) AND status = %s
- ) ranked WHERE rn <= %s
- """ # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql
- recent_run_ids = list(
- Run.objects.raw( # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql
- recent_run_sql,
- [str(repo_id), list(_DEFAULT_BRANCHES), RunStatus.COMPLETED, BASELINE_DRIFT_RECENT_RUN_COUNT],
- )
- )
- if recent_run_ids:
- for identifier, run_type, drift_avg in (
- RunSnapshot.objects.filter(run_id__in=[r.id for r in recent_run_ids])
- .values("identifier", "run__run_type")
- .annotate(drift_avg=Avg("diff_percentage", filter=Q(diff_percentage__gt=0)))
- .values_list("identifier", "run__run_type", "drift_avg")
- ):
- if drift_avg is not None:
- recent_drift_by_key[(run_type, identifier)] = drift_avg
-
- # 4. Totals computed across the *full* universe (not the truncated slice)
- # so the stat row stays correct when the entries are clipped.
- if truncated:
- # Re-issue a small COUNT-only query for accurate totals across the
- # universe; we already have the truncated list in memory.
- totals_all = total_universe
- else:
- totals_all = len(universe)
-
- # Recently / frequently tolerated — counts of distinct identifiers with
- # ≥1 (or ≥3) intentional tolerations in the rolling window. Scope across
- # the *full* universe so the stat row stays correct under truncation, and
- # match the per-entry counts above by excluding AUTO_THRESHOLD.
- recent_cutoff = now - timedelta(days=30)
- frequent_cutoff = now - timedelta(days=90)
- recent_ids: set[str] = set()
- frequent_ids: set[str] = set()
- if full_universe_identifiers:
- recent_ids = set(
- ToleratedHash.objects.filter(
- repo_id=repo_id,
- identifier__in=full_universe_identifiers,
- reason__in=intentional_tolerate_reasons,
- created_at__gte=recent_cutoff,
- )
- .values_list("identifier", flat=True)
- .distinct()
- )
- frequent_grouped = (
- ToleratedHash.objects.filter(
- repo_id=repo_id,
- identifier__in=full_universe_identifiers,
- reason__in=intentional_tolerate_reasons,
- created_at__gte=frequent_cutoff,
- )
- .values("identifier")
- .annotate(c=Count("id"))
- .filter(c__gte=3)
- .values_list("identifier", flat=True)
- )
- frequent_ids = set(frequent_grouped)
-
- # `active_quarantines_by_key` was built from the truncated set above (per-entry
- # attached). Re-query for the totals so they cover the full universe.
- if truncated and full_universe_identifiers:
- quarantined_id_count = (
- QuarantinedIdentifier.objects.filter(
- repo_id=repo_id,
- identifier__in=full_universe_identifiers,
- )
- .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
- .values("identifier")
- .distinct()
- .count()
- )
- else:
- quarantined_id_count = len({identifier for _, identifier in active_quarantines_by_key})
-
- # by_run_type counts every entry in the universe. Aggregate query under
- # truncation so it doesn't undercount; in-memory Counter when not truncated
- # (we already paid for the row hydration).
- if truncated:
- by_run_type = dict(
- universe_qs.values_list("run__run_type")
- .order_by()
- .annotate(c=Count("id"))
- .values_list("run__run_type", "c")
- )
- else:
- by_run_type = dict(Counter(s.run.run_type for s in universe))
-
- return _BaselineOverviewRaw(
- entries=universe,
- tolerate_30d_by_id=tolerate_30d_by_id,
- tolerate_90d_by_id=tolerate_90d_by_id,
- active_quarantines_by_key=active_quarantines_by_key,
- change_count_by_key=change_count_by_key,
- recent_drift_by_key=recent_drift_by_key,
- totals_all=totals_all,
- totals_recent=len(recent_ids),
- totals_frequent=len(frequent_ids),
- totals_quarantined=quarantined_id_count,
- by_run_type=by_run_type,
- truncated=truncated,
- generated_at=now,
- )
-
-
-@frozen
-class _BaselineOverviewRaw:
- """Internal raw shape — the facade layer reshapes this into the public DTOs.
-
- Kept private to logic.py so that contract changes don't ripple through here.
- """
-
- entries: list[RunSnapshot]
- tolerate_30d_by_id: dict[str, int]
- tolerate_90d_by_id: dict[str, int]
- # Latest active QuarantinedIdentifier (with `source_run` preloaded) for each
- # `(run_type, identifier)` in the universe — lets the facade build the rich
- # quarantine summary embedded on each BaselineEntry. Membership doubles as
- # the "is_quarantined" signal — no separate set needed.
- active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier]
- # Stability signals keyed by `(run_type, identifier)` because the same
- # identifier in different run types is a different baseline; merging would
- # bleed storybook stability into playwright stability.
- change_count_by_key: dict[tuple[str, str], int]
- recent_drift_by_key: dict[tuple[str, str], float]
- totals_all: int
- totals_recent: int
- totals_frequent: int
- totals_quarantined: int
- by_run_type: dict[str, int]
- truncated: bool
- generated_at: datetime
-
-
[email protected](using=WRITER_DB)
-def mark_snapshot_as_tolerated(run_id: UUID, snapshot_id: UUID, user_id: int, team_id: int) -> RunSnapshot:
- """Mark a changed snapshot as a known tolerated alternate (human decision).
-
- Creates a ToleratedHash entry tied to the current baseline, reclassifies the
- snapshot as UNCHANGED, and recalculates run summary counts.
- """
- run = _get_run_for_update(run_id, team_id=team_id)
- try:
- snapshot = RunSnapshot.objects.get(id=snapshot_id, run=run, team_id=team_id)
- except RunSnapshot.DoesNotExist:
- raise RunNotFoundError(f"Snapshot {snapshot_id} not found in run {run_id}")
-
- if snapshot.result != SnapshotResult.CHANGED:
- raise ValueError(f"Can only mark CHANGED snapshots as tolerated (current: {snapshot.result})")
-
- if not snapshot.current_hash:
- raise ValueError("Snapshot has no current hash")
-
- # Explicit team_id in the lookup (not just defaults) so the IDOR audit
- # rule sees the scope; ProductTeamManager also auto-filters by canonical
- # team — both belt and suspenders.
- tolerated, _ = ToleratedHash.objects.get_or_create(
- team_id=team_id,
- repo_id=run.repo_id,
- identifier=snapshot.identifier,
- baseline_hash=snapshot.baseline_hash,
- alternate_hash=snapshot.current_hash,
- defaults={
- "reason": ToleratedReason.HUMAN,
- "source_run": run,
- "created_by_id": user_id,
- "diff_percentage": snapshot.diff_percentage,
- },
- )
-
- # result stays CHANGED — it's the technical truth (hashes differ).
- # review_state captures the human decision to tolerate.
- snapshot.review_state = ReviewState.TOLERATED
- snapshot.reviewed_at = timezone.now()
- snapshot.reviewed_by_id = user_id
- snapshot.tolerated_hash_match = tolerated
- snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "tolerated_hash_match"])
-
- # Update tolerated_match_count (only human-tolerated, not auto-threshold)
- tolerated_count = (
- RunSnapshot.objects.using(WRITER_DB)
- .filter(run=run, tolerated_hash_match__isnull=False, tolerated_hash_match__reason=ToleratedReason.HUMAN)
- .count()
- )
- Run.objects.using(WRITER_DB).filter(id=run.id).update(tolerated_match_count=tolerated_count)
-
- return snapshot
-
-
-def get_tolerated_hashes_for_identifier(repo_id: UUID, identifier: str) -> list[ToleratedHash]:
- """List all tolerated hashes for a snapshot identifier, most recent first."""
- return list(ToleratedHash.objects.filter(repo_id=repo_id, identifier=identifier).order_by("-created_at"))
-
-
-# --- Quarantine ---
-
-
-def list_quarantined_identifiers(
- repo_id: UUID, team_id: int, identifier: str | None = None, run_type: str | None = None
-) -> list[QuarantinedIdentifier]:
- qs = (
- QuarantinedIdentifier.objects.using(WRITER_DB)
- .filter(repo_id=repo_id, team_id=team_id)
- # Preload `source_run` so the facade can render the "what was wrong"
- # link without an extra fetch per row. `Run.metadata` (JSONField) and
- # `Run.error_message` (TextField) can be large and aren't needed for
- # the summary — defer to keep response payloads tight.
- .select_related("source_run")
- .defer("source_run__metadata", "source_run__error_message")
- )
- if run_type:
- qs = qs.filter(run_type=run_type)
- if identifier:
- qs = qs.filter(identifier=identifier)
- else:
- now = timezone.now()
- qs = qs.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
- return list(qs.order_by("-created_at"))
-
-
[email protected](using=WRITER_DB)
-def quarantine_identifier(
- repo_id: UUID,
- identifier: str,
- run_type: str,
- reason: str,
- user_id: int,
- team_id: int,
- expires_at: datetime | None = None,
- source_run_id: UUID | None = None,
-) -> QuarantinedIdentifier:
- get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
- now = timezone.now()
- # Resolve the source run inside the team scope so a malicious caller can't
- # attach a quarantine to an unrelated run. Silently drop on mismatch — the
- # quarantine itself still wins; we just lose the "what was wrong" pointer.
- # We fetch (not just .exists()) so the facade can serialize source_run
- # without a lazy-load on the freshly-created row.
- source_run: Run | None = None
- if source_run_id is not None:
- source_run = Run.objects.using(WRITER_DB).filter(id=source_run_id, repo_id=repo_id, team_id=team_id).first()
- QuarantinedIdentifier.objects.using(WRITER_DB).select_for_update().filter(
- repo_id=repo_id,
- identifier=identifier,
- run_type=run_type,
- team_id=team_id,
- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).update(expires_at=now)
- return QuarantinedIdentifier.objects.using(WRITER_DB).create(
- repo_id=repo_id,
- identifier=identifier,
- run_type=run_type,
- team_id=team_id,
- reason=reason,
- expires_at=expires_at,
- created_by_id=user_id,
- source_run=source_run,
- )
-
-
-def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:
- get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
- QuarantinedIdentifier.objects.using(WRITER_DB).filter(
- repo_id=repo_id,
- identifier=identifier,
- run_type=run_type,
- team_id=team_id,
- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now())).update(expires_at=timezone.now())
-
-
-def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
- now = timezone.now()
- active = Q(expires_at__isnull=True) | Q(expires_at__gt=now)
- try:
- entry = QuarantinedIdentifier.objects.using(WRITER_DB).filter(active).get(id=entry_id, team_id=team_id)
- except QuarantinedIdentifier.DoesNotExist as e:
- raise RunNotFoundError(f"Quarantine entry {entry_id} not found or already expired") from e
-
- # Expire all active entries for the same identifier/run_type, not just this one
- QuarantinedIdentifier.objects.using(WRITER_DB).filter(
- repo_id=entry.repo_id,
- identifier=entry.identifier,
- run_type=entry.run_type,
- team_id=team_id,
- ).filter(active).update(expires_at=now)
-
-
-def update_snapshot_diff(
- snapshot_id: UUID,
- diff_artifact: Artifact,
- diff_percentage: float,
- diff_pixel_count: int,
- ssim_score: float,
- change_kind: ChangeKind,
- diff_metadata: DiffMetadata,
- team_id: int | None = None,
-) -> RunSnapshot:
- qs = RunSnapshot.objects.select_related("run")
- if team_id is not None:
- qs = qs.filter(team_id=team_id)
- snapshot = qs.get(id=snapshot_id)
- if diff_artifact.repo_id != snapshot.run.repo_id:
- raise ValueError(
- f"Cross-repo artifact reference: artifact repo {diff_artifact.repo_id} "
- f"!= snapshot repo {snapshot.run.repo_id}"
- )
- if snapshot.result != SnapshotResult.CHANGED:
- raise ValueError(f"Cannot attach diff to snapshot with result={snapshot.result}, expected 'changed'")
- snapshot.diff_artifact = diff_artifact
- snapshot.diff_percentage = diff_percentage
- snapshot.diff_pixel_count = diff_pixel_count
- snapshot.ssim_score = ssim_score
- snapshot.change_kind = change_kind.value
- # The Pydantic dump is the only legal write path into this column; reads
- # go through DiffMetadata.model_validate. Storage is JSONB; the schema
- # lives in diff_metadata.py.
- snapshot.diff_metadata = diff_metadata.model_dump(mode="json")
- snapshot.save(
- update_fields=[
- "diff_artifact",
- "diff_percentage",
- "diff_pixel_count",
- "ssim_score",
- "change_kind",
- "diff_metadata",
- ]
- )
- return snapshot
-
-
-def link_artifacts_to_snapshots(repo_id: UUID, content_hashes: set[str], *, run_id: UUID | None = None) -> int:
- """
- After artifacts are uploaded, link them to any pending snapshots.
-
- Returns number of snapshots updated.
- """
- if not content_hashes:
- return 0
-
- 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/logic/__init__.py b/products/visual_review/backend/logic/__init__.py
new file mode 100644
index 000000000000..3f1480b6fbd7
--- /dev/null
+++ b/products/visual_review/backend/logic/__init__.py
@@ -0,0 +1,7 @@
+"""Business logic for visual_review.
+
+One module per concern, named after it. Import the module you need
+(``from .errors import ...``) rather than re-exporting through here: a single
+binding per symbol keeps it obvious where behavior lives, and keeps test patch
+targets pointing at the real definition.
+"""
diff --git a/products/visual_review/backend/logic/approvals.py b/products/visual_review/backend/logic/approvals.py
new file mode 100644
index 000000000000..3fa311f1d5dc
--- /dev/null
+++ b/products/visual_review/backend/logic/approvals.py
@@ -0,0 +1,184 @@
+"""Approving snapshots and finalizing a run (the all-or-nothing baseline commit)."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from ..db import WRITER_DB
+from ..facade.enums import ReviewDecision, ReviewState, RunPurpose, RunStatus, SnapshotResult
+from ..models import Run
+from . import artifact_store, baselines, ci_status, errors, gating, run_queries
+
+
[email protected](using=WRITER_DB)
+def finalize_run(
+ run_id: UUID,
+ user_id: int,
+ team_id: int | None = None,
+ approve_all: bool = False,
+ review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,
+ commit_to_github: bool = True,
+ add_images_to_comment_on_pr: bool = False,
+) -> Run:
+ """Finalize a fully-reviewed run: commit the approved baseline and green the gate.
+
+ All-or-nothing by design — a run finalizes only once every changed/new snapshot is
+ resolved (approved, tolerated, quarantined, or removed). The committed baseline is
+ derived from DB state — exactly the snapshots with ``review_state == APPROVED``, by
+ their approved hash — so a tolerated snapshot keeps its existing baseline and is
+ never silently overwritten, and the commit always contains the full approved set
+ regardless of how many calls it took to review them.
+
+ With ``approve_all=True`` every still-pending changed/new snapshot is approved first
+ (tolerated ones are left untouched) — the "approve everything and ship" path. Without
+ it, the run must already be fully resolved or this raises RunNotFullyResolvedError.
+
+ Set ``commit_to_github=False`` for CLI auto-approve, which writes the baseline locally
+ instead of pushing it to the PR branch.
+
+ The post-approval PR comment is always posted (subject to the existing conditions: repo
+ PR comments enabled, run initiated from a GitHub review prompt). ``add_images_to_comment_on_pr``
+ only controls whether the before/after snapshot images are embedded in that comment;
+ defaults false so the comment stays a text summary unless the reviewer opts in.
+ """
+ run = run_queries._get_run_for_update(run_id, team_id=team_id)
+ repo = run.repo
+
+ if run.purpose == RunPurpose.OBSERVE:
+ raise ValueError("Observational runs cannot be approved")
+
+ # Idempotent: a finalized run already committed and posted status — don't redo the work
+ # (a second commit, status, and approval comment) on a repeat call.
+ if run.approved:
+ return run
+
+ if run.status != RunStatus.COMPLETED:
+ raise ValueError(f"Run must be completed before approval (current status: {run.status})")
+
+ if run_queries.is_run_stale(run):
+ raise errors.StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")
+
+ # Re-evaluate quarantine so resolution accounting reflects the current policy.
+ gating._stamp_quarantine(run)
+ now = timezone.now()
+
+ actionable = [
+ s
+ for s in run.snapshots.using(WRITER_DB).all()
+ if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW) and not s.is_quarantined
+ ]
+
+ if approve_all:
+ pending = [s for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)]
+ _validate_approval(run, {s.identifier: s.current_hash for s in pending})
+ for snapshot in pending:
+ snapshot.review_state = ReviewState.APPROVED
+ snapshot.reviewed_at = now
+ snapshot.reviewed_by_id = user_id
+ snapshot.approved_hash = snapshot.current_hash
+ snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])
+
+ # All-or-nothing: refuse to commit while any actionable snapshot is still unreviewed.
+ unresolved = [
+ s.identifier for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)
+ ]
+ if unresolved:
+ raise errors.RunNotFullyResolvedError(
+ f"Cannot finalize: {len(unresolved)} snapshot(s) still need review — approve or tolerate them first: "
+ f"{', '.join(sorted(unresolved)[:10])}"
+ )
+
+ # Commit set is derived from DB state, not a caller-supplied list, so it always reflects
+ # the full approved set however many calls reviewed it.
+ approved_updates = baselines._approved_baseline_updates(actionable)
+ has_removed = run.snapshots.using(WRITER_DB).filter(result=SnapshotResult.REMOVED).exists()
+
+ # Commit first — before DB writes — so a GitHub failure aborts cleanly. Removed snapshots
+ # also need a commit, to prune them from the baseline, even when nothing was approved.
+ if commit_to_github and (approved_updates or has_removed) and run.pr_number and repo.repo_full_name:
+ baselines._commit_baseline_to_github(run, repo, approved_updates, approver_user_id=user_id)
+
+ # Removed snapshots are pruned from the baseline on commit; mark them approved for cleanup.
+ run.snapshots.filter(result=SnapshotResult.REMOVED).update(
+ review_state=ReviewState.APPROVED,
+ reviewed_at=now,
+ reviewed_by_id=user_id,
+ )
+
+ run.approved = True
+ run.review_decision = review_decision
+ run.approved_at = now
+ run.approved_by_id = user_id
+ run.save(update_fields=["approved", "review_decision", "approved_at", "approved_by_id"])
+
+ if commit_to_github:
+ ci_status._post_commit_status(run, repo, "success", "Visual changes approved")
+
+ if commit_to_github and review_decision == ReviewDecision.HUMAN_APPROVED:
+ from ..tasks.tasks import post_approval_comment
+
+ run_id_str = str(run.id)
+ run_team_id = run.team_id
+ add_images = add_images_to_comment_on_pr
+ transaction.on_commit(
+ lambda: post_approval_comment.delay(run_team_id, run_id_str, add_images),
+ using=WRITER_DB,
+ )
+
+ return run
+
+
[email protected](using=WRITER_DB)
+def approve_snapshots(run_id: UUID, user_id: int, approved_snapshots: list[dict], team_id: int | None = None) -> Run:
+ """Approve specific snapshots within a run (DB only, no GitHub commit).
+
+ Used for per-snapshot "Accept change" in the UI. Does not finalize
+ the run — that happens via finalize_run.
+ """
+ run = run_queries._get_run_for_update(run_id, team_id=team_id)
+
+ if run.purpose == RunPurpose.OBSERVE:
+ raise ValueError("Observational runs cannot be approved")
+
+ if run_queries.is_run_stale(run):
+ raise errors.StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")
+
+ approvals = {s["identifier"]: s["new_hash"] for s in approved_snapshots}
+ _validate_approval(run, approvals)
+
+ now = timezone.now()
+ for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):
+ new_hash = approvals[snapshot.identifier]
+ snapshot.review_state = ReviewState.APPROVED
+ snapshot.reviewed_at = now
+ snapshot.reviewed_by_id = user_id
+ snapshot.approved_hash = new_hash
+ snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])
+
+ return run
+
+
+def _validate_approval(run: Run, approvals: dict[str, str]) -> None:
+ """Validate snapshot identifiers, hash matches, and artifact existence."""
+ repo = run.repo
+
+ run_identifiers = set(run.snapshots.values_list("identifier", flat=True))
+ unknown = set(approvals.keys()) - run_identifiers
+ if unknown:
+ raise ValueError(f"Unknown snapshot identifiers: {', '.join(sorted(unknown))}")
+
+ for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):
+ expected_hash = approvals[snapshot.identifier]
+ if expected_hash != snapshot.current_hash:
+ raise ValueError(
+ f"Hash mismatch for {snapshot.identifier}: "
+ f"approved {expected_hash[:12]} but current is {snapshot.current_hash[:12]}"
+ )
+
+ for identifier, new_hash in approvals.items():
+ artifact = artifact_store.get_artifact(repo.id, new_hash)
+ if not artifact:
+ raise errors.ArtifactNotFoundError(f"Artifact not found for hash {new_hash} (snapshot: {identifier})")
diff --git a/products/visual_review/backend/logic/artifact_store.py b/products/visual_review/backend/logic/artifact_store.py
new file mode 100644
index 000000000000..b4d3db7ff059
--- /dev/null
+++ b/products/visual_review/backend/logic/artifact_store.py
@@ -0,0 +1,159 @@
+"""Artifact rows and their object-storage bytes."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator
+from uuid import UUID
+
+from django.db import models as db_models
+
+from ..models import Artifact, Repo, RunSnapshot
+from ..storage import ArtifactStorage
+
+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
+
+
+def get_artifact(repo_id: UUID, content_hash: str) -> Artifact | None:
+ return Artifact.objects.filter(repo_id=repo_id, content_hash=content_hash).first()
+
+
+def get_or_create_artifact(
+ repo_id: UUID,
+ content_hash: str,
+ storage_path: str,
+ width: int | None = None,
+ height: int | None = None,
+ size_bytes: int | None = None,
+ team_id: int | None = None,
+) -> tuple[Artifact, bool]:
+ # Resolve team_id from the repo when not provided by the caller.
+ if team_id is None:
+ # nosemgrep: idor-lookup-without-team — resolving team_id from repo
+ team_id = Repo.objects.values_list("team_id", flat=True).get(id=repo_id)
+
+ return Artifact.objects.get_or_create(
+ repo_id=repo_id,
+ content_hash=content_hash,
+ team_id=team_id,
+ defaults={
+ "storage_path": storage_path,
+ "width": width,
+ "height": height,
+ "size_bytes": size_bytes,
+ },
+ )
+
+
+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[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]
+
+
+def get_presigned_upload_url(repo_id: UUID, content_hash: str) -> dict | None:
+ storage = ArtifactStorage(str(repo_id))
+ return storage.get_presigned_upload_url(content_hash)
+
+
+def get_presigned_download_url(repo_id: UUID, content_hash: str) -> str | None:
+ storage = ArtifactStorage(str(repo_id))
+ return storage.get_presigned_download_url(content_hash)
+
+
+def read_artifact_bytes(repo_id: UUID, content_hash: str) -> bytes | None:
+ """Read artifact content from storage."""
+ storage = ArtifactStorage(str(repo_id))
+ return storage.read(content_hash)
+
+
+def write_artifact_bytes(
+ repo_id: UUID,
+ content_hash: str,
+ content: bytes,
+ width: int | None = None,
+ height: int | None = None,
+ team_id: int | None = None,
+) -> Artifact:
+ """
+ Write artifact content to storage and create DB record.
+ Used for server-generated artifacts like diff images.
+ """
+ storage = ArtifactStorage(str(repo_id))
+ storage_path = storage.write(content_hash, content)
+
+ # Resolve team_id from the repo when not provided by the caller.
+ if team_id is None:
+ # nosemgrep: idor-lookup-without-team — resolving team_id from repo
+ team_id = Repo.objects.values_list("team_id", flat=True).get(id=repo_id)
+
+ artifact, _ = Artifact.objects.get_or_create(
+ repo_id=repo_id,
+ content_hash=content_hash,
+ team_id=team_id,
+ defaults={
+ "storage_path": storage_path,
+ "width": width,
+ "height": height,
+ "size_bytes": len(content),
+ },
+ )
+ return artifact
+
+
+def link_artifacts_to_snapshots(repo_id: UUID, content_hashes: set[str], *, run_id: UUID | None = None) -> int:
+ """
+ After artifacts are uploaded, link them to any pending snapshots.
+
+ Returns number of snapshots updated.
+ """
+ if not content_hashes:
+ return 0
+
+ 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/logic/baseline_overview.py b/products/visual_review/backend/logic/baseline_overview.py
new file mode 100644
index 000000000000..67a658b828e8
--- /dev/null
+++ b/products/visual_review/backend/logic/baseline_overview.py
@@ -0,0 +1,359 @@
+"""The baselines overview aggregate that backs the snapshot overview scene."""
+
+from __future__ import annotations
+
+from collections import Counter
+from datetime import datetime
+from uuid import UUID
+
+from django.db.models import Avg, Count, Q
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+
+from ..facade.enums import RunStatus, SnapshotResult, ToleratedReason
+from ..models import QuarantinedIdentifier, Run, RunSnapshot, ToleratedHash
+from . import run_queries
+
+
+def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
+ """Universe of identifiers with a current baseline, plus aggregates.
+
+ The "current baseline" universe is anchored on the latest non-superseded run
+ on the default branch (master/main) for each `run_type`. One row per
+ `(run_type, identifier)` — the closest thing to "what we'd compare a new
+ capture against right now".
+
+ Performance shape:
+ - 1 query for the universe runs (one row per run_type, indexed)
+ - 1 query for the universe rows (with thumbnail + artifact prefetch)
+ - 2 grouped queries for tolerate counts (30d + 90d)
+ - 1 grouped query for active quarantines
+ - 1 grouped query for lifetime baseline-flip count
+ - 2 queries for the recent-drift average (resolve last-N runs, aggregate)
+ - 3 cheap aggregate queries for totals
+ """
+ from datetime import timedelta
+
+ from ..facade.contracts import BASELINE_DRIFT_RECENT_RUN_COUNT, BASELINE_OVERVIEW_MAX_ENTRIES
+
+ now = timezone.now()
+
+ # 1. Find the latest *completed* run on the default branch per (repo,
+ # branch, run_type). Filtering on `superseded_by IS NULL` looks tempting
+ # but is wrong here: a freshly started PENDING/PROCESSING master run is
+ # un-superseded yet has zero (or sparse) RunSnapshots ingested, and would
+ # collapse the universe to whatever it has loaded so far. `status=completed`
+ # makes the universe fall through to the most recent fully-ingested run.
+ universe_runs = list(
+ Run.objects.filter(
+ repo_id=repo_id,
+ branch__in=run_queries._DEFAULT_BRANCHES,
+ status=RunStatus.COMPLETED,
+ )
+ .order_by("repo_id", "branch", "run_type", "-created_at")
+ .distinct("repo_id", "branch", "run_type")
+ .only("id", "run_type", "completed_at", "created_at")
+ )
+ universe_run_ids = [r.id for r in universe_runs]
+ if not universe_run_ids:
+ return _BaselineOverviewRaw(
+ entries=[],
+ tolerate_30d_by_id={},
+ tolerate_90d_by_id={},
+ active_quarantines_by_key={},
+ change_count_by_key={},
+ recent_drift_by_key={},
+ totals_all=0,
+ totals_recent=0,
+ totals_frequent=0,
+ totals_quarantined=0,
+ by_run_type={},
+ truncated=False,
+ generated_at=now,
+ )
+
+ # 2. Pull the universe rows. select_related the chain we need for thumbnails.
+ universe_qs = (
+ RunSnapshot.objects.filter(run_id__in=universe_run_ids)
+ .select_related("run", "current_artifact__thumbnail")
+ .only(
+ "identifier",
+ "metadata",
+ "run__id",
+ "run__run_type",
+ "run__completed_at",
+ "run__created_at",
+ "current_artifact__width",
+ "current_artifact__height",
+ "current_artifact__thumbnail__content_hash",
+ )
+ # Stable ordering so truncation is deterministic; newest baselines first.
+ .order_by("-run__completed_at", "identifier")
+ )
+ total_universe = universe_qs.count()
+ truncated = total_universe > BASELINE_OVERVIEW_MAX_ENTRIES
+ universe = list(universe_qs[:BASELINE_OVERVIEW_MAX_ENTRIES]) if truncated else list(universe_qs)
+ # Per-entry aggregates (tolerate counts, sparklines) only need to cover the
+ # entries we'll return. Totals must scope across the *full* universe,
+ # otherwise truncation makes them undercount in misleading ways (a 6000-id
+ # repo would show 0 frequently-tolerated if all of them sat past the slice).
+ universe_identifiers = list({s.identifier for s in universe})
+ if truncated:
+ full_universe_identifiers = list(universe_qs.values_list("identifier", flat=True).distinct())
+ else:
+ full_universe_identifiers = universe_identifiers
+
+ # 3a. Tolerate counts in 30d / 90d windows. Single grouped query each.
+ # Scope to HUMAN/AGENT reasons only — AUTO_THRESHOLD rows are auto-minted
+ # by the diff pipeline as a tolerated-hash cache for sub-threshold pixel
+ # jitter and don't represent a deliberate "we accept this drift" decision.
+ # Including them inflated the "Tolerated drift" tile with rendering noise.
+ intentional_tolerate_reasons = (ToleratedReason.HUMAN, ToleratedReason.AGENT)
+ tolerate_30d_by_id: dict[str, int] = {}
+ tolerate_90d_by_id: dict[str, int] = {}
+ if universe_identifiers:
+ tol_30d_cutoff = now - timedelta(days=30)
+ tol_90d_cutoff = now - timedelta(days=90)
+ for identifier, count in (
+ ToleratedHash.objects.filter(
+ repo_id=repo_id,
+ identifier__in=universe_identifiers,
+ reason__in=intentional_tolerate_reasons,
+ created_at__gte=tol_30d_cutoff,
+ )
+ .values_list("identifier")
+ .annotate(c=Count("id"))
+ .values_list("identifier", "c")
+ ):
+ tolerate_30d_by_id[identifier] = count
+ for identifier, count in (
+ ToleratedHash.objects.filter(
+ repo_id=repo_id,
+ identifier__in=universe_identifiers,
+ reason__in=intentional_tolerate_reasons,
+ created_at__gte=tol_90d_cutoff,
+ )
+ .values_list("identifier")
+ .annotate(c=Count("id"))
+ .values_list("identifier", "c")
+ ):
+ tolerate_90d_by_id[identifier] = count
+
+ # 3b. Active quarantines for this repo, scoped to the universe identifiers
+ # AND the run_types they live on (quarantine is per (repo, run_type, id)).
+ # We hydrate the full row (not just identity) so the overview can render
+ # reason / expiry / who / source-run inline without a per-card fetch.
+ # `select_related("source_run")` is a single JOIN, capped by
+ # `BASELINE_OVERVIEW_MAX_ENTRIES`. `Run.metadata` (JSONField) and
+ # `Run.error_message` (TextField) can be large and aren't needed by the
+ # summary — defer them to keep the response light.
+ active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier] = {}
+ if universe_identifiers:
+ for q in (
+ QuarantinedIdentifier.objects.filter(
+ repo_id=repo_id,
+ identifier__in=universe_identifiers,
+ )
+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
+ .select_related("source_run")
+ .defer("source_run__metadata", "source_run__error_message")
+ .order_by("-created_at")
+ ):
+ key = (q.run_type, q.identifier)
+ # Multiple active rows for the same key shouldn't happen — create
+ # auto-supersedes prior — but if it does, keep the latest (sorted
+ # above) and ignore the rest.
+ if key not in active_quarantines_by_key:
+ active_quarantines_by_key[key] = q
+
+ # 3c. Per-baseline stability signals: a lifetime baseline-flip count and a
+ # smoothed recent-drift average. Replaces a daily-bucket sparkline that
+ # had to scan millions of RunSnapshot rows on every request (~7s, OOMed on
+ # the web pod for repos with thousands of identifiers — see git history).
+ # Both queries here are scoped tightly enough to finish in tens of ms:
+ #
+ # change_count_by_key: COUNT(*) WHERE result IN ('changed','removed')
+ # across all completed master/main runs ever. Real baseline flips on
+ # master leave a CHANGED/REMOVED row in the run that introduced them
+ # (subsequent runs see UNCHANGED against the new YAML baseline), so
+ # this count IS the number of times the YAML moved. Postgres uses
+ # the `snapshot_run_result` index on (run_id, result) to bitmap-scan
+ # straight to the rare event rows (~1k of millions). No window
+ # function, no per-row LAG comparison.
+ #
+ # recent_drift_by_key: AVG(diff_percentage) over the last 10 master/
+ # main completed runs per (run_type). Bounded by run count, not by
+ # time window — caps the scanned set regardless of CI cadence. We
+ # resolve the run IDs first (sub-ms) and aggregate via PK-indexed
+ # run_id__in, otherwise the planner inlines a CTE that produces a
+ # ROW_NUMBER plan over the full RunSnapshot table.
+ change_count_by_key: dict[tuple[str, str], int] = {}
+ recent_drift_by_key: dict[tuple[str, str], float] = {}
+ if universe_identifiers:
+ for identifier, run_type, c in (
+ RunSnapshot.objects.filter(
+ run__repo_id=repo_id,
+ run__branch__in=run_queries._DEFAULT_BRANCHES,
+ run__status=RunStatus.COMPLETED,
+ result__in=(SnapshotResult.CHANGED, SnapshotResult.REMOVED),
+ )
+ .values("identifier", "run__run_type")
+ .annotate(c=Count("id"))
+ .values_list("identifier", "run__run_type", "c")
+ ):
+ change_count_by_key[(run_type, identifier)] = c
+
+ # Top-N per run_type via window function. There's no pure-ORM
+ # equivalent: Postgres doesn't allow filtering on a window result,
+ # and a per-run_type loop balloons to thousands of queries on repos
+ # where each Storybook story registers as its own run_type
+ # (benchmarked: 4ms raw vs 5.6s loop on a 30k-run repo with 2154
+ # run_types). The query is parameterized — every dynamic value
+ # passes through %s binding, no string concatenation, table name
+ # comes from the model. nosemgrep is required because the rule
+ # blanket-flags any .raw() use.
+ recent_run_sql = f"""
+ SELECT id, run_type FROM (
+ SELECT id, run_type,
+ ROW_NUMBER() OVER (PARTITION BY run_type ORDER BY created_at DESC) AS rn
+ FROM {Run._meta.db_table}
+ WHERE repo_id = %s AND branch = ANY(%s) AND status = %s
+ ) ranked WHERE rn <= %s
+ """ # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql
+ recent_run_ids = list(
+ Run.objects.raw( # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql
+ recent_run_sql,
+ [
+ str(repo_id),
+ list(run_queries._DEFAULT_BRANCHES),
+ RunStatus.COMPLETED,
+ BASELINE_DRIFT_RECENT_RUN_COUNT,
+ ],
+ )
+ )
+ if recent_run_ids:
+ for identifier, run_type, drift_avg in (
+ RunSnapshot.objects.filter(run_id__in=[r.id for r in recent_run_ids])
+ .values("identifier", "run__run_type")
+ .annotate(drift_avg=Avg("diff_percentage", filter=Q(diff_percentage__gt=0)))
+ .values_list("identifier", "run__run_type", "drift_avg")
+ ):
+ if drift_avg is not None:
+ recent_drift_by_key[(run_type, identifier)] = drift_avg
+
+ # 4. Totals computed across the *full* universe (not the truncated slice)
+ # so the stat row stays correct when the entries are clipped.
+ if truncated:
+ # Re-issue a small COUNT-only query for accurate totals across the
+ # universe; we already have the truncated list in memory.
+ totals_all = total_universe
+ else:
+ totals_all = len(universe)
+
+ # Recently / frequently tolerated — counts of distinct identifiers with
+ # ≥1 (or ≥3) intentional tolerations in the rolling window. Scope across
+ # the *full* universe so the stat row stays correct under truncation, and
+ # match the per-entry counts above by excluding AUTO_THRESHOLD.
+ recent_cutoff = now - timedelta(days=30)
+ frequent_cutoff = now - timedelta(days=90)
+ recent_ids: set[str] = set()
+ frequent_ids: set[str] = set()
+ if full_universe_identifiers:
+ recent_ids = set(
+ ToleratedHash.objects.filter(
+ repo_id=repo_id,
+ identifier__in=full_universe_identifiers,
+ reason__in=intentional_tolerate_reasons,
+ created_at__gte=recent_cutoff,
+ )
+ .values_list("identifier", flat=True)
+ .distinct()
+ )
+ frequent_grouped = (
+ ToleratedHash.objects.filter(
+ repo_id=repo_id,
+ identifier__in=full_universe_identifiers,
+ reason__in=intentional_tolerate_reasons,
+ created_at__gte=frequent_cutoff,
+ )
+ .values("identifier")
+ .annotate(c=Count("id"))
+ .filter(c__gte=3)
+ .values_list("identifier", flat=True)
+ )
+ frequent_ids = set(frequent_grouped)
+
+ # `active_quarantines_by_key` was built from the truncated set above (per-entry
+ # attached). Re-query for the totals so they cover the full universe.
+ if truncated and full_universe_identifiers:
+ quarantined_id_count = (
+ QuarantinedIdentifier.objects.filter(
+ repo_id=repo_id,
+ identifier__in=full_universe_identifiers,
+ )
+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
+ .values("identifier")
+ .distinct()
+ .count()
+ )
+ else:
+ quarantined_id_count = len({identifier for _, identifier in active_quarantines_by_key})
+
+ # by_run_type counts every entry in the universe. Aggregate query under
+ # truncation so it doesn't undercount; in-memory Counter when not truncated
+ # (we already paid for the row hydration).
+ if truncated:
+ by_run_type = dict(
+ universe_qs.values_list("run__run_type")
+ .order_by()
+ .annotate(c=Count("id"))
+ .values_list("run__run_type", "c")
+ )
+ else:
+ by_run_type = dict(Counter(s.run.run_type for s in universe))
+
+ return _BaselineOverviewRaw(
+ entries=universe,
+ tolerate_30d_by_id=tolerate_30d_by_id,
+ tolerate_90d_by_id=tolerate_90d_by_id,
+ active_quarantines_by_key=active_quarantines_by_key,
+ change_count_by_key=change_count_by_key,
+ recent_drift_by_key=recent_drift_by_key,
+ totals_all=totals_all,
+ totals_recent=len(recent_ids),
+ totals_frequent=len(frequent_ids),
+ totals_quarantined=quarantined_id_count,
+ by_run_type=by_run_type,
+ truncated=truncated,
+ generated_at=now,
+ )
+
+
+@frozen
+class _BaselineOverviewRaw:
+ """Internal raw shape — the facade layer reshapes this into the public DTOs.
+
+ Kept private to this package so that contract changes don't ripple through here.
+ """
+
+ entries: list[RunSnapshot]
+ tolerate_30d_by_id: dict[str, int]
+ tolerate_90d_by_id: dict[str, int]
+ # Latest active QuarantinedIdentifier (with `source_run` preloaded) for each
+ # `(run_type, identifier)` in the universe — lets the facade build the rich
+ # quarantine summary embedded on each BaselineEntry. Membership doubles as
+ # the "is_quarantined" signal — no separate set needed.
+ active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier]
+ # Stability signals keyed by `(run_type, identifier)` because the same
+ # identifier in different run types is a different baseline; merging would
+ # bleed storybook stability into playwright stability.
+ change_count_by_key: dict[tuple[str, str], int]
+ recent_drift_by_key: dict[tuple[str, str], float]
+ totals_all: int
+ totals_recent: int
+ totals_frequent: int
+ totals_quarantined: int
+ by_run_type: dict[str, int]
+ truncated: bool
+ generated_at: datetime
diff --git a/products/visual_review/backend/logic/baselines.py b/products/visual_review/backend/logic/baselines.py
new file mode 100644
index 000000000000..d7597d471aaf
--- /dev/null
+++ b/products/visual_review/backend/logic/baselines.py
@@ -0,0 +1,429 @@
+"""Baseline resolution, signing, and committing the approved baseline back to GitHub."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from django.conf import settings
+from django.db.models import F, Q
+
+import structlog
+
+if TYPE_CHECKING:
+ from posthog.models.integration import GitHubIntegration
+
+
+from ..db import WRITER_DB
+from ..facade.enums import ReviewState, SnapshotResult
+from ..models import Repo, Run, RunSnapshot
+from ..signing import sign_snapshot_hash, verify_signed_hash
+from . import errors, github_api, run_queries
+
+logger = structlog.get_logger(__name__)
+
+
+def _verify_baseline_hashes(repo: Repo, raw_hashes: dict[str, str]) -> dict[str, str]:
+ """Verify HMAC signatures on baseline hashes from the CLI.
+
+ Accepts a dict of ``{identifier: signed_hash_string}``. Returns a
+ dict of ``{identifier: plain_content_hash}`` for entries with valid
+ signatures. Invalid or unsigned entries are silently dropped —
+ they'll be treated as having no baseline (result = NEW).
+ """
+ if not raw_hashes:
+ return {}
+
+ keys = repo.signing_keys or {}
+ if not keys:
+ # Legitimate baseline files only exist after the server's approval flow
+ # has written one (which populates signing_keys). Reaching here means a
+ # .snapshots.yml was committed before any approval — likely hand-crafted.
+ # Drop every entry rather than passing it through unsigned. Snapshots
+ # will classify NEW, surfacing the situation to a reviewer.
+ logger.warning(
+ "visual_review.baseline_no_signing_keys",
+ repo_id=str(repo.id),
+ entry_count=len(raw_hashes),
+ )
+ return {}
+
+ repo_id = str(repo.id)
+ verified: dict[str, str] = {}
+
+ for identifier, signed_hash in raw_hashes.items():
+ content_hash = verify_signed_hash(repo_id, identifier, signed_hash, keys)
+ if content_hash is not None:
+ verified[identifier] = content_hash
+ else:
+ logger.debug(
+ "visual_review.baseline_hash_rejected",
+ identifier=identifier,
+ reason="invalid_signature",
+ )
+
+ return verified
+
+
+def _resolve_baselines_at_ref(repo: Repo, github: GitHubIntegration, run_type: str, ref: str) -> dict[str, str]:
+ """Fetch baseline content hashes from GitHub at a specific ref (branch name or SHA).
+
+ Returns a dict of identifier → content_hash (plain, not signed).
+ Returns empty dict when baseline file doesn't exist.
+ """
+ baseline_paths = repo.baseline_file_paths or {}
+ baseline_path = baseline_paths.get(run_type) or baseline_paths.get("default", ".snapshots.yml")
+
+ baselines_signed, _sha = github_api._fetch_baseline_file(github, repo.repo_full_name, baseline_path, ref)
+
+ return _verify_baseline_hashes(
+ repo,
+ {
+ identifier: entry["hash"]
+ for identifier, entry in baselines_signed.items()
+ if isinstance(entry, dict) and "hash" in entry
+ },
+ )
+
+
+def _run_is_on_default_branch(repo: Repo, branch: str) -> bool:
+ """Whether this run targets the repo's GitHub default branch.
+
+ Fences the client-supplied ``is_partial`` flag: the default branch holds
+ the authoritative full baseline, so a partial run there must not skip
+ removed-baseline detection. Resolves the default branch server-side from
+ GitHub. Returns ``False`` when it can't be determined (no integration) —
+ harmless, since the baseline fetch then returns empty and removal
+ detection short-circuits regardless.
+ """
+ try:
+ github = github_api.get_github_integration_for_repo(repo)
+ except Exception:
+ logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
+ return False
+ return branch == github_api._get_default_branch(github, repo.repo_full_name)
+
+
+def _resolve_baselines(repo, run_type: str, branch: str) -> dict[str, str]:
+ """Fetch baseline content hashes from GitHub for snapshot comparison.
+
+ Returns a dict of identifier → content_hash (plain, not signed).
+ Returns empty dict when no GitHub integration exists or the baseline
+ file is missing (first run).
+ """
+ try:
+ github = github_api.get_github_integration_for_repo(repo)
+ except Exception:
+ logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
+ return {}
+
+ return _resolve_baselines_at_ref(repo, github, run_type, branch)
+
+
+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
+ fills in entries that were lost during a rebase (the bot commit
+ rewrites the full file, and git rebase replays it destructively).
+
+ Branch entries win on conflict so approvals are preserved.
+ Identifiers previously approved as REMOVED on this branch are
+ tombstoned — healing would otherwise resurrect them from master
+ and 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:
+ github = github_api.get_github_integration_for_repo(repo)
+ except Exception:
+ logger.info("visual_review.no_github_integration", repo_id=str(repo.id))
+ return {}, 0
+
+ default_branch = github_api._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
+
+ merge_base_sha = github_api._get_merge_base_sha(github, repo.repo_full_name, default_branch, branch)
+ if not merge_base_sha:
+ return branch_baseline, 0
+
+ try:
+ merge_base_baseline = _resolve_baselines_at_ref(repo, github, run_type, merge_base_sha)
+ except Exception:
+ logger.warning(
+ "visual_review.merge_base_baseline_fetch_failed",
+ repo_id=str(repo.id),
+ branch=branch,
+ merge_base_sha=merge_base_sha,
+ )
+ return branch_baseline, 0
+ if not merge_base_baseline:
+ return branch_baseline, 0
+
+ source_pr_number = github_api._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)
+ merged = {**healable_merge_base, **branch_baseline}
+
+ if healed or tombstoned:
+ logger.info(
+ "visual_review.baseline_healed",
+ repo_id=str(repo.id),
+ branch=branch,
+ healed_count=len(healed),
+ branch_count=len(branch_baseline),
+ merge_base_count=len(merge_base_baseline),
+ merged_count=len(merged),
+ tombstoned_count=len(tombstoned),
+ )
+
+ return merged, len(healed)
+
+
+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
+ they're missing from branch. Without tombstoning, an approved
+ removal keeps reappearing: the bot commit drops it from the branch
+ file, but the next run's merge-base fetch re-adds it and classifies
+ it REMOVED all over again.
+
+ 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__approved=True,
+ review_state=ReviewState.APPROVED,
+ identifier=OuterRef("identifier"),
+ )
+ .order_by("-run__created_at")
+ .values("run__created_at")[:1]
+ )
+
+ return set(
+ RunSnapshot.objects.using(WRITER_DB)
+ .filter(
+ branch_scope,
+ run__repo=repo,
+ run__run_type=run_type,
+ run__approved=True,
+ review_state=ReviewState.APPROVED,
+ result=SnapshotResult.REMOVED,
+ )
+ .annotate(latest_approved_at=Subquery(latest_approved_run))
+ .filter(run__created_at=F("latest_approved_at"))
+ .values_list("identifier", flat=True)
+ .distinct()
+ )
+
+
+def _approved_baseline_updates(snapshots: Iterable[RunSnapshot]) -> list[dict]:
+ """The committed-baseline update set: approved changed/new snapshots, by approved hash.
+
+ Derived from DB state so the commit always reflects every approval regardless of how
+ many calls it took. Tolerated snapshots are excluded — toleration never updates the baseline.
+ """
+ return [
+ {"identifier": s.identifier, "new_hash": s.approved_hash}
+ for s in snapshots
+ if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW)
+ and not s.is_quarantined
+ and s.review_state == ReviewState.APPROVED
+ ]
+
+
+def _build_snapshots_yaml(
+ repo: Repo,
+ current_baselines: dict[str, dict],
+ updates: list[dict],
+) -> str:
+ """Build updated snapshots.yml with HMAC-signed hashes.
+
+ Each snapshot value is ``{hash: "v1.<kid>.<blake3hex>.<mac>"}``
+ where the MAC binds the hash to the repo and identifier.
+
+ *current_baselines* maps identifier to ``{hash: signed_hash_str}``.
+ *updates* is a list of ``{identifier, new_hash}`` where ``new_hash``
+ is a plain content hash — it gets signed here.
+ """
+ import yaml
+
+ kid, secret_hex = repo.get_active_signing_key()
+ repo_id = str(repo.id)
+
+ merged = dict(current_baselines)
+ for update in updates:
+ identifier = update["identifier"]
+ content_hash = update["new_hash"]
+ signed = sign_snapshot_hash(repo_id, identifier, content_hash, secret_hex, kid)
+ merged[identifier] = {"hash": signed}
+
+ sorted_snapshots = dict(sorted(merged.items()))
+
+ data: dict = {
+ "version": 1,
+ "config": {
+ "api": settings.SITE_URL,
+ "team": str(repo.team_id),
+ "repo": str(repo.id),
+ },
+ "snapshots": sorted_snapshots,
+ }
+
+ return yaml.dump(data, default_flow_style=False, sort_keys=False, indent=4)
+
+
+def _get_coauthor_trailer(user_id: int, installation_id: str) -> str | None:
+ """Return a `Co-authored-by` trailer for the approver, if they have a personal
+ GitHub integration for the same installation. Returns None when no match exists.
+ """
+ from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+
+ user_integration = UserIntegration.objects.filter(
+ user_id=user_id,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id=installation_id,
+ ).first()
+ if user_integration is None:
+ return None
+ return UserGitHubIntegration(user_integration).coauthor_trailer
+
+
+def _commit_baseline_to_github(
+ run: Run, repo: Repo, approved_snapshots: list[dict], approver_user_id: int | None = None
+) -> dict:
+ """
+ Commit updated baseline file to GitHub.
+
+ Raises:
+ GitHubIntegrationNotFoundError: No GitHub integration for team
+ PRSHAMismatchError: PR has newer commits than this run
+ BaselineFilePathNotConfiguredError: No baseline path for run type
+ GitHubCommitError: GitHub API error
+ """
+ baseline_paths = repo.baseline_file_paths or {}
+ baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")
+
+ if not baseline_path:
+ raise errors.BaselineFilePathNotConfiguredError(f"No baseline file path configured for run type {run.run_type}")
+
+ github = github_api.get_github_integration_for_repo(repo)
+
+ if run.pr_number is None:
+ raise errors.GitHubCommitError("Cannot commit to GitHub: run has no associated PR number")
+
+ pr_info = github_api._get_pr_info(github, repo.repo_full_name, run.pr_number)
+
+ if pr_info["head_sha"] != run.commit_sha:
+ raise errors.PRSHAMismatchError(
+ f"PR has newer commits. Expected {run.commit_sha}, got {pr_info['head_sha']}. "
+ "Please re-run visual tests on the latest commit."
+ )
+
+ current_baselines, file_sha = github_api._fetch_baseline_file(
+ github, repo.repo_full_name, baseline_path, pr_info["head_ref"]
+ )
+
+ # Remove entries for snapshots detected as removed in this run
+ removed_identifiers = set(run.snapshots.filter(result=SnapshotResult.REMOVED).values_list("identifier", flat=True))
+ for identifier in removed_identifiers:
+ current_baselines.pop(identifier, None)
+
+ updates = [{"identifier": s["identifier"], "new_hash": s["new_hash"]} for s in approved_snapshots]
+ new_content = _build_snapshots_yaml(repo, current_baselines, updates)
+
+ # Use GitHubIntegration.update_file() - it expects just the repo name, not full path
+ # The org comes from github.organization()
+ repo_name = repo.repo_full_name.split("/")[-1] if "/" in repo.repo_full_name else repo.repo_full_name
+
+ updated_count = len(updates)
+ removed_count = len(removed_identifiers)
+ parts = [f"{updated_count} updated"]
+ if removed_count:
+ parts.append(f"{removed_count} removed")
+ summary = ", ".join(parts)
+ commit_message = f"chore(visual): update {run.run_type} baselines\n\n{summary}\nRun: {run.id}"
+
+ installation_id = github.integration.integration_id
+ if approver_user_id is not None and isinstance(installation_id, str) and installation_id:
+ trailer = _get_coauthor_trailer(approver_user_id, installation_id)
+ if trailer:
+ commit_message = f"{commit_message}\n\n{trailer}"
+
+ result = github.update_file(
+ repository=repo_name,
+ file_path=baseline_path,
+ content=new_content,
+ commit_message=commit_message,
+ branch=pr_info["head_ref"],
+ sha=file_sha,
+ )
+
+ if not result.get("success"):
+ raise errors.GitHubCommitError(f"Failed to commit baseline: {result.get('error')}")
+
+ run.metadata["baseline_commit_sha"] = result.get("commit_sha")
+ run.save(update_fields=["metadata"])
+
+ return result
+
+
+def build_signed_baseline(run_id: UUID, team_id: int | None = None) -> str:
+ """Build the signed baseline YAML for a finalized run, without committing it.
+
+ For callers that commit the baseline themselves (the CLI's auto-approve, which writes
+ the file and commits via git rather than the GitHub App). Mirrors the committed set:
+ the current baseline merged with the approved changed/new hashes, removed entries pruned.
+ """
+ run = run_queries.get_run_with_snapshots(run_id, team_id=team_id)
+ repo = run.repo
+
+ baseline_paths = repo.baseline_file_paths or {}
+ baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")
+
+ github = github_api.get_github_integration_for_repo(repo)
+ current_baselines, _file_sha = github_api._fetch_baseline_file(
+ github, repo.repo_full_name, baseline_path, run.branch
+ )
+
+ snapshots = list(run.snapshots.all())
+ for s in snapshots:
+ if s.result == SnapshotResult.REMOVED:
+ current_baselines.pop(s.identifier, None)
+
+ return _build_snapshots_yaml(
+ repo, current_baselines=current_baselines, updates=_approved_baseline_updates(snapshots)
+ )
diff --git a/products/visual_review/backend/logic/ci_status.py b/products/visual_review/backend/logic/ci_status.py
new file mode 100644
index 000000000000..cdffb0608603
--- /dev/null
+++ b/products/visual_review/backend/logic/ci_status.py
@@ -0,0 +1,154 @@
+"""The GitHub side of the CI gate: commit statuses and job reruns."""
+
+from __future__ import annotations
+
+import structlog
+
+from ..facade.enums import RunPurpose
+from ..models import Repo, Run
+from . import comment_markdown, github_api
+
+logger = structlog.get_logger(__name__)
+
+
+def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:
+ """Rerun the visual-review CI job by its numeric ID. Returns (success, error_message).
+
+ The job ID and workflow run ID both come from client-supplied run metadata
+ (the CI runner has no server-verified channel today), so before calling
+ GitHub we bind the rerun two ways: the job must run on this run's commit
+ (``head_sha``) and must belong to the workflow run recorded at creation
+ (``github_run_id``). That pins recompute to the workflow run that produced
+ this visual-review run instead of letting it re-trigger any job on the
+ commit. It is defense-in-depth, not an identity proof — a caller who forges
+ a self-consistent metadata set can still reach sibling jobs of that run.
+ """
+ if not check_run_id.isdigit():
+ return False, "Invalid check run ID"
+
+ repo = run.repo
+ if not repo.repo_full_name:
+ return False, "Repo has no GitHub full name configured"
+
+ expected_run_id = (run.metadata or {}).get("github_run_id")
+ if not expected_run_id:
+ return False, "Workflow run ID not recorded for this run"
+
+ # `${{ job.check_run_id }}` doubles as the Actions job ID, so the jobs API
+ # gives us head_sha and the owning workflow run (run_id) in one call.
+ try:
+ job_response = github_api._github_api_request("GET", repo, f"actions/jobs/{check_run_id}")
+ except Exception:
+ return False, "Failed to verify CI job ownership"
+
+ if job_response.status_code != 200:
+ return False, f"Could not fetch CI job details (status {job_response.status_code})"
+
+ try:
+ job_data = job_response.json()
+ except Exception:
+ return False, "Failed to parse CI job response"
+
+ if job_data.get("head_sha") != run.commit_sha:
+ logger.warning(
+ "visual_review.ci_rerun_sha_mismatch",
+ run_id=str(run.id),
+ check_run_id=check_run_id,
+ expected_sha=run.commit_sha,
+ actual_sha=job_data.get("head_sha"),
+ )
+ return False, "Check run does not belong to this commit"
+
+ if str(job_data.get("run_id")) != str(expected_run_id):
+ logger.warning(
+ "visual_review.ci_rerun_workflow_mismatch",
+ run_id=str(run.id),
+ check_run_id=check_run_id,
+ expected_workflow_run=str(expected_run_id),
+ actual_workflow_run=str(job_data.get("run_id")),
+ )
+ return False, "CI job does not belong to this run's workflow"
+
+ try:
+ response = github_api._github_api_request("POST", repo, f"actions/jobs/{check_run_id}/rerun")
+ except Exception:
+ return False, "Failed to trigger job rerun"
+
+ if response.status_code == 201:
+ logger.info(
+ "visual_review.ci_job_rerun_triggered",
+ run_id=str(run.id),
+ check_run_id=check_run_id,
+ )
+ return True, None
+
+ return False, f"GitHub API returned {response.status_code} when rerunning job"
+
+
+def _post_commit_status(
+ run: Run,
+ repo: Repo,
+ state: str,
+ description: str,
+) -> None:
+ """
+ Post a commit status to GitHub (best-effort, never raises).
+
+ Uses the GitHub Commit Statuses API:
+ POST /repos/{owner}/{repo}/statuses/{sha}
+
+ state: "pending", "success", "failure", "error"
+
+ Partial runs (is_partial, client-supplied) suppress removed-baseline
+ detection on PR branches, so they must not be able to satisfy the gating
+ status context that branch protection evaluates. Branch protection keys off
+ the (context, state) pair, not the human-facing description, so a partial
+ run is posted to a separate "PostHog Visual Review / {run_type} (partial)"
+ context rather than the gating "PostHog Visual Review / {run_type}" one.
+ A subset run therefore can never turn the gated context green; a reviewer
+ must require the partial context explicitly to gate on partial runs. The
+ description is also annotated so the disclosure is visible to humans.
+ """
+ if not repo.repo_full_name:
+ return
+
+ context = f"PostHog Visual Review / {run.run_type}"
+ # Tracking-only (observe) and partial runs must never satisfy the gating context that
+ # branch protection evaluates. Both purpose and is_partial are client-supplied, so an
+ # observe run posted to the gating context could green a PR head SHA's required check
+ # without review. Route them to a distinct, non-gating context instead.
+ if run.purpose == RunPurpose.OBSERVE:
+ context = f"{context} (tracking)"
+ elif run.is_partial:
+ context = f"{context} (partial)"
+ description = f"{description} (partial run)"
+
+ try:
+ github = github_api.get_github_integration_for_repo(repo)
+ except Exception:
+ logger.debug("visual_review.status_check_skipped", run_id=str(run.id), reason="no_github_integration")
+ return
+
+ target_url = comment_markdown._run_url(run, repo)
+
+ try:
+ response = github.api_request(
+ "POST",
+ f"/repos/{repo.repo_full_name}/statuses/{run.commit_sha}",
+ json_body={
+ "state": state,
+ "description": description[:140],
+ "context": context,
+ "target_url": target_url,
+ },
+ )
+
+ if response.status_code != 201:
+ logger.warning(
+ "visual_review.status_check_failed",
+ run_id=str(run.id),
+ status_code=response.status_code,
+ response=response.text[:200],
+ )
+ except Exception:
+ logger.warning("visual_review.status_check_error", run_id=str(run.id), exc_info=True)
diff --git a/products/visual_review/backend/logic/comment_markdown.py b/products/visual_review/backend/logic/comment_markdown.py
new file mode 100644
index 000000000000..a1af63770b5e
--- /dev/null
+++ b/products/visual_review/backend/logic/comment_markdown.py
@@ -0,0 +1,267 @@
+"""Markdown rendering for PR comments. Pure formatting — no GitHub calls, no writes."""
+
+from __future__ import annotations
+
+import re
+import html
+from collections import Counter
+from dataclasses import dataclass
+
+from django.conf import settings
+from django.db import models as db_models
+
+from ..db import READER_DB
+from ..facade.enums import ReviewState, SnapshotResult
+from ..models import Artifact, Repo, Run, RunSnapshot
+from ..storage import ArtifactStorage
+
+
+def _format_change_counts(changed: int, new: int, removed: int) -> str:
+ """'N changed, M new, K removed', omitting zero counts; '' when all are zero."""
+ parts = []
+ if changed:
+ parts.append(f"{changed} changed")
+ if new:
+ parts.append(f"{new} new")
+ if removed:
+ parts.append(f"{removed} removed")
+ return ", ".join(parts)
+
+
+_MARKDOWN_ESCAPE_CHARS = r"\`*_{}[]()#+-.!|<>~"
+
+
+def _escape_markdown(value: str) -> str:
+ """Escape GitHub-flavored markdown control characters in user-supplied text."""
+ return "".join(f"\\{c}" if c in _MARKDOWN_ESCAPE_CHARS else c for c in value)
+
+
+@dataclass(frozen=True)
+class _Approver:
+ label: str
+ is_github_login: bool
+
+
+# A reviewer should be able to eyeball the approved snapshots straight from the PR.
+# GitHub can't render base64 data URIs (its markdown sanitizer strips them) and the
+# user-attachments upload path needs a browser session we don't have, so we embed
+# presigned object-storage URLs and let GitHub's image proxy (camo) fetch + cache
+# them. That proxy fetch can happen well after the comment is posted, so the URL
+# must outlive the default hour — use the S3 SigV4 maximum.
+_COMMENT_IMAGE_URL_EXPIRATION = 60 * 60 * 24 * 7 # 7 days
+
+_COMMENT_IMAGE_WIDTH = 320
+
+# Keep the comment readable: show the first N snapshots and link out for the rest.
+_MAX_COMMENT_IMAGES = 8
+
+
+def _comment_image_url(repo: Repo, artifact: Artifact | None) -> str | None:
+ """Presigned URL for the full-resolution snapshot image in a PR comment.
+
+ Serves the original artifact (not the thumbnail) so the embedded image opens at full
+ resolution when clicked — GitHub constrains the rendered size via the ``<img width>``
+ attribute but links the original. Returns None when the artifact is missing or object
+ storage is disabled — the caller renders an empty cell in that case.
+ """
+ if artifact is None:
+ return None
+ storage = ArtifactStorage(str(repo.id))
+ return storage.get_presigned_download_url(artifact.content_hash, expiration=_COMMENT_IMAGE_URL_EXPIRATION)
+
+
+_TABLE_BREAKING_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
+
+
+def _run_url(run: Run, repo: Repo) -> str:
+ """Link to the run page in PostHog."""
+ return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
+
+
+def _snapshot_url(run: Run, repo: Repo, snapshot: RunSnapshot) -> str:
+ """Deep link straight to a single snapshot on the run page."""
+ return f"{_run_url(run, repo)}?snapshot={snapshot.id}"
+
+
+def _snapshot_name_cell(identifier: str, suffix: str = "") -> str:
+ """Render a snapshot identifier as a single-line table cell (code span, pipe-safe).
+
+ Identifiers come from the run manifest without newline validation, so collapse
+ control characters (newlines, tabs, etc.) to spaces first — otherwise a
+ malformed or user-controlled story name could break out of the table row and
+ inject markdown/HTML into the comment. Then strip backticks and escape pipes so
+ it stays inside the code span and the cell.
+ """
+ safe = _TABLE_BREAKING_CHARS_RE.sub(" ", identifier).replace("`", "").replace("|", "\\|")
+ return f"`{safe}`{suffix}"
+
+
+def _snapshot_link_cell(run: Run, repo: Repo, snapshot: RunSnapshot, suffix: str = "") -> str:
+ """Snapshot identifier linked to its deep link on the run page, so a reviewer can jump
+ straight to that snapshot rather than the run as a whole."""
+ return f"[{_snapshot_name_cell(snapshot.identifier)}]({_snapshot_url(run, repo, snapshot)}){suffix}"
+
+
+def _image_cell(url: str | None, alt: str) -> str:
+ """Render an image (or an empty placeholder) for a before/after table cell.
+
+ The image is constrained to ``_COMMENT_IMAGE_WIDTH`` so the table stays compact, but
+ ``src`` points at the full-resolution original — GitHub opens that original when the
+ image is clicked.
+ """
+ if not url:
+ return "_(none)_"
+ # Escape both attributes — a URL containing a quote would otherwise break out of src.
+ src = html.escape(url, quote=True)
+ return f'<img src="{src}" width="{_COMMENT_IMAGE_WIDTH}" alt="{html.escape(alt, quote=True)}">'
+
+
+_IMAGE_TABLE_HEADER = "| Snapshot | Before | After |\n| --- | --- | --- |"
+
+_REVIEWABLE_RESULTS = (SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult.REMOVED)
+
+
+def _reviewable_snapshot_qs(run: Run) -> db_models.QuerySet[RunSnapshot]:
+ return run.snapshots.using(READER_DB).filter(result__in=_REVIEWABLE_RESULTS)
+
+
+def _postable_snapshot_qs(run: Run) -> db_models.QuerySet[RunSnapshot]:
+ """Reviewable snapshots minus the ones an approval comment should not surface.
+
+ Quarantined snapshots are suppressed by policy and tolerated ones are
+ intentional known drift, so neither belongs in the comment.
+ """
+ return _reviewable_snapshot_qs(run).exclude(is_quarantined=True).exclude(review_state=ReviewState.TOLERATED)
+
+
+def _build_snapshot_image_tables(run: Run, repo: Repo) -> str:
+ """Before/after image tables for the approved snapshots.
+
+ Changed and removed snapshots share one table (removed ones leave the *after*
+ cell empty); new snapshots get their own table (empty *before* cell). Capped
+ at ``_MAX_COMMENT_IMAGES`` rows total, prioritizing changed/removed diffs;
+ anything beyond links back to PostHog. Returns "" when no image could be
+ resolved (e.g. object storage disabled) so the comment stays text-only.
+ """
+ snapshots = list(
+ _postable_snapshot_qs(run)
+ .select_related(
+ "current_artifact",
+ "baseline_artifact",
+ )
+ .order_by("identifier")
+ )
+ if not snapshots:
+ return ""
+
+ # Changed/removed first — they carry a baseline diff a reviewer most needs to
+ # see — then new snapshots fill whatever's left of the image budget.
+ changed = [s for s in snapshots if s.result in (SnapshotResult.CHANGED, SnapshotResult.REMOVED)]
+ new = [s for s in snapshots if s.result == SnapshotResult.NEW]
+
+ total = len(changed) + len(new)
+ shown_changed = changed[:_MAX_COMMENT_IMAGES]
+ shown_new = new[: max(0, _MAX_COMMENT_IMAGES - len(shown_changed))]
+ shown = len(shown_changed) + len(shown_new)
+
+ any_image = False
+
+ def cell(artifact: Artifact | None, alt: str) -> str:
+ nonlocal any_image
+ url = _comment_image_url(repo, artifact)
+ if url:
+ any_image = True
+ return _image_cell(url, alt)
+
+ def row(s: RunSnapshot, before: Artifact | None) -> str:
+ suffix = " _(removed)_" if s.result == SnapshotResult.REMOVED else ""
+ name = _snapshot_link_cell(run, repo, s, suffix)
+ return f"| {name} | {cell(before, 'before')} | {cell(s.current_artifact, 'after')} |"
+
+ changed_rows = [row(s, s.baseline_artifact) for s in shown_changed]
+ new_rows = [row(s, None) for s in shown_new]
+
+ if not any_image:
+ return ""
+
+ def table(heading: str, rows: list[str]) -> str:
+ return "\n".join((f"**{heading}**", "", _IMAGE_TABLE_HEADER, *rows))
+
+ sections = [table(heading, rows) for heading, rows in (("Changed", changed_rows), ("New", new_rows)) if rows]
+ if shown < total:
+ sections.append(f"…and {total - shown} more — [view all in PostHog]({_run_url(run, repo)}).")
+
+ return "\n\n".join(sections)
+
+
+def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | None, add_images: bool = False) -> str:
+ """Build the markdown body of the post-approval PR comment.
+
+ Always a textual summary of what changed. When ``add_images`` is set, a
+ before/after table of the approved snapshot images is appended so another
+ reviewer can eyeball them without leaving the PR (omitted when no image can
+ be resolved).
+ """
+ counts = Counter(_postable_snapshot_qs(run).values_list("result", flat=True))
+ suppressed_only = not counts and _reviewable_snapshot_qs(run).exists()
+
+ if approver is None:
+ approver_text = "a reviewer"
+ elif approver.is_github_login:
+ approver_text = f"@{approver.label}"
+ else:
+ approver_text = _escape_markdown(approver.label)
+ baseline_sha = run.metadata.get("baseline_commit_sha")
+ sha_text = f" — baseline updated in `{baseline_sha[:7]}`" if isinstance(baseline_sha, str) and baseline_sha else ""
+
+ summary = _format_change_counts(
+ counts[SnapshotResult.CHANGED], counts[SnapshotResult.NEW], counts[SnapshotResult.REMOVED]
+ )
+
+ sections = [
+ f"✅ **Visual changes approved** by {approver_text}{sha_text}.",
+ f"[View this run in PostHog]({_run_url(run, repo)})",
+ ]
+ if summary:
+ sections.append(f"{summary}.")
+ elif suppressed_only:
+ sections.append("All visual changes in this run were quarantined or tolerated.")
+ if add_images:
+ tables = _build_snapshot_image_tables(run, repo)
+ if tables:
+ sections.append(tables)
+
+ return "\n\n".join(sections) + "\n"
+
+
+def _resolve_approver(user_id: int | None) -> _Approver | None:
+ """Resolve the approver's identity for the PR comment.
+
+ Prefers a verified GitHub login (safe to mention with `@`); otherwise
+ falls back to email local-part or first name, which the caller must
+ treat as untrusted markdown.
+ """
+ if user_id is None:
+ return None
+
+ from posthog.models.user import User
+ from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+
+ gh = (
+ UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.GITHUB)
+ .order_by("-created_at")
+ .first()
+ )
+ if gh is not None:
+ github_login = UserGitHubIntegration(gh).github_login
+ if github_login:
+ return _Approver(label=github_login, is_github_login=True)
+
+ user = User.objects.filter(id=user_id).only("email", "first_name").first()
+ if user is None:
+ return None
+ if user.email and "@" in user.email:
+ return _Approver(label=user.email.split("@", 1)[0], is_github_login=False)
+ if user.first_name:
+ return _Approver(label=user.first_name, is_github_login=False)
+ return None
diff --git a/products/visual_review/backend/logic/comments.py b/products/visual_review/backend/logic/comments.py
new file mode 100644
index 000000000000..eb43f83beda3
--- /dev/null
+++ b/products/visual_review/backend/logic/comments.py
@@ -0,0 +1,199 @@
+"""Posting and updating the one visual-review comment per PR."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+import structlog
+
+from posthog.egress.github.transport import GitHubRateLimitError
+
+from ..db import READER_DB, WRITER_DB
+from ..facade.enums import ReviewDecision, RunPurpose
+from ..models import Repo, Run
+from . import comment_markdown, github_api, run_queries
+
+logger = structlog.get_logger(__name__)
+
+
+def _find_existing_comment_id(repo: Repo, pr_number: int, exclude_run_id: UUID) -> int | None:
+ """Find the GitHub comment ID from a previous run on the same PR."""
+ previous_run = (
+ Run.objects.filter(repo=repo, pr_number=pr_number, metadata__has_key="github_comment_id")
+ .exclude(id=exclude_run_id)
+ .order_by("-created_at")
+ .first()
+ )
+ if previous_run:
+ value = previous_run.metadata.get("github_comment_id")
+ if isinstance(value, int):
+ return value
+ if isinstance(value, str) and value.isdigit():
+ return int(value)
+ return None
+
+
+def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
+ """
+ Post or update a PR comment prompting reviewers to approve visual changes.
+
+ One comment per PR — subsequent runs update the existing comment in place.
+ Skips non-actionable runs (observe-only, stale/superseded, already commented).
+ Best-effort and never raises.
+ """
+ if not repo.enable_pr_comments:
+ return
+
+ if not repo.repo_full_name or run.pr_number is None:
+ return
+
+ if run.purpose == RunPurpose.OBSERVE or run_queries.is_run_stale(run):
+ return
+
+ if run.metadata.get("github_comment_id"):
+ return
+
+ run_url = comment_markdown._run_url(run, repo)
+ comment_body = (
+ f"👋 **Visual changes detected** for this PR.\n\n"
+ f"[Review and approve in PostHog Visual Review]({run_url})\n\n"
+ f"If these changes are unexpected, they may be caused by a flaky test or a "
+ f"broken snapshot on master. Don't approve — rerun the job or wait for a fix."
+ )
+
+ try:
+ existing_comment_id = _find_existing_comment_id(repo, run.pr_number, exclude_run_id=run.id)
+ if existing_comment_id:
+ response = github_api._github_api_request(
+ method="PATCH",
+ repo=repo,
+ path=f"issues/comments/{existing_comment_id}",
+ json={"body": comment_body},
+ )
+ if response.status_code == 200:
+ run.metadata["github_comment_id"] = existing_comment_id
+ run.save(update_fields=["metadata"])
+ return
+ # Comment was deleted or inaccessible — fall through to create new one
+ logger.info(
+ "visual_review.pr_comment_update_failed_will_create",
+ run_id=str(run.id),
+ comment_id=existing_comment_id,
+ status_code=response.status_code,
+ )
+
+ response = github_api._github_api_request(
+ method="POST",
+ repo=repo,
+ path=f"issues/{run.pr_number}/comments",
+ json={"body": comment_body},
+ )
+ if response.status_code == 201:
+ comment_id = response.json().get("id")
+ run.metadata["github_comment_id"] = comment_id
+ run.save(update_fields=["metadata"])
+ else:
+ logger.warning(
+ "visual_review.pr_comment_failed",
+ run_id=str(run.id),
+ pr_number=run.pr_number,
+ status_code=response.status_code,
+ response=response.text[:200],
+ )
+ except Exception:
+ logger.warning("visual_review.pr_comment_error", run_id=str(run.id), pr_number=run.pr_number, exc_info=True)
+
+
+def _post_approval_comment(run: Run, repo: Repo, add_images: bool = False) -> None:
+ """Update the existing PR comment in place with the approved-changes summary.
+
+ Best-effort and never raises. Skips silently when the original review-prompt
+ comment was never posted (no `github_comment_id` in run.metadata) — i.e.,
+ when the review wasn't initiated by a human. ``add_images`` embeds the
+ before/after snapshot images in the comment when the reviewer opted in.
+ """
+ if not repo.enable_pr_comments:
+ return
+
+ if not repo.repo_full_name or run.pr_number is None:
+ return
+
+ if run.review_decision != ReviewDecision.HUMAN_APPROVED:
+ return
+
+ comment_id = run.metadata.get("github_comment_id")
+ if not comment_id:
+ return
+ if isinstance(comment_id, str) and comment_id.isdigit():
+ comment_id = int(comment_id)
+ if not isinstance(comment_id, int):
+ return
+
+ approver = comment_markdown._resolve_approver(run.approved_by_id)
+ body = comment_markdown._build_approval_comment_body(run, repo, approver, add_images=add_images)
+
+ try:
+ response = github_api._github_api_request(
+ method="PATCH",
+ repo=repo,
+ path=f"issues/comments/{comment_id}",
+ json={"body": body},
+ timeout=15,
+ )
+ if response.status_code == 200:
+ return
+
+ # Comment was deleted or inaccessible — fall back to creating a new one
+ if response.status_code == 404:
+ create_response = github_api._github_api_request(
+ method="POST",
+ repo=repo,
+ path=f"issues/{run.pr_number}/comments",
+ json={"body": body},
+ timeout=15,
+ )
+ if create_response.status_code == 201:
+ new_comment_id = create_response.json().get("id")
+ if isinstance(new_comment_id, int):
+ run.metadata["github_comment_id"] = new_comment_id
+ run.save(update_fields=["metadata"], using=WRITER_DB)
+ return
+ logger.warning(
+ "visual_review.approval_comment_create_failed",
+ run_id=str(run.id),
+ pr_number=run.pr_number,
+ status_code=create_response.status_code,
+ response=create_response.text[:200],
+ )
+ return
+
+ logger.warning(
+ "visual_review.approval_comment_update_failed",
+ run_id=str(run.id),
+ comment_id=comment_id,
+ status_code=response.status_code,
+ response=response.text[:200],
+ )
+ except GitHubRateLimitError:
+ # Bubble up so the Celery task can retry with the suggested countdown.
+ raise
+ except Exception:
+ logger.warning(
+ "visual_review.approval_comment_error",
+ run_id=str(run.id),
+ pr_number=run.pr_number,
+ exc_info=True,
+ )
+
+
+def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None, add_images: bool = False) -> None:
+ """Public entrypoint for the Celery task to update a PR comment after approval."""
+ run = (
+ Run.objects.select_related("repo")
+ .using(READER_DB)
+ .filter(id=run_id, **({"team_id": team_id} if team_id is not None else {}))
+ .first()
+ )
+ if run is None:
+ return
+ _post_approval_comment(run, run.repo, add_images=add_images)
diff --git a/products/visual_review/backend/logic/errors.py b/products/visual_review/backend/logic/errors.py
new file mode 100644
index 000000000000..95947d75588e
--- /dev/null
+++ b/products/visual_review/backend/logic/errors.py
@@ -0,0 +1,63 @@
+"""Exceptions raised by the visual_review business logic."""
+
+from __future__ import annotations
+
+
+class RepoNotFoundError(Exception):
+ pass
+
+
+class RunNotFoundError(Exception):
+ pass
+
+
+class ArtifactNotFoundError(Exception):
+ pass
+
+
+class GitHubIntegrationNotFoundError(Exception):
+ """Team does not have a GitHub integration configured."""
+
+ pass
+
+
+class GitHubCommitError(Exception):
+ """Failed to commit to GitHub."""
+
+ pass
+
+
+class PRSHAMismatchError(Exception):
+ """PR has new commits since this run was created."""
+
+ pass
+
+
+class HashIntegrityError(Exception):
+ """Uploaded image bytes do not match the claimed content hash."""
+
+ pass
+
+
+class StaleRunError(Exception):
+ """Approval blocked because a newer run exists for this PR."""
+
+ pass
+
+
+class RunNotFullyResolvedError(Exception):
+ """Finalize blocked because some changed/new snapshots are still unreviewed.
+
+ Visual review is all-or-nothing: the baseline is only committed once every
+ changed/new snapshot is approved or tolerated. Committing a subset is pointless
+ (CI re-detects the rest on the next run) and would green the gate over unreviewed
+ changes.
+ """
+
+ pass
+
+
+class BaselineFilePathNotConfiguredError(Exception):
+ """Repo does not have a baseline file path configured for this run type."""
+
+ pass
diff --git a/products/visual_review/backend/logic/gating.py b/products/visual_review/backend/logic/gating.py
new file mode 100644
index 000000000000..a0e517effb82
--- /dev/null
+++ b/products/visual_review/backend/logic/gating.py
@@ -0,0 +1,110 @@
+"""Quarantine stamping, resolution accounting, and the commit status that gates CI."""
+
+from __future__ import annotations
+
+from django.db.models import Q
+from django.utils import timezone
+
+from ..db import WRITER_DB
+from ..facade.enums import ReviewState, RunPurpose, SnapshotResult, ToleratedReason
+from ..models import QuarantinedIdentifier, Run, RunSnapshot
+from . import baselines, ci_status, comment_markdown, comments
+
+
+def _stamp_quarantine(run: Run) -> None:
+ """Evaluate quarantine policy and freeze it on each snapshot."""
+ now = timezone.now()
+ quarantined_ids = set(
+ QuarantinedIdentifier.objects.using(WRITER_DB)
+ .filter(repo_id=run.repo_id, run_type=run.run_type, team_id=run.team_id)
+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
+ .values_list("identifier", flat=True)
+ )
+
+ if not quarantined_ids:
+ run.snapshots.using(WRITER_DB).filter(is_quarantined=True).update(is_quarantined=False)
+ return
+
+ snapshots = run.snapshots.using(WRITER_DB)
+ snapshots.filter(identifier__in=quarantined_ids, is_quarantined=False).update(is_quarantined=True)
+ snapshots.filter(is_quarantined=True).exclude(identifier__in=quarantined_ids).update(is_quarantined=False)
+
+
+def _is_unresolved(s: RunSnapshot) -> bool:
+ """A snapshot is unresolved if it represents a change that hasn't been dealt with."""
+ if s.result == SnapshotResult.UNCHANGED:
+ return False
+ if s.is_quarantined:
+ return False
+ if s.review_state in (ReviewState.TOLERATED, ReviewState.APPROVED):
+ return False
+ return True
+
+
+def _changes_summary(run: Run) -> str:
+ """Change summary from the run's denormalized (quarantine-excluded) counts."""
+ return comment_markdown._format_change_counts(run.changed_count, run.new_count, run.removed_count)
+
+
+def _update_counts_and_post_status(run: Run) -> int:
+ """Re-stamp quarantine, recount snapshots, compute unresolved, and post commit status.
+
+ Counts on the run (changed_count, new_count, removed_count) reflect the raw
+ classifier output excluding quarantined snapshots. The unresolved count is
+ computed separately for the commit status and CI gate — it further excludes
+ tolerated and approved snapshots.
+
+ Returns the unresolved count.
+ """
+ _stamp_quarantine(run)
+
+ snapshots = list(run.snapshots.using(WRITER_DB).select_related("tolerated_hash_match").all())
+
+ run.changed_count = sum(1 for s in snapshots if s.result == SnapshotResult.CHANGED and not s.is_quarantined)
+ run.new_count = sum(1 for s in snapshots if s.result == SnapshotResult.NEW and not s.is_quarantined)
+ run.removed_count = sum(1 for s in snapshots if s.result == SnapshotResult.REMOVED and not s.is_quarantined)
+ run.tolerated_match_count = sum(
+ 1
+ for s in snapshots
+ if s.tolerated_hash_match is not None and s.tolerated_hash_match.reason == ToleratedReason.HUMAN
+ )
+ run.save(
+ update_fields=[
+ "changed_count",
+ "new_count",
+ "removed_count",
+ "tolerated_match_count",
+ ]
+ )
+
+ unresolved = sum(1 for s in snapshots if _is_unresolved(s))
+
+ # Approved-but-uncommitted changes still block the gate: the baseline on the PR branch
+ # doesn't reflect them yet, so re-running CI would re-detect them. Only finalize commits
+ # the baseline (and posts success directly), so until then the gate must stay red.
+ pending_commit = 0 if run.approved else len(baselines._approved_baseline_updates(snapshots))
+
+ repo = run.repo
+ if run.error_message:
+ ci_status._post_commit_status(run, repo, "error", f"Visual review failed: {run.error_message[:100]}")
+ elif run.purpose == RunPurpose.OBSERVE:
+ # Default-branch (tracking-only) runs never gate — there's no PR to approve.
+ # Report any changes as a green, informational status instead of a blocking
+ # failure; the per-snapshot detail lives in the VR UI (linked via target_url).
+ summary = _changes_summary(run)
+ description = f"Tracking only: {summary} recorded" if summary else "Tracking only: no visual changes"
+ ci_status._post_commit_status(run, repo, "success", description)
+ elif unresolved > 0:
+ ci_status._post_commit_status(run, repo, "failure", f"Visual changes detected: {_changes_summary(run)}")
+ comments._post_review_prompt_comment(run, repo)
+ elif pending_commit > 0:
+ ci_status._post_commit_status(
+ run,
+ repo,
+ "failure",
+ f"{pending_commit} approved change(s) awaiting commit — finalize the run to update the baseline",
+ )
+ else:
+ ci_status._post_commit_status(run, repo, "success", "No visual changes")
+
+ return unresolved
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
new file mode 100644
index 000000000000..cadcfc81a58e
--- /dev/null
+++ b/products/visual_review/backend/logic/github_api.py
@@ -0,0 +1,245 @@
+"""GitHub HTTP access: integration lookup, rename-tolerant requests, file and PR reads."""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Mapping
+from typing import TYPE_CHECKING
+from urllib.parse import quote
+
+import structlog
+
+if TYPE_CHECKING:
+ import requests
+
+ from posthog.models.integration import GitHubIntegration
+
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.models.github_integration_base import GitHubIntegrationError
+
+from ..models import Repo
+from . import errors
+
+logger = structlog.get_logger(__name__)
+
+
+def _get_merge_base_sha(github: GitHubIntegration, repo_full_name: str, base: str, head: str) -> str | None:
+ """Get the merge-base SHA between two refs via the GitHub Compare API."""
+ try:
+ response = github.api_request(
+ "GET",
+ f"/repos/{repo_full_name}/compare/{quote(base, safe='')}...{quote(head, safe='')}",
+ )
+ except GitHubIntegrationError:
+ logger.warning("visual_review.merge_base_fetch_failed", repo=repo_full_name, base=base, head=head)
+ return None
+
+ if response.status_code != 200:
+ logger.warning(
+ "visual_review.merge_base_fetch_failed",
+ repo=repo_full_name,
+ base=base,
+ head=head,
+ status=response.status_code,
+ )
+ return None
+
+ sha = response.json().get("merge_base_commit", {}).get("sha")
+ if sha is None:
+ logger.warning(
+ "visual_review.merge_base_sha_missing_from_response",
+ repo=repo_full_name,
+ base=base,
+ head=head,
+ )
+ return sha
+
+
+def _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:
+ """The repo's default branch via the integration's cached verb. Falls back to 'master'."""
+ try:
+ return github.get_default_branch(repo_full_name)
+ except GitHubRateLimitError:
+ raise
+ except Exception:
+ logger.warning("visual_review.default_branch_fetch_failed", repo=repo_full_name)
+ return "master"
+
+
+_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 get_github_integration_for_repo(repo: Repo):
+ """Get GitHub integration for the repo's team."""
+ from posthog.models.integration import GitHubIntegration, Integration
+
+ integration = Integration.objects.filter(team_id=repo.team_id, kind="github").first()
+
+ if not integration:
+ raise errors.GitHubIntegrationNotFoundError(f"No GitHub integration found for team {repo.team_id}")
+
+ return GitHubIntegration(integration, source="visual_review")
+
+
+def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:
+ """
+ Look up the current full_name of a repo by its numeric GitHub ID.
+
+ Used to detect renames: GET /repositories/{id} always returns the
+ latest full_name even if the repo was renamed or transferred.
+ Returns None if the repo is inaccessible.
+ """
+ response = github.api_request("GET", f"/repositories/{repo_external_id}")
+ if response.status_code == 200:
+ return response.json().get("full_name")
+ return None
+
+
+def _github_api_request(
+ method: str,
+ repo: Repo,
+ path: str,
+ *,
+ json: Mapping[str, object] | None = None,
+ timeout: int = 10,
+) -> requests.Response:
+ """
+ Make a GitHub API request, auto-resolving renamed repos on 404.
+
+ If the request returns 404 and the repo has an external ID, looks up
+ the current full_name via /repositories/{id}. If it changed, updates
+ the stored repo_full_name and retries once.
+ """
+ # Prevent path traversal — each segment must be safe
+ safe_path = "/".join(quote(segment, safe="") for segment in path.split("/"))
+
+ github = get_github_integration_for_repo(repo)
+
+ response = github.api_request(method, f"/repos/{repo.repo_full_name}/{safe_path}", json_body=json, timeout=timeout)
+
+ if response.status_code == 404 and repo.repo_external_id:
+ new_full_name = _resolve_repo_by_id(github, repo.repo_external_id)
+ if new_full_name and new_full_name != repo.repo_full_name:
+ logger.info(
+ "visual_review.repo_renamed",
+ repo_id=str(repo.id),
+ old_name=repo.repo_full_name,
+ new_name=new_full_name,
+ )
+ repo.repo_full_name = new_full_name
+ repo.save(update_fields=["repo_full_name"])
+
+ response = github.api_request(
+ method, f"/repos/{new_full_name}/{safe_path}", json_body=json, timeout=timeout
+ )
+
+ return response
+
+
+def _get_pr_info(github, repo_full_name: str, pr_number: int) -> dict:
+ """
+ Fetch PR info from GitHub.
+
+ Returns dict with head_ref (branch) and head_sha.
+ """
+ response = github.api_request("GET", f"/repos/{repo_full_name}/pulls/{pr_number}")
+
+ if response.status_code != 200:
+ raise errors.GitHubCommitError(f"Failed to fetch PR info: {response.status_code} {response.text}")
+
+ pr_data = response.json()
+ return {
+ "head_ref": pr_data["head"]["ref"],
+ "head_sha": pr_data["head"]["sha"],
+ }
+
+
+def _fetch_baseline_file(
+ github, repo_full_name: str, file_path: str, branch: str
+) -> tuple[dict[str, dict], str | None]:
+ """
+ Fetch current baseline file content from GitHub.
+
+ Returns ``(snapshots_dict, file_sha)``. Snapshots dict maps
+ identifier to ``{hash: "v1.kid.hash.tag"}`` (the signed format).
+ If the file doesn't exist, returns ``({}, None)``.
+ """
+ import yaml
+
+ try:
+ result = github.get_file_contents(repo_full_name, file_path, ref=branch)
+ except GitHubRateLimitError:
+ raise
+ except GitHubIntegrationError as e:
+ raise errors.GitHubCommitError(f"Failed to fetch baseline file: {e}") from e
+
+ if result is None:
+ return {}, None
+
+ file_sha = result["sha"]
+
+ parsed = yaml.safe_load(result["content"])
+ if not parsed or parsed.get("version") != 1:
+ return {}, file_sha
+
+ raw_snapshots = parsed.get("snapshots", {})
+
+ normalized: dict[str, dict] = {}
+ for identifier, value in raw_snapshots.items():
+ if isinstance(value, dict) and "hash" in value:
+ normalized[identifier] = value
+ return normalized, file_sha
diff --git a/products/visual_review/backend/logic/history.py b/products/visual_review/backend/logic/history.py
new file mode 100644
index 000000000000..85b4e202290e
--- /dev/null
+++ b/products/visual_review/backend/logic/history.py
@@ -0,0 +1,78 @@
+"""Baseline timeline for a single snapshot identifier."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import connections
+
+from ..db import READER_DB
+from ..models import RunSnapshot
+from . import run_queries
+
+_SNAPSHOT_HISTORY_DEDUP_SQL = """
+WITH ordered AS (
+ SELECT rs.id,
+ rs.baseline_artifact_id,
+ LAG(rs.baseline_artifact_id) OVER (ORDER BY r.created_at) AS prev_baseline_id,
+ r.created_at
+ FROM visual_review_runsnapshot rs
+ JOIN visual_review_run r ON r.id = rs.run_id
+ WHERE r.repo_id = %s
+ AND r.run_type = %s
+ AND r.branch = ANY(%s)
+ AND r.status = 'completed'
+ AND rs.identifier = %s
+)
+SELECT id
+FROM ordered
+WHERE prev_baseline_id IS DISTINCT FROM baseline_artifact_id
+ORDER BY created_at DESC
+"""
+
+
+def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[RunSnapshot]:
+ """Baseline timeline for a snapshot identifier on the default branch.
+
+ Returns one entry per *baseline transition* — every time the committed
+ `.snapshots.yml` baseline actually moved. LAG-on-`baseline_artifact_id`
+ (over ASC ordering) keeps the FIRST run of each baseline period, so the
+ user sees the inception event plus every change since.
+
+ Why LAG on `baseline_artifact_id` and not `current_artifact_id`:
+ - `current_artifact_id` is the bytes captured by THIS run. Pixel jitter
+ and tolerated drift produce different content_hash → different Artifact
+ rows even though the *baseline* didn't move. Keying on current_ caused
+ a prod regression (252 fake history events on a single tolerated-drift
+ story) because the artifact alternated between near-identical hashes
+ the matcher kept absorbing. LAG-on-current-with-result-filter (the
+ prior fix) hid those false events but also hid genuine first-appearance
+ rows whose `result=unchanged` against an existing YAML baseline.
+ - `baseline_artifact_id` reflects the YAML state at run time. It only
+ changes when a baseline-update PR merges. Pixel jitter and tolerated
+ drift leave it untouched, so LAG dedup naturally collapses noise while
+ catching every real baseline flip — without needing a `result` filter.
+
+ DB-level filters:
+ - branch ∈ master/main, run_type, repo: scope to default-branch runs of
+ this kind
+ - status=completed: drop pre-classification rows where the baseline FK
+ hasn't been hydrated yet (pending/processing leave NULL baseline_artifact)
+ """
+ with connections[READER_DB].cursor() as cursor:
+ cursor.execute(
+ _SNAPSHOT_HISTORY_DEDUP_SQL,
+ [str(repo_id), run_type, list(run_queries._DEFAULT_BRANCHES), identifier],
+ )
+ ordered_ids: list[UUID] = [row[0] for row in cursor.fetchall()]
+
+ if not ordered_ids:
+ return []
+
+ # `id__in` doesn't preserve order, so look rows up by id and re-emit in the
+ # cursor's order. Fetched count equals the deduped baseline-event count
+ # (typically <20), so this hydration is cheap regardless of raw history size.
+ rows_by_id: dict[UUID, RunSnapshot] = {
+ row.id: row for row in RunSnapshot.objects.filter(id__in=ordered_ids).select_related("run", "current_artifact")
+ }
+ return [rows_by_id[rid] for rid in ordered_ids if rid in rows_by_id]
diff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.py
new file mode 100644
index 000000000000..cb26a5a38768
--- /dev/null
+++ b/products/visual_review/backend/logic/quarantine.py
@@ -0,0 +1,103 @@
+"""Quarantined identifiers: list, add, lift, expire."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import Q
+from django.utils import timezone
+
+from ..db import WRITER_DB
+from ..models import QuarantinedIdentifier, Run
+from . import errors, repos
+
+
+def list_quarantined_identifiers(
+ repo_id: UUID, team_id: int, identifier: str | None = None, run_type: str | None = None
+) -> list[QuarantinedIdentifier]:
+ qs = (
+ QuarantinedIdentifier.objects.using(WRITER_DB)
+ .filter(repo_id=repo_id, team_id=team_id)
+ # Preload `source_run` so the facade can render the "what was wrong"
+ # link without an extra fetch per row. `Run.metadata` (JSONField) and
+ # `Run.error_message` (TextField) can be large and aren't needed for
+ # the summary — defer to keep response payloads tight.
+ .select_related("source_run")
+ .defer("source_run__metadata", "source_run__error_message")
+ )
+ if run_type:
+ qs = qs.filter(run_type=run_type)
+ if identifier:
+ qs = qs.filter(identifier=identifier)
+ else:
+ now = timezone.now()
+ qs = qs.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
+ return list(qs.order_by("-created_at"))
+
+
[email protected](using=WRITER_DB)
+def quarantine_identifier(
+ repo_id: UUID,
+ identifier: str,
+ run_type: str,
+ reason: str,
+ user_id: int,
+ team_id: int,
+ expires_at: datetime | None = None,
+ source_run_id: UUID | None = None,
+) -> QuarantinedIdentifier:
+ repos.get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
+ now = timezone.now()
+ # Resolve the source run inside the team scope so a malicious caller can't
+ # attach a quarantine to an unrelated run. Silently drop on mismatch — the
+ # quarantine itself still wins; we just lose the "what was wrong" pointer.
+ # We fetch (not just .exists()) so the facade can serialize source_run
+ # without a lazy-load on the freshly-created row.
+ source_run: Run | None = None
+ if source_run_id is not None:
+ source_run = Run.objects.using(WRITER_DB).filter(id=source_run_id, repo_id=repo_id, team_id=team_id).first()
+ QuarantinedIdentifier.objects.using(WRITER_DB).select_for_update().filter(
+ repo_id=repo_id,
+ identifier=identifier,
+ run_type=run_type,
+ team_id=team_id,
+ ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).update(expires_at=now)
+ return QuarantinedIdentifier.objects.using(WRITER_DB).create(
+ repo_id=repo_id,
+ identifier=identifier,
+ run_type=run_type,
+ team_id=team_id,
+ reason=reason,
+ expires_at=expires_at,
+ created_by_id=user_id,
+ source_run=source_run,
+ )
+
+
+def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:
+ repos.get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
+ QuarantinedIdentifier.objects.using(WRITER_DB).filter(
+ repo_id=repo_id,
+ identifier=identifier,
+ run_type=run_type,
+ team_id=team_id,
+ ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now())).update(expires_at=timezone.now())
+
+
+def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
+ now = timezone.now()
+ active = Q(expires_at__isnull=True) | Q(expires_at__gt=now)
+ try:
+ entry = QuarantinedIdentifier.objects.using(WRITER_DB).filter(active).get(id=entry_id, team_id=team_id)
+ except QuarantinedIdentifier.DoesNotExist as e:
+ raise errors.RunNotFoundError(f"Quarantine entry {entry_id} not found or already expired") from e
+
+ # Expire all active entries for the same identifier/run_type, not just this one
+ QuarantinedIdentifier.objects.using(WRITER_DB).filter(
+ repo_id=entry.repo_id,
+ identifier=entry.identifier,
+ run_type=entry.run_type,
+ team_id=team_id,
+ ).filter(active).update(expires_at=now)
diff --git a/products/visual_review/backend/logic/repos.py b/products/visual_review/backend/logic/repos.py
new file mode 100644
index 000000000000..955e8e94907d
--- /dev/null
+++ b/products/visual_review/backend/logic/repos.py
@@ -0,0 +1,38 @@
+"""Repo CRUD."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from ..facade.contracts import UpdateRepoInput
+from ..models import Repo
+from . import errors
+
+
+def get_repo(repo_id: UUID, team_id: int) -> Repo:
+ try:
+ return Repo.objects.get(id=repo_id, team_id=team_id)
+ except Repo.DoesNotExist as e:
+ raise errors.RepoNotFoundError(f"Repo {repo_id} not found") from e
+
+
+def list_repos_for_team(team_id: int) -> list[Repo]:
+ return list(Repo.objects.filter(team_id=team_id).order_by("-created_at"))
+
+
+def create_repo(team_id: int, repo_external_id: int, repo_full_name: str) -> Repo:
+ return Repo.objects.create(
+ team_id=team_id,
+ repo_external_id=repo_external_id,
+ repo_full_name=repo_full_name,
+ )
+
+
+def update_repo(input: UpdateRepoInput, team_id: int) -> Repo:
+ repo = get_repo(input.repo_id, team_id)
+ if input.baseline_file_paths is not None:
+ repo.baseline_file_paths = input.baseline_file_paths
+ if input.enable_pr_comments is not None:
+ repo.enable_pr_comments = input.enable_pr_comments
+ repo.save()
+ return repo
diff --git a/products/visual_review/backend/logic/run_queries.py b/products/visual_review/backend/logic/run_queries.py
new file mode 100644
index 000000000000..5e20d7af54cf
--- /dev/null
+++ b/products/visual_review/backend/logic/run_queries.py
@@ -0,0 +1,154 @@
+"""Read-only run and snapshot lookups, plus the review-state filters the runs list is built on."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import models as db_models
+from django.db.models import Count, Q
+
+from posthog.helpers.trigram_search import (
+ TrigramSearchField,
+ apply_trigram_search,
+ drop_similar_when_exact_exists,
+ normalize_search_term,
+)
+
+from ..db import WRITER_DB
+from ..facade.enums import RunPurpose, RunStatus, SnapshotResult
+from ..models import Run, RunSnapshot
+from . import errors
+
+
+def is_run_stale(run: Run) -> bool:
+ return run.superseded_by_id is not None
+
+
+_HAS_CHANGES = Q(changed_count__gt=0) | Q(new_count__gt=0) | Q(removed_count__gt=0)
+
+_CURRENT = Q(superseded_by__isnull=True)
+
+_ON_PR = Q(pr_number__isnull=False)
+
+REVIEW_STATE_FILTERS: dict[str, Q] = {
+ # Only PR runs need human review — master/branch pushes without a PR are just drift
+ "needs_review": Q(status=RunStatus.COMPLETED)
+ & _HAS_CHANGES
+ & Q(approved=False)
+ & _CURRENT
+ & _ON_PR
+ & Q(purpose=RunPurpose.REVIEW),
+ "clean": (Q(status=RunStatus.COMPLETED) & ~_HAS_CHANGES) | Q(approved=True),
+ "processing": Q(status=RunStatus.PROCESSING) & _CURRENT,
+ "stale": Q(superseded_by__isnull=False) & Q(approved=False) & _HAS_CHANGES,
+}
+
+# Free-text search over the runs list uses the shared trigram helper for the
+# prose-like fields (branch, run type), where fuzzy/typo matching helps. Commit
+# SHA and PR number are matched exactly (prefix / numeric id) via extra_exact_q —
+# fuzzy matching a hex SHA or an integer is meaningless.
+RUN_SEARCH_FIELDS = (TrigramSearchField("branch"), TrigramSearchField("run_type"))
+
+
+def list_runs_for_team(
+ team_id: int,
+ review_state: str | None = None,
+ repo_id: UUID | None = None,
+ pr_number: int | None = None,
+ commit_sha: str | None = None,
+ branch: str | None = None,
+ search: str | None = None,
+) -> db_models.QuerySet[Run]:
+ qs = Run.objects.filter(team_id=team_id).select_related("repo")
+ if repo_id is not None:
+ qs = qs.filter(repo_id=repo_id)
+ if review_state and review_state in REVIEW_STATE_FILTERS:
+ qs = qs.filter(REVIEW_STATE_FILTERS[review_state])
+ if pr_number is not None:
+ qs = qs.filter(pr_number=pr_number)
+ if commit_sha:
+ qs = qs.filter(commit_sha=commit_sha)
+ if branch:
+ qs = qs.filter(branch=branch)
+ if search and (term := normalize_search_term(search)):
+ # Commit SHA matches by prefix (reviewers paste the short SHA); PR number by exact id.
+ extra_exact_q = Q(commit_sha__istartswith=term)
+ if term.isdigit():
+ extra_exact_q |= Q(pr_number=int(term))
+ return drop_similar_when_exact_exists(
+ apply_trigram_search(
+ qs,
+ term,
+ span_prefix="visual_review.runs.search",
+ fields=RUN_SEARCH_FIELDS,
+ extra_exact_q=extra_exact_q,
+ tiebreakers=("-created_at",),
+ )
+ )
+ return qs.order_by("-created_at")
+
+
+def get_review_state_counts(team_id: int, repo_id: UUID | None = None) -> dict[str, int]:
+ qs = Run.objects.filter(team_id=team_id)
+ if repo_id is not None:
+ qs = qs.filter(repo_id=repo_id)
+ return qs.aggregate(
+ needs_review=Count("id", filter=REVIEW_STATE_FILTERS["needs_review"]),
+ clean=Count("id", filter=REVIEW_STATE_FILTERS["clean"]),
+ processing=Count("id", filter=REVIEW_STATE_FILTERS["processing"]),
+ stale=Count("id", filter=REVIEW_STATE_FILTERS["stale"]),
+ )
+
+
+def get_run(run_id: UUID, team_id: int | None = None) -> Run:
+ try:
+ qs = Run.objects.select_related("repo")
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ return qs.get(id=run_id)
+ except Run.DoesNotExist as e:
+ raise errors.RunNotFoundError(f"Run {run_id} not found") from e
+
+
+def _get_run_for_update(run_id: UUID, team_id: int | None = None) -> Run:
+ """Get a run with a row-level lock on the writer DB. Must be called inside a transaction."""
+ try:
+ qs = Run.objects.using(WRITER_DB).select_for_update().select_related("repo")
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ return qs.get(id=run_id)
+ except Run.DoesNotExist as e:
+ raise errors.RunNotFoundError(f"Run {run_id} not found") from e
+
+
+def get_run_with_snapshots(run_id: UUID, team_id: int | None = None) -> Run:
+ try:
+ qs = Run.objects.prefetch_related(
+ "snapshots__current_artifact",
+ "snapshots__baseline_artifact",
+ "snapshots__diff_artifact",
+ )
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ return qs.get(id=run_id)
+ except Run.DoesNotExist as e:
+ raise errors.RunNotFoundError(f"Run {run_id} not found") from e
+
+
+def get_run_snapshots(run_id: UUID, team_id: int | None = None) -> list[RunSnapshot]:
+ run = get_run(run_id, team_id=team_id)
+ return list(
+ run.snapshots.select_related("current_artifact", "baseline_artifact", "diff_artifact").order_by(
+ db_models.Case(
+ db_models.When(result=SnapshotResult.UNCHANGED, then=1),
+ default=0,
+ ),
+ "identifier",
+ )
+ )
+
+
+# Default-branch fallback. We don't track repos' actual default branch, so we
+# include both candidates and assume nobody has both — whichever has rows wins.
+# When `trunk`/`develop`-style defaults show up, this becomes a `Repo` field.
+_DEFAULT_BRANCHES = ("master", "main")
diff --git a/products/visual_review/backend/logic/runs.py b/products/visual_review/backend/logic/runs.py
new file mode 100644
index 000000000000..d4a6d33e5a85
--- /dev/null
+++ b/products/visual_review/backend/logic/runs.py
@@ -0,0 +1,426 @@
+"""Run lifecycle: create, ingest snapshots, classify on completion, finish, recompute."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import transaction
+from django.db.models import Count, F, Q
+from django.utils import timezone
+
+import structlog
+
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.ph_client import ph_scoped_capture
+
+from ..classifier import SnapshotClassifier
+from ..db import WRITER_DB
+from ..facade.contracts import CreateRunInput
+from ..facade.enums import RunStatus, SnapshotResult
+from ..models import Repo, Run, RunSnapshot, ToleratedHash
+from ..storage import ArtifactStorage
+from . import artifact_store, baselines, ci_status, errors, gating, repos, run_queries, uploads
+
+logger = structlog.get_logger(__name__)
+
+
+def create_run(input: CreateRunInput, team_id: int) -> tuple[Run, list[dict]]:
+ """
+ Create a new run with its snapshots.
+
+ Returns the run and list of upload targets for missing artifacts.
+ Each upload target has: content_hash, url, fields
+
+ input.baseline_hashes, input.unchanged_count and input.removed_identifiers
+ are deprecated and ignored: the backend fetches baselines from GitHub and
+ computes everything. The fields are kept for backward compat with older
+ CLI versions.
+
+ input.is_partial tags the run as a subset; the classifier then leaves baseline
+ identifiers we didn't touch alone instead of marking them as removed.
+ """
+ repo = repos.get_repo(input.repo_id, team_id)
+
+ return _create_run_inner(repo, team_id, input)
+
+
[email protected](using=WRITER_DB)
+def _create_run_inner(repo: Repo, team_id: int, input: CreateRunInput) -> tuple[Run, list[dict]]:
+ # Supersede ALL old runs before inserting the new one. The unique
+ # partial index on (repo, branch, run_type) WHERE superseded_by IS NULL
+ # requires the slot to be free before the insert. A new CI push always
+ # replaces the previous run — approved and clean runs still show up in
+ # their respective UI filters via REVIEW_STATE_FILTERS.
+ supersede_filter = Run.objects.using(WRITER_DB).filter(
+ repo_id=repo.id,
+ branch=input.branch,
+ run_type=input.run_type,
+ superseded_by__isnull=True,
+ )
+ # Collect IDs before mutating, then self-reference to clear the slot
+ superseded_ids = list(supersede_filter.values_list("id", flat=True))
+ if superseded_ids:
+ from django.db.models import F
+
+ Run.objects.using(WRITER_DB).filter(id__in=superseded_ids, team_id=team_id).update(superseded_by=F("id"))
+
+ run = Run.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ run_type=input.run_type,
+ commit_sha=input.commit_sha,
+ branch=input.branch,
+ pr_number=input.pr_number,
+ purpose=input.purpose,
+ total_snapshots=len(input.snapshots),
+ metadata=input.metadata or {},
+ is_partial=input.is_partial,
+ )
+
+ # Fix up the sentinel pointers to reference the actual new run
+ if superseded_ids:
+ Run.objects.using(WRITER_DB).filter(id__in=superseded_ids, team_id=team_id).update(superseded_by=run)
+
+ snapshots = [
+ {
+ "identifier": s.identifier,
+ "content_hash": s.content_hash,
+ "width": s.width,
+ "height": s.height,
+ "metadata": dict(s.metadata) if s.metadata else {},
+ }
+ for s in input.snapshots
+ ]
+ _added, uploads = _register_snapshots(run, repo, snapshots)
+ _update_run_counts(run, using=WRITER_DB)
+
+ transaction.on_commit(
+ lambda: ci_status._post_commit_status(run, repo, "pending", "Visual review in progress"), using=WRITER_DB
+ )
+
+ return run, uploads
+
+
+def _register_snapshots(
+ run: Run,
+ repo: Repo,
+ snapshots: list[dict],
+) -> tuple[int, list[dict]]:
+ """Store snapshot rows and generate upload URLs.
+
+ Stores raw identifier + hash pairs. Classification (CHANGED/NEW/UNCHANGED/REMOVED)
+ happens at complete_run time when the baseline is fetched once.
+ Idempotent per (run, identifier) via unique constraint — safe for retries.
+ """
+ repo_id = repo.id
+ all_hashes: set[str] = set()
+ added_count = 0
+
+ for snap in snapshots:
+ identifier = snap["identifier"]
+ current_hash = snap["content_hash"]
+ all_hashes.add(current_hash)
+
+ _snapshot, created = RunSnapshot.objects.get_or_create(
+ run=run,
+ team_id=repo.team_id,
+ identifier=identifier,
+ defaults={
+ "current_hash": current_hash,
+ "baseline_hash": "",
+ "result": SnapshotResult.NEW, # Provisional — reclassified at complete time
+ "current_width": snap.get("width"),
+ "current_height": snap.get("height"),
+ "metadata": snap.get("metadata") or {},
+ },
+ )
+ if created:
+ added_count += 1
+
+ # Generate upload URLs for missing artifacts
+ missing_hashes = artifact_store.find_missing_hashes(repo_id, list(all_hashes))
+ storage = ArtifactStorage(str(repo_id))
+
+ uploads = []
+ for content_hash in missing_hashes:
+ upload_data = storage.get_presigned_upload_url(content_hash)
+ if upload_data:
+ uploads.append(
+ {
+ "content_hash": content_hash,
+ "url": upload_data["url"],
+ "fields": upload_data["fields"],
+ }
+ )
+
+ return added_count, uploads
+
+
+def _update_run_counts(run: Run, using: str | None = None) -> None:
+ """Recalculate result counts from RunSnapshot rows."""
+ db_alias = using or WRITER_DB
+ counts = RunSnapshot.objects.using(db_alias).filter(run_id=run.id).values("result").annotate(n=Count("id"))
+ by_result = {row["result"]: row["n"] for row in counts}
+
+ run.changed_count = by_result.get(SnapshotResult.CHANGED, 0)
+ run.new_count = by_result.get(SnapshotResult.NEW, 0)
+ run.removed_count = by_result.get(SnapshotResult.REMOVED, 0)
+ run.save(using=db_alias, update_fields=["changed_count", "new_count", "removed_count"])
+
+
+def add_snapshots_to_run(
+ run_id: UUID,
+ team_id: int,
+ snapshots: list[dict],
+ baseline_hashes: dict[str, str] | None = None,
+ unchanged_count: int = 0,
+) -> tuple[int, list[dict]]:
+ """Add a batch of snapshots to an existing run (shard-based flow).
+
+ Returns (added_count, upload_targets). Idempotent — safe for retries.
+ baseline_hashes is deprecated — backend fetches from GitHub.
+ """
+ run = run_queries.get_run(run_id, team_id=team_id)
+
+ if run.status != RunStatus.PENDING:
+ raise ValueError(f"Can only add snapshots to pending runs (current status: {run.status})")
+
+ repo = run.repo
+
+ return _add_snapshots_inner(run, run_id, team_id, repo, snapshots)
+
+
[email protected](using=WRITER_DB)
+def _add_snapshots_inner(run, run_id, team_id, repo, snapshots):
+ added, uploads = _register_snapshots(run, repo, snapshots)
+
+ # Atomically increment total (safe for concurrent shards)
+ Run.objects.using(WRITER_DB).filter(id=run_id, team_id=team_id).update(total_snapshots=F("total_snapshots") + added)
+ _update_run_counts(run, using=WRITER_DB)
+
+ return added, uploads
+
+
+def mark_run_processing(run_id: UUID) -> Run:
+ run = run_queries.get_run(run_id)
+ run.status = RunStatus.PROCESSING
+ run.save(update_fields=["status"])
+ return run
+
+
+def complete_run(run_id: UUID) -> Run:
+ """
+ Complete a run: detect removals, classify snapshots, hand off to the diff task.
+
+ 1. Fetches baseline from GitHub, diffs against RunSnapshot rows to find removed
+ 2. Creates REMOVED RunSnapshot rows
+ 3. Classifies snapshots and updates run counts
+ 4. Either verifies uploads + finishes synchronously (no-change fast path) or
+ enqueues process_run_diffs which verifies + diffs + finishes
+
+ Idempotent: returns immediately if already processing or completed.
+ """
+ run = run_queries.get_run(run_id)
+ if run.status in (RunStatus.COMPLETED, RunStatus.PROCESSING):
+ return run
+
+ # Transition to PROCESSING early so late add_snapshots calls are rejected.
+ # Atomic update with condition prevents race with concurrent complete calls.
+ updated = Run.objects.filter(id=run_id, team_id=run.repo.team_id, status=RunStatus.PENDING).update(
+ status=RunStatus.PROCESSING
+ )
+ if not updated:
+ # Another complete_run got here first, or status changed
+ return run_queries.get_run(run_id)
+
+ repo = run.repo
+
+ # 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 = baselines._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 resets
+ Run.objects.filter(id=run_id).update(status=RunStatus.PENDING)
+ raise
+ if healed_count:
+ run.metadata["baseline_healed_from_merge_base"] = healed_count
+ run.save(using=WRITER_DB, update_fields=["metadata"])
+
+ # Pre-load tolerated hashes scoped to this run's identifiers and baseline hashes
+ run_identifiers = set(run.snapshots.using(WRITER_DB).values_list("identifier", flat=True))
+ 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
+
+ # is_partial is client-supplied and only suppresses removed-baseline
+ # detection. Never honor it on the default branch (authoritative full
+ # baseline), so a token can't hide deleted snapshots from the gate. Persist
+ # the correction so every downstream reader (status posting, UI) sees the
+ # effective value rather than the raw client claim.
+ #
+ # On PR branches honoring the client is deliberate, but a partial run must
+ # never satisfy the gating status context: _post_commit_status routes it to
+ # a separate non-gating "(partial)" context (see there). Branch protection
+ # keys off context + state, not the human-facing description, so a separate
+ # context is what actually keeps a one-flag subset run from turning the gate
+ # green — the description annotation alone does not.
+ if run.is_partial and baselines._run_is_on_default_branch(repo, run.branch):
+ logger.warning(
+ "visual_review.is_partial_ignored_on_default_branch",
+ run_id=str(run.id),
+ branch=run.branch,
+ )
+ run.is_partial = False
+ run.save(using=WRITER_DB, update_fields=["is_partial"])
+
+ classifier = SnapshotClassifier(run, baseline, tolerated_lookup, is_partial=run.is_partial)
+ classifier.classify()
+
+ # Update total and counts from actual RunSnapshot rows
+ run.total_snapshots = run.snapshots.using(WRITER_DB).count()
+ run.save(using=WRITER_DB, update_fields=["total_snapshots"])
+ _update_run_counts(run, using=WRITER_DB)
+
+ run = run_queries.get_run(run_id)
+
+ # No-changes fast path: verify any pending uploads synchronously, then
+ # finish. Skipping verify here would silently drop uploads whenever an
+ # Artifact row is missing for a hash that the baseline still points at
+ # (e.g. DB cleanup removed the row but the GitHub-side baseline file
+ # wasn't updated). The CLI re-uploads via find_missing_hashes, the
+ # snapshot classifies as UNCHANGED, and the bytes never get checked or
+ # recorded — leaving every future run requesting the same upload while
+ # CI posts green.
+ if run.changed_count == 0 and run.new_count == 0:
+ from ..tasks.tasks import emit_run_processing_metrics # noqa: PLC0415 — avoids the logic/tasks circular import
+
+ try:
+ uploads.verify_uploads_and_create_artifacts(run_id)
+ except errors.HashIntegrityError as e:
+ logger.warning("visual_review.hash_integrity_failed", run_id=str(run_id), error=str(e))
+ finish_processing(run_id, error_message=str(e))
+ emit_run_processing_metrics.delay(run.team_id, str(run_id), "hash_integrity_failed", 0)
+ return run_queries.get_run(run_id)
+ finish_processing(run_id)
+ emit_run_processing_metrics.delay(run.team_id, str(run_id), "completed", 0)
+ return run_queries.get_run(run_id)
+
+ mark_run_processing(run_id)
+ from ..tasks.tasks import process_run_diffs
+
+ process_run_diffs.delay(run.team_id, str(run_id))
+ return run_queries.get_run(run_id)
+
+
+def finish_processing(run_id: UUID, error_message: str = "") -> Run:
+ run = run_queries.get_run_with_snapshots(run_id)
+
+ run.status = RunStatus.FAILED if error_message else RunStatus.COMPLETED
+ run.error_message = error_message
+ run.completed_at = timezone.now()
+ run.save(update_fields=["status", "error_message", "completed_at"])
+
+ gating._update_counts_and_post_status(run)
+
+ return run
+
+
+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
+ comparison (changed / new / removed vs. unchanged / tolerated). That's the
+ signal to tell a snapshot-determinism regression — where the changed rate
+ climbs because images stop being byte-stable, so the content-hash dedup and
+ tolerance cache stop absorbing work — apart from plain run-volume growth.
+ Where the time goes is captured separately as OTel spans in the task.
+
+ Best-effort: instrumentation must never fail or slow the task, so every
+ error is swallowed — including so it can't mask a real exception when
+ called from the task's ``finally``.
+ """
+ try:
+ try:
+ run = Run.objects.using(WRITER_DB).select_related("repo").get(id=run_id)
+ except Run.DoesNotExist:
+ return
+
+ properties = {
+ "run_id": str(run.id),
+ "run_type": run.run_type,
+ "outcome": outcome,
+ "status": run.status,
+ "repo": run.repo.repo_full_name,
+ "branch": run.branch,
+ "pr_number": run.pr_number,
+ "team_id": run.team_id,
+ "is_partial": run.is_partial,
+ "total_snapshots": run.total_snapshots,
+ "changed_count": run.changed_count,
+ "new_count": run.new_count,
+ "removed_count": run.removed_count,
+ "tolerated_match_count": run.tolerated_match_count,
+ "diffed_count": diffed_count,
+ "reviewable_count": run.changed_count + run.new_count + run.removed_count,
+ }
+
+ with ph_scoped_capture() as capture_ph_event:
+ capture_ph_event(
+ 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)
+
+
[email protected](using=WRITER_DB)
+def recompute_run(run_id: UUID, team_id: int | None = None) -> dict:
+ """Re-evaluate quarantine and counts, update commit status, and optionally rerun the CI job.
+
+ Returns a dict with counts_changed, ci_rerun_triggered, and ci_rerun_error.
+ """
+ run = run_queries._get_run_for_update(run_id, team_id=team_id)
+
+ if run.status != RunStatus.COMPLETED:
+ raise ValueError(f"Can only recompute completed runs (current status: {run.status})")
+
+ if run.approved:
+ raise ValueError("Run is already approved")
+
+ old_counts = (run.changed_count, run.new_count, run.removed_count)
+ unresolved = gating._update_counts_and_post_status(run)
+ new_counts = (run.changed_count, run.new_count, run.removed_count)
+ counts_changed = old_counts != new_counts
+
+ ci_rerun_triggered = False
+ ci_rerun_error: str | None = None
+
+ check_run_id = (run.metadata or {}).get("github_check_run_id")
+
+ if not check_run_id:
+ ci_rerun_error = "CI job ID not available (set JOB_CHECK_RUN_ID=${{ job.check_run_id }} in workflow)"
+ else:
+ # Stored as a string, but coerce defensively — `_rerun_github_job` calls `.isdigit()`.
+ ci_rerun_triggered, ci_rerun_error = ci_status._rerun_github_job(run, str(check_run_id))
+
+ return {
+ "counts_changed": counts_changed,
+ "unresolved": unresolved,
+ "ci_rerun_triggered": ci_rerun_triggered,
+ "ci_rerun_error": ci_rerun_error,
+ }
diff --git a/products/visual_review/backend/logic/snapshot_diffs.py b/products/visual_review/backend/logic/snapshot_diffs.py
new file mode 100644
index 000000000000..3b7a94986d71
--- /dev/null
+++ b/products/visual_review/backend/logic/snapshot_diffs.py
@@ -0,0 +1,52 @@
+"""Attaching computed diff results to a snapshot."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from ..diff_metadata import DiffMetadata
+from ..facade.enums import ChangeKind, SnapshotResult
+from ..models import Artifact, RunSnapshot
+
+
+def update_snapshot_diff(
+ snapshot_id: UUID,
+ diff_artifact: Artifact,
+ diff_percentage: float,
+ diff_pixel_count: int,
+ ssim_score: float,
+ change_kind: ChangeKind,
+ diff_metadata: DiffMetadata,
+ team_id: int | None = None,
+) -> RunSnapshot:
+ qs = RunSnapshot.objects.select_related("run")
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ snapshot = qs.get(id=snapshot_id)
+ if diff_artifact.repo_id != snapshot.run.repo_id:
+ raise ValueError(
+ f"Cross-repo artifact reference: artifact repo {diff_artifact.repo_id} "
+ f"!= snapshot repo {snapshot.run.repo_id}"
+ )
+ if snapshot.result != SnapshotResult.CHANGED:
+ raise ValueError(f"Cannot attach diff to snapshot with result={snapshot.result}, expected 'changed'")
+ snapshot.diff_artifact = diff_artifact
+ snapshot.diff_percentage = diff_percentage
+ snapshot.diff_pixel_count = diff_pixel_count
+ snapshot.ssim_score = ssim_score
+ snapshot.change_kind = change_kind.value
+ # The Pydantic dump is the only legal write path into this column; reads
+ # go through DiffMetadata.model_validate. Storage is JSONB; the schema
+ # lives in diff_metadata.py.
+ snapshot.diff_metadata = diff_metadata.model_dump(mode="json")
+ snapshot.save(
+ update_fields=[
+ "diff_artifact",
+ "diff_percentage",
+ "diff_pixel_count",
+ "ssim_score",
+ "change_kind",
+ "diff_metadata",
+ ]
+ )
+ return snapshot
diff --git a/products/visual_review/backend/logic/thumbnails.py b/products/visual_review/backend/logic/thumbnails.py
new file mode 100644
index 000000000000..5bf8e813b985
--- /dev/null
+++ b/products/visual_review/backend/logic/thumbnails.py
@@ -0,0 +1,40 @@
+"""Thumbnail lookup and reads for a snapshot identifier."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from ..models import RunSnapshot
+from ..storage import ArtifactStorage
+
+
+def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str) -> str | None:
+ """Look up the thumbnail content hash for a snapshot identifier.
+
+ Finds the most recent artifact with a thumbnail for this identifier
+ across all runs. Returns the thumbnail's content_hash or None.
+ """
+ snapshot = (
+ RunSnapshot.objects.filter(
+ run__repo_id=repo_id,
+ identifier=identifier,
+ current_artifact__thumbnail__isnull=False,
+ )
+ .select_related("current_artifact__thumbnail")
+ .order_by("-run__created_at")
+ .first()
+ )
+
+ if snapshot is None:
+ return None
+
+ artifact = snapshot.current_artifact
+ if artifact is None or artifact.thumbnail is None:
+ return None
+
+ return artifact.thumbnail.content_hash
+
+
+def read_thumbnail_bytes(repo_id: UUID, content_hash: str) -> bytes | None:
+ storage = ArtifactStorage(str(repo_id))
+ return storage.read(content_hash)
diff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.py
new file mode 100644
index 000000000000..0f8ed54ed94e
--- /dev/null
+++ b/products/visual_review/backend/logic/toleration.py
@@ -0,0 +1,73 @@
+"""Tolerated hashes: accepting a known alternate rendering as not-a-regression."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from ..db import WRITER_DB
+from ..facade.enums import ReviewState, SnapshotResult, ToleratedReason
+from ..models import Run, RunSnapshot, ToleratedHash
+from . import errors, run_queries
+
+
[email protected](using=WRITER_DB)
+def mark_snapshot_as_tolerated(run_id: UUID, snapshot_id: UUID, user_id: int, team_id: int) -> RunSnapshot:
+ """Mark a changed snapshot as a known tolerated alternate (human decision).
+
+ Creates a ToleratedHash entry tied to the current baseline, reclassifies the
+ snapshot as UNCHANGED, and recalculates run summary counts.
+ """
+ run = run_queries._get_run_for_update(run_id, team_id=team_id)
+ try:
+ snapshot = RunSnapshot.objects.get(id=snapshot_id, run=run, team_id=team_id)
+ except RunSnapshot.DoesNotExist:
+ raise errors.RunNotFoundError(f"Snapshot {snapshot_id} not found in run {run_id}")
+
+ if snapshot.result != SnapshotResult.CHANGED:
+ raise ValueError(f"Can only mark CHANGED snapshots as tolerated (current: {snapshot.result})")
+
+ if not snapshot.current_hash:
+ raise ValueError("Snapshot has no current hash")
+
+ # Explicit team_id in the lookup (not just defaults) so the IDOR audit
+ # rule sees the scope; ProductTeamManager also auto-filters by canonical
+ # team — both belt and suspenders.
+ tolerated, _ = ToleratedHash.objects.get_or_create(
+ team_id=team_id,
+ repo_id=run.repo_id,
+ identifier=snapshot.identifier,
+ baseline_hash=snapshot.baseline_hash,
+ alternate_hash=snapshot.current_hash,
+ defaults={
+ "reason": ToleratedReason.HUMAN,
+ "source_run": run,
+ "created_by_id": user_id,
+ "diff_percentage": snapshot.diff_percentage,
+ },
+ )
+
+ # result stays CHANGED — it's the technical truth (hashes differ).
+ # review_state captures the human decision to tolerate.
+ snapshot.review_state = ReviewState.TOLERATED
+ snapshot.reviewed_at = timezone.now()
+ snapshot.reviewed_by_id = user_id
+ snapshot.tolerated_hash_match = tolerated
+ snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "tolerated_hash_match"])
+
+ # Update tolerated_match_count (only human-tolerated, not auto-threshold)
+ tolerated_count = (
+ RunSnapshot.objects.using(WRITER_DB)
+ .filter(run=run, tolerated_hash_match__isnull=False, tolerated_hash_match__reason=ToleratedReason.HUMAN)
+ .count()
+ )
+ Run.objects.using(WRITER_DB).filter(id=run.id).update(tolerated_match_count=tolerated_count)
+
+ return snapshot
+
+
+def get_tolerated_hashes_for_identifier(repo_id: UUID, identifier: str) -> list[ToleratedHash]:
+ """List all tolerated hashes for a snapshot identifier, most recent first."""
+ return list(ToleratedHash.objects.filter(repo_id=repo_id, identifier=identifier).order_by("-created_at"))
diff --git a/products/visual_review/backend/logic/uploads.py b/products/visual_review/backend/logic/uploads.py
new file mode 100644
index 000000000000..035302476d32
--- /dev/null
+++ b/products/visual_review/backend/logic/uploads.py
@@ -0,0 +1,143 @@
+"""Upload verification: server-side hashing of uploaded PNGs before they become artifacts."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+import structlog
+
+from ..models import Artifact
+from ..storage import ArtifactStorage
+from . import artifact_store, errors, run_queries
+
+logger = structlog.get_logger(__name__)
+
+
+def verify_uploads_and_create_artifacts(run_id: UUID) -> int:
+ """
+ Verify S3 uploads, check hash integrity, and create Artifact records.
+
+ For each new upload (no existing Artifact), reads the PNG bytes from S3,
+ decodes to sRGB RGBA, and computes the BLAKE3 hash. The CLI-claimed hash
+ is used only as a lookup key into S3 — once verified, it's discarded and
+ the server-computed hash is used everywhere downstream. This ensures the
+ CLI cannot (accidentally or maliciously) associate wrong hashes with image
+ content.
+
+ Verification runs in two passes so a late failure can't leave a partial
+ set of Artifact rows behind: pass 1 reads + hashes all uploads, pass 2
+ creates Artifact rows from the verified results.
+
+ Raises HashIntegrityError if any upload fails verification.
+
+ Returns number of artifacts created.
+ """
+ from ..hashing import ImageTooLargeError, hash_image
+
+ run = run_queries.get_run(run_id)
+ repo_id = run.repo_id
+ storage = 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[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 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 artifact_store._iter_batches(expected_hashes, artifact_store.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, int, dict[str, int | None]]] = []
+ for claimed_hash, metadata in expected_hashes.items():
+ if claimed_hash in existing_hashes:
+ continue
+
+ png_bytes = storage.read(claimed_hash)
+ if png_bytes is None:
+ # Race: complete_run fired before the CLI's S3 upload landed, or
+ # the upload was never made. Log loudly so we can spot it instead
+ # of silently dropping the artifact and forcing the next run to
+ # re-upload the same content.
+ logger.warning(
+ "visual_review.upload_missing_in_s3",
+ run_id=str(run_id),
+ claimed_hash=claimed_hash,
+ )
+ continue
+ if len(png_bytes) == 0:
+ raise errors.HashIntegrityError(f"Upload rejected: empty file for hash {claimed_hash[:16]}…")
+
+ try:
+ actual_hash = hash_image(png_bytes)
+ except ImageTooLargeError as e:
+ logger.exception(
+ "visual_review.hash_image_too_large",
+ run_id=str(run_id),
+ claimed_hash=claimed_hash,
+ error=str(e),
+ )
+ raise errors.HashIntegrityError(f"Upload rejected: {e}") from e
+ except Exception as e:
+ # Pillow can raise UnidentifiedImageError, DecompressionBombError,
+ # OSError, etc. Funnel everything into HashIntegrityError so the
+ # task handler routes it through the structured-failure path
+ # instead of celery's retry loop.
+ logger.exception(
+ "visual_review.hash_image_failed",
+ run_id=str(run_id),
+ claimed_hash=claimed_hash,
+ error=str(e),
+ error_type=type(e).__name__,
+ )
+ raise errors.HashIntegrityError(
+ f"Upload integrity check failed: could not decode image for hash {claimed_hash[:16]}…"
+ ) from e
+
+ if actual_hash != claimed_hash:
+ logger.error(
+ "visual_review.hash_integrity_failure",
+ run_id=str(run_id),
+ claimed_hash=claimed_hash,
+ actual_hash=actual_hash,
+ )
+ raise errors.HashIntegrityError(
+ f"Upload integrity check failed: claimed {claimed_hash[:16]}… but image hashes to {actual_hash[:16]}…"
+ )
+
+ 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.
+ artifacts = [
+ Artifact(
+ repo_id=repo_id,
+ content_hash=actual_hash,
+ storage_path=storage._key(actual_hash),
+ width=metadata.get("width"),
+ height=metadata.get("height"),
+ 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_store.ARTIFACT_HASH_BATCH_SIZE, ignore_conflicts=True)
+ artifact_store.link_artifacts_to_snapshots(repo_id, set(expected_hashes), run_id=run_id)
+
+ return len(artifacts)
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 26272611e6dd..463ed3865741 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -17,7 +17,7 @@ from opentelemetry.trace import Status, StatusCode
from posthog.models.scoping import with_team_scope
-from ..logic import HashIntegrityError
+from ..logic.errors import HashIntegrityError
logger = structlog.get_logger(__name__)
TRACER = trace.get_tracer(__name__)
@@ -29,9 +29,9 @@ TRACER = trace.get_tracer(__name__)
)
@with_team_scope()
def emit_run_processing_metrics(team_id: int, run_id: str, outcome: str, diffed_count: int) -> None:
- from .. import logic # noqa: PLC0415 — avoids the logic/tasks circular import
+ from ..logic import runs # noqa: PLC0415 — avoids the logic/tasks circular import
- logic.capture_run_processing_metrics(UUID(run_id), outcome=outcome, diffed_count=diffed_count)
+ runs.capture_run_processing_metrics(UUID(run_id), outcome=outcome, diffed_count=diffed_count)
@shared_task(
@@ -53,8 +53,8 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
"""
from posthog.egress.github.transport import GitHubRateLimitError
- from .. import logic
from ..diffing import count_processed_diffs, process_diffs
+ from ..logic import runs, uploads
run_uuid = UUID(run_id)
outcome = "completed"
@@ -70,18 +70,18 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
logger.info("visual_review.diff_processing_started", run_id=run_id, team_id=team_id)
with TRACER.start_as_current_span("visual_review.verify_uploads"):
- logic.verify_uploads_and_create_artifacts(run_uuid)
+ uploads.verify_uploads_and_create_artifacts(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)
+ runs.finish_processing(run_uuid)
logger.info("visual_review.diff_processing_completed", run_id=run_id, team_id=team_id)
except HashIntegrityError as e:
outcome = "hash_integrity_failed"
logger.warning("visual_review.hash_integrity_failed", run_id=run_id, error=str(e))
- logic.finish_processing(run_uuid, error_message=str(e))
+ runs.finish_processing(run_uuid, error_message=str(e))
except GitHubRateLimitError as e:
outcome = "rate_limited"
logger.warning(
@@ -92,7 +92,7 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
)
if self.max_retries is not None and self.request.retries >= self.max_retries:
outcome = "rate_limit_exhausted"
- logic.finish_processing(run_uuid, error_message="GitHub API rate limit exceeded after retries")
+ runs.finish_processing(run_uuid, error_message="GitHub API rate limit exceeded after retries")
else:
retrying = True
countdown = e.retry_after or 60
@@ -102,7 +102,7 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
span.set_status(Status(StatusCode.ERROR, str(e)))
span.record_exception(e)
logger.exception("visual_review.diff_processing_failed", run_id=run_id, team_id=team_id, error=str(e))
- logic.finish_processing(run_uuid, error_message=str(e))
+ runs.finish_processing(run_uuid, error_message=str(e))
raise
finally:
span.set_attribute("visual_review.outcome", outcome)
@@ -113,7 +113,7 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
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)
+ runs.capture_run_processing_metrics(run_uuid, outcome=outcome, diffed_count=cumulative_diffed_count)
@shared_task(
@@ -134,12 +134,12 @@ def post_approval_comment(self, team_id: int, run_id: str, add_images: bool = Fa
"""
from posthog.egress.github.transport import GitHubRateLimitError
- from .. import logic
+ from ..logic import comments
run_uuid = UUID(run_id)
try:
- logic.post_approval_comment_for_run(run_uuid, team_id=team_id, add_images=add_images)
+ comments.post_approval_comment_for_run(run_uuid, team_id=team_id, add_images=add_images)
except GitHubRateLimitError as e:
logger.warning(
"visual_review.approval_comment_rate_limited",
diff --git a/products/visual_review/backend/tests/logic/__init__.py b/products/visual_review/backend/tests/logic/__init__.py
new file mode 100644
index 000000000000..bfabbd5acf6e
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/__init__.py
@@ -0,0 +1 @@
+"""Unit tests for the visual_review logic package, one module per logic module."""
diff --git a/products/visual_review/backend/tests/logic/test_approvals.py b/products/visual_review/backend/tests/logic/test_approvals.py
new file mode 100644
index 000000000000..f9e2521f95fd
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_approvals.py
@@ -0,0 +1,199 @@
+"""Unit tests for logic/approvals.py — Approving snapshots and finalizing a run."""
+
+import pytest
+
+from django.db import transaction
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import ReviewState, RunType, SnapshotResult
+from products.visual_review.backend.logic import (
+ approvals,
+ artifact_store,
+ ci_status,
+ errors,
+ repos,
+ run_queries,
+ runs,
+ toleration,
+)
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestApproveRun:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
+
+ def test_approve_run(self, repo, user, mocker):
+ current_artifact, _ = artifact_store.get_or_create_artifact(
+ repo_id=repo.id, content_hash="new_hash", storage_path="p/new"
+ )
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
+ baseline_hashes={"Button": "old_hash"},
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Classification happens at complete_run time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"Button": "old_hash"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ updated = approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)
+
+ assert updated.approved is True
+ assert updated.review_decision == "human_approved"
+ assert updated.approved_at is not None
+ assert updated.approved_by_id == user.id
+
+ # Result should NOT be mutated - approval is recorded separately
+ snapshot = updated.snapshots.first()
+ assert snapshot is not None
+ assert snapshot.result == SnapshotResult.CHANGED # Result preserved
+ assert snapshot.approved_hash == "new_hash" # Approval recorded
+ assert snapshot.reviewed_at is not None
+ assert snapshot.reviewed_by_id == user.id
+
+ def _completed_two_change_run(self, repo, mocker):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="ha", storage_path="p/a")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="hb", storage_path="p/b")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="A", content_hash="ha"),
+ SnapshotManifestItem(identifier="B", content_hash="hb"),
+ ],
+ baseline_hashes={"A": "olda", "B": "oldb"},
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"A": "olda", "B": "oldb"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+ return run
+
+ def test_finalize_requires_full_resolution(self, repo, user, mocker):
+ # Finalize is all-or-nothing: it refuses while any changed/new snapshot is unreviewed.
+ run = self._completed_two_change_run(repo, mocker)
+
+ approvals.approve_snapshots(
+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "A", "new_hash": "ha"}]
+ )
+ with pytest.raises(errors.RunNotFullyResolvedError, match="B"):
+ approvals.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)
+
+ # Resolving the rest lets it finalize.
+ approvals.approve_snapshots(
+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "B", "new_hash": "hb"}]
+ )
+ updated = approvals.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)
+ assert updated.approved is True
+
+ def test_finalize_leaves_tolerated_snapshot_alone(self, repo, user, mocker):
+ # A tolerated snapshot resolves the run without being approved or committed.
+ run = self._completed_two_change_run(repo, mocker)
+ snap_b = run.snapshots.get(identifier="B")
+ toleration.mark_snapshot_as_tolerated(run.id, snap_b.id, user.id, repo.team_id)
+
+ updated = approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ assert updated.approved is True
+ snapshots = {s.identifier: s for s in updated.snapshots.all()}
+ assert snapshots["A"].review_state == ReviewState.APPROVED
+ assert snapshots["B"].review_state == ReviewState.TOLERATED # approve_all did not clobber it
+
+ def test_finalize_is_idempotent_on_approved_run(self, repo, user, mocker):
+ # Re-finalizing an already-finalized run is a no-op — no second commit/status/comment.
+ run = self._completed_two_change_run(repo, mocker)
+ approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
+ approved_at = run_queries.get_run_with_snapshots(run.id).approved_at
+
+ again = approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ assert again.approved is True
+ assert again.approved_at == approved_at # unchanged — the second call did no work
+
+ @pytest.mark.parametrize("add_images", [True, False])
+ def test_finalize_always_comments_and_forwards_add_images(self, repo, user, mocker, add_images):
+ # The PR comment is always dispatched on finalize; add_images_to_comment_on_pr only
+ # controls whether the snapshot images are embedded — forwarded to the task.
+ run = self._completed_two_change_run(repo, mocker)
+ mocker.patch.object(ci_status, "_post_commit_status")
+ mocker.patch.object(transaction, "on_commit", side_effect=lambda fn, *args, **kwargs: fn())
+ delay = mocker.patch("products.visual_review.backend.tasks.tasks.post_approval_comment.delay")
+
+ approvals.finalize_run(
+ run_id=run.id,
+ user_id=user.id,
+ approve_all=True,
+ commit_to_github=True,
+ add_images_to_comment_on_pr=add_images,
+ )
+
+ assert delay.called is True
+ assert delay.call_args.args[2] is add_images
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestApproveSnapshots:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99998, repo_full_name="org/test-snap")
+
+ def test_approve_single_snapshot_db_only(self, repo, user, mocker):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="new_hash", storage_path="p/new")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
+ baseline_hashes={"Button": "old_hash"},
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"Button": "old_hash"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ updated = approvals.approve_snapshots(
+ run_id=run.id,
+ user_id=user.id,
+ approved_snapshots=[{"identifier": "Button", "new_hash": "new_hash"}],
+ )
+
+ snapshot = updated.snapshots.first()
+ assert snapshot is not None
+ assert snapshot.review_state == "approved"
+ assert snapshot.approved_hash == "new_hash"
+
+ # Run-level state should NOT change
+ assert updated.approved is False
+ assert updated.review_decision == "pending"
diff --git a/products/visual_review/backend/tests/logic/test_artifact_store.py b/products/visual_review/backend/tests/logic/test_artifact_store.py
new file mode 100644
index 000000000000..ea508bd31080
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_artifact_store.py
@@ -0,0 +1,78 @@
+"""Unit tests for logic/artifact_store.py — Artifact rows and their stored bytes."""
+
+import pytest
+
+from products.visual_review.backend.logic import artifact_store, repos
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestArtifactOperations:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
+
+ def test_get_or_create_artifact_creates_new(self, repo):
+ artifact, created = artifact_store.get_or_create_artifact(
+ repo_id=repo.id,
+ content_hash="abc123",
+ storage_path="visual_review/abc123",
+ width=100,
+ height=200,
+ size_bytes=5000,
+ )
+
+ assert created is True
+ assert artifact.content_hash == "abc123"
+ assert artifact.width == 100
+ assert artifact.height == 200
+ assert artifact.size_bytes == 5000
+
+ def test_get_or_create_artifact_returns_existing(self, repo):
+ artifact1, created1 = artifact_store.get_or_create_artifact(
+ repo_id=repo.id,
+ content_hash="abc123",
+ storage_path="visual_review/abc123",
+ )
+ artifact2, created2 = artifact_store.get_or_create_artifact(
+ repo_id=repo.id,
+ content_hash="abc123",
+ storage_path="visual_review/abc123",
+ )
+
+ assert created1 is True
+ assert created2 is False
+ assert artifact1.id == artifact2.id
+
+ def test_get_artifact(self, repo):
+ artifact_store.get_or_create_artifact(
+ repo_id=repo.id,
+ content_hash="xyz789",
+ storage_path="visual_review/xyz789",
+ )
+
+ artifact = artifact_store.get_artifact(repo.id, "xyz789")
+
+ assert artifact is not None
+ assert artifact.content_hash == "xyz789"
+
+ def test_get_artifact_not_found(self, repo):
+ artifact = artifact_store.get_artifact(repo.id, "nonexistent")
+
+ assert artifact is None
+
+ def test_find_missing_hashes(self, repo):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="exists1", storage_path="p/exists1")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="exists2", storage_path="p/exists2")
+
+ missing = artifact_store.find_missing_hashes(repo.id, ["exists1", "missing1", "exists2", "missing2"])
+
+ assert set(missing) == {"missing1", "missing2"}
+
+ def test_find_missing_hashes_all_exist(self, repo):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="a", storage_path="p/a")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="b", storage_path="p/b")
+
+ missing = artifact_store.find_missing_hashes(repo.id, ["a", "b"])
+
+ assert missing == []
diff --git a/products/visual_review/backend/tests/logic/test_baselines.py b/products/visual_review/backend/tests/logic/test_baselines.py
new file mode 100644
index 000000000000..e358dc743ed3
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_baselines.py
@@ -0,0 +1,592 @@
+"""Unit tests for logic/baselines.py — Baseline resolution, merge-base healing, and hash verification."""
+
+from datetime import timedelta
+
+import pytest
+
+from django.utils import timezone
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResult
+from products.visual_review.backend.logic import artifact_store, baselines, errors, repos, runs
+from products.visual_review.backend.models import Repo, Run, RunSnapshot
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRunIsOnDefaultBranch:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=1234, repo_full_name="org/test-repo")
+
+ def _mock_github(self, mocker, default_branch="master"):
+ mock_github = mocker.MagicMock()
+ mock_github.access_token_expired.return_value = False
+ mocker.patch(
+ "products.visual_review.backend.logic.github_api.get_github_integration_for_repo", return_value=mock_github
+ )
+ mocker.patch("products.visual_review.backend.logic.github_api._get_default_branch", return_value=default_branch)
+
+ def test_true_when_branch_matches_default(self, repo, mocker):
+ self._mock_github(mocker, default_branch="main")
+ assert baselines._run_is_on_default_branch(repo, "main") is True
+
+ def test_false_when_branch_differs(self, repo, mocker):
+ self._mock_github(mocker, default_branch="main")
+ assert baselines._run_is_on_default_branch(repo, "feature-x") is False
+
+ def test_false_when_no_github_integration(self, repo, mocker):
+ mocker.patch(
+ "products.visual_review.backend.logic.github_api.get_github_integration_for_repo",
+ side_effect=errors.GitHubIntegrationNotFoundError("none"),
+ )
+ assert baselines._run_is_on_default_branch(repo, "master") is False
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestMergeBaseBaselineHealing:
+ """Tests for _resolve_baselines_with_merge_base healing rebase-corrupted baselines."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.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",
+ 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"}
+ mock_github.access_token_expired.return_value = False
+ mocker.patch(
+ "products.visual_review.backend.logic.github_api.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:
+ baselines = merge_base_baseline if merge_base_baseline is not None else branch_baseline
+ 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.github_api._fetch_baseline_file", side_effect=fake_fetch)
+ mocker.patch("products.visual_review.backend.logic.github_api._get_merge_base_sha", side_effect=fake_merge_base)
+ mocker.patch("products.visual_review.backend.logic.github_api._get_default_branch", return_value=default_branch)
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._verify_baseline_hashes",
+ side_effect=lambda repo, hashes: hashes,
+ )
+ return mock_github
+
+ def test_no_healing_when_baselines_match(self, repo, mocker):
+ baseline = {"A": "h1", "B": "h2"}
+ self._mock_github(mocker, branch_baseline=baseline, merge_base_baseline=baseline)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged == baseline
+ assert healed == 0
+
+ def test_heals_entries_missing_from_branch(self, repo, mocker):
+ branch_baseline = {"A": "h1"}
+ merge_base_baseline = {"A": "h1", "B": "h2", "C": "h3"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged == {"A": "h1", "B": "h2", "C": "h3"}
+ assert healed == 2
+
+ def test_branch_wins_on_conflict(self, repo, mocker):
+ branch_baseline = {"A": "branch_hash"}
+ merge_base_baseline = {"A": "master_hash", "B": "h2"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged["A"] == "branch_hash"
+ assert merged["B"] == "h2"
+ assert healed == 1
+
+ def test_branch_approvals_preserved(self, repo, mocker):
+ branch_baseline = {"A": "h1", "NewStory": "new_hash"}
+ merge_base_baseline = {"A": "h1"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert "NewStory" in merged
+ assert merged["NewStory"] == "new_hash"
+ assert healed == 0
+
+ def test_skips_merge_base_for_default_branch(self, repo, mocker):
+ baseline = {"A": "h1"}
+ self._mock_github(mocker, branch_baseline=baseline, default_branch="master")
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "master")
+
+ assert merged == baseline
+ assert 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 = baselines._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 = baselines._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)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged == branch_baseline
+ assert healed == 0
+
+ def test_falls_back_when_merge_base_file_fetch_raises(self, repo, mocker):
+ branch_baseline = {"A": "h1"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline={"A": "h1", "B": "h2"})
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_at_ref",
+ side_effect=[branch_baseline, Exception("GitHub 500")],
+ )
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged == branch_baseline
+ assert healed == 0
+
+ def test_first_run_both_baselines_empty(self, repo, mocker):
+ self._mock_github(mocker, branch_baseline={}, merge_base_baseline={})
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert merged == {}
+ assert healed == 0
+
+ def test_heals_rebase_scenario_end_to_end(self, repo, mocker):
+ """Simulates Paul's bug: rebase replayed bot commit, dropping 8 entries."""
+ branch_baseline = {"story1": "h1", "story2": "h2"}
+ merge_base_baseline = {
+ "story1": "h1",
+ "story2": "h2",
+ "lost1": "h3",
+ "lost2": "h4",
+ "lost3": "h5",
+ "lost4": "h6",
+ "lost5": "h7",
+ "lost6": "h8",
+ "lost7": "h9",
+ "lost8": "h10",
+ }
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
+
+ assert len(merged) == 10
+ assert healed == 8
+ assert all(f"lost{i}" in merged for i in range(1, 9))
+
+ def test_healing_integrates_with_complete_run(self, repo, mocker):
+ """Healed entries classify as unchanged when hashes match."""
+ branch_baseline = {"existing": "h1"}
+ merge_base_baseline = {"existing": "h1", "healed": "h2"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ 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")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="my-branch",
+ pr_number=1,
+ snapshots=[
+ SnapshotManifestItem(identifier="existing", content_hash="h1"),
+ SnapshotManifestItem(identifier="healed", content_hash="h2"),
+ ],
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+
+ snapshots = {s.identifier: s for s in run.snapshots.all()}
+ assert snapshots["existing"].result == SnapshotResult.UNCHANGED
+ assert snapshots["healed"].result == SnapshotResult.UNCHANGED
+
+ 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},
+ )
+
+ 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")
+ artifact_store.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, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="commit_a_sha",
+ branch="master",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="story1", content_hash="h1"),
+ SnapshotManifestItem(identifier="story2", content_hash="h2"),
+ SnapshotManifestItem(identifier="story3", content_hash="h3"),
+ ],
+ ),
+ team_id=repo.team_id,
+ )
+
+ runs.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] = {}
+ merge_base_baseline = {"flaky": "master_hash"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="master_hash", storage_path="p/master")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="branch_hash", storage_path="p/branch")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="my-branch",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="flaky", content_hash="branch_hash")],
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+
+ snapshot = run.snapshots.get(identifier="flaky")
+ assert snapshot.result == SnapshotResult.CHANGED
+ assert snapshot.baseline_hash == "master_hash"
+
+ @pytest.mark.parametrize(
+ "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", "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",
+ ],
+ )
+ def test_tombstone_excludes_only_approved_removals_on_branch(
+ 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,
+ 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,
+ )
+ RunSnapshot.objects.create(
+ run=prior_run,
+ team_id=team.id,
+ identifier="candidate",
+ baseline_hash="h1",
+ current_hash="",
+ result=SnapshotResult.REMOVED,
+ review_state=prior_review_state,
+ )
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, run_branch)
+
+ if expect_tombstoned:
+ assert merged == {}
+ assert healed == 0
+ else:
+ assert merged == merge_base_baseline
+ assert healed == 1
+
+ def test_tombstone_cleared_by_later_re_addition(self, repo, team, mocker):
+ """Remove→approve→restore→approve: the re-addition clears the tombstone."""
+ branch_baseline: dict[str, str] = {}
+ merge_base_baseline = {"story-x": "h1"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ # Run 1: story-x removed and approved
+ run1 = Run.objects.create(
+ team_id=team.id,
+ repo=repo,
+ run_type=RunType.STORYBOOK,
+ branch="my-branch",
+ commit_sha="sha1",
+ status=RunStatus.COMPLETED,
+ approved=True,
+ created_at=timezone.now() - timedelta(hours=2),
+ )
+ RunSnapshot.objects.create(
+ run=run1,
+ team_id=team.id,
+ identifier="story-x",
+ baseline_hash="h1",
+ current_hash="",
+ result=SnapshotResult.REMOVED,
+ review_state=ReviewState.APPROVED,
+ )
+
+ # Supersede run1 (as create_run would)
+ run1.superseded_by = run1
+ run1.save(update_fields=["superseded_by"])
+
+ # Run 2: story-x re-added and approved as NEW
+ run2 = Run.objects.create(
+ team_id=team.id,
+ repo=repo,
+ run_type=RunType.STORYBOOK,
+ branch="my-branch",
+ commit_sha="sha2",
+ status=RunStatus.COMPLETED,
+ approved=True,
+ created_at=timezone.now() - timedelta(hours=1),
+ )
+ RunSnapshot.objects.create(
+ run=run2,
+ team_id=team.id,
+ identifier="story-x",
+ baseline_hash="",
+ current_hash="h1",
+ result=SnapshotResult.NEW,
+ review_state=ReviewState.APPROVED,
+ )
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, "my-branch")
+
+ # Latest approved outcome is NEW, not REMOVED — tombstone cleared, healing works
+ assert "story-x" in merged
+ assert healed == 1
+
+ def test_tombstone_persists_without_later_approval(self, repo, team, mocker):
+ """Remove→approve: tombstone stays until a later approval overrides it."""
+ branch_baseline: dict[str, str] = {}
+ merge_base_baseline = {"story-x": "h1"}
+ self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
+
+ run1 = Run.objects.create(
+ team_id=team.id,
+ repo=repo,
+ run_type=RunType.STORYBOOK,
+ branch="my-branch",
+ commit_sha="sha1",
+ status=RunStatus.COMPLETED,
+ approved=True,
+ )
+ RunSnapshot.objects.create(
+ run=run1,
+ team_id=team.id,
+ identifier="story-x",
+ baseline_hash="h1",
+ current_hash="",
+ result=SnapshotResult.REMOVED,
+ review_state=ReviewState.APPROVED,
+ )
+
+ merged, healed = baselines._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, "my-branch")
+
+ assert "story-x" not in merged
+ assert healed == 0
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestVerifyBaselineHashes:
+ """Bootstrap-window guard: unsigned baselines must not be honored."""
+
+ def test_drops_all_entries_when_no_signing_keys(self, team):
+ repo = Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=77777,
+ repo_full_name="org/no-keys",
+ signing_keys={},
+ )
+
+ result = baselines._verify_baseline_hashes(repo, {"snap-a": "v1.k1.deadbeef.fake"})
+
+ assert result == {}
diff --git a/products/visual_review/backend/tests/logic/test_ci_status.py b/products/visual_review/backend/tests/logic/test_ci_status.py
new file mode 100644
index 000000000000..cf9d1851b65b
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_ci_status.py
@@ -0,0 +1,548 @@
+"""Unit tests for logic/ci_status.py — Commit statuses and CI job reruns."""
+
+import pytest
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import RunType
+from products.visual_review.backend.logic import approvals, artifact_store, ci_status, repos, runs
+from products.visual_review.backend.models import Repo, Run
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(transaction=True, databases=PRODUCT_DATABASES)
+class TestCommitStatusChecks:
+ """Test that GitHub commit status checks are posted at state transitions."""
+
+ @pytest.fixture
+ def github_repo(self, team, mock_github_integration):
+ return Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=55555,
+ repo_full_name="test-org/test-repo",
+ baseline_file_paths={"storybook": ".snapshots.yml"},
+ )
+
+ def test_create_run_posts_pending_status(self, github_repo, mock_github_api):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
+ baseline_hashes={},
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ assert len(mock_github_api.status_checks) == 1
+ check = mock_github_api.status_checks[0]
+ assert check["state"] == "pending"
+ assert check["context"] == "PostHog Visual Review / storybook"
+ assert f"/visual_review/runs/{run.id}" in check["target_url"]
+
+ def test_complete_run_posts_success_when_no_changes(self, github_repo, mock_github_api, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
+ baseline_hashes={"snap": "same"},
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"snap": "same"}, 0),
+ )
+ runs.complete_run(run.id)
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert statuses[-1]["description"] == "No visual changes"
+ # A full run posts to the gating context that branch protection evaluates.
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook"
+
+ def test_complete_run_partial_annotates_posted_status(self, github_repo, mock_github_api, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="feature-x",
+ pr_number=7,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
+ baseline_hashes={"snap": "same"},
+ is_partial=True,
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"snap": "same", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic.baselines._run_is_on_default_branch", return_value=False)
+ runs.complete_run(run.id)
+
+ # A partial run suppresses removal detection, so it must never satisfy
+ # the gating status context branch protection evaluates. It posts to a
+ # separate "(partial)" context instead, and the description discloses it.
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert statuses[-1]["description"] == "No visual changes (partial run)"
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (partial)"
+ # The gating context is never posted green by a partial run.
+ gating_context = "PostHog Visual Review / storybook"
+ assert all(s["context"] != gating_context for s in statuses)
+
+ def test_complete_run_posts_comment_when_changes_detected(self, github_repo, mock_github_api, mocker):
+ github_repo.enable_pr_comments = True
+ github_repo.save(update_fields=["enable_pr_comments"])
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[
+ SnapshotManifestItem(identifier="changed", content_hash="new_h"),
+ SnapshotManifestItem(identifier="added", content_hash="brand_new"),
+ ],
+ baseline_hashes={"changed": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"changed": "old_h"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ statuses = mock_github_api.status_checks
+ # VR is the gate — unapproved changes post failure
+ assert statuses[-1]["state"] == "failure"
+ assert "1 changed" in statuses[-1]["description"]
+ assert "1 new" in statuses[-1]["description"]
+ assert len(mock_github_api.issue_comments) == 1
+ assert mock_github_api.issue_comments[0]["action"] == "created"
+ comment = mock_github_api.issue_comments[0]["body"]
+ assert "Review and approve in PostHog Visual Review" in comment
+ assert f"/visual_review/runs/{run.id}" in comment
+ # Verify comment ID stored for future updates
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] is not None
+
+ def test_subsequent_run_updates_existing_comment(self, github_repo, mock_github_api):
+ github_repo.enable_pr_comments = True
+ github_repo.save(update_fields=["enable_pr_comments"])
+
+ run1, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc111",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="changed", content_hash="new_h")],
+ baseline_hashes={"changed": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+ runs.finish_processing(run1.id)
+
+ run2, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc222",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="changed", content_hash="newer_h")],
+ baseline_hashes={"changed": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+ runs.finish_processing(run2.id)
+
+ created = [c for c in mock_github_api.issue_comments if c["action"] == "created"]
+ updated = [c for c in mock_github_api.issue_comments if c["action"] == "updated"]
+ assert len(created) == 1
+ assert len(updated) == 1
+ assert f"/visual_review/runs/{run2.id}" in updated[0]["body"]
+
+ def test_complete_run_does_not_comment_twice_on_retry(self, github_repo, mock_github_api):
+ github_repo.enable_pr_comments = True
+ github_repo.save(update_fields=["enable_pr_comments"])
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="changed", content_hash="new_h")],
+ baseline_hashes={"changed": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ runs.finish_processing(run.id)
+ runs.finish_processing(run.id)
+
+ assert len(mock_github_api.issue_comments) == 1
+
+ @pytest.mark.parametrize(
+ "enable_pr_comments, pr_number, snapshots, baseline_hashes, purpose",
+ [
+ (
+ False,
+ 1,
+ [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
+ {"changed": "old_h"},
+ "review",
+ ),
+ (
+ True,
+ None,
+ [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
+ {"changed": "old_h"},
+ "review",
+ ),
+ (True, 1, [SnapshotManifestItem(identifier="snap", content_hash="same")], {"snap": "same"}, "review"),
+ (
+ True,
+ 1,
+ [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
+ {"changed": "old_h"},
+ "observe",
+ ),
+ ],
+ ids=["toggle_off", "no_pr", "no_changes", "observe_purpose"],
+ )
+ def test_complete_run_does_not_comment(
+ self, enable_pr_comments, pr_number, snapshots, baseline_hashes, purpose, github_repo, mock_github_api, mocker
+ ):
+ if enable_pr_comments:
+ github_repo.enable_pr_comments = True
+ github_repo.save(update_fields=["enable_pr_comments"])
+
+ # Mock baseline for classification at complete time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=(dict(baseline_hashes), 0),
+ )
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=pr_number,
+ snapshots=snapshots,
+ baseline_hashes=baseline_hashes,
+ purpose=purpose,
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ runs.complete_run(run.id)
+
+ assert len(mock_github_api.issue_comments) == 0
+
+ def test_complete_run_posts_error_on_failure(self, github_repo, mock_github_api):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[],
+ baseline_hashes={},
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ runs.finish_processing(run.id, error_message="Diff processing failed")
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "error"
+ assert "failed" in statuses[-1]["description"].lower()
+ assert len(mock_github_api.issue_comments) == 0
+
+ def test_observe_run_with_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):
+ # Default-branch (observe) runs are tracking-only: a visual change posts a green,
+ # informational status — never a blocking failure — and no review-prompt comment.
+ github_repo.enable_pr_comments = True
+ github_repo.save(update_fields=["enable_pr_comments"])
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="master",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="changed", content_hash="new_h"),
+ SnapshotManifestItem(identifier="added", content_hash="brand_new"),
+ ],
+ baseline_hashes={"changed": "old_h"},
+ purpose="observe",
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"changed": "old_h"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert statuses[-1]["description"] == "Tracking only: 1 changed, 1 new recorded"
+ # Observe runs post to a separate, non-gating context. purpose is client-supplied,
+ # so greening the gating context would let an observe run bypass branch protection
+ # on a PR head SHA — the gating context must never be touched by an observe run.
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"
+ assert all(s["context"] != "PostHog Visual Review / storybook" for s in statuses)
+ assert len(mock_github_api.issue_comments) == 0
+
+ def test_observe_run_without_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="master",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
+ baseline_hashes={"snap": "same"},
+ purpose="observe",
+ ),
+ team_id=github_repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"snap": "same"}, 0),
+ )
+ runs.complete_run(run.id)
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert statuses[-1]["description"] == "Tracking only: no visual changes"
+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"
+
+ def test_approve_run_posts_success(self, github_repo, mock_github_api, user):
+ artifact_store.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="new_h")],
+ baseline_hashes={"snap": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+ runs.finish_processing(run.id)
+
+ approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "success"
+ assert "approved" in statuses[-1]["description"].lower()
+
+ def test_recompute_does_not_green_approved_but_uncommitted(self, github_repo, mock_github_api, user, mocker):
+ # Approving in the DB does not commit the baseline, so recompute must keep the gate red —
+ # otherwise re-running CI would re-detect the change. Only finalize (which commits) greens it.
+ artifact_store.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=github_repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="new_h")],
+ baseline_hashes={"snap": "old_h"},
+ ),
+ team_id=github_repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"snap": "old_h"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ approvals.approve_snapshots(
+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "snap", "new_hash": "new_h"}]
+ )
+ runs.recompute_run(run.id, team_id=github_repo.team_id)
+
+ statuses = mock_github_api.status_checks
+ assert statuses[-1]["state"] == "failure"
+ assert "awaiting commit" in statuses[-1]["description"].lower()
+
+ def test_no_status_without_github_integration(self, team):
+ """Status checks are silently skipped when no GitHub integration exists."""
+ repo = repos.create_repo(team_id=team.id, repo_external_id=77777, repo_full_name="org/no-github")
+
+ # No mock_github_api/mock_github_integration — should not raise
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ runs.finish_processing(run.id)
+
+ def test_no_status_without_repo_full_name(self, team, mock_github_integration, mock_github_api):
+ """Status checks are silently skipped when repo has no repo_full_name."""
+ repo = Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=88888,
+ repo_full_name="",
+ )
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ runs.finish_processing(run.id)
+
+ assert len(mock_github_api.status_checks) == 0
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRerunGithubJob:
+ """Tests for _rerun_github_job SHA validation."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=55555, repo_full_name="org/test-repo")
+
+ def _make_run(self, repo: "Repo", commit_sha: str = "abc123def456", workflow_run_id: str | None = "98765") -> "Run":
+ metadata: dict = {"github_check_run_id": "72855643533"}
+ if workflow_run_id is not None:
+ metadata["github_run_id"] = workflow_run_id
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha=commit_sha,
+ branch="feature",
+ pr_number=1,
+ snapshots=[],
+ metadata=metadata,
+ ),
+ team_id=repo.team_id,
+ )
+ return run
+
+ def test_rejects_non_digit_check_run_id(self, repo):
+ run = self._make_run(repo)
+ success, error = ci_status._rerun_github_job(run, "not-a-number")
+ assert success is False
+ assert error == "Invalid check run ID"
+
+ def test_rejects_when_workflow_run_id_missing(self, repo):
+ run = self._make_run(repo, workflow_run_id=None)
+ success, error = ci_status._rerun_github_job(run, "72855643533")
+ assert success is False
+ assert error == "Workflow run ID not recorded for this run"
+
+ def test_rejects_when_sha_does_not_match(self, repo, mocker):
+ run = self._make_run(repo, commit_sha="abc123")
+ mock_response = mocker.MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"head_sha": "different_sha_entirely", "run_id": 98765}
+ mocker.patch("products.visual_review.backend.logic.github_api._github_api_request", return_value=mock_response)
+
+ success, error = ci_status._rerun_github_job(run, "72855643533")
+
+ assert success is False
+ assert error == "Check run does not belong to this commit"
+
+ def test_rejects_when_workflow_run_does_not_match(self, repo, mocker):
+ commit_sha = "abc123def456"
+ run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
+ mock_response = mocker.MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"head_sha": commit_sha, "run_id": 11111}
+ mocker.patch("products.visual_review.backend.logic.github_api._github_api_request", return_value=mock_response)
+
+ success, error = ci_status._rerun_github_job(run, "72855643533")
+
+ assert success is False
+ assert error == "CI job does not belong to this run's workflow"
+
+ def test_rejects_when_check_run_fetch_fails(self, repo, mocker):
+ run = self._make_run(repo)
+ mock_response = mocker.MagicMock()
+ mock_response.status_code = 404
+ mocker.patch("products.visual_review.backend.logic.github_api._github_api_request", return_value=mock_response)
+
+ success, error = ci_status._rerun_github_job(run, "72855643533")
+
+ assert success is False
+ assert error is not None
+ assert "404" in error
+
+ def test_triggers_rerun_when_sha_and_workflow_match(self, repo, mocker):
+ commit_sha = "abc123def456"
+ run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
+
+ job_response = mocker.MagicMock()
+ job_response.status_code = 200
+ job_response.json.return_value = {"head_sha": commit_sha, "run_id": 98765}
+
+ rerun_response = mocker.MagicMock()
+ rerun_response.status_code = 201
+
+ mocker.patch(
+ "products.visual_review.backend.logic.github_api._github_api_request",
+ side_effect=[job_response, rerun_response],
+ )
+
+ success, error = ci_status._rerun_github_job(run, "72855643533")
+
+ assert success is True
+ assert error is None
diff --git a/products/visual_review/backend/tests/logic/test_comments.py b/products/visual_review/backend/tests/logic/test_comments.py
new file mode 100644
index 000000000000..72ebc890cbba
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_comments.py
@@ -0,0 +1,512 @@
+"""Unit tests for logic/comments.py — The visual-review PR comment."""
+
+import pytest
+
+from parameterized import parameterized
+
+from products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, SnapshotResult
+from products.visual_review.backend.logic import comment_markdown, comments, github_api
+from products.visual_review.backend.models import Repo, Run, RunSnapshot
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestApprovalComment:
+ """Tests for the post-approval PR comment summary."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=66666,
+ repo_full_name="test-org/approval-repo",
+ enable_pr_comments=True,
+ )
+
+ @pytest.fixture
+ def run_with_snapshots(self, repo):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="deadbeef",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ metadata={"github_comment_id": 9001, "baseline_commit_sha": "abc1234567"},
+ )
+
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Login/Form",
+ current_hash="curr_a",
+ baseline_hash="base_a",
+ result=SnapshotResult.CHANGED,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Settings/Tab",
+ current_hash="curr_b",
+ baseline_hash="",
+ result=SnapshotResult.NEW,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Old/Component",
+ current_hash="",
+ baseline_hash="base_c",
+ result=SnapshotResult.REMOVED,
+ )
+
+ return run
+
+ def test_build_approval_comment_body_summarizes_changes(self, repo, run_with_snapshots):
+ approver = comment_markdown._Approver(label="alice", is_github_login=True)
+ body = comment_markdown._build_approval_comment_body(run_with_snapshots, repo, approver)
+
+ assert "✅ **Visual changes approved** by @alice" in body
+ assert "abc1234" in body # baseline SHA prefix
+ assert f"/visual_review/runs/{run_with_snapshots.id}" in body
+ assert "1 changed, 1 new, 1 removed." in body
+ assert "<img" not in body
+ assert "<table" not in body
+ assert "/api/visual_review/public/" not in body
+
+ def test_build_approval_comment_body_falls_back_to_a_reviewer(self, repo, run_with_snapshots):
+ body = comment_markdown._build_approval_comment_body(run_with_snapshots, repo, None)
+
+ assert "by a reviewer" in body
+
+ def test_build_approval_comment_body_escapes_non_github_approver(self, repo, run_with_snapshots):
+ # email local-part / first_name fallbacks are user-controlled — must be escaped
+ approver = comment_markdown._Approver(label="alice[evil](http://attacker)", is_github_login=False)
+ body = comment_markdown._build_approval_comment_body(run_with_snapshots, repo, approver)
+
+ # No raw `@` mention (which would render as a GitHub user link)
+ assert "by @alice" not in body
+ # Markdown control chars in the label must be backslash-escaped
+ assert "\\[evil\\]" in body
+ assert "\\(http://attacker\\)" in body
+
+ def test_build_approval_comment_body_no_actionable_snapshots(self, repo):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="empty",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ approver = comment_markdown._Approver(label="bob", is_github_login=True)
+ body = comment_markdown._build_approval_comment_body(run, repo, approver)
+ assert "✅ **Visual changes approved**" in body
+ # No counts line when there's nothing to summarize
+ assert "changed" not in body
+ assert "new" not in body
+ assert "removed" not in body
+ # A genuinely empty run stays silent — the suppressed-only note must not fire
+ assert "quarantined or tolerated" not in body
+
+ def test_build_approval_comment_body_excludes_quarantined_and_tolerated(self, repo):
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="mixed",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id, run=run, identifier="Real/Change", result=SnapshotResult.CHANGED
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Flaky/Quarantined",
+ result=SnapshotResult.CHANGED,
+ is_quarantined=True,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Known/Tolerated",
+ result=SnapshotResult.NEW,
+ review_state=ReviewState.TOLERATED,
+ )
+
+ body = comment_markdown._build_approval_comment_body(
+ run, repo, comment_markdown._Approver(label="bob", is_github_login=True)
+ )
+
+ assert "1 changed." in body
+ assert "new" not in body
+ assert "quarantined or tolerated" not in body
+
+ def test_build_approval_comment_body_notes_when_only_quarantined_and_tolerated(self, repo):
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="suppressed",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Flaky/Quarantined",
+ result=SnapshotResult.CHANGED,
+ is_quarantined=True,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Known/Tolerated",
+ result=SnapshotResult.NEW,
+ review_state=ReviewState.TOLERATED,
+ )
+
+ body = comment_markdown._build_approval_comment_body(
+ run, repo, comment_markdown._Approver(label="bob", is_github_login=True)
+ )
+
+ assert "All visual changes in this run were quarantined or tolerated." in body
+ assert "1 changed" not in body
+
+ def test_post_approval_comment_skips_when_pr_comments_disabled(self, repo, run_with_snapshots, mocker):
+ repo.enable_pr_comments = False
+ repo.save(update_fields=["enable_pr_comments"])
+
+ spy = mocker.patch.object(github_api, "_github_api_request")
+ comments._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_skips_when_no_pr_number(self, repo, run_with_snapshots, mocker):
+ run_with_snapshots.pr_number = None
+ run_with_snapshots.save(update_fields=["pr_number"])
+
+ spy = mocker.patch.object(github_api, "_github_api_request")
+ comments._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_skips_for_non_human_decision(self, repo, run_with_snapshots, mocker):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run_with_snapshots.review_decision = ReviewDecision.AUTO_APPROVED
+ run_with_snapshots.save(update_fields=["review_decision"])
+
+ spy = mocker.patch.object(github_api, "_github_api_request")
+ comments._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_skips_when_no_existing_comment_id(self, repo, run_with_snapshots, mocker):
+ run_with_snapshots.metadata = {}
+ run_with_snapshots.save(update_fields=["metadata"])
+
+ spy = mocker.patch.object(github_api, "_github_api_request")
+ comments._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_patches_existing_comment(self, repo, run_with_snapshots, mocker):
+ class FakeResp:
+ status_code = 200
+ text = ""
+
+ spy = mocker.patch.object(github_api, "_github_api_request", return_value=FakeResp())
+
+ comments._post_approval_comment(run_with_snapshots, repo)
+
+ spy.assert_called_once()
+ kwargs = spy.call_args.kwargs
+ assert kwargs["method"] == "PATCH"
+ assert kwargs["path"] == "issues/comments/9001"
+ assert "✅ **Visual changes approved**" in kwargs["json"]["body"]
+
+ def test_post_approval_comment_falls_back_to_post_on_404(self, repo, run_with_snapshots, mocker):
+ class PatchResp:
+ status_code = 404
+ text = "Not Found"
+
+ class PostResp:
+ status_code = 201
+ text = ""
+
+ @staticmethod
+ def json():
+ return {"id": 9999}
+
+ spy = mocker.patch.object(github_api, "_github_api_request", side_effect=[PatchResp(), PostResp()])
+
+ comments._post_approval_comment(run_with_snapshots, repo)
+
+ assert spy.call_count == 2
+ first_call = spy.call_args_list[0].kwargs
+ second_call = spy.call_args_list[1].kwargs
+ assert first_call["method"] == "PATCH"
+ assert second_call["method"] == "POST"
+ assert second_call["path"] == "issues/42/comments"
+
+ run_with_snapshots.refresh_from_db()
+ assert run_with_snapshots.metadata["github_comment_id"] == 9999
+
+ def test_post_approval_comment_swallows_exceptions(self, repo, run_with_snapshots, mocker):
+ mocker.patch.object(github_api, "_github_api_request", side_effect=RuntimeError("boom"))
+ # Must not raise
+ comments._post_approval_comment(run_with_snapshots, repo)
+
+ @staticmethod
+ def _mk_artifact(repo, content_hash, *, with_thumbnail=None):
+ from products.visual_review.backend.models import Artifact
+
+ artifact = Artifact.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ content_hash=content_hash,
+ storage_path=f"path/{content_hash}",
+ width=320,
+ height=200,
+ )
+ if with_thumbnail:
+ thumb = Artifact.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ content_hash=with_thumbnail,
+ storage_path=f"thumb/{with_thumbnail}",
+ )
+ artifact.thumbnail = thumb
+ artifact.save(update_fields=["thumbnail"])
+ return artifact
+
+ @staticmethod
+ def _fake_storage(returns_url=True):
+ class _FakeStorage:
+ def __init__(self, repo_id):
+ self.repo_id = repo_id
+
+ def get_presigned_download_url(self, content_hash, expiration=3600):
+ return f"https://cdn.example/{content_hash}?exp={expiration}" if returns_url else None
+
+ return _FakeStorage
+
+ @pytest.fixture
+ def run_with_artifacts(self, repo):
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="cafef00d",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ metadata={"github_comment_id": 9001},
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Login/Form",
+ result=SnapshotResult.CHANGED,
+ baseline_artifact=self._mk_artifact(repo, "base_a", with_thumbnail="thumb_a"),
+ current_artifact=self._mk_artifact(repo, "curr_a"),
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Settings/Tab",
+ result=SnapshotResult.NEW,
+ current_artifact=self._mk_artifact(repo, "curr_b"),
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Old/Component",
+ result=SnapshotResult.REMOVED,
+ baseline_artifact=self._mk_artifact(repo, "base_c"),
+ )
+ return run
+
+ def test_build_approval_comment_body_includes_before_after_tables(self, repo, run_with_artifacts, mocker):
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+
+ body = comment_markdown._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ # Changed table: baseline before, current after — full-resolution originals,
+ # not thumbnails, so clicking opens the image at full size
+ assert "**Changed**" in body
+ assert "| Snapshot | Before | After |" in body
+ assert "https://cdn.example/base_a" in body # full-res original, not thumb_a
+ assert "https://cdn.example/thumb_a" not in body
+ assert "https://cdn.example/curr_a" in body
+ # Removed snapshot lives in the changed table with an empty after cell
+ assert "_(removed)_" in body
+ assert "https://cdn.example/base_c" in body
+ # New table: empty before cell, current after
+ assert "**New**" in body
+ assert "https://cdn.example/curr_b" in body
+ assert "_(none)_" in body
+ # Long-lived URL so GitHub's image proxy can still fetch it later
+ assert f"exp={comment_markdown._COMMENT_IMAGE_URL_EXPIRATION}" in body
+
+ def test_build_snapshot_image_tables_excludes_quarantined_and_tolerated(self, repo, run_with_artifacts, mocker):
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run_with_artifacts,
+ identifier="Flaky/Quarantined",
+ result=SnapshotResult.CHANGED,
+ is_quarantined=True,
+ baseline_artifact=self._mk_artifact(repo, "base_q"),
+ current_artifact=self._mk_artifact(repo, "curr_q"),
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run_with_artifacts,
+ identifier="Known/Tolerated",
+ result=SnapshotResult.CHANGED,
+ review_state=ReviewState.TOLERATED,
+ baseline_artifact=self._mk_artifact(repo, "base_t"),
+ current_artifact=self._mk_artifact(repo, "curr_t"),
+ )
+
+ body = comment_markdown._build_snapshot_image_tables(run_with_artifacts, repo)
+
+ assert "Flaky/Quarantined" not in body
+ assert "Known/Tolerated" not in body
+ assert "curr_q" not in body
+ assert "curr_t" not in body
+ assert "Login/Form" in body
+
+ def test_build_approval_comment_body_deep_links_each_snapshot(self, repo, run_with_artifacts, mocker):
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+
+ body = comment_markdown._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ # Each snapshot name links straight to its deep link on the run page
+ changed = run_with_artifacts.snapshots.get(identifier="Login/Form")
+ assert f"[`Login/Form`]({comment_markdown._run_url(run_with_artifacts, repo)}?snapshot={changed.id})" in body
+
+ def test_build_approval_comment_body_caps_at_eight_and_links_out(self, repo, mocker):
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="manysnaps",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ for i in range(11):
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier=f"Story/{i:02d}",
+ result=SnapshotResult.CHANGED,
+ baseline_artifact=self._mk_artifact(repo, f"base_{i}"),
+ current_artifact=self._mk_artifact(repo, f"curr_{i}"),
+ )
+
+ body = comment_markdown._build_approval_comment_body(run, repo, None, add_images=True)
+
+ # 8 of 11 rows rendered, the rest linked out
+ assert body.count("<img") == 8 * 2 # before + after per shown row
+ assert "…and 3 more" in body
+ assert f"/visual_review/runs/{run.id})" in body
+
+ def test_build_approval_comment_body_falls_back_to_text_without_storage(self, repo, run_with_artifacts, mocker):
+ # Images requested, but storage yields no URL — fall back to the text summary.
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage(returns_url=False))
+
+ body = comment_markdown._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ assert "<img" not in body
+ assert "**Changed**" not in body
+ # Still carries the textual summary
+ assert "1 changed, 1 new, 1 removed." in body
+
+ def test_build_approval_comment_body_omits_images_unless_opted_in(self, repo, run_with_artifacts, mocker):
+ # add_images defaults false: the comment is always posted but stays a text summary.
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+
+ body = comment_markdown._build_approval_comment_body(run_with_artifacts, repo, None)
+
+ assert "<img" not in body
+ assert "**Changed**" not in body
+ # The comment still summarizes what changed and links to the run
+ assert "1 changed, 1 new, 1 removed." in body
+ assert f"/visual_review/runs/{run_with_artifacts.id}" in body
+
+ def test_image_cell_escapes_alt_and_src(self):
+ # Both attributes are escaped so a quote in either can't break out of the tag
+ cell = comment_markdown._image_cell('https://cdn.example/x?a="b', 'a"b')
+ assert 'alt="a&quot;b"' in cell
+ assert 'src="https://cdn.example/x?a=&quot;b"' in cell
+
+ def test_image_cell_constrains_width_but_serves_full_resolution(self):
+ # The cell shows a width-constrained image whose src is the full-resolution
+ # original, so GitHub opens it at full size when clicked — no <a> wrapper needed.
+ cell = comment_markdown._image_cell("https://cdn.example/full", "after")
+ assert (
+ cell == f'<img src="https://cdn.example/full" width="{comment_markdown._COMMENT_IMAGE_WIDTH}" alt="after">'
+ )
+
+ @parameterized.expand(
+ [
+ ("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, _name, identifier, expected):
+ assert comment_markdown._snapshot_name_cell(identifier) == expected
+
+ def test_snapshot_name_cell_collapses_control_characters(self):
+ # Newlines/tabs/carriage returns would otherwise break out of the table row
+ cell = comment_markdown._snapshot_name_cell("a\nb\tc\rd")
+ assert "\n" not in cell
+ assert "\r" not in cell
+ assert "\t" not in cell
+ assert cell == "`a b c d`"
+
+ def test_snapshot_name_cell_newline_cannot_inject_table_rows(self):
+ # A pipe-laden payload across a newline stays a single escaped cell
+ cell = comment_markdown._snapshot_name_cell("x\n| --- |")
+ assert "\n" not in cell
+ assert cell == "`x \\| --- \\|`"
+
+ def test_comment_image_url_requests_seven_day_expiry(self, repo, mocker):
+ # The 7-day expiry is load-bearing: GitHub's image proxy may fetch the URL
+ # long after the comment is posted, so lock the behaviour with a test.
+ captured = {}
+
+ class _RecordingStorage:
+ def __init__(self, repo_id):
+ pass
+
+ def get_presigned_download_url(self, content_hash, expiration=3600):
+ captured["content_hash"] = content_hash
+ captured["expiration"] = expiration
+ return "https://cdn.example/x"
+
+ mocker.patch.object(comment_markdown, "ArtifactStorage", _RecordingStorage)
+
+ artifact = self._mk_artifact(repo, "h1")
+ url = comment_markdown._comment_image_url(repo, artifact)
+
+ assert url == "https://cdn.example/x"
+ assert captured["content_hash"] == "h1"
+ assert captured["expiration"] == 60 * 60 * 24 * 7 == 604800
+
+ def test_comment_image_url_serves_full_resolution_not_thumbnail(self, repo, mocker):
+ # Serve the original artifact, not the thumbnail, so clicking opens it full-size
+ mocker.patch.object(comment_markdown, "ArtifactStorage", self._fake_storage())
+
+ artifact = self._mk_artifact(repo, "full_h", with_thumbnail="thumb_h")
+ url = comment_markdown._comment_image_url(repo, artifact)
+
+ assert url is not None
+ assert "full_h" in url
+ assert "thumb_h" not in url
diff --git a/products/visual_review/backend/tests/logic/test_gating.py b/products/visual_review/backend/tests/logic/test_gating.py
new file mode 100644
index 000000000000..005e2f1c3e7a
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_gating.py
@@ -0,0 +1,137 @@
+"""Unit tests for logic/gating.py — Quarantine stamping and resolution accounting."""
+
+import pytest
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import RunType
+from products.visual_review.backend.logic import approvals, artifact_store, quarantine, repos, runs
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestQuarantineStamping:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99996, repo_full_name="org/test-quarantine")
+
+ def _create_completed_run(self, repo, mocker, identifiers_and_hashes, baseline=None):
+ """Create a run, classify against baseline, and finalize it.
+
+ identifiers_and_hashes: list of (identifier, content_hash)
+ baseline: dict of identifier -> baseline_hash (for _resolve_baselines mock)
+ """
+ snapshots = [SnapshotManifestItem(identifier=ident, content_hash=h) for ident, h in identifiers_and_hashes]
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=1,
+ snapshots=snapshots,
+ ),
+ team_id=repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=(baseline or {}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ return run
+
+ def test_finish_processing_stamps_quarantined_snapshots(self, repo, team, mocker):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[
+ ("Button-primary", "h1"),
+ ("Button-secondary", "h2"),
+ ("Card-default", "h3"),
+ ],
+ baseline={"Button-primary": "old1", "Button-secondary": "old2", "Card-default": "old3"},
+ )
+
+ # Quarantine one identifier
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Button-primary",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ )
+
+ runs.finish_processing(run.id)
+
+ snapshots = {s.identifier: s for s in run.snapshots.all()}
+ assert snapshots["Button-primary"].is_quarantined is True
+ assert snapshots["Button-secondary"].is_quarantined is False
+ assert snapshots["Card-default"].is_quarantined is False
+
+ def test_unquarantine_clears_flag_on_approve(self, repo, team, user, mocker):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ # Create quarantine entry
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Button-primary",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ )
+
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button-primary", "h1")],
+ baseline={"Button-primary": "old1"},
+ )
+
+ runs.finish_processing(run.id)
+ snapshot = run.snapshots.get(identifier="Button-primary")
+ assert snapshot.is_quarantined is True
+
+ # Unquarantine the identifier
+ quarantine.unquarantine_identifier(
+ repo_id=repo.id, identifier="Button-primary", run_type=RunType.STORYBOOK, team_id=team.id
+ )
+
+ # Finalize the run — _stamp_quarantine re-evaluates
+ approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ snapshot.refresh_from_db()
+ assert snapshot.is_quarantined is False
+
+ def test_quarantine_excludes_from_changed_count(self, repo, team, mocker):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ # Quarantine one identifier before finalization
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Button-primary",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ )
+
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[
+ ("Button-primary", "h1"),
+ ("Button-secondary", "h2"),
+ ("Card-new", "h3"),
+ ],
+ baseline={"Button-primary": "old1", "Button-secondary": "old2"},
+ )
+
+ processed = runs.finish_processing(run.id)
+
+ # Button-primary is quarantined — should not count toward changed
+ # Button-secondary is changed (not quarantined), Card-new is new (not quarantined)
+ assert processed.changed_count == 1 # only Button-secondary
+ assert processed.new_count == 1 # only Card-new
diff --git a/products/visual_review/backend/tests/logic/test_quarantine.py b/products/visual_review/backend/tests/logic/test_quarantine.py
new file mode 100644
index 000000000000..9eaf7e1bb15d
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_quarantine.py
@@ -0,0 +1,91 @@
+"""Unit tests for logic/quarantine.py — Quarantined identifiers."""
+
+import pytest
+
+from django.utils import timezone
+
+from products.visual_review.backend.facade.enums import RunStatus, RunType
+from products.visual_review.backend.logic import quarantine, repos
+from products.visual_review.backend.models import Repo, Run
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestQuarantineIdentifier:
+ """Coverage for `quarantine.quarantine_identifier` — especially the new
+ `source_run_id` behavior (valid run is stored, foreign run is dropped)."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/test-source-run")
+
+ def _mk_run(self, repo: Repo, branch: str = "main") -> Run:
+ return Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ run_type=RunType.STORYBOOK,
+ branch=branch,
+ commit_sha="abc123",
+ status=RunStatus.COMPLETED,
+ completed_at=timezone.now(),
+ )
+
+ def test_stores_valid_source_run(self, repo, team, user):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ run = self._mk_run(repo)
+ entry = quarantine.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ source_run_id=run.id,
+ )
+ # Returned row points at the source run …
+ assert entry.source_run_id == run.id
+ # … and the persisted row agrees.
+ persisted = QuarantinedIdentifier.objects.get(id=entry.id)
+ assert persisted.source_run_id == run.id
+
+ def test_drops_source_run_from_another_team(self, repo, team, user):
+ """A `source_run_id` from a run that doesn't belong to this team/repo
+ is silently dropped — the quarantine still gets created, just without
+ the cross-team pointer."""
+ from posthog.models.team.team import Team
+
+ # Sibling team in the same org with its own repo + run.
+ other_team = Team.objects.create(organization=team.organization, name="other")
+ other_repo = repos.create_repo(team_id=other_team.id, repo_external_id=12121, repo_full_name="org/other-repo")
+ foreign_run = Run.objects.create(
+ team_id=other_team.id,
+ repo=other_repo,
+ run_type=RunType.STORYBOOK,
+ branch="main",
+ commit_sha="xyz789",
+ status=RunStatus.COMPLETED,
+ completed_at=timezone.now(),
+ )
+
+ entry = quarantine.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ source_run_id=foreign_run.id,
+ )
+ assert entry.source_run_id is None
+
+ def test_omitting_source_run_leaves_it_null(self, repo, team, user):
+ entry = quarantine.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="flake",
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ )
+ assert entry.source_run_id is None
diff --git a/products/visual_review/backend/tests/logic/test_repos.py b/products/visual_review/backend/tests/logic/test_repos.py
new file mode 100644
index 000000000000..445e83026ef4
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_repos.py
@@ -0,0 +1,40 @@
+"""Unit tests for logic/repos.py — Repo CRUD."""
+
+import pytest
+
+from products.visual_review.backend.logic import errors, repos
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestProjectOperations:
+ def test_create_repo(self, team):
+ repo = repos.create_repo(team_id=team.id, repo_external_id=12345, repo_full_name="org/my-repo")
+
+ assert repo.team_id == team.id
+ assert repo.repo_external_id == 12345
+ assert repo.repo_full_name == "org/my-repo"
+
+ def test_get_repo(self, team):
+ repo = repos.create_repo(team_id=team.id, repo_external_id=11111, repo_full_name="org/test")
+
+ retrieved = repos.get_repo(repo.id, team_id=team.id)
+
+ assert retrieved.id == repo.id
+ assert retrieved.repo_full_name == "org/test"
+
+ def test_get_repo_not_found(self, team):
+ import uuid
+
+ with pytest.raises(errors.RepoNotFoundError):
+ repos.get_repo(uuid.uuid4(), team_id=team.id)
+
+ def test_list_repos_for_team(self, team):
+ repos.create_repo(team_id=team.id, repo_external_id=111, repo_full_name="org/first")
+ repos.create_repo(team_id=team.id, repo_external_id=222, repo_full_name="org/second")
+
+ projects = repos.list_repos_for_team(team.id)
+
+ assert len(projects) == 2
+ names = {p.repo_full_name for p in projects}
+ assert names == {"org/first", "org/second"}
diff --git a/products/visual_review/backend/tests/logic/test_run_queries.py b/products/visual_review/backend/tests/logic/test_run_queries.py
new file mode 100644
index 000000000000..26f89b50ed54
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_run_queries.py
@@ -0,0 +1,39 @@
+"""Unit tests for logic/run_queries.py — Run and snapshot lookups."""
+
+import pytest
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import RunType
+from products.visual_review.backend.logic import repos, run_queries, runs
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestGetRunSnapshots:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
+
+ def test_get_run_snapshots(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="A-component", content_hash="h1"),
+ SnapshotManifestItem(identifier="B-component", content_hash="h2"),
+ SnapshotManifestItem(identifier="C-component", content_hash="h3"),
+ ],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ snapshots = run_queries.get_run_snapshots(run.id)
+
+ assert len(snapshots) == 3
+ # Should be ordered by identifier
+ assert [s.identifier for s in snapshots] == ["A-component", "B-component", "C-component"]
diff --git a/products/visual_review/backend/tests/logic/test_runs.py b/products/visual_review/backend/tests/logic/test_runs.py
new file mode 100644
index 000000000000..c0268006af15
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_runs.py
@@ -0,0 +1,817 @@
+"""Unit tests for logic/runs.py — Run creation, ingestion, completion, supersession, and recompute."""
+
+import pytest
+
+from products.visual_review.backend.db import WRITER_DB
+from 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.logic import approvals, artifact_store, errors, repos, run_queries, runs
+from products.visual_review.backend.models import Repo, RunSnapshot
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRunOperations:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
+
+ def test_create_run_basic(self, repo):
+ run, uploads = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123def456",
+ branch="main",
+ pr_number=42,
+ snapshots=[
+ SnapshotManifestItem(identifier="Button-primary", content_hash="hash1"),
+ SnapshotManifestItem(identifier="Button-secondary", content_hash="hash2"),
+ ],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ assert run.repo_id == repo.id
+ assert run.run_type == RunType.STORYBOOK
+ assert run.commit_sha == "abc123def456"
+ assert run.branch == "main"
+ assert run.pr_number == 42
+ assert run.status == RunStatus.PENDING
+ assert run.total_snapshots == 2
+ # uploads is a list of dicts with content_hash, url, fields
+ upload_hashes = {u["content_hash"] for u in uploads}
+ assert upload_hashes == {"hash1", "hash2"}
+
+ def test_create_run_with_existing_artifacts(self, repo):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="existing", storage_path="p/existing")
+
+ run, uploads = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.PLAYWRIGHT,
+ commit_sha="abc",
+ branch="feat",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="snap1", content_hash="existing"),
+ SnapshotManifestItem(identifier="snap2", content_hash="new"),
+ ],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Only "new" needs upload, "existing" already has artifact
+ assert len(uploads) == 1
+ assert uploads[0]["content_hash"] == "new"
+
+ def test_create_run_with_baselines(self, repo, mocker):
+ baseline_artifact, _ = artifact_store.get_or_create_artifact(
+ repo_id=repo.id, content_hash="baseline_hash", storage_path="p/baseline"
+ )
+
+ run, _uploads = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
+ baseline_hashes={"Button": "baseline_hash"},
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Classification happens at complete_run time, not create_run time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"Button": "baseline_hash"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+
+ snapshot = run.snapshots.first()
+ assert snapshot is not None
+ assert snapshot.baseline_artifact_id == baseline_artifact.id
+ assert snapshot.result == SnapshotResult.CHANGED
+
+ def test_create_run_snapshot_results(self, repo, mocker):
+ baseline_artifact, _ = artifact_store.get_or_create_artifact(
+ repo_id=repo.id, content_hash="same_hash", storage_path="p/same"
+ )
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="unchanged", content_hash="same_hash"),
+ SnapshotManifestItem(identifier="new", content_hash="brand_new"),
+ SnapshotManifestItem(identifier="changed", content_hash="different"),
+ ],
+ baseline_hashes={
+ "unchanged": "same_hash",
+ "changed": "old_hash",
+ },
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Classification happens at complete_run time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"unchanged": "same_hash", "changed": "old_hash"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+
+ snapshots = {s.identifier: s for s in run.snapshots.all()}
+ assert snapshots["unchanged"].result == SnapshotResult.UNCHANGED
+ assert snapshots["new"].result == SnapshotResult.NEW
+ assert snapshots["changed"].result == SnapshotResult.CHANGED
+
+ def test_create_run_empty(self, repo):
+ run, uploads = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ ),
+ team_id=repo.team_id,
+ )
+
+ assert run.total_snapshots == 0
+ assert run.changed_count == 0
+ assert run.new_count == 0
+ assert run.removed_count == 0
+ assert run.snapshots.count() == 0
+ assert len(uploads) == 0
+
+ def test_add_snapshots_to_run(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ ),
+ team_id=repo.team_id,
+ )
+ assert run.total_snapshots == 0
+
+ # Shard 1
+ added, _uploads = runs.add_snapshots_to_run(
+ run_id=run.id,
+ team_id=repo.team_id,
+ snapshots=[{"identifier": "btn", "content_hash": "h1"}],
+ )
+ assert added == 1
+ run.refresh_from_db()
+ assert run.total_snapshots == 1
+ assert run.new_count == 1
+
+ # Shard 2
+ added, _uploads = runs.add_snapshots_to_run(
+ run_id=run.id,
+ team_id=repo.team_id,
+ snapshots=[{"identifier": "card", "content_hash": "h2"}],
+ )
+ assert added == 1
+ run.refresh_from_db()
+ assert run.total_snapshots == 2
+ assert run.new_count == 2
+ assert run.snapshots.count() == 2
+
+ def test_add_snapshots_idempotent(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ ),
+ team_id=repo.team_id,
+ )
+
+ for _ in range(2):
+ runs.add_snapshots_to_run(
+ run_id=run.id,
+ team_id=repo.team_id,
+ snapshots=[{"identifier": "btn", "content_hash": "h1"}],
+ )
+
+ assert run.snapshots.count() == 1
+
+ def test_add_snapshots_rejects_non_pending(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ ),
+ team_id=repo.team_id,
+ )
+ runs.finish_processing(run.id)
+
+ with pytest.raises(ValueError, match="pending"):
+ runs.add_snapshots_to_run(
+ run_id=run.id,
+ team_id=repo.team_id,
+ snapshots=[{"identifier": "btn", "content_hash": "h1"}],
+ )
+
+ def test_complete_run_detects_removals(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Mock baseline to include an identifier not in the run
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"kept": "h1", "deleted": "h2"}, 0),
+ )
+
+ completed = runs.complete_run(run.id)
+
+ assert completed.removed_count == 1
+ removed = run.snapshots.get(identifier="deleted")
+ assert removed.result == SnapshotResult.REMOVED
+
+ def test_complete_run_partial_skips_removals_off_default_branch(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="feature-x",
+ pr_number=7,
+ snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
+ is_partial=True,
+ ),
+ team_id=repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"kept": "h1", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic.baselines._run_is_on_default_branch", return_value=False)
+
+ completed = runs.complete_run(run.id)
+
+ assert completed.removed_count == 0
+ assert not run.snapshots.filter(identifier="deleted").exists()
+
+ def test_complete_run_partial_ignored_on_default_branch(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="master",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
+ is_partial=True,
+ ),
+ team_id=repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"kept": "h1", "deleted": "h2"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.logic.baselines._run_is_on_default_branch", return_value=True)
+
+ completed = runs.complete_run(run.id)
+
+ # is_partial must not suppress removal detection on the default branch.
+ assert completed.removed_count == 1
+ removed = run.snapshots.get(identifier="deleted")
+ assert removed.result == SnapshotResult.REMOVED
+ # The default-branch correction is persisted, so the run is no longer
+ # treated as partial anywhere downstream (status context, UI).
+ assert completed.is_partial is False
+
+ 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, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="deadbeef123",
+ branch="master",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="A", content_hash="h1")],
+ ),
+ team_id=repo.team_id,
+ )
+
+ mock_resolve = mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"A": "h1"}, 0),
+ )
+
+ runs.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, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ purpose="observe",
+ ),
+ team_id=repo.team_id,
+ )
+ assert run.purpose == "observe"
+
+ def test_approve_rejects_observe_runs(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="btn", content_hash="h1")],
+ purpose="observe",
+ ),
+ team_id=repo.team_id,
+ )
+ runs.finish_processing(run.id)
+
+ with pytest.raises(ValueError, match="Observational"):
+ approvals.finalize_run(run_id=run.id, user_id=1, approve_all=True)
+
+ def test_get_run(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ retrieved = run_queries.get_run(run.id)
+
+ assert retrieved.id == run.id
+
+ def test_get_run_not_found(self):
+ import uuid
+
+ with pytest.raises(errors.RunNotFoundError):
+ run_queries.get_run(uuid.uuid4())
+
+ def test_mark_run_processing(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ updated = runs.mark_run_processing(run.id)
+
+ assert updated.status == RunStatus.PROCESSING
+
+ def test_finish_processing_success(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="changed1", content_hash="h1"),
+ SnapshotManifestItem(identifier="new1", content_hash="h2"),
+ ],
+ baseline_hashes={"changed1": "old"},
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Classification happens at complete_run time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"changed1": "old"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+
+ # complete_run leaves the run in PROCESSING when there are changes;
+ # finish_processing completes it
+ updated = runs.finish_processing(run.id)
+
+ assert updated.status == RunStatus.COMPLETED
+ assert updated.completed_at is not None
+ assert updated.changed_count == 1
+ assert updated.new_count == 1
+ assert updated.error_message == ""
+
+ def test_finish_processing_with_error(self, repo):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ updated = runs.finish_processing(run.id, error_message="Something failed")
+
+ assert updated.status == RunStatus.FAILED
+ assert updated.error_message == "Something failed"
+
+ def test_update_run_counts_reads_and_writes_through_requested_db(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+
+ snapshot_queryset = mocker.Mock()
+ snapshot_queryset.values.return_value.annotate.return_value = [
+ {"result": SnapshotResult.CHANGED, "n": 2},
+ {"result": SnapshotResult.NEW, "n": 1},
+ ]
+ snapshot_manager = mocker.Mock()
+ snapshot_manager.filter.return_value = snapshot_queryset
+
+ run_snapshot_using = mocker.patch.object(RunSnapshot.objects, "using", return_value=snapshot_manager)
+ run_save = mocker.patch.object(run, "save")
+
+ runs._update_run_counts(run, using=WRITER_DB)
+
+ run_snapshot_using.assert_called_once_with(WRITER_DB)
+ snapshot_manager.filter.assert_called_once_with(run_id=run.id)
+ run_save.assert_called_once_with(using=WRITER_DB, update_fields=["changed_count", "new_count", "removed_count"])
+ assert run.changed_count == 2
+ assert run.new_count == 1
+ assert run.removed_count == 0
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRunSupersession:
+ """When a new run is created for the same (repo, branch, run_type), older runs get superseded."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return Repo.objects.create(team_id=team.id, repo_external_id=66666, repo_full_name="org/test-repo")
+
+ def _create_run(self, repo, *, branch="feat/x", run_type=RunType.STORYBOOK, commit_sha="abc"):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=run_type,
+ commit_sha=commit_sha,
+ branch=branch,
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash=commit_sha)],
+ baseline_hashes={},
+ ),
+ team_id=repo.team_id,
+ )
+ runs.finish_processing(run.id)
+ run.refresh_from_db()
+ return run
+
+ def test_single_run_not_superseded(self, repo):
+ run = self._create_run(repo)
+
+ assert run.superseded_by is None
+ assert run_queries.is_run_stale(run) is False
+
+ def test_newer_run_supersedes_older(self, repo):
+ old = self._create_run(repo, commit_sha="old")
+ new = self._create_run(repo, commit_sha="new")
+
+ old.refresh_from_db()
+ assert old.superseded_by_id == new.id
+ assert new.superseded_by is None
+
+ def test_supersession_chains(self, repo):
+ first = self._create_run(repo, commit_sha="1st")
+ second = self._create_run(repo, commit_sha="2nd")
+ third = self._create_run(repo, commit_sha="3rd")
+
+ first.refresh_from_db()
+ second.refresh_from_db()
+ # first was superseded by second, then second by third
+ # first still points to second (not updated again)
+ assert first.superseded_by_id == second.id
+ assert second.superseded_by_id == third.id
+ assert third.superseded_by is None
+
+ def test_different_branches_are_independent(self, repo):
+ run_a = self._create_run(repo, branch="feat/a", commit_sha="a")
+ self._create_run(repo, branch="feat/b", commit_sha="b")
+
+ run_a.refresh_from_db()
+ assert run_a.superseded_by is None
+
+ def test_different_run_types_are_independent(self, repo):
+ run_sb = self._create_run(repo, run_type=RunType.STORYBOOK, commit_sha="a")
+ self._create_run(repo, run_type=RunType.PLAYWRIGHT, commit_sha="b")
+
+ run_sb.refresh_from_db()
+ assert run_sb.superseded_by is None
+
+ def test_review_state_filter_excludes_superseded(self, repo, team):
+ self._create_run(repo, commit_sha="old")
+ self._create_run(repo, commit_sha="new")
+
+ current_runs = list(run_queries.list_runs_for_team(team.id, review_state="needs_review"))
+ stale_runs = list(run_queries.list_runs_for_team(team.id, review_state="stale"))
+
+ assert len(current_runs) == 1
+ assert current_runs[0].commit_sha == "new"
+ assert len(stale_runs) == 1
+ assert stale_runs[0].commit_sha == "old"
+
+ def test_review_state_counts(self, repo, team):
+ self._create_run(repo, commit_sha="old")
+ self._create_run(repo, commit_sha="new")
+
+ counts = run_queries.get_review_state_counts(team.id)
+
+ assert counts["stale"] == 1
+ assert counts["needs_review"] == 1
+
+ def test_approve_superseded_run_raises(self, repo, user):
+ old = self._create_run(repo, commit_sha="old")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="old", storage_path="p/old")
+ self._create_run(repo, commit_sha="new")
+
+ old.refresh_from_db()
+ with pytest.raises(errors.StaleRunError):
+ approvals.finalize_run(run_id=old.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ def test_approve_latest_run_succeeds(self, repo, user):
+ self._create_run(repo, commit_sha="old")
+ newest = self._create_run(repo, commit_sha="new")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="new", storage_path="p/new")
+
+ run = approvals.finalize_run(run_id=newest.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ assert run.approved is True
+
+ def test_approved_run_superseded_but_stays_clean(self, repo, user, team):
+ first = self._create_run(repo, commit_sha="1st")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")
+ approvals.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ self._create_run(repo, commit_sha="2nd")
+
+ first.refresh_from_db()
+ assert first.superseded_by is not None
+ # Approved runs still show in clean filter, not stale
+ clean = list(run_queries.list_runs_for_team(team.id, review_state="clean"))
+ assert any(r.id == first.id for r in clean)
+
+ def test_clean_run_superseded_but_stays_clean(self, repo, team, mocker):
+ clean_run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="clean",
+ branch="feat/x",
+ pr_number=1,
+ snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
+ baseline_hashes={"snap": "same"},
+ ),
+ team_id=repo.team_id,
+ )
+
+ # Classification happens at complete_run time
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"snap": "same"}, 0),
+ )
+ runs.complete_run(clean_run.id)
+
+ self._create_run(repo, commit_sha="next")
+
+ clean_run.refresh_from_db()
+ assert clean_run.superseded_by is not None
+ # Clean runs still show in clean filter, not stale
+ clean = list(run_queries.list_runs_for_team(team.id, review_state="clean"))
+ assert any(r.id == clean_run.id for r in clean)
+
+ def test_approved_run_shows_in_clean_not_stale(self, repo, team, user):
+ first = self._create_run(repo, commit_sha="1st")
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")
+ approvals.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ self._create_run(repo, commit_sha="2nd")
+
+ stale = list(run_queries.list_runs_for_team(team.id, review_state="stale"))
+ clean = list(run_queries.list_runs_for_team(team.id, review_state="clean"))
+
+ assert len(stale) == 0
+ clean_shas = {r.commit_sha for r in clean}
+ assert "1st" in clean_shas
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRecomputeRun:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=77777, repo_full_name="org/test-repo")
+
+ def _create_completed_run(self, repo, mocker, identifiers_and_hashes, baseline=None, metadata=None):
+ snapshots = [SnapshotManifestItem(identifier=ident, content_hash=h) for ident, h in identifiers_and_hashes]
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="my-branch",
+ pr_number=1,
+ snapshots=snapshots,
+ metadata=metadata or {},
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=(baseline or {}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ mocker.patch("products.visual_review.backend.logic.ci_status._post_commit_status")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+ run.refresh_from_db()
+ return run
+
+ def test_recompute_run_updates_counts_after_quarantine(self, repo, team, mocker):
+ from products.visual_review.backend.models import QuarantinedIdentifier
+
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1"), ("Card", "h2")],
+ baseline={"Button": "old1", "Card": "old2"},
+ )
+ assert run.changed_count == 2
+
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Button",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ )
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Card",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ )
+
+ result = runs.recompute_run(run.id, team_id=team.id)
+
+ assert result["counts_changed"] is True
+ run.refresh_from_db()
+ assert run.changed_count == 0
+
+ def test_recompute_run_no_change_without_quarantine(self, repo, team, mocker):
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1")],
+ baseline={"Button": "old1"},
+ )
+
+ result = runs.recompute_run(run.id, team_id=team.id)
+
+ assert result["counts_changed"] is False
+ assert "CI job ID not available" in result["ci_rerun_error"]
+
+ def test_recompute_run_rejects_non_completed_run(self, repo, team, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id, run_type=RunType.STORYBOOK, commit_sha="abc", branch="main", pr_number=1, snapshots=[]
+ ),
+ team_id=repo.team_id,
+ )
+
+ with pytest.raises(ValueError, match="Can only recompute completed runs"):
+ runs.recompute_run(run.id, team_id=team.id)
+
+ def test_recompute_run_rejects_approved_run(self, repo, team, user, mocker):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1")],
+ baseline={"Button": "old1"},
+ )
+ approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
+
+ with pytest.raises(ValueError, match="already approved"):
+ runs.recompute_run(run.id, team_id=team.id)
+
+ def test_recompute_run_reports_missing_ci_metadata(self, repo, team, mocker):
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1")],
+ baseline={"Button": "old1"},
+ )
+
+ result = runs.recompute_run(run.id, team_id=team.id)
+
+ assert result["ci_rerun_triggered"] is False
+ assert "CI job ID not available" in result["ci_rerun_error"]
+
+ def test_recompute_run_triggers_ci_rerun(self, repo, team, mocker):
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1")],
+ baseline={"Button": "old1"},
+ metadata={"github_check_run_id": "72855643533"},
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.ci_status._rerun_github_job",
+ return_value=(True, None),
+ )
+
+ result = runs.recompute_run(run.id, team_id=team.id)
+
+ assert result["ci_rerun_triggered"] is True
+ assert result["ci_rerun_error"] is None
+
+ def test_recompute_run_handles_ci_rerun_failure(self, repo, team, mocker):
+ run = self._create_completed_run(
+ repo,
+ mocker,
+ identifiers_and_hashes=[("Button", "h1")],
+ baseline={"Button": "old1"},
+ metadata={"github_check_run_id": "72855643533"},
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.ci_status._rerun_github_job",
+ return_value=(False, "GitHub API returned 403 when rerunning job"),
+ )
+
+ result = runs.recompute_run(run.id, team_id=team.id)
+
+ assert result["ci_rerun_triggered"] is False
+ assert "403" in result["ci_rerun_error"]
diff --git a/products/visual_review/backend/tests/logic/test_toleration.py b/products/visual_review/backend/tests/logic/test_toleration.py
new file mode 100644
index 000000000000..29b479b1de67
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_toleration.py
@@ -0,0 +1,158 @@
+"""Unit tests for logic/toleration.py — Tolerated hashes."""
+
+import pytest
+
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import RunType, SnapshotResult
+from products.visual_review.backend.logic import artifact_store, repos, runs, toleration
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestToleratedHashes:
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99997, repo_full_name="org/test-tol")
+
+ def _create_completed_run(
+ self, repo, mocker, identifier="Button", current_hash="new_hash", baseline_hash="old_hash"
+ ):
+ artifact_store.get_or_create_artifact(
+ repo_id=repo.id, content_hash=current_hash, storage_path=f"p/{current_hash}"
+ )
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier=identifier, content_hash=current_hash)],
+ baseline_hashes={identifier: baseline_hash},
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({identifier: baseline_hash}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+ return run
+
+ def test_mark_snapshot_as_tolerated(self, repo, user, mocker):
+ run = self._create_completed_run(repo, mocker)
+ snapshot = run.snapshots.first()
+ assert snapshot.result == SnapshotResult.CHANGED
+
+ updated = toleration.mark_snapshot_as_tolerated(run.id, snapshot.id, user.id, repo.team_id)
+
+ assert updated.result == SnapshotResult.CHANGED # result stays technical truth
+ assert updated.review_state == "tolerated"
+ assert updated.reviewed_by_id == user.id
+ assert updated.tolerated_hash_match is not None
+ assert updated.tolerated_hash_match.alternate_hash == "new_hash"
+ assert updated.tolerated_hash_match.baseline_hash == "old_hash"
+ assert updated.tolerated_hash_match.reason == "human"
+
+ def test_mark_unchanged_snapshot_rejected(self, repo, user, mocker):
+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="same", storage_path="p/same")
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="same")],
+ baseline_hashes={"Button": "same"},
+ ),
+ team_id=repo.team_id,
+ )
+ mocker.patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"Button": "same"}, 0),
+ )
+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
+ runs.complete_run(run.id)
+ runs.finish_processing(run.id)
+
+ snapshot = run.snapshots.first()
+ assert snapshot is not None
+ 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",
+ )
+
+ # Run with the same hashes — should be classified UNCHANGED via cache
+ run = self._create_completed_run(repo, mocker)
+ snapshot = run.snapshots.first()
+
+ assert snapshot.result == SnapshotResult.UNCHANGED
+ assert snapshot.classification_reason == "tolerated_hash"
+ assert snapshot.tolerated_hash_match is not None
+
+ def test_tolerated_hash_expires_on_baseline_change(self, repo, user, mocker):
+ from products.visual_review.backend.models import ToleratedHash
+
+ # Tolerated hash tied to OLD baseline
+ ToleratedHash.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Button",
+ baseline_hash="old_hash",
+ alternate_hash="new_hash",
+ reason="auto_threshold",
+ )
+
+ # Run with a DIFFERENT baseline — tolerated hash should not match
+ run = self._create_completed_run(repo, mocker, baseline_hash="updated_baseline")
+ snapshot = run.snapshots.first()
+
+ assert snapshot.result == SnapshotResult.CHANGED
+ assert snapshot.classification_reason == ""
+ assert snapshot.tolerated_hash_match is None
+
+ def test_get_tolerated_hashes_for_identifier(self, repo):
+ from products.visual_review.backend.models import ToleratedHash
+
+ ToleratedHash.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Button",
+ baseline_hash="b1",
+ alternate_hash="c1",
+ reason="auto_threshold",
+ )
+ ToleratedHash.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Button",
+ baseline_hash="b1",
+ alternate_hash="c2",
+ reason="human",
+ )
+ ToleratedHash.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Other",
+ baseline_hash="b1",
+ alternate_hash="c3",
+ reason="auto_threshold",
+ )
+
+ results = toleration.get_tolerated_hashes_for_identifier(repo.id, "Button")
+ assert len(results) == 2
+ assert {r.alternate_hash for r in results} == {"c1", "c2"}
diff --git a/products/visual_review/backend/tests/logic/test_uploads.py b/products/visual_review/backend/tests/logic/test_uploads.py
new file mode 100644
index 000000000000..a7f772e84b4b
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_uploads.py
@@ -0,0 +1,190 @@
+"""Unit tests for logic/uploads.py — Upload verification and artifact creation."""
+
+import pytest
+
+from django.db import connections
+from django.test.utils import CaptureQueriesContext
+
+from products.visual_review.backend.db import WRITER_DB
+from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
+from products.visual_review.backend.facade.enums import RunType
+from products.visual_review.backend.logic import artifact_store, errors, repos, runs, uploads
+from products.visual_review.backend.models import Run, RunSnapshot
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestVerifyUploadsAndCreateArtifacts:
+ """Server-side hash integrity for uploaded PNGs."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=42424, repo_full_name="org/vr")
+
+ def _png(self, color: tuple[int, int, int, int]) -> bytes:
+ import io as _io
+
+ from PIL import Image as _Image
+
+ img = _Image.new("RGBA", (8, 8), color)
+ buf = _io.BytesIO()
+ img.save(buf, format="PNG")
+ return buf.getvalue()
+
+ def test_creates_artifact_with_server_computed_hash(self, repo, mocker):
+ from products.visual_review.backend.hashing import hash_image
+
+ png = self._png((10, 20, 30, 255))
+ server_hash = hash_image(png)
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="sha",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Card", content_hash=server_hash)],
+ ),
+ team_id=repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.storage.ArtifactStorage.read",
+ return_value=png,
+ )
+
+ created = uploads.verify_uploads_and_create_artifacts(run.id)
+
+ assert created == 1
+ artifact = artifact_store.get_artifact(repo.id, server_hash)
+ assert artifact is not None
+ assert artifact.content_hash == server_hash
+ assert 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[SnapshotManifestItem] = []
+ 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(
+ SnapshotManifestItem(identifier=f"Card-{color_offset}-{index}", content_hash=content_hash)
+ )
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha=f"sha-{count}-{color_offset}",
+ branch="main",
+ pr_number=None,
+ snapshots=snapshots,
+ ),
+ team_id=repo.team_id,
+ )
+ 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:
+ uploads.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:
+ uploads.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(artifact_store, "ARTIFACT_HASH_BATCH_SIZE", 2)
+ snapshots: list[SnapshotManifestItem] = []
+ for index, color in enumerate([(10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255)]):
+ content_hash = hash_image(self._png(color))
+ artifact_store.get_or_create_artifact(repo.id, content_hash, f"visual_review/{content_hash}")
+ snapshots.append(SnapshotManifestItem(identifier=f"Card-{index}", content_hash=content_hash))
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="sha-retry",
+ branch="main",
+ pr_number=None,
+ snapshots=snapshots,
+ ),
+ team_id=repo.team_id,
+ )
+
+ assert uploads.verify_uploads_and_create_artifacts(run.id) == 0
+ assert RunSnapshot.objects.filter(run=run, current_artifact__isnull=False).count() == 3
+
+ def test_hash_mismatch_raises_and_persists_no_artifacts(self, repo, mocker):
+ # Two snapshots: first verifies cleanly, second has a mismatched claim.
+ # The two-pass split must prevent the first artifact from being written
+ # before the second is checked.
+ from products.visual_review.backend.hashing import hash_image
+
+ png_a = self._png((255, 0, 0, 255))
+ png_b = self._png((0, 0, 255, 255))
+ good_hash = hash_image(png_a)
+ bad_claim = "f" * 64 # nothing hashes to this
+
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="sha",
+ branch="main",
+ pr_number=None,
+ snapshots=[
+ SnapshotManifestItem(identifier="Good", content_hash=good_hash),
+ SnapshotManifestItem(identifier="Bad", content_hash=bad_claim),
+ ],
+ ),
+ team_id=repo.team_id,
+ )
+
+ def _read(self, content_hash):
+ return {good_hash: png_a, bad_claim: png_b}.get(content_hash)
+
+ mocker.patch("products.visual_review.backend.storage.ArtifactStorage.read", autospec=True, side_effect=_read)
+
+ with pytest.raises(errors.HashIntegrityError):
+ uploads.verify_uploads_and_create_artifacts(run.id)
+
+ assert artifact_store.get_artifact(repo.id, good_hash) is None
+ assert artifact_store.get_artifact(repo.id, bad_claim) is None
+
+ def test_corrupt_png_raises_hash_integrity_error(self, repo, mocker):
+ run, _ = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="sha",
+ branch="main",
+ pr_number=None,
+ snapshots=[SnapshotManifestItem(identifier="Card", content_hash="a" * 64)],
+ ),
+ team_id=repo.team_id,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.storage.ArtifactStorage.read",
+ return_value=b"not a png",
+ )
+
+ with pytest.raises(errors.HashIntegrityError):
+ uploads.verify_uploads_and_create_artifacts(run.id)
diff --git a/products/visual_review/backend/tests/test_api.py b/products/visual_review/backend/tests/test_api.py
index 6752ade9f84f..a94d4b0f0de8 100644
--- a/products/visual_review/backend/tests/test_api.py
+++ b/products/visual_review/backend/tests/test_api.py
@@ -5,7 +5,6 @@ from uuid import UUID, uuid4
import pytest
from unittest.mock import patch
-from products.visual_review.backend import logic
from products.visual_review.backend.facade import api
from products.visual_review.backend.facade.contracts import (
ApproveRunInput,
@@ -15,6 +14,7 @@ from products.visual_review.backend.facade.contracts import (
UpdateRepoInput,
)
from products.visual_review.backend.facade.enums import RunType, SnapshotResult
+from products.visual_review.backend.logic import artifact_store, errors, quarantine, runs
from products.visual_review.backend.models import Run
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -219,7 +219,7 @@ class TestRunAPI:
),
team_id=repo.team_id,
)
- logic.quarantine_identifier(
+ quarantine.quarantine_identifier(
repo_id=repo.id,
identifier="Button",
run_type=RunType.STORYBOOK,
@@ -303,8 +303,8 @@ class TestRunAPI:
@patch("products.visual_review.backend.tasks.tasks.emit_run_processing_metrics.delay")
@patch(
- "products.visual_review.backend.logic.verify_uploads_and_create_artifacts",
- side_effect=logic.HashIntegrityError("hash mismatch"),
+ "products.visual_review.backend.logic.uploads.verify_uploads_and_create_artifacts",
+ side_effect=errors.HashIntegrityError("hash mismatch"),
)
@patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
def test_complete_run_hash_integrity_failure_emits_terminal_metrics(
@@ -359,7 +359,7 @@ class TestApproveRunAPI:
def test_approve_run(self, repo, user):
# Create artifact first (directly via logic since API no longer exposes this)
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=repo.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -381,13 +381,13 @@ class TestApproveRunAPI:
# Classification happens at complete_run time
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
- logic.finish_processing(create_result.run_id)
+ runs.complete_run(create_result.run_id)
+ runs.finish_processing(create_result.run_id)
# Per-snapshot approval is DB only — no run-level finalization
result = api.approve_snapshots(
diff --git a/products/visual_review/backend/tests/test_baselines.py b/products/visual_review/backend/tests/test_baselines.py
index 1e7da2debfbf..d43f21c7d38e 100644
--- a/products/visual_review/backend/tests/test_baselines.py
+++ b/products/visual_review/backend/tests/test_baselines.py
@@ -456,7 +456,7 @@ class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
assert entry.baseline_change_count == 0
def test_truncation_at_cap(self):
- # Use a tiny cap for speed. logic.get_baselines_overview imports the
+ # Use a tiny cap for speed. baseline_overview.get_baselines_overview imports the
# constant lazily, so patching contracts is enough.
run = _mk_run(self.repo)
for i in range(7):
diff --git a/products/visual_review/backend/tests/test_classifier.py b/products/visual_review/backend/tests/test_classifier.py
index b5f9683eeadc..918cbc11797f 100644
--- a/products/visual_review/backend/tests/test_classifier.py
+++ b/products/visual_review/backend/tests/test_classifier.py
@@ -303,7 +303,7 @@ 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 logic.complete_run."""
+ """Mirrors the tolerated hash query in runs.complete_run."""
from django.db.models import Q
now = timezone.now()
diff --git a/products/visual_review/backend/tests/test_gating.py b/products/visual_review/backend/tests/test_gating.py
index b60c88f77edc..4da68fcea246 100644
--- a/products/visual_review/backend/tests/test_gating.py
+++ b/products/visual_review/backend/tests/test_gating.py
@@ -20,10 +20,10 @@ import pytest
from parameterized import parameterized
-from products.visual_review.backend import logic
from products.visual_review.backend.facade import api
from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
from products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResult
+from products.visual_review.backend.logic import approvals, artifact_store, repos, runs, toleration
from products.visual_review.backend.models import QuarantinedIdentifier, Run
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -61,8 +61,8 @@ class TestGatingInvariants:
self.team = team
self.user = user
self.mocker = mocker
- self.repo = logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test-gating")
- mocker.patch("products.visual_review.backend.logic._post_commit_status")
+ self.repo = repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test-gating")
+ mocker.patch("products.visual_review.backend.logic.ci_status._post_commit_status")
mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
def _build_run(self, result: str, action: str | None, purpose: str = "review") -> Run:
@@ -81,11 +81,11 @@ class TestGatingInvariants:
baseline = {"target": "same_hash"}
self.mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
return_value=(baseline, 0),
)
- run, _ = logic.create_run(
+ run, _ = runs.create_run(
CreateRunInput(
repo_id=self.repo.id,
run_type=RunType.STORYBOOK,
@@ -97,10 +97,10 @@ class TestGatingInvariants:
),
team_id=self.team.id,
)
- logic.complete_run(run.id)
+ runs.complete_run(run.id)
run.refresh_from_db()
if run.status == RunStatus.PROCESSING:
- logic.finish_processing(run.id)
+ runs.finish_processing(run.id)
run.refresh_from_db()
if action == "quarantine":
@@ -113,19 +113,19 @@ class TestGatingInvariants:
)
elif action == "tolerate":
snapshot = run.snapshots.get(identifier="target")
- logic.mark_snapshot_as_tolerated(run.id, snapshot.id, self.user.id, self.team.id)
+ toleration.mark_snapshot_as_tolerated(run.id, snapshot.id, self.user.id, self.team.id)
elif action == "approve":
snapshot = run.snapshots.get(identifier="target")
if result == "removed":
snapshot.review_state = ReviewState.APPROVED
snapshot.save(update_fields=["review_state"])
else:
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=self.repo.id,
content_hash=snapshot.current_hash,
storage_path=f"p/{snapshot.current_hash}",
)
- logic.approve_snapshots(
+ approvals.approve_snapshots(
run_id=run.id,
user_id=self.user.id,
approved_snapshots=[{"identifier": "target", "new_hash": snapshot.current_hash}],
@@ -136,21 +136,21 @@ class TestGatingInvariants:
@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)
+ recompute_result = runs.recompute_run(run.id, team_id=self.team.id)
gate_passes = recompute_result["unresolved"] == 0
assert gate_passes is expected_gate_passes
@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)
+ runs.recompute_run(run.id, team_id=self.team.id)
run.refresh_from_db()
assert run.changed_count == expected_changed_count
@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)
+ runs.recompute_run(run.id, team_id=self.team.id)
snapshot = run.snapshots.get(identifier="target")
snapshot.refresh_from_db()
@@ -159,9 +159,9 @@ class TestGatingInvariants:
@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)
+ runs.recompute_run(run.id, team_id=self.team.id)
- second = logic.recompute_run(run.id, team_id=self.team.id)
+ second = runs.recompute_run(run.id, team_id=self.team.id)
assert second["counts_changed"] is False
def test_observe_run_summary_never_gates(self):
diff --git a/products/visual_review/backend/tests/test_github_integration.py b/products/visual_review/backend/tests/test_github_integration.py
index 8768bb4e5d54..005691901309 100644
--- a/products/visual_review/backend/tests/test_github_integration.py
+++ b/products/visual_review/backend/tests/test_github_integration.py
@@ -19,8 +19,8 @@ from unittest.mock import MagicMock
import yaml
import responses
-from products.visual_review.backend import logic
from products.visual_review.backend.facade.enums import RunStatus, SnapshotResult
+from products.visual_review.backend.logic import approvals, errors, toleration
from products.visual_review.backend.models import Artifact, Repo, Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -370,7 +370,7 @@ class TestGitHubCommitOnApprove:
"""
run = run_with_changes
- result = logic.finalize_run(
+ result = approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -415,17 +415,17 @@ class TestGitHubCommitOnApprove:
run = run_with_changes
# Mark each snapshot reviewed in a separate DB-only call, then finalize with no list.
- logic.approve_snapshots(
+ approvals.approve_snapshots(
run_id=run.id,
user_id=user.id,
approved_snapshots=[{"identifier": "button--primary", "new_hash": "abc123hash"}],
)
- logic.approve_snapshots(
+ approvals.approve_snapshots(
run_id=run.id,
user_id=user.id,
approved_snapshots=[{"identifier": "card--default", "new_hash": "def456hash"}],
)
- logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)
+ approvals.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)
parsed = yaml.safe_load((local_git_repo / ".snapshots.yml").read_text())
# Both land — the old explicit-list path would have dropped the one not in the final call.
@@ -445,9 +445,9 @@ class TestGitHubCommitOnApprove:
current hash into snapshots.yml (and approve_all must not flip it to approved)."""
run = run_with_changes
card = run.snapshots.get(identifier="card--default")
- logic.mark_snapshot_as_tolerated(run.id, card.id, user.id, run.team_id)
+ toleration.mark_snapshot_as_tolerated(run.id, card.id, user.id, run.team_id)
- logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=True)
+ approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=True)
parsed = yaml.safe_load((local_git_repo / ".snapshots.yml").read_text())
assert "abc123hash" in parsed["snapshots"]["button--primary"]["hash"]
@@ -493,7 +493,7 @@ class TestGitHubCommitOnApprove:
result=SnapshotResult.REMOVED,
)
- result = logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)
+ result = approvals.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)
assert result.approved is True
parsed = yaml.safe_load(snapshots_file.read_text())
@@ -527,7 +527,7 @@ class TestGitHubCommitOnApprove:
run.commit_sha = _get_head_sha(local_git_repo)
run.save()
- logic.finalize_run(
+ approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -561,8 +561,8 @@ class TestGitHubCommitOnApprove:
subprocess.run(["git", "commit", "-m", "new commit"], cwd=local_git_repo, check=True)
# Now the run's commit_sha doesn't match HEAD
- with pytest.raises(logic.PRSHAMismatchError) as exc_info:
- logic.finalize_run(
+ with pytest.raises(errors.PRSHAMismatchError) as exc_info:
+ approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -604,7 +604,7 @@ class TestGitHubCommitOnApprove:
sensitive_config={"user_access_token": "ghu_fake"},
)
- logic.finalize_run(
+ approvals.finalize_run(
run_id=run_with_changes.id,
user_id=user.id,
approve_all=True,
@@ -633,7 +633,7 @@ class TestGitHubCommitOnApprove:
run = run_with_changes
# This should succeed without GitHub mocks
- result = logic.finalize_run(
+ result = approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -681,7 +681,7 @@ class TestGitHubCommitOnApprove:
)
# Should succeed without GitHub interaction
- result = logic.finalize_run(
+ result = approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -712,7 +712,7 @@ class TestGitHubCommitOnApprove:
assert s.reviewed_by_id is None
assert s.approved_hash == ""
- logic.finalize_run(
+ approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
@@ -770,8 +770,8 @@ class TestGitHubIntegrationErrors:
result=SnapshotResult.CHANGED,
)
- with pytest.raises(logic.GitHubIntegrationNotFoundError):
- logic.finalize_run(
+ with pytest.raises(errors.GitHubIntegrationNotFoundError):
+ approvals.finalize_run(
run_id=run.id,
user_id=user.id,
approve_all=True,
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
deleted file mode 100644
index 49b9d712bfa6..000000000000
--- a/products/visual_review/backend/tests/test_logic.py
+++ /dev/null
@@ -1,3284 +0,0 @@
-"""Unit tests for visual_review business logic."""
-
-from datetime import timedelta
-
-import pytest
-
-from django.db import connections
-from django.test.utils import CaptureQueriesContext
-from django.utils import timezone
-
-from parameterized import parameterized
-
-from products.visual_review.backend import logic
-from products.visual_review.backend.db import WRITER_DB
-from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
-from products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, RunStatus, RunType, SnapshotResult
-from products.visual_review.backend.models import Repo, Run, RunSnapshot
-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestProjectOperations:
- def test_create_repo(self, team):
- repo = logic.create_repo(team_id=team.id, repo_external_id=12345, repo_full_name="org/my-repo")
-
- assert repo.team_id == team.id
- assert repo.repo_external_id == 12345
- assert repo.repo_full_name == "org/my-repo"
-
- def test_get_repo(self, team):
- repo = logic.create_repo(team_id=team.id, repo_external_id=11111, repo_full_name="org/test")
-
- retrieved = logic.get_repo(repo.id, team_id=team.id)
-
- assert retrieved.id == repo.id
- assert retrieved.repo_full_name == "org/test"
-
- def test_get_repo_not_found(self, team):
- import uuid
-
- with pytest.raises(logic.RepoNotFoundError):
- logic.get_repo(uuid.uuid4(), team_id=team.id)
-
- def test_list_repos_for_team(self, team):
- logic.create_repo(team_id=team.id, repo_external_id=111, repo_full_name="org/first")
- logic.create_repo(team_id=team.id, repo_external_id=222, repo_full_name="org/second")
-
- projects = logic.list_repos_for_team(team.id)
-
- assert len(projects) == 2
- names = {p.repo_full_name for p in projects}
- assert names == {"org/first", "org/second"}
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestArtifactOperations:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
-
- def test_get_or_create_artifact_creates_new(self, repo):
- artifact, created = logic.get_or_create_artifact(
- repo_id=repo.id,
- content_hash="abc123",
- storage_path="visual_review/abc123",
- width=100,
- height=200,
- size_bytes=5000,
- )
-
- assert created is True
- assert artifact.content_hash == "abc123"
- assert artifact.width == 100
- assert artifact.height == 200
- assert artifact.size_bytes == 5000
-
- def test_get_or_create_artifact_returns_existing(self, repo):
- artifact1, created1 = logic.get_or_create_artifact(
- repo_id=repo.id,
- content_hash="abc123",
- storage_path="visual_review/abc123",
- )
- artifact2, created2 = logic.get_or_create_artifact(
- repo_id=repo.id,
- content_hash="abc123",
- storage_path="visual_review/abc123",
- )
-
- assert created1 is True
- assert created2 is False
- assert artifact1.id == artifact2.id
-
- def test_get_artifact(self, repo):
- logic.get_or_create_artifact(
- repo_id=repo.id,
- content_hash="xyz789",
- storage_path="visual_review/xyz789",
- )
-
- artifact = logic.get_artifact(repo.id, "xyz789")
-
- assert artifact is not None
- assert artifact.content_hash == "xyz789"
-
- def test_get_artifact_not_found(self, repo):
- artifact = logic.get_artifact(repo.id, "nonexistent")
-
- assert artifact is None
-
- def test_find_missing_hashes(self, repo):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="exists1", storage_path="p/exists1")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="exists2", storage_path="p/exists2")
-
- missing = logic.find_missing_hashes(repo.id, ["exists1", "missing1", "exists2", "missing2"])
-
- assert set(missing) == {"missing1", "missing2"}
-
- def test_find_missing_hashes_all_exist(self, repo):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="a", storage_path="p/a")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="b", storage_path="p/b")
-
- missing = logic.find_missing_hashes(repo.id, ["a", "b"])
-
- assert missing == []
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestRunOperations:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
-
- def test_create_run_basic(self, repo):
- run, uploads = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123def456",
- branch="main",
- pr_number=42,
- snapshots=[
- SnapshotManifestItem(identifier="Button-primary", content_hash="hash1"),
- SnapshotManifestItem(identifier="Button-secondary", content_hash="hash2"),
- ],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- assert run.repo_id == repo.id
- assert run.run_type == RunType.STORYBOOK
- assert run.commit_sha == "abc123def456"
- assert run.branch == "main"
- assert run.pr_number == 42
- assert run.status == RunStatus.PENDING
- assert run.total_snapshots == 2
- # uploads is a list of dicts with content_hash, url, fields
- upload_hashes = {u["content_hash"] for u in uploads}
- assert upload_hashes == {"hash1", "hash2"}
-
- def test_create_run_with_existing_artifacts(self, repo):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="existing", storage_path="p/existing")
-
- run, uploads = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.PLAYWRIGHT,
- commit_sha="abc",
- branch="feat",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="snap1", content_hash="existing"),
- SnapshotManifestItem(identifier="snap2", content_hash="new"),
- ],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- # Only "new" needs upload, "existing" already has artifact
- assert len(uploads) == 1
- assert uploads[0]["content_hash"] == "new"
-
- def test_create_run_with_baselines(self, repo, mocker):
- baseline_artifact, _ = logic.get_or_create_artifact(
- repo_id=repo.id, content_hash="baseline_hash", storage_path="p/baseline"
- )
-
- run, _uploads = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
- baseline_hashes={"Button": "baseline_hash"},
- ),
- team_id=repo.team_id,
- )
-
- # Classification happens at complete_run time, not create_run time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"Button": "baseline_hash"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
-
- snapshot = run.snapshots.first()
- assert snapshot is not None
- assert snapshot.baseline_artifact_id == baseline_artifact.id
- assert snapshot.result == SnapshotResult.CHANGED
-
- def test_create_run_snapshot_results(self, repo, mocker):
- baseline_artifact, _ = logic.get_or_create_artifact(
- repo_id=repo.id, content_hash="same_hash", storage_path="p/same"
- )
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="unchanged", content_hash="same_hash"),
- SnapshotManifestItem(identifier="new", content_hash="brand_new"),
- SnapshotManifestItem(identifier="changed", content_hash="different"),
- ],
- baseline_hashes={
- "unchanged": "same_hash",
- "changed": "old_hash",
- },
- ),
- team_id=repo.team_id,
- )
-
- # Classification happens at complete_run time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"unchanged": "same_hash", "changed": "old_hash"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
-
- snapshots = {s.identifier: s for s in run.snapshots.all()}
- assert snapshots["unchanged"].result == SnapshotResult.UNCHANGED
- assert snapshots["new"].result == SnapshotResult.NEW
- assert snapshots["changed"].result == SnapshotResult.CHANGED
-
- def test_create_run_empty(self, repo):
- run, uploads = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- ),
- team_id=repo.team_id,
- )
-
- assert run.total_snapshots == 0
- assert run.changed_count == 0
- assert run.new_count == 0
- assert run.removed_count == 0
- assert run.snapshots.count() == 0
- assert len(uploads) == 0
-
- def test_add_snapshots_to_run(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- ),
- team_id=repo.team_id,
- )
- assert run.total_snapshots == 0
-
- # Shard 1
- added, _uploads = logic.add_snapshots_to_run(
- run_id=run.id,
- team_id=repo.team_id,
- snapshots=[{"identifier": "btn", "content_hash": "h1"}],
- )
- assert added == 1
- run.refresh_from_db()
- assert run.total_snapshots == 1
- assert run.new_count == 1
-
- # Shard 2
- added, _uploads = logic.add_snapshots_to_run(
- run_id=run.id,
- team_id=repo.team_id,
- snapshots=[{"identifier": "card", "content_hash": "h2"}],
- )
- assert added == 1
- run.refresh_from_db()
- assert run.total_snapshots == 2
- assert run.new_count == 2
- assert run.snapshots.count() == 2
-
- def test_add_snapshots_idempotent(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- ),
- team_id=repo.team_id,
- )
-
- for _ in range(2):
- logic.add_snapshots_to_run(
- run_id=run.id,
- team_id=repo.team_id,
- snapshots=[{"identifier": "btn", "content_hash": "h1"}],
- )
-
- assert run.snapshots.count() == 1
-
- def test_add_snapshots_rejects_non_pending(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- ),
- team_id=repo.team_id,
- )
- logic.finish_processing(run.id)
-
- with pytest.raises(ValueError, match="pending"):
- logic.add_snapshots_to_run(
- run_id=run.id,
- team_id=repo.team_id,
- snapshots=[{"identifier": "btn", "content_hash": "h1"}],
- )
-
- def test_complete_run_detects_removals(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
- ),
- team_id=repo.team_id,
- )
-
- # Mock baseline to include an identifier not in the run
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"kept": "h1", "deleted": "h2"}, 0),
- )
-
- completed = logic.complete_run(run.id)
-
- assert completed.removed_count == 1
- removed = run.snapshots.get(identifier="deleted")
- assert removed.result == SnapshotResult.REMOVED
-
- def test_complete_run_partial_skips_removals_off_default_branch(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="feature-x",
- pr_number=7,
- snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
- is_partial=True,
- ),
- team_id=repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"kept": "h1", "deleted": "h2"}, 0),
- )
- mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=False)
-
- completed = logic.complete_run(run.id)
-
- assert completed.removed_count == 0
- assert not run.snapshots.filter(identifier="deleted").exists()
-
- def test_complete_run_partial_ignored_on_default_branch(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="master",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="kept", content_hash="h1")],
- is_partial=True,
- ),
- team_id=repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"kept": "h1", "deleted": "h2"}, 0),
- )
- mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=True)
-
- completed = logic.complete_run(run.id)
-
- # is_partial must not suppress removal detection on the default branch.
- assert completed.removed_count == 1
- removed = run.snapshots.get(identifier="deleted")
- assert removed.result == SnapshotResult.REMOVED
- # The default-branch correction is persisted, so the run is no longer
- # treated as partial anywhere downstream (status context, UI).
- assert completed.is_partial is False
-
- 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(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="deadbeef123",
- branch="master",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="A", content_hash="h1")],
- ),
- team_id=repo.team_id,
- )
-
- 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(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- purpose="observe",
- ),
- team_id=repo.team_id,
- )
- assert run.purpose == "observe"
-
- def test_approve_rejects_observe_runs(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="btn", content_hash="h1")],
- purpose="observe",
- ),
- team_id=repo.team_id,
- )
- logic.finish_processing(run.id)
-
- with pytest.raises(ValueError, match="Observational"):
- logic.finalize_run(run_id=run.id, user_id=1, approve_all=True)
-
- def test_get_run(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- retrieved = logic.get_run(run.id)
-
- assert retrieved.id == run.id
-
- def test_get_run_not_found(self):
- import uuid
-
- with pytest.raises(logic.RunNotFoundError):
- logic.get_run(uuid.uuid4())
-
- def test_mark_run_processing(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- updated = logic.mark_run_processing(run.id)
-
- assert updated.status == RunStatus.PROCESSING
-
- def test_finish_processing_success(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="changed1", content_hash="h1"),
- SnapshotManifestItem(identifier="new1", content_hash="h2"),
- ],
- baseline_hashes={"changed1": "old"},
- ),
- team_id=repo.team_id,
- )
-
- # Classification happens at complete_run time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"changed1": "old"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
-
- # complete_run leaves the run in PROCESSING when there are changes;
- # finish_processing completes it
- updated = logic.finish_processing(run.id)
-
- assert updated.status == RunStatus.COMPLETED
- assert updated.completed_at is not None
- assert updated.changed_count == 1
- assert updated.new_count == 1
- assert updated.error_message == ""
-
- def test_finish_processing_with_error(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- updated = logic.finish_processing(run.id, error_message="Something failed")
-
- assert updated.status == RunStatus.FAILED
- assert updated.error_message == "Something failed"
-
- def test_update_run_counts_reads_and_writes_through_requested_db(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- snapshot_queryset = mocker.Mock()
- snapshot_queryset.values.return_value.annotate.return_value = [
- {"result": SnapshotResult.CHANGED, "n": 2},
- {"result": SnapshotResult.NEW, "n": 1},
- ]
- snapshot_manager = mocker.Mock()
- snapshot_manager.filter.return_value = snapshot_queryset
-
- run_snapshot_using = mocker.patch.object(logic.RunSnapshot.objects, "using", return_value=snapshot_manager)
- run_save = mocker.patch.object(run, "save")
-
- logic._update_run_counts(run, using=logic.WRITER_DB)
-
- run_snapshot_using.assert_called_once_with(logic.WRITER_DB)
- snapshot_manager.filter.assert_called_once_with(run_id=run.id)
- run_save.assert_called_once_with(
- using=logic.WRITER_DB, update_fields=["changed_count", "new_count", "removed_count"]
- )
- assert run.changed_count == 2
- assert run.new_count == 1
- assert run.removed_count == 0
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestApproveRun:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
-
- def test_approve_run(self, repo, user, mocker):
- current_artifact, _ = logic.get_or_create_artifact(
- repo_id=repo.id, content_hash="new_hash", storage_path="p/new"
- )
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
- baseline_hashes={"Button": "old_hash"},
- ),
- team_id=repo.team_id,
- )
-
- # Classification happens at complete_run time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"Button": "old_hash"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- updated = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)
-
- assert updated.approved is True
- assert updated.review_decision == "human_approved"
- assert updated.approved_at is not None
- assert updated.approved_by_id == user.id
-
- # Result should NOT be mutated - approval is recorded separately
- snapshot = updated.snapshots.first()
- assert snapshot is not None
- assert snapshot.result == SnapshotResult.CHANGED # Result preserved
- assert snapshot.approved_hash == "new_hash" # Approval recorded
- assert snapshot.reviewed_at is not None
- assert snapshot.reviewed_by_id == user.id
-
- def _completed_two_change_run(self, repo, mocker):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="ha", storage_path="p/a")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="hb", storage_path="p/b")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="A", content_hash="ha"),
- SnapshotManifestItem(identifier="B", content_hash="hb"),
- ],
- baseline_hashes={"A": "olda", "B": "oldb"},
- ),
- team_id=repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"A": "olda", "B": "oldb"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
- return run
-
- def test_finalize_requires_full_resolution(self, repo, user, mocker):
- # Finalize is all-or-nothing: it refuses while any changed/new snapshot is unreviewed.
- run = self._completed_two_change_run(repo, mocker)
-
- logic.approve_snapshots(
- run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "A", "new_hash": "ha"}]
- )
- with pytest.raises(logic.RunNotFullyResolvedError, match="B"):
- logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)
-
- # Resolving the rest lets it finalize.
- logic.approve_snapshots(
- run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "B", "new_hash": "hb"}]
- )
- updated = logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)
- assert updated.approved is True
-
- def test_finalize_leaves_tolerated_snapshot_alone(self, repo, user, mocker):
- # A tolerated snapshot resolves the run without being approved or committed.
- run = self._completed_two_change_run(repo, mocker)
- snap_b = run.snapshots.get(identifier="B")
- logic.mark_snapshot_as_tolerated(run.id, snap_b.id, user.id, repo.team_id)
-
- updated = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- assert updated.approved is True
- snapshots = {s.identifier: s for s in updated.snapshots.all()}
- assert snapshots["A"].review_state == ReviewState.APPROVED
- assert snapshots["B"].review_state == ReviewState.TOLERATED # approve_all did not clobber it
-
- def test_finalize_is_idempotent_on_approved_run(self, repo, user, mocker):
- # Re-finalizing an already-finalized run is a no-op — no second commit/status/comment.
- run = self._completed_two_change_run(repo, mocker)
- logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
- approved_at = logic.get_run_with_snapshots(run.id).approved_at
-
- again = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- assert again.approved is True
- assert again.approved_at == approved_at # unchanged — the second call did no work
-
- @pytest.mark.parametrize("add_images", [True, False])
- def test_finalize_always_comments_and_forwards_add_images(self, repo, user, mocker, add_images):
- # The PR comment is always dispatched on finalize; add_images_to_comment_on_pr only
- # controls whether the snapshot images are embedded — forwarded to the task.
- run = self._completed_two_change_run(repo, mocker)
- mocker.patch.object(logic, "_post_commit_status")
- mocker.patch.object(logic.transaction, "on_commit", side_effect=lambda fn, *args, **kwargs: fn())
- delay = mocker.patch("products.visual_review.backend.tasks.tasks.post_approval_comment.delay")
-
- logic.finalize_run(
- run_id=run.id,
- user_id=user.id,
- approve_all=True,
- commit_to_github=True,
- add_images_to_comment_on_pr=add_images,
- )
-
- assert delay.called is True
- assert delay.call_args.args[2] is add_images
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestApproveSnapshots:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99998, repo_full_name="org/test-snap")
-
- def test_approve_single_snapshot_db_only(self, repo, user, mocker):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="new_hash", storage_path="p/new")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
- baseline_hashes={"Button": "old_hash"},
- ),
- team_id=repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"Button": "old_hash"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- updated = logic.approve_snapshots(
- run_id=run.id,
- user_id=user.id,
- approved_snapshots=[{"identifier": "Button", "new_hash": "new_hash"}],
- )
-
- snapshot = updated.snapshots.first()
- assert snapshot is not None
- assert snapshot.review_state == "approved"
- assert snapshot.approved_hash == "new_hash"
-
- # Run-level state should NOT change
- assert updated.approved is False
- assert updated.review_decision == "pending"
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestToleratedHashes:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99997, repo_full_name="org/test-tol")
-
- def _create_completed_run(
- self, repo, mocker, identifier="Button", current_hash="new_hash", baseline_hash="old_hash"
- ):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash=current_hash, storage_path=f"p/{current_hash}")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier=identifier, content_hash=current_hash)],
- baseline_hashes={identifier: baseline_hash},
- ),
- team_id=repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({identifier: baseline_hash}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
- return run
-
- def test_mark_snapshot_as_tolerated(self, repo, user, mocker):
- run = self._create_completed_run(repo, mocker)
- snapshot = run.snapshots.first()
- assert snapshot.result == SnapshotResult.CHANGED
-
- updated = logic.mark_snapshot_as_tolerated(run.id, snapshot.id, user.id, repo.team_id)
-
- assert updated.result == SnapshotResult.CHANGED # result stays technical truth
- assert updated.review_state == "tolerated"
- assert updated.reviewed_by_id == user.id
- assert updated.tolerated_hash_match is not None
- assert updated.tolerated_hash_match.alternate_hash == "new_hash"
- assert updated.tolerated_hash_match.baseline_hash == "old_hash"
- assert updated.tolerated_hash_match.reason == "human"
-
- def test_mark_unchanged_snapshot_rejected(self, repo, user, mocker):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="same", storage_path="p/same")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Button", content_hash="same")],
- baseline_hashes={"Button": "same"},
- ),
- team_id=repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"Button": "same"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- snapshot = run.snapshots.first()
- assert snapshot is not None
- with pytest.raises(ValueError, match="Can only mark CHANGED"):
- logic.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",
- )
-
- # Run with the same hashes — should be classified UNCHANGED via cache
- run = self._create_completed_run(repo, mocker)
- snapshot = run.snapshots.first()
-
- assert snapshot.result == SnapshotResult.UNCHANGED
- assert snapshot.classification_reason == "tolerated_hash"
- assert snapshot.tolerated_hash_match is not None
-
- def test_tolerated_hash_expires_on_baseline_change(self, repo, user, mocker):
- from products.visual_review.backend.models import ToleratedHash
-
- # Tolerated hash tied to OLD baseline
- ToleratedHash.objects.create(
- repo=repo,
- team_id=repo.team_id,
- identifier="Button",
- baseline_hash="old_hash",
- alternate_hash="new_hash",
- reason="auto_threshold",
- )
-
- # Run with a DIFFERENT baseline — tolerated hash should not match
- run = self._create_completed_run(repo, mocker, baseline_hash="updated_baseline")
- snapshot = run.snapshots.first()
-
- assert snapshot.result == SnapshotResult.CHANGED
- assert snapshot.classification_reason == ""
- assert snapshot.tolerated_hash_match is None
-
- def test_get_tolerated_hashes_for_identifier(self, repo):
- from products.visual_review.backend.models import ToleratedHash
-
- ToleratedHash.objects.create(
- repo=repo,
- team_id=repo.team_id,
- identifier="Button",
- baseline_hash="b1",
- alternate_hash="c1",
- reason="auto_threshold",
- )
- ToleratedHash.objects.create(
- repo=repo,
- team_id=repo.team_id,
- identifier="Button",
- baseline_hash="b1",
- alternate_hash="c2",
- reason="human",
- )
- ToleratedHash.objects.create(
- repo=repo,
- team_id=repo.team_id,
- identifier="Other",
- baseline_hash="b1",
- alternate_hash="c3",
- reason="auto_threshold",
- )
-
- results = logic.get_tolerated_hashes_for_identifier(repo.id, "Button")
- assert len(results) == 2
- assert {r.alternate_hash for r in results} == {"c1", "c2"}
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestGetRunSnapshots:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
-
- def test_get_run_snapshots(self, repo):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="A-component", content_hash="h1"),
- SnapshotManifestItem(identifier="B-component", content_hash="h2"),
- SnapshotManifestItem(identifier="C-component", content_hash="h3"),
- ],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- snapshots = logic.get_run_snapshots(run.id)
-
- assert len(snapshots) == 3
- # Should be ordered by identifier
- assert [s.identifier for s in snapshots] == ["A-component", "B-component", "C-component"]
-
-
[email protected]_db(transaction=True, databases=PRODUCT_DATABASES)
-class TestCommitStatusChecks:
- """Test that GitHub commit status checks are posted at state transitions."""
-
- @pytest.fixture
- def github_repo(self, team, mock_github_integration):
- return Repo.objects.create(
- team_id=team.id,
- repo_external_id=55555,
- repo_full_name="test-org/test-repo",
- baseline_file_paths={"storybook": ".snapshots.yml"},
- )
-
- def test_create_run_posts_pending_status(self, github_repo, mock_github_api):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
- baseline_hashes={},
- ),
- team_id=github_repo.team_id,
- )
-
- assert len(mock_github_api.status_checks) == 1
- check = mock_github_api.status_checks[0]
- assert check["state"] == "pending"
- assert check["context"] == "PostHog Visual Review / storybook"
- assert f"/visual_review/runs/{run.id}" in check["target_url"]
-
- def test_complete_run_posts_success_when_no_changes(self, github_repo, mock_github_api, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
- baseline_hashes={"snap": "same"},
- ),
- team_id=github_repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"snap": "same"}, 0),
- )
- logic.complete_run(run.id)
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "success"
- assert statuses[-1]["description"] == "No visual changes"
- # A full run posts to the gating context that branch protection evaluates.
- assert statuses[-1]["context"] == "PostHog Visual Review / storybook"
-
- def test_complete_run_partial_annotates_posted_status(self, github_repo, mock_github_api, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="feature-x",
- pr_number=7,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
- baseline_hashes={"snap": "same"},
- is_partial=True,
- ),
- team_id=github_repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"snap": "same", "deleted": "h2"}, 0),
- )
- mocker.patch("products.visual_review.backend.logic._run_is_on_default_branch", return_value=False)
- logic.complete_run(run.id)
-
- # A partial run suppresses removal detection, so it must never satisfy
- # the gating status context branch protection evaluates. It posts to a
- # separate "(partial)" context instead, and the description discloses it.
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "success"
- assert statuses[-1]["description"] == "No visual changes (partial run)"
- assert statuses[-1]["context"] == "PostHog Visual Review / storybook (partial)"
- # The gating context is never posted green by a partial run.
- gating_context = "PostHog Visual Review / storybook"
- assert all(s["context"] != gating_context for s in statuses)
-
- def test_complete_run_posts_comment_when_changes_detected(self, github_repo, mock_github_api, mocker):
- github_repo.enable_pr_comments = True
- github_repo.save(update_fields=["enable_pr_comments"])
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[
- SnapshotManifestItem(identifier="changed", content_hash="new_h"),
- SnapshotManifestItem(identifier="added", content_hash="brand_new"),
- ],
- baseline_hashes={"changed": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"changed": "old_h"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- statuses = mock_github_api.status_checks
- # VR is the gate — unapproved changes post failure
- assert statuses[-1]["state"] == "failure"
- assert "1 changed" in statuses[-1]["description"]
- assert "1 new" in statuses[-1]["description"]
- assert len(mock_github_api.issue_comments) == 1
- assert mock_github_api.issue_comments[0]["action"] == "created"
- comment = mock_github_api.issue_comments[0]["body"]
- assert "Review and approve in PostHog Visual Review" in comment
- assert f"/visual_review/runs/{run.id}" in comment
- # Verify comment ID stored for future updates
- run.refresh_from_db()
- assert run.metadata["github_comment_id"] is not None
-
- def test_subsequent_run_updates_existing_comment(self, github_repo, mock_github_api):
- github_repo.enable_pr_comments = True
- github_repo.save(update_fields=["enable_pr_comments"])
-
- run1, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc111",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="changed", content_hash="new_h")],
- baseline_hashes={"changed": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
- logic.finish_processing(run1.id)
-
- run2, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc222",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="changed", content_hash="newer_h")],
- baseline_hashes={"changed": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
- logic.finish_processing(run2.id)
-
- created = [c for c in mock_github_api.issue_comments if c["action"] == "created"]
- updated = [c for c in mock_github_api.issue_comments if c["action"] == "updated"]
- assert len(created) == 1
- assert len(updated) == 1
- assert f"/visual_review/runs/{run2.id}" in updated[0]["body"]
-
- def test_complete_run_does_not_comment_twice_on_retry(self, github_repo, mock_github_api):
- github_repo.enable_pr_comments = True
- github_repo.save(update_fields=["enable_pr_comments"])
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="changed", content_hash="new_h")],
- baseline_hashes={"changed": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
-
- logic.finish_processing(run.id)
- logic.finish_processing(run.id)
-
- assert len(mock_github_api.issue_comments) == 1
-
- @pytest.mark.parametrize(
- "enable_pr_comments, pr_number, snapshots, baseline_hashes, purpose",
- [
- (
- False,
- 1,
- [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
- {"changed": "old_h"},
- "review",
- ),
- (
- True,
- None,
- [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
- {"changed": "old_h"},
- "review",
- ),
- (True, 1, [SnapshotManifestItem(identifier="snap", content_hash="same")], {"snap": "same"}, "review"),
- (
- True,
- 1,
- [SnapshotManifestItem(identifier="changed", content_hash="new_h")],
- {"changed": "old_h"},
- "observe",
- ),
- ],
- ids=["toggle_off", "no_pr", "no_changes", "observe_purpose"],
- )
- def test_complete_run_does_not_comment(
- self, enable_pr_comments, pr_number, snapshots, baseline_hashes, purpose, github_repo, mock_github_api, mocker
- ):
- if enable_pr_comments:
- github_repo.enable_pr_comments = True
- github_repo.save(update_fields=["enable_pr_comments"])
-
- # Mock baseline for classification at complete time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=(dict(baseline_hashes), 0),
- )
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=pr_number,
- snapshots=snapshots,
- baseline_hashes=baseline_hashes,
- purpose=purpose,
- ),
- team_id=github_repo.team_id,
- )
-
- logic.complete_run(run.id)
-
- assert len(mock_github_api.issue_comments) == 0
-
- def test_complete_run_posts_error_on_failure(self, github_repo, mock_github_api):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[],
- baseline_hashes={},
- ),
- team_id=github_repo.team_id,
- )
-
- logic.finish_processing(run.id, error_message="Diff processing failed")
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "error"
- assert "failed" in statuses[-1]["description"].lower()
- assert len(mock_github_api.issue_comments) == 0
-
- def test_observe_run_with_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):
- # Default-branch (observe) runs are tracking-only: a visual change posts a green,
- # informational status — never a blocking failure — and no review-prompt comment.
- github_repo.enable_pr_comments = True
- github_repo.save(update_fields=["enable_pr_comments"])
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="master",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="changed", content_hash="new_h"),
- SnapshotManifestItem(identifier="added", content_hash="brand_new"),
- ],
- baseline_hashes={"changed": "old_h"},
- purpose="observe",
- ),
- team_id=github_repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"changed": "old_h"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "success"
- assert statuses[-1]["description"] == "Tracking only: 1 changed, 1 new recorded"
- # Observe runs post to a separate, non-gating context. purpose is client-supplied,
- # so greening the gating context would let an observe run bypass branch protection
- # on a PR head SHA — the gating context must never be touched by an observe run.
- assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"
- assert all(s["context"] != "PostHog Visual Review / storybook" for s in statuses)
- assert len(mock_github_api.issue_comments) == 0
-
- def test_observe_run_without_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="master",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
- baseline_hashes={"snap": "same"},
- purpose="observe",
- ),
- team_id=github_repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"snap": "same"}, 0),
- )
- logic.complete_run(run.id)
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "success"
- assert statuses[-1]["description"] == "Tracking only: no visual changes"
- assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"
-
- def test_approve_run_posts_success(self, github_repo, mock_github_api, user):
- logic.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="new_h")],
- baseline_hashes={"snap": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
- logic.finish_processing(run.id)
-
- logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "success"
- assert "approved" in statuses[-1]["description"].lower()
-
- def test_recompute_does_not_green_approved_but_uncommitted(self, github_repo, mock_github_api, user, mocker):
- # Approving in the DB does not commit the baseline, so recompute must keep the gate red —
- # otherwise re-running CI would re-detect the change. Only finalize (which commits) greens it.
- logic.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=github_repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="new_h")],
- baseline_hashes={"snap": "old_h"},
- ),
- team_id=github_repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"snap": "old_h"}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
-
- logic.approve_snapshots(
- run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "snap", "new_hash": "new_h"}]
- )
- logic.recompute_run(run.id, team_id=github_repo.team_id)
-
- statuses = mock_github_api.status_checks
- assert statuses[-1]["state"] == "failure"
- assert "awaiting commit" in statuses[-1]["description"].lower()
-
- def test_no_status_without_github_integration(self, team):
- """Status checks are silently skipped when no GitHub integration exists."""
- repo = logic.create_repo(team_id=team.id, repo_external_id=77777, repo_full_name="org/no-github")
-
- # No mock_github_api/mock_github_integration — should not raise
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- logic.finish_processing(run.id)
-
- def test_no_status_without_repo_full_name(self, team, mock_github_integration, mock_github_api):
- """Status checks are silently skipped when repo has no repo_full_name."""
- repo = Repo.objects.create(
- team_id=team.id,
- repo_external_id=88888,
- repo_full_name="",
- )
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="h1")],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
-
- logic.finish_processing(run.id)
-
- assert len(mock_github_api.status_checks) == 0
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestRunSupersession:
- """When a new run is created for the same (repo, branch, run_type), older runs get superseded."""
-
- @pytest.fixture
- def repo(self, team):
- return Repo.objects.create(team_id=team.id, repo_external_id=66666, repo_full_name="org/test-repo")
-
- def _create_run(self, repo, *, branch="feat/x", run_type=RunType.STORYBOOK, commit_sha="abc"):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=run_type,
- commit_sha=commit_sha,
- branch=branch,
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash=commit_sha)],
- baseline_hashes={},
- ),
- team_id=repo.team_id,
- )
- logic.finish_processing(run.id)
- run.refresh_from_db()
- return run
-
- def test_single_run_not_superseded(self, repo):
- run = self._create_run(repo)
-
- assert run.superseded_by is None
- assert logic.is_run_stale(run) is False
-
- def test_newer_run_supersedes_older(self, repo):
- old = self._create_run(repo, commit_sha="old")
- new = self._create_run(repo, commit_sha="new")
-
- old.refresh_from_db()
- assert old.superseded_by_id == new.id
- assert new.superseded_by is None
-
- def test_supersession_chains(self, repo):
- first = self._create_run(repo, commit_sha="1st")
- second = self._create_run(repo, commit_sha="2nd")
- third = self._create_run(repo, commit_sha="3rd")
-
- first.refresh_from_db()
- second.refresh_from_db()
- # first was superseded by second, then second by third
- # first still points to second (not updated again)
- assert first.superseded_by_id == second.id
- assert second.superseded_by_id == third.id
- assert third.superseded_by is None
-
- def test_different_branches_are_independent(self, repo):
- run_a = self._create_run(repo, branch="feat/a", commit_sha="a")
- self._create_run(repo, branch="feat/b", commit_sha="b")
-
- run_a.refresh_from_db()
- assert run_a.superseded_by is None
-
- def test_different_run_types_are_independent(self, repo):
- run_sb = self._create_run(repo, run_type=RunType.STORYBOOK, commit_sha="a")
- self._create_run(repo, run_type=RunType.PLAYWRIGHT, commit_sha="b")
-
- run_sb.refresh_from_db()
- assert run_sb.superseded_by is None
-
- def test_review_state_filter_excludes_superseded(self, repo, team):
- self._create_run(repo, commit_sha="old")
- self._create_run(repo, commit_sha="new")
-
- current_runs = list(logic.list_runs_for_team(team.id, review_state="needs_review"))
- stale_runs = list(logic.list_runs_for_team(team.id, review_state="stale"))
-
- assert len(current_runs) == 1
- assert current_runs[0].commit_sha == "new"
- assert len(stale_runs) == 1
- assert stale_runs[0].commit_sha == "old"
-
- def test_review_state_counts(self, repo, team):
- self._create_run(repo, commit_sha="old")
- self._create_run(repo, commit_sha="new")
-
- counts = logic.get_review_state_counts(team.id)
-
- assert counts["stale"] == 1
- assert counts["needs_review"] == 1
-
- def test_approve_superseded_run_raises(self, repo, user):
- old = self._create_run(repo, commit_sha="old")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="old", storage_path="p/old")
- self._create_run(repo, commit_sha="new")
-
- old.refresh_from_db()
- with pytest.raises(logic.StaleRunError):
- logic.finalize_run(run_id=old.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- def test_approve_latest_run_succeeds(self, repo, user):
- self._create_run(repo, commit_sha="old")
- newest = self._create_run(repo, commit_sha="new")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="new", storage_path="p/new")
-
- run = logic.finalize_run(run_id=newest.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- assert run.approved is True
-
- def test_approved_run_superseded_but_stays_clean(self, repo, user, team):
- first = self._create_run(repo, commit_sha="1st")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")
- logic.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- self._create_run(repo, commit_sha="2nd")
-
- first.refresh_from_db()
- assert first.superseded_by is not None
- # Approved runs still show in clean filter, not stale
- clean = list(logic.list_runs_for_team(team.id, review_state="clean"))
- assert any(r.id == first.id for r in clean)
-
- def test_clean_run_superseded_but_stays_clean(self, repo, team, mocker):
- clean_run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="clean",
- branch="feat/x",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="snap", content_hash="same")],
- baseline_hashes={"snap": "same"},
- ),
- team_id=repo.team_id,
- )
-
- # Classification happens at complete_run time
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=({"snap": "same"}, 0),
- )
- logic.complete_run(clean_run.id)
-
- self._create_run(repo, commit_sha="next")
-
- clean_run.refresh_from_db()
- assert clean_run.superseded_by is not None
- # Clean runs still show in clean filter, not stale
- clean = list(logic.list_runs_for_team(team.id, review_state="clean"))
- assert any(r.id == clean_run.id for r in clean)
-
- def test_approved_run_shows_in_clean_not_stale(self, repo, team, user):
- first = self._create_run(repo, commit_sha="1st")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")
- logic.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- self._create_run(repo, commit_sha="2nd")
-
- stale = list(logic.list_runs_for_team(team.id, review_state="stale"))
- clean = list(logic.list_runs_for_team(team.id, review_state="clean"))
-
- assert len(stale) == 0
- clean_shas = {r.commit_sha for r in clean}
- assert "1st" in clean_shas
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestQuarantineStamping:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=99996, repo_full_name="org/test-quarantine")
-
- def _create_completed_run(self, repo, mocker, identifiers_and_hashes, baseline=None):
- """Create a run, classify against baseline, and finalize it.
-
- identifiers_and_hashes: list of (identifier, content_hash)
- baseline: dict of identifier -> baseline_hash (for _resolve_baselines mock)
- """
- snapshots = [SnapshotManifestItem(identifier=ident, content_hash=h) for ident, h in identifiers_and_hashes]
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="main",
- pr_number=1,
- snapshots=snapshots,
- ),
- team_id=repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=(baseline or {}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
- return run
-
- def test_finish_processing_stamps_quarantined_snapshots(self, repo, team, mocker):
- from products.visual_review.backend.models import QuarantinedIdentifier
-
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[
- ("Button-primary", "h1"),
- ("Button-secondary", "h2"),
- ("Card-default", "h3"),
- ],
- baseline={"Button-primary": "old1", "Button-secondary": "old2", "Card-default": "old3"},
- )
-
- # Quarantine one identifier
- QuarantinedIdentifier.objects.create(
- repo=repo,
- team_id=team.id,
- identifier="Button-primary",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- )
-
- logic.finish_processing(run.id)
-
- snapshots = {s.identifier: s for s in run.snapshots.all()}
- assert snapshots["Button-primary"].is_quarantined is True
- assert snapshots["Button-secondary"].is_quarantined is False
- assert snapshots["Card-default"].is_quarantined is False
-
- def test_unquarantine_clears_flag_on_approve(self, repo, team, user, mocker):
- from products.visual_review.backend.models import QuarantinedIdentifier
-
- # Create quarantine entry
- QuarantinedIdentifier.objects.create(
- repo=repo,
- team_id=team.id,
- identifier="Button-primary",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- )
-
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button-primary", "h1")],
- baseline={"Button-primary": "old1"},
- )
-
- logic.finish_processing(run.id)
- snapshot = run.snapshots.get(identifier="Button-primary")
- assert snapshot.is_quarantined is True
-
- # Unquarantine the identifier
- logic.unquarantine_identifier(
- repo_id=repo.id, identifier="Button-primary", run_type=RunType.STORYBOOK, team_id=team.id
- )
-
- # Finalize the run — _stamp_quarantine re-evaluates
- logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- snapshot.refresh_from_db()
- assert snapshot.is_quarantined is False
-
- def test_quarantine_excludes_from_changed_count(self, repo, team, mocker):
- from products.visual_review.backend.models import QuarantinedIdentifier
-
- # Quarantine one identifier before finalization
- QuarantinedIdentifier.objects.create(
- repo=repo,
- team_id=team.id,
- identifier="Button-primary",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- )
-
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[
- ("Button-primary", "h1"),
- ("Button-secondary", "h2"),
- ("Card-new", "h3"),
- ],
- baseline={"Button-primary": "old1", "Button-secondary": "old2"},
- )
-
- processed = logic.finish_processing(run.id)
-
- # Button-primary is quarantined — should not count toward changed
- # Button-secondary is changed (not quarantined), Card-new is new (not quarantined)
- assert processed.changed_count == 1 # only Button-secondary
- assert processed.new_count == 1 # only Card-new
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestQuarantineIdentifier:
- """Coverage for `logic.quarantine_identifier` — especially the new
- `source_run_id` behavior (valid run is stored, foreign run is dropped)."""
-
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/test-source-run")
-
- def _mk_run(self, repo: Repo, branch: str = "main") -> Run:
- return Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- run_type=RunType.STORYBOOK,
- branch=branch,
- commit_sha="abc123",
- status=RunStatus.COMPLETED,
- completed_at=timezone.now(),
- )
-
- def test_stores_valid_source_run(self, repo, team, user):
- from products.visual_review.backend.models import QuarantinedIdentifier
-
- run = self._mk_run(repo)
- entry = logic.quarantine_identifier(
- repo_id=repo.id,
- identifier="flake",
- run_type=RunType.STORYBOOK,
- reason="non-deterministic",
- user_id=user.id,
- team_id=team.id,
- source_run_id=run.id,
- )
- # Returned row points at the source run …
- assert entry.source_run_id == run.id
- # … and the persisted row agrees.
- persisted = QuarantinedIdentifier.objects.get(id=entry.id)
- assert persisted.source_run_id == run.id
-
- def test_drops_source_run_from_another_team(self, repo, team, user):
- """A `source_run_id` from a run that doesn't belong to this team/repo
- is silently dropped — the quarantine still gets created, just without
- the cross-team pointer."""
- from posthog.models.team.team import Team
-
- # Sibling team in the same org with its own repo + run.
- other_team = Team.objects.create(organization=team.organization, name="other")
- other_repo = logic.create_repo(team_id=other_team.id, repo_external_id=12121, repo_full_name="org/other-repo")
- foreign_run = Run.objects.create(
- team_id=other_team.id,
- repo=other_repo,
- run_type=RunType.STORYBOOK,
- branch="main",
- commit_sha="xyz789",
- status=RunStatus.COMPLETED,
- completed_at=timezone.now(),
- )
-
- entry = logic.quarantine_identifier(
- repo_id=repo.id,
- identifier="flake",
- run_type=RunType.STORYBOOK,
- reason="non-deterministic",
- user_id=user.id,
- team_id=team.id,
- source_run_id=foreign_run.id,
- )
- assert entry.source_run_id is None
-
- def test_omitting_source_run_leaves_it_null(self, repo, team, user):
- entry = logic.quarantine_identifier(
- repo_id=repo.id,
- identifier="flake",
- run_type=RunType.STORYBOOK,
- reason="non-deterministic",
- user_id=user.id,
- team_id=team.id,
- )
- assert entry.source_run_id is None
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestRecomputeRun:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=77777, repo_full_name="org/test-repo")
-
- def _create_completed_run(self, repo, mocker, identifiers_and_hashes, baseline=None, metadata=None):
- snapshots = [SnapshotManifestItem(identifier=ident, content_hash=h) for ident, h in identifiers_and_hashes]
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="my-branch",
- pr_number=1,
- snapshots=snapshots,
- metadata=metadata or {},
- ),
- team_id=repo.team_id,
- )
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
- return_value=(baseline or {}, 0),
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- mocker.patch("products.visual_review.backend.logic._post_commit_status")
- logic.complete_run(run.id)
- logic.finish_processing(run.id)
- run.refresh_from_db()
- return run
-
- def test_recompute_run_updates_counts_after_quarantine(self, repo, team, mocker):
- from products.visual_review.backend.models import QuarantinedIdentifier
-
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1"), ("Card", "h2")],
- baseline={"Button": "old1", "Card": "old2"},
- )
- assert run.changed_count == 2
-
- QuarantinedIdentifier.objects.create(
- repo=repo,
- team_id=team.id,
- identifier="Button",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- )
- QuarantinedIdentifier.objects.create(
- repo=repo,
- team_id=team.id,
- identifier="Card",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- )
-
- result = logic.recompute_run(run.id, team_id=team.id)
-
- assert result["counts_changed"] is True
- run.refresh_from_db()
- assert run.changed_count == 0
-
- def test_recompute_run_no_change_without_quarantine(self, repo, team, mocker):
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1")],
- baseline={"Button": "old1"},
- )
-
- result = logic.recompute_run(run.id, team_id=team.id)
-
- assert result["counts_changed"] is False
- assert "CI job ID not available" in result["ci_rerun_error"]
-
- def test_recompute_run_rejects_non_completed_run(self, repo, team, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id, run_type=RunType.STORYBOOK, commit_sha="abc", branch="main", pr_number=1, snapshots=[]
- ),
- team_id=repo.team_id,
- )
-
- with pytest.raises(ValueError, match="Can only recompute completed runs"):
- logic.recompute_run(run.id, team_id=team.id)
-
- def test_recompute_run_rejects_approved_run(self, repo, team, user, mocker):
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="h1", storage_path="p/h1")
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1")],
- baseline={"Button": "old1"},
- )
- logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
-
- with pytest.raises(ValueError, match="already approved"):
- logic.recompute_run(run.id, team_id=team.id)
-
- def test_recompute_run_reports_missing_ci_metadata(self, repo, team, mocker):
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1")],
- baseline={"Button": "old1"},
- )
-
- result = logic.recompute_run(run.id, team_id=team.id)
-
- assert result["ci_rerun_triggered"] is False
- assert "CI job ID not available" in result["ci_rerun_error"]
-
- def test_recompute_run_triggers_ci_rerun(self, repo, team, mocker):
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1")],
- baseline={"Button": "old1"},
- metadata={"github_check_run_id": "72855643533"},
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._rerun_github_job",
- return_value=(True, None),
- )
-
- result = logic.recompute_run(run.id, team_id=team.id)
-
- assert result["ci_rerun_triggered"] is True
- assert result["ci_rerun_error"] is None
-
- def test_recompute_run_handles_ci_rerun_failure(self, repo, team, mocker):
- run = self._create_completed_run(
- repo,
- mocker,
- identifiers_and_hashes=[("Button", "h1")],
- baseline={"Button": "old1"},
- metadata={"github_check_run_id": "72855643533"},
- )
-
- mocker.patch(
- "products.visual_review.backend.logic._rerun_github_job",
- return_value=(False, "GitHub API returned 403 when rerunning job"),
- )
-
- result = logic.recompute_run(run.id, team_id=team.id)
-
- assert result["ci_rerun_triggered"] is False
- assert "403" in result["ci_rerun_error"]
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestRerunGithubJob:
- """Tests for _rerun_github_job SHA validation."""
-
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=55555, repo_full_name="org/test-repo")
-
- def _make_run(self, repo: "Repo", commit_sha: str = "abc123def456", workflow_run_id: str | None = "98765") -> "Run":
- metadata: dict = {"github_check_run_id": "72855643533"}
- if workflow_run_id is not None:
- metadata["github_run_id"] = workflow_run_id
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha=commit_sha,
- branch="feature",
- pr_number=1,
- snapshots=[],
- metadata=metadata,
- ),
- team_id=repo.team_id,
- )
- return run
-
- def test_rejects_non_digit_check_run_id(self, repo):
- run = self._make_run(repo)
- success, error = logic._rerun_github_job(run, "not-a-number")
- assert success is False
- assert error == "Invalid check run ID"
-
- def test_rejects_when_workflow_run_id_missing(self, repo):
- run = self._make_run(repo, workflow_run_id=None)
- success, error = logic._rerun_github_job(run, "72855643533")
- assert success is False
- assert error == "Workflow run ID not recorded for this run"
-
- def test_rejects_when_sha_does_not_match(self, repo, mocker):
- run = self._make_run(repo, commit_sha="abc123")
- mock_response = mocker.MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"head_sha": "different_sha_entirely", "run_id": 98765}
- mocker.patch("products.visual_review.backend.logic._github_api_request", return_value=mock_response)
-
- success, error = logic._rerun_github_job(run, "72855643533")
-
- assert success is False
- assert error == "Check run does not belong to this commit"
-
- def test_rejects_when_workflow_run_does_not_match(self, repo, mocker):
- commit_sha = "abc123def456"
- run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
- mock_response = mocker.MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"head_sha": commit_sha, "run_id": 11111}
- mocker.patch("products.visual_review.backend.logic._github_api_request", return_value=mock_response)
-
- success, error = logic._rerun_github_job(run, "72855643533")
-
- assert success is False
- assert error == "CI job does not belong to this run's workflow"
-
- def test_rejects_when_check_run_fetch_fails(self, repo, mocker):
- run = self._make_run(repo)
- mock_response = mocker.MagicMock()
- mock_response.status_code = 404
- mocker.patch("products.visual_review.backend.logic._github_api_request", return_value=mock_response)
-
- success, error = logic._rerun_github_job(run, "72855643533")
-
- assert success is False
- assert error is not None
- assert "404" in error
-
- def test_triggers_rerun_when_sha_and_workflow_match(self, repo, mocker):
- commit_sha = "abc123def456"
- run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
-
- job_response = mocker.MagicMock()
- job_response.status_code = 200
- job_response.json.return_value = {"head_sha": commit_sha, "run_id": 98765}
-
- rerun_response = mocker.MagicMock()
- rerun_response.status_code = 201
-
- mocker.patch(
- "products.visual_review.backend.logic._github_api_request",
- side_effect=[job_response, rerun_response],
- )
-
- success, error = logic._rerun_github_job(run, "72855643533")
-
- assert success is True
- assert error is None
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestRunIsOnDefaultBranch:
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=1234, repo_full_name="org/test-repo")
-
- def _mock_github(self, mocker, default_branch="master"):
- mock_github = mocker.MagicMock()
- mock_github.access_token_expired.return_value = False
- mocker.patch("products.visual_review.backend.logic.get_github_integration_for_repo", return_value=mock_github)
- mocker.patch("products.visual_review.backend.logic._get_default_branch", return_value=default_branch)
-
- def test_true_when_branch_matches_default(self, repo, mocker):
- self._mock_github(mocker, default_branch="main")
- assert logic._run_is_on_default_branch(repo, "main") is True
-
- def test_false_when_branch_differs(self, repo, mocker):
- self._mock_github(mocker, default_branch="main")
- assert logic._run_is_on_default_branch(repo, "feature-x") is False
-
- def test_false_when_no_github_integration(self, repo, mocker):
- mocker.patch(
- "products.visual_review.backend.logic.get_github_integration_for_repo",
- side_effect=logic.GitHubIntegrationNotFoundError("none"),
- )
- assert logic._run_is_on_default_branch(repo, "master") is False
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestMergeBaseBaselineHealing:
- """Tests for _resolve_baselines_with_merge_base healing rebase-corrupted baselines."""
-
- @pytest.fixture
- def repo(self, team):
- 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",
- 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"}
- mock_github.access_token_expired.return_value = False
- mocker.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:
- baselines = merge_base_baseline if merge_base_baseline is not None else branch_baseline
- 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", 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
- )
- return mock_github
-
- def test_no_healing_when_baselines_match(self, repo, mocker):
- baseline = {"A": "h1", "B": "h2"}
- self._mock_github(mocker, branch_baseline=baseline, merge_base_baseline=baseline)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged == baseline
- assert healed == 0
-
- def test_heals_entries_missing_from_branch(self, repo, mocker):
- branch_baseline = {"A": "h1"}
- merge_base_baseline = {"A": "h1", "B": "h2", "C": "h3"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged == {"A": "h1", "B": "h2", "C": "h3"}
- assert healed == 2
-
- def test_branch_wins_on_conflict(self, repo, mocker):
- branch_baseline = {"A": "branch_hash"}
- merge_base_baseline = {"A": "master_hash", "B": "h2"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged["A"] == "branch_hash"
- assert merged["B"] == "h2"
- assert healed == 1
-
- def test_branch_approvals_preserved(self, repo, mocker):
- branch_baseline = {"A": "h1", "NewStory": "new_hash"}
- merge_base_baseline = {"A": "h1"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert "NewStory" in merged
- assert merged["NewStory"] == "new_hash"
- assert healed == 0
-
- def test_skips_merge_base_for_default_branch(self, repo, mocker):
- baseline = {"A": "h1"}
- self._mock_github(mocker, branch_baseline=baseline, default_branch="master")
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "master")
-
- assert merged == baseline
- assert 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)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged == branch_baseline
- assert healed == 0
-
- def test_falls_back_when_merge_base_file_fetch_raises(self, repo, mocker):
- branch_baseline = {"A": "h1"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline={"A": "h1", "B": "h2"})
- mocker.patch(
- "products.visual_review.backend.logic._resolve_baselines_at_ref",
- side_effect=[branch_baseline, Exception("GitHub 500")],
- )
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged == branch_baseline
- assert healed == 0
-
- def test_first_run_both_baselines_empty(self, repo, mocker):
- self._mock_github(mocker, branch_baseline={}, merge_base_baseline={})
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert merged == {}
- assert healed == 0
-
- def test_heals_rebase_scenario_end_to_end(self, repo, mocker):
- """Simulates Paul's bug: rebase replayed bot commit, dropping 8 entries."""
- branch_baseline = {"story1": "h1", "story2": "h2"}
- merge_base_baseline = {
- "story1": "h1",
- "story2": "h2",
- "lost1": "h3",
- "lost2": "h4",
- "lost3": "h5",
- "lost4": "h6",
- "lost5": "h7",
- "lost6": "h8",
- "lost7": "h9",
- "lost8": "h10",
- }
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, "storybook", "my-branch")
-
- assert len(merged) == 10
- assert healed == 8
- assert all(f"lost{i}" in merged for i in range(1, 9))
-
- def test_healing_integrates_with_complete_run(self, repo, mocker):
- """Healed entries classify as unchanged when hashes match."""
- branch_baseline = {"existing": "h1"}
- merge_base_baseline = {"existing": "h1", "healed": "h2"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_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")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="my-branch",
- pr_number=1,
- snapshots=[
- SnapshotManifestItem(identifier="existing", content_hash="h1"),
- SnapshotManifestItem(identifier="healed", content_hash="h2"),
- ],
- ),
- team_id=repo.team_id,
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
-
- snapshots = {s.identifier: s for s in run.snapshots.all()}
- assert snapshots["existing"].result == SnapshotResult.UNCHANGED
- assert snapshots["healed"].result == SnapshotResult.UNCHANGED
-
- 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(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="commit_a_sha",
- branch="master",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="story1", content_hash="h1"),
- SnapshotManifestItem(identifier="story2", content_hash="h2"),
- SnapshotManifestItem(identifier="story3", content_hash="h3"),
- ],
- ),
- team_id=repo.team_id,
- )
-
- 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] = {}
- merge_base_baseline = {"flaky": "master_hash"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="master_hash", storage_path="p/master")
- logic.get_or_create_artifact(repo_id=repo.id, content_hash="branch_hash", storage_path="p/branch")
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc",
- branch="my-branch",
- pr_number=1,
- snapshots=[SnapshotManifestItem(identifier="flaky", content_hash="branch_hash")],
- ),
- team_id=repo.team_id,
- )
- mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")
- logic.complete_run(run.id)
-
- snapshot = run.snapshots.get(identifier="flaky")
- assert snapshot.result == SnapshotResult.CHANGED
- assert snapshot.baseline_hash == "master_hash"
-
- @pytest.mark.parametrize(
- "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", "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",
- ],
- )
- def test_tombstone_excludes_only_approved_removals_on_branch(
- 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,
- 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,
- )
- RunSnapshot.objects.create(
- run=prior_run,
- team_id=team.id,
- identifier="candidate",
- baseline_hash="h1",
- current_hash="",
- result=SnapshotResult.REMOVED,
- review_state=prior_review_state,
- )
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, run_branch)
-
- if expect_tombstoned:
- assert merged == {}
- assert healed == 0
- else:
- assert merged == merge_base_baseline
- assert healed == 1
-
- def test_tombstone_cleared_by_later_re_addition(self, repo, team, mocker):
- """Remove→approve→restore→approve: the re-addition clears the tombstone."""
- branch_baseline: dict[str, str] = {}
- merge_base_baseline = {"story-x": "h1"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- # Run 1: story-x removed and approved
- run1 = Run.objects.create(
- team_id=team.id,
- repo=repo,
- run_type=RunType.STORYBOOK,
- branch="my-branch",
- commit_sha="sha1",
- status=RunStatus.COMPLETED,
- approved=True,
- created_at=timezone.now() - timedelta(hours=2),
- )
- RunSnapshot.objects.create(
- run=run1,
- team_id=team.id,
- identifier="story-x",
- baseline_hash="h1",
- current_hash="",
- result=SnapshotResult.REMOVED,
- review_state=ReviewState.APPROVED,
- )
-
- # Supersede run1 (as create_run would)
- run1.superseded_by = run1
- run1.save(update_fields=["superseded_by"])
-
- # Run 2: story-x re-added and approved as NEW
- run2 = Run.objects.create(
- team_id=team.id,
- repo=repo,
- run_type=RunType.STORYBOOK,
- branch="my-branch",
- commit_sha="sha2",
- status=RunStatus.COMPLETED,
- approved=True,
- created_at=timezone.now() - timedelta(hours=1),
- )
- RunSnapshot.objects.create(
- run=run2,
- team_id=team.id,
- identifier="story-x",
- baseline_hash="",
- current_hash="h1",
- result=SnapshotResult.NEW,
- review_state=ReviewState.APPROVED,
- )
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, "my-branch")
-
- # Latest approved outcome is NEW, not REMOVED — tombstone cleared, healing works
- assert "story-x" in merged
- assert healed == 1
-
- def test_tombstone_persists_without_later_approval(self, repo, team, mocker):
- """Remove→approve: tombstone stays until a later approval overrides it."""
- branch_baseline: dict[str, str] = {}
- merge_base_baseline = {"story-x": "h1"}
- self._mock_github(mocker, branch_baseline=branch_baseline, merge_base_baseline=merge_base_baseline)
-
- run1 = Run.objects.create(
- team_id=team.id,
- repo=repo,
- run_type=RunType.STORYBOOK,
- branch="my-branch",
- commit_sha="sha1",
- status=RunStatus.COMPLETED,
- approved=True,
- )
- RunSnapshot.objects.create(
- run=run1,
- team_id=team.id,
- identifier="story-x",
- baseline_hash="h1",
- current_hash="",
- result=SnapshotResult.REMOVED,
- review_state=ReviewState.APPROVED,
- )
-
- merged, healed = logic._resolve_baselines_with_merge_base(repo, RunType.STORYBOOK, "my-branch")
-
- assert "story-x" not in merged
- assert healed == 0
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestVerifyUploadsAndCreateArtifacts:
- """Server-side hash integrity for uploaded PNGs."""
-
- @pytest.fixture
- def repo(self, team):
- return logic.create_repo(team_id=team.id, repo_external_id=42424, repo_full_name="org/vr")
-
- def _png(self, color: tuple[int, int, int, int]) -> bytes:
- import io as _io
-
- from PIL import Image as _Image
-
- img = _Image.new("RGBA", (8, 8), color)
- buf = _io.BytesIO()
- img.save(buf, format="PNG")
- return buf.getvalue()
-
- def test_creates_artifact_with_server_computed_hash(self, repo, mocker):
- from products.visual_review.backend.hashing import hash_image
-
- png = self._png((10, 20, 30, 255))
- server_hash = hash_image(png)
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="sha",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Card", content_hash=server_hash)],
- ),
- team_id=repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.storage.ArtifactStorage.read",
- return_value=png,
- )
-
- created = logic.verify_uploads_and_create_artifacts(run.id)
-
- assert created == 1
- artifact = logic.get_artifact(repo.id, server_hash)
- assert artifact is not None
- assert artifact.content_hash == server_hash
- assert 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[SnapshotManifestItem] = []
- 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(
- SnapshotManifestItem(identifier=f"Card-{color_offset}-{index}", content_hash=content_hash)
- )
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha=f"sha-{count}-{color_offset}",
- branch="main",
- pr_number=None,
- snapshots=snapshots,
- ),
- team_id=repo.team_id,
- )
- 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[SnapshotManifestItem] = []
- 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(SnapshotManifestItem(identifier=f"Card-{index}", content_hash=content_hash))
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="sha-retry",
- branch="main",
- pr_number=None,
- snapshots=snapshots,
- ),
- team_id=repo.team_id,
- )
-
- assert logic.verify_uploads_and_create_artifacts(run.id) == 0
- assert RunSnapshot.objects.filter(run=run, current_artifact__isnull=False).count() == 3
-
- def test_hash_mismatch_raises_and_persists_no_artifacts(self, repo, mocker):
- # Two snapshots: first verifies cleanly, second has a mismatched claim.
- # The two-pass split must prevent the first artifact from being written
- # before the second is checked.
- from products.visual_review.backend.hashing import hash_image
-
- png_a = self._png((255, 0, 0, 255))
- png_b = self._png((0, 0, 255, 255))
- good_hash = hash_image(png_a)
- bad_claim = "f" * 64 # nothing hashes to this
-
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="sha",
- branch="main",
- pr_number=None,
- snapshots=[
- SnapshotManifestItem(identifier="Good", content_hash=good_hash),
- SnapshotManifestItem(identifier="Bad", content_hash=bad_claim),
- ],
- ),
- team_id=repo.team_id,
- )
-
- def _read(self, content_hash):
- return {good_hash: png_a, bad_claim: png_b}.get(content_hash)
-
- mocker.patch("products.visual_review.backend.storage.ArtifactStorage.read", autospec=True, side_effect=_read)
-
- with pytest.raises(logic.HashIntegrityError):
- logic.verify_uploads_and_create_artifacts(run.id)
-
- assert logic.get_artifact(repo.id, good_hash) is None
- assert logic.get_artifact(repo.id, bad_claim) is None
-
- def test_corrupt_png_raises_hash_integrity_error(self, repo, mocker):
- run, _ = logic.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="sha",
- branch="main",
- pr_number=None,
- snapshots=[SnapshotManifestItem(identifier="Card", content_hash="a" * 64)],
- ),
- team_id=repo.team_id,
- )
-
- mocker.patch(
- "products.visual_review.backend.storage.ArtifactStorage.read",
- return_value=b"not a png",
- )
-
- with pytest.raises(logic.HashIntegrityError):
- logic.verify_uploads_and_create_artifacts(run.id)
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestVerifyBaselineHashes:
- """Bootstrap-window guard: unsigned baselines must not be honored."""
-
- def test_drops_all_entries_when_no_signing_keys(self, team):
- repo = Repo.objects.create(
- team_id=team.id,
- repo_external_id=77777,
- repo_full_name="org/no-keys",
- signing_keys={},
- )
-
- result = logic._verify_baseline_hashes(repo, {"snap-a": "v1.k1.deadbeef.fake"})
-
- assert result == {}
-
-
[email protected]_db(databases=PRODUCT_DATABASES)
-class TestApprovalComment:
- """Tests for the post-approval PR comment summary."""
-
- @pytest.fixture
- def repo(self, team):
- return Repo.objects.create(
- team_id=team.id,
- repo_external_id=66666,
- repo_full_name="test-org/approval-repo",
- enable_pr_comments=True,
- )
-
- @pytest.fixture
- def run_with_snapshots(self, repo):
- from products.visual_review.backend.facade.enums import ReviewDecision
-
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="deadbeef",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- metadata={"github_comment_id": 9001, "baseline_commit_sha": "abc1234567"},
- )
-
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Login/Form",
- current_hash="curr_a",
- baseline_hash="base_a",
- result=SnapshotResult.CHANGED,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Settings/Tab",
- current_hash="curr_b",
- baseline_hash="",
- result=SnapshotResult.NEW,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Old/Component",
- current_hash="",
- baseline_hash="base_c",
- result=SnapshotResult.REMOVED,
- )
-
- return run
-
- def test_build_approval_comment_body_summarizes_changes(self, repo, run_with_snapshots):
- approver = logic._Approver(label="alice", is_github_login=True)
- body = logic._build_approval_comment_body(run_with_snapshots, repo, approver)
-
- assert "✅ **Visual changes approved** by @alice" in body
- assert "abc1234" in body # baseline SHA prefix
- assert f"/visual_review/runs/{run_with_snapshots.id}" in body
- assert "1 changed, 1 new, 1 removed." in body
- assert "<img" not in body
- assert "<table" not in body
- assert "/api/visual_review/public/" not in body
-
- def test_build_approval_comment_body_falls_back_to_a_reviewer(self, repo, run_with_snapshots):
- body = logic._build_approval_comment_body(run_with_snapshots, repo, None)
-
- assert "by a reviewer" in body
-
- def test_build_approval_comment_body_escapes_non_github_approver(self, repo, run_with_snapshots):
- # email local-part / first_name fallbacks are user-controlled — must be escaped
- approver = logic._Approver(label="alice[evil](http://attacker)", is_github_login=False)
- body = logic._build_approval_comment_body(run_with_snapshots, repo, approver)
-
- # No raw `@` mention (which would render as a GitHub user link)
- assert "by @alice" not in body
- # Markdown control chars in the label must be backslash-escaped
- assert "\\[evil\\]" in body
- assert "\\(http://attacker\\)" in body
-
- def test_build_approval_comment_body_no_actionable_snapshots(self, repo):
- from products.visual_review.backend.facade.enums import ReviewDecision
-
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="empty",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- )
- approver = logic._Approver(label="bob", is_github_login=True)
- body = logic._build_approval_comment_body(run, repo, approver)
- assert "✅ **Visual changes approved**" in body
- # No counts line when there's nothing to summarize
- assert "changed" not in body
- assert "new" not in body
- assert "removed" not in body
- # A genuinely empty run stays silent — the suppressed-only note must not fire
- assert "quarantined or tolerated" not in body
-
- def test_build_approval_comment_body_excludes_quarantined_and_tolerated(self, repo):
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="mixed",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id, run=run, identifier="Real/Change", result=SnapshotResult.CHANGED
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Flaky/Quarantined",
- result=SnapshotResult.CHANGED,
- is_quarantined=True,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Known/Tolerated",
- result=SnapshotResult.NEW,
- review_state=ReviewState.TOLERATED,
- )
-
- body = logic._build_approval_comment_body(run, repo, logic._Approver(label="bob", is_github_login=True))
-
- assert "1 changed." in body
- assert "new" not in body
- assert "quarantined or tolerated" not in body
-
- def test_build_approval_comment_body_notes_when_only_quarantined_and_tolerated(self, repo):
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="suppressed",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Flaky/Quarantined",
- result=SnapshotResult.CHANGED,
- is_quarantined=True,
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Known/Tolerated",
- result=SnapshotResult.NEW,
- review_state=ReviewState.TOLERATED,
- )
-
- body = logic._build_approval_comment_body(run, repo, logic._Approver(label="bob", is_github_login=True))
-
- assert "All visual changes in this run were quarantined or tolerated." in body
- assert "1 changed" not in body
-
- def test_post_approval_comment_skips_when_pr_comments_disabled(self, repo, run_with_snapshots, mocker):
- repo.enable_pr_comments = False
- repo.save(update_fields=["enable_pr_comments"])
-
- spy = mocker.patch.object(logic, "_github_api_request")
- logic._post_approval_comment(run_with_snapshots, repo)
- spy.assert_not_called()
-
- def test_post_approval_comment_skips_when_no_pr_number(self, repo, run_with_snapshots, mocker):
- run_with_snapshots.pr_number = None
- run_with_snapshots.save(update_fields=["pr_number"])
-
- spy = mocker.patch.object(logic, "_github_api_request")
- logic._post_approval_comment(run_with_snapshots, repo)
- spy.assert_not_called()
-
- def test_post_approval_comment_skips_for_non_human_decision(self, repo, run_with_snapshots, mocker):
- from products.visual_review.backend.facade.enums import ReviewDecision
-
- run_with_snapshots.review_decision = ReviewDecision.AUTO_APPROVED
- run_with_snapshots.save(update_fields=["review_decision"])
-
- spy = mocker.patch.object(logic, "_github_api_request")
- logic._post_approval_comment(run_with_snapshots, repo)
- spy.assert_not_called()
-
- def test_post_approval_comment_skips_when_no_existing_comment_id(self, repo, run_with_snapshots, mocker):
- run_with_snapshots.metadata = {}
- run_with_snapshots.save(update_fields=["metadata"])
-
- spy = mocker.patch.object(logic, "_github_api_request")
- logic._post_approval_comment(run_with_snapshots, repo)
- spy.assert_not_called()
-
- def test_post_approval_comment_patches_existing_comment(self, repo, run_with_snapshots, mocker):
- class FakeResp:
- status_code = 200
- text = ""
-
- spy = mocker.patch.object(logic, "_github_api_request", return_value=FakeResp())
-
- logic._post_approval_comment(run_with_snapshots, repo)
-
- spy.assert_called_once()
- kwargs = spy.call_args.kwargs
- assert kwargs["method"] == "PATCH"
- assert kwargs["path"] == "issues/comments/9001"
- assert "✅ **Visual changes approved**" in kwargs["json"]["body"]
-
- def test_post_approval_comment_falls_back_to_post_on_404(self, repo, run_with_snapshots, mocker):
- class PatchResp:
- status_code = 404
- text = "Not Found"
-
- class PostResp:
- status_code = 201
- text = ""
-
- @staticmethod
- def json():
- return {"id": 9999}
-
- spy = mocker.patch.object(logic, "_github_api_request", side_effect=[PatchResp(), PostResp()])
-
- logic._post_approval_comment(run_with_snapshots, repo)
-
- assert spy.call_count == 2
- first_call = spy.call_args_list[0].kwargs
- second_call = spy.call_args_list[1].kwargs
- assert first_call["method"] == "PATCH"
- assert second_call["method"] == "POST"
- assert second_call["path"] == "issues/42/comments"
-
- run_with_snapshots.refresh_from_db()
- assert run_with_snapshots.metadata["github_comment_id"] == 9999
-
- def test_post_approval_comment_swallows_exceptions(self, repo, run_with_snapshots, mocker):
- mocker.patch.object(logic, "_github_api_request", side_effect=RuntimeError("boom"))
- # Must not raise
- logic._post_approval_comment(run_with_snapshots, repo)
-
- @staticmethod
- def _mk_artifact(repo, content_hash, *, with_thumbnail=None):
- from products.visual_review.backend.models import Artifact
-
- artifact = Artifact.objects.create(
- repo=repo,
- team_id=repo.team_id,
- content_hash=content_hash,
- storage_path=f"path/{content_hash}",
- width=320,
- height=200,
- )
- if with_thumbnail:
- thumb = Artifact.objects.create(
- repo=repo,
- team_id=repo.team_id,
- content_hash=with_thumbnail,
- storage_path=f"thumb/{with_thumbnail}",
- )
- artifact.thumbnail = thumb
- artifact.save(update_fields=["thumbnail"])
- return artifact
-
- @staticmethod
- def _fake_storage(returns_url=True):
- class _FakeStorage:
- def __init__(self, repo_id):
- self.repo_id = repo_id
-
- def get_presigned_download_url(self, content_hash, expiration=3600):
- return f"https://cdn.example/{content_hash}?exp={expiration}" if returns_url else None
-
- return _FakeStorage
-
- @pytest.fixture
- def run_with_artifacts(self, repo):
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="cafef00d",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- metadata={"github_comment_id": 9001},
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Login/Form",
- result=SnapshotResult.CHANGED,
- baseline_artifact=self._mk_artifact(repo, "base_a", with_thumbnail="thumb_a"),
- current_artifact=self._mk_artifact(repo, "curr_a"),
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Settings/Tab",
- result=SnapshotResult.NEW,
- current_artifact=self._mk_artifact(repo, "curr_b"),
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier="Old/Component",
- result=SnapshotResult.REMOVED,
- baseline_artifact=self._mk_artifact(repo, "base_c"),
- )
- return run
-
- def test_build_approval_comment_body_includes_before_after_tables(self, repo, run_with_artifacts, mocker):
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
-
- body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
-
- # Changed table: baseline before, current after — full-resolution originals,
- # not thumbnails, so clicking opens the image at full size
- assert "**Changed**" in body
- assert "| Snapshot | Before | After |" in body
- assert "https://cdn.example/base_a" in body # full-res original, not thumb_a
- assert "https://cdn.example/thumb_a" not in body
- assert "https://cdn.example/curr_a" in body
- # Removed snapshot lives in the changed table with an empty after cell
- assert "_(removed)_" in body
- assert "https://cdn.example/base_c" in body
- # New table: empty before cell, current after
- assert "**New**" in body
- assert "https://cdn.example/curr_b" in body
- assert "_(none)_" in body
- # Long-lived URL so GitHub's image proxy can still fetch it later
- assert f"exp={logic._COMMENT_IMAGE_URL_EXPIRATION}" in body
-
- def test_build_snapshot_image_tables_excludes_quarantined_and_tolerated(self, repo, run_with_artifacts, mocker):
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run_with_artifacts,
- identifier="Flaky/Quarantined",
- result=SnapshotResult.CHANGED,
- is_quarantined=True,
- baseline_artifact=self._mk_artifact(repo, "base_q"),
- current_artifact=self._mk_artifact(repo, "curr_q"),
- )
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run_with_artifacts,
- identifier="Known/Tolerated",
- result=SnapshotResult.CHANGED,
- review_state=ReviewState.TOLERATED,
- baseline_artifact=self._mk_artifact(repo, "base_t"),
- current_artifact=self._mk_artifact(repo, "curr_t"),
- )
-
- body = logic._build_snapshot_image_tables(run_with_artifacts, repo)
-
- assert "Flaky/Quarantined" not in body
- assert "Known/Tolerated" not in body
- assert "curr_q" not in body
- assert "curr_t" not in body
- assert "Login/Form" in body
-
- def test_build_approval_comment_body_deep_links_each_snapshot(self, repo, run_with_artifacts, mocker):
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
-
- body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
-
- # Each snapshot name links straight to its deep link on the run page
- changed = run_with_artifacts.snapshots.get(identifier="Login/Form")
- assert f"[`Login/Form`]({logic._run_url(run_with_artifacts, repo)}?snapshot={changed.id})" in body
-
- def test_build_approval_comment_body_caps_at_eight_and_links_out(self, repo, mocker):
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
-
- run = Run.objects.create(
- team_id=repo.team_id,
- repo=repo,
- commit_sha="manysnaps",
- branch="feature",
- pr_number=42,
- review_decision=ReviewDecision.HUMAN_APPROVED,
- )
- for i in range(11):
- RunSnapshot.objects.create(
- team_id=repo.team_id,
- run=run,
- identifier=f"Story/{i:02d}",
- result=SnapshotResult.CHANGED,
- baseline_artifact=self._mk_artifact(repo, f"base_{i}"),
- current_artifact=self._mk_artifact(repo, f"curr_{i}"),
- )
-
- body = logic._build_approval_comment_body(run, repo, None, add_images=True)
-
- # 8 of 11 rows rendered, the rest linked out
- assert body.count("<img") == 8 * 2 # before + after per shown row
- assert "…and 3 more" in body
- assert f"/visual_review/runs/{run.id})" in body
-
- def test_build_approval_comment_body_falls_back_to_text_without_storage(self, repo, run_with_artifacts, mocker):
- # Images requested, but storage yields no URL — fall back to the text summary.
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage(returns_url=False))
-
- body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
-
- assert "<img" not in body
- assert "**Changed**" not in body
- # Still carries the textual summary
- assert "1 changed, 1 new, 1 removed." in body
-
- def test_build_approval_comment_body_omits_images_unless_opted_in(self, repo, run_with_artifacts, mocker):
- # add_images defaults false: the comment is always posted but stays a text summary.
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
-
- body = logic._build_approval_comment_body(run_with_artifacts, repo, None)
-
- assert "<img" not in body
- assert "**Changed**" not in body
- # The comment still summarizes what changed and links to the run
- assert "1 changed, 1 new, 1 removed." in body
- assert f"/visual_review/runs/{run_with_artifacts.id}" in body
-
- def test_image_cell_escapes_alt_and_src(self):
- # Both attributes are escaped so a quote in either can't break out of the tag
- cell = logic._image_cell('https://cdn.example/x?a="b', 'a"b')
- assert 'alt="a&quot;b"' in cell
- assert 'src="https://cdn.example/x?a=&quot;b"' in cell
-
- def test_image_cell_constrains_width_but_serves_full_resolution(self):
- # The cell shows a width-constrained image whose src is the full-resolution
- # original, so GitHub opens it at full size when clicked — no <a> wrapper needed.
- 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">'
-
- @parameterized.expand(
- [
- ("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, _name, identifier, expected):
- assert logic._snapshot_name_cell(identifier) == expected
-
- def test_snapshot_name_cell_collapses_control_characters(self):
- # Newlines/tabs/carriage returns would otherwise break out of the table row
- cell = logic._snapshot_name_cell("a\nb\tc\rd")
- assert "\n" not in cell
- assert "\r" not in cell
- assert "\t" not in cell
- assert cell == "`a b c d`"
-
- def test_snapshot_name_cell_newline_cannot_inject_table_rows(self):
- # A pipe-laden payload across a newline stays a single escaped cell
- cell = logic._snapshot_name_cell("x\n| --- |")
- assert "\n" not in cell
- assert cell == "`x \\| --- \\|`"
-
- def test_comment_image_url_requests_seven_day_expiry(self, repo, mocker):
- # The 7-day expiry is load-bearing: GitHub's image proxy may fetch the URL
- # long after the comment is posted, so lock the behaviour with a test.
- captured = {}
-
- class _RecordingStorage:
- def __init__(self, repo_id):
- pass
-
- def get_presigned_download_url(self, content_hash, expiration=3600):
- captured["content_hash"] = content_hash
- captured["expiration"] = expiration
- return "https://cdn.example/x"
-
- mocker.patch.object(logic, "ArtifactStorage", _RecordingStorage)
-
- artifact = self._mk_artifact(repo, "h1")
- url = logic._comment_image_url(repo, artifact)
-
- assert url == "https://cdn.example/x"
- assert captured["content_hash"] == "h1"
- assert captured["expiration"] == 60 * 60 * 24 * 7 == 604800
-
- def test_comment_image_url_serves_full_resolution_not_thumbnail(self, repo, mocker):
- # Serve the original artifact, not the thumbnail, so clicking opens it full-size
- mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
-
- artifact = self._mk_artifact(repo, "full_h", with_thumbnail="thumb_h")
- url = logic._comment_image_url(repo, artifact)
-
- assert url is not None
- assert "full_h" in url
- assert "thumb_h" not in url
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index b0ff53afbca4..f048411396ea 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -11,10 +11,10 @@ from rest_framework import status
from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH
-from products.visual_review.backend import logic
from products.visual_review.backend.facade import api
from 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.logic import artifact_store, quarantine, runs
from products.visual_review.backend.models import Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin
@@ -164,7 +164,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
),
team_id=self.team.id,
)
- logic.quarantine_identifier(
+ quarantine.quarantine_identifier(
repo_id=self.vr_project.id,
identifier="Button",
run_type=RunType.STORYBOOK,
@@ -204,7 +204,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
def test_approve_run(self):
# Create artifact directly via logic (API no longer exposes register_artifact)
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -236,7 +236,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
self.assertFalse(response.json()["approved"])
def test_finalize_run(self):
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -254,13 +254,13 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
)
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
- logic.finish_processing(create_result.run_id)
+ runs.complete_run(create_result.run_id)
+ runs.finish_processing(create_result.run_id)
# No PR on this run, so nothing is pushed, but approve_all + finalize marks it approved.
response = self.client.post(
@@ -282,7 +282,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
def test_finalize_run_always_comments_and_forwards_add_images(
self, _name: str, body: dict, expect_add_images: bool
):
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -300,17 +300,17 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
)
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
- logic.finish_processing(create_result.run_id)
+ runs.complete_run(create_result.run_id)
+ runs.finish_processing(create_result.run_id)
with (
- patch("products.visual_review.backend.logic._post_commit_status"),
- patch("products.visual_review.backend.logic.transaction.on_commit", side_effect=lambda fn, *a, **k: fn()),
+ patch("products.visual_review.backend.logic.ci_status._post_commit_status"),
+ patch("django.db.transaction.on_commit", side_effect=lambda fn, *a, **k: fn()),
patch("products.visual_review.backend.tasks.tasks.post_approval_comment.delay") as delay,
):
response = self.client.post(
@@ -325,7 +325,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
self.assertEqual(delay.call_args.args[2], expect_add_images)
def _changed_snapshot_for_tolerate(self) -> tuple[str, str]:
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -383,7 +383,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
result: str = SnapshotResult.UNCHANGED,
) -> RunSnapshot:
"""Create one Run + one RunSnapshot directly, with full control over result and status."""
- artifact, _ = logic.get_or_create_artifact(
+ artifact, _ = artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash=content_hash,
storage_path=f"visual_review/{content_hash}",
@@ -392,7 +392,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
# Default to the same artifact as `current_` for trivial cases.
baseline_artifact = artifact
if baseline_content_hash is not None and baseline_content_hash != content_hash:
- baseline_artifact, _ = logic.get_or_create_artifact(
+ baseline_artifact, _ = artifact_store.get_or_create_artifact(
repo_id=self.vr_project.id,
content_hash=baseline_content_hash,
storage_path=f"visual_review/{baseline_content_hash}",
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index cd391b873eca..97349a06dc30 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -10,7 +10,7 @@ from unittest.mock import patch
from parameterized import parameterized
from PIL import Image
-from products.visual_review.backend import diffing, logic
+from products.visual_review.backend import diffing
from products.visual_review.backend.diffing import process_diffs
from products.visual_review.backend.facade import api
from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
@@ -21,6 +21,7 @@ from products.visual_review.backend.facade.enums import (
RunType,
SnapshotResult,
)
+from products.visual_review.backend.logic import artifact_store, runs
from products.visual_review.backend.models import RunSnapshot, ToleratedHash
from products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin
@@ -92,7 +93,7 @@ class TestProcessRunDiffs:
assert "Something went wrong" in (run.error_message or "")
def test_metrics_event_uses_run_id_as_uuid(self, repo, mocker):
- run, _ = logic.create_run(
+ run, _ = runs.create_run(
CreateRunInput(
repo_id=repo.id,
run_type=RunType.STORYBOOK,
@@ -109,9 +110,9 @@ class TestProcessRunDiffs:
def scoped_capture():
yield capture
- mocker.patch.object(logic, "ph_scoped_capture", scoped_capture)
+ mocker.patch.object(runs, "ph_scoped_capture", scoped_capture)
- logic.capture_run_processing_metrics(run.id, outcome="completed", diffed_count=0)
+ runs.capture_run_processing_metrics(run.id, outcome="completed", diffed_count=0)
assert capture.call_args.kwargs["uuid"] == run.id
@@ -130,7 +131,7 @@ class TestProcessRunDiffs:
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,
+ patch("products.visual_review.backend.logic.runs.capture_run_processing_metrics") as capture,
):
process_run_diffs(repo.team_id, str(create_result.run_id))
@@ -153,7 +154,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,
+ patch("products.visual_review.backend.logic.runs.capture_run_processing_metrics") as capture,
):
with pytest.raises(Exception, match="boom"):
process_run_diffs(repo.team_id, str(create_result.run_id))
@@ -165,7 +166,7 @@ class TestProcessRunDiffs:
def testprocess_diffs_skips_unchanged(self, repo):
# Create artifact that exists for both baseline and current
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=repo.id,
content_hash="same_hash",
storage_path="visual_review/same_hash",
@@ -185,10 +186,10 @@ class TestProcessRunDiffs:
# Classification happens at complete_run time
with patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
return_value=({"Button": "same_hash"}, 0),
):
- logic.complete_run(create_result.run_id)
+ runs.complete_run(create_result.run_id)
# Process - should skip unchanged snapshot
process_diffs(create_result.run_id)
@@ -219,8 +220,8 @@ class TestProcessRunDiffs:
assert 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")
+ thumbnail, _ = artifact_store.get_or_create_artifact(repo.id, "thumb_hash", "visual_review/thumb_hash")
+ current, _ = artifact_store.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(
@@ -241,13 +242,13 @@ class TestProcessRunDiffs:
def testprocess_diffs_attempts_diff_for_changed(self, repo):
# Create baseline artifact
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=repo.id,
content_hash="old_hash",
storage_path="visual_review/old_hash",
)
# Create current artifact
- logic.get_or_create_artifact(
+ artifact_store.get_or_create_artifact(
repo_id=repo.id,
content_hash="new_hash",
storage_path="visual_review/new_hash",
@@ -268,12 +269,12 @@ class TestProcessRunDiffs:
# Classification happens at complete_run time
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
+ runs.complete_run(create_result.run_id)
# Process - should attempt to diff but fail because artifacts aren't in storage
with patch("products.visual_review.backend.diffing.logger") as mock_logger:
@@ -290,8 +291,8 @@ class TestProcessRunDiffs:
"old_hash": _make_png((255, 0, 0, 255)),
"new_hash": _make_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")
+ artifact_store.get_or_create_artifact(repo.id, "old_hash", "visual_review/old_hash")
+ artifact_store.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")
create_result = api.create_run(
CreateRunInput(
repo_id=repo.id,
@@ -305,12 +306,12 @@ class TestProcessRunDiffs:
)
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
+ runs.complete_run(create_result.run_id)
mocker.patch(
"products.visual_review.backend.storage.ArtifactStorage.read",
@@ -335,8 +336,8 @@ class TestProcessRunDiffs:
"old_hash": _make_png((255, 0, 0, 255), size=(100, 100)),
"new_hash": _make_png_with_single_changed_pixel(),
}
- 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")
+ artifact_store.get_or_create_artifact(repo.id, "old_hash", "visual_review/old_hash")
+ artifact_store.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")
create_result = api.create_run(
CreateRunInput(
repo_id=repo.id,
@@ -350,12 +351,12 @@ class TestProcessRunDiffs:
)
with (
patch(
- "products.visual_review.backend.logic._resolve_baselines_with_merge_base",
+ "products.visual_review.backend.logic.baselines._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)
+ runs.complete_run(create_result.run_id)
mocker.patch(
"products.visual_review.backend.storage.ArtifactStorage.read",
@@ -419,7 +420,7 @@ class TestCountProcessedDiffs(VisualReviewTeamScopedTestMixin, BaseTest):
)
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(
+ run, _ = runs.create_run(
CreateRunInput(
repo_id=repo.id,
run_type=RunType.STORYBOOK,
@@ -442,7 +443,7 @@ class TestPostApprovalCommentTask:
return api.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/approval")
def test_calls_logic_helper(self, repo):
- with patch("products.visual_review.backend.logic.post_approval_comment_for_run") as helper:
+ with patch("products.visual_review.backend.logic.comments.post_approval_comment_for_run") as helper:
post_approval_comment(repo.team_id, "00000000-0000-0000-0000-000000000001")
helper.assert_called_once()
args, kwargs = helper.call_args
@@ -451,7 +452,7 @@ class TestPostApprovalCommentTask:
def test_swallows_unexpected_errors(self, repo):
with patch(
- "products.visual_review.backend.logic.post_approval_comment_for_run",
+ "products.visual_review.backend.logic.comments.post_approval_comment_for_run",
side_effect=RuntimeError("boom"),
):
# Must not raise — failure to comment must never block other work.
@@ -462,7 +463,7 @@ class TestPostApprovalCommentTask:
with (
patch(
- "products.visual_review.backend.logic.post_approval_comment_for_run",
+ "products.visual_review.backend.logic.comments.post_approval_comment_for_run",
side_effect=GitHubRateLimitError("rate limited", retry_after=42),
),
patch.object(post_approval_comment, "retry", side_effect=RuntimeError("retry called")) as retry_mock,
diff --git a/products/visual_review/backend/tests/test_thumbnails.py b/products/visual_review/backend/tests/test_thumbnails.py
index 5f0c489cd859..a0ca76915559 100644
--- a/products/visual_review/backend/tests/test_thumbnails.py
+++ b/products/visual_review/backend/tests/test_thumbnails.py
@@ -82,7 +82,7 @@ def _make_compare_result(thumbnail: bytes = b"fake-webp") -> CompareResult:
@pytest.mark.django_db(databases=list(PRODUCT_DATABASES))
class TestStoreThumbnail:
- @patch("products.visual_review.backend.logic.write_artifact_bytes")
+ @patch("products.visual_review.backend.logic.artifact_store.write_artifact_bytes")
def test_stores_thumbnail_and_links_to_artifact(self, mock_write, team):
repo = _make_repo(team)
_run, snapshot = _make_run_with_snapshot(repo)
@@ -103,7 +103,7 @@ class TestStoreThumbnail:
artifact.refresh_from_db()
assert artifact.thumbnail == thumb_artifact
- @patch("products.visual_review.backend.logic.write_artifact_bytes")
+ @patch("products.visual_review.backend.logic.artifact_store.write_artifact_bytes")
def test_skips_when_thumbnail_already_exists(self, mock_write, team):
repo = _make_repo(team)
_run, snapshot = _make_run_with_snapshot(repo)
@@ -118,7 +118,7 @@ class TestStoreThumbnail:
mock_write.assert_not_called()
- @patch("products.visual_review.backend.logic.write_artifact_bytes")
+ @patch("products.visual_review.backend.logic.artifact_store.write_artifact_bytes")
def test_skips_when_no_thumbnail_in_result(self, mock_write, team):
repo = _make_repo(team)
_run, snapshot = _make_run_with_snapshot(repo)