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(github): retry an unmapped 4xx status instead of crashing the sync (#104130)

Tom Owerse68a7ffdd251
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
index 52d631d11878..5e42ba124e0e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
@@ -5,6 +5,7 @@ import asyncio
import dataclasses
from collections.abc import AsyncIterator, Callable, Iterator
from datetime import UTC, date, datetime, timedelta
+from http import HTTPStatus
from itertools import batched
from typing import Any, Literal, Optional
from urllib.parse import urlencode, urlsplit
@@ -903,6 +904,20 @@ def _pace_before_request(installation_id: str, logger: FilteringBoundLogger) ->
time.sleep(pace)
+def _is_unmapped_client_status(status_code: int) -> bool:
+ """A 4xx `HTTPStatus` doesn't recognize, like the nginx-style 499 ("client closed request")
+ GitHub's edge has been observed returning from `/graphql` on an upstream hiccup. It's not a
+ denial GitHub meant to send us, so group it with the 5xx path instead of crashing the sync on
+ an unclassified HTTPError. Mirrors the Hubspot source's `_is_retryable_status`."""
+ if not (400 <= status_code < 500):
+ return False
+ try:
+ HTTPStatus(status_code)
+ except ValueError:
+ return True
+ return False
+
+
# Transient failures every GitHub call retries on, REST and GraphQL alike.
_GITHUB_RETRYABLE_ERRORS = (
GithubRetryableError,
@@ -958,7 +973,7 @@ def _fetch_page(
)
# Transient server errors: retry with plain exponential backoff.
- if response.status_code >= 500:
+ if response.status_code >= 500 or _is_unmapped_client_status(response.status_code):
raise GithubRetryableError(f"Github API error (retryable): status={response.status_code}, url={page_url}")
# Rate limited (secondary 429, or primary 403 with a rate-limit body): raise
@@ -1463,7 +1478,7 @@ def _fetch_merge_commit_shas(
},
)
- if response.status_code >= 500:
+ if response.status_code >= 500 or _is_unmapped_client_status(response.status_code):
raise GithubRetryableError(f"Github GraphQL error (retryable): status={response.status_code}")
raise_if_github_rate_limited(response)
if response.status_code in {401, 403, 404}:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py
index c2f0a74db4d5..4a606d0bfa3c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py
@@ -156,6 +156,20 @@ def test_fetch_page_retries_chunked_encoding_error():
assert session.request.call_count == 2
+def test_fetch_page_treats_unmapped_4xx_as_retryable():
+ # GitHub's edge has been observed returning the nginx-style 499 ("client closed request") on an
+ # upstream hiccup. It's not a real denial, so it must retry like a 5xx rather than crash the sync
+ # on a raw, unclassified HTTPError.
+ session = mock.Mock()
+ session.request.return_value = _error_response(499, "Unknown")
+
+ with mock.patch.object(github, "make_tracked_session", return_value=session):
+ with pytest.raises(github.GithubRetryableError):
+ github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock())
+
+ assert session.request.call_count == 5
+
+
def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():
session = mock.Mock()
session.request.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken")] * 5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
index 47ebd0519d2b..0126e93814f1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
@@ -537,6 +537,24 @@ class TestMergeCommitSha:
assert github_request.call_count == 5
+ def test_an_unmapped_4xx_status_retries_before_failing_the_walk(self) -> None:
+ # GitHub's edge has been observed returning the nginx-style 499 ("client closed request")
+ # from `/graphql` on an upstream hiccup — not a real denial. It must retry like a 5xx
+ # instead of crashing the walk on the unclassified HTTPError `raise_for_status()` would
+ # otherwise produce, which tenacity never retries.
+ graphql = mock.Mock()
+ graphql.status_code = 499
+ page = _response([self._pull_request(7, merged=True)])
+
+ with (
+ mock.patch.object(github, "github_request", return_value=graphql) as github_request,
+ mock.patch.object(github, "_github_backoff_wait", return_value=0.0),
+ pytest.raises(github.GithubRetryableError),
+ ):
+ _run("pull_requests", {"api.github.com": page})
+
+ assert github_request.call_count == 5
+
@parameterized.expand([("advertised reset", 900, 900), ("no reset header", None, 60)])
def test_graphql_rate_limit_carries_a_wait_that_outlasts_the_window(
self, _name: str, reset_in: int | None, expected_retry_after: int