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 4 missing tables to the OpenAIAds source (#125249)

Tom Owers8890333975ed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 2888a7e53877..25ae16785e4f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -8741,10 +8741,10 @@ Today (7): `ad_account_insights`, `ad_group_insights`, `ad_groups`, `ad_insights
Diffed against: <https://developers.openai.com/ads/llms.txt>
-- [ ] `GET /ad_account` — account metadata lookup - we sync ad_account_insights but not the account entity itself (medium)
-- [ ] `insights with segments[]=country` — geographic breakdown dimension on the insights endpoints we already sync (medium)
-- [ ] `insights with segments[]=device` — device breakdown dimension on existing insights endpoints (medium)
-- [ ] `insights with segments[]=product` — product-feed breakdown, the only way to attribute spend to catalog items (medium)
+- [x] `GET /ad_account` — account metadata lookup - we sync ad_account_insights but not the account entity itself (medium)
+- [x] `insights with segments[]=country` — geographic breakdown dimension on the insights endpoints we already sync (medium)
+- [x] `insights with segments[]=device` — device breakdown dimension on existing insights endpoints (medium)
+- [x] `insights with segments[]=product` — product-feed breakdown, the only way to attribute spend to catalog items (medium)
Note: The Ads API is small - ad_account, campaigns, ad_groups, ads, insights, plus conversion setup and file upload (both excluded as config/plumbing). Coverage of the entity and insight levels is otherwise complete; the remaining value is in the segments[] breakdowns.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/canonical_descriptions.py
index b444a7ce75b7..10df66a9c93d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/canonical_descriptions.py
@@ -16,7 +16,46 @@ _INSIGHTS_COMMON_COLUMNS = {
"cpm": "Average cost per thousand impressions, in the ad account's currency.",
}
+_SEGMENT_INSIGHTS_COMMON_COLUMNS = {
+ "id": "Composite bucket identifier, unique per time bucket, campaign, and segment value.",
+ "start_time": "Start of the reporting bucket (UTC timestamp).",
+ "end_time": "End of the reporting bucket (UTC timestamp).",
+ "readable_time": "Human-readable bucket label, e.g. the bucket's calendar date for daily granularity.",
+ "currency_code": "Account currency code fetched from the ad account metadata for this sync.",
+ "campaign_id": "Identifier of the campaign the row aggregates.",
+ "campaign_name": "Name of the campaign the row aggregates.",
+}
+
+
+def _segment_metric_columns(segment: str, label: str) -> dict[str, str]:
+ return {
+ f"{segment}_impressions": f"Number of times the campaign's ads were shown for this {label} during the bucket.",
+ f"{segment}_clicks": f"Number of clicks for this {label} during the bucket.",
+ f"{segment}_spend": f"Amount spent for this {label} during the bucket, in the ad account's currency.",
+ f"{segment}_ctr": f"Click-through rate for this {label}: clicks divided by impressions.",
+ f"{segment}_cpc": f"Average cost per click for this {label}, in the ad account's currency.",
+ f"{segment}_cpm": f"Average cost per thousand impressions for this {label}, in the ad account's currency.",
+ }
+
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "ad_account": {
+ "description": "The ad account that the API key belongs to: names, primary URL, status, timezone, currency, and brand review status.",
+ "docs_url": "https://developers.openai.com/ads/api-reference/ad-account",
+ "columns": {
+ "id": "Unique identifier for the ad account.",
+ "name": "Legal business name, kept for compatibility.",
+ "legal_name": "Legal business name.",
+ "account_name": "Internal account name shown in Ads Manager.",
+ "brand_name": "Public advertiser name shown in ads.",
+ "url": "Primary destination URL of the advertiser.",
+ "preview_url": "Preview URL of the advertiser icon, when one is available.",
+ "status": "Account status, when one is available.",
+ "timezone": "Timezone of the ad account.",
+ "currency_code": "Currency of the ad account.",
+ "review": "Brand review object, including the review status.",
+ },
+ },
"campaigns": {
"description": "Ad campaigns in the ad account. A campaign defines the budget, flight dates, and location targeting under which its ad groups deliver.",
"docs_url": "https://developers.openai.com/ads/api-reference/campaigns",
@@ -106,4 +145,37 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"ad_account_name": "Name of the ad account the row aggregates.",
},
},
+ "campaign_country_insights": {
+ "description": "Daily delivery metrics per campaign, split by the country where the ads were shown. Needs segmented insights enabled for the ad account.",
+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",
+ "columns": {
+ **_SEGMENT_INSIGHTS_COMMON_COLUMNS,
+ **_segment_metric_columns("country", "country"),
+ "country_name": "Name of the country the row covers.",
+ },
+ },
+ "campaign_device_insights": {
+ "description": "Daily delivery metrics per campaign, split by device type. Needs segmented insights enabled for the ad account.",
+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",
+ "columns": {
+ **_SEGMENT_INSIGHTS_COMMON_COLUMNS,
+ **_segment_metric_columns("device", "device type"),
+ "device_type": "Device type the row covers.",
+ },
+ },
+ "campaign_product_insights": {
+ "description": "Daily delivery metrics per campaign, split by product-feed item. Use the feed ID and item ID together to match a row to your catalog. Needs segmented insights enabled for the ad account.",
+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",
+ "columns": {
+ **_SEGMENT_INSIGHTS_COMMON_COLUMNS,
+ **_segment_metric_columns("product", "product"),
+ "product_feed_id": "Identifier of the product feed the item belongs to.",
+ "item_id": "Identifier of the item in the product feed.",
+ "product_title": "Title of the product-feed item.",
+ "product_brand": "Brand of the product-feed item.",
+ "product_seller_name": "Seller name of the product-feed item.",
+ "product_price": "Price of the product-feed item.",
+ "product_availability": "Availability of the product-feed item.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
index 86faf97ce673..43c7e406a382 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py
@@ -312,7 +312,8 @@ def openai_ads_source(
client = _make_client(api_key)
return _source_response(config, lambda: _retry_forbidden_server_errors(_fan_out_rows(client, endpoint)))
- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ can_resume = resumable_source_manager.can_resume() and not config.single_object
+ resume = resumable_source_manager.load_state() if can_resume else None
data_map: Callable[[dict[str, Any]], dict[str, Any]] | None = None
if config.aggregation_level is not None:
@@ -332,12 +333,17 @@ def openai_ads_source(
{"type": "date_range", "since": window.start, "until": window.end, "timezone": "UTC"}
),
}
+ if config.segment is not None:
+ params["segments[]"] = config.segment
currency = _account_currency(api_key)
def enrich_insights(row: dict[str, Any]) -> dict[str, Any]:
return {**_convert_insights_times(_stable_insights_id(row)), "currency_code": currency}
data_map = enrich_insights
+ elif config.single_object:
+ window = SyncWindow(start="", end="")
+ params = {}
else:
window = SyncWindow(start="", end="")
# An explicit stable sort prevents page-boundary skips/duplicates while paginating the
@@ -357,8 +363,8 @@ def openai_ads_source(
"endpoint": {
"path": config.path,
"params": params,
- "data_selector": "data",
- "paginator": _ListPaginator(),
+ "data_selector": "$" if config.single_object else "data",
+ "paginator": SinglePagePaginator() if config.single_object else _ListPaginator(),
},
"data_map": data_map,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/settings.py
index 7ddb4d80f477..5107a12d5cff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/settings.py
@@ -29,6 +29,19 @@ def _insights_fields(level: str, metadata: tuple[str, ...]) -> list[str]:
]
+def _segmented_insights_fields(
+ level: str, level_metadata: tuple[str, ...], segment: str, segment_metadata: tuple[str, ...]
+) -> list[str]:
+ # Segment metrics (`country.clicks`) give the segment's share of each row entity. The
+ # aggregation-level metrics would repeat the entity total on every segment row.
+ return [
+ "metadata.readable_time",
+ *(f"{level}.{name}" for name in level_metadata),
+ *(f"{segment}.{name}" for name in segment_metadata),
+ *(f"{segment}.{metric}" for metric in _INSIGHTS_METRICS),
+ ]
+
+
def _datetime_incremental_field(name: str) -> IncrementalField:
return {
"label": name,
@@ -38,7 +51,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
-@dataclass
+@dataclass(frozen=True)
class OpenAIAdsEndpointConfig:
name: str
path: str
@@ -56,19 +69,30 @@ class OpenAIAdsEndpointConfig:
# projection requested for that level.
aggregation_level: Optional[str] = None
insights_fields: list[str] = field(default_factory=list)
+ # Insights-only: the one `segments[]` breakdown dimension (product, country, device).
+ segment: Optional[str] = None
+ # The endpoint returns one JSON object, not a paginated list.
+ single_object: bool = False
default_incremental_lookback_seconds: Optional[int] = None
-def _insights_endpoint(name: str, level: str, metadata: tuple[str, ...]) -> OpenAIAdsEndpointConfig:
+def _insights_endpoint(
+ name: str,
+ level: str,
+ metadata: tuple[str, ...],
+ segment: Optional[str] = None,
+ segment_metadata: tuple[str, ...] = (),
+) -> OpenAIAdsEndpointConfig:
return OpenAIAdsEndpointConfig(
name=name,
# Account-scoped insights cover every entity of the account; `aggregation_level`
# picks the row entity, so no per-entity fan-out is needed.
path="/v1/ad_account/insights",
# The API's composite bucket id ("start=<unix>:end=<unix>:entity_id=<id>") is unique and
- # stable per (bucket, entity) as long as no sort[]/segments[] params are sent (those
- # append suffixes to the id). The id can also carry a `plan=` segment that changes between
- # requests, so the source removes that segment before the merge.
+ # stable per (bucket, entity) as long as the request shape stays fixed. A segmented request
+ # encodes the segment value into `entity_id`, so its ids are unique per (bucket, entity,
+ # segment value). The id can also carry a `plan=` segment that changes between requests,
+ # so the source removes that segment before the merge.
primary_keys=["id"],
partition_key="start_time",
incremental_fields=[_datetime_incremental_field("start_time")],
@@ -78,12 +102,24 @@ def _insights_endpoint(name: str, level: str, metadata: tuple[str, ...]) -> Open
# regardless of arrival order.
sort_mode="desc",
aggregation_level=level,
- insights_fields=_insights_fields(level, metadata),
+ insights_fields=(
+ _segmented_insights_fields(level, metadata, segment, segment_metadata)
+ if segment is not None
+ else _insights_fields(level, metadata)
+ ),
+ segment=segment,
default_incremental_lookback_seconds=INSIGHTS_LOOKBACK_SECONDS,
)
OPENAI_ADS_ENDPOINTS: dict[str, OpenAIAdsEndpointConfig] = {
+ # The key's ad account as one row. The object has no creation timestamp to partition on.
+ "ad_account": OpenAIAdsEndpointConfig(
+ name="ad_account",
+ path="/v1/ad_account",
+ primary_keys=["id"],
+ single_object=True,
+ ),
"campaigns": OpenAIAdsEndpointConfig(
name="campaigns",
path="/v1/campaigns",
@@ -112,6 +148,20 @@ OPENAI_ADS_ENDPOINTS: dict[str, OpenAIAdsEndpointConfig] = {
"ad_group_insights": _insights_endpoint("ad_group_insights", "ad_group", ("id", "name", "status")),
"ad_insights": _insights_endpoint("ad_insights", "ad", ("id", "name", "title", "status", "review_status")),
"ad_account_insights": _insights_endpoint("ad_account_insights", "ad_account", ("name",)),
+ # Segmented insights need the segment to be enabled for the ad account.
+ "campaign_country_insights": _insights_endpoint(
+ "campaign_country_insights", "campaign", ("id", "name"), segment="country", segment_metadata=("name",)
+ ),
+ "campaign_device_insights": _insights_endpoint(
+ "campaign_device_insights", "campaign", ("id", "name"), segment="device", segment_metadata=("type",)
+ ),
+ "campaign_product_insights": _insights_endpoint(
+ "campaign_product_insights",
+ "campaign",
+ ("id", "name"),
+ segment="product",
+ segment_metadata=("feed_id", "item_id", "title", "brand", "seller_name", "price", "availability"),
+ ),
}
ENDPOINTS = tuple(OPENAI_ADS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
index 4fa195ff4c38..b8d094059e0c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py
@@ -76,7 +76,56 @@ class TestFanOut:
}
+class TestAdAccount:
+ def test_account_object_syncs_as_one_row(self) -> None:
+ account = {
+ "id": "adacct_example",
+ "name": "Example Co",
+ "status": "active",
+ "timezone": "UTC",
+ "currency_code": "USD",
+ "review": {"status": "approved"},
+ }
+ result = _driver().run("ad_account", [ScriptedResponse(json=account)])
+
+ assert result.raised is None
+ assert result.rows == [account]
+ assert result.paths == ["/v1/ad_account"]
+ assert result.queries == [{}]
+ assert result.saved_states == []
+
+
class TestInsights:
+ @parameterized.expand(
+ [
+ ("unsegmented", "campaign_insights", None, "campaign.clicks"),
+ ("country", "campaign_country_insights", "country", "country.clicks"),
+ ("device", "campaign_device_insights", "device", "device.clicks"),
+ ("product", "campaign_product_insights", "product", "product.clicks"),
+ ]
+ )
+ def test_segment_tables_request_the_breakdown_and_its_metrics(
+ self, _name: str, endpoint: str, segment: str | None, metric_field: str
+ ) -> None:
+ result = _driver().run(
+ endpoint,
+ [
+ ScriptedResponse(json={"currency_code": "EUR"}),
+ _page([{"id": "b1", "start_time": 1777075200, "end_time": 1777161600}], has_more=False),
+ ],
+ )
+
+ assert result.raised is None
+ insights_request = result.requests[1]
+ assert insights_request.path == "/v1/ad_account/insights"
+ assert insights_request.param("aggregation_level") == "campaign"
+ assert insights_request.query.get("segments[]") == ((segment,) if segment else None)
+ fields = insights_request.query["fields[]"]
+ assert metric_field in fields
+ # A segment row must carry the segment's share, not the campaign total repeated per segment.
+ assert ("campaign.clicks" in fields) is (segment is None)
+ assert result.rows[0]["currency_code"] == "EUR"
+
@parameterized.expand(
[
("plan_in_middle", "start=1777075200:{plan}:end=1777161600:entity_id=cmpn_1"),