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.

fix(visual-review): publish a run's settled counts with its completed status (#90035)

Julian Bez4ea88b1aabe4
diff --git a/products/visual_review/backend/logic/gating.py b/products/visual_review/backend/logic/gating.py
index a0e517effb82..b54b027114e0 100644
--- a/products/visual_review/backend/logic/gating.py
+++ b/products/visual_review/backend/logic/gating.py
@@ -46,15 +46,20 @@ def _changes_summary(run: Run) -> str:
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.
+# The count fields `_recount` assigns. A caller that publishes them alongside other
+# fields passes these to its own `save(update_fields=...)`.
+COUNT_FIELDS = ("changed_count", "new_count", "removed_count", "tolerated_match_count")
+
+
+def _recount(run: Run) -> list[RunSnapshot]:
+ """Re-stamp quarantine and recount the run's snapshots onto `run`, without saving.
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.
+ classifier output excluding quarantined snapshots.
- Returns the unresolved count.
+ The caller owns the write, because `finish_processing` must publish these counts
+ in the same write as the completed status. Returns the loaded snapshots so the
+ caller does not query them again.
"""
_stamp_quarantine(run)
@@ -68,15 +73,17 @@ def _update_counts_and_post_status(run: Run) -> int:
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",
- ]
- )
+ return snapshots
+
+def _post_status(run: Run, snapshots: list[RunSnapshot]) -> int:
+ """Compute unresolved and post the commit status that gates CI.
+
+ The unresolved count is separate from the run's counts because it further
+ excludes tolerated and approved snapshots.
+
+ Returns the unresolved 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
@@ -108,3 +115,15 @@ def _update_counts_and_post_status(run: Run) -> int:
ci_status._post_commit_status(run, repo, "success", "No visual changes")
return unresolved
+
+
+def _update_counts_and_post_status(run: Run) -> int:
+ """Recount the run, save the counts on their own, and post the commit status.
+
+ For a run that is already completed, where the status is not part of the write.
+
+ Returns the unresolved count.
+ """
+ snapshots = _recount(run)
+ run.save(update_fields=COUNT_FIELDS)
+ return _post_status(run, snapshots)
diff --git a/products/visual_review/backend/logic/runs.py b/products/visual_review/backend/logic/runs.py
index 62d5a921c5bb..5e1bf9f30e8f 100644
--- a/products/visual_review/backend/logic/runs.py
+++ b/products/visual_review/backend/logic/runs.py
@@ -336,12 +336,42 @@ def complete_run(run_id: UUID) -> Run:
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
+ if error_message:
+ # A failing run has to reach FAILED even when the recount is what failed. The diff
+ # task calls this from its exception handler, so recounting first would hit the same
+ # failure again and leave the run in PROCESSING while clients poll it.
+ run.status = RunStatus.FAILED
+ 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
+
+ # Recount first, so one write publishes the status and the settled counts together.
+ # The counts `complete_run` saved come from the hash classification, and the diff task
+ # then reclassifies every snapshot whose diff came in under the threshold. A reader
+ # that sees COMPLETED before the recount therefore gets counts that still report drift
+ # the run no longer has, and the CLI fails CI on them.
+ try:
+ snapshots = gating._recount(run)
+ except Exception as exc:
+ # Terminalize before the exception leaves. `complete_run` runs its no-change path
+ # synchronously with no exception handler behind it, and it returns early on a run
+ # that is already PROCESSING, so every later retry would be a no-op. Report the
+ # failure rather than publish counts the recount did not settle.
+ logger.exception("visual_review.recount_failed", run_id=str(run_id))
+ run.status = RunStatus.FAILED
+ run.error_message = f"Recount failed: {exc}"
+ run.completed_at = timezone.now()
+ run.save(update_fields=["status", "error_message", "completed_at"])
+ raise
+
+ run.status = RunStatus.COMPLETED
+ run.error_message = ""
run.completed_at = timezone.now()
- run.save(update_fields=["status", "error_message", "completed_at"])
+ run.save(update_fields=["status", "error_message", "completed_at", *gating.COUNT_FIELDS])
- gating._update_counts_and_post_status(run)
+ gating._post_status(run, snapshots)
return run
diff --git a/products/visual_review/backend/tests/logic/test_runs.py b/products/visual_review/backend/tests/logic/test_runs.py
index 2e2fe29dab1d..c7741ea07ae7 100644
--- a/products/visual_review/backend/tests/logic/test_runs.py
+++ b/products/visual_review/backend/tests/logic/test_runs.py
@@ -2,11 +2,13 @@
import pytest
+from django.db.models.signals import post_save
+
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.models import Repo, Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -455,6 +457,52 @@ class TestRunOperations:
assert updated.new_count == 1
assert updated.error_message == ""
+ def test_finish_processing_publishes_settled_counts_with_the_completed_status(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,
+ )
+ 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 saved one changed and one new. Absorb both, which is what the diff
+ # task does to a snapshot whose diff comes in under the threshold.
+ RunSnapshot.objects.using(WRITER_DB).filter(run_id=run.id).update(result=SnapshotResult.UNCHANGED)
+
+ published: list[tuple[str, int, int]] = []
+
+ def record(sender, instance, **kwargs):
+ if instance.id == run.id:
+ published.append((instance.status, instance.changed_count, instance.new_count))
+
+ post_save.connect(record, sender=Run)
+ try:
+ runs.finish_processing(run.id)
+ finally:
+ post_save.disconnect(record, sender=Run)
+
+ # The CLI polls until the run reads COMPLETED and then reports that row's counts.
+ # A status published before the recount hands it the pre-diff counts, and it fails
+ # CI over drift the run no longer has.
+ completed = [state for state in published if state[0] == RunStatus.COMPLETED]
+ assert completed
+ assert all(state[1:] == (0, 0) for state in completed)
+
def test_finish_processing_with_error(self, repo):
run, _ = runs.create_run(
CreateRunInput(
@@ -474,6 +522,42 @@ class TestRunOperations:
assert updated.status == RunStatus.FAILED
assert updated.error_message == "Something failed"
+ # Neither caller can recover a run left in PROCESSING: the diff task retries
+ # finish_processing through the same recount, and complete_run's no-change path runs
+ # synchronously and returns early on a run that is already PROCESSING.
+ @pytest.mark.parametrize(
+ "error_message,expected_error",
+ [
+ ("recount timed out", "recount timed out"),
+ ("", "Recount failed: recount timed out"),
+ ],
+ )
+ def test_finish_processing_fails_the_run_when_the_recount_raises(self, error_message, expected_error, 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,
+ )
+
+ mocker.patch(
+ "products.visual_review.backend.logic.gating._recount",
+ side_effect=RuntimeError("recount timed out"),
+ )
+
+ with pytest.raises(RuntimeError):
+ runs.finish_processing(run.id, error_message=error_message)
+
+ run.refresh_from_db()
+ assert run.status == RunStatus.FAILED
+ assert run.error_message == expected_error
+
def test_update_run_counts_reads_and_writes_through_requested_db(self, repo, mocker):
run, _ = runs.create_run(
CreateRunInput(