: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): implement openai_ads import source (#72649)
Tom Owersce4eb293e9de
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 8a763b3e4c1c..2b721fda332d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -379,6 +379,7 @@ the row lists both.| onfleet | HTTP (cursor pagination) | requests | ✅ || open_exchange_rates | HTTP | requests | ✅ || openai | HTTP | requests | ✅ |+| openai_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || opinion_stage | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || orca_security | HTTP (POST query DSL) | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openaiads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openaiads.pyindex 0cd60b1ba1ab..ac0dee2a7ac0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openaiads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openaiads.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass OpenAIAdsSourceConfig(config.Config):- pass+ api_key: strdiff --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.pynew file mode 100644index 000000000000..98bb83ff0323--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/canonical_descriptions.py@@ -0,0 +1,108 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_INSIGHTS_COMMON_COLUMNS = {+ "id": "Composite bucket identifier (start=<unix>:end=<unix>:entity_id=<id>), unique per time bucket and entity.",+ "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.",+ "impressions": "Number of times ads were shown during the bucket.",+ "clicks": "Number of clicks recorded during the bucket.",+ "spend": "Amount spent during the bucket, in the ad account's currency (decimal, not micros).",+ "ctr": "Click-through rate: clicks divided by impressions.",+ "cpc": "Average cost per click, in the ad account's currency.",+ "cpm": "Average cost per thousand impressions, in the ad account's currency.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "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",+ "columns": {+ "id": "Unique identifier for the campaign.",+ "name": "Internal campaign name (not shown to users).",+ "description": "Optional campaign description.",+ "status": "Delivery status: active, paused, or archived.",+ "bidding_type": "What the campaign bids on: impressions, clicks, or conversions.",+ "budget": "Budget object, including the lifetime spend limit in micros of the account currency.",+ "targeting": "Targeting object, including the locations the campaign delivers to.",+ "conversion_event_setting_ids": "Conversion event settings attached to the campaign.",+ "mode": "Campaign mode; product_feed for product-feed campaigns.",+ "start_time": "Unix timestamp the campaign starts delivering.",+ "end_time": "Unix timestamp the campaign stops delivering, if set.",+ "created_at": "Unix timestamp the campaign was created.",+ "updated_at": "Unix timestamp the campaign was last updated.",+ },+ },+ "ad_groups": {+ "description": "Ad groups in the ad account, listed per parent campaign. An ad group defines the bidding configuration and audience hints for the ads it contains.",+ "docs_url": "https://developers.openai.com/ads/api-reference/ad-groups",+ "columns": {+ "id": "Unique identifier for the ad group.",+ "campaign_id": "Identifier of the parent campaign (stamped from the listing request).",+ "name": "Internal ad group name (not shown to users).",+ "description": "Optional ad group description.",+ "status": "Delivery status: active, paused, or archived.",+ "context_hints": "Free-form audience or placement hints.",+ "bidding_config": "Bidding configuration: billing event type (impression or click) and max bid in micros.",+ "created_at": "Unix timestamp the ad group was created.",+ "updated_at": "Unix timestamp the ad group was last updated.",+ },+ },+ "ads": {+ "description": "Ads in the ad account, listed per parent ad group. An ad carries the creative (title, body, image, target URL) shown to users in ChatGPT.",+ "docs_url": "https://developers.openai.com/ads/api-reference/ads",+ "columns": {+ "id": "Unique identifier for the ad.",+ "ad_group_id": "Identifier of the parent ad group (stamped from the listing request).",+ "campaign_id": "Identifier of the grandparent campaign (stamped from the listing request).",+ "name": "Internal ad name (not shown to users).",+ "status": "Delivery status: active, paused, or archived.",+ "review_status": "Ad review outcome: in_review, approved, or rejected.",+ "creative": "Creative object: type (chat_card or product_ad_template), title, body, image, target URL, and optional price.",+ "created_at": "Unix timestamp the ad was created.",+ "updated_at": "Unix timestamp the ad was last updated.",+ },+ },+ "campaign_insights": {+ "description": "Daily delivery metrics per campaign: impressions, clicks, spend, CTR, CPC, and CPM.",+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",+ "columns": {+ **_INSIGHTS_COMMON_COLUMNS,+ "campaign_id": "Identifier of the campaign the row aggregates.",+ "campaign_name": "Name of the campaign the row aggregates.",+ "campaign_status": "Status of the campaign at query time.",+ },+ },+ "ad_group_insights": {+ "description": "Daily delivery metrics per ad group: impressions, clicks, spend, CTR, CPC, and CPM.",+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",+ "columns": {+ **_INSIGHTS_COMMON_COLUMNS,+ "ad_group_id": "Identifier of the ad group the row aggregates.",+ "ad_group_name": "Name of the ad group the row aggregates.",+ "ad_group_status": "Status of the ad group at query time.",+ },+ },+ "ad_insights": {+ "description": "Daily delivery metrics per ad: impressions, clicks, spend, CTR, CPC, and CPM.",+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",+ "columns": {+ **_INSIGHTS_COMMON_COLUMNS,+ "ad_id": "Identifier of the ad the row aggregates.",+ "ad_name": "Internal name of the ad the row aggregates.",+ "ad_title": "Creative title of the ad the row aggregates.",+ "ad_status": "Status of the ad at query time.",+ "ad_review_status": "Review status of the ad at query time.",+ },+ },+ "ad_account_insights": {+ "description": "Daily delivery metrics for the whole ad account: impressions, clicks, spend, CTR, CPC, and CPM.",+ "docs_url": "https://developers.openai.com/ads/api-reference/insights",+ "columns": {+ **_INSIGHTS_COMMON_COLUMNS,+ "ad_account_name": "Name of the ad account the row aggregates.",+ },+ },+}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.pynew file mode 100644index 000000000000..b361d7b0bda6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/openai_ads.py@@ -0,0 +1,303 @@+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++from dateutil import parser+from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+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.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.settings import (+ INSIGHTS_PAGE_SIZE,+ LIST_PAGE_SIZE,+ OPENAI_ADS_BASE_URL,+ OPENAI_ADS_ENDPOINTS,+ OpenAIAdsEndpointConfig,+)++# Floor for the insights window on a full refresh. OpenAI Ads launched to advertisers in 2026, so+# no reporting data can predate this; the whole window rides a single date_range request, so a+# generous floor costs nothing while staying within the API's 5-year time-range bound.+DEFAULT_INSIGHTS_SINCE = date(2025, 1, 1)+++class OpenAIAdsResumeConfig:+ # `after` cursor for the page the sync should resume at. None means "start at the first page".+ cursor: str | None = None+ # Insights only: the date window (ISO dates) the saved cursor was issued for. A resumed sync+ # must reuse the exact window — recomputing "until" as a later day would pair the cursor with+ # a different result set.+ since: str | None = None+ until: str | None = None+++class _ListPaginator(BasePaginator):+ """OpenAI-style list pagination: an `after` object-id cursor.++ `last_id` drives the next page, falling back to the last item's id so pagination keeps moving+ if `last_id` is ever absent. `has_more` is the authoritative stop signal — the API returns a+ `last_id` on the final page too, so a present token alone can't be trusted.+ """++ def __init__(self) -> None:+ super().__init__()+ self._after: Optional[str] = None++ def _apply(self, request: Request) -> None:+ if self._after is not None:+ if request.params is None:+ request.params = {}+ request.params["after"] = self._after++ def init_request(self, request: Request) -> None:+ # Apply a seeded resume cursor to the first request.+ self._apply(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except Exception:+ body = None+ if not isinstance(body, dict):+ self._has_next_page = False+ return+ items = data or []+ last_id = body.get("last_id") or (items[-1].get("id") if items and isinstance(items[-1], dict) else None)+ if body.get("has_more") and last_id:+ self._after = last_id+ self._has_next_page = True+ else:+ self._has_next_page = False++ def update_request(self, request: Request) -> None:+ self._apply(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._after} if self._has_next_page and self._after is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._after = cursor+ self._has_next_page = True++ def __str__(self) -> str:+ return "_ListPaginator()"+++def _headers() -> dict[str, str]:+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from logs+ # and raised errors; only the non-secret accept header is set here.+ return {"Accept": "application/json"}+++def validate_credentials(api_key: str) -> bool:+ # One cheap probe against the campaigns list confirms the key is genuine. 200 => valid.+ # 403 => a real key the API recognizes but with restricted access; accept it at create time+ # (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{OPENAI_ADS_BASE_URL}/v1/campaigns?limit=1",+ headers={"Authorization": f"Bearer {api_key}", **_headers()},+ ok_statuses=(200, 403),+ )+ return ok+++def _to_utc_date(value: Any) -> date:+ """Coerce an incremental watermark (datetime/date/epoch/str) to a UTC calendar date."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).date()+ if isinstance(value, date):+ return value+ if isinstance(value, int | float):+ return datetime.fromtimestamp(value, tz=UTC).date()+ return parser.parse(str(value)).astimezone(UTC).date()+++def _insights_window(db_incremental_field_last_value: Optional[Any]) -> tuple[str, str]:+ """The [since, until] ISO date window for one insights sync.++ Incremental runs start at the watermark (the pipeline already rewinds it by the configured+ lookback); full refreshes start at the product-launch floor. `until` is today — the API+ rejects future dates.+ """+ until = datetime.now(tz=UTC).date()+ since = DEFAULT_INSIGHTS_SINCE+ if db_incremental_field_last_value is not None:+ since = _to_utc_date(db_incremental_field_last_value)+ since = min(since, until)+ return since.isoformat(), until.isoformat()+++def _convert_insights_times(row: dict[str, Any]) -> dict[str, Any]:+ # Bucket bounds arrive as epoch seconds; real timestamps are needed for the DateTime+ # incremental watermark and datetime partitioning.+ row = {**row}+ for key in ("start_time", "end_time"):+ value = row.get(key)+ if isinstance(value, int | float):+ row[key] = datetime.fromtimestamp(value, tz=UTC)+ return row+++def _make_client(api_key: str) -> RESTClient:+ return RESTClient(+ base_url=OPENAI_ADS_BASE_URL,+ headers=_headers(),+ auth=BearerTokenAuth(api_key),+ )+++def _list_pages(client: RESTClient, path: str, params: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:+ yield from client.paginate(+ path=path,+ params=params,+ paginator=_ListPaginator(),+ data_selector="data",+ )+++def _fan_out_rows(client: RESTClient, endpoint: str) -> Iterator[list[dict[str, Any]]]:+ """Walk the campaign hierarchy for the fan-out entity streams.++ Ad groups list per campaign and ads list per ad group — both via required query params the+ declarative fan-out can't bind (it only resolves path placeholders). The response objects+ don't carry their parent ids, so every row is stamped with its lineage; the composite primary+ keys in settings.py rely on those stamped columns.+ """+ for campaign_page in _list_pages(client, "/v1/campaigns", {"limit": LIST_PAGE_SIZE, "order": "asc"}):+ for campaign in campaign_page:+ campaign_id = campaign.get("id")+ if campaign_id is None:+ continue+ for ad_group_page in _list_pages(+ client, "/v1/ad_groups", {"campaign_id": campaign_id, "limit": LIST_PAGE_SIZE, "order": "asc"}+ ):+ if endpoint == "ad_groups":+ yield [{**row, "campaign_id": campaign_id} for row in ad_group_page]+ continue+ for ad_group in ad_group_page:+ ad_group_id = ad_group.get("id")+ if ad_group_id is None:+ continue+ for ad_page in _list_pages(+ client, "/v1/ads", {"ad_group_id": ad_group_id, "limit": LIST_PAGE_SIZE, "order": "asc"}+ ):+ yield [{**row, "campaign_id": campaign_id, "ad_group_id": ad_group_id} for row in ad_page]+++def _source_response(config: OpenAIAdsEndpointConfig, items: Any, column_hints: Any = None) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=column_hints,+ )+++def openai_ads_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[OpenAIAdsResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = OPENAI_ADS_ENDPOINTS[endpoint]++ if endpoint in ("ad_groups", "ads"):+ # Multi-level fan-out with query-param parents: hand-rolled over the tracked, retrying+ # RESTClient. Not resumable — a retry re-walks the hierarchy and full refresh replaces.+ client = _make_client(api_key)+ return _source_response(config, lambda: _fan_out_rows(client, endpoint))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.aggregation_level is not None:+ if resume is not None and resume.since and resume.until:+ since, until = resume.since, resume.until+ else:+ since, until = _insights_window(db_incremental_field_last_value)+ params: dict[str, Any] = {+ "aggregation_level": config.aggregation_level,+ "time_granularity": "daily",+ "limit": INSIGHTS_PAGE_SIZE,+ # `requests` encodes the list as one repeated fields[] query param per element.+ "fields[]": list(config.insights_fields),+ # One JSON-encoded time-range object; the explicit timezone keeps daily buckets (and+ # therefore the bucket ids merge dedupes on) stable across runs.+ "time_ranges[]": json.dumps({"type": "date_range", "since": since, "until": until, "timezone": "UTC"}),+ }+ data_map = _convert_insights_times+ else:+ since = until = ""+ # An explicit stable sort prevents page-boundary skips/duplicates while paginating the+ # full campaign list.+ params = {"limit": LIST_PAGE_SIZE, "order": "asc"}+ data_map = None++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": OPENAI_ADS_BASE_URL,+ "headers": _headers(),+ "auth": {"type": "bearer", "token": api_key},+ },+ "resource_defaults": None,+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": "data",+ "paginator": _ListPaginator(),+ },+ "data_map": data_map,+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume is not None and resume.cursor:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; the checkpoint is saved AFTER a page is yielded,+ # pointing at the next page, so a crash resumes from a page whose predecessors were all+ # yielded — the overlap merge dedupes on the primary key. Insights pin their window so the+ # resumed cursor pairs with the result set it was issued for.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(+ OpenAIAdsResumeConfig(cursor=state["cursor"], since=since or None, until=until or None)+ )++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return _source_response(config, lambda: resource, column_hints=resource.column_hints)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.pynew file mode 100644index 000000000000..c3a25f60cd36--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/settings.py@@ -0,0 +1,120 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++OPENAI_ADS_BASE_URL = "https://api.ads.openai.com"++# Entity list endpoints (campaigns, ad groups, ads) allow up to 500 per page.+LIST_PAGE_SIZE = 500+# Insights allow up to 2000 per page; 500 keeps individual pages modest.+INSIGHTS_PAGE_SIZE = 500++# Insights buckets for recent days get restated as reporting catches up (delivery is real-time,+# reporting is not), so each incremental run re-reads a trailing window and merge dedupes on the+# bucket row id.+INSIGHTS_LOOKBACK_SECONDS = 60 * 60 * 24 * 3++# Delivery metrics exposed by every insights aggregation level, requested as+# `{aggregation_level}.{metric}` and returned as bare wire keys (impressions, clicks, ...).+_INSIGHTS_METRICS = ("impressions", "clicks", "spend", "ctr", "cpc", "cpm")+++def _insights_fields(level: str, metadata: tuple[str, ...]) -> list[str]:+ return [+ "metadata.readable_time",+ *(f"{level}.{name}" for name in metadata),+ *(f"{level}.{metric}" for metric in _INSIGHTS_METRICS),+ ]+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class OpenAIAdsEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ # Stable creation-style timestamp used for datetime partitioning — never an+ # `updated_at`-style field.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only True where the API has a genuine server-side time filter: the insights endpoints'+ # `time_ranges[]`. Entity lists expose created_at/updated_at on rows but no date filter+ # param, so they are full-refresh only.+ supports_incremental: bool = False+ sort_mode: SortMode = "asc"+ # Insights-only: the `aggregation_level` picking the row entity, and the `fields[]`+ # projection requested for that level.+ aggregation_level: Optional[str] = None+ insights_fields: list[str] = field(default_factory=list)+ default_incremental_lookback_seconds: Optional[int] = None+++def _insights_endpoint(name: str, level: str, 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).+ primary_keys=["id"],+ partition_key="start_time",+ incremental_fields=[_datetime_incremental_field("start_time")],+ supports_incremental=True,+ # Row ordering within a multi-day window is undocumented and unverified, so "desc" makes+ # the pipeline commit the incremental watermark only at sync completion — correct+ # regardless of arrival order.+ sort_mode="desc",+ aggregation_level=level,+ insights_fields=_insights_fields(level, metadata),+ default_incremental_lookback_seconds=INSIGHTS_LOOKBACK_SECONDS,+ )+++OPENAI_ADS_ENDPOINTS: dict[str, OpenAIAdsEndpointConfig] = {+ "campaigns": OpenAIAdsEndpointConfig(+ name="campaigns",+ path="/v1/campaigns",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ # `GET /v1/ad_groups` requires a `campaign_id` query param, so ad groups fan out one+ # listing per campaign. The response objects don't carry their parent id — the transport+ # stamps `campaign_id` onto every row, and the key is composite because ad group id+ # uniqueness across campaigns isn't documented.+ "ad_groups": OpenAIAdsEndpointConfig(+ name="ad_groups",+ path="/v1/ad_groups",+ primary_keys=["campaign_id", "id"],+ partition_key="created_at",+ ),+ # `GET /v1/ads` requires an `ad_group_id` query param — a two-level fan-out+ # (campaigns -> ad groups -> ads). Rows are stamped with both parent ids.+ "ads": OpenAIAdsEndpointConfig(+ name="ads",+ path="/v1/ads",+ primary_keys=["ad_group_id", "id"],+ partition_key="created_at",+ ),+ "campaign_insights": _insights_endpoint("campaign_insights", "campaign", ("id", "name", "status")),+ "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",)),+}++ENDPOINTS = tuple(OPENAI_ADS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OPENAI_ADS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.pyindex ab6fd58aae50..226bebc0b547 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/source.py@@ -1,21 +1,46 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.openaiads import (OpenAIAdsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.openai_ads import (+ OpenAIAdsResumeConfig,+ openai_ads_source,+ validate_credentials as validate_openai_ads_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ OPENAI_ADS_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OpenAIAdsSource(SimpleSource[OpenAIAdsSourceConfig]):+class OpenAIAdsSource(ResumableSource[OpenAIAdsSourceConfig, OpenAIAdsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://developers.openai.com/ads/api-overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPENAIADS@@ -26,7 +51,91 @@ class OpenAIAdsSource(SimpleSource[OpenAIAdsSourceConfig]):name=SchemaExternalDataSourceType.OPEN_AI_ADS,category=DataWarehouseSourceCategory.ADVERTISING,label="OpenAI Ads",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your OpenAI Ads API key to pull your campaigns, ad groups, ads, and performance insights into the PostHog Data warehouse.++Create an API key in the Settings tab of [OpenAI Ads Manager](https://ads.openai.com). Each key is scoped to a single ad account — to import more than one ad account, connect one source per account.""",iconPath="/static/services/openai_ads.svg",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/openai-ads",+ keywords=["chatgpt", "chatgpt ads", "openai advertising"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.ads.openai.com": "Your OpenAI Ads API key is invalid or has been revoked. Create a new API key in the Settings tab of OpenAI Ads Manager, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.ads.openai.com": "Your OpenAI Ads API key does not have access to this ad account. Create a key for this ad account in the Settings tab of OpenAI Ads Manager, then reconnect.",+ }++ def get_schemas(+ self,+ config: OpenAIAdsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = OPENAI_ADS_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ # Insights buckets get restated as reporting catches up, so append would+ # materialize duplicates; entity lists are full refresh only.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: OpenAIAdsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_openai_ads_credentials(config.api_key):+ return True, None++ return False, "Invalid OpenAI Ads API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAIAdsResumeConfig]:+ return ResumableSourceManager[OpenAIAdsResumeConfig](inputs, OpenAIAdsResumeConfig)++ def source_for_pipeline(+ self,+ config: OpenAIAdsSourceConfig,+ resumable_source_manager: ResumableSourceManager[OpenAIAdsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return openai_ads_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)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.pynew file mode 100644index 000000000000..9e8a749df4fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads.py@@ -0,0 +1,320 @@+import json+from datetime import UTC, datetime+from typing import Any++from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.openai_ads import (+ OpenAIAdsResumeConfig,+ openai_ads_source,+ validate_credentials,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the openai_ads module.+OPENAI_ADS_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.openai_ads.make_tracked_session"+)+++def _response(body: dict[str, Any], status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = json.dumps(body).encode()+ resp.url = "https://api.ads.openai.com/v1/campaigns"+ return resp+++def _page(items: list[dict[str, Any]], *, has_more: bool, last_id: str | None = None) -> Response:+ body: dict[str, Any] = {"object": "list", "data": items, "has_more": has_more}+ if last_id is not None:+ body["last_id"] = last_id+ return _response(body)+++def _make_manager(resume_state: OpenAIAdsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's url + params AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, last_value: Any = None):+ return openai_ads_source(+ api_key="oa-ads-test",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ db_incremental_field_last_value=last_value,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestListPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_cursor_pagination_uses_after_and_stops_on_has_more_false(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page([{"id": "cmpn_1"}], has_more=True, last_id="cmpn_1"),+ # Final page still carries a last_id — has_more must stop the walk with no extra call.+ _page([{"id": "cmpn_2"}], has_more=False, last_id="cmpn_2"),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("campaigns", manager))++ assert [r["id"] for r in rows] == ["cmpn_1", "cmpn_2"]+ assert "after" not in params[0]["params"]+ assert params[0]["params"]["limit"] == 500+ assert params[0]["params"]["order"] == "asc"+ assert params[1]["params"]["after"] == "cmpn_1"+ assert session.send.call_count == 2+ # Checkpoint saved after the first page was yielded, pointing at the next page.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == OpenAIAdsResumeConfig(cursor="cmpn_1")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_falls_back_to_last_item_id_when_last_id_missing(self, MockSession) -> None:+ # If `last_id` is ever absent, the last item's id must keep pagination moving instead of+ # stopping after page one.+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page([{"id": "cmpn_1"}], has_more=True),+ _page([{"id": "cmpn_2"}], has_more=False),+ ],+ )++ rows = _rows(_source("campaigns", _make_manager()))++ assert [r["id"] for r in rows] == ["cmpn_1", "cmpn_2"]+ assert params[1]["params"]["after"] == "cmpn_1"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_after_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_page([{"id": "cmpn_6"}], has_more=False, last_id="cmpn_6")])++ _rows(_source("campaigns", _make_manager(OpenAIAdsResumeConfig(cursor="cmpn_5"))))++ assert params[0]["params"]["after"] == "cmpn_5"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_missing_data_key_yields_no_rows(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"object": "list", "has_more": False})])++ assert _rows(_source("campaigns", _make_manager())) == []+++class TestFanOut:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_ad_groups_listed_per_campaign_and_stamped_with_campaign_id(self, MockSession) -> None:+ # The API requires campaign_id as a query param and the ad group objects don't carry+ # their parent id — the stamped column is what the composite primary key merges on.+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page([{"id": "cmpn_1"}, {"id": "cmpn_2"}], has_more=False, last_id="cmpn_2"),+ _page([{"id": "adgrp_1"}], has_more=False, last_id="adgrp_1"),+ _page([{"id": "adgrp_2"}], has_more=False, last_id="adgrp_2"),+ ],+ )++ rows = _rows(_source("ad_groups", _make_manager()))++ assert [(r["campaign_id"], r["id"]) for r in rows] == [("cmpn_1", "adgrp_1"), ("cmpn_2", "adgrp_2")]+ assert params[0]["url"].endswith("/v1/campaigns")+ assert params[1]["url"].endswith("/v1/ad_groups")+ assert params[1]["params"]["campaign_id"] == "cmpn_1"+ assert params[2]["params"]["campaign_id"] == "cmpn_2"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_ads_walk_both_levels_and_carry_full_lineage(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page([{"id": "cmpn_1"}], has_more=False, last_id="cmpn_1"),+ _page([{"id": "adgrp_1"}, {"id": "adgrp_2"}], has_more=False, last_id="adgrp_2"),+ _page([{"id": "ad_1"}], has_more=False, last_id="ad_1"),+ _page([{"id": "ad_2"}], has_more=False, last_id="ad_2"),+ ],+ )++ rows = _rows(_source("ads", _make_manager()))++ assert [(r["campaign_id"], r["ad_group_id"], r["id"]) for r in rows] == [+ ("cmpn_1", "adgrp_1", "ad_1"),+ ("cmpn_1", "adgrp_2", "ad_2"),+ ]+ assert params[2]["params"]["ad_group_id"] == "adgrp_1"+ assert params[3]["params"]["ad_group_id"] == "adgrp_2"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_child_pagination_within_one_parent(self, MockSession) -> None:+ # The child listing itself paginates with the same after cursor; page two must keep the+ # parent's campaign_id param.+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page([{"id": "cmpn_1"}], has_more=False, last_id="cmpn_1"),+ _page([{"id": "adgrp_1"}], has_more=True, last_id="adgrp_1"),+ _page([{"id": "adgrp_2"}], has_more=False, last_id="adgrp_2"),+ ],+ )++ rows = _rows(_source("ad_groups", _make_manager()))++ assert [(r["campaign_id"], r["id"]) for r in rows] == [("cmpn_1", "adgrp_1"), ("cmpn_1", "adgrp_2")]+ assert params[2]["params"] == {"campaign_id": "cmpn_1", "limit": 500, "order": "asc", "after": "adgrp_1"}+++class TestInsights:+ @freeze_time("2026-07-21")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_windows_from_watermark_to_today(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_page([], has_more=False)])++ watermark = datetime(2026, 7, 1, 12, 30, tzinfo=UTC)+ _rows(_source("campaign_insights", _make_manager(), last_value=watermark))++ sent = params[0]["params"]+ assert sent["aggregation_level"] == "campaign"+ assert sent["time_granularity"] == "daily"+ assert json.loads(sent["time_ranges[]"]) == {+ "type": "date_range",+ "since": "2026-07-01",+ "until": "2026-07-21",+ "timezone": "UTC",+ }+ # The explicit projection must keep the metrics and the bucket label in the rows.+ assert "campaign.spend" in sent["fields[]"]+ assert "metadata.readable_time" in sent["fields[]"]++ @freeze_time("2026-07-21")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_refresh_windows_from_product_launch_floor(self, MockSession) -> None:+ # Without a watermark we still need a bounded window — the API rejects unbounded/future+ # ranges — and it must cover all possible history for the product.+ session = MockSession.return_value+ params = _wire(session, [_page([], has_more=False)])++ _rows(_source("ad_account_insights", _make_manager()))++ assert json.loads(params[0]["params"]["time_ranges[]"])["since"] == "2025-01-01"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bucket_times_become_datetimes(self, MockSession) -> None:+ # start_time is the DateTime incremental watermark and the partition key — epoch ints+ # would break both.+ session = MockSession.return_value+ _wire(+ session,+ [+ _page(+ [+ {+ "id": "start=1777075200:end=1777161600:entity_id=cmpn_1",+ "start_time": 1777075200,+ "end_time": 1777161600,+ "impressions": 5,+ }+ ],+ has_more=False,+ )+ ],+ )++ rows = _rows(_source("campaign_insights", _make_manager()))++ assert rows[0]["start_time"] == datetime(2026, 4, 25, tzinfo=UTC)+ assert rows[0]["end_time"] == datetime(2026, 4, 26, tzinfo=UTC)+ assert rows[0]["impressions"] == 5++ @freeze_time("2026-07-21")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoint_pins_the_window_alongside_the_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _page([{"id": "b1", "start_time": 1, "end_time": 2}], has_more=True, last_id="b1"),+ _page([{"id": "b2", "start_time": 2, "end_time": 3}], has_more=False, last_id="b2"),+ ],+ )++ manager = _make_manager()+ _rows(_source("campaign_insights", manager, last_value=datetime(2026, 7, 1, tzinfo=UTC)))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == OpenAIAdsResumeConfig(+ cursor="b1", since="2026-07-01", until="2026-07-21"+ )++ @freeze_time("2026-07-21")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_reuses_the_pinned_window_with_the_saved_cursor(self, MockSession) -> None:+ # A cursor is only valid for the result set it was issued for — recomputing `until` as a+ # later day on resume would pair it with a different window.+ session = MockSession.return_value+ params = _wire(session, [_page([], has_more=False)])++ resume = OpenAIAdsResumeConfig(cursor="b1", since="2026-06-01", until="2026-07-19")+ _rows(_source("campaign_insights", _make_manager(resume)))++ sent = params[0]["params"]+ assert sent["after"] == "b1"+ window = json.loads(sent["time_ranges[]"])+ assert (window["since"], window["until"]) == ("2026-06-01", "2026-07-19")+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("forbidden_scope", 403, True), ("unauthorized", 401, False)])+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ # 403 is accepted at create time (a real key with restricted access); 401 means a bad key.+ session = mock.MagicMock()+ session.get.return_value = mock.MagicMock(status_code=status)+ with mock.patch(OPENAI_ADS_SESSION_PATCH, return_value=session):+ assert validate_credentials("oa-ads-test") is expected++ def test_network_error_is_invalid(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch(OPENAI_ADS_SESSION_PATCH, return_value=session):+ assert validate_credentials("oa-ads-test") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads_source.pynew file mode 100644index 000000000000..636a32cbdac3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai_ads/tests/test_openai_ads_source.py@@ -0,0 +1,145 @@+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.openai_ads import OpenAIAdsResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.openai_ads.source import OpenAIAdsSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_ENTITY_ENDPOINTS = ["campaigns", "ad_groups", "ads"]+_INSIGHTS_ENDPOINTS = ["campaign_insights", "ad_group_insights", "ad_insights", "ad_account_insights"]+++class TestOpenAIAdsSourceConfig:+ def test_source_type(self) -> None:+ assert OpenAIAdsSource().source_type == ExternalDataSourceType.OPENAIADS++ def test_config_is_released_with_single_secret_api_key_field(self) -> None:+ config = OpenAIAdsSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.OPEN_AI_ADS+ # A finished source must be visible: alpha-labelled, never hidden via unreleasedSource.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/openai-ads"+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["api_key"]+ assert fields[0].secret is True and fields[0].required is True+++class TestOpenAIAdsSchemas:+ def test_all_endpoints_present(self) -> None:+ names = {s.name for s in OpenAIAdsSource().get_schemas(MagicMock(), team_id=1)}+ assert names == {*_ENTITY_ENDPOINTS, *_INSIGHTS_ENDPOINTS}++ @parameterized.expand([(endpoint,) for endpoint in _INSIGHTS_ENDPOINTS])+ def test_insights_are_incremental_on_start_time_with_lookback(self, endpoint: str) -> None:+ # Insights have a genuine server-side time filter (time_ranges[]); recent buckets get+ # restated, so a trailing lookback re-reads them and merge dedupes.+ schema = next(s for s in OpenAIAdsSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is True+ assert schema.supports_append is False+ assert [f["field"] for f in schema.incremental_fields] == ["start_time"]+ assert schema.default_incremental_lookback_seconds == 60 * 60 * 24 * 3++ @parameterized.expand([(endpoint,) for endpoint in _ENTITY_ENDPOINTS])+ def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:+ # The list endpoints have no server-side date filter, so they must not advertise incremental.+ schema = next(s for s in OpenAIAdsSource().get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_names_filter(self) -> None:+ schemas = OpenAIAdsSource().get_schemas(MagicMock(), team_id=1, names=["campaigns"])+ assert [s.name for s in schemas] == ["campaigns"]+++class TestOpenAIAdsResumableManager:+ def test_manager_bound_to_resume_config(self) -> None:+ manager = OpenAIAdsSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is OpenAIAdsResumeConfig+++class TestOpenAIAdsSourceForPipeline:+ @parameterized.expand(+ [+ ("campaigns", ["id"], ["created_at"], "asc"),+ ("ad_groups", ["campaign_id", "id"], ["created_at"], "asc"),+ ("ads", ["ad_group_id", "id"], ["created_at"], "asc"),+ # Insights row ordering within a window is unverified, so the watermark must only+ # commit at sync completion.+ ("campaign_insights", ["id"], ["start_time"], "desc"),+ ("ad_account_insights", ["id"], ["start_time"], "desc"),+ ]+ )+ def test_primary_keys_partitioning_and_sort_mode(+ self, endpoint: str, primary_keys: list[str], partition_keys: list[str], sort_mode: str+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ manager = MagicMock()+ manager.can_resume.return_value = False+ response = OpenAIAdsSource().source_for_pipeline(MagicMock(api_key="k"), manager, inputs)+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys+ assert response.partition_mode == "datetime"+ assert response.sort_mode == sort_mode+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.ads.openai.com/v1/campaigns?limit=500",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.ads.openai.com/v1/ad_account/insights",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = OpenAIAdsSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.ads.openai.com', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.ads.openai.com/v1/campaigns",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = OpenAIAdsSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestDocumentedTables:+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # The docs' Supported tables section keys canonical entries by endpoint name — a drifted+ # key silently loses its curated description.+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog => the source opts into publishing its table list to public docs.+ assert OpenAIAdsSource().lists_tables_without_credentials is True+ tables = OpenAIAdsSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ campaign_insights = next(t for t in tables if t["name"] == "campaign_insights")+ assert "Incremental" in campaign_insights["sync_methods"]+ assert campaign_insights["description"]