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(stamphog): hand refused PRs to ReviewHog via trigger label (#72509)

Paul D'Ambra973814fc52c8
diff --git a/.github/workflows/review-hog.yml b/.github/workflows/review-hog.yml
index e1b052925841..324e14fca18a 100644
--- a/.github/workflows/review-hog.yml
+++ b/.github/workflows/review-hog.yml
@@ -1,13 +1,13 @@
# ReviewHog label trigger.
#
-# When a maintainer adds the `reviewhog` label to a non-fork PR (any author, drafts included), this
-# makes ONE authenticated call to the PostHog `review_hog` trigger endpoint, which starts the review
-# Temporal workflow server-side and publishes the review back to the PR. One label add = one review:
-# pushes and ready-for-review deliberately do NOT re-trigger — re-reviewing is an explicit gesture
-# (remove and re-add the label), so a labeled PR can keep evolving without burning a review per event.
-# Unlike Stamphog, the agent does NOT run in CI: there is no checkout, no app token, no Anthropic key
-# here — the only secret is the shared trigger token. Publishing happens server-side via the PostHog
-# GitHub App installation token.
+# When the `reviewhog` label is added to a non-fork PR — by a maintainer, or by stamphog[bot] handing
+# off a refused/escalated PR — this makes ONE authenticated call to the PostHog `review_hog` trigger
+# endpoint, which starts the review Temporal workflow server-side and publishes the review back to the
+# PR. One label add = one review: pushes and ready-for-review deliberately do NOT re-trigger —
+# re-reviewing is an explicit gesture (remove and re-add the label), so a labeled PR can keep evolving
+# without burning a review per event. Unlike Stamphog, the agent does NOT run in CI: there is no
+# checkout, no app token, no Anthropic key here — the only secret is the shared trigger token.
+# Publishing happens server-side via the PostHog GitHub App installation token.
#
# Safety: `pull_request_target` always runs the base branch's version of this file, so a PR cannot
# edit its own trigger, and it fires even when the PR has merge conflicts. It does expose secrets to
@@ -33,12 +33,13 @@ jobs:
name: Trigger ReviewHog review
runs-on: ubuntu-latest
timeout-minutes: 5
- # Run only when a human applies the `reviewhog` label to a non-fork PR — any author (drafts
- # and bots included), but the labeler must be a person: the label is the explicit human request.
+ # Run when the `reviewhog` label lands on a non-fork PR from an allowed labeler: a human, or
+ # stamphog[bot] handing off a refused/escalated PR. Other bots are skipped below. Any author
+ # (drafts and bots included); the label is the explicit review request.
if: >-
github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
- && github.event.sender.type != 'Bot'
&& github.event.label.name == 'reviewhog'
+ && (github.event.sender.type != 'Bot' || github.event.sender.login == 'stamphog[bot]')
steps:
- name: Trigger ReviewHog review
env:
@@ -61,8 +62,8 @@ jobs:
-H "Content-Type: application/json" \
-d "$payload"
- # The trigger job skips bot-applied labels silently; explain why and strip the label so a
- # human can re-add it deliberately.
+ # The trigger job skips bot-applied labels silently (stamphog[bot] excepted — it hands off
+ # refused PRs and is routed above); explain why and strip the label so a human can re-add it.
bot-labeler-skip:
name: Explain skipped bot label
runs-on: ubuntu-latest
@@ -72,6 +73,7 @@ jobs:
if: >-
github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
&& github.event.sender.type == 'Bot'
+ && github.event.sender.login != 'stamphog[bot]'
&& github.event.label.name == 'reviewhog'
steps:
- name: Comment and strip label
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index 8e0eb7e05fec..6a3fa74aba28 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -1024,6 +1024,35 @@ class StamphogGitHubClient:
status_code=response.status_code,
)
+ def add_pr_label(self, repo: str, number: int, label: str) -> None:
+ """Add a label to a PR (``POST .../issues/{number}/labels``).
+
+ A 404 (repo not found) or 422 (label does not exist on the repo) is swallowed, so a vendored
+ stamphog in another repo never raises over a label — e.g. ``reviewhog`` — that isn't set up
+ there. Any other non-success raises ``StamphogGitHubError``; see ``post_verdict`` for how the
+ ReviewHog handoff caller treats that as best-effort.
+ """
+ path = f"/repos/{repo}/issues/{number}/labels"
+ response = self._request(
+ "POST",
+ path,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/labels",
+ json_body={"labels": [label]},
+ )
+ if response.status_code in (404, 422):
+ logger.info(
+ "stamphog github: reviewhog label unavailable on repo, skipping handoff",
+ repo=repo,
+ pr_number=number,
+ status_code=response.status_code,
+ )
+ return
+ if response.status_code not in (200, 201):
+ raise StamphogGitHubError(
+ f"Failed to add label to {repo}#{number}: {response.text[:200]}",
+ status_code=response.status_code,
+ )
+
def dismiss_pr_review(self, repo: str, pr_number: int, review_id: int, message: str) -> None:
"""Dismiss a previously submitted review (``PUT .../reviews/{review_id}/dismissals``).
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 55a14a98adae..801ef5cdf567 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -55,6 +55,7 @@ from products.stamphog.backend.temporal.constants import (
STAMPHOG_POLICY_ENTRYPOINT,
STAMPHOG_POLICY_PATHS,
STAMPHOG_REVIEW_GUIDANCE_PATH,
+ STAMPHOG_REVIEWHOG_LABEL,
STAMPHOG_SANDBOX_CONTEXT_PATH,
STAMPHOG_SANDBOX_ENGINE_DIR,
STAMPHOG_SANDBOX_OWNERS_DIR,
@@ -750,14 +751,15 @@ def post_verdict(input: StamphogReviewInput) -> dict:
run.status = ReviewRunStatus.COMPLETED
run.verdict = parsed.verdict
+ # Keyed off parsed.verdict, not run.verdict: the gate-blocked branch overrides run.verdict to WAIT,
+ # but both the label-strip and the ReviewHog handoff below treat a gate-blocked refusal the same
+ # as an engine-refused one.
+ is_refusal = parsed.verdict in (ReviewVerdict.REFUSED, ReviewVerdict.ESCALATE)
+
# Action parity: in label-triggered mode a refused/escalated verdict strips the trigger label, so
- # the author re-requests the next review by re-adding it. Keyed off parsed.verdict, not run.verdict —
- # the gate-blocked branch overrides run.verdict to WAIT but the Action strips on gate refusals too.
+ # the author re-requests the next review by re-adding it.
# A failure here raises on purpose: the activity retries and the sticky upsert above is idempotent.
- if repo_config.review_mode == ReviewMode.LABEL and parsed.verdict in (
- ReviewVerdict.REFUSED,
- ReviewVerdict.ESCALATE,
- ):
+ if repo_config.review_mode == ReviewMode.LABEL and is_refusal:
client.remove_pr_label(repo, pull_request.pr_number, repo_config.trigger_label)
run.completed_at = timezone.now()
@@ -781,6 +783,28 @@ def post_verdict(input: StamphogReviewInput) -> dict:
activity.logger.info(f"Run {run.id} superseded during verdict posting; verdict not saved")
return {"verdict": "skipped_superseded"}
+ # Hand a refused/escalated PR to ReviewHog only AFTER the refusal verdict wins the terminal save
+ # above — running it before would trigger ReviewHog for a stale refusal that a superseding delivery
+ # then overrode (a newer run might approve the same head). Same is_refusal condition as the
+ # trigger-label strip above, in both review modes: stamphog couldn't sign off, so a deeper
+ # second-opinion review is wanted. Adding the ReviewHog trigger label fires its workflow
+ # (review-hog.yml exempts stamphog[bot] from the bot-labeler-skip that would otherwise strip it).
+ # This is a secondary, cross-product notification that must never jeopardize the verdict — the
+ # refusal is already durably saved, so it is single-shot best-effort: catching every exception (not
+ # just StamphogGitHubError) contains the client's own errors plus the GitHubRateLimitError /
+ # requests.RequestException the egress layer raises on rate limits and network blips, neither a
+ # subclass of StamphogGitHubError. The sticky upsert above is idempotent, so a missed handoff is a
+ # missed handoff, not corruption.
+ if is_refusal:
+ try:
+ client.add_pr_label(repo, pull_request.pr_number, STAMPHOG_REVIEWHOG_LABEL)
+ except Exception:
+ # Format repo/pr into the message — activity.logger is a stdlib LoggerAdapter that
+ # raises TypeError on arbitrary kwargs, which would escape this best-effort catch.
+ activity.logger.exception(
+ f"stamphog: reviewhog handoff failed for {repo}#{pull_request.pr_number}; verdict still posted"
+ )
+
# Close the merge-before-approval race only AFTER this run's APPROVED verdict is durably saved. If
# the PR auto-merged the instant GitHub recorded the approval, the closed webhook may run before this
# save committed and find no approved run, so it stamps nothing; stamping here (which refreshes
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 03615ee5b025..44db328e417a 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -38,6 +38,12 @@ STAMPHOG_TRUSTED_REACTOR_BOTS = frozenset(
STAMPHOG_BOT_EYES_MAX_AGE_SECONDS = 45 * 60
STAMPHOG_BOT_REVIEW_POLL_SECONDS = 30
STAMPHOG_BOT_REVIEW_MAX_POLLS = 10 # ~300s budget at 30s per poll, matching the Action's wait budget
+
+# The GitHub label Stamphog adds to hand a refused/escalated PR to ReviewHog. ``review-hog.yml``
+# routes this label (when applied by stamphog[bot] — the one sanctioned bot exempted from its
+# bot-labeler-skip) to the ReviewHog trigger endpoint. Kept here so the activity references the same
+# scalar the workflow gates on.
+STAMPHOG_REVIEWHOG_LABEL = "reviewhog"
# The posthog-owners resolver package, expected by the engine as a sibling of its own dir
# (gates.py resolves `../owners` for the hogli-resolver ownership format).
STAMPHOG_SANDBOX_OWNERS_DIR = f"{STAMPHOG_SANDBOX_REPO_DIR}/tools/owners"
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index 4f736787e3a4..18dea4c56b0c 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -97,6 +97,7 @@ _ISSUE_COMMENTS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/(?P<numbe
_COMMENT_PATCH_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/comments/(?P<cid>\d+)$")
_DISMISS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/pulls/(?P<number>\d+)/reviews/(?P<rid>\d+)/dismissals$")
_LABEL_DELETE_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/(?P<number>\d+)/labels/(?P<label>[^/]+)$")
+_LABEL_ADD_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/issues/(?P<number>\d+)/labels$")
_CONTENTS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/contents/(?P<path>.+)$")
_CHECK_RUNS_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/commits/(?P<sha>[^/]+)/check-runs$")
_COLLABORATOR_PERMISSION_RE = re.compile(r"^/repos/(?P<repo>[^/]+/[^/]+)/collaborators/(?P<username>[^/]+)/permission$")
@@ -147,6 +148,12 @@ class GitHubRecorder:
# Test hook: force every reaction POST to return this response (e.g. a 500) to
# exercise the client's fail-open path without monkeypatching bound methods.
self.reaction_response_override: FakeResponse | None = None
+ # Test hook: force every label-add POST to return this response (e.g. a 422 for a label that
+ # does not exist on the repo) to exercise the handoff's best-effort swallow path.
+ self.add_label_response_override: FakeResponse | None = None
+ # 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
self.teams_by_login: dict[str, list[str]] = {}
self.policy_files: dict[str, str] = {}
self.github_writes: list[dict[str, Any]] = []
@@ -206,6 +213,8 @@ class GitHubRecorder:
return self._record_write("issue_comment_edit", m.group("repo"), 0, json_body)
if method == "PUT" and (m := _DISMISS_RE.match(path)):
return self._dismiss_review(m.group("repo"), int(m.group("number")), int(m.group("rid")), json_body)
+ if method == "POST" and (m := _LABEL_ADD_RE.match(path)):
+ return self._add_label(m.group("repo"), int(m.group("number")), json_body)
if method == "DELETE" and (m := _LABEL_DELETE_RE.match(path)):
return self._remove_label(m.group("repo"), int(m.group("number")), m.group("label"))
@@ -301,6 +310,19 @@ class GitHubRecorder:
self.github_writes.append({"kind": "remove_label", "repo": repo, "number": number, "label": label})
return FakeResponse(200, json_data=[])
+ def _add_label(self, repo: str, number: int, body: dict | None) -> FakeResponse:
+ labels = (body or {}).get("labels", [])
+ self.github_writes.append({"kind": "add_label", "repo": repo, "number": number, "labels": labels})
+ # A side effect set by the test simulates the egress layer raising before the response is
+ # returned — a GitHubRateLimitError (the real raise_if_github_rate_limited is stubbed to a
+ # no-op in the chain, so the rate-limit path is otherwise unreachable in tests) or a
+ # requests.RequestException on a network blip. Exercises the handoff's best-effort catch.
+ if self.add_label_side_effect is not None:
+ raise self.add_label_side_effect
+ if self.add_label_response_override is not None:
+ return self.add_label_response_override
+ return FakeResponse(200, json_data=[{"name": n} for n in labels])
+
def _dismiss_review(self, repo: str, number: int, review_id: int, body: dict | None) -> FakeResponse:
self.github_writes.append(
{"kind": "dismiss_review", "repo": repo, "number": number, "review_id": review_id, "body": body or {}}
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 02208c643589..c487144e3405 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -9,6 +9,9 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
from django.utils import timezone
+import requests
+
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models import OAuthAccessToken, Team
from posthog.models.integration import Integration
@@ -181,6 +184,9 @@ def test_signed_webhook_drives_review_and_posts_approval(team, stamphog_chain: S
assert len(additions) == 1
assert [r["reaction_id"] for r in removals] == [additions[0]["id"]]
+ # An APPROVED verdict never hands off to ReviewHog — the reviewhog label is a refusal-only signal.
+ assert [w for w in recorder.github_writes if w["kind"] == "add_label"] == []
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_sandbox_destroy_failure_does_not_mask_a_completed_review(team, stamphog_chain: StamphogChain) -> None:
@@ -1058,6 +1064,101 @@ def test_refused_verdict_strips_trigger_label_only_in_label_mode(
else:
assert label_removals == []
+ # A refused PR hands off to ReviewHog by adding its trigger label, in both review modes —
+ # stamphog couldn't sign off, so a deeper second-opinion review is wanted regardless of how the
+ # review was triggered.
+ label_adds = [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "add_label"]
+ assert label_adds == [{"kind": "add_label", "repo": REPO, "number": 101, "labels": ["reviewhog"]}]
+
+
+ "fault",
+ [
+ # The client swallows a 422 (label missing on the repo) itself; a 500 raises StamphogGitHubError.
+ pytest.param(422, id="swallows_missing_label"),
+ pytest.param(500, id="client_raises_on_500"),
+ # The egress layer raises these directly — not subclasses of StamphogGitHubError, so a narrow
+ # except would let them escape post_verdict and skip the durable verdict save below.
+ pytest.param(GitHubRateLimitError("secondary rate limit"), id="rate_limit_does_not_escape"),
+ pytest.param(requests.ConnectionError("network blip"), id="network_error_does_not_escape"),
+ ],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_refused_verdict_lands_even_when_reviewhog_handoff_fails(
+ team,
+ stamphog_chain: StamphogChain,
+ fault: int | Exception,
+) -> None:
+ # The ReviewHog handoff is a secondary, cross-product notification that runs AFTER the durable
+ # terminal save, so the refusal itself is never at risk — it's already committed by the time the
+ # handoff fires. Left uncaught, though, the exception would fail the activity and trigger a retry,
+ # re-running already-succeeded side effects (posting the sticky comment, stripping the trigger
+ # label) even though the verdict is saved; catching it keeps the handoff single-shot best-effort.
+ # A 422 is swallowed inside the client; a 500 raises StamphogGitHubError; a rate limit raises
+ # GitHubRateLimitError and a network blip raises requests.RequestException from the egress layer.
+ # All four must leave the run COMPLETED + REFUSED, not FAILED. The latter two are the regression:
+ # they are not subclasses of StamphogGitHubError, so only a broad catch at the call site contains
+ # them.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-refused-handoff"
+ stamphog_chain.recorder.register_pr(REPO, 101, _pr_object(101, "devex-dev", head_sha))
+ if isinstance(fault, Exception):
+ stamphog_chain.recorder.add_label_side_effect = fault
+ else:
+ stamphog_chain.recorder.add_label_response_override = fakes.FakeResponse(fault, text="handoff failure")
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=101, 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={"reviewer_raw": _refused_engine_output()},
+ )
+
+ _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.COMPLETED
+ assert run.verdict == ReviewVerdict.REFUSED
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_superseded_refusal_does_not_hand_off_to_reviewhog(team, stamphog_chain: StamphogChain) -> None:
+ # The ReviewHog handoff runs AFTER the conditional terminal save, so a refusal that loses the save
+ # to a supersession (a synchronize/re-review delivery landing between the head guard and the save)
+ # must not trigger ReviewHog for the stale refusal — a newer run may approve the same head. The run
+ # returns skipped_superseded and the reviewhog label is never added.
+ repo_config = _repo_config(team.id)
+ head_sha = "sha-refused-superseded"
+ stamphog_chain.recorder.register_pr(REPO, 101, _pr_object(101, "devex-dev", head_sha))
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=101, 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={"reviewer_raw": _refused_engine_output()},
+ )
+ # A concurrent delivery flips the run to SUPERSEDED during the sticky-comment post (before the
+ # terminal save), so the conditional .exclude(status=SUPERSEDED).update(...) matches nothing and the
+ # run returns skipped_superseded. This reaches the terminal-save early return, NOT the top guard —
+ # the run is REVIEWING at load.
+ original_post_sticky = activities._post_sticky
+
+ def _supersede_then_post(client, repo, pr, body) -> None:
+ ReviewRun.objects.for_team(team.id).filter(id=run.id).update(status=ReviewRunStatus.SUPERSEDED)
+ original_post_sticky(client, repo, pr, body)
+
+ with patch.object(activities, "_post_sticky", side_effect=_supersede_then_post):
+ result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert result == {"verdict": "skipped_superseded"}
+ assert [w for w in stamphog_chain.recorder.github_writes if w["kind"] == "add_label"] == []
+
@pytest.mark.parametrize(
"review_enabled,approved_at_sha,expected_audience_key",