: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 INTERNAL gRPC errors in-process (#65846)
Tom Owerse51ef137daab
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.pyindex 9fc53d2869dd..50ffccc88d53 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@@ -478,29 +478,32 @@ def google_ads_source()-# A transient gRPC ``UNAVAILABLE`` (e.g. Google's frontend returning ``502:Bad Gateway``) is the-# canonical retry-me status: the request never reached a healthy backend, so a fresh attempt after-# a short backoff usually succeeds. Riding the blip out in-process keeps the whole import activity-# from failing — which would otherwise re-fetch schemas, rebuild the gRPC client, and restart-# pagination from the last checkpoint — and avoids the captured error-tracking noise.+# Google flags both ``UNAVAILABLE`` (e.g. its frontend returning ``502:Bad Gateway`` — the request+# never reached a healthy backend) and ``INTERNAL`` ("Internal error encountered." from the+# backend) as transient, retry-with-backoff statuses: a fresh attempt after a short backoff usually+# succeeds. Riding the blip out in-process keeps the whole import activity from failing — which+# would otherwise re-fetch schemas, rebuild the gRPC client, and restart pagination from the last+# checkpoint — and avoids the captured error-tracking noise._MAX_TRANSIENT_SEARCH_ATTEMPTS = 4+_TRANSIENT_GRPC_STATUS_CODES = frozenset({grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.INTERNAL})-def _is_transient_grpc_unavailable(exc: BaseException) -> bool:- """Return True for a transient gRPC ``UNAVAILABLE`` failure.- The gapic transport usually surfaces it as ``google.api_core.exceptions.ServiceUnavailable``,- but the raw ``grpc`` ``_InactiveRpcError`` (whose ``code()`` returns ``StatusCode.UNAVAILABLE``)- can also propagate. The Google Ads SDK additionally re-wraps the transport error in a- ``GoogleAdsException`` when it can pull an ads ``failure`` from the trailing metadata (e.g. a- backend ``DEADLINE_EXCEEDED`` returned alongside an ``UNAVAILABLE`` status); the gRPC status- then lives on the wrapped ``error``, so we unwrap and inspect it too.+def _is_transient_grpc_error(exc: BaseException) -> bool:+ """Return True for a transient gRPC failure Google's guidance says to retry.++ The gapic transport usually surfaces these as ``google.api_core.exceptions.ServiceUnavailable``+ / ``InternalServerError``, but the raw ``grpc`` ``_InactiveRpcError`` (whose ``code()`` returns+ the ``StatusCode``) can also propagate. The Google Ads SDK additionally re-wraps the transport+ error in a ``GoogleAdsException`` when it can pull an ads ``failure`` from the trailing metadata+ (e.g. a backend ``DEADLINE_EXCEEDED`` returned alongside the status); the gRPC status then lives+ on the wrapped ``error``, so we unwrap and inspect it too."""- if isinstance(exc, google_api_exceptions.ServiceUnavailable):+ if isinstance(exc, google_api_exceptions.ServiceUnavailable | google_api_exceptions.InternalServerError):return Truecandidate: typing.Any = exc.error if isinstance(exc, GoogleAdsException) else exccode = getattr(candidate, "code", None)- return callable(code) and code() == grpc.StatusCode.UNAVAILABLE+ return callable(code) and code() in _TRANSIENT_GRPC_STATUS_CODESdef _search_with_transient_retry(@@ -509,12 +512,12 @@ def _search_with_transient_retry(*,max_attempts: int = _MAX_TRANSIENT_SEARCH_ATTEMPTS,) -> pagers.SearchPager:- """Call ``GoogleAdsService.search``, retrying a transient gRPC ``UNAVAILABLE`` with backoff.+ """Call ``GoogleAdsService.search``, retrying a transient gRPC failure with backoff.- Only retries before any page is yielded or checkpointed, so there is no partial state to- reconcile. The transient ``UNAVAILABLE`` may itself arrive wrapped in a ``GoogleAdsException``- (see ``_is_transient_grpc_unavailable``). Non-transient errors re-raise immediately so the- caller's ``INVALID_PAGE_TOKEN`` handling and Temporal's retry policy still apply.+ Each retry re-requests the same ``page_token``, so there is no partial state to reconcile. The+ transient status may itself arrive wrapped in a ``GoogleAdsException`` (see+ ``_is_transient_grpc_error``). Non-transient errors re-raise immediately so the caller's+ ``INVALID_PAGE_TOKEN`` handling and Temporal's retry policy still apply."""attempt = 0while True:@@ -522,7 +525,7 @@ def _search_with_transient_retry(return service.search(request=request)except Exception as e:attempt += 1- if attempt >= max_attempts or not _is_transient_grpc_unavailable(e):+ if attempt >= max_attempts or not _is_transient_grpc_error(e):raisetime.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.pyindex dbb62928c922..e25cf015fc2a 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@@ -22,7 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_adsGoogleAdsColumn,GoogleAdsTable,_is_invalid_page_token_error,- _is_transient_grpc_unavailable,+ _is_transient_grpc_error,_load_client_with_transient_retry,_search_as_arrow_tables,)@@ -536,15 +536,18 @@ class TestLoadClientTransientRetry:assert sleep.call_args_list == []-class _UnavailableRpcError(grpc.RpcError):- """A raw gRPC error whose ``code()`` reports ``UNAVAILABLE`` (502:Bad Gateway shape)."""+class _StatusCodeRpcError(grpc.RpcError):+ """A raw gRPC error whose ``code()`` reports a given ``StatusCode`` (``_InactiveRpcError`` shape)."""++ def __init__(self, status_code: grpc.StatusCode):+ self._status_code = status_codedef code(self) -> grpc.StatusCode:- return grpc.StatusCode.UNAVAILABLE+ return self._status_codedef _grpc_unavailable_error() -> grpc.RpcError:- return _UnavailableRpcError()+ return _StatusCodeRpcError(grpc.StatusCode.UNAVAILABLE)def _google_ads_exception_wrapping(grpc_error: grpc.RpcError) -> GoogleAdsException:@@ -554,25 +557,33 @@ def _google_ads_exception_wrapping(grpc_error: grpc.RpcError) -> GoogleAdsExceptreturn GoogleAdsException(error=grpc_error, call=None, failure=None, request_id="req-1")-class TestTransientGrpcUnavailableDetection:+def _grpc_internal_error() -> grpc.RpcError:+ return _StatusCodeRpcError(grpc.StatusCode.INTERNAL)+++class TestTransientGrpcErrorDetection:@pytest.mark.parametrize("exc, expected",[(google_api_exceptions.ServiceUnavailable("502:Bad Gateway"), True),(_grpc_unavailable_error(), True),- # The SDK wraps the transport UNAVAILABLE in a GoogleAdsException when an ads failure- # rides along (e.g. a backend DEADLINE_EXCEEDED) — still transient, so we unwrap it.+ # The SDK wraps the transport status in a GoogleAdsException when an ads failure rides+ # along (e.g. a backend DEADLINE_EXCEEDED) — still transient, so we unwrap it.(_google_ads_exception_wrapping(_grpc_unavailable_error()), True),- # A different gapic error must not be treated as transient-unavailable.+ # gRPC INTERNAL ("Internal error encountered.") is a transient Google-side blip — the+ # gapic wrapper and the raw _InactiveRpcError must both be ridden out in-process.+ (google_api_exceptions.InternalServerError("500 Internal error encountered."), True),+ (_grpc_internal_error(), True),+ # A different gapic error must not be treated as transient.(google_api_exceptions.PermissionDenied("PERMISSION_DENIED"), False),- # An ads-API GoogleAdsException carries no UNAVAILABLE gRPC status — it routes through- # the existing INVALID_PAGE_TOKEN handling, not the transient retry.+ # Google Ads API errors carry no transient gRPC status — they route through the existing+ # INVALID_PAGE_TOKEN / GoogleAdsException handling, not the transient retry.(_google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN), False),(ValueError("boom"), False),],)- def test_is_transient_grpc_unavailable(self, exc, expected):- assert _is_transient_grpc_unavailable(exc) is expected+ def test_is_transient_grpc_error(self, exc, expected):+ assert _is_transient_grpc_error(exc) is expectedclass _FlakyService:@@ -598,9 +609,11 @@ class TestSearchTransientRetry:google_api_exceptions.ServiceUnavailable("502:Bad Gateway"),_grpc_unavailable_error(),_google_ads_exception_wrapping(_grpc_unavailable_error()),+ google_api_exceptions.InternalServerError("500 Internal error encountered."),+ _grpc_internal_error(),],)- def test_rides_out_transient_unavailable(self, error):+ def test_rides_out_transient_error(self, error):service = _FlakyService(_single_page(), error=error, fail_times=2)manager = _FakeResumableManager(saved_token=None)