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(stamphog): say on the pull request when a review failed (#91525)

Julian Bez591bd983cec3
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index c56a21b4f742..ca7151120062 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -949,6 +949,11 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:
first_error_line = (input.error.splitlines() or [""])[0][:300]
if run.status in TERMINAL_STATUSES:
activity.logger.warning(f"Run {run.id} already {run.status}; keeping it, error was: {first_error_line}")
+ # A retry that died between the FAILED save and the notice finds its own run terminal. Keep
+ # the status, but post the notice the author is still owed. Only FAILED resumes: every other
+ # terminal state belongs to a run that gave a verdict.
+ if run.status == ReviewRunStatus.FAILED:
+ _post_failure_notice(StamphogGitHubClient(run.pull_request.repo_config.installation_id), run, input.team_id)
return
# A prior post_verdict attempt may have approved on GitHub and then exhausted retries before the
# terminal save — the id is persisted, the verdict is not, and without a future delivery nothing
@@ -965,8 +970,11 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:
# Conditional like every terminal save (the load-time guard above can race an in-flight
# supersession): a run that just went SUPERSEDED keeps that status, FAILED must not clobber it.
now = timezone.now()
- ReviewRun.objects.for_team(input.team_id).filter(id=run.id).exclude(status__in=TERMINAL_STATUSES).update(
- status=ReviewRunStatus.FAILED, error=first_error_line, completed_at=now, updated_at=now
+ marked_failed = (
+ ReviewRun.objects.for_team(input.team_id)
+ .filter(id=run.id)
+ .exclude(status__in=TERMINAL_STATUSES)
+ .update(status=ReviewRunStatus.FAILED, error=first_error_line, completed_at=now, updated_at=now)
)
# This run is done reviewing (unrecoverably) — clean up its own "review in flight" 👀 too. After
# the terminal save on purpose: the removal's live-peer check must see this run as terminal, or
@@ -984,6 +992,7 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:
# the global client's background flush may never run before the worker thread moves on.
pull_request = run.pull_request
repo = pull_request.repo_config.repository
+
with ph_scoped_capture() as capture:
capture(
distinct_id=pull_request.author_login or repo,
@@ -997,6 +1006,11 @@ def mark_review_failed(input: MarkReviewFailedInput) -> None:
},
)
+ # Last, because this step raises. A retry returns through the terminal guard, which posts the
+ # notice and nothing else, so the event above must reach PostHog on this attempt.
+ if marked_failed:
+ _post_failure_notice(client, run, input.team_id)
+
def _harden_reviewer_command(command: Sequence[str] | str) -> str:
"""Turn the reviewer invocation into a shell string that runs uv in isolation.
@@ -1329,6 +1343,47 @@ def _post_non_approval_review(
ReviewRun.objects.for_team(team_id).filter(id=run.id).update(output=run.output, updated_at=timezone.now())
+FAILURE_NOTICE_BODY = (
+ "**The review did not complete.**\n\n"
+ "Stamphog hit an error and produced no verdict for this commit.\n\n"
+ "Push a new commit to try again."
+)
+
+
+def _post_failure_notice(client: StamphogGitHubClient, run: ReviewRun, team_id: int) -> None:
+ """Tell the PR that this run gave no verdict, once.
+
+ The notice names a push, because that route works in every mode. A failure keeps the trigger
+ label, so a push carries it and starts a run, while a re-added label waits out the per-PR
+ cooldown. A self-driving run ignores labels and re-reviews only on synchronize, reopen and base
+ retarget.
+
+ The notice gives no error text, because this is a public pull request.
+
+ A newer run at the same head stops the notice. Supersession skips terminal states, so a
+ `reopened` delivery can queue a replacement at the unchanged head, and that replacement can
+ approve the commit this notice would call unreviewed. A newer run at a different head is not a
+ replacement. The read uses the writer, because it gates a GitHub write.
+
+ A GitHub error propagates. If this function hides it, the activity completes, Temporal does not
+ retry, and the PR keeps no notice. Raising is safe: the FAILED update is committed, and the retry
+ finishes the post through the terminal guard.
+ """
+ replaced_at_same_head = (
+ ReviewRun.objects.for_team(team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(pull_request_id=run.pull_request_id, head_sha=run.head_sha, created_at__gt=run.created_at)
+ .exists()
+ )
+ if replaced_at_same_head:
+ activity.logger.info(f"Skipping the failure notice for run {run.id}; a newer run holds the same head")
+ return
+
+ _post_non_approval_review(
+ client, run.pull_request.repo_config.repository, run, run.pull_request, team_id, FAILURE_NOTICE_BODY
+ )
+
+
def _comment_id(obj: dict) -> int | None:
"""Pull the numeric id out of a GitHub review/comment response, or None."""
value = obj.get("id") if isinstance(obj, dict) else None
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index deafa1858eb8..7a8b33173a5b 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -157,6 +157,8 @@ class GitHubRecorder:
# Test hook: raise this exception from the label-add POST (e.g. GitHubRateLimitError) to
# exercise the best-effort catch for exception types the client does not raise itself.
self.add_label_side_effect: Exception | None = None
+ # Set to make posting a COMMENT review blow up, e.g. a rate limit on the failure notice.
+ self.comment_review_side_effect: Exception | None = None
self.teams_by_login: dict[str, list[str]] = {}
self.policy_files: dict[str, str] = {}
# Per-repository overrides for the same paths, for cases where two connected repos must
@@ -211,6 +213,8 @@ class GitHubRecorder:
# Split by event so a test asserting on approvals never matches a COMMENT review.
event = (json_body or {}).get("event")
kind = "approve_review" if event == "APPROVE" else "comment_review"
+ if kind == "comment_review" and self.comment_review_side_effect is not None:
+ raise self.comment_review_side_effect
return self._record_write(kind, m.group("repo"), int(m.group("number")), json_body)
if method == "GET" and (m := _ISSUE_COMMENTS_RE.match(path)):
page = int(params.get("page", 1))
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 6c02148f15f2..788767a0495c 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -249,9 +249,8 @@ def test_failure_once_the_sandbox_exists_is_not_retried(team, stamphog_chain: St
run = ReviewRun.objects.for_team(team.id).latest("created_at")
assert run.status == ReviewRunStatus.FAILED
- # The record names the marker and the failing type, and carries nothing from the sandbox: run.error
- # is readable with stamphog:read by people who need no access to the repository, and everything in
- # this phase derives from an untrusted PR head.
+ # The record names the marker and the type, and nothing from the sandbox. Anyone with
+ # stamphog:read can read run.error, and this phase reads an untrusted PR head.
assert run.error == "SandboxPhaseError: the sandbox phase failed with RuntimeError"
assert "modal refused the box" not in (run.error or "")
@@ -281,9 +280,8 @@ def test_a_second_attempt_never_provisions_a_second_sandbox(team, stamphog_chain
def test_malformed_repo_policy_keeps_the_parser_text_out_of_the_error() -> None:
- # PyYAML names the offending construct on its first line, and that line is what mark_review_failed
- # persists into run.error, which is readable with stamphog:read by people who need no access to
- # the repository. The default branch it comes from is private to that repository.
+ # PyYAML names the bad tag on its first line, and run.error keeps that line. Anyone with
+ # stamphog:read can read it without access to the repository the policy file comes from.
with pytest.raises(RuntimeError) as raised:
activities._overlay_policy_yaml("acme/widgets", "version: 1\n", "!a-private-internal-tag {}\n")
@@ -291,6 +289,141 @@ def test_malformed_repo_policy_keeps_the_parser_text_out_of_the_error() -> None:
assert ".stamphog/policy.yml" in str(raised.value)
+ "review_mode,self_driving",
+ [(ReviewMode.LABEL, False), (ReviewMode.ALL, False), (ReviewMode.LABEL, True)],
+ ids=["label_mode", "all_mode", "self_driving"],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_failed_run_says_so_on_the_pull_request(
+ team, stamphog_chain: StamphogChain, review_mode: ReviewMode, self_driving: bool
+) -> None:
+ # A failure keeps the trigger label, so the per-PR cooldown rejects a re-added one and a
+ # self-driving run ignores labels. A push is the only route that starts a run in every mode.
+ repo_config = _repo_config(team.id)
+ repo_config.review_mode = review_mode
+ repo_config.save()
+ head_sha = "sha-failed"
+ stamphog_chain.recorder.register_pr(REPO, 114, _pr_object(114, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=114, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id,
+ pull_request=pull_request,
+ head_sha=head_sha,
+ status=ReviewRunStatus.REVIEWING,
+ output={"inbox_review": True} if self_driving else {},
+ )
+
+ _run_activity(
+ mark_review_failed,
+ MarkReviewFailedInput(str(run.id), team.id, "SandboxPhaseError: modal refused the box"),
+ )
+
+ notices = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"]
+ assert len(notices) == 1
+ body = notices[0]["body"]["body"]
+ assert body.startswith("**The review did not complete.**")
+ assert "Push a new commit to try again." in body
+ assert "label" not in body # the cooldown makes a relabel the one route that can do nothing
+ # The cause belongs on the run and in the worker logs, never on a public pull request.
+ assert "modal refused the box" not in body
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_superseded_run_posts_no_failure_notice(team, stamphog_chain: StamphogChain) -> None:
+ # A superseded run must stay quiet: its replacement holds the same head. Two guards give that,
+ # the terminal-status return this case reaches and the marked_failed gate. Driving the race
+ # between them needs a mocked load, so this pins the outcome they share.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-superseded"
+ stamphog_chain.recorder.register_pr(REPO, 115, _pr_object(115, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=115, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.SUPERSEDED
+ )
+
+ _run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, "RuntimeError: worker lost"))
+
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.SUPERSEDED # the terminal guard held
+ assert [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"] == []
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_no_failure_notice_once_a_newer_run_holds_the_same_head(team, stamphog_chain: StamphogChain) -> None:
+ # `reopened` does not move the head, and supersession skips terminal states, so a replacement
+ # can hold the same head. That replacement can approve the commit this notice calls unreviewed.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-reopened"
+ stamphog_chain.recorder.register_pr(REPO, 118, _pr_object(118, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=118, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.REVIEWING
+ )
+ ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.QUEUED
+ )
+
+ _run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, "RuntimeError: worker lost"))
+
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.FAILED # the run still records its own outcome
+ assert [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"] == []
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_notice_github_error_fails_the_activity_so_temporal_retries(team, stamphog_chain: StamphogChain) -> None:
+ # A hidden error completes the activity, so Temporal does not retry and the PR keeps no notice.
+ # A rate limit does this. The FAILED update is committed, so raising cannot undo it.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-notice-error"
+ stamphog_chain.recorder.register_pr(REPO, 117, _pr_object(117, "devex-dev", head_sha))
+ stamphog_chain.recorder.comment_review_side_effect = GitHubRateLimitError("secondary rate limit")
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=117, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.REVIEWING
+ )
+
+ with pytest.raises(GitHubRateLimitError):
+ _run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, "RuntimeError: worker lost"))
+
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.FAILED # committed before the post, so the raise leaves it
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_retry_finishes_a_notice_the_previous_attempt_never_posted(team, stamphog_chain: StamphogChain) -> None:
+ # The activity marks the run FAILED, removes its reaction, sweeps GitHub, then posts. An attempt
+ # that dies in that window leaves a FAILED run with no notice, and the retry finds it terminal.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-resumed"
+ stamphog_chain.recorder.register_pr(REPO, 116, _pr_object(116, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=116, author_login="devex-dev"
+ )
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id, pull_request=pull_request, head_sha=head_sha, status=ReviewRunStatus.FAILED
+ )
+
+ _run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, "RuntimeError: worker lost"))
+
+ notices = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"]
+ assert len(notices) == 1
+ assert notices[0]["body"]["body"].startswith("**The review did not complete.**")
+
+ # And only once: the recorded review id makes a further retry a no-op.
+ _run_activity(mark_review_failed, MarkReviewFailedInput(str(run.id), team.id, "RuntimeError: worker lost"))
+ assert len([w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"]) == 1
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
team, user, stamphog_chain: StamphogChain
@@ -837,7 +970,7 @@ def test_fetch_review_context_carries_inline_review_threads(team, stamphog_chain
ids=["single_line", "multiline_truncated_to_first_line"],
)
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
-def test_mark_review_failed_captures_failure_event(team, raw_error, expected_stored) -> None:
+def test_mark_review_failed_captures_failure_event(team, stamphog_chain, raw_error, expected_stored) -> None:
# Hosted failures used to be visible only in worker logs; the dashboards need the
# stamphog_review_failed event next to the review-completed ones. The stored error is scrubbed to
# its first line so raw exception text can't leak repo file content to stamphog:read.