: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(google_ads): retry transient OAuth token-refresh timeout at client init (#65358)
Tom Owers35ee42ee3d94
diff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.pyindex cc474e563107..bd613fae94c5 100644--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py@@ -1,3 +1,4 @@+import timeimport typingimport datetime as dtimport collections.abc@@ -14,6 +15,7 @@ from google.ads.googleads.v23.enums import types as ga_enumsfrom google.ads.googleads.v23.resources import types as ga_resourcesfrom google.ads.googleads.v23.services import types as ga_servicesfrom google.ads.googleads.v23.services.services.google_ads_service import GoogleAdsServiceClient+from google.auth import exceptions as google_auth_exceptionsfrom google.oauth2 import service_accountfrom google.protobuf.json_format import MessageToJson@@ -64,6 +66,37 @@ def _ensure_grpc_receive_limit() -> None:options.append((_GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY, GRPC_MAX_RECEIVE_MESSAGE_LENGTH))+# ``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.+_MAX_CLIENT_INIT_ATTEMPTS = 4+++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.++ 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.+ """+ attempt = 0+ while True:+ try:+ return GoogleAdsClient.load_from_dict(config_dict)+ except google_auth_exceptions.TransportError:+ attempt += 1+ if attempt >= max_attempts:+ raise+ time.sleep(min(2 * attempt, 30))++def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> GoogleAdsClient:"""Initialize a `GoogleAdsClient` with provided config."""_ensure_grpc_receive_limit()@@ -90,7 +123,7 @@ def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> Googlif login_customer_id is not None:config_dict["login_customer_id"] = login_customer_id- client = GoogleAdsClient.load_from_dict(config_dict)+ client = _load_client_with_transient_retry(config_dict)else:credentials = service_account.Credentials.from_service_account_info({diff --git a/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.pyindex ff8300480459..310c70bcb8b4 100644--- a/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py+++ b/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py@@ -7,6 +7,7 @@ from google.ads.googleads.errors import GoogleAdsExceptionfrom google.ads.googleads.v23.enums import types as ga_enumsfrom google.ads.googleads.v23.errors.types.errors import ErrorCode, GoogleAdsError, GoogleAdsFailurefrom google.ads.googleads.v23.errors.types.request_error import RequestErrorEnum+from google.auth import exceptions as google_auth_exceptionsfrom posthog.models.integration import Integrationfrom posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig@@ -15,6 +16,7 @@ from posthog.temporal.data_imports.sources.google_ads.google_ads import (GoogleAdsColumn,GoogleAdsTable,_is_invalid_page_token_error,+ _load_client_with_transient_retry,_search_as_arrow_tables,)from posthog.temporal.data_imports.sources.google_ads.source import GoogleAdsSource@@ -443,3 +445,60 @@ class TestSearchPageTokenResumption:assert always_failing.calls == [""]assert manager.saved_states == []+++_CLIENT_PATH = "posthog.temporal.data_imports.sources.google_ads.google_ads.GoogleAdsClient"+_SLEEP_PATH = "posthog.temporal.data_imports.sources.google_ads.google_ads.time.sleep"+++class TestLoadClientTransientRetry:+ def test_retries_transport_error_then_succeeds(self):+ client = object()+ load = mock.Mock(+ side_effect=[+ google_auth_exceptions.TransportError("timed out"),+ google_auth_exceptions.TransportError("timed out"),+ 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 == 3+ # 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_reraises_after_exhausting_attempts(self):+ load = mock.Mock(side_effect=google_auth_exceptions.TransportError("timed out"))++ with mock.patch(_CLIENT_PATH) as ga_client, mock.patch(_SLEEP_PATH) as sleep:+ ga_client.load_from_dict = load+ with pytest.raises(google_auth_exceptions.TransportError):+ _load_client_with_transient_retry({"refresh_token": "x"}, max_attempts=3)++ assert load.call_count == 3+ # One sleep fewer than attempts — no backoff after the final failure.+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]++ @pytest.mark.parametrize(+ "error",+ [+ # A revoked/expired credential surfaces as RefreshError, not TransportError — it must+ # not be retried as if it were transient (it's handled as non-retryable elsewhere).+ google_auth_exceptions.RefreshError("invalid_grant"),+ ValueError("boom"),+ ],+ )+ def test_non_transient_error_is_not_retried(self, error):+ load = mock.Mock(side_effect=error)++ with mock.patch(_CLIENT_PATH) as ga_client, mock.patch(_SLEEP_PATH) as sleep:+ ga_client.load_from_dict = load+ with pytest.raises(type(error)):+ _load_client_with_transient_retry({"refresh_token": "x"})++ assert load.call_count == 1+ assert sleep.call_args_list == []