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(warehouse-sources): sync meta ads spend by landing page url (#100670)

posthog[bot]ddedce195819
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 658309c02c58..a7cbddfa8047 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
@@ -207,6 +207,7 @@ Have: `campaigns`, `campaign_stats`, `adsets`, `adset_stats`, `ads`, `ad_stats`,
- [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.
+- [x] Creative asset breakdown `link_url_asset`, shipped as `ad_stats_by_link_url`: spend and conversions against the landing page an ad sent people to. Ad level only, since the asset belongs to one ad's creative. Meta returns one row per creative asset, so an ad it reports no landing page asset for is absent and the table's spend total can fall short of `ad_stats`. The other asset breakdowns (`body_asset`, `image_asset`, `title_asset`, `video_asset`, `call_to_action_asset`, `description_asset`) are still open.
- [ ] 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.)
diff --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.py
index fc5352b1bae7..5f4229efacec 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
@@ -9,6 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (
+ AD_ASSET_BREAKDOWN_STATS_FIELDS,
HOURLY_BREAKDOWN_STATS_FIELDS,
MetaAdsResource,
)
@@ -45,8 +46,15 @@ def _stats_columns(**overrides: str) -> dict[str, str]:
_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.
+# The hourly and creative-asset tables sync a reduced metric set, so their descriptions are
+# filtered to match.
_HOURLY_COLUMN_NAMES = {*HOURLY_BREAKDOWN_STATS_FIELDS, "hourly_stats_aggregated_by_advertiser_time_zone"}
+_LINK_URL_COLUMN_NAMES = {
+ *AD_ASSET_BREAKDOWN_STATS_FIELDS,
+ "link_url_asset",
+ "link_url",
+ "link_url_asset_id",
+}
def _campaign_breakdown_columns(**breakdowns: str) -> dict[str, str]:
@@ -54,6 +62,16 @@ def _campaign_breakdown_columns(**breakdowns: str) -> dict[str, str]:
return _stats_columns(campaign_id="The ID of the campaign the metrics belong to.", **breakdowns)
+def _ad_breakdown_columns(**breakdowns: str) -> dict[str, str]:
+ """Ad-level breakdown tables share the ad_stats columns, plus their own dimensions."""
+ return _stats_columns(
+ ad_id="The ID of the ad the metrics belong to.",
+ adset_id="The ID of the ad set the ad belongs to.",
+ campaign_id="The ID of the campaign the ad belongs to.",
+ **breakdowns,
+ )
+
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
MetaAdsResource.Campaigns: {
"description": "An advertising campaign in Meta Ads, defining the objective for its ad sets and ads.",
@@ -115,6 +133,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"configured_status": "The status set by the advertiser, before effective rules are applied.",
"effective_status": "The effective status after account and delivery rules are applied.",
"creative": "The creative associated with the ad.",
+ "creative_id": "The ID of the creative associated with the ad, joining to the ad_creatives table.",
"bid_amount": "The bid amount for the ad, in the account's minor currency unit.",
"created_time": "Time the ad was created.",
"updated_time": "Time the ad was last updated.",
@@ -319,4 +338,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
if key in _HOURLY_COLUMN_NAMES
},
},
+ MetaAdsResource.AdStatsByLinkUrl: {
+ "description": (
+ "Daily ad Insights split by the landing page each ad sent people to. "
+ "Meta builds this split from creative assets. An ad that Meta reports no landing page "
+ "asset for has no row here, so the total spend can be lower than in ad_stats. "
+ "Meta does not report unique metrics such as reach and frequency with creative asset "
+ "breakdowns, so this table omits them."
+ ),
+ "docs_url": _INSIGHTS_BREAKDOWNS_DOCS_URL,
+ "columns": {
+ key: value
+ for key, value in _ad_breakdown_columns(
+ link_url="The landing page URL the ad sent people to.",
+ link_url_asset_id="The ID Meta gives the landing page URL as a creative asset.",
+ link_url_asset="The landing page URL as Meta returns it, with its asset ID.",
+ ).items()
+ if key in _LINK_URL_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.py
index 5d19e38edfd0..f8421fa2f1ff 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
@@ -17,6 +17,7 @@ from requests.exceptions import (
ReadTimeout,
)
+from posthog.dataclasses import frozen
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, MetaAdsIntegration
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
@@ -33,7 +34,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.metaads import (
MetaAdsSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import RESOURCE_SCHEMAS
+from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (
+ RESOURCE_SCHEMAS,
+ HoistedColumn,
+)
from products.warehouse_sources.backend.types import IncrementalFieldType
logger = structlog.get_logger(__name__)
@@ -186,7 +190,7 @@ def get_integration(config: MetaAdsSourceConfig, team_id: int) -> Integration:
return get_integration_by_id(config.meta_ads_integration_id, team_id)
-@dataclass
+@frozen
class MetaAdsSchema:
name: str
primary_keys: list[str]
@@ -201,6 +205,8 @@ class MetaAdsSchema:
is_stats: bool = False
# The Graph API returns the node itself rather than a paged `data` list (`GET /act_<id>`).
single_object: bool = False
+ # Scalar columns to copy out of the nested objects in each row (see `HoistedColumn`).
+ hoisted_columns: tuple[HoistedColumn, ...] = ()
# Note: can make this static but keeping schemas.py to match other schema files for now
@@ -220,6 +226,7 @@ def get_schemas() -> dict[str, MetaAdsSchema]:
partition_format=schema_def.get("partition_format"),
is_stats=schema_def.get("is_stats", False),
single_object=schema_def.get("single_object", False),
+ hoisted_columns=schema_def.get("hoisted_columns", ()),
)
schemas[resource_name] = schema
@@ -883,6 +890,30 @@ def _fetch_single_object(url: str, params: dict, access_token: str) -> collectio
yield [response.json()]
+def _hoisted_values(row: dict, hoisted_columns: tuple[HoistedColumn, ...]) -> dict:
+ values = {}
+ for hoisted in hoisted_columns:
+ nested = row.get(hoisted.source_field)
+ values[hoisted.column] = nested.get(hoisted.key) if isinstance(nested, dict) else None
+ return values
+
+
+def _hoist_columns(
+ batches: collections.abc.Iterable[list[dict]], hoisted_columns: tuple[HoistedColumn, ...]
+) -> collections.abc.Generator[list[dict]]:
+ """Add each hoisted column to every row, read out of the row's nested object.
+
+ The column is always written, as ``None`` when the nested object is missing or is not an
+ object, so every row of the table carries the same columns whatever Meta returns for it.
+ """
+ if not hoisted_columns:
+ yield from batches
+ return
+
+ for batch in batches:
+ yield [{**row, **_hoisted_values(row, hoisted_columns)} for row in batch]
+
+
def _make_paginated_api_request(
url: str,
params: dict,
@@ -993,7 +1024,10 @@ def meta_ads_source(
formatted_url = schema.url.format(API_VERSION=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)
+ yield from _hoist_columns(
+ _fetch_single_object(formatted_url, {"fields": ",".join(schema.field_names)}, access_token),
+ schema.hoisted_columns,
+ )
return
params = {
@@ -1006,8 +1040,9 @@ def meta_ads_source(
if schema.is_stats:
params.update(_attribution_params(config))
- yield from _make_paginated_api_request(
- formatted_url, params, access_token, time_range, resumable_source_manager
+ yield from _hoist_columns(
+ _make_paginated_api_request(formatted_url, params, access_token, time_range, resumable_source_manager),
+ schema.hoisted_columns,
)
return SourceResponse(
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.py
index 1ff74a97b61b..7e34343155c0 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
@@ -1,6 +1,8 @@
from enum import StrEnum
from typing import Any
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -31,13 +33,15 @@ class MetaAdsResource(StrEnum):
AdStatsByRegion = "ad_stats_by_region"
AdStatsByPlatform = "ad_stats_by_platform"
AdStatsHourly = "ad_stats_hourly"
+ AdStatsByLinkUrl = "ad_stats_by_link_url"
# 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. The same breakdown dimensions
-# are offered at campaign, adset and ad grain — creative testing and ad-fatigue analysis only
-# make sense at ad level, which campaign-grain rows can't express.
+# they stay off in the schema picker until a user asks for them. The delivery dimensions are
+# offered at campaign, adset and ad grain — creative testing and ad-fatigue analysis only
+# make sense at ad level, which campaign-grain rows can't express. The creative-asset dimensions
+# describe one ad's creative, so Meta reports them at ad level only.
BREAKDOWN_STATS_ENDPOINTS = (
MetaAdsResource.CampaignStatsByAgeGender,
MetaAdsResource.CampaignStatsByCountry,
@@ -54,6 +58,7 @@ BREAKDOWN_STATS_ENDPOINTS = (
MetaAdsResource.AdStatsByRegion,
MetaAdsResource.AdStatsByPlatform,
MetaAdsResource.AdStatsHourly,
+ MetaAdsResource.AdStatsByLinkUrl,
)
ENDPOINTS = (
@@ -138,9 +143,11 @@ ADSET_BREAKDOWN_STATS_FIELDS = ["adset_id", "campaign_id", *_BREAKDOWN_METRIC_FI
AD_BREAKDOWN_STATS_FIELDS = ["ad_id", "adset_id", "campaign_id", *_BREAKDOWN_METRIC_FIELDS]
# 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 = {
+# `unique_*`, `reach` or `frequency`." `cpp` and `cost_per_unique_click` are derived from those.
+# A person who saw an ad cannot be counted once across a split Meta does not deduplicate over, so
+# the same restriction applies to the creative-asset breakdowns. Both tables ask for none of these
+# fields rather than storing columns Meta zeroes out.
+_UNIQUE_METRIC_FIELDS = {
"reach",
"frequency",
"cpp",
@@ -151,25 +158,57 @@ _HOURLY_UNSUPPORTED_FIELDS = {
}
-def _hourly_fields(field_names: list[str]) -> list[str]:
- return [f for f in field_names if f not in _HOURLY_UNSUPPORTED_FIELDS]
+def _without_unique_metrics(field_names: list[str]) -> list[str]:
+ return [f for f in field_names if f not in _UNIQUE_METRIC_FIELDS]
+
+
+HOURLY_BREAKDOWN_STATS_FIELDS = _without_unique_metrics(CAMPAIGN_BREAKDOWN_STATS_FIELDS)
+AD_ASSET_BREAKDOWN_STATS_FIELDS = _without_unique_metrics(AD_BREAKDOWN_STATS_FIELDS)
-HOURLY_BREAKDOWN_STATS_FIELDS = _hourly_fields(CAMPAIGN_BREAKDOWN_STATS_FIELDS)
+@frozen
+class HoistedColumn:
+ """A scalar column copied out of a nested Graph API object, next to the object itself.
+
+ The pipeline stores a nested object as a JSON string, which HogQL can read only by unpacking
+ it. A value a user needs as a join key or a group-by column is unusable in that form, so the
+ source lifts it into a column of its own. The nested field stays, because it carries more than
+ the hoisted key.
+ """
+
+ source_field: str
+ key: str
+ column: str
+
# The Insights `level` and its grain column, which heads that level's primary key and field list.
_LEVEL_GRAIN_COLUMN = {"campaign": "campaign_id", "adset": "adset_id", "ad": "ad_id"}
-def _breakdown_stats(level: str, breakdowns: list[str], field_names: list[str]) -> dict[str, Any]:
+def _breakdown_stats(
+ level: str,
+ breakdowns: list[str],
+ field_names: list[str],
+ *,
+ key_columns: list[str] | None = None,
+ hoisted_columns: tuple[HoistedColumn, ...] = (),
+) -> dict[str, Any]:
"""Insights split by `breakdowns` at `level` (campaign/adset/ad).
Every breakdown dimension joins the primary key: a grain/day pair now yields one row per
combination of dimension values, so keying on the grain id + `date_start` alone would collapse
- them into duplicates that merge multi-matches on every sync.
+ them into duplicates that merge multi-matches on every sync. `key_columns` overrides which
+ columns stand for the dimensions in that key, for a dimension Meta returns as an object: the
+ JSON string the object is stored as would make the merge key depend on Meta's key ordering,
+ so the scalar id hoisted out of it is keyed on instead.
"""
return {
- "primary_keys": [_LEVEL_GRAIN_COLUMN[level], "account_id", "date_start", *breakdowns],
+ "primary_keys": [
+ _LEVEL_GRAIN_COLUMN[level],
+ "account_id",
+ "date_start",
+ *(key_columns if key_columns is not None else breakdowns),
+ ],
"url": "https://graph.facebook.com/{API_VERSION}/{account_id}/insights",
"extra_params": {
"level": level,
@@ -181,6 +220,7 @@ def _breakdown_stats(level: str, breakdowns: list[str], field_names: list[str])
"partition_format": "week",
"partition_keys": ["date_start"],
"is_stats": True,
+ "hoisted_columns": hoisted_columns,
}
@@ -208,6 +248,9 @@ RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {
"partition_mode": "datetime",
"partition_format": "week",
"partition_keys": ["created_time"],
+ # The Ad node returns its creative as a nested object. Without a scalar id there is no join
+ # from an ad to `ad_creatives`, where the destination URL and the URL tags live.
+ "hoisted_columns": (HoistedColumn(source_field="creative", key="id", column="creative_id"),),
},
MetaAdsResource.AdStats: {
"primary_keys": ["ad_id", "account_id", "date_start"],
@@ -555,7 +598,9 @@ RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {
"adset", ["publisher_platform", "platform_position", "impression_device"], ADSET_BREAKDOWN_STATS_FIELDS
),
MetaAdsResource.AdsetStatsHourly: _breakdown_stats(
- "adset", ["hourly_stats_aggregated_by_advertiser_time_zone"], _hourly_fields(ADSET_BREAKDOWN_STATS_FIELDS)
+ "adset",
+ ["hourly_stats_aggregated_by_advertiser_time_zone"],
+ _without_unique_metrics(ADSET_BREAKDOWN_STATS_FIELDS),
),
MetaAdsResource.AdStatsByAgeGender: _breakdown_stats("ad", ["age", "gender"], AD_BREAKDOWN_STATS_FIELDS),
MetaAdsResource.AdStatsByCountry: _breakdown_stats("ad", ["country"], AD_BREAKDOWN_STATS_FIELDS),
@@ -564,6 +609,23 @@ RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {
"ad", ["publisher_platform", "platform_position", "impression_device"], AD_BREAKDOWN_STATS_FIELDS
),
MetaAdsResource.AdStatsHourly: _breakdown_stats(
- "ad", ["hourly_stats_aggregated_by_advertiser_time_zone"], _hourly_fields(AD_BREAKDOWN_STATS_FIELDS)
+ "ad", ["hourly_stats_aggregated_by_advertiser_time_zone"], _without_unique_metrics(AD_BREAKDOWN_STATS_FIELDS)
+ ),
+ # Spend against the landing page an ad sent people to. Meta reports the destination URL only
+ # as a creative asset, and `ad_creatives.link_url` alone cannot carry spend, so this is the
+ # only table that pairs the two. Ad level only: the asset belongs to one ad's creative, and a
+ # campaign or ad set total per URL is a sum over these rows, which already carry `campaign_id`
+ # and `adset_id`.
+ MetaAdsResource.AdStatsByLinkUrl: _breakdown_stats(
+ "ad",
+ ["link_url_asset"],
+ AD_ASSET_BREAKDOWN_STATS_FIELDS,
+ key_columns=["link_url_asset_id"],
+ # `link_url_asset` arrives as `{"id": ..., "website_url": ...}`. The URL is what the table
+ # exists for, and the asset id is its stable identity, so both become columns.
+ hoisted_columns=(
+ HoistedColumn(source_field="link_url_asset", key="website_url", column="link_url"),
+ HoistedColumn(source_field="link_url_asset", key="id", column="link_url_asset_id"),
+ ),
),
}
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.py
index 50fa56a33145..d09a023dd90c 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
@@ -1791,10 +1791,16 @@ class TestBreakdownStatsSchemas:
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(",")
+ # A dimension Meta returns as an object stands in the key through a column hoisted out of
+ # it, because the JSON string the object is stored as makes the merge key depend on Meta's
+ # key ordering.
+ keyed = set(schema.primary_keys) | {
+ hoisted.source_field for hoisted in schema.hoisted_columns if hoisted.column in schema.primary_keys
+ }
# 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)
+ assert set(breakdowns) <= keyed
@pytest.mark.parametrize(
"endpoint,level,grain_column",
@@ -1831,13 +1837,15 @@ class TestBreakdownStatsSchemas:
# 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:
+ @pytest.mark.parametrize("endpoint", [MetaAdsResource.CampaignStatsHourly, MetaAdsResource.AdStatsByLinkUrl])
+ def test_tables_without_unique_metric_support_omit_them(self, endpoint: str) -> 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.
+ # The creative-asset breakdowns split one ad's delivery the same way.
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.isdisjoint(schemas[endpoint].field_names)
assert unique_metrics <= set(schemas[MetaAdsResource.CampaignStatsByCountry].field_names)
@@ -1918,6 +1926,59 @@ class TestBreakdownStatsRequests:
assert "use_unified_attribution_setting" not in captured["params"]
+class TestHoistedColumns:
+ """Scalar columns lifted out of the nested objects the Graph API returns."""
+
+ def _emit_rows(self, monkeypatch, resource_name: str, rows: list[dict]) -> list[dict]:
+ integration = mock.MagicMock()
+ integration.access_token = "token"
+ monkeypatch.setattr(meta_ads_module, "get_integration", lambda config, team_id: integration)
+
+ def fake_request(url, params, access_token, time_range, resumable_source_manager):
+ yield rows
+
+ 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(),
+ api_version=META_ADS_API_VERSION_V26,
+ )
+ return [row for batch in cast(Any, response.items()) for row in batch]
+
+ @pytest.mark.parametrize(
+ "endpoint,row,expected",
+ [
+ (
+ MetaAdsResource.Ads,
+ {"id": "ad-1", "creative": {"id": "creative-1"}},
+ {"creative_id": "creative-1"},
+ ),
+ (
+ MetaAdsResource.Ads,
+ {"id": "ad-1"},
+ {"creative_id": None},
+ ),
+ (
+ MetaAdsResource.AdStatsByLinkUrl,
+ {"ad_id": "ad-1", "link_url_asset": {"id": "asset-1", "website_url": "https://example.com/pricing"}},
+ {"link_url": "https://example.com/pricing", "link_url_asset_id": "asset-1"},
+ ),
+ ],
+ )
+ def test_nested_objects_become_scalar_columns(self, monkeypatch, endpoint: str, row: dict, expected: dict) -> None:
+ # The pipeline stores a nested object as a JSON string. Without these columns an ad has no
+ # join key to `ad_creatives`, and spend cannot be grouped by landing page without unpacking
+ # JSON, which is the whole reason the breakdown table exists.
+ emitted = self._emit_rows(monkeypatch, endpoint, [row])
+
+ assert {column: emitted[0][column] for column in expected} == expected
+ # The nested field stays, because it carries more than the hoisted keys.
+ assert {column: emitted[0][column] for column in row} == row
+
+
class TestSingleObjectEndpoint:
"""`GET /act_<id>` returns the account node itself, not a paged `data` list."""