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(reviewhog): production hotfixes for label-triggered reviews (#70866)

Alex Lebedev5f6af619cb9e
diff --git a/.github/workflows/review-hog.yml b/.github/workflows/review-hog.yml
index 8ad184fe8ef5..d2c3513c42e1 100644
--- a/.github/workflows/review-hog.yml
+++ b/.github/workflows/review-hog.yml
@@ -1,8 +1,10 @@
# ReviewHog label trigger.
#
-# When a maintainer adds the `reviewhog` label to a non-fork PR (or pushes to an already-labeled one),
-# 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. Unlike Stamphog, the
+# When a maintainer adds the `reviewhog` label to a non-fork PR (or marks an already-labeled draft as
+# ready for review), 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.
+# Pushes 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 push. 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.
@@ -13,7 +15,7 @@ name: ReviewHog
on:
pull_request:
- types: [labeled, ready_for_review, synchronize]
+ types: [labeled, ready_for_review]
# No GitHub permissions needed — the job only makes an outbound authenticated request; the review is
# fetched and published server-side via the PostHog GitHub App installation token.
@@ -29,7 +31,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 5
# Run only for the `reviewhog` label on a non-fork, non-draft, human-authored PR. On `labeled`
- # the label name is on the event; on `synchronize`/`ready_for_review` it must already be present.
+ # the label name is on the event; on `ready_for_review` it must already be present.
if: >-
!github.event.pull_request.draft
&& github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 4aa9fc11108e..b7d4021bc663 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -2121,6 +2121,8 @@ github-actions[bot] trick), and its Action carries **one** secret (no Anthropic
4. ✅ **The Action:** `.github/workflows/review-hog.yml` — `on: pull_request [labeled, ready_for_review, synchronize]`,
`permissions: {}`, per-PR concurrency, `if:` gates (label + non-fork + non-bot + non-draft), one `curl` with the
bearer secret. `pull_request` (not `pull_request_target`) ⇒ forks get no secret ⇒ can't trigger.
+ **2026-07-14 update:** `synchronize` dropped (ADR 0002) — pushes no longer re-trigger; re-review = re-add the
+ label (or mark an already-labeled draft ready).
5. ⏳ **Later (v2):** label lifecycle (strip-on-non-approval / keep-on-error / dismiss-stale-on-push). (`synchronize` /
`ready_for_review` events are already wired in step 4.) Then **Stage 5b** (iterate-on-same-PR validation).
@@ -2193,7 +2195,7 @@ eval loop still recomputes to measure reviewer changes. New inline comments are
**📌 New comments at an unchanged head → nothing, for now (decision 2026-06-29).** When important new human/bot
review comments appear but the SHA hasn't moved, ReviewHog currently does **nothing**: there's no comment-event
-trigger (the Action fires only on `[labeled, ready_for_review, synchronize]`), and a manual same-head re-trigger
+trigger (the Action fires only on `[labeled, ready_for_review]` since ADR 0002), and a manual same-head re-trigger
hits the early-exit gate above (or, pre-publish, only re-feeds dedup). This is the right scope **while ReviewHog
only _reviews_**. It changes once the **Action plane** ("not just find issues — fix them", see Stage 4 →
_Action plane_) lands: a human reply ("this is wrong" / "please fix this" / answering a finding) should then
diff --git a/products/review_hog/backend/api/trigger.py b/products/review_hog/backend/api/trigger.py
index e44d0c5e5b71..e27ff4538f4d 100644
--- a/products/review_hog/backend/api/trigger.py
+++ b/products/review_hog/backend/api/trigger.py
@@ -10,6 +10,8 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
from products.review_hog.backend.temporal.client import start_review_pr_workflow
from products.review_hog.backend.temporal.types import TRIGGER_LABEL
@@ -53,9 +55,33 @@ def _bearer_token(request: Request) -> str:
def _resolve_run_user_id(team_id: int) -> int | None:
- """The user the sandbox tasks run as, falling back to the team's GitHub integration creator."""
+ """The user the sandbox tasks run as: the GitHub integration creator if still an active org
+ member, else the oldest active org member (same semantics as signals' resolve_user_id_for_team).
+
+ A disabled run user is worse than none: every user-scoped sandbox credential 403s and the agent
+ hangs silently until the poll budget expires, so never return an inactive user here.
+ """
+ team = Team.objects.select_related("organization").get(id=team_id)
integration = Integration.objects.filter(team_id=team_id, kind="github").order_by("id").first()
- return integration.created_by_id if integration is not None else None
+ if integration is not None and integration.created_by_id:
+ creator_is_active = OrganizationMembership.objects.filter(
+ organization=team.organization,
+ user_id=integration.created_by_id,
+ user__is_active=True,
+ ).exists()
+ if creator_is_active:
+ return integration.created_by_id
+ logger.warning(
+ "ReviewHog run-user fallback: integration creator %s is not an active org member",
+ integration.created_by_id,
+ )
+ membership = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization=team.organization, user__is_active=True)
+ .order_by("id")
+ .first()
+ )
+ return membership.user_id if membership else None
class ReviewHogTriggerViewSet(viewsets.ViewSet):
@@ -126,7 +152,21 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):
user_id = settings.REVIEWHOG_RUN_USER_ID or _resolve_run_user_id(team_id)
if not user_id:
return Response(
- {"error": "No run user configured and no GitHub integration creator found for the team"},
+ {"error": "No active run user found for the team (no GitHub integration creator or org member)"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ # Fail loud here rather than silently downstream: sandbox credentials are authorized against
+ # active org membership, so an unauthorized run user hangs the review until its poll budget expires.
+ run_user_is_authorized = OrganizationMembership.objects.filter(
+ organization__team__id=team_id,
+ user_id=user_id,
+ user__is_active=True,
+ ).exists()
+ if not run_user_is_authorized:
+ # The Action echoes error bodies into public CI logs, so the id stays server-side.
+ logger.warning("ReviewHog trigger: run user %s is not an active member of the team's organization", user_id)
+ return Response(
+ {"error": "Configured run user is not an active member of the team's organization"},
status=status.HTTP_400_BAD_REQUEST,
)
diff --git a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
index e2cb181d08e2..31218f63640f 100644
--- a/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
+++ b/products/review_hog/backend/reviewer/tools/prepare_validation_markdown.py
@@ -128,14 +128,16 @@ def _render_review_body(
chunk_type = chunk.chunk_type.replace("_", " ").capitalize() if chunk.chunk_type else "Changes"
lines.extend([f"## {chunk_type}", ""])
- if chunk.files:
- file_list = ", ".join(f"`{f.filename}`" for f in chunk.files)
- lines.extend([f"**Files:** {file_list}", ""])
-
if issue_count > 0:
issues_label = "issue" if issue_count == 1 else "issues"
lines.extend([f"**Issues:** {issue_count} {issues_label}", ""])
+ if chunk.files:
+ lines.extend(["<details>", f"<summary>Files ({len(chunk.files)})</summary>", "<br>", ""])
+ for f in chunk.files:
+ lines.append(f"- `{f.filename}`")
+ lines.extend(["", "</details>", ""])
+
if chunk.key_changes:
lines.extend(["<details>", "<summary>What were the main changes</summary>", "<br>", ""])
for change in chunk.key_changes:
@@ -167,8 +169,14 @@ def _render_off_diff_section(findings: list[tuple[Issue, IssueValidation]]) -> l
"",
" | ".join(meta),
"",
+ "<details>",
+ "<summary><strong>Issue description</strong></summary>",
+ "<br>",
+ "",
issue.issue,
"",
+ "</details>",
+ "",
"<details>",
"<summary><strong>Suggested fix</strong></summary>",
"<br>",
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index 94a2ae3753c4..46277c473e89 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -195,10 +195,14 @@ def _format_issue_comment(finding: ReviewIssueFinding, verdict: ValidationVerdic
"",
" | ".join(meta_parts),
"",
- "---",
+ "<details>",
+ "<summary><strong>Issue description</strong></summary>",
+ "<br>",
"",
finding.body,
"",
+ "</details>",
+ "",
"<details>",
"<summary><strong>Suggested fix</strong></summary>",
"<br>",
diff --git a/products/review_hog/backend/tests/test_trigger_api.py b/products/review_hog/backend/tests/test_trigger_api.py
index 323d66b076d3..8e569cc7e3a6 100644
--- a/products/review_hog/backend/tests/test_trigger_api.py
+++ b/products/review_hog/backend/tests/test_trigger_api.py
@@ -7,6 +7,9 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
+from posthog.models.user import User
TRIGGER_URL = "/api/review_hog/trigger/"
_START = "products.review_hog.backend.api.trigger.start_review_pr_workflow"
@@ -14,6 +17,15 @@ _START = "products.review_hog.backend.api.trigger.start_review_pr_workflow"
@override_settings(REVIEWHOG_TRIGGER_TOKEN="secret-token", REVIEWHOG_TEAM_ID=99, REVIEWHOG_RUN_USER_ID=42)
class TestReviewHogTriggerApi(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ # The class-level REVIEWHOG_TEAM_ID=99 / REVIEWHOG_RUN_USER_ID=42 must be a real team and an
+ # active member of its org: the trigger rejects unauthorized run users (their sandbox
+ # credentials 403 and the review hangs).
+ self.trigger_team = Team.objects.create(id=99, organization=self.organization, name="reviewhog trigger")
+ self.run_user = User.objects.create(id=42, email="[email protected]")
+ OrganizationMembership.objects.create(organization=self.organization, user=self.run_user)
+
@patch(_START, return_value="wf-1")
def test_valid_trigger_starts_workflow_and_publishes_by_default(self, mock_start):
resp = self.client.post(
@@ -127,3 +139,54 @@ class TestReviewHogTriggerApi(APIBaseTest):
)
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
self.assertEqual(mock_start.call_args.kwargs["user_id"], self.user.id)
+
+ @parameterized.expand(
+ [
+ ("membership_removed", False),
+ ("still_member_but_disabled", True),
+ ]
+ )
+ @override_settings(REVIEWHOG_RUN_USER_ID=None)
+ @patch(_START, return_value="wf-1")
+ def test_inactive_integration_creator_falls_back_to_active_org_member(self, _name, keep_membership, mock_start):
+ departed = User.objects.create(email="[email protected]", is_active=False)
+ if keep_membership:
+ OrganizationMembership.objects.create(organization=self.organization, user=departed)
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="inst-1",
+ config={},
+ sensitive_config={},
+ created_by=departed,
+ )
+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id):
+ resp = self.client.post(
+ TRIGGER_URL,
+ {"repo": "PostHog/posthog", "pr_number": 1},
+ format="json",
+ HTTP_AUTHORIZATION="Bearer secret-token",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
+ self.assertEqual(mock_start.call_args.kwargs["user_id"], self.user.id)
+
+ @parameterized.expand(
+ [
+ ("deactivated", True),
+ ("active_but_not_org_member", False),
+ ]
+ )
+ @patch(_START, return_value="wf-1")
+ def test_unauthorized_configured_run_user_rejected(self, _name, deactivate, mock_start):
+ if deactivate:
+ User.objects.filter(id=42).update(is_active=False)
+ else:
+ OrganizationMembership.objects.filter(user_id=42).delete()
+ resp = self.client.post(
+ TRIGGER_URL,
+ {"repo": "PostHog/posthog", "pr_number": 1},
+ format="json",
+ HTTP_AUTHORIZATION="Bearer secret-token",
+ )
+ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_start.assert_not_called()
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index 978b2e30f668..c0352aa60ffc 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -32,7 +32,7 @@ OutputFn = Callable[[str], object] | None
# Sandbox logs polling from S3
POLL_INTERVAL_SECONDS = 10
-MAX_POLL_SECONDS = 30 * 60 # 30 minutes (matches sandbox TTL)
+MAX_POLL_SECONDS = 30 * 60 # default per-turn budget; callers with longer turns pass max_poll_seconds
MAX_CONSECUTIVE_STORAGE_ERRORS = 3
# Continuous log silence required before salvaging a dropped-finalization turn — one SSE read window
# (SSE_READ_TIMEOUT_SECONDS). The null-cost finalization fingerprint (_ended_on_pending_finalization)