:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(stamphog): hide dismissed approvals as outdated (#105644)
Julian Bez632b5966544f
diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 72ccb0224496..3f221408ede0 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -125,6 +125,7 @@ Why the digest works this way: [`docs/digest.md`](docs/digest.md).Hosted flow: webhook → Celery (`backend/tasks/tasks.py`) → Temporal (`backend/temporal/workflow.py`) → sandboxed engine → verdict posted back (`post_verdict`).The workflow dismisses stale approvals first, waits out other in-flight reviewer bots, then reviews.+A dismissed approval is also hidden on the PR timeline as outdated, so superseded reviews do not pile up. Hiding is best-effort and never blocks the dismissal.Reviews run in an isolated Modal sandbox with per-run minted credentials.The sandbox clones the repository, checks out the PR head, and runs `review_local.py` against a pre-fetched context, with no GitHub token inside the sandbox.diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.pyindex c1267f3e6197..937a851966c0 100644--- a/products/stamphog/backend/logic/github_client.py+++ b/products/stamphog/backend/logic/github_client.py@@ -422,6 +422,7 @@ class StamphogGitHubClient:headers: dict[str, str] | None = None,timeout: int = 15,stream: bool = False,+ priority: Priority = Priority.CRITICAL,) -> requests.Response:"""Installation-authenticated request through the gated egress transport.@@ -441,7 +442,7 @@ class StamphogGitHubClient:source=_SOURCE,headers={**(headers or {}), "Authorization": f"Bearer {token}"},installation_id=self.installation_id,- priority=Priority.CRITICAL,+ priority=priority,endpoint=endpoint,params=params,json=json_body,@@ -1147,6 +1148,53 @@ class StamphogGitHubClient:f"Failed to dismiss review {review_id} on {repo}#{pr_number}: {response.text[:200]}",status_code=response.status_code,)+ try:+ node_id = self._json(response, path).get("node_id")+ except (StamphogGitHubError, AttributeError):+ node_id = None+ if node_id:+ self._minimize_as_outdated(node_id, repo=repo, pr_number=pr_number, review_id=review_id)++ def _minimize_as_outdated(self, node_id: str, *, repo: str, pr_number: int, review_id: int) -> None:+ """Hide a dismissed review as "Outdated" on the PR timeline (GraphQL ``minimizeComment``).++ Fail-open: the dismissal already retracted the approval, and hiding the review is only noise+ reduction. A failure here must never make the caller retry a dismissal that succeeded.+ """+ mutation = (+ "mutation($id: ID!) { minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) "+ "{ minimizedComment { isMinimized } } }"+ )+ log_fields = {"repo": repo, "pr_number": pr_number, "review_id": review_id}+ try:+ # BATCH lets the egress limiter shed this cosmetic call before it spends budget that dismissals need.+ response = self._request(+ "POST",+ "/graphql",+ endpoint="/graphql",+ json_body={"query": mutation, "variables": {"id": node_id}},+ priority=Priority.BATCH,+ )+ except Exception:+ logger.warning("stamphog_github_minimize_dismissed_review_request_failed", **log_fields, exc_info=True)+ return+ if response.status_code != 200:+ logger.warning(+ "stamphog_github_minimize_dismissed_review_http_error", **log_fields, status_code=response.status_code+ )+ return+ try:+ data = self._json(response, "/graphql")+ except StamphogGitHubError:+ logger.warning("stamphog_github_minimize_dismissed_review_non_json_response", **log_fields)+ return+ if not isinstance(data, dict) or data.get("errors"):+ errors = data.get("errors") if isinstance(data, dict) else None+ logger.warning(+ "stamphog_github_minimize_dismissed_review_graphql_errors",+ **log_fields,+ error_types=[e.get("type") for e in errors or [] if isinstance(e, dict)],+ )def upsert_sticky_comment(self, repo: str, number: int, body: str) -> dict:"""Create or update Stamphog's single status comment on a PR, identified by a hidden marker.diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.pyindex 355489f28aae..cb71b930a89d 100644--- a/products/stamphog/backend/tests/fakes.py+++ b/products/stamphog/backend/tests/fakes.py@@ -267,8 +267,13 @@ class GitHubRecorder:def _graphql(self, body: dict) -> FakeResponse:query = str(body.get("query") or "")variables = body.get("variables") or {}- # Two GraphQL callers share /graphql: get_pr_review_threads and get_user_team_slugs. Route by- # the query's shape (only the review-threads query mentions reviewThreads).+ # GraphQL callers share /graphql: get_pr_review_threads, get_user_team_slugs, and the+ # minimizeComment mutation after a dismissal. Route by the query's shape.+ if "minimizeComment" in query:+ self.github_writes.append({"kind": "minimize_review", "node_id": variables.get("id"), "query": query})+ return FakeResponse(+ 200, json_data={"data": {"minimizeComment": {"minimizedComment": {"isMinimized": True}}}}+ )if "reviewThreads" in query:repo = f"{variables.get('owner', '')}/{variables.get('name', '')}"number = int(variables.get("pr") or 0)@@ -345,7 +350,7 @@ class GitHubRecorder:for review in self.pr_reviews.get((repo, number), []):if review.get("id") == review_id:review["state"] = "DISMISSED"- return FakeResponse(200, json_data={})+ return FakeResponse(200, json_data={"id": review_id, "node_id": f"PRR_{review_id}", "state": "DISMISSED"})def _extract(query: str, prefix: str) -> str:diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.pyindex 0e88bf9c2e8a..3b935848e98e 100644--- a/products/stamphog/backend/tests/test_integration.py+++ b/products/stamphog/backend/tests/test_integration.py@@ -477,6 +477,9 @@ def test_failed_run_still_dismisses_the_stale_approval_first(team, stamphog_chaiassert prior.approval_dismissed_at is not Nonedismissals = [w for w in recorder.github_writes if w["kind"] == "dismiss_review"]assert [w["review_id"] for w in dismissals] == [777]+ minimized = [w for w in recorder.github_writes if w["kind"] == "minimize_review"]+ assert [w["node_id"] for w in minimized] == ["PRR_777"]+ assert "classifier: OUTDATED" in minimized[0]["query"]@pytest.mark.django_db(databases=PRODUCT_DATABASES)diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.pyindex 82135c4eefbd..1d93a6c38014 100644--- a/products/stamphog/backend/tests/test_logic.py+++ b/products/stamphog/backend/tests/test_logic.py@@ -507,10 +507,13 @@ class GetPrReviewThreadsTests(SimpleTestCase):self._fetch(self._threads_page([], has_next=True))-# add_pr_reaction / remove_pr_reaction are deliberately the one fail-open pair on the client-# (see their docstrings): a cosmetic "review in flight" 👀 must never fail or retry the calling-# review activity, unlike every other read/write on StamphogGitHubClient.-class PrReactionFailOpenTests(SimpleTestCase):+# The client's cosmetic writes fail open (see their docstrings): the "review in flight" 👀 reaction+# and hiding a dismissed review as outdated must never fail or retry the calling activity, unlike+# every other read/write on StamphogGitHubClient.+class CosmeticWriteFailOpenTests(SimpleTestCase):+ def setUp(self) -> None:+ self.requested_urls: list[str] = []+def _call(self,transport_response_or_error: fakes.FakeResponse | Exception,@@ -519,6 +522,9 @@ class PrReactionFailOpenTests(SimpleTestCase):def fake_request(method: str, url: str, **kwargs: object) -> fakes.FakeResponse:if url.endswith("/access_tokens"):return fakes.FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})+ self.requested_urls.append(url)+ if url.endswith("/dismissals"):+ return fakes.FakeResponse(200, json_data={"id": 999, "node_id": "PRR_999"})if isinstance(transport_response_or_error, Exception):raise transport_response_or_errorreturn transport_response_or_error@@ -562,6 +568,20 @@ class PrReactionFailOpenTests(SimpleTestCase):result = self._call(response, lambda c: c.add_pr_reaction("acme/widgets", 5))assert result == 555+ @parameterized.expand(+ [+ ("http_error", fakes.FakeResponse(502, text="bad gateway")),+ ("graphql_errors", fakes.FakeResponse(200, json_data={"errors": [{"message": "forbidden"}]})),+ ("non_json_body", fakes.FakeResponse(200, text="not json")),+ ("transport_exception", RuntimeError("network blew up")),+ ]+ )+ def test_failed_minimize_does_not_fail_a_successful_dismissal(+ self, _name: str, minimize_failure: fakes.FakeResponse | Exception+ ) -> None:+ self._call(minimize_failure, lambda c: c.dismiss_pr_review("acme/widgets", 5, 999, "stale"))+ assert self.requested_urls[-1] == "https://api.github.com/graphql"+class BuildAppJwtIssuerTests(SimpleTestCase):@parameterized.expand(