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(review-hog): retry the publish past a github budget window (#115219)

Julian Bez225744d3bff5
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index bfa270a8afa6..fe3fa95ae0a6 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -59,6 +59,7 @@ from products.review_hog.backend.reviewer.tools.github_client import (
github_api_get_paginated,
github_api_request,
is_app_bot_author,
+ is_transient_github_error,
)
from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised
from products.review_hog.backend.reviewer.tools.redaction import redact_secrets
@@ -685,7 +686,9 @@ class FinalizeStatusCommentInput:
def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
- """Rewrite the status comment with the turn's outcome: everything found vs. what was published."""
+ """Rewrite the status comment with the turn's outcome: everything found vs. what was published.
+
+ A transient GitHub error raises, so the activity's retry policy tries the edit again."""
try:
report = ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first()
if report is None or report.status_comment_id is None or report.pr_number is None:
@@ -715,7 +718,9 @@ def finalize_status_comment(input: FinalizeStatusCommentInput) -> None:
if redacted:
logger.warning("Redacted %s credential-shaped string(s) from the status comment", redacted)
_edit_and_stamp(input.team_id, report, body)
- except Exception:
+ except Exception as error:
+ if is_transient_github_error(error):
+ raise
logger.exception("Could not finalize the ReviewHog status comment; the review is unaffected")
diff --git a/products/review_hog/backend/reviewer/tools/github_client.py b/products/review_hog/backend/reviewer/tools/github_client.py
index 73a4ca2e0642..4346de92a1c5 100644
--- a/products/review_hog/backend/reviewer/tools/github_client.py
+++ b/products/review_hog/backend/reviewer/tools/github_client.py
@@ -14,7 +14,12 @@ from django.conf import settings
import requests
-from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
+from posthog.egress.github.transport import (
+ GitHubEgressBudgetExhausted,
+ GitHubRateLimitError,
+ github_request,
+ raise_if_github_rate_limited,
+)
from posthog.egress.limiter.policies import Priority
logger = logging.getLogger(__name__)
@@ -58,6 +63,13 @@ class GitHubAPIError(Exception):
self.api_message = api_message
+def is_transient_github_error(error: BaseException) -> bool:
+ """A GitHub failure a later attempt can get past: our own budget, GitHub's rate limit, a 5xx, or the network."""
+ return isinstance(error, GitHubEgressBudgetExhausted | GitHubRateLimitError | requests.RequestException) or (
+ isinstance(error, GitHubAPIError) and error.status >= 500
+ )
+
+
def _api_message(response: requests.Response) -> str:
try:
body = response.json()
diff --git a/products/review_hog/backend/reviewer/tools/publish_review.py b/products/review_hog/backend/reviewer/tools/publish_review.py
index 14953cbf3f94..240036da62a8 100644
--- a/products/review_hog/backend/reviewer/tools/publish_review.py
+++ b/products/review_hog/backend/reviewer/tools/publish_review.py
@@ -29,6 +29,7 @@ from products.review_hog.backend.reviewer.tools.github_client import (
github_api_get_paginated,
github_api_request,
is_app_bot_author,
+ is_transient_github_error,
)
from products.review_hog.backend.reviewer.tools.github_threads import REVIEW_HOG_FINDING_MARKER
from products.review_hog.backend.reviewer.tools.redaction import redact_secrets
@@ -335,8 +336,9 @@ def _review_already_posted(
) -> bool:
"""True if a review carrying this run's `marker` is already on the PR (we posted, then crashed).
- Best-effort idempotency backstop: if the readback fails we proceed to post rather than silently
- drop the review — the `published_head_sha` watermark still guards the common retry path. Only
+ Best-effort idempotency backstop: a transient readback failure raises, because an earlier attempt
+ may have posted already and the activity retries. Any other readback failure proceeds to post rather
+ than silently drop the review — the `published_head_sha` watermark still guards the common retry path. Only
our own app-bot's reviews count (`is_app_bot_author`, shared with the status comment's marker
scan): on a public repo anyone can paste the marker, and a spoofed match would silently
suppress the publish.
@@ -361,6 +363,8 @@ def _review_already_posted(
)
)
except (GitHubAPIError, GitHubRateLimitError) as e:
+ if is_transient_github_error(e):
+ raise
logger.warning(f"Could not read existing reviews to check publish idempotency: {e}. Proceeding to post.")
return False
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index 36bb8fcd1acd..f0cca50ccaa1 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -26,6 +26,7 @@ from temporalio import activity
from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.event_usage import groups
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team.team import Team
@@ -1873,6 +1874,13 @@ def _publish(input: PublishInput) -> PublishResult:
return PublishResult(posted=outcome.posted, review_url=outcome.review_url)
+def _wait_for_github_reset(error: GitHubRateLimitError) -> ApplicationError | GitHubRateLimitError:
+ # GitHub names its reset time, at most an hour away, which can be later than the retry policy's next attempt.
+ if error.retry_after is None:
+ return error
+ return ApplicationError(str(error), next_retry_delay=datetime.timedelta(seconds=error.retry_after))
+
+
@activity.defn
@scoped_temporal()
@close_db_connections
@@ -1882,7 +1890,10 @@ async def publish_review_activity(input: PublishInput) -> PublishResult:
The per-run publish gate lives in the workflow (`inputs.publish`): this activity is dispatched
only when publishing is enabled and the turn has a PR to post to.
"""
- return await database_sync_to_async(_publish, thread_sensitive=False)(input)
+ try:
+ return await database_sync_to_async(_publish, thread_sensitive=False)(input)
+ except GitHubRateLimitError as error:
+ raise _wait_for_github_reset(error) from error
def _remove_trigger_label(input: RemoveTriggerLabelInput) -> None:
@@ -2251,7 +2262,10 @@ async def post_status_comment_activity(input: StatusCommentInput) -> None:
@close_db_connections
async def finalize_status_comment_activity(input: FinalizeStatusCommentInput) -> None:
"""Rewrite the status comment with the turn's outcome: full found counts vs. what was published."""
- await database_sync_to_async(finalize_status_comment, thread_sensitive=False)(input)
+ try:
+ await database_sync_to_async(finalize_status_comment, thread_sensitive=False)(input)
+ except GitHubRateLimitError as error:
+ raise _wait_for_github_reset(error) from error
def _fail_run(team_id: int, report_id: str, review_mode: str = REVIEW_MODE_FULL, run_index: int | None = None) -> None:
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index d716632c7811..14a50a88667a 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -140,6 +140,14 @@ _ONESHOT_RETRY = RetryPolicy(
# output limit — a killed sandbox or half-flushed log tail raises the same type and recovers on
# retry. Only the one-shot path can read stop_reason == "max_tokens" and fail fast on it.
)
+# The GitHub writes that carry the result to the PR. Another caller can exhaust the shared
+# installation budget for a minute or two, and GitHub returns 5xx in short spells, so the waits
+# (30s, 60s, 120s) outlast both. A retry never double-posts, because publish checks its marker first.
+_GITHUB_POST_RETRY = RetryPolicy(
+ maximum_attempts=4,
+ initial_interval=timedelta(seconds=30),
+ backoff_coefficient=2.0,
+)
def _enforce_failure_floor(stage: str, failed: int, total: int) -> None:
@@ -783,7 +791,7 @@ class ReviewPRWorkflow:
trigger_source=inputs.trigger_source,
),
start_to_close_timeout=_QUICK_TIMEOUT,
- retry_policy=_RETRY,
+ retry_policy=_GITHUB_POST_RETRY,
)
elif inputs.publish:
workflow.logger.info("No PR to publish to (branch target); the review is stored only")
@@ -885,7 +893,7 @@ class ReviewPRWorkflow:
raised_elsewhere_count=dedup.raised_elsewhere_count if dedup is not None else 0,
),
start_to_close_timeout=_QUICK_TIMEOUT,
- retry_policy=_RETRY,
+ retry_policy=_GITHUB_POST_RETRY,
)
except Exception:
workflow.logger.warning("Could not finalize the status comment")
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index 295deedd31d6..bc82051208af 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -1,13 +1,19 @@
from collections.abc import Callable, Iterator
from dataclasses import replace
+from datetime import timedelta
from typing import Any
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.test import override_settings
from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import ActivityEnvironment
+
+from posthog.egress.github.transport import GitHubRateLimitError
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.constants import LEGACY_FLASH_MODE_MESSAGE_PREFIX
@@ -21,7 +27,7 @@ from products.review_hog.backend.reviewer.tools.publish_review import (
_review_already_posted,
_review_marker,
)
-from products.review_hog.backend.temporal.activities import PublishInput, _publish
+from products.review_hog.backend.temporal.activities import PublishInput, _publish, publish_review_activity
# `_publish` now delegates to `publish_persisted_review` in the tool, so the GitHub-post seam and the
# snapshot load are patched there; the installation auth is still resolved in the activity wrapper.
@@ -29,14 +35,17 @@ _PUBLISH = "products.review_hog.backend.reviewer.tools.publish_review.publish_re
_SNAPSHOT = "products.review_hog.backend.reviewer.tools.publish_review.load_pr_snapshot"
_AUTH = "products.review_hog.backend.temporal.activities._installation_auth"
_PAGINATED = "products.review_hog.backend.reviewer.tools.publish_review.github_api_get_paginated"
+_ACTIVITIES = "products.review_hog.backend.temporal.activities"
-def _paginated(items: list[dict[str, Any]], *, boom: bool = False) -> Callable[..., Iterator[dict[str, Any]]]:
+def _paginated(
+ items: list[dict[str, Any]], *, boom: bool = False, status: int = 500
+) -> Callable[..., Iterator[dict[str, Any]]]:
"""A github_api_get_paginated stand-in yielding `items` (or failing the readback with `boom`)."""
def fake(path: str, **kwargs: Any) -> Iterator[dict[str, Any]]:
if boom:
- raise GitHubAPIError("readback failed", status=500)
+ raise GitHubAPIError("readback failed", status=status)
return iter(items)
return fake
@@ -78,7 +87,17 @@ def test_review_already_posted_detects_our_own_markered_review() -> None:
def test_review_already_posted_proceeds_when_readback_fails() -> None:
# Best-effort: if listing reviews errors we post rather than silently drop the review (the
# published_head_sha watermark still guards the common retry path).
- assert _review_posted(_review_marker("rep-1", "sha1"), [], boom=True) is False
+ with patch(_PAGINATED, side_effect=_paginated([], boom=True, status=404)):
+ assert (
+ _review_already_posted("o", "r", 1, _review_marker("rep-1", "sha1"), token="t", installation_id=None)
+ is False
+ )
+
+
+def test_review_already_posted_raises_on_a_transient_readback_failure() -> None:
+ # An earlier attempt may have posted already, so posting blind on a 5xx risks a second review.
+ with pytest.raises(GitHubAPIError):
+ _review_posted(_review_marker("rep-1", "sha1"), [], boom=True)
@parameterized.expand(
@@ -274,3 +293,14 @@ class TestPublishIdempotency(BaseTest):
_publish(replace(_publish_input(self.team.id, report_id, "sha1"), trigger_source="automatic"))
report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
assert report.automatic_reviewed_head_sha is None
+
+
+async def test_publish_waits_for_the_rate_limit_reset_github_names() -> None:
+ with (
+ patch(f"{_ACTIVITIES}._publish", side_effect=GitHubRateLimitError("limited", retry_after=3000)),
+ pytest.raises(ApplicationError) as raised,
+ ):
+ await ActivityEnvironment().run(publish_review_activity, _publish_input(1, "rep-1", "sha1"))
+
+ assert raised.value.next_retry_delay == timedelta(seconds=3000)
diff --git a/products/review_hog/backend/tests/test_status_comment.py b/products/review_hog/backend/tests/test_status_comment.py
index 3513d1c76cc0..1977212e777b 100644
--- a/products/review_hog/backend/tests/test_status_comment.py
+++ b/products/review_hog/backend/tests/test_status_comment.py
@@ -2,13 +2,17 @@ from collections.abc import Callable
from datetime import timedelta
from typing import Any
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
+import requests
from parameterized import parameterized
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+
from products.review_hog.backend.models import ReviewReport
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
@@ -36,6 +40,7 @@ from products.review_hog.backend.reviewer.status_comment import (
status_marker,
update_resolution_status_comment,
)
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.review_hog.backend.reviewer.tools.issue_deduplicator import AlreadyRaised
from products.review_hog.backend.temporal.activities import _fail_run
@@ -501,6 +506,33 @@ _OLD_BODY = (
)
+class TestFinalizeStatusCommentErrors(BaseTest):
+ @parameterized.expand(
+ [
+ ("egress_budget", GitHubEgressBudgetExhausted("shed", scope="1"), True),
+ ("github_5xx", GitHubAPIError("boom", status=502), True),
+ ("network", requests.ConnectionError("reset"), True),
+ ("github_4xx", GitHubAPIError("gone", status=404), False),
+ ]
+ )
+ def test_transient_github_errors_raise_so_the_activity_retries(
+ self, _name: str, error: Exception, raises: bool
+ ) -> None:
+ report_id = upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
+ ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(status_comment_id=555)
+ finalize_input = FinalizeStatusCommentInput(
+ team_id=self.team.id, report_id=report_id, run_index=1, urgency_threshold=IssuePriority.CONSIDER.value
+ )
+
+ with patch(_INTEGRATION) as mock_integration, patch(_REQUEST, side_effect=error):
+ _wire_auth(mock_integration)
+ if raises:
+ with pytest.raises(type(error)):
+ finalize_status_comment(finalize_input)
+ else:
+ finalize_status_comment(finalize_input)
+
+
class TestResolutionRow:
@parameterized.expand(
[