: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(warehouse_sources): support the Apple Ads Platform API v1 (#89997)
Tom Owersfe489ca933c1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.pyindex 00f8e911be88..c03bc512f15e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py@@ -14,19 +14,23 @@ from urllib3.util.retry import Retryfrom posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (- APPLE_SEARCH_ADS_ENDPOINTS,+ APPLE_ADS_API_VERSION_V1,+ APPLE_SEARCH_ADS_API_VERSION_V5,DEFAULT_INITIAL_LOOKBACK_DAYS,- MAX_INITIAL_LOOKBACK_DAYS,PAGE_SIZE,REPORT_WINDOW_DAYS,AppleSearchAdsEndpointConfig,+ ReportingLimits,+ endpoints_for_version,+ reporting_limits_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponseAPPLE_SEARCH_ADS_HOST = "https://api.searchads.apple.com"-# Apple Search Ads authenticates through Apple ID's OAuth token endpoint, not a Search Ads host.+APPLE_ADS_HOST = "https://api.ads.apple.com"+# Both API versions authenticate through Apple ID's OAuth token endpoint, not an ads host.APPLE_OAUTH_TOKEN_URL = "https://appleid.apple.com/auth/oauth2/token"APPLE_OAUTH_AUDIENCE = "https://appleid.apple.com"APPLE_OAUTH_SCOPE = "searchadsorg"@@ -36,14 +40,19 @@ APPLE_OAUTH_SCOPE = "searchadsorg"CLIENT_SECRET_TTL_SECONDS = 30 * 60REQUEST_TIMEOUT_SECONDS = 120-# Cheap org-scoped probe for credential validation: it exercises the access token *and* the-# `X-AP-Context` org id, which `/acls` would not.-CREDENTIAL_PROBE_PATH = "/campaigns"+# Kinds whose whole result set arrives in one response, so there is no next page to ask for.+_UNPAGINATED_KINDS = frozenset({"single", "acls"})++# Where each version puts the per-day metric buckets on a report row.+_REPORT_METRICS_KEY = {+ APPLE_SEARCH_ADS_API_VERSION_V5: "granularity",+ APPLE_ADS_API_VERSION_V1: "granularMetrics",+}# Apple's documented ceiling is 100 requests/minute per account, surfaced as 429 with# `Retry-After`. The transport honors that header; POST is added to the retryable methods-# because every read path here except `/campaigns` and `/acls` is a side-effect-free POST-# (`/find`, `/reports/...`) that urllib3 would otherwise refuse to retry.+# because every read path here except v5's `/campaigns` and `/acls` is a side-effect-free POST+# (`/find`, `/query`, `/reports/...`) that urllib3 would otherwise refuse to retry.APPLE_SEARCH_ADS_RETRY = Retry(total=5,backoff_factor=1.0,@@ -62,17 +71,22 @@ class AppleSearchAdsAuthError(Exception):@dataclasses.dataclass(frozen=True)class AppleSearchAdsCredentials:- org_id: strclient_id: strteam_id: strkey_id: str# repr=False: keep the PEM out of tracebacks, logs, and pytest assertion diffs.private_key: str = dataclasses.field(repr=False)+ # v5 scopes every request to an organization, the Platform API to an ad account, and the+ # two are different identifiers. Which one a source needs follows its version pin, which+ # the connect form cannot express — so both are optional here and `validate_credentials`+ # enforces the one that applies.+ org_id: Optional[str] = None+ ad_account_id: Optional[str] = None@dataclasses.dataclass(frozen=True)class AppleSearchAdsResumeConfig:- # Offset into the current page set. Entity endpoints only ever use this field.+ # Offset into the current page set.offset: int = 0# ISO date of the reporting window in progress, and the campaign it was being fanned out# to. Both are matched by value on resume, so a changed campaign list restarts the run's@@ -89,9 +103,9 @@ def _normalize_private_key(private_key: str) -> str:def build_client_secret(credentials: AppleSearchAdsCredentials, *, issued_at: Optional[int] = None) -> str:"""Sign the ES256 client-secret assertion Apple's token endpoint expects.- Apple Search Ads has no static client secret: the caller signs a JWT with the private key- whose public half was uploaded in the Search Ads UI (`kid` = key id, `iss` = team id,- `sub` = client id) and presents that as `client_secret`.+ Apple has no static client secret: the caller signs a JWT with the private key whose public+ half was uploaded in the Apple Ads UI (`kid` = key id, `iss` = team id, `sub` = client id)+ and presents that as `client_secret`. Unchanged between v5 and the Platform API."""now = int(issued_at if issued_at is not None else time.time())try:@@ -109,13 +123,39 @@ def build_client_secret(credentials: AppleSearchAdsCredentials, *, issued_at: Op)except (jwt.PyJWTError, ValueError, TypeError) as e:raise AppleSearchAdsAuthError(- "Could not sign the Apple Search Ads client secret. The private key must be the "- f"unencrypted EC (P-256) PEM generated for your Search Ads API key: {e}"+ "Could not sign the Apple Ads client secret. The private key must be the unencrypted "+ f"EC (P-256) PEM generated for your Apple Ads API client: {e}") from e+def base_url_for_version(api_version: str) -> str:+ if api_version == APPLE_ADS_API_VERSION_V1:+ return f"{APPLE_ADS_HOST}/{api_version}"+ return f"{APPLE_SEARCH_ADS_HOST}/api/{api_version}"+++def _context_header(credentials: AppleSearchAdsCredentials, api_version: str) -> str:+ if api_version == APPLE_ADS_API_VERSION_V1:+ return f"adAccountId={credentials.ad_account_id}"+ return f"orgId={credentials.org_id}"+++def missing_context_id(credentials: AppleSearchAdsCredentials, api_version: str) -> Optional[str]:+ """Message naming the context id this version needs, when the form did not collect it."""+ if api_version == APPLE_ADS_API_VERSION_V1:+ if not credentials.ad_account_id:+ return (+ "Enter the ad account ID. The Apple Ads Platform API scopes every request to an "+ "ad account, which is not the same as the organization ID the older API used."+ )+ return None+ if not credentials.org_id:+ return "Enter the organization ID. The Apple Search Ads API scopes every request to an organization."+ return None++class AppleSearchAdsClient:- """Minimal Campaign Management API client: token minting plus JSON request helpers."""+ """Minimal Apple Ads client: token minting plus JSON request helpers."""def __init__(self,@@ -124,7 +164,8 @@ class AppleSearchAdsClient:request_logger: Optional[FilteringBoundLogger] = None,) -> None:self._credentials = credentials- self._base_url = f"{APPLE_SEARCH_ADS_HOST}/api/{api_version}"+ self._api_version = api_version+ self._base_url = base_url_for_version(api_version)self._logger: FilteringBoundLogger = request_logger or loggerself._access_token: Optional[str] = Noneself._session = make_tracked_session(@@ -162,7 +203,7 @@ class AppleSearchAdsClient:)if not response.ok:self._logger.error(- f"Apple Search Ads token exchange failed: status={response.status_code}, url={APPLE_OAUTH_TOKEN_URL}"+ f"Apple Ads token exchange failed: status={response.status_code}, url={APPLE_OAUTH_TOKEN_URL}")response.raise_for_status()@@ -171,10 +212,10 @@ class AppleSearchAdsClient:raise AppleSearchAdsAuthError("Apple's token response did not contain an access token")return str(access_token)- def _headers(self, requires_org_context: bool) -> dict[str, str]:+ def _headers(self, requires_context: bool) -> dict[str, str]:headers = {"Authorization": f"Bearer {self._access_token}", "Accept": "application/json"}- if requires_org_context:- headers["X-AP-Context"] = f"orgId={self._credentials.org_id}"+ if requires_context:+ headers["X-AP-Context"] = _context_header(self._credentials, self._api_version)return headersdef _send(@@ -184,9 +225,9 @@ class AppleSearchAdsClient:*,params: Optional[dict[str, Any]],body: Optional[dict[str, Any]],- requires_org_context: bool,+ requires_context: bool,) -> requests.Response:- headers = self._headers(requires_org_context)+ headers = self._headers(requires_context)if method == "POST":return self._session.post(url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)return self._session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)@@ -198,18 +239,18 @@ class AppleSearchAdsClient:*,params: Optional[dict[str, Any]] = None,body: Optional[dict[str, Any]] = None,- requires_org_context: bool = True,+ requires_context: bool = True,) -> requests.Response:if self._access_token is None:self.authenticate()url = f"{self._base_url}{path}"- response = self._send(method, url, params=params, body=body, requires_org_context=requires_org_context)+ response = self._send(method, url, params=params, body=body, requires_context=requires_context)# Access tokens live an hour, which a backfill routinely outlives — re-mint once and# replay before treating a 401 as a credential problem.if response.status_code == 401:self.authenticate()- response = self._send(method, url, params=params, body=body, requires_org_context=requires_org_context)+ response = self._send(method, url, params=params, body=body, requires_context=requires_context)return responsedef request_json(@@ -219,21 +260,27 @@ class AppleSearchAdsClient:*,params: Optional[dict[str, Any]] = None,body: Optional[dict[str, Any]] = None,- requires_org_context: bool = True,+ requires_context: bool = True,) -> dict[str, Any]:- response = self._request(method, path, params=params, body=body, requires_org_context=requires_org_context)+ response = self._request(method, path, params=params, body=body, requires_context=requires_context)if not response.ok:self._logger.error(- f"Apple Search Ads API error: status={response.status_code}, "- f"body={response.text}, url={self._base_url}{path}"+ f"Apple Ads API error: status={response.status_code}, body={response.text}, url={self._base_url}{path}")response.raise_for_status()payload = response.json()return payload if isinstance(payload, dict) else {}- def probe_status(self, path: str, *, params: Optional[dict[str, Any]] = None) -> int:- return self._request("GET", path, params=params).status_code+ def probe_status(+ self,+ method: str,+ path: str,+ *,+ params: Optional[dict[str, Any]] = None,+ body: Optional[dict[str, Any]] = None,+ ) -> int:+ return self._request(method, path, params=params, body=body).status_codedef validate_credentials(@@ -241,7 +288,7 @@ def validate_credentials(api_version: str,schema_name: Optional[str] = None,) -> tuple[bool, str | None]:- """Mint a token and probe one org-scoped endpoint.+ """Mint a token and probe one account-scoped endpoint.A 403 means the credentials are genuine but the role can't read this resource; accepted atsource-create (``schema_name is None``) so a user who only granted a subset of access can@@ -253,22 +300,66 @@ def validate_credentials(except AppleSearchAdsAuthError as e:return False, str(e)except requests.RequestException as e:- return False, f"Could not exchange the Apple Search Ads credentials for an access token: {e}"-+ return False, f"Could not exchange the Apple Ads credentials for an access token: {e}"++ # Checked after the token exchange so a bad key pair is reported as such, and so the+ # message can name the ids this API client can actually read.+ missing = missing_context_id(credentials, api_version)+ if missing is not None:+ return False, missing + _readable_ad_accounts(client, api_version)++ # The campaign list is the cheapest account-scoped read: it exercises the access token+ # *and* the `X-AP-Context` id, which the ACL endpoint would not.+ config = endpoints_for_version(api_version)["campaigns"]+ request = page_request(config, api_version, RequestScope(), offset=0, page_size=1)try:- status = client.probe_status(CREDENTIAL_PROBE_PATH, params={"limit": 1})+ status = client.probe_status(request.method, request.path, params=request.params, body=request.body)except requests.RequestException as e:- return False, f"Could not reach the Apple Search Ads API: {e}"+ return False, f"Could not reach the Apple Ads API: {e}"if status == 200:return True, Noneif status == 401:- return False, "Apple Search Ads rejected the access token. Check the client ID, team ID and key ID."+ return False, "Apple rejected the access token. Check the client ID, team ID and key ID."if status == 403:if schema_name is None:return True, None- return False, "These Apple Search Ads credentials do not have permission to read this table."- return False, f"Apple Search Ads returned an unexpected status code: {status}"+ return False, (+ "These Apple Ads credentials cannot read this table. Give the API client the API "+ "Account Read Only role for this ad account in Apple Ads."+ )+ return False, f"The Apple Ads API returned an unexpected status code: {status}"+++def _readable_ad_accounts(client: AppleSearchAdsClient, api_version: str) -> str:+ """Sentence naming the ad accounts these credentials can read, to append to an error.++ Best effort. The ACL lookup carries no context id, so it works before one is entered, but+ a failure here must not replace the more useful message asking for the id.+ """+ if api_version != APPLE_ADS_API_VERSION_V1:+ return ""++ config = endpoints_for_version(api_version)["acls"]+ request = page_request(config, api_version, RequestScope(), offset=0)+ try:+ payload = client.request_json(+ request.method, request.path, params=request.params, body=request.body, requires_context=False+ )+ except (requests.RequestException, ValueError):+ return ""++ named = []+ for account in flatten_acl_rows(page_rows(payload, config, api_version)):+ account_id = account.get("id")+ if account_id is None:+ continue+ name = account.get("name")+ named.append(f"{account_id} ({name})" if name else str(account_id))++ if not named:+ return " This API client cannot read any ad account yet. Check its role in Apple Ads."+ return " This API client can read: " + ", ".join(named) + "."def _today() -> date:@@ -294,24 +385,28 @@ def _report_start_date(db_incremental_field_last_value: Any,start_date: Optional[str],today: date,+ limits: ReportingLimits,) -> date:"""First reporting day to request.The pipeline already shifts the stored watermark back by the schema's lookback, so it isused verbatim. Without a watermark the run starts at the user's configured start date, or- a bounded default so a first sync can't walk the whole account history.+ a bounded default so a first sync can't walk the whole account history. Everything is+ floored at the version's oldest requestable day, including the watermark — Apple serves no+ DAILY data past it, so a source that fell further behind would otherwise fail every run+ instead of resuming at the oldest day it can still read."""+ floor = today - timedelta(days=limits.max_lookback_days)+if should_use_incremental_field:watermark = _to_date(db_incremental_field_last_value)if watermark is not None:- return watermark+ return max(watermark, floor)configured = _to_date(start_date) if start_date else Noneif configured is not None:- # Apple rejects a DAILY-granularity report whose startTime is more than 24 months in- # the past with a 400, so a configured date older than that is floored here.- return max(configured, today - timedelta(days=MAX_INITIAL_LOOKBACK_DAYS))- return today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS)+ return max(configured, floor)+ return max(today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS), floor)@frozen@@ -320,30 +415,43 @@ class ReportWindow:end: date-def _report_windows(start: date, end: date) -> list[ReportWindow]:+@frozen+class RequestScope:+ """One paginated request series: an optional campaign, and an optional reporting window."""++ campaign_id: Optional[int] = None+ window: Optional[ReportWindow] = None+++def _report_windows(start: date, end: date, min_window_days: int = 1) -> list[ReportWindow]:"""Split ``start..end`` (inclusive) into ascending windows of at most one week."""windows: list[ReportWindow] = []window_start = startwhile window_start <= end:window_end = min(window_start + timedelta(days=REPORT_WINDOW_DAYS - 1), end)+ if (window_end - window_start).days + 1 < min_window_days:+ # The Platform API rejects a DAILY range covering a single day, so a short trailing+ # window reaches back until it is long enough. Report tables merge on their primary+ # key, so re-reading a day already imported cannot duplicate rows.+ window_start = window_end - timedelta(days=min_window_days - 1)windows.append(ReportWindow(start=window_start, end=window_end))window_start = window_end + timedelta(days=1)return windows-def _report_body(window_start: date, window_end: date, offset: int) -> dict[str, Any]:+def _v5_report_body(window: ReportWindow, offset: int, page_size: int) -> dict[str, Any]:return {- "startTime": window_start.isoformat(),- "endTime": window_end.isoformat(),+ "startTime": window.start.isoformat(),+ "endTime": window.end.isoformat(),"granularity": "DAILY",# Report in the organization's own time zone so the `date` column matches what the- # Search Ads UI shows for the same campaign.+ # Apple Ads UI shows for the same campaign."timeZone": "ORTZ","selector": {"conditions": [],# No `orderBy`: Apple's sortable-field enum differs per report level and rejects# unknown fields, and rows are keyed by entity + date so merge order is irrelevant.- "pagination": {"offset": offset, "limit": PAGE_SIZE},+ "pagination": {"offset": offset, "limit": page_size},},"returnRecordsWithNoMetrics": False,"returnRowTotals": False,@@ -351,87 +459,184 @@ def _report_body(window_start: date, window_end: date, offset: int) -> dict[str,}-def _report_page_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:- reporting_data = payload.get("data") or {}- if not isinstance(reporting_data, dict):- return []- response = reporting_data.get("reportingDataResponse") or {}- if not isinstance(response, dict):- return []- rows = response.get("row") or []- return [row for row in rows if isinstance(row, dict)]+def _platform_report_body(+ window: ReportWindow, campaign_id: Optional[int], offset: int, page_size: int+) -> dict[str, Any]:+ body: dict[str, Any] = {+ "pagination": {"offset": offset, "pageSize": page_size},+ "timeRange": {+ "start": window.start.isoformat(),+ "end": window.end.isoformat(),+ # Report in the ad account's own time zone so the `date` column matches what the+ # Apple Ads UI shows for the same campaign.+ "timeZone": "ORTZ",+ "granularity": "DAILY",+ },+ }+ if campaign_id is not None:+ body["filters"] = [_campaign_filter(campaign_id, as_string=True)]+ # No `groupBy`: it splits each entity's metrics across dimension values, and these tables+ # carry one row per entity per day.+ return body+++def _campaign_filter(campaign_id: int, *, as_string: bool) -> dict[str, Any]:+ # Apple documents the report filter's value as an array of strings, and the entity query+ # filter's as the field's own integer type.+ value: Any = [str(campaign_id)] if as_string else campaign_id+ return {"field": "campaignId", "operator": "EQUALS", "value": value}+++def _platform_query_body(scope: RequestScope, offset: int, page_size: int) -> dict[str, Any]:+ body: dict[str, Any] = {"pagination": {"offset": offset, "pageSize": page_size}}+ if scope.campaign_id is not None:+ body["filters"] = [_campaign_filter(scope.campaign_id, as_string=False)]+ return body+++@frozen+class PageRequest:+ """HTTP method, path, query params and JSON body for one page of a request."""+ method: str+ path: str+ params: Optional[dict[str, Any]] = None+ body: Optional[dict[str, Any]] = None-def flatten_report_rows(payload: dict[str, Any], campaign_id: Optional[int]) -> list[dict[str, Any]]:- """Explode one report page into a row per entity per day.- Apple returns one row per entity carrying a `metadata` block plus a `granularity` array of- daily metric buckets; the warehouse wants those flattened so `date` is a real column.+def page_request(+ config: AppleSearchAdsEndpointConfig,+ api_version: str,+ scope: RequestScope,+ offset: int,+ page_size: int = PAGE_SIZE,+) -> PageRequest:+ """HTTP method, path, query params and JSON body for one page of ``config``."""+ path = config.path+ if scope.campaign_id is not None and "{campaign_id}" in path:+ path = path.format(campaign_id=scope.campaign_id)++ if config.kind == "report":+ if scope.window is None:+ raise ValueError(f"Apple Ads: a {config.name} request needs a reporting window")+ if api_version == APPLE_ADS_API_VERSION_V1:+ body = _platform_report_body(scope.window, scope.campaign_id, offset, page_size)+ else:+ body = _v5_report_body(scope.window, offset, page_size)+ return PageRequest(method="POST", path=path, body=body)+ if config.kind == "query":+ return PageRequest(method="POST", path=path, body=_platform_query_body(scope, offset, page_size))+ if config.kind == "find":+ return PageRequest(+ method="POST",+ path=path,+ body={"conditions": [], "pagination": {"offset": offset, "limit": page_size}},+ )+ if config.kind == "query_page":+ return PageRequest(method="GET", path=path, params={"limit": page_size, "offset": offset})+ return PageRequest(method="GET", path=path)+++def page_rows(payload: dict[str, Any], config: AppleSearchAdsEndpointConfig, api_version: str) -> list[dict[str, Any]]:+ """Entity rows on one page — what pagination counts, before any flattening."""+ if api_version == APPLE_ADS_API_VERSION_V1:+ result = payload.get("result")+ if config.kind == "report":+ rows = result.get("rows") if isinstance(result, dict) else None+ elif config.kind == "acls":+ rows = result.get("acls") if isinstance(result, dict) else None+ else:+ rows = result+ elif config.kind == "report":+ data = payload.get("data")+ response = data.get("reportingDataResponse") if isinstance(data, dict) else None+ rows = response.get("row") if isinstance(response, dict) else None+ else:+ rows = payload.get("data")++ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []+++def flatten_report_rows(+ rows: list[dict[str, Any]],+ *,+ metrics_key: str,+ entity_id_field: Optional[str] = None,+ campaign_id: Optional[int] = None,+) -> list[dict[str, Any]]:+ """Explode report rows into a row per entity per day.++ Apple returns one row per entity carrying a `metadata` block plus an array of daily metric+ buckets; the warehouse wants those flattened so `date` is a real column."""flattened: list[dict[str, Any]] = []- for row in _report_page_rows(payload):+ for row in rows:metadata = dict(row.get("metadata") or {})+ if entity_id_field is not None:+ # The Platform API names every report level's own entity `id`, where v5 named it+ # `campaignId`/`adGroupId`/`keywordId`. Project it back so the table keeps the+ # primary key it had, and so the column does not arrive twice under two names.+ entity_id = metadata.pop("id", None)+ if entity_id is not None:+ metadata.setdefault(entity_id_field, entity_id)if campaign_id is not None:- # Ad-group and keyword reports are requested per campaign and their metadata does- # not repeat the campaign id the primary key needs.+ # v5's ad-group and keyword report metadata does not repeat the campaign id the+ # primary key needs. The Platform API does supply it, so this only fills a gap.metadata.setdefault("campaignId", campaign_id)- for daily in row.get("granularity") or []:+ for daily in row.get(metrics_key) or []:if isinstance(daily, dict):flattened.append({**metadata, **daily})return flattened-def _entity_page(- client: AppleSearchAdsClient, config: AppleSearchAdsEndpointConfig, offset: int-) -> list[dict[str, Any]]:- if config.kind == "find":- payload = client.request_json(- "POST",- config.path,- body={"conditions": [], "pagination": {"offset": offset, "limit": PAGE_SIZE}},- requires_org_context=config.requires_org_context,- )- elif config.kind == "query_page":- payload = client.request_json(- "GET",- config.path,- params={"limit": PAGE_SIZE, "offset": offset},- requires_org_context=config.requires_org_context,- )- else:- payload = client.request_json("GET", config.path, requires_org_context=config.requires_org_context)+def flatten_acl_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """One row per ad account the credentials can read.- rows = payload.get("data")- return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []+ The Platform API nests the account under `adAccount` and lists the caller's roles beside+ it. Flattening keeps `orgId` a column while `id` — the value the connect form asks for —+ identifies the row.+ """+ flattened: list[dict[str, Any]] = []+ for entry in rows:+ account = entry.get("adAccount")+ if isinstance(account, dict):+ flattened.append({**account, "roles": entry.get("roles") or []})+ return flattened-def _iter_entity_rows(- client: AppleSearchAdsClient,+def _project_rows(+ rows: list[dict[str, Any]],config: AppleSearchAdsEndpointConfig,- resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],- resume: Optional[AppleSearchAdsResumeConfig],-) -> Iterator[list[dict[str, Any]]]:- offset = resume.offset if resume is not None else 0-- while True:- rows = _entity_page(client, config, offset)- if rows:- yield rows-- if config.kind == "single" or len(rows) < PAGE_SIZE:- break-- offset += len(rows)- resumable_source_manager.save_state(AppleSearchAdsResumeConfig(offset=offset))+ api_version: str,+ campaign_id: Optional[int],+) -> list[dict[str, Any]]:+ if config.kind == "report":+ return flatten_report_rows(+ rows,+ metrics_key=_REPORT_METRICS_KEY[api_version],+ entity_id_field=config.entity_id_field,+ campaign_id=campaign_id,+ )+ if config.kind == "acls":+ return flatten_acl_rows(rows)+ return rows-def _list_campaign_ids(client: AppleSearchAdsClient) -> list[int]:- """Campaign ids to fan the per-campaign report endpoints out over, in a stable order."""- campaigns_config = APPLE_SEARCH_ADS_ENDPOINTS["campaigns"]+def _list_campaign_ids(client: AppleSearchAdsClient, api_version: str) -> list[int]:+ """Campaign ids to scope the per-campaign endpoints by, in a stable order."""+ config = endpoints_for_version(api_version)["campaigns"]ids: set[int] = set()offset = 0while True:- rows = _entity_page(client, campaigns_config, offset)+ request = page_request(config, api_version, RequestScope(), offset)+ payload = client.request_json(+ request.method,+ request.path,+ params=request.params,+ body=request.body,+ requires_context=config.requires_context,+ )+ rows = page_rows(payload, config, api_version)for row in rows:campaign_id = row.get("id")if campaign_id is not None:@@ -442,104 +647,96 @@ def _list_campaign_ids(client: AppleSearchAdsClient) -> list[int]:return sorted(ids)-ReportTask = tuple[date, date, Optional[int]]-+def _scopes(campaign_ids: list[Optional[int]], windows: Optional[list[ReportWindow]]) -> Iterator[RequestScope]:+ """Every paginated request series this run must make, lazily.-def _report_tasks(start: date, end: date, campaign_ids: list[Optional[int]]) -> Iterator[ReportTask]:- """Every (window, campaign) report request this run must make, lazily.-- Yielded rather than listed so a large window range never materialises as millions of- tuples up front.+ ``windows is None`` for the entity tables, which are not date-bounded. Yielded rather than+ listed so a large window range never materialises as millions of tuples up front."""- for window in _report_windows(start, end):+ if windows is None:+ for campaign_id in campaign_ids:+ yield RequestScope(campaign_id=campaign_id)+ return+ for window in windows:for campaign_id in campaign_ids:- yield window.start, window.end, campaign_id+ yield RequestScope(campaign_id=campaign_id, window=window)+++def _scope_key(scope: RequestScope) -> tuple[Optional[str], Optional[int]]:+ return (scope.window.start.isoformat() if scope.window is not None else None, scope.campaign_id)+++def _checkpoint(scope: RequestScope, offset: int) -> AppleSearchAdsResumeConfig:+ window_start, campaign_id = _scope_key(scope)+ return AppleSearchAdsResumeConfig(offset=offset, window_start=window_start, campaign_id=campaign_id)def _advance_to_resume(- make_tasks: Callable[[], Iterator[ReportTask]],+ make_scopes: Callable[[], Iterator[RequestScope]],resume: Optional[AppleSearchAdsResumeConfig],request_logger: FilteringBoundLogger,-) -> tuple[Iterator[ReportTask], int]:- """Fast-forward the lazy task stream to a saved checkpoint, matched by value not position.+) -> tuple[Iterator[RequestScope], int]:+ """Fast-forward the lazy scope stream to a saved checkpoint, matched by value not position.- A checkpoint from a different window range (e.g. the start date changed) is never found, so- the run restarts from the first task with a fresh stream.+ A checkpoint from a different window range or campaign list (e.g. the start date changed,+ or a campaign was deleted) is never found, so the run restarts from the first scope with a+ fresh stream."""- if resume is None or not resume.window_start:- return make_tasks(), 0+ if resume is None:+ return make_scopes(), 0key = (resume.window_start, resume.campaign_id)- tasks = make_tasks()- for task in tasks:- window_start, _window_end, campaign_id = task- if (window_start.isoformat(), campaign_id) == key:- return itertools.chain([task], tasks), resume.offset-- request_logger.debug(- f"Apple Search Ads: saved checkpoint {key} is not in this run's window range, starting from the beginning"- )- return make_tasks(), 0+ scopes = make_scopes()+ for scope in scopes:+ if _scope_key(scope) == key:+ return itertools.chain([scope], scopes), resume.offset+ request_logger.debug(f"Apple Ads: saved checkpoint {key} is not in this run's scopes, starting from the beginning")+ return make_scopes(), 0-def _iter_report_rows(++def _iter_rows(client: AppleSearchAdsClient,config: AppleSearchAdsEndpointConfig,+ api_version: str,resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],resume: Optional[AppleSearchAdsResumeConfig],request_logger: FilteringBoundLogger,*,- should_use_incremental_field: bool,- db_incremental_field_last_value: Any,- start_date: Optional[str],+ campaign_ids: list[Optional[int]],+ windows: Optional[list[ReportWindow]],) -> Iterator[list[dict[str, Any]]]:- today = _today()- start = _report_start_date(should_use_incremental_field, db_incremental_field_last_value, start_date, today)- campaign_ids: list[Optional[int]] = [None]- if config.fan_out_over_campaigns:- campaign_ids = list(_list_campaign_ids(client))+ scopes, resume_offset = _advance_to_resume(lambda: _scopes(campaign_ids, windows), resume, request_logger)- tasks, start_offset = _advance_to_resume(lambda: _report_tasks(start, today, campaign_ids), resume, request_logger)-- current = next(tasks, None)- resume_offset = start_offset+ current = next(scopes, None)while current is not None:- window_start, window_end, campaign_id = current- # Peek at the next task so a completed window can checkpoint where the run should pick up.- upcoming = next(tasks, None)- path = config.path.format(campaign_id=campaign_id) if campaign_id is not None else config.path+ # Peek at the next scope so a completed one can checkpoint where the run picks up.+ upcoming = next(scopes, None)offset = resume_offsetresume_offset = 0while True:+ request = page_request(config, api_version, current, offset)payload = client.request_json(- "POST",- path,- body=_report_body(window_start, window_end, offset),- requires_org_context=config.requires_org_context,+ request.method,+ request.path,+ params=request.params,+ body=request.body,+ requires_context=config.requires_context,)- rows = flatten_report_rows(payload, campaign_id)+ page = page_rows(payload, config, api_version)+ rows = _project_rows(page, config, api_version, current.campaign_id)if rows:yield rows- page_size = len(_report_page_rows(payload))- if page_size < PAGE_SIZE:+ if config.kind in _UNPAGINATED_KINDS or len(page) < PAGE_SIZE:break- offset += page_size- resumable_source_manager.save_state(- AppleSearchAdsResumeConfig(- offset=offset, window_start=window_start.isoformat(), campaign_id=campaign_id- )- )+ offset += len(page)+ resumable_source_manager.save_state(_checkpoint(current, offset))if upcoming is not None:- next_window_start, _next_window_end, next_campaign_id = upcoming- resumable_source_manager.save_state(- AppleSearchAdsResumeConfig(- offset=0, window_start=next_window_start.isoformat(), campaign_id=next_campaign_id- )- )+ resumable_source_manager.save_state(_checkpoint(upcoming, 0))current = upcoming@@ -553,23 +750,35 @@ def get_rows(db_incremental_field_last_value: Any = None,start_date: Optional[str] = None,) -> Iterator[list[dict[str, Any]]]:- config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]+ config = endpoints_for_version(api_version)[endpoint]client = AppleSearchAdsClient(credentials, api_version, request_logger)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ # Listed once, up front: the scope stream is lazy and rebuilt on a missed checkpoint, so+ # deriving the campaign list inside it would re-request the whole campaign list.+ campaign_ids: list[Optional[int]] = [None]+ if config.fan_out_over_campaigns:+ campaign_ids = list(_list_campaign_ids(client, api_version))++ windows: Optional[list[ReportWindow]] = Noneif config.kind == "report":- yield from _iter_report_rows(- client,- config,- resumable_source_manager,- resume,- request_logger,- should_use_incremental_field=should_use_incremental_field,- db_incremental_field_last_value=db_incremental_field_last_value,- start_date=start_date,+ limits = reporting_limits_for_version(api_version)+ today = _today()+ start = _report_start_date(+ should_use_incremental_field, db_incremental_field_last_value, start_date, today, limits)- else:- yield from _iter_entity_rows(client, config, resumable_source_manager, resume)+ windows = _report_windows(start, today, limits.min_window_days)++ yield from _iter_rows(+ client,+ config,+ api_version,+ resumable_source_manager,+ resume,+ request_logger,+ campaign_ids=campaign_ids,+ windows=windows,+ )# The stream ran to completion; leaving the last checkpoint would make a later attempt# resume mid-range instead of restarting cleanly.@@ -586,7 +795,7 @@ def apple_search_ads_source(db_incremental_field_last_value: Any = None,start_date: Optional[str] = None,) -> SourceResponse:- config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]+ config = endpoints_for_version(api_version)[endpoint]return SourceResponse(name=endpoint,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.pyindex 77e1b4b22940..f55d668cab0d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py@@ -1,9 +1,11 @@-"""Canonical, documentation-sourced descriptions for Apple Search Ads endpoints and columns.+"""Canonical, documentation-sourced descriptions for Apple Ads endpoints and columns.-Sourced from Apple's Search Ads Campaign Management API v5 reference-(https://developer.apple.com/documentation/apple_search_ads). Keyed by the endpoint names in-`settings.py` `APPLE_SEARCH_ADS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced-table. Columns absent here fall back to LLM enrichment.+Sourced from Apple's Ads Platform API reference+(https://developer.apple.com/documentation/apple-ads-platform-api) and the Campaign Management+API 5 reference it supersedes (https://developer.apple.com/documentation/apple_search_ads).+Keyed by the endpoint names in `settings.py`, which match the `ExternalDataSchema.name` of a+synced table. Both versions' column names are described here, because a source pinned to either+one syncs into the same table; columns absent here fall back to LLM enrichment."""from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -26,14 +28,29 @@ _REPORT_METRIC_COLUMNS: dict[str, str] = {"avgCPA": "Average cost per acquisition, in the organization's currency.","avgCPT": "Average cost per tap, in the organization's currency.","avgCPM": "Average cost per thousand impressions, in the organization's currency.",+ # The Platform API renamed these two and split installs by attribution type.+ "cpt": "Average cost per tap, as an amount plus currency code.",+ "cpm": "Average cost per thousand impressions, as an amount plus currency code.",+ "tapInstalls": "Conversions attributed to a tap on the ad.",+ "viewInstalls": "Conversions attributed to an impression the user did not tap.",+ "totalInstalls": "Conversions attributed to the ad, combining tap-through and view-through.",+ "tapNewDownloads": "Tap-through conversions from users who had not downloaded the app before.",+ "tapRedownloads": "Tap-through conversions from users who had downloaded the app before.",+ "viewNewDownloads": "View-through conversions from users who had not downloaded the app before.",+ "viewRedownloads": "View-through conversions from users who had downloaded the app before.",+ "totalNewDownloads": "Conversions from users who had not downloaded the app before.",+ "totalRedownloads": "Conversions from users who had downloaded the app before.",}CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"acls": {- "description": "Organizations the API credentials can read, with the role granted to them.",- "docs_url": "https://developer.apple.com/documentation/apple_search_ads/get_user_acl",+ "description": "Ad accounts the API credentials can read, with the roles granted on each.",+ "docs_url": "https://developer.apple.com/documentation/apple-ads-platform-api/get-user-acls","columns": {- "orgId": "Identifier of the organization, used as the `orgId` in the API context header.",+ "id": "Identifier of the ad account, used as the `adAccountId` in the API context header.",+ "name": "Display name of the ad account.",+ "roles": "Roles the API client holds on the ad account, such as API Account Read Only.",+ "orgId": "Identifier of the organization the ad account belongs to.","orgName": "Display name of the organization.","currency": "Three-letter ISO currency code the organization is billed in.","timeZone": "Time zone the organization's reporting is expressed in.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.pyindex 04ad5cb71994..cd3b3e632568 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py@@ -1,19 +1,29 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Apple's Campaign Management API 5, which Apple sunsets on 2027-01-26.+APPLE_SEARCH_ADS_API_VERSION_V5 = "v5"+# Apple Ads Platform API 1.0, which supersedes it and also covers Apple Maps advertising.+APPLE_ADS_API_VERSION_V1 = "v1"+# How each endpoint is read:# single — one GET, whole result set in `data` (no pagination params).# query_page — GET with `limit`/`offset` query params.# find — POST whose body *is* a Selector (`conditions`/`pagination`).-# report — POST a date-bounded report request; rows arrive nested under-# `data.reportingDataResponse.row`, one per entity with a daily-# `granularity` array.-EndpointKind = Literal["single", "query_page", "find", "report"]+# report — POST a date-bounded report request; rows arrive one per entity with a daily+# metric array to flatten.+# acls — one GET, ad accounts nested under `result.acls`.+# query — POST a `QueryRequest` (`filters`/`sorting`/`pagination`), rows in `result`.+# `single`, `query_page` and `find` are v5 only; `acls` and `query` are v1 only.+EndpointKind = Literal["single", "query_page", "find", "report", "acls", "query"]-# Apple caps `limit` (entity endpoints) and `selector.pagination.limit` (find/report) at 1000.+# v5 caps `limit` at 1000; the Platform API caps `pageSize` at 5000. One page size stays under+# both.PAGE_SIZE = 1000# Reporting requests are bounded to a short window so that the per-batch incremental@@ -26,42 +36,71 @@ REPORT_WINDOW_DAYS = 7# incremental run re-reads a trailing week rather than trusting the frozen watermark.REPORT_LOOKBACK_SECONDS = REPORT_WINDOW_DAYS * 24 * 60 * 60-# How far back the first sync of a report table reaches when the user gives no start date.+# How far back the first sync of a report table reaches when the user gives no start date,+# before the version's own ceiling clamps it.DEFAULT_INITIAL_LOOKBACK_DAYS = 365-# The earliest a configured start date may reach. Apple's Reporting API rejects a DAILY--# granularity report (the only granularity this source requests) whose startTime is more than-# 24 months in the past with a 400 — treating a month as 30 days keeps this clamp safely inside-# that limit despite calendar-month variation.-MAX_INITIAL_LOOKBACK_DAYS = 24 * 30++# Apple evaluates a report's date range in the ad account's own reporting time zone, while this+# source counts days in UTC. An account ahead of UTC can already be on the next day, so a floor+# that landed exactly on Apple's boundary would be one day too old for part of every UTC day.+_REPORT_TIME_ZONE_SKEW_DAYS = 2+++@frozen+class ReportingLimits:+ """Bounds Apple enforces on a DAILY-granularity report request, per API version."""++ # Oldest day a request may start at, counted back from today in UTC.+ max_lookback_days: int+ # Shortest range a request may cover. The Platform API rejects a DAILY range of a single+ # day, which v5 accepted.+ min_window_days: int+++REPORTING_LIMITS: dict[str, ReportingLimits] = {+ # v5 rejects a DAILY range starting more than 24 months back. Treating a month as 30 days+ # keeps the clamp inside that limit despite calendar-month variation.+ APPLE_SEARCH_ADS_API_VERSION_V5: ReportingLimits(+ max_lookback_days=24 * 30 - _REPORT_TIME_ZONE_SKEW_DAYS, min_window_days=1+ ),+ # The Platform API rejects a DAILY range starting more than 90 days back.+ APPLE_ADS_API_VERSION_V1: ReportingLimits(max_lookback_days=90 - _REPORT_TIME_ZONE_SKEW_DAYS, min_window_days=2),+}@dataclass(frozen=True)class AppleSearchAdsEndpointConfig:name: str- # Path under `https://api.searchads.apple.com/api/{version}`.+ # Path under the version's base URL.path: strkind: EndpointKindprimary_keys: list[str]- # Every Campaign Management endpoint except `/acls` is scoped to one organization via- # the `X-AP-Context: orgId=...` header.- requires_org_context: bool = True- # Apple only exposes ad-group/keyword level reports per campaign, so those tables are- # built by fanning out over the org's campaign ids.+ # Every endpoint except the ACL lookup is scoped to one organization (v5) or one ad+ # account (Platform API) through the `X-AP-Context` header.+ requires_context: bool = True+ # Endpoints Apple only serves per campaign, built by fanning out over the account's+ # campaign ids. v5 takes the campaign in the path; the Platform API takes it as a filter,+ # and additionally requires one on every report and on the keyword query.fan_out_over_campaigns: bool = False+ # Column the Platform API's `metadata.id` is projected onto, so a report table keeps the+ # primary key it had under v5.+ entity_id_field: Optional[str] = Noneincremental_fields: list[IncrementalField] = field(default_factory=list)# Reporting date — set by Apple, never restated to a different day, so it is a stable# partition key.partition_key: Optional[str] = None+_REPORT_INCREMENTAL_FIELDS = [incremental_field("date", IncrementalFieldType.Date)]+APPLE_SEARCH_ADS_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {"acls": AppleSearchAdsEndpointConfig(name="acls",path="/acls",kind="single",primary_keys=["orgId"],- requires_org_context=False,+ requires_context=False,),"campaigns": AppleSearchAdsEndpointConfig(name="campaigns",@@ -87,7 +126,7 @@ APPLE_SEARCH_ADS_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {kind="report",primary_keys=["campaignId", "date"],partition_key="date",- incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,),"ad_group_report": AppleSearchAdsEndpointConfig(name="ad_group_report",@@ -96,7 +135,7 @@ APPLE_SEARCH_ADS_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {fan_out_over_campaigns=True,primary_keys=["campaignId", "adGroupId", "date"],partition_key="date",- incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,),"keyword_report": AppleSearchAdsEndpointConfig(name="keyword_report",@@ -107,10 +146,107 @@ APPLE_SEARCH_ADS_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {# out from plus the keyword and date identify a row table-wide.primary_keys=["campaignId", "keywordId", "date"],partition_key="date",- incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,+ ),+}++# The Platform API serves the same seven tables, so a repinned source keeps its table names,+# primary keys and incremental fields. It reads them differently: every collection moved to a+# `POST .../query` body, the report paths carry the entity level instead of the campaign id,+# and each report row names its own entity `id` rather than `campaignId`/`adGroupId`/+# `keywordId`.+APPLE_ADS_PLATFORM_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {+ "acls": AppleSearchAdsEndpointConfig(+ name="acls",+ path="/acls",+ kind="acls",+ # One row per ad account rather than per organization: an access token binds to a+ # single org, so every row repeats the same `orgId` and only `id` identifies one.+ primary_keys=["id"],+ requires_context=False,+ ),+ "campaigns": AppleSearchAdsEndpointConfig(+ name="campaigns",+ path="/campaigns/query",+ kind="query",+ primary_keys=["id"],+ ),+ "ad_groups": AppleSearchAdsEndpointConfig(+ name="ad_groups",+ path="/adgroups/query",+ kind="query",+ primary_keys=["id"],+ ),+ "keywords": AppleSearchAdsEndpointConfig(+ name="keywords",+ path="/keywords/query",+ kind="query",+ # Apple rejects a keyword query that scopes neither a campaign nor an ad group, so+ # this table is built per campaign even though it is not a report.+ fan_out_over_campaigns=True,+ primary_keys=["id"],+ ),+ "campaign_report": AppleSearchAdsEndpointConfig(+ name="campaign_report",+ path="/reports/apps/campaigns/query",+ kind="report",+ # Apple requires a `campaignId` filter on every apps report, including this one, which+ # v5 served for the whole organization in a single request.+ fan_out_over_campaigns=True,+ entity_id_field="campaignId",+ primary_keys=["campaignId", "date"],+ partition_key="date",+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,+ ),+ "ad_group_report": AppleSearchAdsEndpointConfig(+ name="ad_group_report",+ path="/reports/apps/adgroups/query",+ kind="report",+ fan_out_over_campaigns=True,+ entity_id_field="adGroupId",+ primary_keys=["campaignId", "adGroupId", "date"],+ partition_key="date",+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,+ ),+ "keyword_report": AppleSearchAdsEndpointConfig(+ name="keyword_report",+ path="/reports/apps/keywords/query",+ kind="report",+ fan_out_over_campaigns=True,+ entity_id_field="keywordId",+ primary_keys=["campaignId", "keywordId", "date"],+ partition_key="date",+ incremental_fields=_REPORT_INCREMENTAL_FIELDS,),}+ENDPOINTS_BY_VERSION: dict[str, dict[str, AppleSearchAdsEndpointConfig]] = {+ APPLE_SEARCH_ADS_API_VERSION_V5: APPLE_SEARCH_ADS_ENDPOINTS,+ APPLE_ADS_API_VERSION_V1: APPLE_ADS_PLATFORM_ENDPOINTS,+}+++def endpoints_for_version(api_version: str) -> dict[str, AppleSearchAdsEndpointConfig]:+ """Endpoint catalog for a resolved version pin.++ Raising beats falling back: a version this source declares but has no catalog for would+ otherwise sync silently against the wrong wire.+ """+ try:+ return ENDPOINTS_BY_VERSION[api_version]+ except KeyError:+ raise ValueError(f"Apple Ads: no endpoint catalog for API version {api_version!r}")+++def reporting_limits_for_version(api_version: str) -> ReportingLimits:+ try:+ return REPORTING_LIMITS[api_version]+ except KeyError:+ raise ValueError(f"Apple Ads: no reporting limits for API version {api_version!r}")+++# The table set is identical across versions by design, so discovery does not depend on the+# pin and a repinned source keeps every table it had.ENDPOINTS = tuple(APPLE_SEARCH_ADS_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {@@ -120,11 +256,11 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {REPORT_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if config.kind == "report")ENDPOINT_DESCRIPTIONS: dict[str, str] = {- "acls": "Organizations the API credentials can read, with currency, time zone and role names.",- "campaigns": "Campaigns in the organization, with budget, serving status and countries or regions.",- "ad_groups": "Ad groups across every campaign in the organization, with default bid and targeting.",- "keywords": "Targeting keywords across every ad group in the organization, with match type and bid.",+ "acls": "Ad accounts the API credentials can read, with the organization and role names.",+ "campaigns": "Campaigns in the account, with budget, serving status and countries or regions.",+ "ad_groups": "Ad groups across every campaign in the account, with default bid and targeting.",+ "keywords": "Targeting keywords across every ad group in the account, with match type and bid.","campaign_report": "Daily campaign performance: impressions, taps, installs, spend and derived rates.",- "ad_group_report": "Daily ad group performance for every campaign in the organization.",- "keyword_report": "Daily keyword performance for every campaign in the organization.",+ "ad_group_report": "Daily ad group performance for every campaign in the account.",+ "keyword_report": "Daily keyword performance for every campaign in the account.",}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.pyindex 9a212d2ca74a..ecd2c78210b8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py@@ -1,3 +1,4 @@+from datetime import datefrom typing import Optional, castfrom posthog.schema import (@@ -16,14 +17,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apple_searvalidate_credentials as validate_apple_search_ads_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (- APPLE_SEARCH_ADS_ENDPOINTS,+ APPLE_ADS_API_VERSION_V1,+ APPLE_SEARCH_ADS_API_VERSION_V5,ENDPOINT_DESCRIPTIONS,ENDPOINTS,INCREMENTAL_FIELDS,REPORT_ENDPOINTS,REPORT_LOOKBACK_SECONDS,+ endpoints_for_version,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ FieldType,+ ResumableSource,+ VersionDeprecation,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -44,21 +51,35 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeclass AppleSearchAdsSource(ResumableSource[AppleSearchAdsSourceConfig, AppleSearchAdsResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docs- supported_versions = ("v5",)- default_version = "v5"- api_docs_url = "https://developer.apple.com/documentation/apple_search_ads"+ supported_versions = (APPLE_SEARCH_ADS_API_VERSION_V5, APPLE_ADS_API_VERSION_V1)+ default_version = APPLE_ADS_API_VERSION_V1+ # Apple sunsets the Campaign Management API 5 on 2027-01-26, after which its endpoints stop+ # serving. A pinned source cannot be repinned for it: the Platform API scopes requests to+ # an ad account id, which is not derivable from the stored organization id.+ deprecated_versions = (VersionDeprecation(version=APPLE_SEARCH_ADS_API_VERSION_V5, sunset_at=date(2027, 1, 26)),)+ api_docs_url = "https://developer.apple.com/documentation/apple-ads-platform-api"@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPLESEARCHADS+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored private key is sent against whichever ad account (Platform API) or+ # organization (v5) is configured, so changing either retargets the saved credential at a+ # different Apple account — force secret re-entry on a change to either.+ return ["ad_account_id", "org_id"]+def get_non_retryable_errors(self) -> dict[str, str | None]:return {"400 Client Error: Bad Request for url: https://appleid.apple.com/auth/oauth2/token": "Apple rejected the signed client secret. Check your client ID, team ID, key ID and private key.","401 Client Error: Unauthorized for url: https://appleid.apple.com/auth/oauth2/token": "Apple rejected the signed client secret. Check your client ID, team ID, key ID and private key.",- "401 Client Error: Unauthorized for url: https://api.searchads.apple.com": "Apple Search Ads rejected the access token. Your API key may have been revoked — generate a new one and reconnect.",+ "401 Client Error: Unauthorized for url: https://api.ads.apple.com": "Apple rejected the access token. Your API client may have been removed. Create a new one in Apple Ads and reconnect this source.",+ "403 Client Error: Forbidden for url: https://api.ads.apple.com": "Apple denied access to this ad account. Check that the API client has the API Account Read Only role for the ad account ID you entered.",+ "404 Client Error: Not Found for url: https://api.ads.apple.com": "Apple could not find this ad account. Check the ad account ID, which you can read from `adAccount.id` in Apple's Get User ACL endpoint.",+ "401 Client Error: Unauthorized for url: https://api.searchads.apple.com": "Apple Search Ads rejected the access token. Your API key may have been revoked. Generate a new one and reconnect this source.","403 Client Error: Forbidden for url: https://api.searchads.apple.com": "Apple Search Ads denied access to this organization. Check that the API user has at least read access to the organization ID you entered.",- "Could not sign the Apple Search Ads client secret": "The private key isn't a valid unencrypted EC (P-256) PEM. Paste the key you generated for your Search Ads API key and reconnect.",+ "Could not sign the Apple Ads client secret": "The private key isn't a valid unencrypted EC (P-256) PEM. Paste the key you generated for your Apple Ads API client and reconnect.",}@property@@ -66,23 +87,39 @@ class AppleSearchAdsSource(ResumableSource[AppleSearchAdsSourceConfig, AppleSearreturn SourceConfig(name=SchemaExternalDataSourceType.APPLE_SEARCH_ADS,category=DataWarehouseSourceCategory.ADVERTISING,- label="Apple Search Ads",- caption="""Connect your Apple Search Ads account to pull campaigns, ad groups, keywords and daily performance into the PostHog Data warehouse.+ label="Apple Ads",+ caption="""Connect your Apple Ads account, formerly Apple Search Ads, to pull campaigns, ad groups, keywords and daily performance into the PostHog Data warehouse.++Apple does not generate an API key for you. An account admin creates an API client, and you supply your own key pair:++1. Generate an EC P-256 key pair. On macOS or Linux, run `openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem` and then `openssl ec -in private-key.pem -pubout -out public-key.pem`.+2. In [Apple Ads](https://ads.apple.com), open **Account settings > API** and add an API client. Paste the contents of `public-key.pem` into the public key field and save it.+3. Apple then shows the client ID, team ID and key ID. Enter those below, along with the contents of `private-key.pem`.+4. Read your ad account ID from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`, under `adAccount.id`. This is not the same value as your organization ID.++PostHog stores the private key encrypted and uses it to sign a short-lived token on every sync. The token itself is never stored.-In the Search Ads UI, create an API user with at least **Read only** access, generate an API key, and keep the private key it gives you. Then enter the organization ID, client ID, team ID and key ID from the API key page, plus the private key itself. PostHog signs a short-lived token with the key on every sync, so no long-lived secret is stored.""",+Reporting tables use daily granularity, which Apple serves for the last 90 days only.""",+ permissionsCaption="""Give the API client the **API Account Read Only** role, which grants read access to the campaign data these tables are built from. The **API Account Manager** role also works if you already use it.""",iconPath="/static/services/apple_search_ads.png",docsUrl="https://posthog.com/docs/cdp/sources/apple-search-ads",releaseStatus=ReleaseStatus.ALPHA,- keywords=["asa", "app store ads", "search ads"],+ # "Apple Search Ads" is the former product name, kept so the catalog still finds+ # this source under what Apple used to call it.+ keywords=["apple search ads", "asa", "app store ads", "search ads", "apple maps ads"],fields=cast(list[FieldType],[SourceFieldInputConfig(- name="org_id",- label="Organization ID",+ name="ad_account_id",+ label="Ad account ID",type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="123456",+ # Optional at the form level because a source pinned to Apple's older+ # API needs the organization ID below instead. `validate_credentials`+ # requires whichever one the source's API version uses.+ required=False,+ placeholder="123456789",+ caption="Read this from `adAccount.id` in the response from Apple's Get User ACL endpoint, `GET https://api.ads.apple.com/v1/acls`.",secret=False,),SourceFieldInputConfig(@@ -91,6 +128,7 @@ In the Search Ads UI, create an API user with at least **Read only** access, gentype=SourceFieldInputConfigType.TEXT,required=True,placeholder="SEARCHADS.27478e17-...",+ caption="Apple shows this after you save the public key for your API client.",secret=False,),SourceFieldInputConfig(@@ -98,7 +136,8 @@ In the Search Ads UI, create an API user with at least **Read only** access, genlabel="Team ID",type=SourceFieldInputConfigType.TEXT,required=True,- placeholder="SEARCHADS.27478e17-...",+ placeholder="SEARCHADS.6f0a1b2c-...",+ caption="Apple shows this next to the client ID. It often matches the client ID.",secret=False,),SourceFieldInputConfig(@@ -107,6 +146,7 @@ In the Search Ads UI, create an API user with at least **Read only** access, gentype=SourceFieldInputConfigType.TEXT,required=True,placeholder="a1b2c3d4-...",+ caption="Apple shows this next to the client ID.",secret=False,),SourceFieldInputConfig(@@ -115,6 +155,7 @@ In the Search Ads UI, create an API user with at least **Read only** access, gentype=SourceFieldInputConfigType.TEXTAREA,required=True,placeholder="-----BEGIN EC PRIVATE KEY-----",+ caption="The unencrypted EC P-256 private key matching the public key you uploaded to Apple.",secret=True,),SourceFieldInputConfig(@@ -122,7 +163,17 @@ In the Search Ads UI, create an API user with at least **Read only** access, genlabel="Report start date",type=SourceFieldInputConfigType.TEXT,required=False,- placeholder="2024-01-01",+ placeholder="2026-06-01",+ caption="Earliest day to pull reporting for. Apple serves daily reporting for the last 90 days, so anything older is read from that day instead.",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="org_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="123456",+ caption="Only for sources still on Apple's Campaign Management API 5, which Apple stops serving on 26 January 2027. Leave this empty and enter an ad account ID instead.",secret=False,),],@@ -145,6 +196,7 @@ In the Search Ads UI, create an API user with at least **Read only** access, genforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:+ endpoints = endpoints_for_version(self.resolve_api_version(api_version))schemas = build_endpoint_schemas(ENDPOINTS,INCREMENTAL_FIELDS,@@ -159,7 +211,7 @@ In the Search Ads UI, create an API user with at least **Read only** access, gen# Apple keeps revising the last few days of reporting data (ingestion delay plus# attribution), so an incremental run re-reads a trailing window instead of# trusting the frozen watermark.- if APPLE_SEARCH_ADS_ENDPOINTS[schema.name].partition_key is not None:+ if endpoints[schema.name].partition_key is not None:schema.default_incremental_lookback_seconds = REPORT_LOOKBACK_SECONDSreturn schemas@@ -204,9 +256,10 @@ In the Search Ads UI, create an API user with at least **Read only** access, gen@staticmethoddef _credentials(config: AppleSearchAdsSourceConfig) -> AppleSearchAdsCredentials:return AppleSearchAdsCredentials(- org_id=config.org_id,client_id=config.client_id,team_id=config.apple_team_id,key_id=config.key_id,private_key=config.private_key,+ org_id=config.org_id,+ ad_account_id=config.ad_account_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.pyindex e9ad21bfd1ec..fe968d0c92b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py@@ -14,6 +14,7 @@ from parameterized import parameterizedfrom requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (+ APPLE_ADS_HOST,APPLE_OAUTH_AUDIENCE,APPLE_OAUTH_TOKEN_URL,APPLE_SEARCH_ADS_HOST,@@ -26,17 +27,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apple_sear_report_windows,apple_search_ads_source,build_client_secret,+ flatten_acl_rows,flatten_report_rows,get_rows,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (- APPLE_SEARCH_ADS_ENDPOINTS,+ APPLE_ADS_API_VERSION_V1,+ APPLE_SEARCH_ADS_API_VERSION_V5,DEFAULT_INITIAL_LOOKBACK_DAYS,ENDPOINTS,- MAX_INITIAL_LOOKBACK_DAYS,PAGE_SIZE,REPORT_WINDOW_DAYS,+ ReportingLimits,+ endpoints_for_version,+ reporting_limits_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -48,8 +53,9 @@ TODAY_PATCH = ("products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads._today")-API_VERSION = "v5"-BASE_URL = f"{APPLE_SEARCH_ADS_HOST}/api/{API_VERSION}"+V5 = APPLE_SEARCH_ADS_API_VERSION_V5+V1 = APPLE_ADS_API_VERSION_V1+BASE_URL = {V5: f"{APPLE_SEARCH_ADS_HOST}/api/{V5}", V1: f"{APPLE_ADS_HOST}/{V1}"}_private_key = ec.generate_private_key(ec.SECP256R1())PRIVATE_KEY_PEM = _private_key.private_bytes(@@ -67,22 +73,26 @@ PUBLIC_KEY_PEM = ()CREDENTIALS = AppleSearchAdsCredentials(- org_id="555",client_id="SEARCHADS.client",team_id="SEARCHADS.team",key_id="key-1",private_key=PRIVATE_KEY_PEM,+ org_id="555",+ ad_account_id="123456789",)LOGGER = cast(Any, structlog.get_logger(__name__))+# What each version calls the per-day metric buckets on a report row.+METRICS_KEY = {V5: "granularity", V1: "granularMetrics"}+def _with_key(private_key: str) -> AppleSearchAdsCredentials:return dataclasses.replace(CREDENTIALS, private_key=private_key)class _FakeResponse:- def __init__(self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, url: str = BASE_URL):+ def __init__(self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, url: str = BASE_URL[V5]):self.status_code = status_codeself._json_data = json_data if json_data is not None else {}self.url = url@@ -173,22 +183,30 @@ class _FakeResumableManager(ResumableSourceManager[AppleSearchAdsResumeConfig]):self.cleared = True-def _entity_page(rows: list[dict[str, Any]]) -> _FakeResponse:+def _entity_page(rows: list[dict[str, Any]], api_version: str = V5) -> _FakeResponse:+ if api_version == V1:+ return _FakeResponse(200, {"result": rows, "pagination": {"offset": 0, "pageSize": PAGE_SIZE}})return _FakeResponse(200, {"data": rows, "pagination": {"totalResults": len(rows)}})-def _report_payload(rows: list[dict[str, Any]]) -> dict[str, Any]:+def _acls_page(accounts: list[dict[str, Any]]) -> _FakeResponse:+ return _FakeResponse(200, {"result": {"acls": accounts}})+++def _report_payload(rows: list[dict[str, Any]], api_version: str = V5) -> dict[str, Any]:+ if api_version == V1:+ return {"result": {"rows": rows}, "pagination": {"offset": 0, "pageSize": PAGE_SIZE}}return {"data": {"reportingDataResponse": {"row": rows}}}-def _report_page(rows: list[dict[str, Any]]) -> _FakeResponse:- return _FakeResponse(200, _report_payload(rows))+def _report_page(rows: list[dict[str, Any]], api_version: str = V5) -> _FakeResponse:+ return _FakeResponse(200, _report_payload(rows, api_version))-def _report_row(metadata: dict[str, Any], dates: list[str]) -> dict[str, Any]:+def _report_row(metadata: dict[str, Any], dates: list[str], api_version: str = V5) -> dict[str, Any]:return {"metadata": metadata,- "granularity": [{"date": day, "impressions": 10, "taps": 1} for day in dates],+ METRICS_KEY[api_version]: [{"date": day, "impressions": 10, "taps": 1} for day in dates],}@@ -196,6 +214,7 @@ def _run(endpoint: str,session: _FakeSession,manager: _FakeResumableManager,+ api_version: str = V5,**kwargs: Any,) -> list[list[dict[str, Any]]]:with mock.patch(SESSION_PATCH, return_value=session):@@ -203,7 +222,7 @@ def _run(get_rows(credentials=CREDENTIALS,endpoint=endpoint,- api_version=API_VERSION,+ api_version=api_version,request_logger=LOGGER,resumable_source_manager=manager,**kwargs,@@ -248,11 +267,14 @@ class TestAppleSearchAdsTransport:with pytest.raises(AppleSearchAdsAuthError):build_client_secret(_with_key(private_key))- def test_requests_carry_the_bearer_token_and_org_context(self) -> None:- session = _FakeSession([_entity_page([{"id": 1}])])+ @parameterized.expand([(V5, "orgId=555"), (V1, "adAccountId=123456789")])+ def test_requests_carry_the_bearer_token_and_the_versions_context_id(+ self, api_version: str, expected_context: str+ ) -> None:+ session = _FakeSession([_entity_page([{"id": 1}], api_version)])manager = _FakeResumableManager()- _run("campaigns", session, manager)+ _run("campaigns", session, manager, api_version=api_version)assert len(session.token_calls) == 1token_body = session.token_calls[0]["data"]@@ -262,38 +284,36 @@ class TestAppleSearchAdsTransport:headers = session.api_calls[0]["headers"]assert headers["Authorization"] == "Bearer access-token"- assert headers["X-AP-Context"] == "orgId=555"-- def test_acls_is_a_single_page_without_org_context(self) -> None:- session = _FakeSession([_entity_page([{"orgId": 555}])])+ # v5 scopes to an organization, the Platform API to an ad account, and the two ids are+ # different values.+ assert headers["X-AP-Context"] == expected_context++ @parameterized.expand([(V5,), (V1,)])+ def test_acls_is_a_single_page_without_the_context_header(self, api_version: str) -> None:+ response = (+ _acls_page([{"adAccount": {"id": 9, "orgId": 555}, "roles": ["Admin"]}])+ if api_version == V1+ else _entity_page([{"orgId": 555}])+ )+ session = _FakeSession([response])manager = _FakeResumableManager()- batches = _run("acls", session, manager)+ batches = _run("acls", session, manager, api_version=api_version)- assert batches == [[{"orgId": 555}]]assert len(session.api_calls) == 1- assert session.api_calls[0]["url"] == f"{BASE_URL}/acls"+ assert session.api_calls[0]["url"] == f"{BASE_URL[api_version]}/acls"assert "X-AP-Context" not in session.api_calls[0]["headers"]+ assert batches[0][0]["orgId"] == 555- def test_find_endpoints_page_in_the_request_body(self) -> None:- session = _FakeSession([_entity_page([{"id": 7}])])- manager = _FakeResumableManager()-- _run("ad_groups", session, manager)-- call = session.api_calls[0]- assert call["method"] == "POST"- assert call["url"] == f"{BASE_URL}/adgroups/find"- assert call["json"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}-- def test_expired_access_token_is_reminted_once_and_the_request_replayed(self) -> None:+ @parameterized.expand([(V5,), (V1,)])+ def test_expired_access_token_is_reminted_once_and_the_request_replayed(self, api_version: str) -> None:session = _FakeSession(- [_FakeResponse(401, url=BASE_URL), _entity_page([{"id": 1}])],+ [_FakeResponse(401, url=BASE_URL[api_version]), _entity_page([{"id": 1}], api_version)],token_responses=[_token_response("first"), _token_response("second")],)manager = _FakeResumableManager()- batches = _run("campaigns", session, manager)+ batches = _run("campaigns", session, manager, api_version=api_version)assert batches == [[{"id": 1}]]assert len(session.token_calls) == 2@@ -303,38 +323,202 @@ class TestAppleSearchAdsTransport:@parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("server_error", 500)])def test_a_persistent_error_status_raises(self, _name: str, status: int) -> None:# Two identical failures so the single 401 re-mint retry is exhausted too.- session = _FakeSession([_FakeResponse(status, url=BASE_URL), _FakeResponse(status, url=BASE_URL)])+ session = _FakeSession([_FakeResponse(status, url=BASE_URL[V5]), _FakeResponse(status, url=BASE_URL[V5])])manager = _FakeResumableManager()with pytest.raises(HTTPError):_run("campaigns", session, manager)- def test_entity_pagination_advances_the_offset_and_checkpoints_between_pages(self) -> None:+ @parameterized.expand([(V5,), (V1,)])+ def test_entity_pagination_advances_the_offset_and_checkpoints_between_pages(self, api_version: str) -> None:first_page = [{"id": index} for index in range(PAGE_SIZE)]- session = _FakeSession([_entity_page(first_page), _entity_page([{"id": PAGE_SIZE}])])+ session = _FakeSession(+ [_entity_page(first_page, api_version), _entity_page([{"id": PAGE_SIZE}], api_version)],+ )manager = _FakeResumableManager()- batches = _run("campaigns", session, manager)+ batches = _run("campaigns", session, manager, api_version=api_version)assert [len(batch) for batch in batches] == [PAGE_SIZE, 1]- assert [call["params"]["offset"] for call in session.api_calls] == [0, PAGE_SIZE]+ assert [_offset_of(call, api_version) for call in session.api_calls] == [0, PAGE_SIZE]assert [state.offset for state in manager.saved_states] == [PAGE_SIZE]assert manager.cleared is True- def test_entity_pagination_resumes_from_the_saved_offset(self) -> None:- session = _FakeSession([_entity_page([{"id": 1}])])+ @parameterized.expand([(V5,), (V1,)])+ def test_entity_pagination_resumes_from_the_saved_offset(self, api_version: str) -> None:+ session = _FakeSession([_entity_page([{"id": 1}], api_version)])manager = _FakeResumableManager(AppleSearchAdsResumeConfig(offset=2000))- _run("campaigns", session, manager)+ _run("campaigns", session, manager, api_version=api_version)- assert session.api_calls[0]["params"]["offset"] == 2000+ assert _offset_of(session.api_calls[0], api_version) == 2000- def test_empty_first_page_yields_nothing_and_terminates(self) -> None:- session = _FakeSession([_entity_page([])])+ @parameterized.expand([(V5,), (V1,)])+ def test_empty_first_page_yields_nothing_and_terminates(self, api_version: str) -> None:+ # The Platform API scopes keywords per campaign, so it needs the campaign list first.+ responses = [_entity_page([{"id": 10}], V1), _entity_page([], V1)] if api_version == V1 else [_entity_page([])]+ session = _FakeSession(responses)manager = _FakeResumableManager()- assert _run("keywords", session, manager) == []- assert len(session.api_calls) == 1+ assert _run("keywords", session, manager, api_version=api_version) == []+++def _offset_of(call: dict[str, Any], api_version: str) -> int:+ """Requested offset, wherever this version puts it."""+ if api_version == V1:+ return call["json"]["pagination"]["offset"]+ return call["params"]["offset"]+++class TestVersionFivePaths:+ def test_find_endpoints_page_in_the_request_body(self) -> None:+ session = _FakeSession([_entity_page([{"id": 7}])])++ _run("ad_groups", session, _FakeResumableManager())++ call = session.api_calls[0]+ assert call["method"] == "POST"+ assert call["url"] == f"{BASE_URL[V5]}/adgroups/find"+ assert call["json"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}++ def test_reports_page_inside_a_selector(self) -> None:+ session = _FakeSession([_report_page([_report_row({"campaignId": 1}, ["2026-01-01"])])])++ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 2)):+ _run(+ "campaign_report",+ session,+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 1),+ )++ body = session.api_calls[0]["json"]+ assert body["granularity"] == "DAILY"+ assert body["timeZone"] == "ORTZ"+ assert (body["startTime"], body["endTime"]) == ("2026-01-01", "2026-01-02")+ assert body["selector"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}++ def test_the_campaign_report_reads_the_whole_organization_in_one_request(self) -> None:+ session = _FakeSession([_report_page([_report_row({"campaignId": 1}, ["2026-01-01"])])])++ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 2)):+ _run(+ "campaign_report",+ session,+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 1),+ )++ # No campaign list is fetched: v5 serves this report org-wide.+ assert [call["url"] for call in session.api_calls] == [f"{BASE_URL[V5]}/reports/campaigns"]+++class TestPlatformApiPaths:+ def test_entity_collections_are_read_through_a_query_body(self) -> None:+ session = _FakeSession([_entity_page([{"id": 7}], V1)])++ _run("ad_groups", session, _FakeResumableManager(), api_version=V1)++ call = session.api_calls[0]+ assert call["method"] == "POST"+ assert call["url"] == f"{BASE_URL[V1]}/adgroups/query"+ assert call["json"] == {"pagination": {"offset": 0, "pageSize": PAGE_SIZE}}++ def test_keywords_are_scoped_per_campaign(self) -> None:+ session = _FakeSession(+ [+ _entity_page([{"id": 20}, {"id": 10}], V1),+ _entity_page([{"id": 1}], V1),+ _entity_page([{"id": 2}], V1),+ ]+ )++ _run("keywords", session, _FakeResumableManager(), api_version=V1)++ keyword_calls = [call for call in session.api_calls if call["url"].endswith("/keywords/query")]+ # Apple rejects a keyword query that scopes neither a campaign nor an ad group, and the+ # ids are visited in a stable ascending order rather than response order.+ assert [call["json"]["filters"] for call in keyword_calls] == [+ [{"field": "campaignId", "operator": "EQUALS", "value": 10}],+ [{"field": "campaignId", "operator": "EQUALS", "value": 20}],+ ]++ def test_reports_carry_a_time_range_and_a_required_campaign_filter(self) -> None:+ session = _FakeSession(+ [+ _entity_page([{"id": 10}], V1),+ _report_page([_report_row({"id": 10}, ["2026-06-01"], V1)], V1),+ ]+ )++ with mock.patch(TODAY_PATCH, return_value=date(2026, 6, 2)):+ _run(+ "campaign_report",+ session,+ _FakeResumableManager(),+ api_version=V1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 6, 1),+ )++ report_call = next(call for call in session.api_calls if "/reports/" in call["url"])+ assert report_call["url"] == f"{BASE_URL[V1]}/reports/apps/campaigns/query"+ body = report_call["json"]+ assert body["timeRange"] == {+ "start": "2026-06-01",+ "end": "2026-06-02",+ "timeZone": "ORTZ",+ "granularity": "DAILY",+ }+ assert body["pagination"] == {"offset": 0, "pageSize": PAGE_SIZE}+ # Apple requires a campaignId filter on every apps report, including the campaign level,+ # and documents the value as an array of strings.+ assert body["filters"] == [{"field": "campaignId", "operator": "EQUALS", "value": ["10"]}]+ # Unsegmented daily rows, so no groupBy is sent.+ assert "groupBy" not in body++ def test_the_campaign_report_fans_out_over_every_campaign(self) -> None:+ session = _FakeSession(+ [+ _entity_page([{"id": 20}, {"id": 10}], V1),+ _report_page([_report_row({"id": 10}, ["2026-06-01"], V1)], V1),+ _report_page([_report_row({"id": 20}, ["2026-06-01"], V1)], V1),+ ]+ )++ with mock.patch(TODAY_PATCH, return_value=date(2026, 6, 2)):+ batches = _run(+ "campaign_report",+ session,+ _FakeResumableManager(),+ api_version=V1,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 6, 1),+ )++ assert [row["campaignId"] for batch in batches for row in batch] == [10, 20]++ def test_acl_rows_become_one_row_per_ad_account(self) -> None:+ session = _FakeSession(+ [+ _acls_page(+ [+ {"adAccount": {"id": 123456789, "name": "Account A", "orgId": 555}, "roles": ["Admin"]},+ {"adAccount": {"id": 987654321, "name": "Account B", "orgId": 555}, "roles": ["Read Only"]},+ ]+ )+ ]+ )++ batches = _run("acls", session, _FakeResumableManager(), api_version=V1)++ # `orgId` repeats across ad accounts under one token, so `id` is what identifies a row.+ assert batches[0] == [+ {"id": 123456789, "name": "Account A", "orgId": 555, "roles": ["Admin"]},+ {"id": 987654321, "name": "Account B", "orgId": 555, "roles": ["Read Only"]},+ ]class TestReportWindows:@@ -376,6 +560,22 @@ class TestReportWindows:# Contiguous with no gaps or overlaps.assert all(later.start == earlier.end + timedelta(days=1) for earlier, later in zip(windows, windows[1:]))+ @parameterized.expand(+ [+ ("whole_range_is_one_day", date(2026, 1, 8), date(2026, 1, 8), date(2026, 1, 7)),+ ("trailing_window_is_one_day", date(2026, 1, 1), date(2026, 1, 8), date(2026, 1, 7)),+ ]+ )+ def test_a_one_day_window_reaches_back_far_enough_for_the_platform_api(+ self, _name: str, start: date, end: date, expected_last_start: date+ ) -> None:+ # The Platform API rejects a DAILY range covering a single day, so the window widens+ # rather than sending a request Apple would refuse.+ windows = _report_windows(start, end, min_window_days=2)++ assert windows[-1] == ReportWindow(start=expected_last_start, end=end)+ assert all((window.end - window.start).days + 1 >= 2 for window in windows)+@parameterized.expand([("watermark_wins", True, date(2026, 5, 1), "2020-01-01", date(2026, 5, 1)),@@ -385,9 +585,6 @@ class TestReportWindows:("unparseable_start_date_falls_back", False, None, "not-a-date", None),("no_watermark_no_start_date", False, None, None, None),("incremental_without_watermark", True, None, None, None),- # An implausibly old configured start is floored so it can't fan out over thousands- # of empty windows.- ("ancient_start_date_is_floored", False, None, "0001-01-01", None),])def test_report_start_date(@@ -399,53 +596,96 @@ class TestReportWindows:expected: Optional[date],) -> None:today = date(2026, 6, 1)- resolved = _report_start_date(should_use_incremental_field, watermark, start_date, today)+ limits = ReportingLimits(max_lookback_days=24 * 30, min_window_days=1)+ resolved = _report_start_date(should_use_incremental_field, watermark, start_date, today, limits)- if _name == "ancient_start_date_is_floored":- assert resolved == today - timedelta(days=MAX_INITIAL_LOOKBACK_DAYS)- else:- assert resolved == (expected or today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS))+ assert resolved == (expected or today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS))++ @parameterized.expand(+ [+ ("ancient_configured_start", False, None, "0001-01-01"),+ # A source that fell further behind than Apple serves would otherwise ask for a day+ # Apple refuses, and fail every run instead of resuming at the oldest readable day.+ ("watermark_older_than_the_window", True, date(2020, 1, 1), None),+ ("default_lookback_exceeds_the_window", False, None, None),+ ]+ )+ def test_every_start_date_is_floored_at_the_versions_oldest_readable_day(+ self, _name: str, should_use_incremental_field: bool, watermark: Any, start_date: Optional[str]+ ) -> None:+ today = date(2026, 6, 1)+ limits = reporting_limits_for_version(V1)++ resolved = _report_start_date(should_use_incremental_field, watermark, start_date, today, limits)- def test_max_initial_lookback_stays_within_apples_daily_report_limit(self) -> None:- # Apple's Reporting API rejects a DAILY-granularity report whose startTime is more than- # 24 months in the past with a 400 — this guards against re-widening the floor past it.- assert MAX_INITIAL_LOOKBACK_DAYS <= 24 * 30+ assert resolved == today - timedelta(days=limits.max_lookback_days)++ def test_platform_api_reporting_limits_stay_inside_apples_daily_rules(self) -> None:+ limits = reporting_limits_for_version(V1)++ # Apple serves DAILY reporting for ranges starting within the last 90 days, and rejects+ # a range covering a single day.+ assert limits.max_lookback_days < 90+ assert limits.min_window_days == 2class TestFlattenReportRows:- def test_granularity_buckets_become_one_row_per_day(self) -> None:- payload = _report_payload([_report_row({"campaignId": 1, "campaignName": "A"}, ["2026-01-01", "2026-01-02"])])+ @parameterized.expand([(V5,), (V1,)])+ def test_daily_buckets_become_one_row_per_day(self, api_version: str) -> None:+ rows = [_report_row({"campaignId": 1, "campaignName": "A"}, ["2026-01-01", "2026-01-02"], api_version)]- rows = flatten_report_rows(payload, None)+ flattened = flatten_report_rows(rows, metrics_key=METRICS_KEY[api_version])- assert rows == [+ assert flattened == [{"campaignId": 1, "campaignName": "A", "date": "2026-01-01", "impressions": 10, "taps": 1},{"campaignId": 1, "campaignName": "A", "date": "2026-01-02", "impressions": 10, "taps": 1},]def test_fan_out_injects_the_campaign_id_the_primary_key_needs(self) -> None:- payload = _report_payload([_report_row({"adGroupId": 9}, ["2026-01-01"])])+ rows = [_report_row({"adGroupId": 9}, ["2026-01-01"])]- rows = flatten_report_rows(payload, 42)+ flattened = flatten_report_rows(rows, metrics_key=METRICS_KEY[V5], campaign_id=42)- assert rows[0]["campaignId"] == 42- assert rows[0]["adGroupId"] == 9+ assert flattened[0]["campaignId"] == 42+ assert flattened[0]["adGroupId"] == 9def test_fan_out_does_not_clobber_a_campaign_id_apple_supplied(self) -> None:- payload = _report_payload([_report_row({"campaignId": 7, "adGroupId": 9}, ["2026-01-01"])])+ rows = [_report_row({"campaignId": 7, "adGroupId": 9}, ["2026-01-01"])]++ assert flatten_report_rows(rows, metrics_key=METRICS_KEY[V5], campaign_id=42)[0]["campaignId"] == 7++ @parameterized.expand(+ [+ ("campaign_report", "campaignId", {"id": 10, "name": "A"}),+ ("ad_group_report", "adGroupId", {"id": 55, "campaignId": 10}),+ ("keyword_report", "keywordId", {"id": 88, "campaignId": 10, "adGroupId": 55}),+ ]+ )+ def test_the_platform_apis_entity_id_is_projected_onto_the_primary_key_column(+ self, endpoint: str, entity_id_field: str, metadata: dict[str, Any]+ ) -> None:+ # The Platform API names every report level's own entity `id`, where v5 named it after+ # the level. Without this projection the table's primary key column would be missing.+ rows = [_report_row(metadata, ["2026-06-01"], V1)]++ flattened = flatten_report_rows(rows, metrics_key=METRICS_KEY[V1], entity_id_field=entity_id_field)- assert flatten_report_rows(payload, 42)[0]["campaignId"] == 7+ assert flattened[0][entity_id_field] == metadata["id"]+ # Projected, not duplicated, so the value does not arrive under two column names.+ assert "id" not in flattened[0]+ assert set(endpoints_for_version(V1)[endpoint].primary_keys) <= set(flattened[0])@parameterized.expand([- ("no_granularity", {"data": {"reportingDataResponse": {"row": [{"metadata": {"campaignId": 1}}]}}}),- ("empty_row_list", {"data": {"reportingDataResponse": {"row": []}}}),- ("null_reporting_data", {"data": None}),- ("missing_data_key", {}),+ ("no_daily_buckets", [{"metadata": {"campaignId": 1}}]),+ ("empty_row_list", []),])- def test_pages_without_daily_metrics_flatten_to_nothing(self, _name: str, payload: dict[str, Any]) -> None:- assert flatten_report_rows(payload, None) == []+ def test_rows_without_daily_metrics_flatten_to_nothing(self, _name: str, rows: list[dict[str, Any]]) -> None:+ assert flatten_report_rows(rows, metrics_key=METRICS_KEY[V5]) == []++ def test_acl_entries_without_an_ad_account_are_skipped(self) -> None:+ assert flatten_acl_rows([{"roles": ["Admin"]}, {"adAccount": None}]) == []class TestReportSync:@@ -473,8 +713,6 @@ class TestReportSync:("2026-01-01", "2026-01-07"),("2026-01-08", "2026-01-09"),]- assert bodies[0]["granularity"] == "DAILY"- assert bodies[0]["selector"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}# After the first window completes, the checkpoint points at the next window.assert manager.saved_states[0] == AppleSearchAdsResumeConfig(offset=0, window_start="2026-01-08", campaign_id=None@@ -502,34 +740,40 @@ class TestReportSync:report_calls = [call for call in session.api_calls if "/reports/" in call["url"]]# Campaign ids are visited in a stable ascending order, not response order.assert [call["url"] for call in report_calls] == [- f"{BASE_URL}/reports/campaigns/10/adgroups",- f"{BASE_URL}/reports/campaigns/20/adgroups",+ f"{BASE_URL[V5]}/reports/campaigns/10/adgroups",+ f"{BASE_URL[V5]}/reports/campaigns/20/adgroups",]assert [row["campaignId"] for batch in batches for row in batch] == [10, 20]assert manager.saved_states[0] == AppleSearchAdsResumeConfig(offset=0, window_start="2026-01-01", campaign_id=20)- def test_fan_out_reports_resume_at_the_checkpointed_campaign(self) -> None:+ @parameterized.expand([(V5,), (V1,)])+ def test_fan_out_reports_resume_at_the_checkpointed_campaign(self, api_version: str) -> None:session = _FakeSession([- _entity_page([{"id": 10}, {"id": 20}]),- _report_page([_report_row({"adGroupId": 2}, ["2026-01-01"])]),+ _entity_page([{"id": 10}, {"id": 20}], api_version),+ _report_page([_report_row({"adGroupId": 2}, ["2026-06-01"], api_version)], api_version),])- manager = _FakeResumableManager(AppleSearchAdsResumeConfig(offset=0, window_start="2026-01-01", campaign_id=20))+ manager = _FakeResumableManager(AppleSearchAdsResumeConfig(offset=0, window_start="2026-06-01", campaign_id=20))- with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 3)):+ with mock.patch(TODAY_PATCH, return_value=date(2026, 6, 3)):_run("ad_group_report",session,manager,+ api_version=api_version,should_use_incremental_field=True,- db_incremental_field_last_value=date(2026, 1, 1),+ db_incremental_field_last_value=date(2026, 6, 1),)report_calls = [call for call in session.api_calls if "/reports/" in call["url"]]- assert [call["url"] for call in report_calls] == [f"{BASE_URL}/reports/campaigns/20/adgroups"]+ assert len(report_calls) == 1+ if api_version == V1:+ assert report_calls[0]["json"]["filters"][0]["value"] == ["20"]+ else:+ assert report_calls[0]["url"].endswith("/reports/campaigns/20/adgroups")def test_a_checkpoint_outside_this_runs_windows_restarts_the_range(self) -> None:session = _FakeSession([_report_page([_report_row({"campaignId": 1}, ["2026-01-01"])])])@@ -550,36 +794,47 @@ class TestReportSync:assert body["startTime"] == "2026-01-01"assert body["selector"]["pagination"]["offset"] == 0- def test_report_pagination_continues_while_a_page_is_full(self) -> None:- full_page = _report_page([_report_row({"campaignId": index}, ["2026-01-01"]) for index in range(PAGE_SIZE)])- session = _FakeSession([full_page, _report_page([_report_row({"campaignId": 9999}, ["2026-01-01"])])])+ @parameterized.expand([(V5,), (V1,)])+ def test_report_pagination_continues_while_a_page_is_full(self, api_version: str) -> None:+ full_page = [_report_row({"campaignId": index}, ["2026-06-01"], api_version) for index in range(PAGE_SIZE)]+ responses = [+ _report_page(full_page, api_version),+ _report_page([_report_row({"campaignId": 9999}, ["2026-06-01"], api_version)], api_version),+ ]+ if api_version == V1:+ # The Platform API needs a campaign filter on this report, so the list comes first.+ responses.insert(0, _entity_page([{"id": 1}], V1))+ session = _FakeSession(responses)manager = _FakeResumableManager()- with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 2)):+ with mock.patch(TODAY_PATCH, return_value=date(2026, 6, 2)):_run("campaign_report",session,manager,+ api_version=api_version,should_use_incremental_field=True,- db_incremental_field_last_value=date(2026, 1, 1),+ db_incremental_field_last_value=date(2026, 6, 1),)- offsets = [call["json"]["selector"]["pagination"]["offset"] for call in session.api_calls]+ report_calls = [call for call in session.api_calls if "/reports/" in call["url"]]+ if api_version == V1:+ offsets = [call["json"]["pagination"]["offset"] for call in report_calls]+ else:+ offsets = [call["json"]["selector"]["pagination"]["offset"] for call in report_calls]assert offsets == [0, PAGE_SIZE]- assert manager.saved_states[0] == AppleSearchAdsResumeConfig(- offset=PAGE_SIZE, window_start="2026-01-01", campaign_id=None- )+ assert manager.saved_states[0].offset == PAGE_SIZEclass TestSourceResponse:- @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])- def test_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:- config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]+ @parameterized.expand([(endpoint, version) for endpoint in ENDPOINTS for version in (V5, V1)])+ def test_response_matches_the_endpoint_catalog(self, endpoint: str, api_version: str) -> None:+ config = endpoints_for_version(api_version)[endpoint]response = apple_search_ads_source(credentials=CREDENTIALS,endpoint=endpoint,- api_version=API_VERSION,+ api_version=api_version,request_logger=LOGGER,resumable_source_manager=_FakeResumableManager(),)@@ -595,11 +850,27 @@ class TestSourceResponse:assert response.partition_mode == "datetime"assert response.partition_keys == [config.partition_key]+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_report_tables_keep_their_primary_keys_across_versions(self, endpoint: str) -> None:+ # A repinned source must not change what identifies a row, or the merge would either+ # duplicate history or collapse it.+ v5_config = endpoints_for_version(V5)[endpoint]+ v1_config = endpoints_for_version(V1)[endpoint]++ assert v5_config.partition_key == v1_config.partition_key+ assert v5_config.incremental_fields == v1_config.incremental_fields+ if endpoint == "acls":+ # The one exception: v5 returned a row per organization, the Platform API a row per+ # ad account, and every such row repeats the same `orgId`.+ assert (v5_config.primary_keys, v1_config.primary_keys) == (["orgId"], ["id"])+ else:+ assert v5_config.primary_keys == v1_config.primary_keys+def test_items_are_lazy(self) -> None:response = apple_search_ads_source(credentials=CREDENTIALS,endpoint="campaigns",- api_version=API_VERSION,+ api_version=V1,request_logger=LOGGER,resumable_source_manager=_FakeResumableManager(),)@@ -620,28 +891,71 @@ class TestValidateCredentials:])def test_probe_status_is_mapped(self, _name: str, status: int, schema_name: Optional[str], expected: bool) -> None:- session = _FakeSession([_FakeResponse(status, url=BASE_URL), _FakeResponse(status, url=BASE_URL)])+ session = _FakeSession([_FakeResponse(status, url=BASE_URL[V5]), _FakeResponse(status, url=BASE_URL[V5])])with mock.patch(SESSION_PATCH, return_value=session):- is_valid, message = validate_credentials(CREDENTIALS, API_VERSION, schema_name)+ is_valid, message = validate_credentials(CREDENTIALS, V5, schema_name)assert is_valid is expectedassert (message is None) is expected- def test_probe_targets_an_org_scoped_endpoint(self) -> None:- session = _FakeSession([_FakeResponse(200, {"data": []}, url=BASE_URL)])+ @parameterized.expand(+ [+ (V5, f"{BASE_URL[V5]}/campaigns", "orgId=555"),+ (V1, f"{BASE_URL[V1]}/campaigns/query", "adAccountId=123456789"),+ ]+ )+ def test_the_probe_targets_a_context_scoped_endpoint(+ self, api_version: str, expected_url: str, expected_context: str+ ) -> None:+ session = _FakeSession([_entity_page([], api_version)])++ with mock.patch(SESSION_PATCH, return_value=session):+ assert validate_credentials(CREDENTIALS, api_version) == (True, None)++ assert session.api_calls[0]["url"] == expected_url+ assert session.api_calls[0]["headers"]["X-AP-Context"] == expected_context++ def test_a_missing_ad_account_id_names_the_accounts_the_client_can_read(self) -> None:+ credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)+ session = _FakeSession([_acls_page([{"adAccount": {"id": 123456789, "name": "Account A"}, "roles": []}])])with mock.patch(SESSION_PATCH, return_value=session):- assert validate_credentials(CREDENTIALS, API_VERSION) == (True, None)+ is_valid, message = validate_credentials(credentials, V1)- assert session.api_calls[0]["url"] == f"{BASE_URL}/campaigns"- assert session.api_calls[0]["headers"]["X-AP-Context"] == "orgId=555"+ assert is_valid is False+ assert message is not None+ assert "ad account ID" in message+ # The ACL lookup carries no context id, so it can answer before one is entered.+ assert "123456789 (Account A)" in message++ def test_a_missing_ad_account_id_is_still_reported_when_the_acl_lookup_fails(self) -> None:+ credentials = dataclasses.replace(CREDENTIALS, ad_account_id=None)+ session = _FakeSession([_FakeResponse(500, url=BASE_URL[V1]), _FakeResponse(500, url=BASE_URL[V1])])++ with mock.patch(SESSION_PATCH, return_value=session):+ is_valid, message = validate_credentials(credentials, V1)++ assert is_valid is False+ assert message is not None and "ad account ID" in message++ def test_a_missing_org_id_is_reported_for_the_older_api(self) -> None:+ credentials = dataclasses.replace(CREDENTIALS, org_id=None)+ session = _FakeSession([])++ with mock.patch(SESSION_PATCH, return_value=session):+ is_valid, message = validate_credentials(credentials, V5)++ assert is_valid is False+ assert message is not None and "organization ID" in message+ # No ad-account hint for a version that does not use one.+ assert session.api_calls == []def test_an_unusable_private_key_fails_before_any_request(self) -> None:session = _FakeSession([])with mock.patch(SESSION_PATCH, return_value=session):- is_valid, message = validate_credentials(_with_key("nope"), API_VERSION)+ is_valid, message = validate_credentials(_with_key("nope"), V5)assert is_valid is Falseassert message is not None and "private key" in message@@ -651,7 +965,7 @@ class TestValidateCredentials:session = _FakeSession([], token_responses=[_FakeResponse(400, url=APPLE_OAUTH_TOKEN_URL)])with mock.patch(SESSION_PATCH, return_value=session):- is_valid, message = validate_credentials(CREDENTIALS, API_VERSION)+ is_valid, message = validate_credentials(CREDENTIALS, V5)assert is_valid is Falseassert message is not None@@ -660,16 +974,24 @@ class TestValidateCredentials:session = _FakeSession([], token_responses=[_FakeResponse(200, {}, url=APPLE_OAUTH_TOKEN_URL)])with mock.patch(SESSION_PATCH, return_value=session):- is_valid, message = validate_credentials(CREDENTIALS, API_VERSION)+ is_valid, message = validate_credentials(CREDENTIALS, V5)assert is_valid is Falseassert message == "Apple's token response did not contain an access token"class TestClientBaseUrl:- @parameterized.expand([("v5", "v5"), ("pinned_older", "v4")])- def test_base_url_follows_the_resolved_api_version(self, _name: str, api_version: str) -> None:+ @parameterized.expand(+ [+ (V5, f"{APPLE_SEARCH_ADS_HOST}/api/{V5}"),+ (V1, f"{APPLE_ADS_HOST}/{V1}"),+ # A pin the source no longer declares is honored verbatim rather than silently+ # moved, so it keeps reaching the host that served it.+ ("v4", f"{APPLE_SEARCH_ADS_HOST}/api/v4"),+ ]+ )+ def test_base_url_follows_the_resolved_api_version(self, api_version: str, expected: str) -> None:with mock.patch(SESSION_PATCH, return_value=_FakeSession([])):client = AppleSearchAdsClient(CREDENTIALS, api_version)- assert client.base_url == f"{APPLE_SEARCH_ADS_HOST}/api/{api_version}"+ assert client.base_url == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.pyindex fa7536f45d73..543a56dcb10a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py@@ -1,20 +1,26 @@+from datetime import datefrom typing import Any, castfrom unittest import mockfrom parameterized import parameterized+from posthog.schema import SourceFieldInputConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (AppleSearchAdsResumeConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (- APPLE_SEARCH_ADS_ENDPOINTS,+ APPLE_ADS_API_VERSION_V1,+ APPLE_SEARCH_ADS_API_VERSION_V5,ENDPOINTS,REPORT_LOOKBACK_SECONDS,+ endpoints_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source import (AppleSearchAdsSource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import VersionDeprecationfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (AppleSearchAdsSourceConfig,@@ -22,8 +28,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source"-REPORT_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if config.partition_key)-ENTITY_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if not config.partition_key)+_PLATFORM_ENDPOINTS = endpoints_for_version(APPLE_ADS_API_VERSION_V1)+REPORT_ENDPOINTS = tuple(name for name, config in _PLATFORM_ENDPOINTS.items() if config.partition_key)+ENTITY_ENDPOINTS = tuple(name for name, config in _PLATFORM_ENDPOINTS.items() if not config.partition_key)class TestAppleSearchAdsSource:@@ -31,25 +38,40 @@ class TestAppleSearchAdsSource:self.source = AppleSearchAdsSource()self.team_id = 123self.config = AppleSearchAdsSourceConfig(- org_id="555",client_id="SEARCHADS.client",apple_team_id="SEARCHADS.team",key_id="key-1",private_key="-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----",- start_date="2026-01-01",+ ad_account_id="123456789",+ start_date="2026-06-01",)def test_api_version_metadata(self) -> None:- assert self.source.supported_versions == ("v5",)- assert self.source.default_version == "v5"+ assert self.source.supported_versions == (APPLE_SEARCH_ADS_API_VERSION_V5, APPLE_ADS_API_VERSION_V1)+ assert self.source.default_version == APPLE_ADS_API_VERSION_V1assert self.source.api_docs_url.startswith("https://")+ def test_the_retired_api_version_carries_apples_sunset_date(self) -> None:+ # Drives the in-product deprecation warning, so the date has to be Apple's.+ assert self.source.deprecated_versions == (+ VersionDeprecation(version=APPLE_SEARCH_ADS_API_VERSION_V5, sunset_at=date(2027, 1, 26)),+ )+def test_lists_tables_without_credentials(self) -> None:# `get_schemas` walks a static catalog, so the public docs can render the table list.assert self.source.lists_tables_without_credentials is True- def test_get_schemas_covers_the_endpoint_catalog(self) -> None:- schemas = self.source.get_schemas(self.config, self.team_id)+ def test_connection_host_fields_force_secret_reentry_on_account_or_org_change(self) -> None:+ # The stored private key is sent against whichever ad account (Platform API) or+ # organization (v5) is configured, so changing either must force the editor to re-enter+ # the key — otherwise a retarget silently reuses the credential against a different Apple+ # account.+ assert self.source.connection_host_fields == ["ad_account_id", "org_id"]++ @parameterized.expand([(APPLE_SEARCH_ADS_API_VERSION_V5,), (APPLE_ADS_API_VERSION_V1,)])+ def test_get_schemas_covers_the_same_endpoint_catalog_on_every_version(self, api_version: str) -> None:+ # A repinned source must keep every table it had, so the table set cannot vary.+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)assert {schema.name for schema in schemas} == set(ENDPOINTS)assert all(schema.description for schema in schemas)@@ -78,11 +100,18 @@ class TestAppleSearchAdsSource:assert schema.incremental_fields == []assert schema.default_incremental_lookback_seconds is None- @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])- def test_non_retryable_errors_cover_auth_failures(self, _name: str, status: int) -> None:+ @parameterized.expand(+ [+ ("platform_unauthorized", 401, "api.ads.apple.com"),+ ("platform_forbidden", 403, "api.ads.apple.com"),+ ("legacy_unauthorized", 401, "api.searchads.apple.com"),+ ("legacy_forbidden", 403, "api.searchads.apple.com"),+ ]+ )+ def test_non_retryable_errors_cover_auth_failures_on_both_hosts(self, _name: str, status: int, host: str) -> None:errors = self.source.get_non_retryable_errors()- assert any(str(status) in key and "searchads.apple.com" in key for key in errors)+ assert any(str(status) in key and host in key for key in errors)assert all(message for message in errors.values())def test_get_resumable_source_manager_is_namespaced_per_schema(self) -> None:@@ -96,12 +125,13 @@ class TestAppleSearchAdsSource:# Entity and report checkpoints have incompatible shapes, so they must not share a slot.assert manager._namespace == "campaign_report"- def test_source_for_pipeline_plumbs_arguments(self) -> None:+ @parameterized.expand([(None, APPLE_ADS_API_VERSION_V1), ("v5", APPLE_SEARCH_ADS_API_VERSION_V5)])+ def test_source_for_pipeline_plumbs_the_resolved_version(self, pinned: str | None, expected: str) -> None:inputs = mock.MagicMock()inputs.schema_name = "campaign_report"inputs.should_use_incremental_field = Trueinputs.db_incremental_field_last_value = "2026-05-01"- inputs.api_version = None+ inputs.api_version = pinnedmanager = mock.MagicMock()with mock.patch(f"{SOURCE_MODULE}.apple_search_ads_source") as mock_source:@@ -109,9 +139,37 @@ class TestAppleSearchAdsSource:kwargs = cast("dict[str, Any]", mock_source.call_args.kwargs)assert kwargs["endpoint"] == "campaign_report"- assert kwargs["api_version"] == "v5"+ # An unset pin resolves to the current default, a stored one is honored verbatim.+ assert kwargs["api_version"] == expectedassert kwargs["resumable_source_manager"] is managerassert kwargs["should_use_incremental_field"] is Trueassert kwargs["db_incremental_field_last_value"] == "2026-05-01"- assert kwargs["start_date"] == "2026-01-01"- assert kwargs["credentials"].org_id == "555"+ assert kwargs["start_date"] == "2026-06-01"++ def test_both_context_ids_reach_the_credentials(self) -> None:+ # Which one a sync needs follows the version pin, so the form collects either and the+ # request layer picks.+ config = AppleSearchAdsSourceConfig(+ client_id="SEARCHADS.client",+ apple_team_id="SEARCHADS.team",+ key_id="key-1",+ private_key="pem",+ ad_account_id="123456789",+ org_id="555",+ )++ credentials = self.source._credentials(config)++ assert (credentials.ad_account_id, credentials.org_id) == ("123456789", "555")++ def test_the_connect_form_does_not_require_either_context_id(self) -> None:+ # `required` cannot express "depends on the version pin", so `validate_credentials`+ # enforces whichever one applies instead.+ fields = {+ field.name: field+ for field in self.source.get_source_config.fields+ if isinstance(field, SourceFieldInputConfig)+ }++ assert fields["ad_account_id"].required is False+ assert fields["org_id"].required is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.pyindex a9daa4874c19..6124c5e413f8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py@@ -6,9 +6,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AppleSearchAdsSourceConfig(config.Config):- org_id: strclient_id: strapple_team_id: strkey_id: strprivate_key: str+ ad_account_id: str | None = Nonestart_date: str | None = None+ org_id: str | None = None