: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
feat(data-warehouse): backend-driven account picker for google ads (#69838)
Javier Bahamondesed3a6051a896
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 0b6f3cdf6638..6ab6503fd65f 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -1651,6 +1651,12 @@ def validate_slack_request(request: HttpRequest | Request, signing_secret: str)raise SlackIntegrationError("Invalid")+def google_ads_hierarchy_level(account: dict) -> int:+ """Depth of an account below the manager the walk started from. Google's REST responses omit proto3+ defaults, so a level-0 account carries no `level` key at all, and deeper ones arrive as strings."""+ return int(account.get("level") or 0)++class GoogleAdsIntegration:integration: Integration@@ -1709,7 +1715,7 @@ class GoogleAdsIntegration:# Google Ads manager accounts can have access to other accounts (including other manager accounts).# Filter out duplicates where a user has direct access and access through a manager account, while prioritizing direct access.- def list_google_ads_accessible_accounts(self) -> list[dict[str, str]]:+ def list_google_ads_accessible_accounts(self) -> list[dict[str, Any]]:response = requests.request("GET","https://googleads.googleapis.com/v21/customers:listAccessibleCustomers",@@ -1745,7 +1751,7 @@ class GoogleAdsIntegration:raise Exception("There was an internal error")accessible_accounts = response.json()- all_accounts: list[dict[str, str]] = []+ all_accounts: list[dict[str, Any]] = []def dfs(account_id, accounts=None, parent_id=None) -> list[dict]:if accounts is None:@@ -1768,33 +1774,40 @@ class GoogleAdsIntegration:if response.status_code != 200:return accounts+ # searchStream's REST body is an array of response objects, one per streamed batch.data = response.json()-- for nested_account in data[0]["results"]:- if any(- account["id"] == nested_account["customerClient"]["clientCustomer"].split("/")[1]- and account["level"] > nested_account["customerClient"]["level"]- for account in accounts- ):- accounts = [- account- for account in accounts- if account["id"] != nested_account["customerClient"]["clientCustomer"].split("/")[1]- ]- elif any(- account["id"] == nested_account["customerClient"]["clientCustomer"].split("/")[1]- and account["level"] < nested_account["customerClient"]["level"]- for account in accounts- ):- continue- if nested_account["customerClient"].get("status") != "ENABLED":+ results = [row for chunk in data for row in chunk.get("results", [])]++ for nested_account in results:+ client = nested_account["customerClient"]+ client_id = client["clientCustomer"].split("/")[1]+ # `level` is compared numerically: it is absent on the level-0 row and a string ("1", "2")+ # below it, so the raw values are not mutually comparable.+ client_level = google_ads_hierarchy_level(client)++ # Reject non-enabled accounts before deduping. Otherwise a disabled, shallower sighting+ # of an account we already kept as enabled would evict the enabled entry here and then be+ # skipped by the status check below, dropping the account from the picker entirely.+ if client.get("status") != "ENABLED":continue++ # One account can be reached from several accessible roots — e.g. a user with access to+ # both a manager and one of its clients walks that client twice, once as a root (level 0)+ # and once beneath the manager (level 1). Keep the shallowest sighting, whose `parent_id`+ # is the account we can authenticate the sync as.+ already_seen = [account for account in accounts if account["id"] == client_id]+ if already_seen:+ if all(google_ads_hierarchy_level(account) <= client_level for account in already_seen):+ continue+ accounts = [account for account in accounts if account["id"] != client_id]+accounts.append({"parent_id": parent_id,- "id": nested_account["customerClient"].get("clientCustomer").split("/")[1],- "level": nested_account["customerClient"].get("level"),- "name": nested_account["customerClient"].get("descriptiveName", "Google Ads account"),+ "id": client_id,+ "level": client.get("level"),+ "name": client.get("descriptiveName", "Google Ads account"),+ "manager": client.get("manager", False),})diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex c6b770287274..6fdd27d61334 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -40,6 +40,7 @@ from posthog.models.integration import (EmailIntegration,GitHubIntegration,GitHubIntegrationError,+ GoogleAdsIntegration,GoogleCloudIntegration,GoogleCloudServiceAccountIntegration,Integration,@@ -2856,6 +2857,107 @@ class TestS3CompatibleIntegrationModel(BaseTest):S3CompatibleIntegration(integration)+class TestGoogleAdsIntegrationModel(BaseTest):+ def _integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="google-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="google_ads_test",+ )++ @staticmethod+ def _customer_client(+ customer_id: str, name: str, level: Optional[str] = None, manager: bool = False, status: str = "ENABLED"+ ) -> dict:+ client: dict = {"clientCustomer": f"customers/{customer_id}", "descriptiveName": name, "status": status}+ # Google's REST responses omit proto3 defaults, so level 0 and manager=false are absent.+ if level is not None:+ client["level"] = level+ if manager:+ client["manager"] = True+ return {"customerClient": client}++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.requests.request")+ def test_accessible_accounts_reads_every_search_stream_chunk(self, mock_request):+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/6501924158"]}+ # searchStream's REST body is an array of batches; a large hierarchy spans several.+ stream = MagicMock(status_code=200)+ stream.json.return_value = [+ {"results": [self._customer_client("6501924158", "Acme Corp", manager=True)]},+ {"results": [self._customer_client("1234567890", "Client One", level="1")]},+ ]+ mock_request.side_effect = [accessible, stream]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ assert [account["id"] for account in accounts] == ["6501924158", "1234567890"]+ assert accounts[0]["manager"] is True+ assert accounts[1]["parent_id"] == "6501924158"++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.requests.request")+ def test_accessible_accounts_dedupes_an_account_reachable_from_two_roots(self, mock_request):+ # A user with direct access to both a manager and one of its clients gets both in+ # `resourceNames`, so the client is walked twice: once as a root (level absent, i.e. 0) and once+ # under the manager (level "1"). Those two levels must be compared as numbers — comparing the raw+ # values raises TypeError (None vs "1") and 500s the picker.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/1234567890", "customers/6501924158"]}+ client_walk = MagicMock(status_code=200)+ client_walk.json.return_value = [{"results": [self._customer_client("1234567890", "Client One")]}]+ manager_walk = MagicMock(status_code=200)+ manager_walk.json.return_value = [+ {+ "results": [+ self._customer_client("6501924158", "Acme Corp", manager=True),+ self._customer_client("1234567890", "Client One", level="1"),+ ]+ }+ ]+ mock_request.side_effect = [accessible, client_walk, manager_walk]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ # The client is kept once, at its shallowest sighting: reachable directly, so it needs no manager+ # to log in as.+ assert [account["id"] for account in accounts] == ["1234567890", "6501924158"]+ assert accounts[0]["level"] is None+ assert accounts[0]["parent_id"] == "1234567890"++ @override_settings(GOOGLE_ADS_DEVELOPER_TOKEN="dev_token")+ @patch("posthog.models.integration.requests.request")+ def test_accessible_accounts_keeps_enabled_sighting_when_shallower_root_is_disabled(self, mock_request):+ # The same client is reachable enabled under a manager (level "1") and directly as a disabled root+ # (level 0). The enabled path is walked first and kept; the disabled shallower root must not evict+ # it — otherwise the account vanishes from the picker even though Google returned an enabled path.+ accessible = MagicMock(status_code=200)+ accessible.json.return_value = {"resourceNames": ["customers/6501924158", "customers/1234567890"]}+ manager_walk = MagicMock(status_code=200)+ manager_walk.json.return_value = [+ {+ "results": [+ self._customer_client("6501924158", "Acme Corp", manager=True),+ self._customer_client("1234567890", "Client One", level="1"),+ ]+ }+ ]+ disabled_root_walk = MagicMock(status_code=200)+ disabled_root_walk.json.return_value = [+ {"results": [self._customer_client("1234567890", "Client One", status="DISABLED")]}+ ]+ mock_request.side_effect = [accessible, manager_walk, disabled_root_walk]++ accounts = GoogleAdsIntegration(self._integration()).list_google_ads_accessible_accounts()++ client = next(account for account in accounts if account["id"] == "1234567890")+ assert client["level"] == "1"+ assert client["parent_id"] == "6501924158"++class TestPinterestAdsIntegrationDisplayName(BaseTest):@parameterized.expand([diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex c95f327f4e67..0a9e407a63e9 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -3,7 +3,7 @@ import timeimport uuidimport typing as tfrom datetime import date, timedelta-from typing import cast+from typing import Any, castfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, FuzzyInt@@ -11656,6 +11656,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):_BING_LIST_ACCOUNTS = ("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.BingAdsClient.list_accounts")+ _GOOGLE_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.source"_REDDIT_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.source"_LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"_PINTEREST_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source"@@ -12277,6 +12278,92 @@ class TestOAuthAccountsEndpoint(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert "reconnect your account" in str(response.json()).lower()+ def _google_ads_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="google-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="google_ads_test",+ created_by=self.user,+ )++ def _google_ads_accounts(self, listed: list[dict[str, Any]]):+ with (+ patch(f"{self._GOOGLE_ADS_MODULE}.OauthIntegration") as mock_oauth,+ patch(f"{self._GOOGLE_ADS_MODULE}.GoogleAdsIntegration") as mock_google_ads,+ ):+ mock_oauth.return_value.access_token_expired.return_value = False+ mock_google_ads.return_value.list_google_ads_accessible_accounts.return_value = listed+ return self.client.get(self._url("GoogleAds", self._google_ads_integration().id))++ def test_google_ads_maps_hierarchy_to_accounts(self):+ listed: list[dict[str, Any]] = [+ {"parent_id": "6501924158", "id": "6501924158", "level": None, "name": "Acme Corp", "manager": True},+ {"parent_id": "6501924158", "id": "1234567890", "level": "1", "name": "Client One", "manager": False},+ ]++ response = self._google_ads_accounts(listed)++ assert response.status_code == status.HTTP_200_OK, response.content+ # Stored dashed as the Google Ads UI shows it; clean_customer_id normalizes to bare at the API boundary.+ assert response.json()["accounts"] == [+ {+ "value": "650-192-4158",+ "display_name": "Acme Corp",+ "is_primary": True,+ "badges": ["Manager"],+ "group": None,+ "secondary_text": None,+ },+ {+ "value": "123-456-7890",+ "display_name": "Client One",+ "is_primary": False,+ "badges": [],+ "group": "Acme Corp",+ "secondary_text": None,+ },+ ]++ def test_google_ads_does_not_group_accounts_below_the_first_level(self):+ # `parent_id` is the accessible root the hierarchy walk started from, not the direct manager, so+ # it names the true parent only one level down. A sub-manager's client must not claim to sit+ # "under" the root.+ listed: list[dict[str, Any]] = [+ {"parent_id": "6501924158", "id": "6501924158", "level": None, "name": "Acme Corp", "manager": True},+ {"parent_id": "6501924158", "id": "1234567890", "level": "1", "name": "Sub Manager", "manager": True},+ {"parent_id": "6501924158", "id": "5555555555", "level": "2", "name": "Deep Client", "manager": False},+ ]++ response = self._google_ads_accounts(listed)++ assert response.status_code == status.HTTP_200_OK, response.content+ assert [(a["display_name"], a["group"]) for a in response.json()["accounts"]] == [+ ("Acme Corp", None),+ ("Sub Manager", "Acme Corp"),+ ("Deep Client", None),+ ]++ def test_google_ads_search_matches_a_manager_name(self):+ # The client folds `group` into its search text, but the endpoint filters server-side first, so a+ # manager's name has to match there or the client never sees the row.+ listed = [+ {"parent_id": "6501924158", "id": "6501924158", "level": None, "name": "Acme Corp", "manager": True},+ {"parent_id": "6501924158", "id": "1234567890", "level": "1", "name": "Client One", "manager": False},+ ]++ with (+ patch(f"{self._GOOGLE_ADS_MODULE}.OauthIntegration") as mock_oauth,+ patch(f"{self._GOOGLE_ADS_MODULE}.GoogleAdsIntegration") as mock_google_ads,+ ):+ mock_oauth.return_value.access_token_expired.return_value = False+ mock_google_ads.return_value.list_google_ads_accessible_accounts.return_value = listed+ response = self.client.get(self._url("GoogleAds", self._google_ads_integration().id) + "&search=acme")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert [a["value"] for a in response.json()["accounts"]] == ["650-192-4158", "123-456-7890"]+def test_linkedin_success_maps_ad_accounts_to_accounts(self):integration = self._linkedin_integration()client = MagicMock()diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsxindex 8f73f1a97d3f..a1c8244b4051 100644--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx@@ -179,7 +179,13 @@ function useFormIntegrationId(formLogic: any, formKey: string, integrationField:const OWNER_REPO_PATTERN = /^[^/\s]+\/[^/\s]+$/-function accountOptionLabel(displayName: string, value: string, isPrimary: boolean, badges: string[]): JSX.Element {+function accountOptionLabel(+ displayName: string,+ value: string,+ isPrimary: boolean,+ badges: string[],+ group?: string | null+): JSX.Element {// When display_name === value (e.g. GSC site url), "value (value)" is redundant.const labelText = displayName === value ? displayName : `${displayName} (${value})`return (@@ -191,6 +197,7 @@ function accountOptionLabel(displayName: string, value: string, isPrimary: boole{badge}</LemonTag>))}+ {group && <span className="text-xs text-secondary">under {group}</span>}</div>)}@@ -349,13 +356,23 @@ function IntegrationAccountFieldWithDropdown({const suggestions = useMemo<InputSuggestion[]>(() => {const sorted = [...accounts].sort((a, b) => Number(b.is_primary) - Number(a.is_primary))return sorted.map((account) => {- const searchText =- account.display_name === account.value- ? `${account.value} ${account.secondary_text ?? ''}`- : `${account.display_name} ${account.value} ${account.secondary_text ?? ''}`+ const searchText = [+ account.display_name === account.value ? '' : account.display_name,+ account.value,+ account.secondary_text ?? '',+ account.group ?? '',+ ]+ .filter(Boolean)+ .join(' ')return {value: account.value,- label: accountOptionLabel(account.display_name, account.value, account.is_primary, account.badges),+ label: accountOptionLabel(+ account.display_name,+ account.value,+ account.is_primary,+ account.badges,+ account.group+ ),searchText,}})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.pyindex 2d08064824d7..77cadb80468b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_accounts.py@@ -42,4 +42,6 @@ def filter_integration_accounts(accounts: list[IntegrationAccount], search: strif query in account.display_name.lower()or query in account.value.lower()or (account.secondary_text is not None and query in account.secondary_text.lower())+ # The client also matches on `group`, and it can only match rows the server returned.+ or (account.group is not None and query in account.group.lower())]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.pyindex 5b3c7f4b80cf..79a56b2fefe4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_integration_accounts.py@@ -9,6 +9,7 @@ _ACCOUNTS = [IntegrationAccount(value="PostHog/posthog", display_name="PostHog/posthog"),IntegrationAccount(value="PostHog/code", display_name="PostHog/code"),IntegrationAccount(value="123", display_name="Acme Ads", secondary_text="ACC-987"),+ IntegrationAccount(value="456", display_name="Client One", group="Umbrella Corp"),]@@ -29,6 +30,12 @@ class TestFilterIntegrationAccounts:result = filter_integration_accounts(_ACCOUNTS, "acc-987")assert [a.value for a in result] == ["123"]+ def test_matches_group(self):+ # The client folds `group` into its own search text, but it can only match rows the server+ # returned — so searching a manager's name has to survive this filter first.+ result = filter_integration_accounts(_ACCOUNTS, "umbrella")+ assert [a.value for a in result] == ["456"]+def test_no_match_returns_empty(self):assert filter_integration_accounts(_ACCOUNTS, "nonexistent") == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.pyindex 0945138414f2..2f8379ac398f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py@@ -40,6 +40,14 @@ def clean_customer_id(s: str | None) -> str | None:return re.sub(r"\D", "", s)+def format_customer_id(s: str) -> str:+ """Render a bare 10-digit customer ID the way the Google Ads UI shows it (``123-456-7890``); anything else is returned untouched."""+ digits = re.sub(r"\D", "", s)+ if len(digits) != 10:+ return s+ return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"++@config.configclass GoogleAdsServiceAccountSourceConfig(config.Config):"""Google Ads source config using service account for authentication.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.pyindex 67dcc347ccf5..2ae5848fc9b6 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@@ -1,6 +1,10 @@import refrom typing import Optional, cast+from django.core.cache import cache++from rest_framework.exceptions import ValidationError+from posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,@@ -8,12 +12,19 @@ from posthog.schema import (SourceConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SourceFieldSwitchGroupConfig,SuggestedTable,)-from posthog.models.integration import Integration+from posthog.models.integration import (+ ERROR_TOKEN_REFRESH_FAILED,+ GoogleAdsIntegration,+ Integration,+ OauthIntegration,+ google_ads_hierarchy_level,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (SourceInputs,@@ -27,6 +38,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccount,+ IntegrationAccountListingError,+ filter_integration_accounts,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -36,6 +52,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_adsGoogleAdsResumeConfig,GoogleAdsServiceAccountSourceConfig,clean_customer_id,+ format_customer_id,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -51,6 +68,13 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType# enforced at the creation/update endpoints.GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+_OAUTH_ACCOUNTS_CACHE_TTL_SECONDS = 60+++def _oauth_accounts_cache_key(team_id: int, integration_id: int) -> str:+ # Keyed on (team, integration) only — never the search term — so distinct searches share one walk.+ return f"@dwh/google_ads/{team_id}/{integration_id}/oauth_accounts"+@SourceRegistry.registerclass GoogleAdsSource(@@ -200,14 +224,6 @@ class GoogleAdsSource(fields=cast(list[FieldType],[- SourceFieldInputConfig(- name="customer_id",- label="Customer ID",- type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="123-456-7890",- secret=False,- ),SourceFieldOauthConfig(name="google_ads_integration_id",label="Google Ads account",@@ -215,6 +231,14 @@ class GoogleAdsSource(kind="google-ads",requiredScopes="https://www.googleapis.com/auth/adwords",),+ SourceFieldOauthAccountSelectConfig(+ name="customer_id",+ label="Customer ID",+ integrationField="google_ads_integration_id",+ integrationKind="google-ads",+ required=True,+ placeholder="123-456-7890",+ ),SourceFieldSwitchGroupConfig(name="is_mcc_account",label="Using MCC account?",@@ -248,6 +272,65 @@ class GoogleAdsSource(],)+ def get_oauth_accounts(+ self, integration_id: int, team_id: int, search: str | None = None+ ) -> list[IntegrationAccount]:+ # The whole account list comes from one expensive hierarchy walk (listAccessibleCustomers plus a+ # searchStream per accessible root) that ignores `search`. Cache the unfiltered result keyed only+ # on (team, integration) — never `search` — so distinct search terms reuse one walk instead of+ # repeating it and burning shared Google Ads API quota, then filter the cached list in memory.+ cache_key = _oauth_accounts_cache_key(team_id, integration_id)+ cached = cache.get(cache_key)+ if cached is not None:+ return filter_integration_accounts(cached, search)++ try:+ integration = self.get_oauth_integration(integration_id, team_id)+ except ValueError as e:+ raise IntegrationAccountListingError(+ "The linked Google Ads integration could not be found. Please reconnect your Google Ads integration."+ ) from e++ oauth = OauthIntegration(integration)+ if integration.errors != ERROR_TOKEN_REFRESH_FAILED and oauth.access_token_expired():+ oauth.refresh_access_token()+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:+ raise IntegrationAccountListingError(+ "Could not refresh the Google Ads credentials. Please reconnect your Google Ads integration."+ )++ try:+ accounts = GoogleAdsIntegration(integration).list_google_ads_accessible_accounts()+ except ValidationError as e:+ # Raised only for a 401/403 from Google: revoked credentials, or the connected account+ # lost access.+ raise IntegrationAccountListingError(+ "Google rejected the credentials for this integration. Please reconnect your Google Ads "+ "integration and make sure the connected account can access your Google Ads accounts."+ ) from e++ names_by_id = {account["id"]: account["name"] for account in accounts}+ integration_accounts = [+ IntegrationAccount(+ # Dashed as the Google Ads UI shows it; clean_customer_id normalizes to bare at the API boundary.+ value=format_customer_id(account["id"]),+ display_name=account["name"],+ is_primary=google_ads_hierarchy_level(account) == 0,+ badges=("Manager",) if account.get("manager") else (),+ # `parent_id` is the accessible account the walk started from, not the direct manager, so+ # it only names the true parent one level down. Deeper accounts get no group rather than a+ # wrong one (the client renders this as "under <group>").+ group=names_by_id.get(account["parent_id"]) if google_ads_hierarchy_level(account) == 1 else None,+ )+ for account in accounts+ ]++ # Don't cache an empty result: a transient walk that returns [] without raising would otherwise+ # freeze the picker empty for the whole TTL for every admin on the team.+ if integration_accounts:+ cache.set(cache_key, integration_accounts, _OAUTH_ACCOUNTS_CACHE_TTL_SECONDS)+ return filter_integration_accounts(integration_accounts, search)+def validate_config(self, job_inputs: dict) -> tuple[bool, list[str]]:is_valid, errors = super().validate_config(job_inputs)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 a5bf2502d464..0b84addce8f8 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@@ -5,6 +5,7 @@ from types import SimpleNamespaceimport pytestfrom unittest import mock+from django.core.cache import cachefrom django.db import OperationalErrorimport grpc@@ -1133,6 +1134,39 @@ class TestOverviewStatsSchemas:assert overview["filter_field_names"] == [("segments.date", IncrementalFieldType.Date)]+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.source"+++class TestGetOAuthAccountsCaching:+ def test_distinct_search_terms_reuse_one_hierarchy_walk(self):+ # The whole account list comes from one expensive walk (listAccessibleCustomers + a searchStream+ # per accessible root) that ignores `search`. Keying the cache on the search term would repeat+ # that walk for every distinct query; the walk must run once and be filtered in memory.+ cache.clear()+ source = GoogleAdsSource()+ accounts = [+ {"id": "1234567890", "name": "Acme Corp", "level": None, "parent_id": "1234567890", "manager": False},+ {"id": "9876543210", "name": "Beta Client", "level": None, "parent_id": "9876543210", "manager": False},+ ]+ integration = mock.Mock(errors=None)++ with (+ mock.patch.object(GoogleAdsSource, "get_oauth_integration", return_value=integration),+ mock.patch(f"{_SOURCE_MODULE}.OauthIntegration") as mock_oauth,+ mock.patch(f"{_SOURCE_MODULE}.GoogleAdsIntegration") as mock_google_ads,+ ):+ mock_oauth.return_value.access_token_expired.return_value = False+ walk = mock_google_ads.return_value.list_google_ads_accessible_accounts+ walk.return_value = accounts++ first = source.get_oauth_accounts(1, 2, search="acme")+ second = source.get_oauth_accounts(1, 2, search="beta")++ walk.assert_called_once()+ assert [account.value for account in first] == ["123-456-7890"]+ assert [account.value for account in second] == ["987-654-3210"]++class TestGoogleAdsQueryConstruction:_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads"