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): answer each failed lift lookup with its own response (#111802)

Julian Bezedaa0be019cb
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
index 63eff4896ea6..d73ff9923a3c 100644
--- a/products/visual_review/backend/logic/github_api.py
+++ b/products/visual_review/backend/logic/github_api.py
@@ -85,14 +85,20 @@ def default_branch_name(repo: Repo) -> str | None:
def default_branch_head_sha(repo: Repo) -> str | None:
- """The commit the repo's default branch points at, or None when GitHub cannot say."""
+ """The commit the repo's default branch points at, or None when GitHub cannot say.
+
+ Raises `GitHubIntegrationNotFoundError` and `GitHubRateLimitError`, because a retry does not help
+ the first and has to wait for the second.
+ """
+ github = get_github_integration_for_repo(repo)
try:
- github = get_github_integration_for_repo(repo)
# Not `_get_default_branch`: its fallback name can point at a branch that is not the default,
# and a commit from that branch would scope the lift wrongly.
branch = github.get_default_branch(repo.repo_full_name)
# One path segment, so a branch name with a slash does not split the ref.
response = github.api_request("GET", f"/repos/{repo.repo_full_name}/commits/{quote(branch, safe='')}")
+ except GitHubRateLimitError:
+ raise
except Exception:
logger.warning("visual_review.default_branch_head_fetch_failed", repo_id=str(repo.id))
return None
diff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.py
index ce67e5d43938..3788533d6dd6 100644
--- a/products/visual_review/backend/logic/quarantine.py
+++ b/products/visual_review/backend/logic/quarantine.py
@@ -194,14 +194,21 @@ def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_
# Take the cutoff before the GitHub request, and lift only rows that existed at the cutoff. A
# quarantine that somebody creates while the request is in flight must survive this lift.
now = timezone.now()
- lifted_at_sha = _lift_commit(repo)
- QuarantinedIdentifier.objects.using(WRITER_DB).filter(
- repo_id=repo_id,
- identifier=identifier,
- run_type=run_type,
- team_id=team_id,
- created_at__lte=now,
- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).update(expires_at=now, lifted_at_sha=lifted_at_sha)
+ active = (
+ QuarantinedIdentifier.objects.using(WRITER_DB)
+ .filter(
+ repo_id=repo_id,
+ identifier=identifier,
+ run_type=run_type,
+ team_id=team_id,
+ created_at__lte=now,
+ )
+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
+ )
+ # A repeated lift stays a no-op, even while GitHub cannot name the head.
+ if not active.exists():
+ return
+ active.update(expires_at=now, lifted_at_sha=_lift_commit(repo))
def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index b2b51f299818..0b6b7c7d2bce 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -423,6 +423,13 @@ class UnquarantineQuerySerializer(serializers.Serializer):
identifier = serializers.CharField(max_length=512, help_text="Snapshot identifier to unquarantine")
+class ErrorDetailSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="What went wrong and what to do next.")
+ code = serializers.CharField(
+ required=False, help_text="A stable code for the error, such as `lift_commit_unknown` or `rate_limited`."
+ )
+
+
class LiftOnMergeInputSerializer(DataclassSerializer):
identifier = serializers.CharField(
max_length=512,
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index 494f7b0e64bc..c0ab9f0751b4 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -53,6 +53,7 @@ from .serializers import (
CreateRepoInputSerializer,
CreateRunInputSerializer,
CreateRunResultSerializer,
+ ErrorDetailSerializer,
FinalizeResultSerializer,
FinalizeRunInputSerializer,
FlakinessOverviewSerializer,
@@ -334,7 +335,15 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@validated_request(
request_serializer=UnquarantineQuerySerializer,
- responses={204: None},
+ responses={
+ 204: None,
+ 400: OpenApiResponse(response=ErrorDetailSerializer, description="No GitHub integration."),
+ 429: OpenApiResponse(response=ErrorDetailSerializer, description="GitHub rate limit. See Retry-After."),
+ 503: OpenApiResponse(
+ response=ErrorDetailSerializer,
+ description="GitHub cannot name the default branch head. The quarantine stays.",
+ ),
+ },
)
@action(detail=True, methods=["post"], url_path=r"quarantine/(?P<run_type>[^/]+)/expire")
def unquarantine(self, request: TypedRequest, pk: str, run_type: str, **kwargs) -> Response:
@@ -348,6 +357,19 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
except api.RepoNotFoundError:
return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
+ except api.GitHubIntegrationNotFoundError:
+ return Response(
+ {"detail": "No GitHub integration configured. Please install the GitHub App for this team."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except api.GitHubRateLimitError as e:
+ response = Response(
+ {"detail": "GitHub API rate limit exceeded. Please retry later.", "code": "rate_limited"},
+ status=status.HTTP_429_TOO_MANY_REQUESTS,
+ )
+ if e.retry_after:
+ response["Retry-After"] = str(e.retry_after)
+ return response
except api.LiftCommitUnknownError as e:
return Response(
{"detail": str(e), "code": "lift_commit_unknown"}, status=status.HTTP_503_SERVICE_UNAVAILABLE
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index d1a488c7a80f..42600f864444 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -5,13 +5,14 @@ from urllib.parse import quote, urlencode
from uuid import uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH
from products.visual_review.backend.facade import api
@@ -28,7 +29,7 @@ from products.visual_review.backend.facade.enums import (
RunType,
SnapshotResult,
)
-from products.visual_review.backend.logic import artifact_store, github_api, quarantine, runs
+from products.visual_review.backend.logic import artifact_store, errors, github_api, quarantine, runs
from products.visual_review.backend.models import Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin
@@ -91,22 +92,47 @@ class TestRepoViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("head_known", "abc123", status.HTTP_204_NO_CONTENT, []),
- ("head_unknown", None, status.HTTP_503_SERVICE_UNAVAILABLE, ["Button"]),
+ ("head_known", True, "head_known", status.HTTP_204_NO_CONTENT, None, []),
+ (
+ "head_unknown",
+ True,
+ "head_unknown",
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ "lift_commit_unknown",
+ ["Button"],
+ ),
+ ("no_integration", True, "no_integration", status.HTTP_400_BAD_REQUEST, None, ["Button"]),
+ ("rate_limited", True, "rate_limited", status.HTTP_429_TOO_MANY_REQUESTS, "rate_limited", ["Button"]),
+ ("repeat_lift_while_head_unknown", False, "head_unknown", status.HTTP_204_NO_CONTENT, None, []),
]
)
- def test_expire_quarantine_takes_only_an_identifier(self, _name, head_sha, expected_status, expected_active):
+ def test_expire_quarantine_takes_only_an_identifier(
+ self, _name, quarantined, github_state, expected_status, expected_code, expected_active
+ ):
repo = api.create_repo(team_id=self.team.id, repo_external_id=444, repo_full_name="org/expire")
- quarantine.quarantine_identifier(
- repo_id=repo.id,
- identifier="Button",
- run_type=RunType.STORYBOOK,
- reason="flaky",
- user_id=self.user.id,
- team_id=self.team.id,
- )
-
- with patch.object(github_api, "default_branch_head_sha", return_value=head_sha):
+ if quarantined:
+ quarantine.quarantine_identifier(
+ repo_id=repo.id,
+ identifier="Button",
+ run_type=RunType.STORYBOOK,
+ reason="flaky",
+ user_id=self.user.id,
+ team_id=self.team.id,
+ )
+ github = MagicMock()
+ github.get_default_branch.return_value = "master"
+ github.api_request.return_value = MagicMock(status_code=200, json=lambda: {"sha": "abc123"})
+ integration_error = None
+ if github_state == "head_unknown":
+ github.api_request.return_value = MagicMock(status_code=502)
+ elif github_state == "no_integration":
+ integration_error = errors.GitHubIntegrationNotFoundError("none")
+ elif github_state == "rate_limited":
+ github.get_default_branch.side_effect = GitHubRateLimitError("limited", retry_after=30)
+
+ with patch.object(
+ github_api, "get_github_integration_for_repo", return_value=github, side_effect=integration_error
+ ):
response = self.client.post(
f"/api/projects/{self.team.id}/visual_review/repos/{repo.id}/quarantine/{RunType.STORYBOOK}/expire",
{"identifier": "Button"},
@@ -114,6 +140,8 @@ class TestRepoViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
)
assert response.status_code == expected_status
+ if expected_code:
+ assert response.json()["code"] == expected_code
active = quarantine.list_quarantined_identifiers(repo.id, team_id=self.team.id)
assert [entry.identifier for entry in active] == expected_active
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index e9d507799eee..e4636ff18e14 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -308,6 +308,13 @@ export interface UnquarantineQueryApi {
identifier: string
}
+export interface ErrorDetailApi {
+ /** What went wrong and what to do next. */
+ detail: string
+ /** A stable code for the error, such as `lift_commit_unknown` or `rate_limited`. */
+ code?: string
+}
+
export interface TolerationPileupEntryApi {
/** Snapshot identifier, for example a Storybook story id plus theme. */
identifier: string
diff --git a/products/visual_review/mcp/tools.yaml b/products/visual_review/mcp/tools.yaml
index 8dcd3da1da99..c38ed00897ab 100644
--- a/products/visual_review/mcp/tools.yaml
+++ b/products/visual_review/mcp/tools.yaml
@@ -155,7 +155,8 @@ tools:
earlier keeps the quarantine for up to 30 days or until it merges the default branch. Lift one after the fix
that stabilizes the story merges, or when its flakiness entry has `needs_decision`. If the story still
flakes, the next pull request that contains the lift and renders it fails. On `503 lift_commit_unknown`
- GitHub could not name the default-branch head, so the quarantine stays: retry later.
+ GitHub could not name the default-branch head, so the quarantine stays: retry later. On `429 rate_limited`,
+ wait for `Retry-After`.
param_overrides:
id:
description: The repo's UUID, from `visual-review-repos-list`.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4b3c6a70f1d2..d28070e56d61 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -13708,7 +13708,7 @@
"feature_flag": "visual-review"
},
"visual-review-repos-quarantine-expire-create": {
- "description": "Lift every active quarantine on one identifier and run type. The lift is scoped to the current default-branch commit: a run whose commit contains it gates the snapshot again, and a branch that forked earlier keeps the quarantine for up to 30 days or until it merges the default branch. Lift one after the fix that stabilizes the story merges, or when its flakiness entry has `needs_decision`. If the story still flakes, the next pull request that contains the lift and renders it fails. On `503 lift_commit_unknown` GitHub could not name the default-branch head, so the quarantine stays: retry later.",
+ "description": "Lift every active quarantine on one identifier and run type. The lift is scoped to the current default-branch commit: a run whose commit contains it gates the snapshot again, and a branch that forked earlier keeps the quarantine for up to 30 days or until it merges the default branch. Lift one after the fix that stabilizes the story merges, or when its flakiness entry has `needs_decision`. If the story still flakes, the next pull request that contains the lift and renders it fails. On `503 lift_commit_unknown` GitHub could not name the default-branch head, so the quarantine stays: retry later. On `429 rate_limited`, wait for `Retry-After`.",
"category": "Visual review",
"feature": "visual_review",
"summary": "Lift a visual review quarantine",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 54507e944d73..b421dd12e982 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -14386,7 +14386,7 @@
"feature_flag": "visual-review"
},
"visual-review-repos-quarantine-expire-create": {
- "description": "Lift every active quarantine on one identifier and run type. The lift is scoped to the current default-branch commit: a run whose commit contains it gates the snapshot again, and a branch that forked earlier keeps the quarantine for up to 30 days or until it merges the default branch. Lift one after the fix that stabilizes the story merges, or when its flakiness entry has `needs_decision`. If the story still flakes, the next pull request that contains the lift and renders it fails. On `503 lift_commit_unknown` GitHub could not name the default-branch head, so the quarantine stays: retry later.",
+ "description": "Lift every active quarantine on one identifier and run type. The lift is scoped to the current default-branch commit: a run whose commit contains it gates the snapshot again, and a branch that forked earlier keeps the quarantine for up to 30 days or until it merges the default branch. Lift one after the fix that stabilizes the story merges, or when its flakiness entry has `needs_decision`. If the story still flakes, the next pull request that contains the lift and renders it fails. On `503 lift_commit_unknown` GitHub could not name the default-branch head, so the quarantine stays: retry later. On `429 rate_limited`, wait for `Retry-After`.",
"category": "Visual review",
"feature": "visual_review",
"summary": "Lift a visual review quarantine",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e51173a97dc3..6a7d5cb451f6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38211,6 +38211,13 @@ export namespace Schemas {
readonly warehouse_origin: unknown;
}
+ export interface ErrorDetail {
+ /** What went wrong and what to do next. */
+ detail: string;
+ /** A stable code for the error, such as `lift_commit_unknown` or `rate_limited`. */
+ code?: string;
+ }
+
export interface ErrorResponse {
/** Error message */
error: string;