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 as the manager account when a sync is denied (#78187)

Tom Owersc983088d845e
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 d3b4faa1ee2a..10c19692581a 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
@@ -8,6 +8,7 @@ from django.db import OperationalError, close_old_connections
import grpc
import pyarrow as pa
+import structlog
from dateutil import parser as dateutil_parser
from google.ads.googleads import client as google_ads_client_module
from google.ads.googleads.client import GoogleAdsClient
@@ -54,6 +55,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
)
from products.warehouse_sources.backend.types import IncrementalFieldType
+logger = structlog.get_logger()
+
# Host used to label the tracked gRPC transport's logs/metrics. Matches
# `GoogleAdsServiceClient.DEFAULT_ENDPOINT`.
GOOGLE_ADS_HOST = "googleads.googleapis.com"
@@ -543,11 +546,8 @@ def google_ads_source(
return query
def get_rows() -> collections.abc.Iterator[pa.Table]:
- client = google_ads_client(config, team_id)
- service: GoogleAdsServiceClient = client.get_service(
- "GoogleAdsService", version=api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST)
- )
customer_id = clean_customer_id(config.customer_id)
+ service = GoogleAdsSearchService(google_ads_client(config, team_id), api_version, customer_id)
if not should_use_incremental_field:
yield from _search_as_arrow_tables(
@@ -697,7 +697,7 @@ def _call_with_transient_retry(
def _search_with_transient_retry(
- service: GoogleAdsServiceClient,
+ service: "GoogleAdsSearchService | GoogleAdsServiceClient",
request: dict,
*,
max_attempts: int = _MAX_TRANSIENT_SEARCH_ATTEMPTS,
@@ -774,8 +774,124 @@ def _is_rejected_page_token_error(exc: GoogleAdsException, page_token: str) -> b
return False
+# Google Ads only serves a request for a client account the authenticated login reaches *through* a
+# manager (MCC) account when the request carries a `login-customer-id` header naming that manager.
+# We set that header only when the source has the MCC option switched on, so a client account the
+# login can no longer reach directly — moved under a manager, or direct access removed while manager
+# access remains — starts failing every sync with PERMISSION_DENIED / USER_PERMISSION_DENIED, which
+# no amount of retrying clears. The account list at setup time already walks the hierarchy to find
+# which manager an account sits under, so the sync can do the same on demand: find a manager we can
+# still authenticate as, set the header, and repeat the request.
+_MANAGER_LOOKUP_QUERY = "SELECT customer_client.id FROM customer_client WHERE customer_client.id = {customer_id}"
+
+# The ads-level code Google returns alongside a PERMISSION_DENIED status when the login can't reach
+# the requested customer. Matched on the failure text so it is recognised whether the SDK surfaces
+# the transport status, the ads failure, or both.
+_PERMISSION_DENIED_FAILURE_SIGNATURE = "USER_PERMISSION_DENIED"
+
+
+def _is_permission_denied_error(exc: BaseException) -> bool:
+ """Return True when Google refused the request because the login can't reach the customer."""
+ if isinstance(exc, google_api_exceptions.PermissionDenied):
+ return True
+ # The SDK re-wraps the transport error in a ``GoogleAdsException`` when it can pull an ads
+ # failure from the trailing metadata, so the gRPC status may live on the wrapped ``error``.
+ candidate: typing.Any = exc.error if isinstance(exc, GoogleAdsException) else exc
+ code = getattr(candidate, "code", None)
+ if callable(code) and code() == grpc.StatusCode.PERMISSION_DENIED:
+ return True
+ failure = getattr(exc, "failure", None)
+ return failure is not None and _PERMISSION_DENIED_FAILURE_SIGNATURE in str(failure)
+
+
+def _find_manager_customer_id(client: GoogleAdsClient, customer_id: str, api_version: str) -> str | None:
+ """Return an accessible manager account whose hierarchy contains ``customer_id``, if there is one.
+
+ ``list_accessible_customers`` returns only the accounts the login can reach directly, so a
+ client account under a manager never appears there. Querying ``customer_client`` from each of
+ those accounts lists everything below it, which tells us which one to authenticate as. Returns
+ None when the customer is directly accessible (the header isn't what's missing) or when no
+ accessible account can reach it (access really is gone). The probe never raises: a failure here
+ must not replace the permission error the caller is recovering from.
+ """
+ # The id is interpolated into a GAQL query below, so only ever accept the bare digits Google
+ # Ads uses (`clean_customer_id` already normalizes to that on the sync path).
+ if not customer_id.isdigit():
+ return None
+
+ original_login_customer_id = client.login_customer_id
+ try:
+ customer_service = client.get_service(
+ "CustomerService", version=api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST)
+ )
+ resource_names = customer_service.list_accessible_customers().resource_names
+ candidates = [name.rsplit("/", 1)[-1] for name in resource_names]
+ if customer_id in candidates:
+ return None
+
+ query = _MANAGER_LOOKUP_QUERY.format(customer_id=customer_id)
+ for candidate in candidates:
+ client.login_customer_id = candidate
+ service: GoogleAdsServiceClient = client.get_service(
+ "GoogleAdsService", version=api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST)
+ )
+ try:
+ response = service.search(request={"customer_id": candidate, "query": query})
+ page = next(iter(response.pages), None)
+ except Exception:
+ continue
+ if page is not None and len(page.results) > 0:
+ return candidate
+ return None
+ except Exception:
+ return None
+ finally:
+ client.login_customer_id = original_login_customer_id
+
+
+class GoogleAdsSearchService:
+ """``GoogleAdsService.search`` that recovers from a missing ``login-customer-id`` header.
+
+ The header is a client-level setting the SDK reads when a service is built, so recovering means
+ resetting it on the client and rebuilding the service. Recovery is attempted at most once per
+ sync: if the retry still fails, or no manager can reach the customer, the original error
+ propagates to the caller's non-retryable handling.
+ """
+
+ def __init__(self, client: GoogleAdsClient, api_version: str, customer_id: str | None) -> None:
+ self._client = client
+ self._api_version = api_version
+ self._customer_id = customer_id
+ self._recovery_attempted = False
+ self._service = self._build_service()
+
+ def _build_service(self) -> GoogleAdsServiceClient:
+ return self._client.get_service(
+ "GoogleAdsService", version=self._api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST)
+ )
+
+ def search(self, request: dict) -> pagers.SearchPager:
+ try:
+ return self._service.search(request=request)
+ except Exception as e:
+ if self._recovery_attempted or not self._customer_id or not _is_permission_denied_error(e):
+ raise
+ self._recovery_attempted = True
+ manager_customer_id = _find_manager_customer_id(self._client, self._customer_id, self._api_version)
+ if manager_customer_id is None:
+ raise
+ logger.info(
+ "Retrying Google Ads request as the manager account that can reach this customer",
+ customer_id=self._customer_id,
+ login_customer_id=manager_customer_id,
+ )
+ self._client.login_customer_id = manager_customer_id
+ self._service = self._build_service()
+ return self._service.search(request=request)
+
+
def _search_as_arrow_tables(
- service: GoogleAdsServiceClient,
+ service: GoogleAdsSearchService | GoogleAdsServiceClient,
customer_id: str | None,
query: str,
table: GoogleAdsTable,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
index 2dbb8615c90e..b25c125e0b9b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py
@@ -102,13 +102,29 @@ class GoogleAdsSource(
return CANONICAL_DESCRIPTIONS
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Order matters: the finalization activity shows the message of the *first* pattern that
+ # matches, and Google returns several of the specific codes below under the generic
+ # `PERMISSION_DENIED` / `UNAUTHENTICATED` gRPC statuses. Specific codes therefore come first,
+ # so a scope or deleted-account failure doesn't get the generic access message.
return {
- "PERMISSION_DENIED": None,
- "UNAUTHENTICATED": None,
- "ACCESS_TOKEN_SCOPE_INSUFFICIENT": None,
- "Account has been deleted": None,
- "INVALID_CUSTOMER_ID": None,
+ "ACCESS_TOKEN_SCOPE_INSUFFICIENT": "Your Google Ads connection is missing the access PostHog needs. Reconnect your Google Ads account and allow access to your Google Ads data.",
+ "Account has been deleted": "The Google Ads account this source syncs from has been deleted, so there's nothing left to import. Point the source at an active customer ID, or delete the source.",
+ "INVALID_CUSTOMER_ID": "The customer ID on this source isn't a valid Google Ads account. Update it to the 10-digit customer ID shown in your Google Ads account, then re-enable the sync.",
"REQUESTED_METRICS_FOR_MANAGER": "Metrics cannot be requested for a Google Ads manager (MCC) account. Reconfigure this source with a client account customer ID, or enable the MCC option and provide both the manager and client customer IDs.",
+ # A gRPC PERMISSION_DENIED (and its ads-level USER_PERMISSION_DENIED counterpart) means the
+ # connected Google login can't reach this customer ID. The sync already retries as the
+ # manager account that can reach it (see `GoogleAdsSearchService`), so anything landing here
+ # is access the login genuinely doesn't have. Its str() is a raw gRPC status and protobuf
+ # dump (with a per-request peer IP) the user can't act on, so replace it.
+ "PERMISSION_DENIED": (
+ "The connected Google login can't access this Google Ads account. Check the customer ID "
+ "is correct and still shared with that login, and if it's a client account under a "
+ 'manager (MCC) account, enable "Using MCC account?" and enter your manager\'s customer '
+ "ID. Then reconnect your Google Ads account and re-enable the sync."
+ ),
+ # A gRPC UNAUTHENTICATED means Google rejected the credentials outright. Same story: the raw
+ # status dump is unusable and only reconnecting recovers.
+ "UNAUTHENTICATED": "Your Google Ads connection could not be authenticated. Please reconnect your Google Ads account.",
# google.auth.exceptions.RefreshError raised when the stored OAuth refresh token
# has been revoked, expired, or is otherwise rejected by Google's token endpoint.
# Retrying cannot recover — the user must reconnect their Google Ads account.
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 3ef333a34bfa..4997b9a29d3d 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
@@ -16,6 +16,7 @@ import pyarrow as pa
import requests
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.authorization_error import AuthorizationErrorEnum
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
@@ -40,8 +41,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS,
GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN,
GoogleAdsColumn,
+ GoogleAdsSearchService,
GoogleAdsTable,
_get_integration,
+ _is_permission_denied_error,
_is_rejected_page_token_error,
_is_stale_page_token_error,
_is_transient_client_init_error,
@@ -300,6 +303,25 @@ class TestGoogleAdsNonRetryableErrors:
def test_documented_patterns_present(self, pattern):
assert pattern in self.non_retryable
+ def test_every_pattern_has_user_facing_copy(self):
+ # A pattern mapped to None leaves the raw error on the job, which for this source is a gRPC
+ # status and protobuf dump (peer IP included) that means nothing to the customer.
+ assert [pattern for pattern, message in self.non_retryable.items() if message is None] == []
+
+ @pytest.mark.parametrize(
+ "specific_pattern",
+ [
+ # Google returns these under a PERMISSION_DENIED status, so the generic status pattern
+ # would match them too. The finalization activity shows the first match, so the specific
+ # pattern has to come first or the customer is told to fix the wrong thing.
+ "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
+ "Account has been deleted",
+ ],
+ )
+ def test_specific_codes_are_matched_before_the_generic_status(self, specific_pattern):
+ patterns = list(self.non_retryable.keys())
+ assert patterns.index(specific_pattern) < patterns.index("PERMISSION_DENIED")
+
def test_requested_metrics_for_manager_has_user_facing_message(self):
message = self.non_retryable["REQUESTED_METRICS_FOR_MANAGER"]
assert message is not None
@@ -998,6 +1020,147 @@ class TestSearchTransientRetry:
assert sleep.call_count == 0
+_MANAGER_CUSTOMER_ID = "1112223333"
+_CLIENT_CUSTOMER_ID = "1234567890"
+
+
+def _grpc_permission_denied_error() -> grpc.RpcError:
+ return _StatusCodeRpcError(grpc.StatusCode.PERMISSION_DENIED, "The caller does not have permission")
+
+
+def _user_permission_denied_failure() -> GoogleAdsException:
+ failure = GoogleAdsFailure(
+ errors=[
+ GoogleAdsError(
+ error_code=ErrorCode(
+ authorization_error=AuthorizationErrorEnum.AuthorizationError.USER_PERMISSION_DENIED
+ ),
+ message="User doesn't have permission to access customer.",
+ )
+ ]
+ )
+ return GoogleAdsException(error=None, call=None, failure=failure, request_id="req-1")
+
+
+class _FakeSearchService:
+ def __init__(self, client: "_FakeGoogleAdsClient", login_customer_id: str | None):
+ self._client = client
+ # The header is baked in when the service is built, as the real SDK does.
+ self._login_customer_id = login_customer_id
+
+ def search(self, request: dict):
+ customer_id = request["customer_id"]
+ self._client.searches.append((customer_id, self._login_customer_id))
+
+ clients_under_request_target = self._client.manager_of.get(customer_id)
+ if clients_under_request_target is not None and "customer_client" in request["query"]:
+ hits = [client for client in clients_under_request_target if client in request["query"]]
+ return SimpleNamespace(pages=iter([SimpleNamespace(results=[SimpleNamespace()] * len(hits))]))
+
+ reachable = self._client.manager_of.get(self._login_customer_id or "", [])
+ if customer_id not in reachable:
+ raise _google_ads_exception_wrapping(_grpc_permission_denied_error())
+ return SimpleNamespace(pages=iter([self._client.page]))
+
+
+class _FakeGoogleAdsClient:
+ """Stand-in for ``GoogleAdsClient`` that refuses a client account without a login-customer-id.
+
+ ``manager_of`` maps a manager account to the client accounts under it, which is both what the
+ ``customer_client`` lookup reports and what the login is allowed to request.
+ """
+
+ def __init__(self, *, accessible: list[str], manager_of: dict[str, list[str]], page: SimpleNamespace):
+ self.login_customer_id: str | None = None
+ self.accessible = accessible
+ self.manager_of = manager_of
+ self.page = page
+ self.searches: list[tuple[str, str | None]] = []
+
+ def get_service(self, name: str, version: str | None = None, interceptors: object = None):
+ if name == "CustomerService":
+ return SimpleNamespace(
+ list_accessible_customers=lambda: SimpleNamespace(
+ resource_names=[f"customers/{customer_id}" for customer_id in self.accessible]
+ )
+ )
+ return _FakeSearchService(self, self.login_customer_id)
+
+
+class TestPermissionDeniedDetection:
+ @pytest.mark.parametrize(
+ "exc, expected",
+ [
+ # The production shape: the SDK wraps the transport status in a GoogleAdsException, so the
+ # PERMISSION_DENIED status lives on the wrapped error rather than the exception itself.
+ (_google_ads_exception_wrapping(_grpc_permission_denied_error()), True),
+ (_grpc_permission_denied_error(), True),
+ (google_api_exceptions.PermissionDenied("403 The caller does not have permission"), True),
+ # Google can also report it only at the ads level, with no transport status to unwrap.
+ (_user_permission_denied_failure(), True),
+ # A transient blip must not send us hunting for a manager account.
+ (_google_ads_exception_wrapping(_grpc_unavailable_error()), False),
+ (_google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN), False),
+ (ValueError("boom"), False),
+ ],
+ )
+ def test_is_permission_denied_error(self, exc, expected):
+ assert _is_permission_denied_error(exc) is expected
+
+
+class TestLoginCustomerIdRecovery:
+ def test_retries_as_the_manager_account_that_can_reach_the_customer(self):
+ # A client account the login only reaches through a manager: without the login-customer-id
+ # header Google refuses every request, so the sync has to find the manager and retry.
+ client = _FakeGoogleAdsClient(
+ accessible=[_MANAGER_CUSTOMER_ID],
+ manager_of={_MANAGER_CUSTOMER_ID: [_CLIENT_CUSTOMER_ID]},
+ page=_single_page(),
+ )
+ service = GoogleAdsSearchService(client, "v25", _CLIENT_CUSTOMER_ID)
+
+ tables = list(
+ _search_as_arrow_tables(
+ service=service,
+ customer_id=_CLIENT_CUSTOMER_ID,
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=_FakeResumableManager(saved_token=None), # type: ignore[arg-type]
+ )
+ )
+
+ # The rows landed, and the successful request carried the manager as its login-customer-id.
+ assert [t.to_pylist() for t in tables] == [[{"campaign_name": "Acme"}]]
+ assert client.searches[-1] == (_CLIENT_CUSTOMER_ID, _MANAGER_CUSTOMER_ID)
+
+ def test_permission_denied_propagates_when_no_accessible_manager_reaches_the_customer(self):
+ # Access really is gone: no accessible account can reach the customer, so the error must
+ # surface for the non-retryable handling instead of being retried forever.
+ client = _FakeGoogleAdsClient(
+ accessible=[_MANAGER_CUSTOMER_ID],
+ manager_of={_MANAGER_CUSTOMER_ID: ["9999999999"]},
+ page=_single_page(),
+ )
+ service = GoogleAdsSearchService(client, "v25", _CLIENT_CUSTOMER_ID)
+
+ with pytest.raises(GoogleAdsException):
+ list(
+ _search_as_arrow_tables(
+ service=service,
+ customer_id=_CLIENT_CUSTOMER_ID,
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=_FakeResumableManager(saved_token=None), # type: ignore[arg-type]
+ )
+ )
+
+ # The sync request was tried once and not repeated, and no bogus header was left behind.
+ assert [search for search in client.searches if search[0] == _CLIENT_CUSTOMER_ID] == [
+ (_CLIENT_CUSTOMER_ID, None)
+ ]
+ assert client.login_customer_id is None
+
+
class _FlakyFieldService:
"""Raises a transient error for the first ``fail_times`` calls, then returns a fields pager."""