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 13 missing Reddit Ads tables (#77283)

Tom Owersf3192a9db635
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 507778d3b896..80ba98f8a4f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
@@ -369,6 +369,23 @@ campaign_stats_daily_demographics, ad_stats_daily_country, ad_stats_daily_demogr
- [ ] Organization-level tables — funding sources, billing centers, invoices, members (skipped: all
scoped to an organization ID this source does not collect).
+### Reddit Ads — spec-verified
+
+Reddit Ads is done; the section above still covers TikTok.
+Diffed against the Reddit Ads v3 OpenAPI spec (`https://ads-api.reddit.com/api/v3/openapi.json`) on 2026-08-04.
+
+Have: campaigns, ad_groups, ads, campaign_report, ad_group_report, ad_report, ad_account,
+custom_audiences, saved_audiences, pixels, funding_instruments, lead_gen_forms, profiles,
+structured_posts, campaign_country_report, campaign_gender_report, campaign_placement_report,
+campaign_community_report, campaign_os_type_report.
+
+- [x] Creative metadata — `structured_posts`, fanned out over the account's profiles. Reddit hangs creatives off profiles, not off the ad account, and ad rows carry the `post_id` to join on.
+- [x] Breakdown dimensions on the report tables — gender, country, placement, device (`OS_TYPE`) and community, each a campaign-grain report table defaulted to `should_sync_default=False`. Reddit returns breakdowns as extra dimensions on the same `POST /reports` call, capped at three per request, so each dimension is its own table rather than a new param. Age is not shippable: `AGE` is absent from the spec's `breakdowns` enum (it appears only in a stale request example).
+- [x] Ad account table — `ad_account`, carrying `currency` and `time_zone_id`.
+- [x] Audiences and pixel definitions — `custom_audiences`, `saved_audiences`, `pixels`. Conversion _events_ are write-only (`POST /pixels/{id}/conversion_events`), so there is nothing to sync.
+- Also added: `funding_instruments` (per-instrument currency and credit limit), `lead_gen_forms`, `profiles`.
+- Not built: `apps` (the response schema exposes only `id`); `creative_assets` (rows arrive wrapped in a per-item `result` envelope); product catalogs, feeds, sets and their imports (business-scoped, not reachable from the configured ad account); the targeting reference lists (`communities`, `interests`, `geolocations`, `languages`, `devices`, `carriers`) and `time_zones`, which are global catalogs rather than account data; `POST /ad_accounts/{id}/history` (an audit log, not warehouse-shaped); forecasting, bid suggestions and data-deletion jobs (write or estimate endpoints).
+
### Pinterest Ads — spec-verified
Diffed against the Pinterest API v5 OpenAPI description in
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/canonical_descriptions.py
index a88fa4ef639a..20f165184ab9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/canonical_descriptions.py
@@ -114,4 +114,185 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"ad_id": "ID of the ad the metrics are aggregated for.",
},
},
+ "ad_account": {
+ "description": "The connected Reddit Ads account, including the currency and time zone every spend figure is reported in.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/get-ad-account",
+ "columns": {
+ "id": "The ad account ID.",
+ "name": "The ad account name.",
+ "currency": "The currency the ad account is billed and reported in.",
+ "time_zone_id": "The time zone the ad account reports in.",
+ "type": "The ad account type. Can only be changed by Reddit.",
+ "business_id": "ID of the business that owns the ad account.",
+ "admin_approval": "The approval state of the account. Can only be changed by Reddit.",
+ "attribution_type": "The attribution conversion type used for cost-per-action bidding and reporting.",
+ "click_attribution_window": "The window for click attributions, used in reporting.",
+ "view_attribution_window": "The window for view attributions, used in reporting.",
+ "app_attribution_type": "The attribution conversion type used for app-install campaigns.",
+ "app_click_attribution_window": "The window for app-install click attributions.",
+ "app_view_attribution_window": "The window for app-install view attributions.",
+ "spend_cap_type": "The spend cap type applied to the ad account.",
+ "suspension_reason": "Why the ad account was suspended, if it was.",
+ "primary_contact_member_id": "ID of the member listed as the account's primary contact.",
+ "excluded_communities": "Communities (subreddits) excluded at the ad account level.",
+ "excluded_keywords": "Keywords excluded at the ad account level.",
+ "pixel_partner_preferences": "Pixel partners allowed by the advertiser.",
+ "created_at": "When the ad account was created.",
+ "modified_at": "When the ad account was last changed.",
+ },
+ },
+ "custom_audiences": {
+ "description": "An audience built from advertiser-supplied data: a customer list, website or app retargeting via a Pixel, engagement retargeting, or a lookalike.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-user-custom-audiences",
+ "columns": {
+ "id": "The custom audience ID.",
+ "name": "The custom audience name.",
+ "type": "The custom audience type.",
+ "status": "The audience's processing status. Only VALID once at least 1,000 users match.",
+ "ad_account_id": "ID of the ad account that owns this custom audience.",
+ "business_id": "ID of the business that owns this custom audience.",
+ "size_range_lower": "Lower bound of the estimated matched users for this audience.",
+ "size_range_upper": "Upper bound of the estimated matched users for this audience.",
+ "delivery_status": "The delivery statuses for this audience.",
+ "customer_list_config": "Details for a customer list audience.",
+ "pixel_audience_config": "Details for a website retargeting audience.",
+ "engagement_audience_config": "Details for an engagement retargeting audience.",
+ "lookalike_config": "Details for a lookalike audience.",
+ "cost": "Cost information for audiences sourced from third-party data providers.",
+ "created_at": "When the audience was created.",
+ "modified_at": "When the audience was last changed.",
+ },
+ },
+ "saved_audiences": {
+ "description": "A reusable targeting definition that ad groups can point at instead of redefining targeting each time.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-saved-audiences",
+ "columns": {
+ "id": "The saved audience ID.",
+ "name": "The saved audience name.",
+ "type": "The saved audience type.",
+ "status": "The saved audience status.",
+ "ad_account_id": "The ad account ID.",
+ "targeting": "The targeting definition this saved audience applies.",
+ "active_ad_groups_count": "Number of active ad groups using this saved audience.",
+ "size_range_lower": "Lower bound of the audience's predicted impressions.",
+ "size_range_upper": "Upper bound of the audience's predicted impressions.",
+ "delivery_status": "The delivery statuses for this saved audience.",
+ "created_at": "When the saved audience was created.",
+ "updated_at": "When the saved audience was last updated.",
+ },
+ },
+ "pixels": {
+ "description": "A Reddit Pixel, the conversion tracker that reports website events back to Reddit Ads.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-pixels-by-ad-account",
+ "columns": {
+ "id": "The Pixel ID.",
+ "name": "The Pixel's human-readable name.",
+ "business_id": "ID of the business that owns the Pixel.",
+ "automatic_matching_config": "The Pixel's automated advanced matching settings.",
+ "enhanced_signal_collection_config": "The Pixel's enhanced signal collection settings.",
+ "created_by": "ID of the member who created the Pixel.",
+ "modified_by": "ID of the member who last modified the Pixel.",
+ "created_at": "When the Pixel was created.",
+ "modified_at": "When the Pixel was last changed.",
+ },
+ },
+ "funding_instruments": {
+ "description": "A payment source campaigns bill against, carrying the currency spend is denominated in.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-funding-instruments",
+ "columns": {
+ "id": "The funding instrument ID.",
+ "name": "The funding instrument's name.",
+ "currency": "The currency used in this invoice (ISO 4217).",
+ "credit_limit": "The maximum amount this funding instrument can spend before linked campaigns stop running.",
+ "billable_amount": "The funding instrument's current outstanding debt, in local microcurrency.",
+ "is_servable": "Whether campaigns linked to this funding instrument are allowed to run.",
+ "reasons_not_servable": "Why this funding instrument is not servable. Empty when it is servable.",
+ "authorize_status": "The state of the credit card attachment. Only applies to CREDIT_CARD funding instruments.",
+ "invoice_group_status": "Eligibility or issues with the invoice group.",
+ "start_time": "Campaigns using this funding instrument will not deliver until this time.",
+ "end_time": "Campaigns using this funding instrument will not deliver after this time.",
+ },
+ },
+ "lead_gen_forms": {
+ "description": "A lead generation form users fill in from an ad, defining the questions asked and the privacy policy shown.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-lead-gen-forms",
+ "columns": {
+ "id": "The form's ID.",
+ "name": "The form's name. Shown only in the Ads Manager.",
+ "ad_account_id": "The ad account ID.",
+ "prompt": "The text shown at the top of the form and beside the ad's call to action.",
+ "privacy_link": "The privacy policy URL shown on the form.",
+ "questions": "The list of questions the user fills out.",
+ "created_at": "When the form was created.",
+ "modified_at": "When the form was last changed.",
+ },
+ },
+ "profiles": {
+ "description": "A Reddit profile the ad account can publish ads from. Ad and post rows reference it by ID.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-profiles-by-ad-account",
+ "columns": {
+ "id": "The profile ID.",
+ "name": "The profile's Reddit username.",
+ "reddit_user_id": "The profile's Reddit user ID.",
+ "business_id": "ID of the business associated with this profile.",
+ "modified_at": "When the profile was last changed.",
+ },
+ },
+ "structured_posts": {
+ "description": "The post backing an ad's creative, carrying the headline, media, and destination the ad actually showed. Join to ads on `post_id` to attribute performance to a creative.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/api/list-structured-posts",
+ "columns": {
+ "id": "The post ID. Matches an ad's `post_id`.",
+ "profile_id": "ID of the profile the post belongs to.",
+ "url": "The post URL.",
+ "creative": "The creative payload: type, headline, media, and click destination.",
+ "allow_comments": "Whether comments are allowed on the post.",
+ "created_at": "When the post was created.",
+ },
+ },
+ "campaign_country_report": {
+ "description": "Daily campaign performance metrics broken down by the country the impression was served in.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/operations/Generate%20Report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "campaign_id": "ID of the campaign the metrics are aggregated for.",
+ "country": "The targeted country.",
+ },
+ },
+ "campaign_gender_report": {
+ "description": "Daily campaign performance metrics broken down by the viewer's gender.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/operations/Generate%20Report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "campaign_id": "ID of the campaign the metrics are aggregated for.",
+ "gender": "The user's gender.",
+ },
+ },
+ "campaign_placement_report": {
+ "description": "Daily campaign performance metrics broken down by where on Reddit the creative was placed.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/operations/Generate%20Report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "campaign_id": "ID of the campaign the metrics are aggregated for.",
+ "placement": "Where the creative was placed.",
+ },
+ },
+ "campaign_community_report": {
+ "description": "Daily campaign performance metrics broken down by the community (subreddit) the ad ran in.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/operations/Generate%20Report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "campaign_id": "ID of the campaign the metrics are aggregated for.",
+ "community": "The targeted community (subreddit).",
+ },
+ },
+ "campaign_os_type_report": {
+ "description": "Daily campaign performance metrics broken down by the viewer's device operating system.",
+ "docs_url": "https://ads-api.reddit.com/docs/v3/operations/Generate%20Report",
+ "columns": {
+ **_REPORT_COLUMNS,
+ "campaign_id": "ID of the campaign the metrics are aggregated for.",
+ "os_type": "The device operating system type.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py
index cc200287484d..5824c7891f5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py
@@ -17,11 +17,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.settings import REDDIT_ADS_CONFIG
+from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.settings import (
+ REDDIT_ADS_CONFIG,
+ REDDIT_ADS_FANOUT,
+)
logger = structlog.get_logger(__name__)
@@ -33,6 +42,8 @@ REDDIT_ADS_BASE_HOST = urlsplit(REDDIT_ADS_BASE_URL).netloc
MAX_LISTING_PAGES = 50
# These listings run in the web request path, so never let a stalled connection pin a worker.
LISTING_TIMEOUT_SECONDS = 10
+# Reddit caps `page.size` at 100 on the endpoints we read.
+DEFAULT_PAGE_SIZE = 100
@dataclasses.dataclass
@@ -251,6 +262,75 @@ class RedditAdsPaginator(BasePaginator):
self._has_next_page = True
+class _FanoutEndpoint:
+ """Adapter exposing a `REDDIT_ADS_CONFIG` entry as the shape `build_dependent_resource` expects."""
+
+ name: str
+ path: str
+ incremental_fields: list[Any]
+ default_incremental_field: Optional[str]
+ page_size: int
+
+
+def _fanout_endpoint(name: str) -> _FanoutEndpoint:
+ config = REDDIT_ADS_CONFIG[name]
+ endpoint = config.resource["endpoint"]
+ if not isinstance(endpoint, dict):
+ raise ValueError(f"Expected endpoint to be a dict, got {type(endpoint)}")
+ page_size = (endpoint.get("params") or {}).get("page.size")
+ return _FanoutEndpoint(
+ name=name,
+ path=endpoint["path"] or "",
+ incremental_fields=list(config.incremental_fields or []),
+ default_incremental_field=None,
+ page_size=page_size if isinstance(page_size, int) else DEFAULT_PAGE_SIZE,
+ )
+
+
+def _data_selector(name: str) -> str:
+ endpoint = REDDIT_ADS_CONFIG[name].resource["endpoint"]
+ if not isinstance(endpoint, dict):
+ raise ValueError(f"Expected endpoint to be a dict, got {type(endpoint)}")
+ return str(endpoint["data_selector"])
+
+
+def _client_config(access_token: str) -> ClientConfig:
+ return {
+ "base_url": REDDIT_ADS_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": access_token,
+ },
+ "headers": {
+ "Content-Type": "application/json",
+ },
+ "paginator": RedditAdsPaginator(),
+ }
+
+
+def _fanout_items(endpoint: str, account_id: str, team_id: int, job_id: str, access_token: str):
+ fanout = REDDIT_ADS_FANOUT[endpoint]
+ # No resume hook: a fan-out walks one paginated child list per parent row, so a single saved
+ # `next_url` cannot say which parent it belonged to. These tables restart from the top instead.
+ return build_dependent_resource(
+ endpoint_configs={
+ fanout.parent_name: _fanout_endpoint(fanout.parent_name),
+ endpoint: _fanout_endpoint(endpoint),
+ },
+ child_endpoint=endpoint,
+ fanout=fanout,
+ client_config=_client_config(access_token),
+ path_format_values={"account_id": account_id},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector": _data_selector(fanout.parent_name)},
+ child_endpoint_extra={"data_selector": _data_selector(endpoint)},
+ page_size_param="page.size",
+ )
+
+
def reddit_ads_source(
account_id: str,
endpoint: str,
@@ -261,18 +341,11 @@ def reddit_ads_source(
resumable_source_manager: ResumableSourceManager[RedditAdsResumeConfig],
should_use_incremental_field: bool = False,
):
+ if endpoint in REDDIT_ADS_FANOUT:
+ return _source_response(endpoint, _fanout_items(endpoint, account_id, team_id, job_id, access_token))
+
config: RESTAPIConfig = {
- "client": {
- "base_url": REDDIT_ADS_BASE_URL,
- "auth": {
- "type": "bearer",
- "token": access_token,
- },
- "headers": {
- "Content-Type": "application/json",
- },
- "paginator": RedditAdsPaginator(),
- },
+ "client": _client_config(access_token),
"resource_defaults": {
"write_disposition": {
"disposition": "merge",
@@ -307,11 +380,15 @@ def reddit_ads_source(
initial_paginator_state=initial_paginator_state,
)
+ return _source_response(endpoint, resource)
+
+
+def _source_response(endpoint: str, items: Any) -> SourceResponse:
endpoint_config = REDDIT_ADS_CONFIG[endpoint]
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=lambda: items,
primary_keys=list(endpoint_config.resource["primary_key"])
if isinstance(endpoint_config.resource["primary_key"], list | tuple)
else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/settings.py
index 3d8597bc1a8d..dcea4132a289 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/settings.py
@@ -1,7 +1,11 @@
from dataclasses import dataclass
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
PartitionMode,
@@ -11,12 +15,127 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
@dataclass
class EndpointConfig:
- partition_keys: list[str]
- partition_mode: PartitionMode
resource: EndpointResource
+ partition_keys: Optional[list[str]] = None
+ partition_mode: Optional[PartitionMode] = None
incremental_fields: Optional[list[IncrementalField]] = None
partition_format: Optional[PartitionFormat] = None
partition_size: int = 1
+ should_sync_default: bool = True
+
+
+def _entity_endpoint(
+ name: str,
+ path: str,
+ *,
+ primary_key: list[str],
+ partition_key: Optional[str] = None,
+) -> EndpointConfig:
+ """A plain account-scoped GET list endpoint.
+
+ None of these accept a server-side timestamp filter (only `page.token` / `page.size` and a few
+ value filters), so they stay full refresh — see the Reddit Ads v3 OpenAPI spec.
+ """
+ return EndpointConfig(
+ resource={
+ "name": name,
+ "table_name": name,
+ "primary_key": primary_key,
+ "endpoint": {
+ "path": path,
+ "method": "GET",
+ "params": {"page.size": 100},
+ "data_selector": "data",
+ },
+ "table_format": "delta",
+ },
+ partition_keys=[partition_key] if partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="week" if partition_key else None,
+ )
+
+
+# Metrics requested for every breakdown report table. Deliberately narrower than the entity-level
+# report tables: reach and frequency only exist from June 2024 and the app-install family is
+# objective-specific, so neither survives a per-dimension breakdown usefully.
+_BREAKDOWN_REPORT_METRICS = [
+ "CLICKS",
+ "CONVERSION_PURCHASE_TOTAL_ITEMS",
+ "CONVERSION_PURCHASE_TOTAL_VALUE",
+ "CONVERSION_ROAS",
+ "CPC",
+ "CTR",
+ "CURRENCY",
+ "ECPM",
+ "IMPRESSIONS",
+ "KEY_CONVERSION_RATE",
+ "KEY_CONVERSION_TOTAL_COUNT",
+ "SPEND",
+ "VIDEO_COMPLETION_RATE",
+ "VIDEO_STARTED",
+ "VIDEO_VIEW_RATE",
+ "VIDEO_WATCHED_100_PERCENT",
+ "VIDEO_WATCHED_25_PERCENT",
+ "VIDEO_WATCHED_50_PERCENT",
+ "VIDEO_WATCHED_75_PERCENT",
+]
+
+
+def _breakdown_report_endpoint(
+ name: str,
+ breakdown: str,
+ column: str,
+ *,
+ breakdown_is_requestable_field: bool = True,
+) -> EndpointConfig:
+ """A campaign-grain report broken down by one extra dimension.
+
+ Reddit returns breakdowns as extra dimensions on the same `POST /reports` call rather than from a
+ separate endpoint, so each dimension is its own table with its own `breakdowns` array. Reddit caps
+ a request at three breakdowns, which `CAMPAIGN_ID` + `DATE` + the dimension exactly fills.
+
+ A few breakdowns (`OS_TYPE`, `LANGUAGE`, `METRO`, ...) are not members of the `fields` enum even
+ though the response carries their column, so those are requested as a breakdown only.
+ """
+ fields = ["CAMPAIGN_ID", "DATE", *_BREAKDOWN_REPORT_METRICS]
+ if breakdown_is_requestable_field:
+ fields.append(breakdown)
+
+ return EndpointConfig(
+ resource={
+ "name": name,
+ "table_name": name,
+ "primary_key": ["campaign_id", "date", column],
+ "endpoint": {
+ "path": "/ad_accounts/{account_id}/reports",
+ "method": "POST",
+ "params": {"page.size": 100},
+ "json": {
+ "data": {
+ "breakdowns": ["CAMPAIGN_ID", "DATE", breakdown],
+ "fields": sorted(fields),
+ "starts_at": None, # Will be set dynamically
+ "ends_at": None, # Will be set dynamically
+ "time_zone_id": "UTC",
+ }
+ },
+ "data_selector": "data.metrics",
+ "incremental": {
+ "cursor_path": "date",
+ "start_param": "starts_at",
+ "end_param": "ends_at",
+ },
+ },
+ "table_format": "delta",
+ },
+ incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="week",
+ # One report request per dimension value per day is expensive and only some advertisers
+ # break spend down this way, so these stay off unless the user picks them.
+ should_sync_default=False,
+ )
REDDIT_ADS_CONFIG: dict[str, EndpointConfig] = {
@@ -319,4 +438,87 @@ REDDIT_ADS_CONFIG: dict[str, EndpointConfig] = {
partition_format="week",
partition_size=1,
),
+ "ad_account": _entity_endpoint(
+ "ad_account",
+ "/ad_accounts/{account_id}",
+ primary_key=["id"],
+ ),
+ "custom_audiences": _entity_endpoint(
+ "custom_audiences",
+ "/ad_accounts/{account_id}/custom_audiences",
+ primary_key=["id"],
+ partition_key="created_at",
+ ),
+ "saved_audiences": _entity_endpoint(
+ "saved_audiences",
+ "/ad_accounts/{account_id}/saved_audiences",
+ primary_key=["id"],
+ partition_key="created_at",
+ ),
+ "pixels": _entity_endpoint(
+ "pixels",
+ "/ad_accounts/{account_id}/pixels",
+ primary_key=["id"],
+ partition_key="created_at",
+ ),
+ "funding_instruments": _entity_endpoint(
+ "funding_instruments",
+ "/ad_accounts/{account_id}/funding_instruments",
+ primary_key=["id"],
+ ),
+ "lead_gen_forms": _entity_endpoint(
+ "lead_gen_forms",
+ "/ad_accounts/{account_id}/lead_gen_forms",
+ primary_key=["id"],
+ partition_key="created_at",
+ ),
+ "profiles": _entity_endpoint(
+ "profiles",
+ "/ad_accounts/{account_id}/profiles",
+ primary_key=["id"],
+ ),
+ "structured_posts": EndpointConfig(
+ resource={
+ "name": "structured_posts",
+ "table_name": "structured_posts",
+ # Fanned out over every profile on the account, so the parent id is part of the key.
+ "primary_key": ["profile_id", "id"],
+ "endpoint": {
+ "path": "/profiles/{profile_id}/structured_posts",
+ "method": "GET",
+ "params": {"page.size": 100},
+ "data_selector": "data",
+ },
+ "table_format": "delta",
+ },
+ partition_keys=["created_at"],
+ partition_mode="datetime",
+ partition_format="week",
+ ),
+ "campaign_country_report": _breakdown_report_endpoint("campaign_country_report", "COUNTRY", "country"),
+ "campaign_gender_report": _breakdown_report_endpoint("campaign_gender_report", "GENDER", "gender"),
+ "campaign_placement_report": _breakdown_report_endpoint("campaign_placement_report", "PLACEMENT", "placement"),
+ "campaign_community_report": _breakdown_report_endpoint("campaign_community_report", "COMMUNITY", "community"),
+ "campaign_os_type_report": _breakdown_report_endpoint(
+ "campaign_os_type_report",
+ "OS_TYPE",
+ "os_type",
+ # `OS_TYPE` is a valid breakdown but is not a member of the report `fields` enum, so asking
+ # for it as a field would be rejected. The response carries `os_type` from the breakdown.
+ breakdown_is_requestable_field=False,
+ ),
+}
+
+# Endpoints that are not reachable from the ad account directly and have to be walked from a parent
+# resource. `structured_posts` is the only one today: Reddit hangs creatives off the ad account's
+# profiles, not off the account.
+REDDIT_ADS_FANOUT: dict[str, DependentEndpointConfig] = {
+ "structured_posts": DependentEndpointConfig(
+ parent_name="profiles",
+ resolve_param="profile_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ # Post rows carry a nullable `profile_id`; the parent id we fetched under is authoritative.
+ parent_field_renames={"id": "profile_id"},
+ ),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/source.py
index 4ec3e531280a..b84338ce26ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/source.py
@@ -223,6 +223,7 @@ class RedditAdsSource(ResumableSource[RedditAdsSourceConfig, RedditAdsResumeConf
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 REDDIT_ADS_CONFIG.values()
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_ads.py
index f90e2621bec1..e86d36a7a15f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_ads.py
@@ -1,3 +1,4 @@
+import json
import datetime as dt
from typing import Any, Optional
@@ -5,6 +6,7 @@ import pytest
from unittest import mock
from parameterized import parameterized
+from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
IntegrationAccountListingError,
@@ -16,7 +18,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads
get_resource,
list_business_ad_accounts,
list_businesses,
+ reddit_ads_source,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.settings import REDDIT_ADS_CONFIG
class TestRedditAdsHelperFunctions:
@@ -127,6 +131,77 @@ class TestGetResource:
resource = get_resource("campaigns", "test_account", False)
assert isinstance(resource["endpoint"], dict)
+ @parameterized.expand(
+ [
+ ("ad_account", "/ad_accounts/test_account"),
+ ("custom_audiences", "/ad_accounts/test_account/custom_audiences"),
+ ("saved_audiences", "/ad_accounts/test_account/saved_audiences"),
+ ("pixels", "/ad_accounts/test_account/pixels"),
+ ("funding_instruments", "/ad_accounts/test_account/funding_instruments"),
+ ("lead_gen_forms", "/ad_accounts/test_account/lead_gen_forms"),
+ ("profiles", "/ad_accounts/test_account/profiles"),
+ ]
+ )
+ def test_account_scoped_list_endpoints_bind_the_account_id(self, endpoint: str, expected_path: str) -> None:
+ resource = get_resource(endpoint, "test_account", False)
+
+ assert isinstance(resource["endpoint"], dict)
+ assert resource["endpoint"]["path"] == expected_path
+ assert resource["endpoint"]["method"] == "GET"
+
+
+class TestBreakdownReportEndpoints:
+ """Reddit returns breakdowns as extra dimensions on the same report request, so each dimension is
+ its own table. The request body has two hard constraints these tests pin down."""
+
+ BREAKDOWN_TABLES = [
+ ("campaign_country_report", "COUNTRY", "country"),
+ ("campaign_gender_report", "GENDER", "gender"),
+ ("campaign_placement_report", "PLACEMENT", "placement"),
+ ("campaign_community_report", "COMMUNITY", "community"),
+ ("campaign_os_type_report", "OS_TYPE", "os_type"),
+ ]
+
+ @parameterized.expand(BREAKDOWN_TABLES)
+ def test_breakdowns_stay_within_reddits_three_dimension_cap(
+ self, endpoint: str, breakdown: str, column: str
+ ) -> None:
+ resource = get_resource(endpoint, "test_account", False)
+
+ assert isinstance(resource["endpoint"], dict)
+ body = resource["endpoint"]["json"]
+ assert body is not None
+ assert body["data"]["breakdowns"] == ["CAMPAIGN_ID", "DATE", breakdown]
+
+ @parameterized.expand(BREAKDOWN_TABLES)
+ def test_breakdown_column_is_part_of_the_primary_key(self, endpoint: str, breakdown: str, column: str) -> None:
+ # Rows only differ by the breakdown value, so leaving it out collapses every dimension value
+ # for a campaign-day onto one row.
+ assert REDDIT_ADS_CONFIG[endpoint].resource["primary_key"] == ["campaign_id", "date", column]
+
+ @parameterized.expand(
+ [
+ # Dimensions Reddit accepts in both `breakdowns` and `fields` must be requested as a field,
+ # otherwise the response carries no column to key the row on.
+ ("campaign_country_report", "COUNTRY", True),
+ ("campaign_gender_report", "GENDER", True),
+ ("campaign_placement_report", "PLACEMENT", True),
+ ("campaign_community_report", "COMMUNITY", True),
+ # `OS_TYPE` is a valid breakdown but is not a member of Reddit's `fields` enum — asking for
+ # it as a field is rejected and fails the whole report request.
+ ("campaign_os_type_report", "OS_TYPE", False),
+ ]
+ )
+ def test_dimension_is_requested_as_a_field_only_when_reddit_allows_it(
+ self, endpoint: str, breakdown: str, expected_in_fields: bool
+ ) -> None:
+ resource = get_resource(endpoint, "test_account", False)
+
+ assert isinstance(resource["endpoint"], dict)
+ body = resource["endpoint"]["json"]
+ assert body is not None
+ assert (breakdown in body["data"]["fields"]) is expected_in_fields
+
class TestRedditAdsPaginator:
"""Test RedditAdsPaginator class."""
@@ -337,3 +412,72 @@ class TestListBusinessesAndAdAccounts:
assert [business["id"] for business in businesses] == ["b1", "b2"]
assert session.get.call_args_list[1][0][0] == "https://ads-api.reddit.com/api/v3/me/businesses?page=2"
+
+
+def _http_response(body: Any) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+class TestRedditAdsListEndpointTransport:
+ """Behaviour of the endpoints added on top of the original six, driven through a mocked session."""
+
+ SESSION_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source."
+ "rest_client.make_tracked_session"
+ )
+
+ def _run(self, endpoint: str, responses: list[Response]) -> tuple[list[Any], mock.MagicMock]:
+ with mock.patch(self.SESSION_PATH) as MockSession:
+ session = MockSession.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda req: req
+ session.send.side_effect = responses
+
+ source = reddit_ads_source(
+ account_id="789",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ access_token="test_token",
+ db_incremental_field_last_value=None,
+ resumable_source_manager=mock.MagicMock(can_resume=mock.MagicMock(return_value=False)),
+ should_use_incremental_field=False,
+ )
+ pages = list(source.items())
+ return [row for page in pages for row in page], session
+
+ def test_single_object_ad_account_response_yields_one_row(self):
+ # `GET /ad_accounts/{id}` returns one object rather than a list, and the pipeline must still
+ # see a row rather than choking on the unwrapped dict.
+ rows, session = self._run(
+ "ad_account",
+ [_http_response({"data": {"id": "a2_789", "currency": "USD", "time_zone_id": "America/Los_Angeles"}})],
+ )
+
+ assert rows == [{"id": "a2_789", "currency": "USD", "time_zone_id": "America/Los_Angeles"}]
+ assert session.send.call_args_list[0].args[0].url == "https://ads-api.reddit.com/api/v3/ad_accounts/789"
+
+ def test_structured_posts_are_fanned_out_over_every_profile(self):
+ # Reddit hangs creatives off profiles, not off the ad account, so this is the only endpoint
+ # that has to walk a parent list first.
+ rows, session = self._run(
+ "structured_posts",
+ [
+ _http_response({"data": [{"id": "t2_p1"}, {"id": "t2_p2"}], "pagination": {}}),
+ _http_response({"data": [{"id": "post-1", "profile_id": None}], "pagination": {}}),
+ _http_response({"data": [{"id": "post-2", "profile_id": None}], "pagination": {}}),
+ ],
+ )
+
+ requested = [call.args[0].url for call in session.send.call_args_list]
+ assert requested[0].startswith("https://ads-api.reddit.com/api/v3/ad_accounts/789/profiles")
+ assert "/profiles/t2_p1/structured_posts" in requested[1]
+ assert "/profiles/t2_p2/structured_posts" in requested[2]
+
+ # The parent id is authoritative: post rows carry a nullable `profile_id`, but the primary key
+ # is (profile_id, id), so an unpopulated one would collapse posts across profiles.
+ assert [(row["profile_id"], row["id"]) for row in rows] == [("t2_p1", "post-1"), ("t2_p2", "post-2")]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_source.py
index 0e3c65c8b84b..278eacc2e153 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/tests/test_reddit_source.py
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads
RedditAdsApiError,
RedditAdsResumeConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.settings import REDDIT_ADS_CONFIG
from products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.source import RedditAdsSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -233,13 +234,51 @@ class TestRedditAdsSource:
"""Test get_schemas returns all endpoint schemas."""
schemas = self.source.get_schemas(self.config, self.team_id)
- # Should have schemas for all endpoints in REDDIT_ADS_CONFIG
- expected_endpoints = ["campaigns", "ad_groups", "ads", "campaign_report", "ad_group_report", "ad_report"]
+ expected_endpoints = set(REDDIT_ADS_CONFIG)
+ assert {schema.name for schema in schemas} == expected_endpoints
assert len(schemas) == len(expected_endpoints)
- schema_names = [schema.name for schema in schemas]
- for endpoint in expected_endpoints:
- assert endpoint in schema_names
+ @pytest.mark.parametrize(
+ "endpoint",
+ [
+ "ad_account",
+ "custom_audiences",
+ "saved_audiences",
+ "pixels",
+ "funding_instruments",
+ "lead_gen_forms",
+ "profiles",
+ "structured_posts",
+ ],
+ )
+ def test_list_endpoints_without_a_server_side_time_filter_are_not_incremental(self, endpoint):
+ # Reddit's entity list endpoints take only `page.token` / `page.size` and value filters, so an
+ # "incremental" sync would re-fetch every page while merging on a cursor Reddit never applied.
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ @pytest.mark.parametrize(
+ "endpoint,should_sync_default",
+ [
+ ("campaigns", True),
+ ("campaign_report", True),
+ ("ad_account", True),
+ ("pixels", True),
+ # Breakdown reports fan a campaign-day out across every dimension value, so they cost far
+ # more than the totals tables and stay off until the user opts in.
+ ("campaign_country_report", False),
+ ("campaign_gender_report", False),
+ ("campaign_placement_report", False),
+ ("campaign_community_report", False),
+ ("campaign_os_type_report", False),
+ ],
+ )
+ def test_expensive_breakdown_reports_are_not_selected_by_default(self, endpoint, should_sync_default):
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ assert schema.should_sync_default is should_sync_default
def test_get_resumable_source_manager(self):
"""The source must expose a ResumableSourceManager instance."""