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 UNAVAILABLE during search (#65293)

Tom Owers80c92bd8a4cb
diff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
index bd613fae94c5..1d75274cdf0e 100644
--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
@@ -6,6 +6,7 @@ import collections.abc
from django.conf import settings
from django.db import close_old_connections
+import grpc
import pyarrow as pa
from google.ads.googleads import client as google_ads_client_module
from google.ads.googleads.client import GoogleAdsClient
@@ -14,7 +15,8 @@ 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_service import GoogleAdsServiceClient
+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
from google.oauth2 import service_account
from google.protobuf.json_format import MessageToJson
@@ -473,6 +475,50 @@ 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.
+_MAX_TRANSIENT_SEARCH_ATTEMPTS = 4
+
+
+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, so we accept either shape.
+ """
+ if isinstance(exc, google_api_exceptions.ServiceUnavailable):
+ return True
+ code = getattr(exc, "code", None)
+ return callable(code) and code() == grpc.StatusCode.UNAVAILABLE
+
+
+def _search_with_transient_retry(
+ service: GoogleAdsServiceClient,
+ request: dict,
+ *,
+ max_attempts: int = _MAX_TRANSIENT_SEARCH_ATTEMPTS,
+) -> pagers.SearchPager:
+ """Call ``GoogleAdsService.search``, retrying a transient gRPC ``UNAVAILABLE`` with backoff.
+
+ Only retries before any page is yielded or checkpointed, so there is no partial state to
+ reconcile. Non-transient errors (including ``GoogleAdsException``) re-raise immediately so the
+ caller's ``INVALID_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_unavailable(e):
+ raise
+ time.sleep(min(2 * attempt, 30))
+
+
def _is_invalid_page_token_error(exc: GoogleAdsException) -> bool:
"""Return True if a ``GoogleAdsException`` was caused by an expired/invalid page token.
@@ -517,12 +563,13 @@ def _search_as_arrow_tables(
# as convenience kwargs — `page_token` must be passed via the `request`
# argument (a dict is coerced to ``SearchGoogleAdsRequest`` by gapic).
try:
- response = service.search(
- request={
+ response = _search_with_transient_retry(
+ service,
+ {
"customer_id": customer_id,
"query": query,
"page_token": page_token,
- }
+ },
)
except GoogleAdsException as e:
# Only a non-empty (resumed or mid-stream) token can be stale; an empty
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.py
index 661a0f4d229f..e0e583c282a9 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
@@ -3,10 +3,12 @@ from types import SimpleNamespace
import pytest
from unittest import mock
+import grpc
from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.v23.enums import types as ga_enums
from google.ads.googleads.v23.errors.types.errors import ErrorCode, GoogleAdsError, GoogleAdsFailure
from google.ads.googleads.v23.errors.types.request_error import RequestErrorEnum
+from google.api_core import exceptions as google_api_exceptions
from google.auth import exceptions as google_auth_exceptions
from posthog.models.integration import Integration
@@ -16,6 +18,7 @@ from posthog.temporal.data_imports.sources.google_ads.google_ads import (
GoogleAdsColumn,
GoogleAdsTable,
_is_invalid_page_token_error,
+ _is_transient_grpc_unavailable,
_load_client_with_transient_retry,
_search_as_arrow_tables,
)
@@ -525,3 +528,121 @@ class TestLoadClientTransientRetry:
assert load.call_count == 1
assert sleep.call_args_list == []
+
+
+class _UnavailableRpcError(grpc.RpcError):
+ """A raw gRPC error whose ``code()`` reports ``UNAVAILABLE`` (502:Bad Gateway shape)."""
+
+ def code(self) -> grpc.StatusCode:
+ return grpc.StatusCode.UNAVAILABLE
+
+
+def _grpc_unavailable_error() -> grpc.RpcError:
+ return _UnavailableRpcError()
+
+
+class TestTransientGrpcUnavailableDetection:
+ @pytest.mark.parametrize(
+ "exc, expected",
+ [
+ (google_api_exceptions.ServiceUnavailable("502:Bad Gateway"), True),
+ (_grpc_unavailable_error(), True),
+ # A different gapic error must not be treated as transient-unavailable.
+ (google_api_exceptions.PermissionDenied("PERMISSION_DENIED"), False),
+ # Google Ads API errors carry no UNAVAILABLE gRPC status — they route through
+ # the existing 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
+
+
+class _FlakyService:
+ """Raises a transient error for the first ``fail_times`` calls, then serves one page."""
+
+ def __init__(self, page: SimpleNamespace, error: BaseException, fail_times: int):
+ self.page = page
+ self.error = error
+ self.fail_times = fail_times
+ self.calls = 0
+
+ def search(self, request: dict):
+ self.calls += 1
+ if self.calls <= self.fail_times:
+ raise self.error
+ return SimpleNamespace(pages=iter([self.page]))
+
+
+class TestSearchTransientRetry:
+ @pytest.mark.parametrize(
+ "error",
+ [
+ google_api_exceptions.ServiceUnavailable("502:Bad Gateway"),
+ _grpc_unavailable_error(),
+ ],
+ )
+ def test_rides_out_transient_unavailable(self, error):
+ service = _FlakyService(_single_page(), error=error, fail_times=2)
+ manager = _FakeResumableManager(saved_token=None)
+
+ with mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.time.sleep") as sleep:
+ tables = list(
+ _search_as_arrow_tables(
+ service=service, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ # Two transient failures were retried, then the page was served — no data lost.
+ assert service.calls == 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)]
+ assert [t.to_pylist() for t in tables] == [[{"campaign_name": "Acme"}]]
+
+ def test_persistent_unavailable_is_reraised_for_temporal_to_retry(self):
+ service = _FlakyService(
+ _single_page(), error=google_api_exceptions.ServiceUnavailable("502:Bad Gateway"), fail_times=99
+ )
+ manager = _FakeResumableManager(saved_token=None)
+
+ with mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.time.sleep") as sleep:
+ with pytest.raises(google_api_exceptions.ServiceUnavailable):
+ list(
+ _search_as_arrow_tables(
+ service=service, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry.
+ assert service.calls == 4
+ # Backed off between each attempt (2s, 4s, 6s) but not after the final attempt that re-raises.
+ assert sleep.call_args_list == [mock.call(2), mock.call(4), mock.call(6)]
+
+ def test_non_transient_error_is_not_retried(self):
+ service = _FlakyService(_single_page(), error=ValueError("boom"), fail_times=99)
+ manager = _FakeResumableManager(saved_token=None)
+
+ with mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.time.sleep") as sleep:
+ with pytest.raises(ValueError):
+ list(
+ _search_as_arrow_tables(
+ service=service, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ # First call raises and propagates immediately — no retry, no backoff.
+ assert service.calls == 1
+ assert sleep.call_count == 0