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 gRPC errors during schema discovery (#66891)

Tom Owers24aca8c3a985
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 b2897a665998..727fdf5505cb 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
@@ -15,6 +15,10 @@ from google.ads.googleads.v23.common import types as ga_common
from google.ads.googleads.v23.enums import types as ga_enums
from google.ads.googleads.v23.resources import types as ga_resources
from google.ads.googleads.v23.services import types as ga_services
+from google.ads.googleads.v23.services.services.google_ads_field_service import (
+ GoogleAdsFieldServiceClient,
+ pagers as field_service_pagers,
+)
from google.ads.googleads.v23.services.services.google_ads_service import GoogleAdsServiceClient, pagers
from google.api_core import exceptions as google_api_exceptions
from google.auth import exceptions as google_auth_exceptions
@@ -372,8 +376,8 @@ def get_schemas(config: GoogleAdsSourceConfigUnion, team_id: int) -> TableSchema
"""
client = google_ads_client(config, team_id)
gaf_service = client.get_service("GoogleAdsFieldService", interceptors=tracked_interceptors(GOOGLE_ADS_HOST))
- fields_query = gaf_service.search_google_ads_fields(
- query=f"select name, data_type, is_repeated, type_url where selectable = true"
+ fields_query = _search_fields_with_transient_retry(
+ gaf_service, "select name, data_type, is_repeated, type_url where selectable = true"
)
fields_map = {field.name: field for field in fields_query.results}
table_schemas = {}
@@ -543,6 +547,30 @@ def _is_transient_grpc_error(exc: BaseException) -> bool:
return callable(code) and code() in _TRANSIENT_GRPC_STATUS_CODES
+_T = typing.TypeVar("_T")
+
+
+def _call_with_transient_retry(
+ call: collections.abc.Callable[[], _T],
+ *,
+ max_attempts: int = _MAX_TRANSIENT_SEARCH_ATTEMPTS,
+) -> _T:
+ """Run ``call``, retrying a transient gRPC failure (see ``_is_transient_grpc_error``) with backoff.
+
+ A non-transient error re-raises immediately so the caller's handling and Temporal's retry policy
+ still apply; the final attempt re-raises rather than sleeping.
+ """
+ attempt = 0
+ while True:
+ try:
+ return call()
+ except Exception as e:
+ attempt += 1
+ if attempt >= max_attempts or not _is_transient_grpc_error(e):
+ raise
+ time.sleep(min(2 * attempt, 30))
+
+
def _search_with_transient_retry(
service: GoogleAdsServiceClient,
request: dict,
@@ -556,15 +584,23 @@ def _search_with_transient_retry(
``_is_transient_grpc_error``). Non-transient errors re-raise immediately so the caller's
stale-page-token handling and Temporal's retry policy still apply.
"""
- attempt = 0
- while True:
- try:
- return service.search(request=request)
- except Exception as e:
- attempt += 1
- if attempt >= max_attempts or not _is_transient_grpc_error(e):
- raise
- time.sleep(min(2 * attempt, 30))
+ return _call_with_transient_retry(lambda: service.search(request=request), max_attempts=max_attempts)
+
+
+def _search_fields_with_transient_retry(
+ service: GoogleAdsFieldServiceClient,
+ query: str,
+ *,
+ max_attempts: int = _MAX_TRANSIENT_SEARCH_ATTEMPTS,
+) -> field_service_pagers.SearchGoogleAdsFieldsPager:
+ """Call ``GoogleAdsFieldService.search_google_ads_fields``, retrying a transient gRPC failure.
+
+ Schema discovery hits the same transient ``UNAVAILABLE`` / ``INTERNAL`` blips as the row search
+ (see ``_is_transient_grpc_error``), so riding them out in-process keeps a momentary Google-side
+ error from failing the whole import. Non-transient errors re-raise immediately so the caller's
+ handling and Temporal's retry policy still apply.
+ """
+ return _call_with_transient_retry(lambda: service.search_google_ads_fields(query=query), max_attempts=max_attempts)
_STALE_PAGE_TOKEN_REQUEST_ERRORS = ("INVALID_PAGE_TOKEN", "EXPIRED_PAGE_TOKEN")
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 26daa4368f7f..08d3b777072b 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
@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
_is_transient_grpc_error,
_load_client_with_transient_retry,
_search_as_arrow_tables,
+ _search_fields_with_transient_retry,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.schemas import RESOURCE_SCHEMAS
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.source import GoogleAdsSource
@@ -780,6 +781,71 @@ class TestSearchTransientRetry:
assert sleep.call_count == 0
+class _FlakyFieldService:
+ """Raises a transient error for the first ``fail_times`` calls, then returns a fields pager."""
+
+ def __init__(self, pager: object, error: BaseException, fail_times: int):
+ self.pager = pager
+ self.error = error
+ self.fail_times = fail_times
+ self.calls = 0
+
+ def search_google_ads_fields(self, query: str):
+ self.calls += 1
+ if self.calls <= self.fail_times:
+ raise self.error
+ return self.pager
+
+
+class TestSearchFieldsTransientRetry:
+ @pytest.mark.parametrize(
+ "error",
+ [
+ google_api_exceptions.ServiceUnavailable("502:Bad Gateway"),
+ _grpc_unavailable_error(),
+ _google_ads_exception_wrapping(_grpc_unavailable_error()),
+ # The reported failure: gRPC INTERNAL ("Internal error encountered.") during schema
+ # discovery, arriving both as the gapic wrapper and the raw _InactiveRpcError.
+ google_api_exceptions.InternalServerError("500 Internal error encountered."),
+ _grpc_internal_error(),
+ ],
+ )
+ def test_rides_out_transient_error(self, error):
+ pager = object()
+ service = _FlakyFieldService(pager, error=error, fail_times=2)
+
+ with mock.patch(_SLEEP_PATH) as sleep:
+ result = _search_fields_with_transient_retry(service, "select name from x") # type: ignore[arg-type]
+
+ assert result is pager
+ # Two transient failures retried, then the pager was returned.
+ assert service.calls == 3
+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]
+
+ def test_persistent_internal_is_reraised_for_temporal_to_retry(self):
+ service = _FlakyFieldService(
+ object(), error=google_api_exceptions.InternalServerError("500 Internal error encountered."), fail_times=99
+ )
+
+ with mock.patch(_SLEEP_PATH) as sleep:
+ with pytest.raises(google_api_exceptions.InternalServerError):
+ _search_fields_with_transient_retry(service, "select name from x") # type: ignore[arg-type]
+
+ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry.
+ assert service.calls == 4
+ assert sleep.call_args_list == [mock.call(2), mock.call(4), mock.call(6)]
+
+ def test_non_transient_error_is_not_retried(self):
+ service = _FlakyFieldService(object(), error=ValueError("boom"), fail_times=99)
+
+ with mock.patch(_SLEEP_PATH) as sleep:
+ with pytest.raises(ValueError):
+ _search_fields_with_transient_retry(service, "select name from x") # type: ignore[arg-type]
+
+ assert service.calls == 1
+ assert sleep.call_count == 0
+
+
_INTEGRATION_GET_PATH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.Integration.objects.get"
)