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_ads): retry transient 502 token-refresh failures in-process (#66652)

Tom Owersae6f391f017f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
index cb0c4e9e5174..357f33ff9bc3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py
@@ -72,32 +72,55 @@ def _ensure_grpc_receive_limit() -> None:
# ``GoogleAdsClient`` performs an OAuth token refresh at construction, reaching Google's token
-# endpoint over the network. A transient hiccup on that hop (e.g. a proxy connection timeout)
-# surfaces as ``google.auth.exceptions.TransportError`` — the stored credential is fine, only the
-# request failed, so a short backoff usually clears it. Riding it out here avoids failing (and
-# re-capturing) the whole import activity before a single row is fetched. Auth rejections surface
-# as ``RefreshError`` (handled as non-retryable elsewhere), not ``TransportError``, so retrying
-# here never masks bad credentials.
+# endpoint over the network. Two failure shapes on that hop are transient and usually clear on a
+# short backoff: a connection-level hiccup (e.g. a proxy timeout) surfaces as
+# ``google.auth.exceptions.TransportError``, while a server-side blip surfaces as a ``RefreshError``
+# carrying a 5xx token-endpoint response. Riding both out here avoids failing (and re-capturing) the
+# whole import activity before a single row is fetched. Auth rejections (revoked/expired refresh
+# token, restricted API access) also surface as ``RefreshError`` but carry an OAuth error body, not
+# a 5xx — they are not retried here and still hit the non-retryable handling elsewhere.
_MAX_CLIENT_INIT_ATTEMPTS = 4
+# google-auth flags token-endpoint responses with status 500/503/504/408/429 as retryable
+# (``RefreshError.retryable``), but its retryable set omits 502 Bad Gateway. Google's frontend
+# returns 502 as a transient HTML "Error 502 (Server Error)" page while a backend is briefly
+# unreachable — as recoverable as the codes it does retry — so we recognise it explicitly.
+_BAD_GATEWAY_REFRESH_ERROR_SIGNATURE = "502 (Server Error)"
+
+
+def _is_transient_client_init_error(exc: BaseException) -> bool:
+ """Return True for a client-construction failure worth riding out in-process.
+
+ Covers a connection-level ``TransportError`` and a ``RefreshError`` carrying a transient 5xx
+ token-endpoint response. An auth-rejection ``RefreshError`` (revoked/expired credential,
+ restricted API access) is not transient — it carries ``retryable=False`` and an OAuth error
+ body, never a 5xx — so it returns False and the caller's non-retryable handling still applies.
+ """
+ if isinstance(exc, google_auth_exceptions.TransportError):
+ return True
+ if isinstance(exc, google_auth_exceptions.RefreshError):
+ return getattr(exc, "retryable", False) or _BAD_GATEWAY_REFRESH_ERROR_SIGNATURE in str(exc)
+ return False
+
def _load_client_with_transient_retry(
config_dict: dict[str, object],
*,
max_attempts: int = _MAX_CLIENT_INIT_ATTEMPTS,
) -> GoogleAdsClient:
- """Build a ``GoogleAdsClient`` from a config dict, retrying a transient transport failure.
+ """Build a ``GoogleAdsClient`` from a config dict, retrying a transient token-refresh failure.
- Only the token-refresh network hop is retried; a ``RefreshError`` (revoked/expired credential)
- or any other error re-raises immediately so the caller's non-retryable handling still applies.
+ Only transient failures on the token-refresh hop are retried (see
+ ``_is_transient_client_init_error``); any other error — including an auth-rejection
+ ``RefreshError`` — re-raises immediately so the caller's non-retryable handling still applies.
"""
attempt = 0
while True:
try:
return GoogleAdsClient.load_from_dict(config_dict)
- except google_auth_exceptions.TransportError:
+ except Exception as e:
attempt += 1
- if attempt >= max_attempts:
+ if attempt >= max_attempts or not _is_transient_client_init_error(e):
raise
time.sleep(min(2 * attempt, 30))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
index 565f7d8ef6e0..5061d870fa70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
GoogleAdsTable,
_get_integration,
_is_invalid_page_token_error,
+ _is_transient_client_init_error,
_is_transient_grpc_error,
_load_client_with_transient_retry,
_search_as_arrow_tables,
@@ -487,6 +488,13 @@ class TestSearchPageTokenResumption:
_CLIENT_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.GoogleAdsClient"
_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.time.sleep"
+# The HTML body Google's frontend returns for a transient 502 on the OAuth token endpoint, as it
+# reaches `str()` on the resulting RefreshError. google-auth does not flag this status retryable.
+_BAD_GATEWAY_TOKEN_ENDPOINT_BODY = (
+ "<!DOCTYPE html>\n<html lang=en>\n <title>Error 502 (Server Error)!!1</title>\n"
+ " <p>The server encountered a temporary error and could not complete your request."
+)
+
class TestLoadClientTransientRetry:
def test_retries_transport_error_then_succeeds(self):
@@ -508,6 +516,26 @@ class TestLoadClientTransientRetry:
# Backoff grows per attempt per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.
assert sleep.call_args_list == [mock.call(2), mock.call(4)]
+ def test_retries_transient_refresh_error_then_succeeds(self):
+ # A 502 from Google's token endpoint surfaces as a RefreshError (not TransportError) and
+ # google-auth does not flag it retryable, but it's a transient server-side blip — ride it
+ # out in-process rather than failing the whole import activity before a row is fetched.
+ client = object()
+ load = mock.Mock(
+ side_effect=[
+ google_auth_exceptions.RefreshError(_BAD_GATEWAY_TOKEN_ENDPOINT_BODY),
+ client,
+ ]
+ )
+
+ with mock.patch(_CLIENT_PATH) as ga_client, mock.patch(_SLEEP_PATH) as sleep:
+ ga_client.load_from_dict = load
+ result = _load_client_with_transient_retry({"refresh_token": "x"})
+
+ assert result is client
+ assert load.call_count == 2
+ assert sleep.call_args_list == [mock.call(2)]
+
def test_reraises_after_exhausting_attempts(self):
load = mock.Mock(side_effect=google_auth_exceptions.TransportError("timed out"))
@@ -541,6 +569,28 @@ class TestLoadClientTransientRetry:
assert sleep.call_args_list == []
+class TestTransientClientInitErrorDetection:
+ @pytest.mark.parametrize(
+ "exc, expected",
+ [
+ (google_auth_exceptions.TransportError("connection reset by peer"), True),
+ # 502 Bad Gateway from the token endpoint: a RefreshError google-auth does not flag
+ # retryable, but a transient server-side blip we ride out via its message signature.
+ (google_auth_exceptions.RefreshError(_BAD_GATEWAY_TOKEN_ENDPOINT_BODY), True),
+ # 500/503/504/408/429 token-endpoint responses arrive as a RefreshError google-auth
+ # already flags retryable.
+ (google_auth_exceptions.RefreshError("server_error", retryable=True), True),
+ # Auth rejections also surface as RefreshError but are not transient — they must not be
+ # ridden out in-process (they route through the non-retryable handling elsewhere).
+ (google_auth_exceptions.RefreshError("invalid_grant: Token has been expired or revoked."), False),
+ (google_auth_exceptions.RefreshError("access_not_configured"), False),
+ (ValueError("boom"), False),
+ ],
+ )
+ def test_is_transient_client_init_error(self, exc, expected):
+ assert _is_transient_client_init_error(exc) is expected
+
+
class _StatusCodeRpcError(grpc.RpcError):
"""A raw gRPC error whose ``code()`` reports a given ``StatusCode`` (``_InactiveRpcError`` shape)."""