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(tasks): back off on GitHub rate limits in get_pr_context (#74568)

posthog[bot]dc2b5d735d2c
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index 729d4b25dafb..e84415614b02 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -1,3 +1,4 @@
+from datetime import timedelta
from typing import Any, Optional
from temporalio.exceptions import ApplicationError
@@ -57,6 +58,32 @@ class TaskRunNotReadyError(ProcessTaskTransientError):
ProcessTaskError.__init__(self, message, context, None, non_retryable=False)
+class GitHubRateLimitedError(ProcessTaskTransientError):
+ """GitHub rate-limited a call (or our egress budget shed it before it was sent).
+
+ An expected, recoverable condition rather than a fault. Kept retryable so the
+ activity's retry policy recovers once the limit window passes, but intentionally
+ not captured to error tracking — there is nothing to investigate, and capturing
+ it mints a noisy issue for something we expect to happen. ``retry_after`` (seconds)
+ drives ``next_retry_delay`` so the retry lands after the window instead of burning
+ every attempt inside it, and is folded into the message so the surfaced error names
+ a real wait instead of an empty reset time.
+ """
+
+ def __init__(self, message: str, context: dict[str, Any], retry_after: int):
+ # Bypass ProcessTaskTransientError.__init__ to pass cause=None with capture=False,
+ # skipping the capture_exception() call in ProcessTaskError (mirrors TaskRunNotReadyError).
+ ProcessTaskError.__init__(
+ self,
+ message,
+ context,
+ None,
+ capture=False,
+ non_retryable=False,
+ next_retry_delay=timedelta(seconds=retry_after),
+ )
+
+
class TaskInvalidStateError(ProcessTaskFatalError):
pass
diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
index 372eb60e8e67..e3794ab4a4e6 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py
@@ -6,16 +6,21 @@ from django.core.exceptions import ObjectDoesNotExist
from temporalio import activity
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
from posthog.models import Integration
from posthog.models.integration import GitHubIntegration
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.temporal.common.utils import close_db_connections
-from products.tasks.backend.exceptions import ProcessTaskTransientError
+from products.tasks.backend.exceptions import GitHubRateLimitedError, ProcessTaskTransientError
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.observability import log_activity_execution
from products.tasks.backend.temporal.process_task.activities import TaskProcessingContext
+# GitHub's documented guidance when it rate-limits without timing headers is to wait ≥1 minute;
+# also the fallback for our own egress-budget shed, which carries no reset hint.
+DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS = 60
+
@dataclass
class GetPrContextInput:
@@ -132,6 +137,21 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:
if not pull_request.get("success"):
return None
fingerprint = compute_pr_fingerprint(pull_request)
+ except (GitHubRateLimitError, GitHubEgressBudgetExhausted) as e:
+ # A GitHub rate limit (its own 429) or our egress budget shedding the call is a
+ # normal, recoverable condition — not a fault. Keep it retryable but skip error
+ # tracking capture, and honor the backoff hint so the retry lands after the limit
+ # window instead of burning every attempt inside it.
+ retry_after = getattr(e, "retry_after", None) or DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS
+ raise GitHubRateLimitedError(
+ f"GitHub rate limited PR context fetch for URL {pr_url}; retrying in {retry_after}s",
+ context={
+ "pr_url": pr_url,
+ "github_integration_id": ctx.github_integration_id,
+ "github_user_integration_id": ctx.github_user_integration_id,
+ },
+ retry_after=retry_after,
+ )
except Exception as e:
# A failed snapshot fetch is almost always a transient GitHub hiccup (a network
# blip, a rate limit, or a 200-with-`errors` GraphQL server error). Raise it as
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py
index 3908ea1374ce..853b768049b7 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_pr_context.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import timedelta
import pytest
from unittest.mock import MagicMock, patch
@@ -7,8 +8,11 @@ from django.core.exceptions import ObjectDoesNotExist
from parameterized import parameterized
-from products.tasks.backend.exceptions import ProcessTaskTransientError
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+
+from products.tasks.backend.exceptions import GitHubRateLimitedError, ProcessTaskTransientError
from products.tasks.backend.temporal.process_task.activities.get_pr_context import (
+ DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS,
GetPrContextInput,
GetPrContextOutput,
compute_pr_fingerprint,
@@ -242,6 +246,42 @@ class TestGetPrContextActivity:
self._run(ctx)
assert exc_info.value.non_retryable is False
+ # pytest.mark.parametrize (not parameterized.expand) so the test_task_run fixture still injects.
+ @pytest.mark.parametrize(
+ "raised, expected_backoff",
+ [
+ # GitHub's own 429 with a reset hint: the retry must wait that long.
+ (GitHubRateLimitError("resets at None", retry_after=60), 60),
+ # Hand-built rate-limit error with no hint falls back to the ≥1 minute default.
+ (GitHubRateLimitError("rate limited"), DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS),
+ # Our own egress budget shedding the call carries no reset hint either.
+ (GitHubEgressBudgetExhausted("shed"), DEFAULT_GITHUB_RATE_LIMIT_BACKOFF_SECONDS),
+ ],
+ )
+ @pytest.mark.django_db
+ def test_rate_limit_stays_retryable_uncaptured_and_honors_backoff(self, raised, expected_backoff, test_task_run):
+ # A rate limit is a normal, recoverable condition: it must retry after the hinted
+ # window (not within 1s, which abandons the follow-up run) and must not be captured
+ # to error tracking (which mints a noisy issue for something we expect to happen).
+ pr_url = "https://github.com/org/repo/pull/1"
+ test_task_run.output = {"pr_url": pr_url}
+ test_task_run.save(update_fields=["output"])
+
+ integration = MagicMock()
+ integration.get_pull_request_snapshot.side_effect = raised
+
+ ctx = self._ctx(run_id=str(test_task_run.id))
+ with (
+ patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration),
+ patch("products.tasks.backend.exceptions.capture_exception") as mock_capture,
+ ):
+ with pytest.raises(GitHubRateLimitedError) as exc_info:
+ self._run(ctx)
+
+ assert exc_info.value.non_retryable is False
+ assert exc_info.value.next_retry_delay == timedelta(seconds=expected_backoff)
+ mock_capture.assert_not_called()
+
@pytest.mark.django_db
def test_ci_status_change_yields_different_fingerprint(self, test_task_run):
# When CI actually transitions (pending -> failing) the workflow must see a new