:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 10 missing Meta Ads tables (#77273)
Tom Owers6df06b295f65
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.mdindex 18b5f6e2daa1..58951efb6520 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@@ -176,23 +176,30 @@ on 2026-08-04, using each resource's attributed/segmenting resource lists and thexisting `*_stats` table selects `segments.device`)- [x] Conversion stats segmented by `conversion_action` (we have the actions but not their stats).-### Meta Ads — needs confirmation--Six tables: `campaigns`, `adsets`, `ads`, and one stats table each.-The thinnest coverage of any tier 1 source, and the two biggest omissions are structural.--- [ ] `adcreatives` — no creative metadata at all. You cannot tell what an ad looked like.-- [ ] Insight breakdowns: `age`, `gender`, `country`, `region`, `publisher_platform`, `platform_position`, `impression_device`. None available.-- [ ] Action breakdowns: `actions`, `action_values`, `cost_per_action_type` — conversion outcomes by type.-- [ ] `ad_account` — spend caps, currency, timezone, funding. Currency especially, since stats are meaningless without it.-- [ ] Lead gen forms and `leads` — the payload of Meta lead ads.-- [ ] `customaudiences` and saved audiences.-- [ ] `adimages`, `advideos` — creative assets.-- [ ] `adspixels` and custom conversions.-- [ ] `adrules_library` — automated rules.--`schemas.py` also carries a `AdsetStats = "adset_stats" # TODO: remove this` marker worth resolving-while in here.+### Meta Ads — spec-verified++Diffed against the [Marketing API reference](https://developers.facebook.com/docs/marketing-api/reference/)+and the [Insights breakdowns reference](https://developers.facebook.com/docs/marketing-api/insights/breakdowns/)+on 2026-08-04, against API version v25.0.++Have: `campaigns`, `campaign_stats`, `adsets`, `adset_stats`, `ads`, `ad_stats`, `ad_account`,+`ad_creatives`, `ad_images`, `ads_pixels`, `custom_conversions`, `campaign_stats_by_age_gender`,+`campaign_stats_by_country`, `campaign_stats_by_region`, `campaign_stats_by_platform`,+`campaign_stats_hourly`.++- [x] `adcreatives` — shipped as `ad_creatives`.+- [x] Insight breakdowns: `age`, `gender`, `country`, `region`, `publisher_platform`, `platform_position`, `impression_device`, plus hourly. Shipped as five campaign-level breakdown tables, all off by default. `device_platform` is not in Meta's valid-permutation table, so it was dropped.+- [ ] Action breakdowns: `actions`, `action_values`, `cost_per_action_type` (skipped: already synced. All three are AdsInsights fields and are in every stats table's field list today. The `action_breakdowns` parameter only adds keys inside those nested arrays, it does not produce rows.)+- [x] `ad_account` — shipped, including currency, timezone, spend caps and funding.+- [ ] Lead gen forms and `leads` (skipped: reading them needs `leads_retrieval` plus Page-level access, and our OAuth consent requests `ads_read` only, so every sync would 403.)+- [ ] `customaudiences` and saved audiences (skipped: gated behind `ads_management` and the account having accepted the Custom Audience terms of service, neither of which our consent covers.)+- [x] `adimages` — shipped as `ad_images`.+- [ ] `advideos` (skipped: AdVideo is a Page video object whose readable fields depend on video permissions we do not request, and its useful fields are short-lived URLs rather than warehouse-shaped data.)+- [x] `adspixels` and custom conversions — shipped as `ads_pixels` and `custom_conversions`.+- [ ] `adrules_library` (skipped: automated rules are configuration objects, not analytics data, and reading the rules library needs `ads_management`.)++`schemas.py` still carries a `AdsetStats = "adset_stats" # TODO: remove this` marker. Left alone:+the table ships and has live syncs, so removing it would orphan synced data.### GitHub — spec-verifieddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/canonical_descriptions.pyindex 32c34277e289..fc5352b1bae7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/canonical_descriptions.py@@ -8,7 +8,10 @@ Keyed by the resource names in `schemas.py` `MetaAdsResource`, which match thefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)-from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import MetaAdsResource+from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (+ HOURLY_BREAKDOWN_STATS_FIELDS,+ MetaAdsResource,+)# Columns shared by every Insights (stats) endpoint; merged into each stats entry._COMMON_STATS_COLUMNS = {@@ -40,6 +43,17 @@ def _stats_columns(**overrides: str) -> dict[str, str]:return {**_COMMON_STATS_COLUMNS, **overrides}+_INSIGHTS_BREAKDOWNS_DOCS_URL = "https://developers.facebook.com/docs/marketing-api/insights/breakdowns/"++# The hourly table syncs a reduced metric set, so its descriptions are filtered to match.+_HOURLY_COLUMN_NAMES = {*HOURLY_BREAKDOWN_STATS_FIELDS, "hourly_stats_aggregated_by_advertiser_time_zone"}+++def _campaign_breakdown_columns(**breakdowns: str) -> dict[str, str]:+ """Campaign-level breakdown tables share the campaign_stats columns, plus their own dimensions."""+ return _stats_columns(campaign_id="The ID of the campaign the metrics belong to.", **breakdowns)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {MetaAdsResource.Campaigns: {"description": "An advertising campaign in Meta Ads, defining the objective for its ad sets and ads.",@@ -138,4 +152,171 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {video_p100_watched_actions="The number of times the video was watched to 100% of its length.",),},+ MetaAdsResource.AdAccount: {+ "description": "The Meta ad account this source syncs, including its currency, timezone and spend limits.",+ "docs_url": "https://developers.facebook.com/docs/marketing-api/reference/ad-account/",+ "columns": {+ "id": "The ad account ID, prefixed with act_.",+ "account_id": "The ad account ID without the act_ prefix.",+ "name": "The name of the ad account.",+ "account_status": "Numeric status of the account (1 active, 2 disabled, 3 unsettled, 101 closed).",+ "currency": "The currency the account is billed in. Every spend and value metric is denominated in it.",+ "timezone_id": "The ID of the account's timezone.",+ "timezone_name": "The name of the account's timezone, for example America/Los_Angeles.",+ "timezone_offset_hours_utc": "The account timezone's offset from UTC, in hours.",+ "amount_spent": "Total amount spent by the account, in the account's minor currency unit.",+ "balance": "Outstanding balance on the account, in the account's minor currency unit.",+ "spend_cap": "The account-level spend cap, in the account's minor currency unit.",+ "min_campaign_group_spend_cap": "The minimum spend cap allowed on a campaign in this account.",+ "min_daily_budget": "The minimum daily budget allowed in this account.",+ "created_time": "Time the ad account was created.",+ "business_country_code": "Country code of the business that owns the account.",+ "business_name": "Name of the business that owns the account.",+ "business": "The business that owns the account.",+ "funding_source_details": "Details of the payment method funding the account.",+ "disable_reason": "Why the account was disabled, if it was.",+ "is_prepay_account": "Whether the account is prepaid.",+ "tos_accepted": "Which Meta terms of service the account has accepted.",+ "capabilities": "Capabilities granted to the account.",+ "owner": "ID of the business or person that owns the account.",+ },+ },+ MetaAdsResource.AdCreatives: {+ "description": "An ad creative in Meta Ads: the copy, imagery and call to action an ad is built from.",+ "docs_url": "https://developers.facebook.com/docs/marketing-api/reference/ad-creative/",+ "columns": {+ "id": "Unique identifier for the ad creative.",+ "account_id": "The ID of the ad account the creative belongs to.",+ "name": "The name of the creative as it appears in the account's library.",+ "status": "The status of the creative (ACTIVE, IN_PROCESS, WITH_ISSUES, DELETED).",+ "object_type": "The type of Facebook object the creative advertises (e.g. PAGE, SHARE, VIDEO).",+ "object_story_id": "ID of the Page post used in the ad.",+ "effective_object_story_id": "ID of the Page post actually delivered, including unpublished posts.",+ "object_story_spec": "Specification of the unpublished Page post backing the creative.",+ "thumbnail_url": "URL of a thumbnail image for the creative.",+ "image_url": "URL of the creative's image.",+ "image_hash": "Hash of the creative's image, joining to the ad_images table.",+ "video_id": "ID of the video used in the creative.",+ "body": "The body text of the ad.",+ "title": "The headline of a link ad.",+ "call_to_action_type": "Type of call to action button on the ad (e.g. SHOP_NOW, LEARN_MORE).",+ "link_url": "The destination the ad links to.",+ "url_tags": "Query string parameters appended to the ad's URLs, typically UTM tags.",+ "instagram_permalink_url": "Permalink to the Instagram post run as an ad.",+ "actor_id": "The Page ID behind the creative.",+ "asset_feed_spec": "Asset combinations used for dynamic creative.",+ "degrees_of_freedom_spec": "Which automatic creative transformations are enabled.",+ "effective_authorization_category": "Whether the ad is categorized as political or issue advertising.",+ },+ },+ MetaAdsResource.AdImages: {+ "description": "An image in the ad account's image library, referenced by ad creatives via its hash.",+ "docs_url": "https://developers.facebook.com/docs/marketing-api/reference/ad-image/",+ "columns": {+ "id": "Identifier for the image, made up of the account ID and the image hash.",+ "hash": "Hash of the image. Ad creatives reference images by this value.",+ "account_id": "The ID of the ad account the image belongs to.",+ "name": "The filename of the image.",+ "url": "A temporary URL the image can be fetched from.",+ "url_128": "A temporary URL for a 128px version of the image.",+ "permalink_url": "A permanent URL for the image.",+ "width": "Width of the image as stored, in pixels.",+ "height": "Height of the image as stored, in pixels.",+ "original_width": "Width of the uploaded image before resizing, in pixels.",+ "original_height": "Height of the uploaded image before resizing, in pixels.",+ "status": "Status of the image (ACTIVE, INTERNAL, DELETED).",+ "created_time": "Time the image was uploaded.",+ "updated_time": "Time the image was last updated.",+ "creatives": "IDs of the ad creatives using this image.",+ "is_associated_creatives_in_adgroups": "Whether creatives using this image are attached to ads.",+ },+ },+ MetaAdsResource.AdsPixels: {+ "description": "A Meta pixel owned by the ad account, used to track website conversions.",+ "docs_url": "https://developers.facebook.com/docs/marketing-api/reference/ads-pixel/",+ "columns": {+ "id": "Unique identifier for the pixel.",+ "name": "The name of the pixel.",+ "code": "The pixel's base code snippet.",+ "creation_time": "Time the pixel was created.",+ "last_fired_time": "Time the pixel last fired.",+ "is_created_by_business": "Whether the pixel was created by a business rather than a person.",+ "is_unavailable": "Whether the pixel is unavailable.",+ "data_use_setting": "How data collected by the pixel may be used.",+ "enable_automatic_matching": "Whether automatic advanced matching is enabled.",+ "automatic_matching_fields": "Which fields are enabled for automatic advanced matching.",+ "owner_business": "The business that owns the pixel.",+ },+ },+ MetaAdsResource.CustomConversions: {+ "description": "A custom conversion defined on the ad account, mapping pixel or offline events to an outcome.",+ "docs_url": "https://developers.facebook.com/docs/marketing-api/reference/custom-conversion/",+ "columns": {+ "id": "Unique identifier for the custom conversion.",+ "account_id": "The ID of the ad account the custom conversion belongs to.",+ "name": "The name of the custom conversion.",+ "description": "The description of the custom conversion.",+ "creation_time": "Time the custom conversion was created.",+ "first_fired_time": "Time the custom conversion first fired.",+ "last_fired_time": "Time the custom conversion last fired.",+ "custom_event_type": "The standard event the conversion maps to (e.g. PURCHASE, LEAD, OTHER).",+ "default_conversion_value": "The value assigned to the conversion when the event carries none.",+ "event_source_type": "Where the events come from (e.g. pixel, app, offline).",+ "is_archived": "Whether the custom conversion is archived.",+ "is_unavailable": "Whether the custom conversion is unavailable.",+ "pixel": "The pixel the custom conversion is defined on.",+ "rule": "The rule matching events to this conversion.",+ "retention_days": "How many days of events the conversion retains.",+ "data_sources": "The data sources feeding the custom conversion.",+ "business": "The business that owns the custom conversion.",+ },+ },+ MetaAdsResource.CampaignStatsByAgeGender: {+ "description": "Daily campaign Insights split by the age and gender of the people reached.",+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,+ "columns": _campaign_breakdown_columns(+ age="Age bracket of the people the metrics cover (e.g. 25-34).",+ gender="Gender of the people the metrics cover (female, male, unknown).",+ ),+ },+ MetaAdsResource.CampaignStatsByCountry: {+ "description": "Daily campaign Insights split by the country the ads were delivered in.",+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,+ "columns": _campaign_breakdown_columns(+ country="Two-letter country code the metrics were delivered in.",+ ),+ },+ MetaAdsResource.CampaignStatsByRegion: {+ "description": "Daily campaign Insights split by the region, such as a state or province, the ads were delivered in.",+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,+ "columns": _campaign_breakdown_columns(+ region="Name of the region, such as a state or province, the metrics were delivered in.",+ ),+ },+ MetaAdsResource.CampaignStatsByPlatform: {+ "description": "Daily campaign Insights split by where the ads appeared and what device they were seen on.",+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,+ "columns": _campaign_breakdown_columns(+ publisher_platform="The platform the ads ran on (facebook, instagram, audience_network, messenger).",+ platform_position="The placement within the platform (e.g. feed, story, reels).",+ impression_device="The device the impression was served on (e.g. iphone, android_smartphone, desktop).",+ ),+ },+ MetaAdsResource.CampaignStatsHourly: {+ "description": (+ "Campaign Insights split by hour of the day in the advertiser's timezone. "+ "Meta does not report unique metrics such as reach and frequency with hourly breakdowns, "+ "so this table omits them."+ ),+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,+ "columns": {+ key: value+ for key, value in _campaign_breakdown_columns(+ hourly_stats_aggregated_by_advertiser_time_zone=(+ "The hour range the metrics cover, in the advertiser's timezone (e.g. 09:00:00 - 09:59:59)."+ ),+ ).items()+ if key in _HOURLY_COLUMN_NAMES+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.pyindex 4cdf413a7dcf..60cd96a761a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -186,10 +186,14 @@ class MetaAdsSchema:field_names: list[str]url: strextra_params: dict- partition_keys: list[str]- partition_mode: PartitionMode- partition_format: PartitionFormat- is_stats: bool+ # Endpoints with no stable datetime column (e.g. AdCreative) leave these unset and sync+ # unpartitioned, as do the one-row and lookup tables where partitioning buys nothing.+ partition_keys: list[str] | None = None+ partition_mode: PartitionMode | None = None+ partition_format: PartitionFormat | None = None+ is_stats: bool = False+ # The Graph API returns the node itself rather than a paged `data` list (`GET /act_<id>`).+ single_object: bool = False# Note: can make this static but keeping schemas.py to match other schema files for now@@ -198,25 +202,17 @@ def get_schemas() -> dict[str, MetaAdsSchema]:schemas: dict[str, MetaAdsSchema] = {}for resource_name, schema_def in RESOURCE_SCHEMAS.items():- field_names = schema_def["field_names"].copy()- primary_keys = schema_def["primary_keys"]- url = schema_def["url"]- extra_params = schema_def["extra_params"]- partition_keys = schema_def["partition_keys"]- partition_mode = schema_def["partition_mode"]- partition_format = schema_def["partition_format"]- is_stats = schema_def.get("is_stats", False)-schema = MetaAdsSchema(name=resource_name,- primary_keys=primary_keys,- field_names=field_names,- url=url,- extra_params=extra_params,- partition_keys=partition_keys,- partition_mode=partition_mode,- partition_format=partition_format,- is_stats=is_stats,+ primary_keys=schema_def["primary_keys"],+ field_names=schema_def["field_names"].copy(),+ url=schema_def["url"],+ extra_params=schema_def["extra_params"],+ partition_keys=schema_def.get("partition_keys"),+ partition_mode=schema_def.get("partition_mode"),+ partition_format=schema_def.get("partition_format"),+ is_stats=schema_def.get("is_stats", False),+ single_object=schema_def.get("single_object", False),)schemas[resource_name] = schema@@ -823,6 +819,18 @@ def _iter_time_range_pagination(_save(current_start, chunk_size_days, None)+def _fetch_single_object(url: str, params: dict, access_token: str) -> collections.abc.Generator[list[dict]]:+ """Read a Graph API node that returns the object itself instead of a paged ``data`` list.++ No pagination, no resume state and no shrink ladder: the response is a single row, so+ there is nothing to page through and nothing a smaller request could fix.+ """+ response = _get_initial_request(url, {**params, "access_token": access_token})+ if response.status_code != 200:+ _raise_meta_api_error(response)+ yield [response.json()]++def _make_paginated_api_request(url: str,params: dict,@@ -905,6 +913,11 @@ def meta_ads_source(formatted_url = schema.url.format(API_VERSION=MetaAdsIntegration.api_version, account_id=_clean_account_id(config.account_id))++ if schema.single_object:+ yield from _fetch_single_object(formatted_url, {"fields": ",".join(schema.field_names)}, access_token)+ return+params = {"fields": ",".join(schema.field_names),"limit": PAGE_LIMIT_FALLBACK_SIZES[0],diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.pyindex 252849ed1b3b..9037d23f0131 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py@@ -11,8 +11,29 @@ class MetaAdsResource(StrEnum):AdStats = "ad_stats"Ads = "ads"AdsetStats = "adset_stats" # TODO: remove this+ AdAccount = "ad_account"+ AdCreatives = "ad_creatives"+ AdImages = "ad_images"+ AdsPixels = "ads_pixels"+ CustomConversions = "custom_conversions"+ CampaignStatsByAgeGender = "campaign_stats_by_age_gender"+ CampaignStatsByCountry = "campaign_stats_by_country"+ CampaignStatsByRegion = "campaign_stats_by_region"+ CampaignStatsByPlatform = "campaign_stats_by_platform"+ CampaignStatsHourly = "campaign_stats_hourly"+# Insights broken down by a dimension. Each one multiplies the daily row count by the+# cardinality of its breakdown, and only some accounts care about any given dimension, so+# they stay off in the schema picker until a user asks for them.+BREAKDOWN_STATS_ENDPOINTS = (+ MetaAdsResource.CampaignStatsByAgeGender,+ MetaAdsResource.CampaignStatsByCountry,+ MetaAdsResource.CampaignStatsByRegion,+ MetaAdsResource.CampaignStatsByPlatform,+ MetaAdsResource.CampaignStatsHourly,+)+ENDPOINTS = (MetaAdsResource.Campaigns,MetaAdsResource.CampaignStats,@@ -20,41 +41,99 @@ ENDPOINTS = (MetaAdsResource.AdsetStats,MetaAdsResource.Ads,MetaAdsResource.AdStats,+ MetaAdsResource.AdAccount,+ MetaAdsResource.AdCreatives,+ MetaAdsResource.AdImages,+ MetaAdsResource.AdsPixels,+ MetaAdsResource.CustomConversions,+ *BREAKDOWN_STATS_ENDPOINTS,)INCREMENTAL_ENDPOINTS = (MetaAdsResource.AdStats,MetaAdsResource.AdsetStats,MetaAdsResource.CampaignStats,+ *BREAKDOWN_STATS_ENDPOINTS,)-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- MetaAdsResource.AdStats: [- {- "label": "date_start",- "type": IncrementalFieldType.Date,- "field": "date_start",- "field_type": IncrementalFieldType.Date,- }- ],- MetaAdsResource.AdsetStats: [- {- "label": "date_start",- "type": IncrementalFieldType.Date,- "field": "date_start",- "field_type": IncrementalFieldType.Date,- }- ],- MetaAdsResource.CampaignStats: [+SHOULD_SYNC_DEFAULT: dict[str, bool] = dict.fromkeys(BREAKDOWN_STATS_ENDPOINTS, False)+++def _date_start_incremental_field() -> list[IncrementalField]:+ return [{"label": "date_start","type": IncrementalFieldType.Date,"field": "date_start","field_type": IncrementalFieldType.Date,}- ],+ ]+++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ endpoint: _date_start_incremental_field() for endpoint in INCREMENTAL_ENDPOINTS}+# Insights metrics requested for every campaign-level breakdown table, mirroring `campaign_stats`.+# Breakdown dimensions are deliberately absent: Meta returns them as columns automatically and+# rejects the request when they are also passed in `fields`, since they are breakdowns rather+# than AdsInsights fields.+CAMPAIGN_BREAKDOWN_STATS_FIELDS = [+ "campaign_id",+ "account_id",+ "account_currency",+ "date_start",+ "date_stop",+ "impressions",+ "clicks",+ "spend",+ "reach",+ "frequency",+ "cpm",+ "cpc",+ "ctr",+ "cpp",+ "cost_per_unique_click",+ "unique_clicks",+ "unique_ctr",+ "actions",+ "conversions",+ "conversion_values",+ "cost_per_action_type",+ "action_values",+]++# Meta: "Hourly breakdowns do not support unique fields, which are any fields prepended with+# `unique_*`, `reach` or `frequency`." `cpp` and `cost_per_unique_click` are derived from those,+# so the hourly table asks for none of them rather than storing columns Meta zeroes out.+_HOURLY_UNSUPPORTED_FIELDS = {"reach", "frequency", "cpp", "cost_per_unique_click", "unique_clicks", "unique_ctr"}++HOURLY_BREAKDOWN_STATS_FIELDS = [f for f in CAMPAIGN_BREAKDOWN_STATS_FIELDS if f not in _HOURLY_UNSUPPORTED_FIELDS]+++def _campaign_breakdown_stats(breakdowns: list[str], field_names: list[str] | None = None) -> dict[str, Any]:+ """Campaign-level Insights split by `breakdowns`.++ Every breakdown dimension joins the primary key: a campaign/day pair now yields one row per+ combination of dimension values, so keying on `campaign_id + date_start` alone would collapse+ them into duplicates that merge multi-matches on every sync.+ """+ return {+ "primary_keys": ["campaign_id", "account_id", "date_start", *breakdowns],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}/insights",+ "extra_params": {+ "level": "campaign",+ "time_increment": 1, # daily+ "breakdowns": ",".join(breakdowns),+ },+ "field_names": field_names if field_names is not None else CAMPAIGN_BREAKDOWN_STATS_FIELDS,+ "partition_mode": "datetime",+ "partition_format": "week",+ "partition_keys": ["date_start"],+ "is_stats": True,+ }++RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {MetaAdsResource.Ads: {"primary_keys": ["id", "account_id"],@@ -252,4 +331,151 @@ RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {"partition_keys": ["date_start"],"is_stats": True,},+ # `GET /act_<id>` returns the account node itself, not a `data` list, so this one endpoint+ # reads a single object. One row per source, carrying the currency every spend figure in the+ # stats tables is denominated in.+ MetaAdsResource.AdAccount: {+ "primary_keys": ["id"],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}",+ "extra_params": {},+ "field_names": [+ "id",+ "account_id",+ "name",+ "account_status",+ "currency",+ "timezone_id",+ "timezone_name",+ "timezone_offset_hours_utc",+ "amount_spent",+ "balance",+ "spend_cap",+ "min_campaign_group_spend_cap",+ "min_daily_budget",+ "created_time",+ "business_country_code",+ "business_name",+ "business",+ "funding_source_details",+ "disable_reason",+ "is_prepay_account",+ "tos_accepted",+ "capabilities",+ "owner",+ ],+ "single_object": True,+ },+ # AdCreative carries no created_time or updated_time, so there is no stable column to+ # partition on.+ MetaAdsResource.AdCreatives: {+ "primary_keys": ["id", "account_id"],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}/adcreatives",+ "extra_params": {},+ "field_names": [+ "id",+ "account_id",+ "name",+ "status",+ "object_type",+ "object_story_id",+ "effective_object_story_id",+ "object_story_spec",+ "thumbnail_url",+ "image_url",+ "image_hash",+ "video_id",+ "body",+ "title",+ "call_to_action_type",+ "link_url",+ "url_tags",+ "instagram_permalink_url",+ "actor_id",+ "asset_feed_spec",+ "degrees_of_freedom_spec",+ "effective_authorization_category",+ ],+ },+ # `hash` rather than `id` as the key: Meta documents it as AdImage's default field, and the+ # `id` it returns is just the account and hash joined.+ MetaAdsResource.AdImages: {+ "primary_keys": ["hash", "account_id"],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}/adimages",+ "extra_params": {},+ "field_names": [+ "id",+ "hash",+ "account_id",+ "name",+ "url",+ "url_128",+ "permalink_url",+ "width",+ "height",+ "original_width",+ "original_height",+ "status",+ "created_time",+ "updated_time",+ "creatives",+ "is_associated_creatives_in_adgroups",+ ],+ "partition_mode": "datetime",+ "partition_format": "week",+ "partition_keys": ["created_time"],+ },+ # AdsPixel returns no account_id, and pixel ids are unique across Meta, so `id` alone keys+ # the table.+ MetaAdsResource.AdsPixels: {+ "primary_keys": ["id"],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}/adspixels",+ "extra_params": {},+ "field_names": [+ "id",+ "name",+ "code",+ "creation_time",+ "last_fired_time",+ "is_created_by_business",+ "is_unavailable",+ "data_use_setting",+ "enable_automatic_matching",+ "automatic_matching_fields",+ "owner_business",+ ],+ },+ MetaAdsResource.CustomConversions: {+ "primary_keys": ["id", "account_id"],+ "url": "https://graph.facebook.com/{API_VERSION}/{account_id}/customconversions",+ "extra_params": {},+ "field_names": [+ "id",+ "account_id",+ "name",+ "description",+ "creation_time",+ "first_fired_time",+ "last_fired_time",+ "custom_event_type",+ "default_conversion_value",+ "event_source_type",+ "is_archived",+ "is_unavailable",+ "pixel",+ "rule",+ "retention_days",+ "data_sources",+ "business",+ ],+ },+ MetaAdsResource.CampaignStatsByAgeGender: _campaign_breakdown_stats(["age", "gender"]),+ MetaAdsResource.CampaignStatsByCountry: _campaign_breakdown_stats(["country"]),+ MetaAdsResource.CampaignStatsByRegion: _campaign_breakdown_stats(["region"]),+ MetaAdsResource.CampaignStatsByPlatform: _campaign_breakdown_stats(+ ["publisher_platform", "platform_position", "impression_device"]+ ),+ MetaAdsResource.CampaignStatsHourly: _campaign_breakdown_stats(+ ["hourly_stats_aggregated_by_advertiser_time_zone"],+ field_names=HOURLY_BREAKDOWN_STATS_FIELDS,+ ),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.pyindex a0020cac4885..5c05cde24a59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mfrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (ENDPOINTS,INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -156,7 +157,7 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], Oforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetaAdsResumeConfig]:return ResumableSourceManager[MetaAdsResumeConfig](inputs, MetaAdsResumeConfig)@@ -208,7 +209,7 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O),SourceFieldInputConfig(name="sync_lookback_days",- label="Sync history for insights (days) - applies to AdStats, AdsetStats, CampaignStats",+ label="Sync history for insights (days) - applies to every stats table",type=SourceFieldInputConfigType.NUMBER,required=False,placeholder="90",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex fd704f90b08d..80f25784fe38 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -43,9 +43,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m_raise_meta_api_error,_strip_access_token,get_integration,+ get_schemas as get_meta_ads_schemas,list_ad_accounts,meta_ads_source,)+from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (+ BREAKDOWN_STATS_ENDPOINTS,+ ENDPOINTS,+ RESOURCE_SCHEMAS,+ MetaAdsResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source import MetaAdsSourcefrom products.warehouse_sources.backend.types import IncrementalFieldType@@ -1621,3 +1628,133 @@ class TestListAdAccounts:assert session.get.call_count == 2for call in session.get.call_args_list:assert call.kwargs["timeout"] == AD_ACCOUNT_LISTING_TIMEOUT_SECONDS+++def _source_config() -> mock.MagicMock:+ config = mock.MagicMock()+ config.account_id = "act_123"+ config.meta_ads_integration_id = 1+ config.sync_lookback_days = None+ return config+++class TestEndpointCatalog:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_every_advertised_endpoint_has_a_resource_schema(self, endpoint: str) -> None:+ # `meta_ads_source` looks the endpoint up by name, so advertising one in `get_schemas`+ # without a `RESOURCE_SCHEMAS` entry only fails at sync time with a KeyError.+ assert endpoint in get_meta_ads_schemas()++ def test_source_advertises_the_whole_catalog(self) -> None:+ advertised = {schema.name for schema in MetaAdsSource().get_schemas(cast(Any, None), team_id=1)}+ assert advertised == set(RESOURCE_SCHEMAS)+++class TestBreakdownStatsSchemas:+ """Insights breakdown tables fan a campaign/day pair out into one row per dimension combination."""++ @pytest.mark.parametrize("endpoint", list(BREAKDOWN_STATS_ENDPOINTS))+ def test_breakdown_dimensions_are_part_of_the_primary_key(self, endpoint: str) -> None:+ schema = get_meta_ads_schemas()[endpoint]+ breakdowns = schema.extra_params["breakdowns"].split(",")++ # Without the dimensions in the key, every combination for a campaign/day collapses onto+ # one key: duplicate rows seed the Delta table and each later merge multi-matches them.+ assert set(breakdowns) <= set(schema.primary_keys)++ @pytest.mark.parametrize("endpoint", list(BREAKDOWN_STATS_ENDPOINTS))+ def test_breakdown_dimensions_are_not_requested_as_fields(self, endpoint: str) -> None:+ schema = get_meta_ads_schemas()[endpoint]+ breakdowns = schema.extra_params["breakdowns"].split(",")++ # Meta returns breakdowns as columns automatically and rejects the request outright when+ # they are also listed in `fields`, so the table would 400 on every sync.+ assert set(breakdowns).isdisjoint(schema.field_names)++ @pytest.mark.parametrize("endpoint", list(BREAKDOWN_STATS_ENDPOINTS))+ def test_breakdown_tables_are_off_by_default(self, endpoint: str) -> None:+ schemas = {schema.name: schema for schema in MetaAdsSource().get_schemas(cast(Any, None), team_id=1)}++ # Each breakdown multiplies the daily row count, so a new connection must not pick them+ # up unless the user asks for them.+ assert schemas[endpoint].should_sync_default is False++ def test_hourly_table_omits_metrics_meta_cannot_report_hourly(self) -> None:+ # "Hourly breakdowns do not support unique fields, which are any fields prepended with+ # `unique_*`, `reach` or `frequency`" — requesting them stores columns Meta zeroes out.+ unique_metrics = {"reach", "frequency", "cpp", "cost_per_unique_click", "unique_clicks", "unique_ctr"}+ schemas = get_meta_ads_schemas()++ assert unique_metrics.isdisjoint(schemas[MetaAdsResource.CampaignStatsHourly].field_names)+ assert unique_metrics <= set(schemas[MetaAdsResource.CampaignStatsByCountry].field_names)+++class TestBreakdownStatsRequests:+ def _capture_request(self, monkeypatch, resource_name: str) -> dict[str, Any]:+ integration = mock.MagicMock()+ integration.access_token = "token"+ monkeypatch.setattr(meta_ads_module, "get_integration", lambda config, team_id: integration)++ captured: dict[str, Any] = {}++ def fake_request(url, params, access_token, time_range, resumable_source_manager):+ captured.update(url=url, params=params, time_range=time_range)+ yield from ()++ monkeypatch.setattr(meta_ads_module, "_make_paginated_api_request", fake_request)++ response = meta_ads_source(+ resource_name=resource_name,+ config=_source_config(),+ team_id=1,+ resumable_source_manager=_build_manager(),+ )+ list(cast(Any, response.items()))+ return captured++ @pytest.mark.parametrize("endpoint", list(BREAKDOWN_STATS_ENDPOINTS))+ def test_breakdown_request_is_windowed_and_carries_its_breakdowns(self, monkeypatch, endpoint: str) -> None:+ captured = self._capture_request(monkeypatch, endpoint)++ # A breakdown table that loses `is_stats` would drop the time window and ask Meta for the+ # whole account history on every sync.+ assert captured["time_range"] is not None+ assert captured["params"]["breakdowns"] == get_meta_ads_schemas()[endpoint].extra_params["breakdowns"]+ assert captured["params"]["level"] == "campaign"++ def test_non_stats_endpoint_is_not_windowed(self, monkeypatch) -> None:+ captured = self._capture_request(monkeypatch, MetaAdsResource.AdCreatives)++ assert captured["time_range"] is None+ assert captured["url"].endswith("/act_123/adcreatives")+++class TestSingleObjectEndpoint:+ """`GET /act_<id>` returns the account node itself, not a paged `data` list."""++ def _rows(self, monkeypatch, response: mock.MagicMock) -> list[list[dict]]:+ integration = mock.MagicMock()+ integration.access_token = "token"+ monkeypatch.setattr(meta_ads_module, "get_integration", lambda config, team_id: integration)+ monkeypatch.setattr(meta_ads_module, "_get_initial_request", lambda url, params: response)++ source = meta_ads_source(+ resource_name=MetaAdsResource.AdAccount,+ config=_source_config(),+ team_id=1,+ resumable_source_manager=_build_manager(),+ )+ return list(cast(Any, source.items()))++ def test_account_node_is_yielded_as_a_single_row(self, monkeypatch) -> None:+ body = {"id": "act_123", "account_id": "123", "currency": "GBP"}++ # Routing this through the list paginator would read a `data` key that is not there and+ # sync the table empty.+ assert self._rows(monkeypatch, _mock_response(200, body)) == [[body]]++ def test_permanent_auth_failure_surfaces_the_actionable_message(self, monkeypatch) -> None:+ response = _mock_response(400, {"error": {"code": 190, "message": "Invalid OAuth access token"}})++ with pytest.raises(Exception, match=META_AUTH_ERROR_MESSAGE):+ self._rows(monkeypatch, response)