: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): retry transient GitHub GraphQL server errors instead of failing the run (#69652)
Alessandro Pogliaghi33b93dc7b1e9
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 108ed077855f..8b0b8791b3b9 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -840,34 +840,81 @@ class GitHubIntegrationBase:}"""+ # GitHub surfaces its own transient server errors not as a 5xx but as an HTTP 200 with+ # ``data: null`` and an ``errors`` body — the documented "Something went wrong while+ # executing your query" class, plus ``SERVICE_UNAVAILABLE``/timeout errors. Because the+ # HTTP status is 200, :meth:`api_request`'s status-code retry never sees them, so we detect+ # and retry them here. They are safe to repeat (GraphQL reads are idempotent and the query+ # never executed); deterministic field-level errors (permissions, validation) are not.+ _TRANSIENT_GRAPHQL_ERROR_TYPES = frozenset({"SERVICE_UNAVAILABLE"})+ _TRANSIENT_GRAPHQL_ERROR_MESSAGES = ("something went wrong while executing your query",)+ # Total GraphQL attempts (initial + retries) when GitHub returns a transient body error.+ _GRAPHQL_TRANSIENT_ATTEMPTS = 3++ @classmethod+ def _graphql_errors_are_transient(cls, errors: list) -> bool:+ """True when the GraphQL ``errors`` body is one of GitHub's retryable server-side failures.++ Conservative: any single error that isn't a known transient class (e.g. a field-level+ permission or validation error) makes the whole response non-retryable, so we never+ loop on a deterministic failure.+ """+ if not errors:+ return False+ for error in errors:+ if not isinstance(error, dict):+ return False+ if error.get("type") in cls._TRANSIENT_GRAPHQL_ERROR_TYPES:+ continue+ message = str(error.get("message", "")).lower()+ if any(marker in message for marker in cls._TRANSIENT_GRAPHQL_ERROR_MESSAGES):+ continue+ return False+ return True+def _gh_graphql(self, query: str, variables: dict[str, Any], *, endpoint: str, timeout: int = 10) -> dict:"""Authenticated POST to the GitHub GraphQL API. Returns the ``data`` object.GraphQL queries are read-only, so a POST retry on transient failures is safe —- hence ``retry_transient=True`` on the shared :meth:`api_request` lifecycle.+ hence ``retry_transient=True`` on the shared :meth:`api_request` lifecycle, plus an+ extra retry loop here for GitHub's 200-with-``errors`` transient server errors that+ the status-code retry can't catch."""- response = self.api_request(- "POST",- "/graphql",- endpoint=endpoint,- json_body={"query": query, "variables": variables},- timeout=timeout,- retry_transient=True,- )- if response.status_code != 200:- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_graphql {response.status_code} on {endpoint}: {response.text[:300]}",- status_code=response.status_code,+ errors: Any = None+ for attempt in range(self._GRAPHQL_TRANSIENT_ATTEMPTS):+ response = self.api_request(+ "POST",+ "/graphql",+ endpoint=endpoint,+ json_body={"query": query, "variables": variables},+ timeout=timeout,+ retry_transient=True,)- body = response.json()- data = body.get("data")- errors = body.get("errors")- if errors:- # GitHub can return useful partial data with field-level permission errors.- logger.warning("GitHubIntegration: GraphQL partial errors", endpoint=endpoint, errors=errors)- if not data:- raise GitHubIntegrationError(f"GitHubIntegration: GraphQL errors on {endpoint}: {errors}")- return data or {}+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_graphql {response.status_code} on {endpoint}: {response.text[:300]}",+ status_code=response.status_code,+ )+ body = response.json()+ data = body.get("data")+ errors = body.get("errors")+ if not errors:+ return data or {}+ if data:+ # GitHub can return useful partial data with field-level permission errors.+ logger.warning("GitHubIntegration: GraphQL partial errors", endpoint=endpoint, errors=errors)+ return data+ # No data — a hard failure. Retry GitHub's transient server errors; raise the rest.+ if not self._graphql_errors_are_transient(errors):+ break+ if attempt < self._GRAPHQL_TRANSIENT_ATTEMPTS - 1:+ logger.info(+ "GitHubIntegration: retrying transient GraphQL error",+ endpoint=endpoint,+ attempt=attempt,+ errors=errors,+ )+ raise GitHubIntegrationError(f"GitHubIntegration: GraphQL errors on {endpoint}: {errors}")@staticmethoddef _map_pr_state(gql_state: str | None, is_draft: bool) -> str:diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 0614423fcb7d..b69da0b63dff 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -2251,6 +2251,84 @@ class TestGitHubIntegrationGhApiGet(BaseTest):GitHubIntegration(integration)._gh_api_get("repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+class TestGitHubIntegrationGraphQL(BaseTest):+ def _create_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="INSTALL",+ config={"installation_id": "INSTALL", "account": {"name": "PostHog"}},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ )++ @staticmethod+ def _graphql_response(body: dict) -> MagicMock:+ # GitHub returns transient GraphQL server errors as an HTTP 200 with an ``errors`` body,+ # so the retry decision hinges on the body, not the status code.+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = body+ return resp++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_retries_transient_server_error_and_returns_data(self, _mock_expired, mock_request):+ # A 200-with-`errors` "Something went wrong" server error must be retried, not raised —+ # otherwise a transient GitHub blip permanently kills the in-flight follow-up run.+ transient = self._graphql_response(+ {"data": None, "errors": [{"message": "Something went wrong while executing your query. (abc123)"}]}+ )+ ok = self._graphql_response({"data": {"repository": {"name": "posthog"}}})+ mock_request.side_effect = [transient, ok]++ github = GitHubIntegration(self._create_integration())+ data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert data == {"repository": {"name": "posthog"}}+ assert mock_request.call_count == 2++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_gives_up_after_exhausting_transient_retries(self, _mock_expired, mock_request):+ # Guards against both a run-killing single attempt and an unbounded retry loop.+ transient = self._graphql_response(+ {"data": None, "errors": [{"type": "SERVICE_UNAVAILABLE", "message": "unavailable"}]}+ )+ mock_request.return_value = transient++ github = GitHubIntegration(self._create_integration())+ with pytest.raises(GitHubIntegrationError):+ github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert mock_request.call_count == GitHubIntegration._GRAPHQL_TRANSIENT_ATTEMPTS++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_does_not_retry_deterministic_error(self, _mock_expired, mock_request):+ # A deterministic error (bad query, missing field, permission) will never succeed on+ # retry, so it must raise on the first attempt rather than burn the retry budget.+ mock_request.return_value = self._graphql_response(+ {"data": None, "errors": [{"type": "FORBIDDEN", "message": "Resource not accessible by integration"}]}+ )++ github = GitHubIntegration(self._create_integration())+ with pytest.raises(GitHubIntegrationError):+ github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert mock_request.call_count == 1++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_returns_partial_data_with_field_errors(self, _mock_expired, mock_request):+ # When GitHub returns usable data alongside field-level errors, keep the data rather+ # than treating the response as a failure.+ mock_request.return_value = self._graphql_response(+ {"data": {"repository": {"name": "posthog"}}, "errors": [{"message": "field-level error"}]}+ )++ github = GitHubIntegration(self._create_integration())+ data = github._gh_graphql("query {}", {}, endpoint="/graphql:test")+ assert data == {"repository": {"name": "posthog"}}+ assert mock_request.call_count == 1++class TestDatabricksIntegrationModel(BaseTest):@patch("posthog.models.integration.is_url_allowed", return_value=(True, None))def test_integration_from_config_with_valid_config(self, mock_is_url_allowed):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.pyindex e9ef6844d4b3..42bdad0fa89e 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@@ -11,7 +11,7 @@ from posthog.models.integration import GitHubIntegrationfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegrationfrom posthog.temporal.common.utils import close_db_connections-from products.tasks.backend.exceptions import TaskInvalidStateError+from products.tasks.backend.exceptions import ProcessTaskTransientErrorfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.observability import log_activity_executionfrom products.tasks.backend.temporal.process_task.activities import TaskProcessingContext@@ -111,7 +111,11 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:return Nonefingerprint = compute_pr_fingerprint(pull_request)except Exception as e:- raise TaskInvalidStateError(+ # 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+ # transient so the activity's retry policy retries it, rather than a fatal+ # non-retryable error that permanently kills the in-flight follow-up run.+ raise ProcessTaskTransientError(f"Failed to fetch PR details from GitHub for URL {pr_url}",context={"pr_url": pr_url,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.pyindex 31ee92682eb0..e7a9de2476cc 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@@ -7,7 +7,7 @@ from django.core.exceptions import ObjectDoesNotExistfrom parameterized import parameterized-from products.tasks.backend.exceptions import TaskInvalidStateError+from products.tasks.backend.exceptions import ProcessTaskTransientErrorfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import (GetPrContextInput,GetPrContextOutput,@@ -216,7 +216,9 @@ class TestGetPrContextActivity:assert result.pr_state == "unknown"@pytest.mark.django_db- def test_raises_task_invalid_state_when_github_call_raises(self, test_task_run):+ def test_raises_transient_error_when_github_call_raises(self, test_task_run):+ # A failed GitHub fetch must be retryable — raising a fatal, non-retryable error here+ # would permanently kill the follow-up run over a transient GitHub hiccup.pr_url = "https://github.com/org/repo/pull/1"test_task_run.output = {"pr_url": pr_url}test_task_run.save(update_fields=["output"])@@ -226,8 +228,9 @@ class TestGetPrContextActivity:ctx = self._ctx(run_id=str(test_task_run.id))with patch(f"{GET_PR_CONTEXT_MODULE}.get_github_integration", return_value=integration):- with pytest.raises(TaskInvalidStateError):+ with pytest.raises(ProcessTaskTransientError) as exc_info:self._run(ctx)+ assert exc_info.value.non_retryable is False@pytest.mark.django_dbdef test_ci_status_change_yields_different_fingerprint(self, test_task_run):