: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): add Amazon Ads keyword, target, ad and report tables (#98319)
Tom Owersf679ab254e2e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 082dfaab7e7e..3936d8a86998 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -252,14 +252,14 @@ Note: Single /query endpoint parameterized by `function=`; the docs page exposes## AmazonAds — **thin**-Today (3): `profiles`, `sp_ad_groups`, `sp_campaigns`+Today (7): `profiles`, `sp_ad_groups`, `sp_campaign_reports`, `sp_campaigns`, `sp_keywords`, `sp_product_ads`, `sp_targets`Diffed against: <https://d1y2lf8k3vrkfu.cloudfront.net/openapi/en-us/dest/SponsoredProducts_prod_3p.json>-- [ ] `POST /reporting/reports then GET /reporting/reports/{reportId}` — async reporting v3 - impressions, clicks, spend, sales, ACOS; without it none of the synced entities have any performance metrics (high)-- [ ] `POST /sp/productAds/list` — the ad (ASIN) level under the ad groups already synced (high)-- [ ] `POST /sp/keywords/list` — keyword-level bids and state, the main optimization object (high)-- [ ] `POST /sp/targets/list` — product and category targeting expressions with bids (high)+- [x] `POST /reporting/reports then GET /reporting/reports/{reportId}` — async reporting v3 - impressions, clicks, spend, sales, ACOS; without it none of the synced entities have any performance metrics (high)+- [x] `POST /sp/productAds/list` — the ad (ASIN) level under the ad groups already synced (high)+- [x] `POST /sp/keywords/list` — keyword-level bids and state, the main optimization object (high)+- [x] `POST /sp/targets/list` — product and category targeting expressions with bids (high)- [ ] `POST /portfolios/list` — lookup resolving the portfolioId carried on the campaigns already synced (high)- [ ] `POST /sb/... campaigns, ad groups, ads and targets (AmazonAdsAPISBMerged_prod_3p.json)` — Sponsored Brands entities are entirely absent, so spend coverage is partial (high)- [ ] `POST /sd/... campaigns, ad groups, product ads and targets (AmazonAdsAPISDMerged_prod_3p.json)` — Sponsored Display entities are entirely absent (high)@@ -269,7 +269,7 @@ Diffed against: <https://d1y2lf8k3vrkfu.cloudfront.net/openapi/en-us/dest/Sponso- [ ] `POST /adsAccounts/list` — advertising account lookup above profiles, for multi-account rollups (medium)- [ ] `GET /invoices and POST /invoiceSummaries/list (Advertising Billing API)` — billed spend reconciliation against reported spend (medium)-Note: Static schema list. The Amazon Ads docs site is a Redocly SPA; the real spec index is https://d3a0d0y2hgofx6.cloudfront.net/en-us/toc2.json, which links ~130 OpenAPI documents. I also read OfflineReport_prod_3p.json, Portfolios_prod_3p.json, AmazonAdsAPIExports_prod_3p.json, Changehistory_prod_3p.json, AdvertisingBilling_prod_3p.json and AdvertisingAccounts_prod_3p.json. Note the source code already flags reporting as a known follow-up. Nearly all list endpoints are POST /.../list rather than GET.+Note: Static schema list. The Amazon Ads docs site is a Redocly SPA; the real spec index is https://d3a0d0y2hgofx6.cloudfront.net/en-us/toc2.json, which links ~130 OpenAPI documents. I also read OfflineReport_prod_3p.json, Portfolios_prod_3p.json, AmazonAdsAPIExports_prod_3p.json, Changehistory_prod_3p.json, AdvertisingBilling_prod_3p.json and AdvertisingAccounts_prod_3p.json. Nearly all list endpoints are POST /.../list rather than GET.## Amplitude — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.pyindex e29d1e15b562..9489c194949b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/amazon_ads.py@@ -1,12 +1,24 @@+import io+import gzip+import json+import time+import datetime as dtfrom collections.abc import Iteratorfrom typing import Any, Optional+from urllib.parse import parse_qsl, urlparse, urlsplitimport requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter-from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import AMAZON_ADS_ENDPOINTS+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (+ AMAZON_ADS_ENDPOINTS,+ AmazonAdsReportConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponseAMAZON_ADS_HOSTS = {@@ -20,15 +32,66 @@ PAGE_SIZE = 500REQUEST_TIMEOUT_SECONDS = 120MAX_RETRY_ATTEMPTS = 5+# The vendor's own examples send this on both the create and the status call, and no Accept.+REPORT_MEDIA_TYPE = "application/vnd.createasyncreportrequest.v3+json"+REPORT_POLL_INTERVAL_SECONDS = 30+REPORT_POLL_MAX_ATTEMPTS = 40+REPORT_DOWNLOAD_TIMEOUT_SECONDS = 300+REPORT_ROWS_PER_BATCH = 2000+# The generated file sits on presigned Amazon storage rather than the API host. Pinning the host+# keeps a tampered `url` from pointing the download somewhere else.+REPORT_URL_HOST_SUFFIXES = (".amazonaws.com", ".amazon.com")+class AmazonAdsRetryableError(Exception):pass-def _get_session(client_secret: str, refresh_token: str, client_id: str) -> requests.Session:+class AmazonAdsReportError(Exception):+ """Amazon finished generating a report and marked it failed."""+++@frozen+class ReportWindow:+ start: dt.date+ end: dt.date+++@frozen+class AmazonAdsResumeConfig:+ """The report Amazon is generating right now, so a retried activity re-polls it.++ Asking twice for a report with identical parameters is answered with a 425 until the first+ one finishes, so a retry that starts over would wait out the report it abandoned.+ """++ profile_id: str+ window_start: str+ report_id: str+++def _get_session(+ client_secret: str,+ refresh_token: str,+ client_id: str,+ capture: bool = True,+ extra_redact: tuple[str, ...] = (),+) -> requests.Session:return make_tracked_session(headers={"Amazon-Advertising-API-ClientId": client_id},- redact_values=(client_secret, refresh_token),+ redact_values=(client_secret, refresh_token, *extra_redact),+ capture=capture,+ )+++def presigned_secret_values(url: str) -> tuple[str, ...]:+ """The signing material AWS puts in a presigned URL.++ Anyone holding it can download the report until it expires, and the shared scrubber+ masks query values by name, which does not cover `X-Amz-Signature` and its siblings.+ """+ return tuple(+ value for name, value in parse_qsl(urlsplit(url).query) if name.lower().startswith("x-amz-") and len(value) >= 8)@@ -71,6 +134,59 @@ def validate_credentials(region: str, client_id: str, client_secret: str, refresreturn False+def as_report_date(value: Any) -> Optional[dt.date]:+ """Read the stored `date` cursor, which arrives as a date, a datetime, or a YYYY-MM-DD string."""+ if isinstance(value, dt.datetime):+ return value.date()+ if isinstance(value, dt.date):+ return value+ if isinstance(value, str) and value:+ try:+ return dt.date.fromisoformat(value[:10])+ except ValueError:+ return None+ return None+++def report_windows(start: dt.date, end: dt.date, max_window_days: int) -> Iterator[ReportWindow]:+ while start <= end:+ window_end = min(start + dt.timedelta(days=max_window_days - 1), end)+ yield ReportWindow(start=start, end=window_end)+ start = window_end + dt.timedelta(days=1)+++def report_request_body(report: AmazonAdsReportConfig, start: dt.date, end: dt.date) -> dict[str, Any]:+ return {+ "name": f"PostHog {report.report_type_id} {start.isoformat()} to {end.isoformat()}",+ "startDate": start.isoformat(),+ "endDate": end.isoformat(),+ "configuration": {+ "adProduct": report.ad_product,+ "groupBy": list(report.group_by),+ "columns": list(report.columns),+ "reportTypeId": report.report_type_id,+ "timeUnit": report.time_unit,+ "format": "GZIP_JSON",+ },+ }+++def download_report_rows(url: str, client_id: str, client_secret: str, refresh_token: str) -> list[dict[str, Any]]:+ host = (urlparse(url).hostname or "").lower()+ if not host.endswith(REPORT_URL_HOST_SUFFIXES):+ raise ValueError(f"Amazon Ads report download URL points outside Amazon: host={host}")++ session = _get_session(+ client_secret, refresh_token, client_id, capture=False, extra_redact=presigned_secret_values(url)+ )+ response = session.get(url, timeout=REPORT_DOWNLOAD_TIMEOUT_SECONDS)+ response.raise_for_status()+ with gzip.GzipFile(fileobj=io.BytesIO(response.content)) as unzipped:+ rows = json.load(unzipped)++ return rows if isinstance(rows, list) else []++def get_rows(region: str,client_id: str,@@ -78,9 +194,15 @@ def get_rows(refresh_token: str,endpoint: str,logger: FilteringBoundLogger,+ resumable_source_manager: Optional[ResumableSourceManager[AmazonAdsResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,) -> Iterator[list[dict[str, Any]]]:config = AMAZON_ADS_ENDPOINTS[endpoint]session = _get_session(client_secret, refresh_token, client_id)+ # A report status body carries the presigned download URL, so those calls stay out of+ # sample capture.+ report_session = _get_session(client_secret, refresh_token, client_id, capture=False)base_url = _base_url(region)token = _mint_token(session, client_id, client_secret, refresh_token)@@ -91,10 +213,16 @@ def get_rows(reraise=True,)def request(- method: str, path: str, profile_id: Optional[str] = None, body: Optional[dict[str, Any]] = None+ method: str,+ path: str,+ profile_id: Optional[str] = None,+ body: Optional[dict[str, Any]] = None,+ extra_headers: Optional[dict[str, str]] = None,+ http: Optional[requests.Session] = None,) -> requests.Response:nonlocal tokenurl = f"{base_url}{path}"+ client = http if http is not None else sessiondef _do() -> requests.Response:headers: dict[str, str] = {"Authorization": f"Bearer {token}"}@@ -103,9 +231,11 @@ def get_rows(if config.media_type is not None and method == "POST":headers["Content-Type"] = config.media_typeheaders["Accept"] = config.media_type+ if extra_headers is not None:+ headers.update(extra_headers)if method == "POST":- return session.post(url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)- return session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ return client.post(url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ return client.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)response = _do()# Access tokens last ~1h; re-mint once if the sync outlives one.@@ -113,7 +243,8 @@ def get_rows(token = _mint_token(session, client_id, client_secret, refresh_token)response = _do()- if response.status_code == 429 or response.status_code >= 500:+ # 425 says an identical report is still generating, so the wait is worth repeating.+ if response.status_code in (425, 429) or response.status_code >= 500:raise AmazonAdsRetryableError(f"Amazon Ads API error (retryable): status={response.status_code}, url={url}")if not response.ok:@@ -126,15 +257,104 @@ def get_rows(body = request("GET", "/v2/profiles").json()return body if isinstance(body, list) else []+ def await_report_url(report: AmazonAdsReportConfig, profile_id: str, report_id: str) -> Optional[str]:+ status = None+ for _attempt in range(REPORT_POLL_MAX_ATTEMPTS):+ body = request(+ "GET",+ f"{config.path}/{report_id}",+ profile_id=profile_id,+ extra_headers={"Content-Type": REPORT_MEDIA_TYPE},+ http=report_session,+ ).json()+ status = body.get("status")++ if status == "COMPLETED":+ return body.get("url")+ if status == "FAILED":+ raise AmazonAdsReportError(+ f"Amazon Ads could not generate the {report.report_type_id} report: {body.get('failureReason')}"+ )++ time.sleep(REPORT_POLL_INTERVAL_SECONDS)++ raise AmazonAdsRetryableError(+ f"Amazon Ads {report.report_type_id} report {report_id} still {status} after the polling budget"+ )++ def report_rows(report: AmazonAdsReportConfig, profile_ids: list[str]) -> Iterator[list[dict[str, Any]]]:+ today = dt.datetime.now(dt.UTC).date()+ earliest = today - dt.timedelta(days=report.retention_days - 1)+ start = earliest+ if should_use_incremental_field:+ cursor = as_report_date(db_incremental_field_last_value)+ if cursor is not None:+ start = max(cursor, earliest)++ pending = (+ resumable_source_manager.load_state()+ if resumable_source_manager is not None and resumable_source_manager.can_resume()+ else None+ )++ for window in report_windows(start, today, report.max_window_days):+ for profile_id in profile_ids:+ if (+ pending is not None+ and pending.profile_id == profile_id+ and pending.window_start == window.start.isoformat()+ ):+ report_id = pending.report_id+ pending = None+ else:+ created = request(+ "POST",+ config.path,+ profile_id=profile_id,+ body=report_request_body(report, window.start, window.end),+ extra_headers={"Content-Type": REPORT_MEDIA_TYPE},+ ).json()+ report_id = created["reportId"]++ if resumable_source_manager is not None:+ # Persist before the first poll — a retry that created a second report would+ # be answered with a 425 until this one finished anyway.+ resumable_source_manager.save_state(+ AmazonAdsResumeConfig(+ profile_id=profile_id,+ window_start=window.start.isoformat(),+ report_id=report_id,+ )+ )++ url = await_report_url(report, profile_id, report_id)+ if not url:+ continue++ rows = download_report_rows(url, client_id, client_secret, refresh_token)+ # Amazon does not order the file, and the pipeline advances the `date` cursor from+ # each batch it writes, so a batch must never carry a date later than the rows+ # still to come for this profile.+ rows.sort(key=lambda row: str(row.get("date") or ""))+ for offset in range(0, len(rows), REPORT_ROWS_PER_BATCH):+ yield [{**row, "_profile_id": profile_id} for row in rows[offset : offset + REPORT_ROWS_PER_BATCH]]++ if resumable_source_manager is not None:+ resumable_source_manager.clear_state()+if endpoint == "profiles":profiles = list_profiles()if profiles:yield profilesreturn- # Sponsored Products v3 list endpoints, fanned out per profile.profile_ids = [str(profile["profileId"]) for profile in list_profiles()]+ if config.report is not None:+ yield from report_rows(config.report, profile_ids)+ return++ # Sponsored Products v3 list endpoints, fanned out per profile.for profile_id in profile_ids:next_token: Optional[str] = Nonewhile True:@@ -159,8 +379,12 @@ def amazon_ads_source(refresh_token: str,endpoint: str,logger: FilteringBoundLogger,+ resumable_source_manager: Optional[ResumableSourceManager[AmazonAdsResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = AMAZON_ADS_ENDPOINTS[endpoint]+ is_report = config.report is not Nonereturn SourceResponse(name=endpoint,@@ -171,9 +395,15 @@ def amazon_ads_source(refresh_token=refresh_token,endpoint=endpoint,logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,),- primary_keys=[config.primary_key],+ primary_keys=list(config.primary_keys),partition_count=1,partition_size=1,+ partition_mode="datetime" if is_report else None,+ partition_format="day" if is_report else None,+ partition_keys=["date"] if is_report else None,sort_mode="asc",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.pyindex 76e6b67bd4c8..b7a998e0c1d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/canonical_descriptions.py@@ -49,4 +49,106 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"defaultBid": "Default bid applied to targets in the ad group, in the profile's currency.",},},+ "sp_product_ads": {+ "description": "A Sponsored Products ad: one advertised product (ASIN or SKU) inside an ad group.",+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-products/3-0/openapi/prod#tag/Product-ads",+ "columns": {+ "adId": "Unique identifier for the product ad.",+ "adGroupId": "Identifier of the ad group the ad belongs to.",+ "campaignId": "Identifier of the campaign the ad belongs to.",+ "asin": "ASIN of the advertised product. Set for vendor accounts only.",+ "sku": "SKU of the advertised product. Set for seller accounts only.",+ "state": "Current state of the ad: enabled, paused, or archived.",+ "customText": "Custom text shown with the ad. Set for custom text ads only.",+ "globalAdId": "Identifier of the ad across marketplaces.",+ "_profile_id": "Advertising profile the ad was synced from.",+ },+ },+ "sp_keywords": {+ "description": "A Sponsored Products keyword target, with the bid and match type used to buy that search.",+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-products/3-0/openapi/prod#tag/Keywords",+ "columns": {+ "keywordId": "Unique identifier for the keyword.",+ "adGroupId": "Identifier of the ad group the keyword belongs to.",+ "campaignId": "Identifier of the campaign the keyword belongs to.",+ "keywordText": "Text of the keyword.",+ "matchType": "How the keyword matches a shopper search: broad, phrase, or exact.",+ "bid": "Bid for the keyword. A keyword with no bid inherits the ad group's default bid.",+ "state": "Current state of the keyword: enabled, paused, or archived.",+ "nativeLanguageKeyword": "Keyword text in the advertiser's preferred language.",+ "nativeLanguageLocale": "Locale of the advertiser's preferred language, such as zh_CN.",+ "globalKeywordId": "Identifier of the keyword across marketplaces.",+ "_profile_id": "Advertising profile the keyword was synced from.",+ },+ },+ "sp_targets": {+ "description": "A Sponsored Products targeting clause: a product or category targeting expression with its bid.",+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/sponsored-products/3-0/openapi/prod#tag/Targets",+ "columns": {+ "targetId": "Unique identifier for the target.",+ "adGroupId": "Identifier of the ad group the target belongs to.",+ "campaignId": "Identifier of the campaign the target belongs to.",+ "expression": "Targeting expression, such as a product ASIN or a category with refinements.",+ "resolvedExpression": "Targeting expression with its references resolved to concrete values.",+ "expressionType": "Whether the expression was set manually or generated automatically.",+ "bid": "Bid for the target. A target with no bid inherits the ad group's default bid.",+ "state": "Current state of the target: enabled, paused, or archived.",+ "globalTargetId": "Identifier of the target across marketplaces.",+ "_profile_id": "Advertising profile the target was synced from.",+ },+ },+ "sp_campaign_reports": {+ "description": "Daily Sponsored Products performance for each campaign, from the async reporting API.",+ "docs_url": "https://advertising.amazon.com/API/docs/en-us/guides/reporting/v3/report-types/campaign",+ "columns": {+ "date": "Date the ad activity happened, in YYYY-MM-DD format.",+ "campaignId": "Identifier of the campaign the row reports on.",+ "campaignName": "Name of the campaign.",+ "campaignStatus": "Status of the campaign.",+ "campaignBiddingStrategy": "Bidding strategy the campaign ran with.",+ "campaignBudgetAmount": "Total budget allocated to the campaign.",+ "campaignBudgetType": "Whether the campaign budget is daily or lifetime.",+ "campaignBudgetCurrencyCode": "Currency code of the campaign budget.",+ "campaignRuleBasedBudgetAmount": "Value of the campaign's rule-based budget.",+ "campaignApplicableBudgetRuleId": "Identifier of the budget rule active on the campaign.",+ "campaignApplicableBudgetRuleName": "Name of the budget rule active on the campaign.",+ "impressions": "Total number of ad impressions.",+ "clicks": "Total number of clicks on an ad.",+ "clickThroughRate": "Clicks divided by impressions.",+ "cost": "Total cost of ad clicks.",+ "costPerClick": "Total cost divided by total number of clicks.",+ "spend": "Total cost of ad clicks.",+ "topOfSearchImpressionShare": "Share of eligible top-of-search impressions the campaign won.",+ "addToList": "Times shoppers added a promoted product to a wish list, gift list, or registry.",+ "qualifiedBorrows": "Kindle Unlimited borrows attributed to ad exposure that triggered a royalty payment.",+ "royaltyQualifiedBorrows": "Estimated royalty payment for those Kindle Unlimited borrows.",+ "purchases1d": "Attributed conversion events within 1 day of an ad click.",+ "purchases7d": "Attributed conversion events within 7 days of an ad click.",+ "purchases14d": "Attributed conversion events within 14 days of an ad click.",+ "purchases30d": "Attributed conversion events within 30 days of an ad click.",+ "purchasesSameSku1d": "Attributed conversions within 1 day of a click where the purchased SKU was the advertised SKU.",+ "purchasesSameSku7d": "Attributed conversions within 7 days of a click where the purchased SKU was the advertised SKU.",+ "purchasesSameSku14d": "Attributed conversions within 14 days of a click where the purchased SKU was the advertised SKU.",+ "purchasesSameSku30d": "Attributed conversions within 30 days of a click where the purchased SKU was the advertised SKU.",+ "sales1d": "Total value of sales within 1 day of an ad click.",+ "sales7d": "Total value of sales within 7 days of an ad click.",+ "sales14d": "Total value of sales within 14 days of an ad click.",+ "sales30d": "Total value of sales within 30 days of an ad click.",+ "attributedSalesSameSku1d": "Sales within 1 day of a click where the purchased SKU was the advertised SKU.",+ "attributedSalesSameSku7d": "Sales within 7 days of a click where the purchased SKU was the advertised SKU.",+ "attributedSalesSameSku14d": "Sales within 14 days of a click where the purchased SKU was the advertised SKU.",+ "attributedSalesSameSku30d": "Sales within 30 days of a click where the purchased SKU was the advertised SKU.",+ "unitsSoldClicks1d": "Units ordered within 1 day of an ad click.",+ "unitsSoldClicks7d": "Units ordered within 7 days of an ad click.",+ "unitsSoldClicks14d": "Units ordered within 14 days of an ad click.",+ "unitsSoldClicks30d": "Units ordered within 30 days of an ad click.",+ "unitsSoldSameSku1d": "Units ordered within 1 day of a click where the purchased SKU was the advertised SKU.",+ "unitsSoldSameSku7d": "Units ordered within 7 days of a click where the purchased SKU was the advertised SKU.",+ "unitsSoldSameSku14d": "Units ordered within 14 days of a click where the purchased SKU was the advertised SKU.",+ "unitsSoldSameSku30d": "Units ordered within 30 days of a click where the purchased SKU was the advertised SKU.",+ "kindleEditionNormalizedPagesRead14d": "Attributed Kindle edition normalized pages read within 14 days of an ad click.",+ "kindleEditionNormalizedPagesRoyalties14d": "Estimated royalties for those Kindle edition normalized pages.",+ "_profile_id": "Advertising profile the report was requested for.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.pyindex a116975b4e52..0fc12782baf6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/settings.py@@ -1,34 +1,127 @@-from dataclasses import dataclassfrom typing import Optional+from posthog.dataclasses import frozen-@dataclass+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@frozen+class AmazonAdsReportConfig:+ """One async reporting v3 request shape: create the report, poll it, download the gzipped JSON."""++ report_type_id: str+ ad_product: str+ group_by: tuple[str, ...]+ columns: tuple[str, ...]+ # `date` is only a valid column at DAILY granularity — a SUMMARY report carries startDate/endDate.+ time_unit: str = "DAILY"+ # Amazon rejects a report whose requested range is wider than this.+ max_window_days: int = 31+ # Amazon keeps report data for this long, so a first sync cannot reach further back.+ retention_days: int = 95+++@frozenclass AmazonAdsEndpointConfig:name: str# Path under the regional advertising host.path: str- primary_key: str+ primary_keys: list[str]# Sponsored Products v3 list endpoints are POSTs with vendor media types# and are scoped to a profile via the Amazon-Advertising-API-Scope header.profile_scoped: bool = Falsemedia_type: Optional[str] = None# Key the rows live under in the response body (None = bare array).data_key: Optional[str] = None+ # Set for the async reporting endpoints, which build their rows from a generated file+ # rather than from a paginated list response.+ report: Optional[AmazonAdsReportConfig] = None+++# Sponsored Products campaign performance, one row per campaign per day. `date` is the only+# column Amazon lets us window on, so it is the cursor too.+SP_CAMPAIGN_REPORT = AmazonAdsReportConfig(+ report_type_id="spCampaigns",+ ad_product="SPONSORED_PRODUCTS",+ group_by=("campaign",),+ columns=(+ "date",+ "campaignId",+ "campaignName",+ "campaignStatus",+ "campaignBiddingStrategy",+ "campaignBudgetAmount",+ "campaignBudgetType",+ "campaignBudgetCurrencyCode",+ "campaignRuleBasedBudgetAmount",+ "campaignApplicableBudgetRuleId",+ "campaignApplicableBudgetRuleName",+ "impressions",+ "clicks",+ "clickThroughRate",+ "cost",+ "costPerClick",+ "spend",+ "topOfSearchImpressionShare",+ "addToList",+ "qualifiedBorrows",+ "royaltyQualifiedBorrows",+ "purchases1d",+ "purchases7d",+ "purchases14d",+ "purchases30d",+ "purchasesSameSku1d",+ "purchasesSameSku7d",+ "purchasesSameSku14d",+ "purchasesSameSku30d",+ "sales1d",+ "sales7d",+ "sales14d",+ "sales30d",+ "attributedSalesSameSku1d",+ "attributedSalesSameSku7d",+ "attributedSalesSameSku14d",+ "attributedSalesSameSku30d",+ "unitsSoldClicks1d",+ "unitsSoldClicks7d",+ "unitsSoldClicks14d",+ "unitsSoldClicks30d",+ "unitsSoldSameSku1d",+ "unitsSoldSameSku7d",+ "unitsSoldSameSku14d",+ "unitsSoldSameSku30d",+ "kindleEditionNormalizedPagesRead14d",+ "kindleEditionNormalizedPagesRoyalties14d",+ ),+)++# Amazon restates a day's metrics for as long as its widest attribution window (30 days), and the+# re-read also has to span a whole report window: one window is downloaded per profile, so its rows+# are only ascending by date within a profile.+REPORT_LOOKBACK_SECONDS = 60 * 60 * 24 * (SP_CAMPAIGN_REPORT.max_window_days + 30)+REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ }+]-# Entity lists only — Amazon Ads performance metrics ship via the async-# reporting API (create report → poll → download gzip), a follow-up. Entity-# endpoints have no updated-since filter, so every stream is a full refresh.++# Entity list endpoints have no updated-since filter, so every entity stream is a full refresh.+# Performance metrics come from the async reporting API, which windows on `date`.AMAZON_ADS_ENDPOINTS: dict[str, AmazonAdsEndpointConfig] = {"profiles": AmazonAdsEndpointConfig(name="profiles",path="/v2/profiles",- primary_key="profileId",+ primary_keys=["profileId"],),"sp_campaigns": AmazonAdsEndpointConfig(name="sp_campaigns",path="/sp/campaigns/list",- primary_key="campaignId",+ primary_keys=["campaignId"],profile_scoped=True,media_type="application/vnd.spCampaign.v3+json",data_key="campaigns",@@ -36,11 +129,44 @@ AMAZON_ADS_ENDPOINTS: dict[str, AmazonAdsEndpointConfig] = {"sp_ad_groups": AmazonAdsEndpointConfig(name="sp_ad_groups",path="/sp/adGroups/list",- primary_key="adGroupId",+ primary_keys=["adGroupId"],profile_scoped=True,media_type="application/vnd.spAdGroup.v3+json",data_key="adGroups",),+ # Amazon hands out a separate `globalAdId` / `globalKeywordId` / `globalTargetId` for identity+ # across marketplaces, so the plain ids below are only unique within a profile.+ "sp_product_ads": AmazonAdsEndpointConfig(+ name="sp_product_ads",+ path="/sp/productAds/list",+ primary_keys=["_profile_id", "adId"],+ profile_scoped=True,+ media_type="application/vnd.spProductAd.v3+json",+ data_key="productAds",+ ),+ "sp_keywords": AmazonAdsEndpointConfig(+ name="sp_keywords",+ path="/sp/keywords/list",+ primary_keys=["_profile_id", "keywordId"],+ profile_scoped=True,+ media_type="application/vnd.spKeyword.v3+json",+ data_key="keywords",+ ),+ "sp_targets": AmazonAdsEndpointConfig(+ name="sp_targets",+ path="/sp/targets/list",+ primary_keys=["_profile_id", "targetId"],+ profile_scoped=True,+ media_type="application/vnd.spTargetingClause.v3+json",+ data_key="targetingClauses",+ ),+ "sp_campaign_reports": AmazonAdsEndpointConfig(+ name="sp_campaign_reports",+ path="/reporting/reports",+ primary_keys=["_profile_id", "campaignId", "date"],+ profile_scoped=True,+ report=SP_CAMPAIGN_REPORT,+ ),}ENDPOINTS = tuple(AMAZON_ADS_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.pyindex 9eecf9bfcffa..67ad965da7ff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/source.py@@ -12,15 +12,21 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.amazon_ads import (+ AmazonAdsResumeConfig,amazon_ads_source,validate_credentials as validate_amazon_ads_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import ENDPOINTS-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (+ AMAZON_ADS_ENDPOINTS,+ REPORT_INCREMENTAL_FIELDS,+ REPORT_LOOKBACK_SECONDS,+)+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,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amazonads import (@@ -30,7 +36,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AmazonAdsSource(SimpleSource[AmazonAdsSourceConfig]):+class AmazonAdsSource(ResumableSource[AmazonAdsSourceConfig, AmazonAdsResumeConfig]):api_docs_url = "https://advertising.amazon.com/API/docs"lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -54,7 +60,7 @@ class AmazonAdsSource(SimpleSource[AmazonAdsSourceConfig]):label="Amazon Ads",caption="""Connect your Amazon Ads account to pull your advertising entity data into the PostHog Data warehouse.-You need a Login with Amazon (LWA) application with Advertising API access: enter its client ID and secret plus a refresh token authorized for your advertiser account. Pick the region that matches your advertising profiles (North America, Europe, or Far East). Sponsored Products campaigns and ad groups are synced from every profile the token can access.""",+You need a Login with Amazon (LWA) application with Advertising API access: enter its client ID and secret plus a refresh token authorized for your advertiser account. Pick the region that matches your advertising profiles (North America, Europe, or Far East). Your Sponsored Products entities and daily campaign performance are synced from every profile the token can access.""",iconPath="/static/services/amazon_ads.png",docsUrl="https://posthog.com/docs/cdp/sources/amazon-ads",releaseStatus=ReleaseStatus.ALPHA,@@ -116,16 +122,18 @@ You need a Login with Amazon (LWA) application with Advertising API access: enteforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Entity lists have no updated-since filter; performance metrics ship- # via the async reporting API (a follow-up).+ # Entity lists have no updated-since filter, so they are full refresh only. Report tables+ # are windowed on `date`, and Amazon restates recent days as attribution lands, so they+ # carry a lookback wide enough to re-read what it revises.schemas = [SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=config.report is not None,supports_append=False,- incremental_fields=[],+ incremental_fields=REPORT_INCREMENTAL_FIELDS if config.report is not None else [],+ default_incremental_lookback_seconds=REPORT_LOOKBACK_SECONDS if config.report is not None else None,)- for endpoint in ENDPOINTS+ for endpoint, config in AMAZON_ADS_ENDPOINTS.items()]if names is not None:@@ -146,7 +154,15 @@ You need a Login with Amazon (LWA) application with Advertising API access: entereturn False, "Invalid Amazon Ads credentials"- def source_for_pipeline(self, config: AmazonAdsSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AmazonAdsResumeConfig]:+ return ResumableSourceManager[AmazonAdsResumeConfig](inputs, AmazonAdsResumeConfig)++ def source_for_pipeline(+ self,+ config: AmazonAdsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AmazonAdsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:return amazon_ads_source(region=config.region,client_id=config.client_id,@@ -154,4 +170,9 @@ You need a Login with Amazon (LWA) application with Advertising API access: enterefresh_token=config.refresh_token,endpoint=inputs.schema_name,logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.pyindex 861930497779..86ab049e38e1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py@@ -1,13 +1,22 @@+import gzip+import json+import datetime as dtfrom typing import Anyfrom urllib.parse import urlparseimport pytest+from freezegun import freeze_timefrom unittest import mockimport requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.amazon_ads import (+ LWA_TOKEN_URL,PAGE_SIZE,+ REPORT_POLL_MAX_ATTEMPTS,+ AmazonAdsReportError,+ AmazonAdsResumeConfig,+ AmazonAdsRetryableError,_base_url,amazon_ads_source,get_rows,@@ -16,9 +25,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_adsfrom products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (AMAZON_ADS_ENDPOINTS,ENDPOINTS,+ SP_CAMPAIGN_REPORT,)_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.amazon_ads"+_REPORT_URL = "https://offline-report-storage.s3.amazonaws.com/report.json.gz"+_TODAY = "2026-06-30"def _token_response() -> mock.MagicMock:@@ -37,6 +49,51 @@ def _json_response(body: Any) -> mock.MagicMock:return resp+def _gzip_response(rows: list[dict[str, Any]]) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.content = gzip.compress(json.dumps(rows).encode())+ resp.status_code = 200+ resp.ok = True+ return resp+++def _wire_report_session(+ mock_session: mock.MagicMock,+ profiles: list[dict[str, Any]],+ rows: list[dict[str, Any]],+ poll_statuses: list[str] | None = None,+ report_url: str = _REPORT_URL,+) -> list[dict[str, Any]]:+ """Play the create -> poll -> download flow, and hand back the report bodies we sent."""+ created: list[dict[str, Any]] = []+ statuses = list(poll_statuses or ["COMPLETED"])++ def post(url: str, **kwargs: Any) -> mock.MagicMock:+ if url == LWA_TOKEN_URL:+ return _token_response()+ created.append(kwargs["json"])+ return _json_response({"reportId": f"rep-{len(created)}"})++ def get(url: str, **kwargs: Any) -> mock.MagicMock:+ if url.endswith("/v2/profiles"):+ return _json_response(profiles)+ if "/reporting/reports/" in url:+ status = statuses.pop(0) if len(statuses) > 1 else statuses[0]+ return _json_response({"status": status, "url": report_url if status == "COMPLETED" else None})+ return _gzip_response(rows)++ mock_session.return_value.post.side_effect = post+ mock_session.return_value.get.side_effect = get+ return created+++def _resume_manager(state: AmazonAdsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = state is not None+ manager.load_state.return_value = state+ return manager++class TestBaseUrl:@pytest.mark.parametrize("region, expected_host",@@ -95,23 +152,34 @@ class TestGetRows:assert batches == [[{"profileId": 1}, {"profileId": 2}]]+ @pytest.mark.parametrize(+ "endpoint, id_field",+ [+ ("sp_campaigns", "campaignId"),+ ("sp_ad_groups", "adGroupId"),+ ("sp_product_ads", "adId"),+ ("sp_keywords", "keywordId"),+ ("sp_targets", "targetId"),+ ],+ )@mock.patch(f"{_MODULE}.make_tracked_session")- def test_sp_campaigns_fan_out_per_profile_with_scope_header(self, mock_session):+ def test_entity_fan_out_per_profile_with_scope_header(self, mock_session, endpoint, id_field):+ config = AMAZON_ADS_ENDPOINTS[endpoint]mock_session.return_value.post.side_effect = [_token_response(),- _json_response({"campaigns": [{"campaignId": 11}], "nextToken": "tok"}),- _json_response({"campaigns": [{"campaignId": 12}]}),+ _json_response({config.data_key: [{id_field: 11}], "nextToken": "tok"}),+ _json_response({config.data_key: [{id_field: 12}]}),]mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])- batches = list(get_rows("na", "cid", "sec", "rt", "sp_campaigns", mock.MagicMock()))+ batches = list(get_rows("na", "cid", "sec", "rt", endpoint, mock.MagicMock()))flat = [item for batch in batches for item in batch]- assert [(c["campaignId"], c["_profile_id"]) for c in flat] == [(11, "1"), (12, "1")]+ assert [(row[id_field], row["_profile_id"]) for row in flat] == [(11, "1"), (12, "1")]first_list_call = mock_session.return_value.post.call_args_list[1]- assert urlparse(first_list_call.args[0]).path == "/sp/campaigns/list"+ assert urlparse(first_list_call.args[0]).path == config.pathassert first_list_call.kwargs["headers"]["Amazon-Advertising-API-Scope"] == "1"- assert first_list_call.kwargs["headers"]["Content-Type"] == "application/vnd.spCampaign.v3+json"+ assert first_list_call.kwargs["headers"]["Content-Type"] == config.media_typeassert first_list_call.kwargs["json"] == {"maxResults": PAGE_SIZE}second_list_call = mock_session.return_value.post.call_args_list[2]assert second_list_call.kwargs["json"] == {"maxResults": PAGE_SIZE, "nextToken": "tok"}@@ -130,6 +198,19 @@ class TestGetRows:# One mint at start + one re-mint after the 401.assert mock_session.return_value.post.call_count == 2+ @pytest.mark.parametrize("status_code", [425, 429, 500, 503])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_retryable_statuses_are_retried_then_reraised(self, mock_session, status_code):+ throttled = mock.MagicMock()+ throttled.status_code = status_code+ throttled.ok = False+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = throttled++ with mock.patch(f"{_MODULE}.wait_exponential_jitter", return_value=lambda _state: 0):+ with pytest.raises(AmazonAdsRetryableError):+ list(get_rows("na", "cid", "sec", "rt", "profiles", mock.MagicMock()))+@mock.patch(f"{_MODULE}.make_tracked_session")def test_no_profiles_yields_nothing(self, mock_session):mock_session.return_value.post.return_value = _token_response()@@ -138,6 +219,126 @@ class TestGetRows:assert list(get_rows("na", "cid", "sec", "rt", "sp_campaigns", mock.MagicMock())) == []+@freeze_time(_TODAY)+class TestReportRows:+ def _run(self, manager: mock.MagicMock | None = None, **kwargs: Any) -> list[list[dict[str, Any]]]:+ return list(+ get_rows(+ "na",+ "cid",+ "sec",+ "rt",+ "sp_campaign_reports",+ mock.MagicMock(),+ resumable_source_manager=manager if manager is not None else _resume_manager(),+ **kwargs,+ )+ )++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_report_is_created_polled_and_downloaded_in_date_order(self, mock_session, _sleep):+ created = _wire_report_session(+ mock_session,+ profiles=[{"profileId": 7}],+ rows=[{"campaignId": 2, "date": "2026-06-29"}, {"campaignId": 1, "date": "2026-06-20"}],+ poll_statuses=["PENDING", "PROCESSING", "COMPLETED"],+ )+ manager = _resume_manager()++ batches = self._run(+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-06-20",+ )++ assert [row["date"] for batch in batches for row in batch] == ["2026-06-20", "2026-06-29"]+ assert all(row["_profile_id"] == "7" for batch in batches for row in batch)+ assert len(created) == 1+ assert created[0]["startDate"] == "2026-06-20"+ assert created[0]["endDate"] == _TODAY+ assert created[0]["configuration"]["reportTypeId"] == SP_CAMPAIGN_REPORT.report_type_id+ assert created[0]["configuration"]["timeUnit"] == "DAILY"+ assert "date" in created[0]["configuration"]["columns"]+ manager.save_state.assert_called_once_with(+ AmazonAdsResumeConfig(profile_id="7", window_start="2026-06-20", report_id="rep-1")+ )+ manager.clear_state.assert_called_once()++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_walks_the_retention_window_in_vendor_sized_chunks(self, mock_session, _sleep):+ created = _wire_report_session(mock_session, profiles=[{"profileId": 7}], rows=[])++ self._run()++ earliest = dt.date.fromisoformat(_TODAY) - dt.timedelta(days=SP_CAMPAIGN_REPORT.retention_days - 1)+ assert created[0]["startDate"] == earliest.isoformat()+ assert created[-1]["endDate"] == _TODAY+ assert all(+ (dt.date.fromisoformat(body["endDate"]) - dt.date.fromisoformat(body["startDate"])).days+ < SP_CAMPAIGN_REPORT.max_window_days+ for body in created+ )++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_the_pending_report_instead_of_asking_for_a_second(self, mock_session, _sleep):+ created = _wire_report_session(mock_session, profiles=[{"profileId": 7}], rows=[{"date": "2026-06-25"}])+ manager = _resume_manager(+ AmazonAdsResumeConfig(profile_id="7", window_start="2026-06-20", report_id="rep-in-flight")+ )++ self._run(manager, should_use_incremental_field=True, db_incremental_field_last_value="2026-06-20")++ assert created == []+ polled = [+ call.args[0]+ for call in mock_session.return_value.get.call_args_list+ if "/reporting/reports/" in call.args[0]+ ]+ assert polled and all(url.endswith("rep-in-flight") for url in polled)++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_failed_report_reports_amazons_reason(self, mock_session, _sleep):+ def get(url: str, **kwargs: Any) -> mock.MagicMock:+ if url.endswith("/v2/profiles"):+ return _json_response([{"profileId": 7}])+ return _json_response({"status": "FAILED", "failureReason": "Date range exceeds retention"})++ mock_session.return_value.post.side_effect = lambda url, **kwargs: (+ _token_response() if url == LWA_TOKEN_URL else _json_response({"reportId": "rep-1"})+ )+ mock_session.return_value.get.side_effect = get++ with pytest.raises(AmazonAdsReportError, match="Date range exceeds retention"):+ self._run(should_use_incremental_field=True, db_incremental_field_last_value="2026-06-20")++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_report_still_generating_after_the_budget_is_retryable(self, mock_session, _sleep):+ _wire_report_session(mock_session, profiles=[{"profileId": 7}], rows=[], poll_statuses=["PROCESSING"])++ with pytest.raises(AmazonAdsRetryableError):+ self._run(should_use_incremental_field=True, db_incremental_field_last_value="2026-06-20")++ assert _sleep.call_count == REPORT_POLL_MAX_ATTEMPTS++ @mock.patch(f"{_MODULE}.time.sleep")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_download_url_outside_amazon_is_rejected(self, mock_session, _sleep):+ _wire_report_session(+ mock_session,+ profiles=[{"profileId": 7}],+ rows=[],+ report_url="https://attacker.example.com/report.json.gz",+ )++ with pytest.raises(ValueError, match="outside Amazon"):+ self._run(should_use_incremental_field=True, db_incremental_field_last_value="2026-06-20")++class TestAmazonAdsSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):@@ -145,7 +346,12 @@ class TestAmazonAdsSourceResponse:response = amazon_ads_source("na", "cid", "sec", "rt", endpoint, mock.MagicMock())assert response.name == endpoint- assert response.primary_keys == [config.primary_key]+ assert response.primary_keys == config.primary_keysassert response.sort_mode == "asc"- assert response.partition_mode is None- assert response.partition_keys is None+ if config.report is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "day"+ assert response.partition_keys == ["date"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.pyindex 2783bf45625c..ffaac1d2b747 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py@@ -1,7 +1,10 @@import pytestfrom unittest import mock-from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.settings import (+ AMAZON_ADS_ENDPOINTS,+ ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_ads.source import AmazonAdsSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amazonads import (AmazonAdsSourceConfig,@@ -39,21 +42,23 @@ class TestAmazonAdsSource:non_retryable_errors = self.source.get_non_retryable_errors()assert not any(key in other_error for key in non_retryable_errors)- def test_get_schemas_are_full_refresh_only(self):- schemas = self.source.get_schemas(self.config, self.team_id)-- assert {schema.name for schema in schemas} == set(ENDPOINTS)- assert all(not schema.supports_incremental for schema in schemas)- assert all(not schema.supports_append for schema in schemas)- assert all(schema.incremental_fields == [] for schema in schemas)-- def test_get_schemas_filtered_by_names(self):- schemas = self.source.get_schemas(self.config, self.team_id, names=["sp_campaigns"])- assert len(schemas) == 1- assert schemas[0].name == "sp_campaigns"+ def test_report_schemas_carry_a_cursor_and_entity_schemas_do_not(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}- def test_get_schemas_filtered_unknown_name_returns_empty(self):- assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []+ assert set(schemas) == set(ENDPOINTS)+ for name, config in AMAZON_ADS_ENDPOINTS.items():+ schema = schemas[name]+ assert not schema.supports_append+ if config.report is None:+ assert not schema.supports_incremental+ assert schema.incremental_fields == []+ assert schema.default_incremental_lookback_seconds is None+ else:+ assert schema.supports_incremental+ # Amazon only lets a report be windowed on `date`, and it restates recent days as+ # attribution lands, so the schema has to re-read a trailing window every run.+ assert [field["field"] for field in schema.incremental_fields] == ["date"]+ assert schema.default_incremental_lookback_seconds@pytest.mark.parametrize("mock_return, expected_valid, expected_message",