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.

feat(visual-review): emit vr_run_processed event for diff-processing runs (#72174)

Julian Beze08227f78407
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 1b48883b3a33..af8cc3b9ae37 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -41,6 +41,7 @@ from posthog.helpers.trigram_search import (
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
@@ -1214,6 +1215,57 @@ def finish_processing(run_id: UUID, error_message: str = "") -> Run:
return run
+def capture_run_processing_metrics(run_id: UUID, *, outcome: str) -> 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.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,
+ # Snapshots that actually ran a pixel comparison — the cost the
+ # content-hash dedup and tolerance cache are meant to keep near zero.
+ "diffed_count": run.changed_count,
+ "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,
+ )
+ except Exception:
+ logger.warning("visual_review.metrics_capture_failed", run_id=str(run_id), exc_info=True)
+
+
@transaction.atomic(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.
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 7d6052a4c56c..a1eb3fbd039b 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -12,12 +12,15 @@ from uuid import UUID
import structlog
from celery import shared_task
+from opentelemetry import trace
+from opentelemetry.trace import Status, StatusCode
from posthog.models.scoping import with_team_scope
from ..logic import HashIntegrityError
logger = structlog.get_logger(__name__)
+TRACER = trace.get_tracer(__name__)
@shared_task(
@@ -43,32 +46,57 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
from ..diffing import process_diffs
run_uuid = UUID(run_id)
-
- try:
- logger.info("visual_review.diff_processing_started", run_id=run_id, team_id=team_id)
- logic.verify_uploads_and_create_artifacts(run_uuid)
- process_diffs(run_uuid)
- logic.finish_processing(run_uuid)
- logger.info("visual_review.diff_processing_completed", run_id=run_id, team_id=team_id)
- except HashIntegrityError as e:
- logger.warning("visual_review.hash_integrity_failed", run_id=run_id, error=str(e))
- logic.finish_processing(run_uuid, error_message=str(e))
- except GitHubRateLimitError as e:
- logger.warning(
- "visual_review.diff_processing_rate_limited",
- run_id=run_id,
- retry=self.request.retries,
- max_retries=self.max_retries,
- )
+ outcome = "completed"
+ retrying = False
+
+ # Phase timings go to OTel spans (where is time spent); counts go to the
+ # vr_run_processed event (how many runs, how many diffs).
+ with TRACER.start_as_current_span("visual_review.process_run_diffs") as span:
+ span.set_attribute("visual_review.run_id", run_id)
+ span.set_attribute("visual_review.team_id", team_id)
try:
- countdown = e.retry_after or 60
- self.retry(countdown=min(countdown, 600), exc=e)
- except self.MaxRetriesExceededError:
- logic.finish_processing(run_uuid, error_message="GitHub API rate limit exceeded after retries")
- except Exception as 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))
- raise
+ 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)
+ with TRACER.start_as_current_span("visual_review.process_diffs"):
+ process_diffs(run_uuid)
+ with TRACER.start_as_current_span("visual_review.finish_processing"):
+ logic.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))
+ except GitHubRateLimitError as e:
+ outcome = "rate_limited"
+ logger.warning(
+ "visual_review.diff_processing_rate_limited",
+ run_id=run_id,
+ retry=self.request.retries,
+ max_retries=self.max_retries,
+ )
+ try:
+ retrying = True
+ countdown = e.retry_after or 60
+ self.retry(countdown=min(countdown, 600), exc=e)
+ except self.MaxRetriesExceededError:
+ retrying = False
+ outcome = "rate_limit_exhausted"
+ logic.finish_processing(run_uuid, error_message="GitHub API rate limit exceeded after retries")
+ except Exception as e:
+ outcome = "failed"
+ 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))
+ raise
+ finally:
+ span.set_attribute("visual_review.outcome", outcome)
+ # Skip on retry: the run isn't terminal yet and will emit on its next attempt.
+ if not retrying:
+ logic.capture_run_processing_metrics(run_uuid, outcome=outcome)
@shared_task(
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index ed469aea0989..76a75d5cbffc 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -62,6 +62,47 @@ class TestProcessRunDiffs:
assert run.status == RunStatus.FAILED
assert "Something went wrong" in (run.error_message or "")
+ def test_emits_metrics_event_on_success(self, repo):
+ create_result = api.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="hash1")],
+ ),
+ team_id=repo.team_id,
+ )
+
+ with patch("products.visual_review.backend.logic.capture_run_processing_metrics") as capture:
+ process_run_diffs(repo.team_id, str(create_result.run_id))
+
+ capture.assert_called_once()
+ assert capture.call_args.kwargs["outcome"] == "completed"
+
+ def test_emits_metrics_event_on_failure(self, repo):
+ create_result = api.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ snapshots=[],
+ ),
+ team_id=repo.team_id,
+ )
+
+ with (
+ patch("products.visual_review.backend.diffing.process_diffs", side_effect=Exception("boom")),
+ patch("products.visual_review.backend.logic.capture_run_processing_metrics") as capture,
+ ):
+ with pytest.raises(Exception, match="boom"):
+ process_run_diffs(repo.team_id, str(create_result.run_id))
+
+ # Metrics still emitted on the failure path, and the real error is not masked.
+ capture.assert_called_once()
+ assert capture.call_args.kwargs["outcome"] == "failed"
+
def testprocess_diffs_skips_unchanged(self, repo):
# Create artifact that exists for both baseline and current
logic.get_or_create_artifact(