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 9 missing Snapchat Ads tables (#77293)

Tom Owers78b312a53994
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 a029631abfa6..0a13146e7167 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
@@ -295,6 +295,29 @@ See patterns 1 and 2 above.
- [ ] Ad account table (currency and timezone, without which spend is ambiguous).
- [ ] Audiences and pixel / conversion event definitions.
+### Snapchat Ads — spec-verified
+
+Split out of the four-platform section above.
+Diffed against the [Snapchat Marketing API v1 reference](https://developers.snap.com/api/marketing-api)
+on 2026-08-04.
+Have: campaigns, ad_squads, ads, campaign_stats_daily, ad_squad_stats_daily, ad_stats_daily,
+ad_accounts, creatives, media, audience_segments, pixels, campaign_stats_daily_country,
+campaign_stats_daily_demographics, ad_stats_daily_country, ad_stats_daily_demographics.
+
+- [x] Creative metadata — `creatives` and `media`.
+- [x] Breakdown dimensions — `report_dimension` country and age/gender tables at campaign and ad level,
+ off by default because a breakdown row exists per dimension value per day.
+- [x] Ad account table — `ad_accounts`, carrying the currency and timezone every spend figure is in.
+- [x] Audiences — `audience_segments`.
+- [x] Pixel definitions — `pixels`.
+- [ ] Custom conversion definitions (skipped: `/pixels/{pixel_id}/custom_conversions` only lists per
+ pixel, and this source has no parent fan-out path yet).
+- [ ] Region, DMA, device make, OS, and lifestyle-category breakdowns (skipped: Snapchat documents the
+ dimension names but not the column each returns, so the primary key would be a guess; region, DMA
+ and make also return no conversion metrics).
+- [ ] Organization-level tables — funding sources, billing centers, invoices, members (skipped: all
+ scoped to an organization ID this source does not collect).
+
### Linear — needs confirmation
Eight tables. Two small additions unblock the cycle-time use case.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/canonical_descriptions.py
index 8dbe3716151b..5696de1ce100 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/canonical_descriptions.py
@@ -45,7 +45,112 @@ _STATS_COLUMNS = {
}
+# Objects that carry no delivery `status` of their own (creatives and media report their own
+# status fields instead).
+_UNSTATUSED_OBJECT_COLUMNS = {key: value for key, value in _ENTITY_COLUMNS.items() if key != "status"}
+
+# Columns added to a stats row by a `report_dimension` (delivery insights) request.
+_COUNTRY_DIMENSION_COLUMNS = {
+ "country": "ISO country code the metrics on this row are broken down by.",
+}
+
+_DEMOGRAPHIC_DIMENSION_COLUMNS = {
+ "age_bucket": "Age bucket the metrics on this row are broken down by (e.g. 13-17, 25-34, 35+).",
+ "gender": "Gender the metrics on this row are broken down by (e.g. female, male, unknown).",
+}
+
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "ad_accounts": {
+ "description": "The ad account the data is imported from, including the currency and timezone every spend and daily metric is reported in.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/ad-accounts",
+ "columns": {
+ **_ENTITY_COLUMNS,
+ "type": "Account type (DIRECT or PARTNER).",
+ "currency": "Currency the account is billed and reported in (e.g. USD, EUR, GBP).",
+ "timezone": "Timezone used for the account's reporting day boundaries.",
+ "organization_id": "ID of the organization that owns the ad account.",
+ "advertiser": "Name of the advertiser the account runs ads for.",
+ "advertiser_organization_id": "Organization ID of the selected advertiser.",
+ "billing_type": "Billing model for the account (IO or REVOLVING).",
+ "billing_center_id": "ID of the billing center the account bills through.",
+ "funding_source_ids": "IDs of the funding sources attached to the account.",
+ "lifetime_spend_cap_micro": "Lifetime spend cap for the account, in micro-currency.",
+ "regulations": "Regulated-category settings (credit, housing, employment) applied to the account.",
+ "agency_representing_client": "Whether the account is run by an agency on behalf of a client.",
+ "test": "Whether this is a test ad account, which can never serve live ads.",
+ },
+ },
+ "creatives": {
+ "description": "A creative — the media, headline, and call to action an ad renders. Join to `ads.creative_id` to attribute performance to what people actually saw.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/creatives",
+ "columns": {
+ **_UNSTATUSED_OBJECT_COLUMNS,
+ "ad_account_id": "ID of the ad account that owns the creative.",
+ "type": "Creative type (e.g. SNAP_AD, APP_INSTALL, WEB_VIEW, COLLECTION, LENS).",
+ "headline": "Headline displayed under the brand name.",
+ "brand_name": "Brand name shown on the creative.",
+ "call_to_action": "Call to action shown on the swipe-up button.",
+ "top_snap_media_id": "ID of the media used as the top snap.",
+ "top_snap_crop_position": "How the top snap media is cropped (OPTIMIZED, MIDDLE, TOP, BOTTOM).",
+ "shareable": "Whether users are allowed to share the ad with friends.",
+ "forced_view_eligibility": "Whether the creative can be used as a Commercial (FULL_DURATION, SIX_SECONDS, NONE).",
+ "preview_creative_id": "ID of the preview creative, used by Story Ads.",
+ "packaging_status": "Processing status of the creative's media packaging.",
+ "review_status": "Ad review status of the creative.",
+ "profile_properties": "Public profile attached to the creative.",
+ "web_view_properties": "Web view attachment settings, for WEB_VIEW creatives.",
+ "app_install_properties": "App install attachment settings, for APP_INSTALL creatives.",
+ "deep_link_properties": "Deep link attachment settings, for DEEP_LINK creatives.",
+ "lead_generation_form_id": "ID of the lead generation form, for LEAD_GENERATION creatives.",
+ },
+ },
+ "media": {
+ "description": "A media asset (video, image, or lens package) owned by the ad account. One media asset can be used by several creatives.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/media",
+ "columns": {
+ **_UNSTATUSED_OBJECT_COLUMNS,
+ "ad_account_id": "ID of the ad account that owns the media.",
+ "type": "Media type (VIDEO, IMAGE, LENS_PACKAGE, PLAYABLE).",
+ "media_status": "Upload status of the media (PENDING_UPLOAD or READY).",
+ "file_name": "File name of the uploaded asset.",
+ "download_link": "URL the media file can be downloaded from.",
+ "file_size_in_bytes": "Size of the uploaded file, in bytes.",
+ "duration_in_seconds": "Duration of the asset, for video media.",
+ "image_metadata": "Width, height, and format of the asset, for image media.",
+ "video_metadata": "Width, height, rotation, and loudness of the asset, for video media.",
+ "media_usages": "The creative slots this media can be used in (e.g. TOP_SNAP, APP_INSTALL_ICON).",
+ "lens_package_metadata": "Metadata for lens media created in Lens Studio.",
+ "is_demo_media": "Whether the asset is Snapchat-provided demo media.",
+ "visibility": "Whether the media is visible in the ad account.",
+ },
+ },
+ "audience_segments": {
+ "description": "An audience segment (customer list, lookalike, engagement, or pixel-based) that ad squads can target.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/audience-creation/customer-lists",
+ "columns": {
+ **_ENTITY_COLUMNS,
+ "ad_account_id": "ID of the ad account that owns the segment.",
+ "description": "Free-text description of the segment.",
+ "source_type": "How the segment was built (e.g. FIRST_PARTY, LOOKALIKE, ENGAGEMENT, PIXEL).",
+ "status": "Status of the segment (e.g. PENDING, ACTIVE).",
+ "upload_status": "Whether uploaded users have been processed (NO_UPLOAD, PROCESSING, COMPLETE).",
+ "targetable_status": "Whether the segment can be targeted (NOT_READY, TOO_FEW_USERS, READY).",
+ "retention_in_days": "Number of days a user stays in the segment.",
+ "approximate_number_users": "Approximate number of users matched into the segment.",
+ },
+ },
+ "pixels": {
+ "description": "A Snap Pixel — the tag that ties website conversions back to the ads people saw. Join a pixel to the conversion metrics on the stats tables.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/snap-pixel",
+ "columns": {
+ **_ENTITY_COLUMNS,
+ "ad_account_id": "ID of the ad account the pixel belongs to.",
+ "status": "Configured status of the pixel.",
+ "effective_status": "Status the pixel is actually serving with.",
+ "pixel_javascript": "The pixel's JavaScript snippet, as installed on the advertiser's site.",
+ },
+ },
"campaigns": {
"description": "An advertising campaign — the top-level container that holds ad squads and sets the schedule and objective.",
"docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/campaigns",
@@ -102,4 +207,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/measurement",
"columns": dict(_STATS_COLUMNS),
},
+ "campaign_stats_daily_country": {
+ "description": "Daily delivery insights per campaign and country. Estimated figures that need at least 30 impressions in a day, so totals will not match campaign_stats_daily exactly.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/measurement",
+ "columns": {**_STATS_COLUMNS, **_COUNTRY_DIMENSION_COLUMNS},
+ },
+ "campaign_stats_daily_demographics": {
+ "description": "Daily delivery insights per campaign, age bucket, and gender. Estimated figures that need at least 30 impressions in a day, so totals will not match campaign_stats_daily exactly.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/measurement",
+ "columns": {**_STATS_COLUMNS, **_DEMOGRAPHIC_DIMENSION_COLUMNS},
+ },
+ "ad_stats_daily_country": {
+ "description": "Daily delivery insights per ad and country. Estimated figures that need at least 30 impressions in a day, so totals will not match ad_stats_daily exactly.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/measurement",
+ "columns": {**_STATS_COLUMNS, **_COUNTRY_DIMENSION_COLUMNS},
+ },
+ "ad_stats_daily_demographics": {
+ "description": "Daily delivery insights per ad, age bucket, and gender. Estimated figures that need at least 30 impressions in a day, so totals will not match ad_stats_daily exactly.",
+ "docs_url": "https://developers.snap.com/api/marketing-api/Ads-API/measurement",
+ "columns": {**_STATS_COLUMNS, **_DEMOGRAPHIC_DIMENSION_COLUMNS},
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/settings.py
index f568a840e124..3d99468f4e49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/settings.py
@@ -116,6 +116,35 @@ METRICS_FIELDS = [
SNAPCHAT_STATS_METRICS = ",".join(METRICS_FIELDS)
+# Delivery insights (`report_dimension`) requests use a smaller metric set than the totals
+# tables: Snapchat documents insights support for the delivery and core conversion metrics
+# below, and a breakdown row exists per dimension value per day, so every extra metric
+# multiplies the payload.
+# Docs: https://developers.snap.com/api/marketing-api/Ads-API/measurement
+INSIGHTS_METRICS_FIELDS = [
+ "impressions",
+ "uniques",
+ "swipes",
+ "swipe_up_percent",
+ "spend",
+ "video_views",
+ "quartile_1",
+ "quartile_2",
+ "quartile_3",
+ "view_completion",
+ "total_installs",
+ "conversion_purchases",
+ "conversion_purchases_value",
+ "conversion_sign_ups",
+ "conversion_add_cart",
+ "conversion_view_content",
+ "conversion_start_checkout",
+ "conversion_page_views",
+ "conversion_app_opens",
+]
+
+SNAPCHAT_INSIGHTS_METRICS = ",".join(INSIGHTS_METRICS_FIELDS)
+
class EndpointType(str, Enum):
ACCOUNT = "account"
@@ -132,6 +161,77 @@ class EndpointConfig:
partition_format: Optional[PartitionFormat] = None
partition_size: int = 1
endpoint_type: Optional[EndpointType] = None
+ # Snapchat wraps each list item in a singular key (`{"creative": {...}}`). When set, the
+ # entity transform unwraps that key instead of guessing from the campaign/adsquad/ad set.
+ entity_key: Optional[str] = None
+ should_sync_default: bool = True
+
+
+# The column each `report_dimension` adds to a breakdown row, which the row's primary key
+# needs on top of the entity id and day.
+_DIMENSION_PRIMARY_KEYS: dict[str, list[str]] = {
+ "country": ["country"],
+ "age,gender": ["age_bucket", "gender"],
+}
+
+
+def _stats_dimension_endpoint(
+ name: str,
+ breakdown: str,
+ report_dimension: str,
+) -> EndpointConfig:
+ """Build a delivery-insights stats endpoint broken down by one reporting dimension.
+
+ Only one `report_dimension` can be requested per call (age and gender being the one
+ documented pair), so each dimension is its own table rather than an extra column on the
+ existing totals tables.
+ Docs: https://developers.snap.com/api/marketing-api/Ads-API/measurement
+ """
+ return EndpointConfig(
+ resource={
+ "name": name,
+ "table_name": name,
+ "primary_key": ["id", "start_time", *_DIMENSION_PRIMARY_KEYS[report_dimension]],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}/stats",
+ "method": "GET",
+ "params": {
+ "granularity": "DAY",
+ "fields": SNAPCHAT_INSIGHTS_METRICS,
+ "breakdown": breakdown,
+ "report_dimension": report_dimension,
+ "start_time": "{start_time}",
+ "end_time": "{end_time}",
+ # Insights fan out one row per dimension value per day, so zero-data rows
+ # are dropped here rather than stored.
+ "omit_empty": "true",
+ "limit": 1000,
+ },
+ "data_selector": "timeseries_stats",
+ "incremental": {
+ "cursor_path": "start_time",
+ "start_param": "start_time",
+ "end_param": "end_time",
+ },
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=[
+ {
+ "label": "start_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ partition_keys=["start_time"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.STATS,
+ # Breakdowns multiply every day by the number of dimension values, so they stay opt-in.
+ should_sync_default=False,
+ )
SNAPCHAT_ADS_CONFIG: dict[str, EndpointConfig] = {
@@ -204,6 +304,120 @@ SNAPCHAT_ADS_CONFIG: dict[str, EndpointConfig] = {
partition_size=1,
endpoint_type=EndpointType.ENTITY,
),
+ "ad_accounts": EndpointConfig(
+ resource={
+ # Docs: https://developers.snap.com/api/marketing-api/Ads-API/ad-accounts
+ "name": "ad_accounts",
+ "table_name": "ad_accounts",
+ "primary_key": ["id"],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}",
+ "method": "GET",
+ "data_selector": "adaccounts",
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=None,
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.ENTITY,
+ entity_key="adaccount",
+ ),
+ "creatives": EndpointConfig(
+ resource={
+ # Docs: https://developers.snap.com/api/marketing-api/Ads-API/creatives
+ "name": "creatives",
+ "table_name": "creatives",
+ "primary_key": ["id"],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}/creatives",
+ "method": "GET",
+ "params": {
+ "limit": 1000,
+ },
+ "data_selector": "creatives",
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=None,
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.ENTITY,
+ entity_key="creative",
+ ),
+ "media": EndpointConfig(
+ resource={
+ # Docs: https://developers.snap.com/api/marketing-api/Ads-API/media
+ "name": "media",
+ "table_name": "media",
+ "primary_key": ["id"],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}/media",
+ "method": "GET",
+ "params": {
+ "limit": 1000,
+ },
+ "data_selector": "media",
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=None,
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.ENTITY,
+ entity_key="media",
+ ),
+ "audience_segments": EndpointConfig(
+ resource={
+ # Docs: https://developers.snap.com/api/marketing-api/Ads-API/audience-creation/customer-lists
+ "name": "audience_segments",
+ "table_name": "audience_segments",
+ "primary_key": ["id"],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}/segments",
+ "method": "GET",
+ "params": {
+ "limit": 1000,
+ },
+ "data_selector": "segments",
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=None,
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.ENTITY,
+ entity_key="segment",
+ ),
+ "pixels": EndpointConfig(
+ resource={
+ # Docs: https://developers.snap.com/api/marketing-api/Ads-API/snap-pixel
+ "name": "pixels",
+ "table_name": "pixels",
+ "primary_key": ["id"],
+ "endpoint": {
+ "path": "/adaccounts/{ad_account_id}/pixels",
+ "method": "GET",
+ "data_selector": "pixels",
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=None,
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ partition_size=1,
+ endpoint_type=EndpointType.ENTITY,
+ entity_key="pixel",
+ ),
"campaign_stats_daily": EndpointConfig(
resource={
# Docs: https://developers.snap.com/api/marketing-api/Ads-API/measurement
@@ -327,4 +541,16 @@ SNAPCHAT_ADS_CONFIG: dict[str, EndpointConfig] = {
partition_size=1,
endpoint_type=EndpointType.STATS,
),
+ "campaign_stats_daily_country": _stats_dimension_endpoint(
+ "campaign_stats_daily_country", breakdown="campaign", report_dimension="country"
+ ),
+ "campaign_stats_daily_demographics": _stats_dimension_endpoint(
+ "campaign_stats_daily_demographics", breakdown="campaign", report_dimension="age,gender"
+ ),
+ "ad_stats_daily_country": _stats_dimension_endpoint(
+ "ad_stats_daily_country", breakdown="ad", report_dimension="country"
+ ),
+ "ad_stats_daily_demographics": _stats_dimension_endpoint(
+ "ad_stats_daily_demographics", breakdown="ad", report_dimension="age,gender"
+ ),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py
index b3d67e62112d..7deb3169fa7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py
@@ -245,7 +245,10 @@ def _iter_rows(
rows = list(page)
transformed = SnapchatStatsResource.apply_stream_transformations(
- endpoint_type, rows, currency=account_currency
+ endpoint_type,
+ rows,
+ currency=account_currency,
+ entity_key=SNAPCHAT_ADS_CONFIG[endpoint].entity_key,
)
if transformed:
yield transformed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
index 6ee06eef8a4a..f9cb2393caf2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/source.py
@@ -187,6 +187,7 @@ class SnapchatAdsSource(ResumableSource[SnapchatAdsSourceConfig, SnapchatResumeC
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 SNAPCHAT_ADS_CONFIG.values()
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
index 3f201bca003d..19b570bda75e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py
@@ -1,6 +1,6 @@
from collections.abc import Callable, Iterator
from datetime import datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
import pytest
from unittest.mock import MagicMock, patch
@@ -11,6 +11,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.int
IntegrationAccountListingError,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.settings import (
+ SNAPCHAT_ADS_CONFIG,
+ EndpointType,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads import (
SnapchatResumeConfig,
_iter_rows,
@@ -19,7 +23,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_a
from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.utils import (
AD_ACCOUNTS_PAGE_LIMIT,
MAX_AD_ACCOUNT_PAGES,
+ SnapchatAdsPaginator,
SnapchatDateRangeManager,
+ SnapchatStatsResource,
format_stats_day_boundary,
list_ad_accounts,
)
@@ -577,3 +583,231 @@ class TestListAdAccounts:
# The token-bearing request to the untrusted host is never made.
assert session.get.call_count == 1
+
+
+def _breakdown_page(entity_id: str, breakdown_key: str, entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [
+ {
+ "timeseries_stat": {
+ "breakdown_stats": {
+ breakdown_key: [
+ {
+ "id": entity_id,
+ "type": breakdown_key.upper(),
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-03T00:00:00-07:00",
+ "timeseries": entries,
+ }
+ ]
+ }
+ }
+ }
+ ]
+
+
+class TestStatsDimensionTransform:
+ def test_dimension_stats_expand_to_one_row_per_dimension_value(self) -> None:
+ # A `report_dimension` response replaces the day's `stats` object with a
+ # `dimension_stats` array. Reading only `stats` would sync the breakdown tables empty.
+ page = _breakdown_page(
+ "campaign-1",
+ "campaign",
+ [
+ {
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-02T00:00:00-07:00",
+ "dimension_stats": [
+ {"impressions": 10, "swipes": 1, "country": "us"},
+ {"impressions": 4, "swipes": 0, "country": "gb"},
+ ],
+ },
+ {
+ "start_time": "2026-04-02T00:00:00-07:00",
+ "end_time": "2026-04-03T00:00:00-07:00",
+ "dimension_stats": [{"impressions": 7, "swipes": 2, "country": "us"}],
+ },
+ ],
+ )
+
+ rows = SnapchatStatsResource.transform_stats_reports(page, currency="USD")
+
+ assert rows == [
+ {
+ "id": "campaign-1",
+ "type": "CAMPAIGN",
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-02T00:00:00-07:00",
+ "impressions": 10,
+ "swipes": 1,
+ "country": "us",
+ "currency": "USD",
+ },
+ {
+ "id": "campaign-1",
+ "type": "CAMPAIGN",
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-02T00:00:00-07:00",
+ "impressions": 4,
+ "swipes": 0,
+ "country": "gb",
+ "currency": "USD",
+ },
+ {
+ "id": "campaign-1",
+ "type": "CAMPAIGN",
+ "start_time": "2026-04-02T00:00:00-07:00",
+ "end_time": "2026-04-03T00:00:00-07:00",
+ "impressions": 7,
+ "swipes": 2,
+ "country": "us",
+ "currency": "USD",
+ },
+ ]
+
+ def test_totals_rows_still_read_the_stats_object(self) -> None:
+ # The existing totals tables must keep flattening `stats` unchanged.
+ page = _breakdown_page(
+ "adsquad-1",
+ "adsquad",
+ [
+ {
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-02T00:00:00-07:00",
+ "stats": {"impressions": 21, "spend": 500},
+ }
+ ],
+ )
+
+ assert SnapchatStatsResource.transform_stats_reports(page) == [
+ {
+ "id": "adsquad-1",
+ "type": "ADSQUAD",
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-02T00:00:00-07:00",
+ "impressions": 21,
+ "spend": 500,
+ }
+ ]
+
+ def test_entity_level_dimension_stats_are_kept_and_dated_from_the_entity(self) -> None:
+ # Snapchat only documents delivery insights at TOTAL granularity, where the breakdown
+ # hangs off the entity with no `timeseries`. Those rows must not be silently dropped.
+ page = _breakdown_page("ad-1", "ad", [])
+ page[0]["timeseries_stat"]["breakdown_stats"]["ad"][0]["dimension_stats"] = [
+ {"impressions": 9, "age_bucket": "25-34", "gender": "female"}
+ ]
+
+ assert SnapchatStatsResource.transform_stats_reports(page) == [
+ {
+ "id": "ad-1",
+ "type": "AD",
+ "start_time": "2026-04-01T00:00:00-07:00",
+ "end_time": "2026-04-03T00:00:00-07:00",
+ "impressions": 9,
+ "age_bucket": "25-34",
+ "gender": "female",
+ }
+ ]
+
+
+class TestEntityUnwrapping:
+ @parameterized.expand(
+ [
+ ("creative", "creatives"),
+ ("media", "media"),
+ ("segment", "audience_segments"),
+ ("pixel", "pixels"),
+ ("adaccount", "ad_accounts"),
+ ]
+ )
+ def test_configured_entity_key_unwraps_the_object(self, wrapper_key: str, endpoint: str) -> None:
+ # Snapchat wraps each list item in a singular key that differs per endpoint. Without the
+ # configured key these tables would store the wrapper instead of the object.
+ assert SNAPCHAT_ADS_CONFIG[endpoint].entity_key == wrapper_key
+
+ rows = SnapchatStatsResource.apply_stream_transformations(
+ EndpointType.ENTITY,
+ [{"sub_request_status": "SUCCESS", wrapper_key: {"id": "obj-1", "name": "Object"}}],
+ entity_key=wrapper_key,
+ )
+
+ assert rows == [{"id": "obj-1", "name": "Object"}]
+
+ def test_campaign_style_wrappers_still_unwrap_without_a_configured_key(self) -> None:
+ rows = SnapchatStatsResource.apply_stream_transformations(
+ EndpointType.ENTITY,
+ [{"sub_request_status": "SUCCESS", "campaign": {"id": "c-1"}}],
+ )
+
+ assert rows == [{"id": "c-1"}]
+
+
+class TestBreakdownEndpointConfig:
+ _DIMENSION_COLUMNS = {"country": ["country"], "age,gender": ["age_bucket", "gender"]}
+
+ @parameterized.expand(
+ [
+ "campaign_stats_daily_country",
+ "campaign_stats_daily_demographics",
+ "ad_stats_daily_country",
+ "ad_stats_daily_demographics",
+ ]
+ )
+ def test_primary_key_covers_the_requested_dimension(self, endpoint: str) -> None:
+ # A breakdown row is only unique per entity, day, and dimension value. Dropping the
+ # dimension from the key collapses every country (or age/gender) onto one row on merge.
+ config = SNAPCHAT_ADS_CONFIG[endpoint]
+ params = cast(dict[str, Any], config.resource["endpoint"])["params"]
+ report_dimension = cast(str, params["report_dimension"])
+
+ assert config.resource["primary_key"] == [
+ "id",
+ "start_time",
+ *self._DIMENSION_COLUMNS[report_dimension],
+ ]
+
+
+class TestSchemaDefaults:
+ def test_breakdown_tables_are_opt_in_and_the_rest_stay_on(self) -> None:
+ # Breakdown tables multiply every day by its dimension values, so they must not be
+ # pre-selected for every new connection.
+ schemas = SnapchatAdsSource().get_schemas(config=MagicMock(), team_id=1)
+ by_name = {schema.name: schema.should_sync_default for schema in schemas}
+
+ assert by_name == {
+ "campaigns": True,
+ "ad_squads": True,
+ "ads": True,
+ "ad_accounts": True,
+ "creatives": True,
+ "media": True,
+ "audience_segments": True,
+ "pixels": True,
+ "campaign_stats_daily": True,
+ "ad_squad_stats_daily": True,
+ "ad_stats_daily": True,
+ "campaign_stats_daily_country": False,
+ "campaign_stats_daily_demographics": False,
+ "ad_stats_daily_country": False,
+ "ad_stats_daily_demographics": False,
+ }
+
+
+class TestPaginatorRequestStatus:
+ @parameterized.expand(["SUCCESS", "success"])
+ def test_next_link_is_followed_whatever_the_case_of_request_status(self, request_status: str) -> None:
+ # Snapchat's docs show this status in both cases across endpoints; a case-sensitive
+ # check would fail the sync on the endpoints that report it lowercase.
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = {
+ "request_status": request_status,
+ "paging": {"next_link": "https://adsapi.snapchat.com/v1/adaccounts/a/creatives?cursor=abc"},
+ }
+
+ paginator = SnapchatAdsPaginator()
+ paginator.update_state(response)
+
+ assert paginator.get_resume_state() == {
+ "next_link": "https://adsapi.snapchat.com/v1/adaccounts/a/creatives?cursor=abc"
+ }
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
index 7eda176f2985..2969a4972156 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py
@@ -275,7 +275,28 @@ class SnapchatStatsResource:
"""Handles stats-specific operations like flattening and date chunking."""
@staticmethod
- def transform_stats_reports(reports: list[dict[str, Any]], currency: str | None = None) -> list[dict[str, Any]]:
+ def _stat_rows(entry: dict[str, Any], base: dict[str, Any], currency: str | None) -> list[dict[str, Any]]:
+ """Turn one stats entry into rows: one per dimension value, or a single totals row.
+
+ A `report_dimension` request replaces the entry's `stats` object with a
+ `dimension_stats` array, where each element carries the metrics plus the dimension
+ columns it is broken down by (`country`, or `age_bucket` + `gender`).
+ """
+ dimension_stats = entry.get("dimension_stats")
+ if dimension_stats is None:
+ rows = [{**base, **entry.get("stats", {})}]
+ else:
+ rows = [{**base, **dimension_stat} for dimension_stat in dimension_stats]
+
+ if currency:
+ for row in rows:
+ row["currency"] = currency
+ return rows
+
+ @classmethod
+ def transform_stats_reports(
+ cls, reports: list[dict[str, Any]], currency: str | None = None
+ ) -> list[dict[str, Any]]:
"""Flatten nested timeseries_stat structure to individual daily records.
Handles the breakdown response format where stats are nested inside
@@ -294,31 +315,38 @@ class SnapchatStatsResource:
entities = [timeseries_stat]
for entity in entities:
- entity_id = entity.get("id")
- entity_type = entity.get("type")
+ base = {"id": entity.get("id"), "type": entity.get("type")}
+ timeseries = entity.get("timeseries", [])
- for ts_entry in entity.get("timeseries", []):
- flat_record = {
- "id": entity_id,
- "type": entity_type,
+ for ts_entry in timeseries:
+ entry_base = {
+ **base,
"start_time": ts_entry.get("start_time"),
"end_time": ts_entry.get("end_time"),
- **ts_entry.get("stats", {}),
}
- if currency:
- flat_record["currency"] = currency
- processed_reports.append(flat_record)
+ processed_reports.extend(cls._stat_rows(ts_entry, entry_base, currency))
+
+ # Delivery-insights responses are only documented at TOTAL granularity, where
+ # the breakdown hangs off the entity itself rather than a per-day entry. Keep
+ # those rows instead of dropping them, dated with the entity's own range.
+ if not timeseries and entity.get("dimension_stats") is not None:
+ entity_base = {
+ **base,
+ "start_time": entity.get("start_time"),
+ "end_time": entity.get("end_time"),
+ }
+ processed_reports.extend(cls._stat_rows(entity, entity_base, currency))
return processed_reports
@staticmethod
- def transform_entity_reports(reports: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Extract inner objects from wrapped entity responses (campaign/adsquad/ad)."""
+ def transform_entity_reports(reports: list[dict[str, Any]], entity_key: str | None = None) -> list[dict[str, Any]]:
+ """Extract inner objects from wrapped entity responses (campaign/adsquad/ad/...)."""
processed_reports = []
for report in reports:
# Each item is wrapped: {"campaign": {...}} or {"adsquad": {...}} or {"ad": {...}}
- inner_keys = ["campaign", "adsquad", "ad"]
+ inner_keys = [entity_key] if entity_key else ["campaign", "adsquad", "ad"]
for key in inner_keys:
if key in report:
processed_reports.append(report[key])
@@ -331,7 +359,11 @@ class SnapchatStatsResource:
@classmethod
def apply_stream_transformations(
- cls, endpoint_type: EndpointType, reports: Iterable[Any], currency: str | None = None
+ cls,
+ endpoint_type: EndpointType,
+ reports: Iterable[Any],
+ currency: str | None = None,
+ entity_key: str | None = None,
) -> list[dict[str, Any]]:
"""Apply transformations based on endpoint type."""
reports_list = list(reports)
@@ -340,7 +372,7 @@ class SnapchatStatsResource:
case EndpointType.STATS:
return cls.transform_stats_reports(reports_list, currency=currency)
case EndpointType.ENTITY:
- return cls.transform_entity_reports(reports_list)
+ return cls.transform_entity_reports(reports_list, entity_key=entity_key)
case EndpointType.ACCOUNT:
return reports_list
@@ -449,7 +481,8 @@ class SnapchatAdsPaginator(BasePaginator):
"""Update pagination state from Snapchat API response."""
try:
json_data = response.json()
- request_status = json_data.get("request_status", "")
+ # Snapchat documents this status in both cases across endpoints, so compare case-insensitively.
+ request_status = str(json_data.get("request_status", "")).upper()
if request_status == "SUCCESS":
paging = json_data.get("paging", {})