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(google_sheets): retry transient 5xx errors with non-int API codes (#64062)

Tom Owersdb0b48657def
diff --git a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
index f8e79f11e4c4..ad06875eab20 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -71,6 +71,28 @@ _PERMISSION_DENIED_MESSAGE = "Spreadsheet access denied. Please share the spread
T = TypeVar("T")
+def _is_retryable_api_error(e: gspread.exceptions.APIError) -> bool:
+ """Decide whether a gspread APIError is a transient error worth retrying.
+
+ We deliberately key off the HTTP status on the response rather than `e.code`.
+ gspread derives `e.code` from the JSON error body (`error.code`), which is not a
+ reliable signal for transient failures: when Google (or a gateway/proxy in front of
+ it) returns a 5xx/429 with a non-JSON body, gspread falls back to `code = -1`, and
+ some error envelopes carry the code as a string. In those cases the underlying request
+ is still a transient 5xx/429 that should be retried, but a `code`-based check misses it
+ and fails the sync on the first attempt. `response.status_code` is always the real HTTP
+ status, so prefer it and fall back to `e.code` only when it is unavailable."""
+
+ status_code = getattr(getattr(e, "response", None), "status_code", None)
+ if isinstance(status_code, int):
+ return status_code in _RETRYABLE_API_ERROR_CODES
+
+ try:
+ return int(e.code) in _RETRYABLE_API_ERROR_CODES
+ except (TypeError, ValueError):
+ return False
+
+
def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
"""Run `execute` with linear backoff, retrying transient Google Sheets API
errors. Google Sheets has a 300 request quota per minute, and also returns
@@ -88,7 +110,7 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
try:
return execute()
except gspread.exceptions.APIError as e:
- if e.code not in _RETRYABLE_API_ERROR_CODES or attempts >= max_attempts:
+ if not _is_retryable_api_error(e) or attempts >= max_attempts:
raise
jitter = random.uniform(-jitter_in_seconds, jitter_in_seconds)
diff --git a/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
index 7c4b2accf6bd..bcf96536e7e0 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
@@ -237,6 +237,68 @@ def test_retry_on_transient_api_error_retries_then_exhausts(status_code):
assert fn.call_count == 10
+def _api_error_with_status(
+ status_code: int, body: dict[str, Any] | None, text: str = ""
+) -> gspread.exceptions.APIError:
+ """Build an APIError whose HTTP status and body can differ. When `body` is None the
+ JSON body is unparseable, mirroring a transient 5xx returned by a gateway/proxy with a
+ non-JSON payload — gspread then falls back to `code == -1`."""
+ mock_response = mock.MagicMock()
+ mock_response.status_code = status_code
+ if body is None:
+ mock_response.json.side_effect = ValueError("no json")
+ mock_response.text = text
+ else:
+ mock_response.json.return_value = body
+ return gspread.exceptions.APIError(mock_response)
+
+
[email protected]("status_code", [429, 500, 502, 503, 504])
+def test_retry_on_transient_api_error_retries_5xx_with_non_json_body(status_code):
+ """A transient 5xx/429 can arrive with a non-JSON body (e.g. a gateway/proxy error
+ page), in which case gspread sets `code` to -1. The retry decision must fall back to
+ the HTTP status so the genuinely transient error is still retried rather than failing
+ the sync on the first attempt."""
+ with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
+ error = _api_error_with_status(status_code, body=None, text="upstream connect error")
+ assert error.code == -1 # gspread couldn't parse a code out of the body
+ fn = mock.MagicMock(side_effect=error)
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 10
+
+
[email protected]("status_code", [429, 500, 503])
+def test_retry_on_transient_api_error_retries_when_code_is_string(status_code):
+ """Some error envelopes carry the code as a string, so `e.code` is e.g. "500" and a
+ direct membership test against the integer set misses it. The retry decision must still
+ recognise the transient status via the HTTP status code."""
+ with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
+ body = {"error": {"code": str(status_code), "message": "Internal error encountered.", "status": "INTERNAL"}}
+ error = _api_error_with_status(status_code, body=body)
+ fn = mock.MagicMock(side_effect=error)
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 10
+
+
+def test_retry_on_transient_api_error_does_not_retry_4xx_with_non_json_body():
+ """A non-transient 4xx with an unparseable body must still be raised immediately — the
+ HTTP-status fallback should only retry the transient codes, not everything."""
+ with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
+ error = _api_error_with_status(400, body=None, text="Bad Request")
+ fn = mock.MagicMock(side_effect=error)
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 1
+
+
def test_retry_on_transient_api_error_does_not_retry_non_transient():
with mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"):
fn = mock.MagicMock(side_effect=_api_error(400, status="INVALID_ARGUMENT"))