Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 7 missing Pinterest Ads tables (#77292)

Tom Owers7b99d79bf182
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
index f5d01956828f..ea732ac3c6dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
@@ -369,6 +369,32 @@ campaign_stats_daily_demographics, ad_stats_daily_country, ad_stats_daily_demogr
- [ ] Organization-level tables — funding sources, billing centers, invoices, members (skipped: all
scoped to an organization ID this source does not collect).
+### Pinterest Ads — spec-verified
+
+Diffed against the Pinterest API v5 OpenAPI description in
+[pinterest/api-description](https://github.com/pinterest/api-description) (`v5/openapi.yaml`, spec version
+5.28.0) on 2026-08-04. Supersedes the Pinterest entries in the block above.
+
+Have: `campaigns`, `ad_groups`, `ads`, `campaign_analytics`, `ad_group_analytics`, `ad_analytics`,
+`ad_accounts`, `audiences`, `conversion_tags`, `keywords`, `campaign_targeting_analytics`,
+`ad_group_targeting_analytics`, `ad_targeting_analytics`.
+
+- [ ] Creative metadata (skipped: the only creative endpoints, `GET /pins` and `GET /pins/{pin_id}`,
+ need the `boards:read` and `pins:read` scopes, and the Pinterest OAuth app only requests
+ `ads:read user_accounts:read`. Adding scopes forces every existing connection to reconsent, so
+ it is its own piece of work. `ads.pin_id` and `ads.creative_type` already identify the creative.)
+- [x] Breakdown dimensions on the report tables — `campaign_targeting_analytics`,
+ `ad_group_targeting_analytics`, `ad_targeting_analytics`, broken down by age, gender, device,
+ placement, country and region. Off by default.
+- [x] Ad account table — `ad_accounts`, carrying currency and time zone.
+- [x] Audiences and pixel / conversion event definitions — `audiences` and `conversion_tags`,
+ plus `keywords` to resolve keyword targeting back to the bid term.
+
+Verified but not built: `lead_forms`, `customer_lists`, `customer_segments`, `labels`, `order_lines`,
+`promotions`, `product_group_promotions`, `templates`, `targeting_templates`, `schedules`,
+`advertiser_defined_events`, `ad_accounts/{id}/analytics` (account-level totals),
+`product_groups/analytics`. `billing_invoices` needs the `billing:read` scope.
+
### TikTok Ads — spec-verified
Supersedes the TikTok Ads entries in the section above.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/canonical_descriptions.py
index 207734d47d5c..502c20cd5104 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/canonical_descriptions.py
@@ -38,6 +38,13 @@ _ANALYTICS_COLUMNS = {
}
+# Breakdown columns shared by every targeting analytics endpoint.
+_TARGETING_COLUMNS = {
+ "targeting_type": "The targeting dimension the row is broken down by (AGE_BUCKET, GENDER, APPTYPE, PLACEMENT, COUNTRY, REGION).",
+ "targeting_value": "The value within the targeting dimension, such as '45-49', 'female', 'iphone', or 'US'.",
+}
+
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"campaigns": {
"description": "A Pinterest advertising campaign that groups ad groups under a single objective and budget.",
@@ -109,4 +116,90 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"docs_url": "https://developers.pinterest.com/docs/api/v5/ads-analytics/",
"columns": {"ad_id": "ID of the ad the metrics are for.", **_ANALYTICS_COLUMNS},
},
+ "ad_accounts": {
+ "description": "The configured Pinterest ad account, including the currency and time zone every spend figure is reported in.",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/ad_accounts-get/",
+ "columns": {
+ "id": "Unique identifier for the ad account.",
+ "name": "The ad account's name.",
+ "owner": "The user account that owns the ad account.",
+ "country": "Country the ad account is registered in.",
+ "currency": "Currency the ad account is billed and reported in, as a three-letter code.",
+ "permissions": "Permissions the connected account holds on this ad account.",
+ "time_zone": "Time zone of the ad account, in IANA format (for example America/Los_Angeles).",
+ "created_time": "Time at which the ad account was created, as a Unix timestamp.",
+ "updated_time": "Time at which the ad account was last updated, as a Unix timestamp.",
+ },
+ },
+ "audiences": {
+ "description": "Targetable audiences owned by the ad account, such as customer lists, engagement audiences, and actalike audiences.",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/audiences-list/",
+ "columns": {
+ "id": "Unique identifier for the audience.",
+ "ad_account_id": "ID of the ad account that owns the audience.",
+ "name": "The audience's name.",
+ "description": "The audience's description.",
+ "audience_type": "How the audience was built (for example CUSTOMER_LIST, VISITOR, ENGAGEMENT, ACTALIKE).",
+ "rule": "The rule the audience is built from, such as the source customer list or engagement filter.",
+ "size": "Number of Pinterest users currently in the audience.",
+ "status": "Whether the audience is usable for targeting (READY, INITIALIZING, TOO_SMALL, UPLOADING).",
+ "is_nca": "Whether the audience derives from a new customer acquisition customer list.",
+ "created_by_company_name": "Company that created the audience.",
+ "created_timestamp": "Time at which the audience was created, as a Unix timestamp.",
+ "updated_timestamp": "Time at which the audience was last updated, as a Unix timestamp.",
+ },
+ },
+ "conversion_tags": {
+ "description": "Pinterest tags (pixels) installed for the ad account, which report the conversion events that campaigns optimize against.",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/conversion_tags-list/",
+ "columns": {
+ "id": "Unique identifier for the conversion tag.",
+ "name": "The conversion tag's name.",
+ "version": "Version number of the tag.",
+ "configs": "Tag configuration, including whether automatic enhanced match is enabled.",
+ "enhanced_match_status": "Status of enhanced match for the tag.",
+ "last_fired_time_ms": "Time the tag last fired an event, in milliseconds since the epoch.",
+ "code_snippet": "The tag's code snippet.",
+ },
+ },
+ "keywords": {
+ "description": "Keyword targets defined on the ad account's campaigns and ad groups, used to resolve keyword targeting back to the term that was bid on.",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/keywords-get/",
+ "columns": {
+ "id": "Unique identifier for the keyword.",
+ "value": "The keyword term itself.",
+ "match_type": "How the term is matched (for example BROAD, EXACT, PHRASE, NEGATIVE_BROAD).",
+ "parent_id": "ID of the entity the keyword is attached to.",
+ "parent_type": "Type of entity the keyword is attached to (advertiser, campaign, or ad group).",
+ "archived": "Whether the keyword is archived.",
+ "bid": "Deprecated by Pinterest and always returned as null.",
+ },
+ },
+ "campaign_targeting_analytics": {
+ "description": "Daily campaign performance broken down by targeting dimension (age, gender, device, placement, country, region).",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/campaign_targeting_analytics-get/",
+ "columns": {
+ "campaign_id": "ID of the campaign the metrics are for.",
+ **_TARGETING_COLUMNS,
+ **_ANALYTICS_COLUMNS,
+ },
+ },
+ "ad_group_targeting_analytics": {
+ "description": "Daily ad group performance broken down by targeting dimension (age, gender, device, placement, country, region).",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/ad_group_targeting_analytics-get/",
+ "columns": {
+ "ad_group_id": "ID of the ad group the metrics are for.",
+ **_TARGETING_COLUMNS,
+ **_ANALYTICS_COLUMNS,
+ },
+ },
+ "ad_targeting_analytics": {
+ "description": "Daily ad performance broken down by targeting dimension (age, gender, device, placement, country, region).",
+ "docs_url": "https://developers.pinterest.com/docs/api/v5/ad_targeting_analytics-get/",
+ "columns": {
+ "ad_id": "ID of the ad the metrics are for.",
+ **_TARGETING_COLUMNS,
+ **_ANALYTICS_COLUMNS,
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/pinterest_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/pinterest_ads.py
index 17d2c2f5495e..86bcaea633c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/pinterest_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/pinterest_ads.py
@@ -16,6 +16,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_
ENTITY_ENDPOINT_PATHS,
PAGE_SIZE,
PINTEREST_ADS_CONFIG,
+ TARGETING_ANALYTICS_ENDPOINT_PATHS,
+ TARGETING_ANALYTICS_ID_COLUMNS,
+ TARGETING_TYPES,
EndpointType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.utils import (
@@ -31,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_
ENTITY_RESUME_KIND = "entity"
ANALYTICS_RESUME_KIND = "analytics"
+TARGETING_ANALYTICS_RESUME_KIND = "targeting_analytics"
@dataclasses.dataclass
@@ -80,11 +84,25 @@ def pinterest_ads_source(
db_incremental_field_last_value,
)
+ def targeting_analytics_items() -> Iterator[list[dict[str, Any]]]:
+ session = build_session(access_token)
+ yield from _iter_targeting_analytics_rows(
+ session,
+ ad_account_id,
+ endpoint,
+ resumable_source_manager,
+ source_logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
items_fn: Callable[[], Iterator[list[dict[str, Any]]]]
if endpoint_config.endpoint_type == EndpointType.ENTITY:
items_fn = entity_items
elif endpoint_config.endpoint_type == EndpointType.ANALYTICS:
items_fn = analytics_items
+ elif endpoint_config.endpoint_type == EndpointType.TARGETING_ANALYTICS:
+ items_fn = targeting_analytics_items
else:
raise ValueError(f"Unknown endpoint type: {endpoint_config.endpoint_type}")
@@ -121,6 +139,15 @@ def _iter_entity_rows(
) -> Iterator[list[dict[str, Any]]]:
path = ENTITY_ENDPOINT_PATHS[endpoint].format(ad_account_id=ad_account_id)
url = f"{BASE_URL}{path}"
+ endpoint_config = PINTEREST_ADS_CONFIG[endpoint]
+ supports_pagination = endpoint_config.supports_pagination
+
+ if endpoint_config.returns_single_object:
+ # The response is the resource itself, not an `items` list, so there's nothing to paginate.
+ data = _make_request(session, url, {})
+ if data:
+ yield [data]
+ return
resume_config = _load_resume_config(resumable_source_manager, ENTITY_RESUME_KIND)
bookmark: str | None = resume_config.bookmark if resume_config is not None else None
@@ -128,13 +155,15 @@ def _iter_entity_rows(
source_logger.debug("pinterest_ads_resuming_entity", endpoint=endpoint)
while True:
- params: dict[str, Any] = {"page_size": PAGE_SIZE}
- if bookmark:
- params["bookmark"] = bookmark
+ params: dict[str, Any] = {}
+ if supports_pagination:
+ params["page_size"] = PAGE_SIZE
+ if bookmark:
+ params["bookmark"] = bookmark
data = _make_request(session, url, params)
items = data.get("items", [])
- next_bookmark = data.get("bookmark")
+ next_bookmark = data.get("bookmark") if supports_pagination else None
if items:
yield items
@@ -146,6 +175,42 @@ def _iter_entity_rows(
bookmark = next_bookmark
+def _parse_analytics_rows(data: Any) -> list[dict[str, Any]] | None:
+ """Rows from a totals analytics response, or None when the payload isn't the documented shape."""
+ if not isinstance(data, list):
+ return None
+ return [_normalize_row(row) for row in data]
+
+
+def _parse_targeting_analytics_rows(data: Any) -> list[dict[str, Any]] | None:
+ """Flatten a targeting analytics response into one row per (entity, day, breakdown value).
+
+ Pinterest nests the metrics under `data[].metrics` and keeps the breakdown it belongs to
+ alongside it, so the two have to be merged for the row to be self-describing.
+ """
+ if not isinstance(data, dict):
+ return None
+ items = data.get("data")
+ if not isinstance(items, list):
+ return None
+
+ rows: list[dict[str, Any]] = []
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ metrics = item.get("metrics")
+ if not isinstance(metrics, dict):
+ continue
+ rows.append(
+ {
+ **_normalize_row(metrics),
+ "targeting_type": item.get("targeting_type"),
+ "targeting_value": item.get("targeting_value"),
+ }
+ )
+ return rows
+
+
def _iter_analytics_rows(
session: requests.Session,
ad_account_id: str,
@@ -155,7 +220,67 @@ def _iter_analytics_rows(
should_use_incremental_field: bool,
db_incremental_field_last_value: Optional[Any],
) -> Iterator[list[dict[str, Any]]]:
- resume_config = _load_resume_config(resumable_source_manager, ANALYTICS_RESUME_KIND)
+ path = ANALYTICS_ENDPOINT_PATHS[endpoint].format(ad_account_id=ad_account_id)
+ yield from _iter_fanned_out_analytics(
+ session,
+ ad_account_id,
+ endpoint,
+ resumable_source_manager,
+ source_logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ resume_kind=ANALYTICS_RESUME_KIND,
+ url=f"{BASE_URL}{path}",
+ extra_params={"columns": ",".join(ANALYTICS_COLUMNS), "granularity": "DAY"},
+ parse_rows=_parse_analytics_rows,
+ )
+
+
+def _iter_targeting_analytics_rows(
+ session: requests.Session,
+ ad_account_id: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[PinterestAdsResumeConfig],
+ source_logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[list[dict[str, Any]]]:
+ path = TARGETING_ANALYTICS_ENDPOINT_PATHS[endpoint].format(ad_account_id=ad_account_id)
+ id_column = TARGETING_ANALYTICS_ID_COLUMNS[endpoint]
+ yield from _iter_fanned_out_analytics(
+ session,
+ ad_account_id,
+ endpoint,
+ resumable_source_manager,
+ source_logger,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ resume_kind=TARGETING_ANALYTICS_RESUME_KIND,
+ url=f"{BASE_URL}{path}",
+ extra_params={
+ "columns": ",".join([id_column, *ANALYTICS_COLUMNS]),
+ "granularity": "DAY",
+ "targeting_types": ",".join(TARGETING_TYPES),
+ },
+ parse_rows=_parse_targeting_analytics_rows,
+ )
+
+
+def _iter_fanned_out_analytics(
+ session: requests.Session,
+ ad_account_id: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[PinterestAdsResumeConfig],
+ source_logger: FilteringBoundLogger,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ *,
+ resume_kind: str,
+ url: str,
+ extra_params: dict[str, Any],
+ parse_rows: Callable[[Any], list[dict[str, Any]] | None],
+) -> Iterator[list[dict[str, Any]]]:
+ resume_config = _load_resume_config(resumable_source_manager, resume_kind)
start_batch_idx = resume_config.batch_index if resume_config is not None else 0
start_chunk_idx = resume_config.date_chunk_index if resume_config is not None else 0
@@ -188,8 +313,6 @@ def _iter_analytics_rows(
currency=currency,
)
- path = ANALYTICS_ENDPOINT_PATHS[endpoint].format(ad_account_id=ad_account_id)
- url = f"{BASE_URL}{path}"
id_param_name = ANALYTICS_ID_PARAM_NAMES[endpoint]
date_chunks = _chunk_date_range(start_date, end_date)
@@ -205,33 +328,27 @@ def _iter_analytics_rows(
id_param_name: ",".join(batch),
"start_date": chunk_start,
"end_date": chunk_end,
- "columns": ",".join(ANALYTICS_COLUMNS),
- "granularity": "DAY",
+ **extra_params,
}
data = _make_request(session, url, params)
- is_successful = isinstance(data, list)
- if is_successful:
- rows: list[dict[str, Any]] = []
- for row in data:
- normalized = _normalize_row(row)
- if currency:
- normalized["currency"] = currency
- rows.append(normalized)
- if rows:
- yield rows
- else:
+ rows = parse_rows(data)
+ if rows is None:
source_logger.error(
"pinterest_ads_unexpected_analytics_response",
endpoint=endpoint,
response_type=type(data).__name__,
)
-
- # Only advance the cursor on a successful response — a failed chunk must be retried on resume.
- if not is_successful:
+ # Only advance the cursor on a successful response — a failed chunk must be retried on resume.
continue
+ if currency:
+ for row in rows:
+ row["currency"] = currency
+ if rows:
+ yield rows
+
next_batch_idx, next_chunk_idx = _advance_analytics_cursor(
batch_idx, chunk_idx, len(id_batches), len(date_chunks)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/settings.py
index 981e45d9c411..81ffc46db620 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/settings.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
@@ -68,9 +68,25 @@ ANALYTICS_COLUMNS = [
]
+# Breakdown dimensions requested for the targeting analytics tables. Pinterest reports every
+# requested targeting type independently within one response, and each value below is accepted at
+# the campaign, ad group and ad level. High-cardinality types (KEYWORD, GEO, interests, audiences)
+# are left out on purpose — they multiply row counts without answering the common questions.
+# See https://developers.pinterest.com/docs/api/v5/campaign_targeting_analytics-get/
+TARGETING_TYPES = [
+ "AGE_BUCKET",
+ "GENDER",
+ "APPTYPE",
+ "PLACEMENT",
+ "COUNTRY",
+ "REGION",
+]
+
+
class EndpointType(str, Enum):
ENTITY = "entity"
ANALYTICS = "analytics"
+ TARGETING_ANALYTICS = "targeting_analytics"
_DATE_INCREMENTAL_FIELD: list[IncrementalField] = [
@@ -87,12 +103,19 @@ _DATE_INCREMENTAL_FIELD: list[IncrementalField] = [
class EndpointConfig:
name: str
primary_keys: list[str]
- partition_keys: list[str]
- partition_mode: PartitionMode
endpoint_type: EndpointType
+ # Empty keys with no mode means the endpoint has no stable timestamp to partition on.
+ partition_keys: list[str] = field(default_factory=list)
+ partition_mode: Optional[PartitionMode] = None
incremental_fields: Optional[list[IncrementalField]] = None
partition_format: Optional[PartitionFormat] = None
partition_size: int = 1
+ # Entity endpoints that return every row in one payload and reject bookmark pagination.
+ supports_pagination: bool = True
+ should_sync_default: bool = True
+ # Endpoints that address a single resource by id and return that object directly, not an
+ # `items` list. Fetched once and adapted into a one-row response.
+ returns_single_object: bool = False
PINTEREST_ADS_CONFIG: dict[str, EndpointConfig] = {
@@ -123,6 +146,39 @@ PINTEREST_ADS_CONFIG: dict[str, EndpointConfig] = {
partition_format="week",
endpoint_type=EndpointType.ENTITY,
),
+ "ad_accounts": EndpointConfig(
+ name="ad_accounts",
+ primary_keys=["id"],
+ incremental_fields=None,
+ partition_keys=["created_time"],
+ partition_mode="datetime",
+ partition_format="week",
+ endpoint_type=EndpointType.ENTITY,
+ supports_pagination=False,
+ returns_single_object=True,
+ ),
+ "audiences": EndpointConfig(
+ name="audiences",
+ primary_keys=["id"],
+ incremental_fields=None,
+ partition_keys=["created_timestamp"],
+ partition_mode="datetime",
+ partition_format="week",
+ endpoint_type=EndpointType.ENTITY,
+ ),
+ "conversion_tags": EndpointConfig(
+ name="conversion_tags",
+ primary_keys=["id"],
+ incremental_fields=None,
+ endpoint_type=EndpointType.ENTITY,
+ supports_pagination=False,
+ ),
+ "keywords": EndpointConfig(
+ name="keywords",
+ primary_keys=["id"],
+ incremental_fields=None,
+ endpoint_type=EndpointType.ENTITY,
+ ),
"campaign_analytics": EndpointConfig(
name="campaign_analytics",
primary_keys=["campaign_id", "date"],
@@ -150,12 +206,50 @@ PINTEREST_ADS_CONFIG: dict[str, EndpointConfig] = {
partition_format="week",
endpoint_type=EndpointType.ANALYTICS,
),
+ # Breakdown tables fan out over every entity, every day and every targeting type, so they are
+ # far larger than the totals tables and stay off by default.
+ "campaign_targeting_analytics": EndpointConfig(
+ name="campaign_targeting_analytics",
+ primary_keys=["campaign_id", "date", "targeting_type", "targeting_value"],
+ incremental_fields=_DATE_INCREMENTAL_FIELD,
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="week",
+ endpoint_type=EndpointType.TARGETING_ANALYTICS,
+ should_sync_default=False,
+ ),
+ "ad_group_targeting_analytics": EndpointConfig(
+ name="ad_group_targeting_analytics",
+ primary_keys=["ad_group_id", "date", "targeting_type", "targeting_value"],
+ incremental_fields=_DATE_INCREMENTAL_FIELD,
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="week",
+ endpoint_type=EndpointType.TARGETING_ANALYTICS,
+ should_sync_default=False,
+ ),
+ "ad_targeting_analytics": EndpointConfig(
+ name="ad_targeting_analytics",
+ primary_keys=["ad_id", "date", "targeting_type", "targeting_value"],
+ incremental_fields=_DATE_INCREMENTAL_FIELD,
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="week",
+ endpoint_type=EndpointType.TARGETING_ANALYTICS,
+ should_sync_default=False,
+ ),
}
ENTITY_ENDPOINT_PATHS: dict[str, str] = {
"campaigns": "/ad_accounts/{ad_account_id}/campaigns",
"ad_groups": "/ad_accounts/{ad_account_id}/ad_groups",
"ads": "/ad_accounts/{ad_account_id}/ads",
+ # Scoped to the configured account so the source only ever imports metadata for the advertiser
+ # it was created for, not every account the OAuth token can reach.
+ "ad_accounts": "/ad_accounts/{ad_account_id}",
+ "audiences": "/ad_accounts/{ad_account_id}/audiences",
+ "conversion_tags": "/ad_accounts/{ad_account_id}/conversion_tags",
+ "keywords": "/ad_accounts/{ad_account_id}/keywords",
}
ANALYTICS_ENDPOINT_PATHS: dict[str, str] = {
@@ -164,14 +258,34 @@ ANALYTICS_ENDPOINT_PATHS: dict[str, str] = {
"ad_analytics": "/ad_accounts/{ad_account_id}/ads/analytics",
}
+TARGETING_ANALYTICS_ENDPOINT_PATHS: dict[str, str] = {
+ "campaign_targeting_analytics": "/ad_accounts/{ad_account_id}/campaigns/targeting_analytics",
+ "ad_group_targeting_analytics": "/ad_accounts/{ad_account_id}/ad_groups/targeting_analytics",
+ "ad_targeting_analytics": "/ad_accounts/{ad_account_id}/ads/targeting_analytics",
+}
+
+# Targeting analytics rows only carry the metrics that were asked for, so the entity id has to be
+# requested as a column to keep each row addressable back to its campaign / ad group / ad.
+TARGETING_ANALYTICS_ID_COLUMNS: dict[str, str] = {
+ "campaign_targeting_analytics": "CAMPAIGN_ID",
+ "ad_group_targeting_analytics": "AD_GROUP_ID",
+ "ad_targeting_analytics": "AD_ID",
+}
+
ANALYTICS_ID_PARAM_NAMES: dict[str, str] = {
"campaign_analytics": "campaign_ids",
"ad_group_analytics": "ad_group_ids",
"ad_analytics": "ad_ids",
+ "campaign_targeting_analytics": "campaign_ids",
+ "ad_group_targeting_analytics": "ad_group_ids",
+ "ad_targeting_analytics": "ad_ids",
}
ANALYTICS_ENTITY_SOURCES: dict[str, str] = {
"campaign_analytics": "campaigns",
"ad_group_analytics": "ad_groups",
"ad_analytics": "ads",
+ "campaign_targeting_analytics": "campaigns",
+ "ad_group_targeting_analytics": "ad_groups",
+ "ad_targeting_analytics": "ads",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
index 0d9621c25fdf..b139163e043e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/source.py
@@ -218,6 +218,7 @@ class PinterestAdsSource(ResumableSource[PinterestAdsSourceConfig, PinterestAdsR
supports_incremental=endpoint_config.incremental_fields is not None,
supports_append=False,
incremental_fields=endpoint_config.incremental_fields or [],
+ should_sync_default=endpoint_config.should_sync_default,
)
for endpoint_config in PINTEREST_ADS_CONFIG.values()
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
index 68a15c397269..09fc1f162a66 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_ads.py
@@ -8,12 +8,25 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads import (
ANALYTICS_RESUME_KIND,
ENTITY_RESUME_KIND,
+ TARGETING_ANALYTICS_RESUME_KIND,
PinterestAdsResumeConfig,
_advance_analytics_cursor,
_iter_analytics_rows,
_iter_entity_rows,
+ _iter_targeting_analytics_rows,
+ _parse_targeting_analytics_rows,
pinterest_ads_source,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.settings import (
+ ANALYTICS_ENDPOINT_PATHS,
+ ANALYTICS_ENTITY_SOURCES,
+ ANALYTICS_ID_PARAM_NAMES,
+ ENTITY_ENDPOINT_PATHS,
+ PINTEREST_ADS_CONFIG,
+ TARGETING_ANALYTICS_ENDPOINT_PATHS,
+ TARGETING_ANALYTICS_ID_COLUMNS,
+ EndpointType,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source import PinterestAdsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.utils import (
_chunk_date_range,
@@ -704,3 +717,234 @@ class TestIterAnalyticsRowsResume:
# Falls through to fresh path → re-fetches parent entities
mock_entity_ids.assert_called_once()
+
+
+class TestEndpointCatalog:
+ @pytest.mark.parametrize("endpoint", sorted(PINTEREST_ADS_CONFIG))
+ def test_every_endpoint_has_a_path_for_its_type(self, endpoint):
+ # A config entry with no matching path only fails once a customer selects the table and the
+ # sync KeyErrors, so keep the catalog and the path maps in lockstep here instead.
+ config = PINTEREST_ADS_CONFIG[endpoint]
+
+ if config.endpoint_type == EndpointType.ENTITY:
+ assert endpoint in ENTITY_ENDPOINT_PATHS
+ return
+
+ if config.endpoint_type == EndpointType.ANALYTICS:
+ assert endpoint in ANALYTICS_ENDPOINT_PATHS
+ else:
+ assert endpoint in TARGETING_ANALYTICS_ENDPOINT_PATHS
+ assert endpoint in TARGETING_ANALYTICS_ID_COLUMNS
+
+ assert endpoint in ANALYTICS_ID_PARAM_NAMES
+ assert ANALYTICS_ENTITY_SOURCES[endpoint] in ENTITY_ENDPOINT_PATHS
+
+ @pytest.mark.parametrize("endpoint", sorted(PINTEREST_ADS_CONFIG))
+ def test_primary_keys_identify_a_row(self, endpoint):
+ # Fanned-out tables aggregate rows from every parent, so a key that is only unique per
+ # parent seeds duplicates that every later merge multi-matches.
+ config = PINTEREST_ADS_CONFIG[endpoint]
+
+ if config.endpoint_type == EndpointType.ENTITY:
+ assert config.primary_keys == ["id"]
+ elif config.endpoint_type == EndpointType.ANALYTICS:
+ assert config.primary_keys[-1] == "date"
+ assert len(config.primary_keys) == 2
+ else:
+ assert config.primary_keys[1:] == ["date", "targeting_type", "targeting_value"]
+
+
+class TestParseTargetingAnalyticsRows:
+ @pytest.mark.parametrize(
+ "payload,expected",
+ [
+ (
+ {
+ "data": [
+ {
+ "targeting_type": "GENDER",
+ "targeting_value": "female",
+ "metrics": {"CAMPAIGN_ID": "1", "DATE": "2024-01-01", "SPEND_IN_DOLLAR": 5.0},
+ }
+ ]
+ },
+ [
+ {
+ "campaign_id": "1",
+ "date": "2024-01-01",
+ "spend_in_dollar": 5.0,
+ "targeting_type": "GENDER",
+ "targeting_value": "female",
+ }
+ ],
+ ),
+ # Metrics are nested; an item without them cannot be keyed, so it is dropped rather than
+ # yielding a row with no date or entity id.
+ ({"data": [{"targeting_type": "GENDER", "targeting_value": "female"}]}, []),
+ ({"data": []}, []),
+ ],
+ )
+ def test_flattens_metrics_into_the_row(self, payload, expected):
+ assert _parse_targeting_analytics_rows(payload) == expected
+
+ @pytest.mark.parametrize("payload", [[], {"error": "oops"}, {"data": {"not": "a list"}}, None])
+ def test_unexpected_payloads_report_failure(self, payload):
+ # None tells the caller the chunk failed, so the resume cursor stays put and it is retried.
+ assert _parse_targeting_analytics_rows(payload) is None
+
+
+class TestIterTargetingAnalyticsRows:
+ def _run(self, endpoint, mock_request, manager=None):
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads.fetch_entity_ids",
+ return_value=["1"],
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads.fetch_account_currency",
+ return_value="USD",
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads._chunk_date_range",
+ return_value=[("2024-01-01", "2024-01-31")],
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads._chunk_list",
+ return_value=[["1"]],
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads._make_request",
+ mock_request,
+ ),
+ ):
+ return list(
+ _iter_targeting_analytics_rows(
+ mock.MagicMock(),
+ "acc123",
+ endpoint,
+ manager or _make_resume_manager(),
+ mock.MagicMock(),
+ False,
+ None,
+ )
+ )
+
+ @pytest.mark.parametrize(
+ "endpoint,id_param,id_column",
+ [
+ ("campaign_targeting_analytics", "campaign_ids", "CAMPAIGN_ID"),
+ ("ad_group_targeting_analytics", "ad_group_ids", "AD_GROUP_ID"),
+ ("ad_targeting_analytics", "ad_ids", "AD_ID"),
+ ],
+ )
+ def test_requests_breakdowns_and_the_entity_id_column(self, endpoint, id_param, id_column):
+ # Pinterest only returns the columns that were asked for. Dropping the entity id column
+ # leaves every row keyed on date and breakdown alone, so rows from different campaigns
+ # collide on the primary key.
+ mock_request = mock.MagicMock(return_value={"data": []})
+
+ self._run(endpoint, mock_request)
+
+ params = mock_request.call_args.args[2]
+ assert params[id_param] == "1"
+ assert params["granularity"] == "DAY"
+ assert params["columns"].split(",")[0] == id_column
+ assert params["targeting_types"].split(",") == [
+ "AGE_BUCKET",
+ "GENDER",
+ "APPTYPE",
+ "PLACEMENT",
+ "COUNTRY",
+ "REGION",
+ ]
+
+ url = mock_request.call_args.args[1]
+ assert url.endswith(TARGETING_ANALYTICS_ENDPOINT_PATHS[endpoint].format(ad_account_id="acc123"))
+
+ def test_yields_flattened_rows_with_account_currency(self):
+ mock_request = mock.MagicMock(
+ return_value={
+ "data": [
+ {
+ "targeting_type": "AGE_BUCKET",
+ "targeting_value": "45-49",
+ "metrics": {"CAMPAIGN_ID": "1", "DATE": "2024-01-01", "SPEND_IN_DOLLAR": 5.0},
+ }
+ ]
+ }
+ )
+
+ yielded = self._run("campaign_targeting_analytics", mock_request)
+
+ assert yielded == [
+ [
+ {
+ "campaign_id": "1",
+ "date": "2024-01-01",
+ "spend_in_dollar": 5.0,
+ "targeting_type": "AGE_BUCKET",
+ "targeting_value": "45-49",
+ "currency": "USD",
+ }
+ ]
+ ]
+
+ def test_ignores_resume_state_from_the_totals_tables(self):
+ # Both fan out over (id batch, date chunk) but over different responses, so state saved by
+ # the totals sync must not be mistaken for this table's cursor.
+ manager = _make_resume_manager(
+ can_resume=True,
+ state=PinterestAdsResumeConfig(kind=ANALYTICS_RESUME_KIND, batch_index=5, date_chunk_index=5),
+ )
+ mock_request = mock.MagicMock(return_value={"data": []})
+
+ self._run("campaign_targeting_analytics", mock_request, manager=manager)
+
+ assert mock_request.call_count == 1
+
+ def test_resumes_from_its_own_saved_state(self):
+ manager = _make_resume_manager(
+ can_resume=True,
+ state=PinterestAdsResumeConfig(kind=TARGETING_ANALYTICS_RESUME_KIND, batch_index=1, date_chunk_index=0),
+ )
+ mock_request = mock.MagicMock(return_value={"data": []})
+
+ self._run("campaign_targeting_analytics", mock_request, manager=manager)
+
+ # Only one batch exists, so a cursor pointing past it leaves nothing to request.
+ assert mock_request.call_count == 0
+
+
+class TestIterEntityRowsWithoutPagination:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads._make_request"
+ )
+ def test_unpaginated_endpoint_sends_no_pagination_params(self, mock_request):
+ # Pinterest's conversion tags endpoint takes neither page_size nor bookmark and returns no
+ # bookmark, so sending them risks a 400 and trusting one would loop forever.
+ mock_request.return_value = {"items": [{"id": "1"}], "bookmark": "should_be_ignored"}
+
+ yielded = list(
+ _iter_entity_rows(mock.MagicMock(), "acc123", "conversion_tags", _make_resume_manager(), mock.MagicMock())
+ )
+
+ assert yielded == [[{"id": "1"}]]
+ assert mock_request.call_count == 1
+ assert mock_request.call_args.args[2] == {}
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.pinterest_ads._make_request"
+ )
+ def test_account_endpoint_is_scoped_to_the_configured_account(self, mock_request):
+ # The ad accounts table must fetch only the configured account, not list every account the
+ # OAuth token can reach. The scoped endpoint returns the object directly, not an `items` list.
+ mock_request.return_value = {"id": "acc123", "currency": "EUR"}
+
+ yielded = list(
+ _iter_entity_rows(mock.MagicMock(), "acc123", "ad_accounts", _make_resume_manager(), mock.MagicMock())
+ )
+
+ assert yielded == [[{"id": "acc123", "currency": "EUR"}]]
+ assert mock_request.call_count == 1
+ assert mock_request.call_args.args[1] == "https://api.pinterest.com/v5/ad_accounts/acc123"
+ assert mock_request.call_args.args[2] == {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
index 3d39a5e5d1ad..d1961d8b5902 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pinterest_ads/tests/test_pinterest_source.py
@@ -96,9 +96,16 @@ class TestPinterestAdsSource:
"campaigns",
"ad_groups",
"ads",
+ "ad_accounts",
+ "audiences",
+ "conversion_tags",
+ "keywords",
"campaign_analytics",
"ad_group_analytics",
"ad_analytics",
+ "campaign_targeting_analytics",
+ "ad_group_targeting_analytics",
+ "ad_targeting_analytics",
]
assert len(schemas) == len(expected_endpoints)
@@ -106,6 +113,27 @@ class TestPinterestAdsSource:
for endpoint in expected_endpoints:
assert endpoint in schema_names
+ @pytest.mark.parametrize(
+ "endpoint,should_sync_default",
+ [
+ ("campaigns", True),
+ ("campaign_analytics", True),
+ ("ad_accounts", True),
+ ("audiences", True),
+ ("conversion_tags", True),
+ ("keywords", True),
+ # Breakdown tables fan out over every entity, day and targeting type, so a customer has
+ # to opt into them rather than have them switched on by the schema picker.
+ ("campaign_targeting_analytics", False),
+ ("ad_group_targeting_analytics", False),
+ ("ad_targeting_analytics", False),
+ ],
+ )
+ def test_expensive_breakdown_tables_are_off_by_default(self, endpoint, should_sync_default):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=[endpoint])
+
+ assert [schema.should_sync_default for schema in schemas] == [should_sync_default]
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.pinterest_ads.source.PinterestAdsSource.get_oauth_integration"
)