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 a transient Google token-refresh error (#83484)

Tom Owers916e17e78762
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
index 4f57ec88ed84..440a91c9694a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -1,3 +1,4 @@
+import re
import time
import random
from collections import Counter
@@ -9,6 +10,7 @@ from django.conf import settings
import gspread
import requests
from cachetools import Cache, TTLCache, cached
+from google.auth import exceptions as google_auth_exceptions
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
from gspread.utils import numericise_all
@@ -165,6 +167,18 @@ def _records_from_grid(grid: list[list[str]]) -> list[dict[str, Any]]:
return [dict(zip(column_names, numericise_all(row, default_blank=None))) for row in grid[1:]]
+# Google's frontend returns this stable "That's an error" doodle page — an HTML body, not the JSON
+# `{"error": ...}` an OAuth rejection (e.g. invalid_grant) returns — when its infra has a transient
+# outage in front of the token endpoint. `google-auth`'s own `RefreshError.retryable` flag doesn't
+# cover this: it only recognizes 500/503/504/408/429 as retryable and treats an HTML body's implied
+# 502 as not retryable (see `google.oauth2._client._can_retry`), so key off the page's title instead.
+_GOOGLE_FRONTEND_ERROR_RE = re.compile(r"Error 5\d\d \(")
+
+
+def _is_transient_refresh_error(e: BaseException) -> bool:
+ return bool(_GOOGLE_FRONTEND_ERROR_RE.search(str(e)))
+
+
def _is_retryable_api_error(e: gspread.exceptions.APIError) -> bool:
"""Decide whether a gspread APIError is a transient error worth retrying.
@@ -205,6 +219,8 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
return execute()
except (
gspread.exceptions.APIError,
+ google_auth_exceptions.RefreshError,
+ google_auth_exceptions.TransportError,
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
requests.exceptions.ChunkedEncodingError,
@@ -220,7 +236,18 @@ def _retry_on_transient_api_error(execute: Callable[[], T]) -> T:
# streaming the response body and re-raises it as `ChunkedEncodingError`, which is a
# sibling of `ConnectionError` in the `requests` hierarchy (not a subclass), so the
# `ConnectionError` entry above would not catch it.
- is_retryable = _is_retryable_api_error(e) if isinstance(e, gspread.exceptions.APIError) else True
+ #
+ # `RefreshError`/`TransportError` come from `AuthorizedSession` refreshing our own
+ # service-account token as a side effect of this call (see `_is_transient_refresh_error`)
+ # — gate those on the frontend-error signature rather than treating every auth failure
+ # as transient, since a persistent problem (e.g. a rotated/invalid key) should still fail
+ # fast instead of spending the whole retry budget first.
+ if isinstance(e, gspread.exceptions.APIError):
+ is_retryable = _is_retryable_api_error(e)
+ elif isinstance(e, google_auth_exceptions.RefreshError | google_auth_exceptions.TransportError):
+ is_retryable = _is_transient_refresh_error(e)
+ else:
+ is_retryable = True
if not is_retryable or attempts >= max_attempts:
raise
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
index 39fadf085853..7fbbcc49e30b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/source.py
@@ -92,6 +92,14 @@ class GoogleSheetsSource(SimpleSource[GoogleSheetsSourceConfig]):
# connection, read timeout, dropped socket), so match that stable prefix rather than
# the per-request URL or nested error detail.
"Max retries exceeded with url",
+ # `_retry_on_transient_api_error` also retries a `RefreshError`/`TransportError` raised
+ # while refreshing our own service-account token, when its message carries Google's
+ # stable "Error 5xx (...)" frontend-outage page (see `_is_transient_refresh_error`),
+ # before re-raising once that budget is exhausted.
+ "Error 500 (",
+ "Error 502 (",
+ "Error 503 (",
+ "Error 504 (",
}
def get_schemas(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
index 567fec143790..0a2e06b73c32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
@@ -375,6 +375,42 @@ def test_retry_on_transient_api_error_bubbles_network_error_after_max_retries(er
assert fn.call_count == 10
+ "error_cls",
+ [google_auth_exceptions.RefreshError, google_auth_exceptions.TransportError],
+)
+def test_retry_on_transient_api_error_retries_transient_refresh_error_then_succeeds(error_cls):
+ """Refreshing our own service-account token (a side effect of every Sheets API call) can hit a
+ transient outage in front of Google's token endpoint, which surfaces as an HTML "Error 502
+ (Server Error)" page rather than a JSON OAuth rejection. That page isn't flagged `retryable` by
+ google-auth itself (see `_is_transient_refresh_error`), so without this the sync would fail
+ outright on a blip that clears on its own."""
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.time"
+ ):
+ error = error_cls("Error 502 (Server Error)!!1", retryable=False)
+ fn = mock.MagicMock(side_effect=[error, "ok"])
+
+ assert _retry_on_transient_api_error(fn) == "ok"
+ assert fn.call_count == 2
+
+
+def test_retry_on_transient_api_error_does_not_retry_persistent_refresh_error():
+ """A genuine credential problem (e.g. a rotated/invalid service-account key) surfaces as a
+ `RefreshError` with the OAuth JSON error body, not Google's frontend-outage HTML page. It must
+ fail immediately rather than spending the whole retry budget on something that can't recover."""
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_sheets.google_sheets.time"
+ ):
+ error = google_auth_exceptions.RefreshError("invalid_grant: Invalid JWT Signature.", retryable=False)
+ fn = mock.MagicMock(side_effect=error)
+
+ with pytest.raises(google_auth_exceptions.RefreshError):
+ _retry_on_transient_api_error(fn)
+
+ assert fn.call_count == 1
+
+
def test_google_sheets_source_retries_transient_error_on_data_reads():
"""A transient 5xx on the cell-reading calls (`get_all_values`/`get`) must be retried,
not surfaced on the first occurrence. These reads issue their own Sheets API requests
@@ -533,6 +569,18 @@ def test_error_string_matches_a_retryable_key_for_network_errors(error_message):
assert any(key in error_message for key in retryable_errors)
[email protected]("status_code", [500, 502, 503, 504])
+def test_error_string_matches_a_retryable_key_for_frontend_refresh_errors(status_code):
+ """`_retry_on_transient_api_error` also retries a `RefreshError`/`TransportError` carrying
+ Google's frontend-outage HTML page before re-raising once that budget is exhausted. If the
+ page's status code drops out of this set, the transient error starts polluting error tracking
+ even though Temporal still retries it."""
+ error_message = f"Error {status_code} (Server Error)!!1"
+ retryable_errors = GoogleSheetsSource().get_retryable_errors()
+
+ assert any(key in error_message for key in retryable_errors)
+
+
@pytest.mark.parametrize(
"call_site",
[