: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(data-warehouse): keep the google-ads SDK off the source-registration path (#61071)
Julian Bez0ba05b376be3
diff --git a/posthog/temporal/data_imports/sources/google_ads/configs.py b/posthog/temporal/data_imports/sources/google_ads/configs.pynew file mode 100644index 000000000000..471c378448a7--- /dev/null+++ b/posthog/temporal/data_imports/sources/google_ads/configs.py@@ -0,0 +1,62 @@+"""Lightweight Google Ads config classes.++Kept separate from ``google_ads.py`` so importing the source for registration+(``SourceRegistry`` / ``load_all_sources``) does not drag the ``google-ads`` SDK.+The SDK has a circular module graph that is only safe to import single-threaded;+importing it from concurrent worker threads can deadlock or duplicate-register its+protobuf descriptors. Nothing here imports the SDK — that import is deferred to the+run path in ``source.py``. See ``google_ads.py`` for the SDK-backed functions.+"""++import dataclasses++from posthog.temporal.data_imports.sources.common import config+from posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig+++class GoogleAdsResumeConfig:+ """Resumable state for the Google Ads source.++ `page_token` is the opaque continuation token returned by+ `GoogleAdsService.search` for the next page to fetch.+ """++ page_token: str+++def clean_customer_id(s: str | None) -> str | None:+ """Clean customer IDs from Google Ads.++ Customer IDs can contain dashes, but we need the ID without them.+ """+ if not s:+ return s++ return s.strip().replace("-", "")+++class GoogleAdsServiceAccountSourceConfig(config.Config):+ """Google Ads source config using service account for authentication.++ Old config for when we were using a service account instead of oauth.+ ~100 sources still use this method for auth. We recommend using+ `GoogleAdsSourceConfig` instead"""++ customer_id: str = config.value(converter=clean_customer_id)++ private_key: str = config.value(+ default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")+ )+ private_key_id: str = config.value(+ default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")+ )+ client_email: str = config.value(+ default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")+ )+ token_uri: str = config.value(default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_TOKEN_URI"))+ developer_token: str = config.value(default_factory=config.default_from_settings("GOOGLE_ADS_DEVELOPER_TOKEN"))+++GoogleAdsSourceConfigUnion = GoogleAdsServiceAccountSourceConfig | GoogleAdsSourceConfigdiff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.pyindex beb994f72955..ea44e52f86ab 100644--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py@@ -1,6 +1,5 @@import typingimport datetime as dt-import dataclassesimport collections.abcfrom django.conf import settings@@ -20,11 +19,15 @@ from posthog.models.integration import Integrationfrom posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_valuefrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse-from posthog.temporal.data_imports.sources.common import configfrom posthog.temporal.data_imports.sources.common.grpc import tracked_interceptorsfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.common.sql import Column, Tablefrom posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig+from posthog.temporal.data_imports.sources.google_ads.configs import (+ GoogleAdsResumeConfig,+ GoogleAdsSourceConfigUnion,+ clean_customer_id,+)from posthog.temporal.data_imports.sources.google_ads.schemas import FIELD_ALIASES, RESOURCE_SCHEMASfrom products.data_warehouse.backend.types import IncrementalFieldType@@ -34,54 +37,6 @@ from products.data_warehouse.backend.types import IncrementalFieldTypeGOOGLE_ADS_HOST = "googleads.googleapis.com"-class GoogleAdsResumeConfig:- """Resumable state for the Google Ads source.-- `page_token` is the opaque continuation token returned by- `GoogleAdsService.search` for the next page to fetch.- """-- page_token: str---def clean_customer_id(s: str | None) -> str | None:- """Clean customer IDs from Google Ads.-- Customer IDs can contain dashes, but we need the ID without them.- """- if not s:- return s-- return s.strip().replace("-", "")---class GoogleAdsServiceAccountSourceConfig(config.Config):- """Google Ads source config using service account for authentication.-- Old config for when we were using a service account instead of oauth.- ~100 sources still use this method for auth. We recommend using- `GoogleAdsSourceConfig` instead"""-- customer_id: str = config.value(converter=clean_customer_id)-- private_key: str = config.value(- default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY")- )- private_key_id: str = config.value(- default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_PRIVATE_KEY_ID")- )- client_email: str = config.value(- default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_CLIENT_EMAIL")- )- token_uri: str = config.value(default_factory=config.default_from_settings("GOOGLE_ADS_SERVICE_ACCOUNT_TOKEN_URI"))- developer_token: str = config.value(default_factory=config.default_from_settings("GOOGLE_ADS_DEVELOPER_TOKEN"))---GoogleAdsSourceConfigUnion = GoogleAdsServiceAccountSourceConfig | GoogleAdsSourceConfig--def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> GoogleAdsClient:"""Initialize a `GoogleAdsClient` with provided config."""if isinstance(config, GoogleAdsSourceConfig):diff --git a/posthog/temporal/data_imports/sources/google_ads/source.py b/posthog/temporal/data_imports/sources/google_ads/source.pyindex f53bfd2c116f..ee35d6219d8b 100644--- a/posthog/temporal/data_imports/sources/google_ads/source.py+++ b/posthog/temporal/data_imports/sources/google_ads/source.py@@ -22,14 +22,10 @@ from posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig-from posthog.temporal.data_imports.sources.google_ads.google_ads import (+from posthog.temporal.data_imports.sources.google_ads.configs import (GoogleAdsResumeConfig,GoogleAdsServiceAccountSourceConfig,clean_customer_id,- get_incremental_fields as get_google_ads_incremental_fields,- get_schemas as get_google_ads_schemas,- google_ads_client,- google_ads_source,)from products.data_warehouse.backend.types import ExternalDataSourceType@@ -72,6 +68,12 @@ class GoogleAdsSource(names: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:+ # Deferred so registering this source doesn't import the google-ads SDK — see configs.py.+ from posthog.temporal.data_imports.sources.google_ads.google_ads import ( # noqa: PLC0415+ get_incremental_fields as get_google_ads_incremental_fields,+ get_schemas as get_google_ads_schemas,+ )+google_ads_schemas = get_google_ads_schemas(config,team_id,@@ -109,6 +111,8 @@ class GoogleAdsSource(resumable_source_manager: ResumableSourceManager[GoogleAdsResumeConfig],inputs: SourceInputs,) -> SourceResponse:+ from posthog.temporal.data_imports.sources.google_ads.google_ads import google_ads_source # noqa: PLC0415+return google_ads_source(config=config,resource_name=inputs.schema_name,@@ -228,6 +232,8 @@ class GoogleAdsSource(team_id: int,schema_name: Optional[str] = None,) -> tuple[bool, str | None]:+ from posthog.temporal.data_imports.sources.google_ads.google_ads import google_ads_client # noqa: PLC0415+try:client = google_ads_client(config, team_id)diff --git a/posthog/temporal/tests/data_imports/test_google_ads_source.py b/posthog/temporal/tests/data_imports/test_google_ads_source.pyindex 581d890d9914..01ab074c001f 100644--- a/posthog/temporal/tests/data_imports/test_google_ads_source.py+++ b/posthog/temporal/tests/data_imports/test_google_ads_source.py@@ -1,5 +1,7 @@import os+import sysimport json+import subprocessfrom collections.abc import Iterablefrom dataclasses import dataclass@@ -14,9 +16,11 @@ from posthog.models import Teamfrom posthog.models.organization import Organizationfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.generated_configs import GoogleAdsIsMccAccountConfig, GoogleAdsSourceConfig-from posthog.temporal.data_imports.sources.google_ads.google_ads import (+from posthog.temporal.data_imports.sources.google_ads.configs import (GoogleAdsResumeConfig,GoogleAdsServiceAccountSourceConfig,+)+from posthog.temporal.data_imports.sources.google_ads.google_ads import (GoogleAdsTable,_search_as_arrow_tables,get_schemas,@@ -412,7 +416,7 @@ class TestGoogleAdsSourceValidation:assert any("Please enter a valid Google Ads customer ID" in error for error in errors)assert is_valid is False- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_success(self, mock_client):mock_customer_service = mock.MagicMock()mock_customer_service.list_accessible_customers.return_value.resource_names = ["customers/1234567890"]@@ -425,7 +429,7 @@ class TestGoogleAdsSourceValidation:assert is_valid is Trueassert error is None- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_invalid_customer_id(self, mock_client):mock_customer_service = mock.MagicMock()mock_customer_service.list_accessible_customers.return_value.resource_names = ["customers/9999999999"]@@ -439,7 +443,7 @@ class TestGoogleAdsSourceValidation:assert error is not Noneassert "is not correct" in error- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_access_token_scope_insufficient(self, mock_client):mock_client.return_value.get_service.side_effect = Exception("ACCESS_TOKEN_SCOPE_INSUFFICIENT: Request had insufficient authentication scopes"@@ -453,7 +457,7 @@ class TestGoogleAdsSourceValidation:assert error is not Noneassert "Insufficient permissions" in error- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_not_ads_user(self, mock_client):mock_client.return_value.get_service.side_effect = Exception("NOT_ADS_USER: The Google account is not associated with any Ads accounts"@@ -467,7 +471,7 @@ class TestGoogleAdsSourceValidation:assert error is not Noneassert "not associated with any Google Ads accounts" in error- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_generic_error(self, mock_client):mock_client.return_value.get_service.side_effect = Exception("Some unexpected error occurred")@@ -479,7 +483,7 @@ class TestGoogleAdsSourceValidation:assert error is not Noneassert "Error validating credentials" in error- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_mcc_success(self, mock_client):mock_ga_service = mock.MagicMock()mock_response = [mock.MagicMock()]@@ -500,7 +504,7 @@ class TestGoogleAdsSourceValidation:call_kwargs = mock_ga_service.search.call_args[1]assert call_kwargs["customer_id"] == "1234567890"- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_mcc_customer_not_found(self, mock_client):mock_ga_service = mock.MagicMock()mock_ga_service.search.side_effect = Exception("CUSTOMER_NOT_FOUND: Customer not found")@@ -518,7 +522,7 @@ class TestGoogleAdsSourceValidation:assert error is not Noneassert "is not accessible" in error- @mock.patch("posthog.temporal.data_imports.sources.google_ads.source.google_ads_client")+ @mock.patch("posthog.temporal.data_imports.sources.google_ads.google_ads.google_ads_client")def test_validate_credentials_mcc_permission_denied(self, mock_client):mock_ga_service = mock.MagicMock()mock_ga_service.search.side_effect = Exception("USER_PERMISSION_DENIED: User does not have permission")@@ -590,3 +594,28 @@ class TestGoogleAdsClientStaleConnection:google_ads_client(config, team_id=7)mock_close_old_connections.assert_not_called()+++# Runs in a clean interpreter — this test module imports the google-ads SDK itself, so we can't+# inspect this process's sys.modules.+_SDK_LEAK_CHECK = """+import os, sys+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+from posthog.temporal.data_imports.sources.common.registry import SourceRegistry+SourceRegistry._ensure_loaded()+print("\\n".join(sorted(m for m in sys.modules if m.startswith("google.ads"))))+"""+++def test_source_registration_does_not_import_google_ads_sdk() -> None:+ # google-ads has a circular module graph that is only safe to import single-threaded; importing+ # it from concurrent worker threads deadlocks or duplicate-registers its protobuf descriptors.+ # So registering sources (load_all_sources, which any sync triggers via SourceRegistry) must NOT+ # import the SDK — it loads lazily only when a google-ads sync actually runs. This guards the+ # split between configs.py (lightweight, registered) and google_ads.py (SDK, deferred).+ result = subprocess.run([sys.executable, "-c", _SDK_LEAK_CHECK], capture_output=True, text=True, timeout=120)+ assert result.returncode == 0, result.stderr[-2000:]+ leaked = [m for m in result.stdout.splitlines() if m]+ assert not leaked, f"google-ads SDK imported during source registration: {leaked[:5]}"