: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 import source (#70722)
Tom Owersd33019acd5e7
diff --git a/frontend/public/services/openai.svg b/frontend/public/services/openai.svgnew file mode 100644index 000000000000..b3894ecf14e5--- /dev/null+++ b/frontend/public/services/openai.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#000000" role="img" aria-label="OpenAI">+ <path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.073zM13.2599 22.4287a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6469zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.8956zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997z"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 6d60fa909222..d7c75aa8b226 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -302,6 +302,7 @@ the row lists both.| onepagecrm | HTTP | requests | ✅ || onfleet | HTTP (cursor pagination) | requests | ✅ || open_exchange_rates | HTTP | requests | ✅ |+| openai | HTTP | requests | ✅ || opinion_stage | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || openaq | HTTP | requests | ✅ |@@ -764,7 +765,6 @@ doesn't conflict with concurrent PRs.- onepassword- onesignal- open_data_dc-- openai- opsgenie- opuswatch- oraclediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 69df9e5dc62e..d5b049fcc60b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2869,7 +2869,7 @@ class OpenAIAdsSourceConfig(config.Config):@config.configclass OpenAISourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.pynew file mode 100644index 000000000000..d3e68e3fa958--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/canonical_descriptions.py@@ -0,0 +1,229 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS = "https://platform.openai.com/docs/api-reference"++_USAGE_DIMENSION_COLUMNS = {+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "start_time": "Start of the time bucket (inclusive) as a UTC timestamp.",+ "end_time": "End of the time bucket (exclusive) as a UTC timestamp.",+ "project_id": "ID of the project the usage is attributed to, or null.",+ "user_id": "ID of the user the usage is attributed to, or null.",+ "api_key_id": "ID of the API key used, or null.",+ "model": "Model used, or null.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "usage_completions": {+ "description": "Chat and text completions token usage aggregated into daily buckets, broken down by project, user, API key, model, batch, and service tier.",+ "docs_url": f"{_API_DOCS}/usage/completions",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "batch": "Whether the usage came from the Batch API, or null.",+ "service_tier": "Service tier used, or null.",+ "input_tokens": "Aggregated number of text input tokens used, including cached tokens.",+ "input_cached_tokens": "Aggregated number of text input tokens that have been cached from previous requests.",+ "output_tokens": "Aggregated number of text output tokens used.",+ "input_audio_tokens": "Aggregated number of audio input tokens used.",+ "output_audio_tokens": "Aggregated number of audio output tokens used.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_embeddings": {+ "description": "Embeddings token usage aggregated into daily buckets, broken down by project, user, API key, and model.",+ "docs_url": f"{_API_DOCS}/usage/embeddings",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "input_tokens": "Aggregated number of input tokens used.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_moderations": {+ "description": "Moderations token usage aggregated into daily buckets, broken down by project, user, API key, and model.",+ "docs_url": f"{_API_DOCS}/usage/moderations",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "input_tokens": "Aggregated number of input tokens used.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_images": {+ "description": "Image generation usage aggregated into daily buckets, broken down by project, user, API key, model, image size, and source.",+ "docs_url": f"{_API_DOCS}/usage/images",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "size": "Image size (e.g. 1024x1024), or null.",+ "source": "Image operation: image.generation, image.edit, or image.variation, or null.",+ "images": "Number of images processed.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_audio_speeches": {+ "description": "Text-to-speech usage aggregated into daily buckets, broken down by project, user, API key, and model.",+ "docs_url": f"{_API_DOCS}/usage/audio_speeches",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "characters": "Number of characters processed.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_audio_transcriptions": {+ "description": "Speech-to-text usage aggregated into daily buckets, broken down by project, user, API key, and model.",+ "docs_url": f"{_API_DOCS}/usage/audio_transcriptions",+ "columns": {+ **_USAGE_DIMENSION_COLUMNS,+ "seconds": "Number of seconds of audio processed.",+ "num_model_requests": "Count of requests made to the model.",+ },+ },+ "usage_vector_stores": {+ "description": "Vector store storage usage aggregated into daily buckets, broken down by project.",+ "docs_url": f"{_API_DOCS}/usage/vector_stores",+ "columns": {+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "start_time": "Start of the time bucket (inclusive) as a UTC timestamp.",+ "end_time": "End of the time bucket (exclusive) as a UTC timestamp.",+ "project_id": "ID of the project the usage is attributed to, or null.",+ "usage_bytes": "Vector store usage in bytes.",+ },+ },+ "usage_code_interpreter_sessions": {+ "description": "Code interpreter session usage aggregated into daily buckets, broken down by project.",+ "docs_url": f"{_API_DOCS}/usage/code_interpreter_sessions",+ "columns": {+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "start_time": "Start of the time bucket (inclusive) as a UTC timestamp.",+ "end_time": "End of the time bucket (exclusive) as a UTC timestamp.",+ "project_id": "ID of the project the usage is attributed to, or null.",+ "num_sessions": "Number of code interpreter sessions.",+ },+ },+ "costs": {+ "description": "Daily spend for your OpenAI organization, broken down by project, line item, and API key.",+ "docs_url": f"{_API_DOCS}/usage/costs",+ "columns": {+ "id": "Synthesized surrogate key: a hash of the bucket start and every grouping dimension.",+ "start_time": "Start of the time bucket (inclusive) as a UTC timestamp.",+ "end_time": "End of the time bucket (exclusive) as a UTC timestamp.",+ "project_id": "ID of the project the cost is attributed to, or null.",+ "line_item": "Line item the cost is grouped by (e.g. a model and token type), or null.",+ "api_key_id": "ID of the API key the cost is attributed to, or null.",+ "amount_value": "Numeric value of the cost.",+ "amount_currency": "Lowercase ISO-4217 currency code, e.g. usd.",+ "quantity": "Quantity of the line item, when grouped by line item.",+ },+ },+ "projects": {+ "description": "Projects in your OpenAI organization (includes archived projects).",+ "docs_url": f"{_API_DOCS}/projects/list",+ "columns": {+ "id": "Unique identifier for the project.",+ "object": 'Object type, always "organization.project".',+ "name": "Display name of the project.",+ "created_at": "Unix timestamp (seconds) of when the project was created.",+ "archived_at": "Unix timestamp (seconds) of when the project was archived, or null if active.",+ "status": "Project status: active or archived.",+ },+ },+ "users": {+ "description": "Members of your OpenAI organization.",+ "docs_url": f"{_API_DOCS}/users/list",+ "columns": {+ "id": "Unique identifier for the user.",+ "object": 'Object type, always "organization.user".',+ "name": "Display name of the user.",+ "email": "Email address of the user.",+ "role": "Organization role: owner or reader.",+ "added_at": "Unix timestamp (seconds) of when the user joined the organization.",+ },+ },+ "invites": {+ "description": "Pending and historical invitations to join your OpenAI organization.",+ "docs_url": f"{_API_DOCS}/invite/list",+ "columns": {+ "id": "Unique identifier for the invite.",+ "object": 'Object type, always "organization.invite".',+ "email": "Email address the invite was sent to.",+ "role": "Organization role the invited user will receive: owner or reader.",+ "status": "Invite status: accepted, expired, or pending.",+ "invited_at": "Unix timestamp (seconds) of when the invite was created.",+ "expires_at": "Unix timestamp (seconds) of when the invite expires.",+ "accepted_at": "Unix timestamp (seconds) of when the invite was accepted, or null.",+ },+ },+ "admin_api_keys": {+ "description": "Organization-level Admin API keys.",+ "docs_url": f"{_API_DOCS}/admin-api-keys/list",+ "columns": {+ "id": "Unique identifier for the Admin API key.",+ "name": "Display name of the key.",+ "redacted_value": "Partially redacted hint for the key value.",+ "created_at": "Unix timestamp (seconds) of when the key was created.",+ "last_used_at": "Unix timestamp (seconds) of when the key was last used, or null.",+ "owner_type": "Type of the key's owner (user or service_account).",+ "owner_id": "ID of the key's owner.",+ "owner_name": "Display name of the key's owner.",+ },+ },+ "project_users": {+ "description": "Membership rows mapping users to the projects they belong to, one row per (project, user).",+ "docs_url": f"{_API_DOCS}/project-users/list",+ "columns": {+ "project_id": "ID of the project the user is a member of.",+ "id": "Unique identifier for the user.",+ "name": "Display name of the user.",+ "email": "Email address of the user.",+ "role": "Project role: owner or member.",+ "added_at": "Unix timestamp (seconds) of when the user was added to the project.",+ },+ },+ "project_service_accounts": {+ "description": "Service accounts (bot users not tied to a person) in each project.",+ "docs_url": f"{_API_DOCS}/project-service-accounts/list",+ "columns": {+ "project_id": "ID of the project the service account belongs to.",+ "id": "Unique identifier for the service account.",+ "name": "Display name of the service account.",+ "role": "Project role: owner or member.",+ "created_at": "Unix timestamp (seconds) of when the service account was created.",+ },+ },+ "project_api_keys": {+ "description": "API keys provisioned in each project.",+ "docs_url": f"{_API_DOCS}/project-api-keys/list",+ "columns": {+ "project_id": "ID of the project the key belongs to.",+ "id": "Unique identifier for the API key.",+ "name": "Display name of the API key.",+ "redacted_value": "Partially redacted hint for the key value.",+ "created_at": "Unix timestamp (seconds) of when the key was created.",+ "last_used_at": "Unix timestamp (seconds) of when the key was last used, or null.",+ "owner_type": "Type of the key's owner (user or service_account).",+ "owner_id": "ID of the user or service account that owns the key.",+ "owner_name": "Display name of the key's owner.",+ },+ },+ "project_rate_limits": {+ "description": "Per-model rate limit configuration for each project.",+ "docs_url": f"{_API_DOCS}/project-rate-limits/list",+ "columns": {+ "project_id": "ID of the project the rate limit applies to.",+ "id": "Unique identifier for the rate limit, per model.",+ "model": "Model the rate limit applies to.",+ "max_requests_per_1_minute": "Maximum requests allowed per minute.",+ "max_tokens_per_1_minute": "Maximum tokens allowed per minute.",+ },+ },+ "audit_logs": {+ "description": "User actions and configuration changes within your OpenAI organization.",+ "docs_url": f"{_API_DOCS}/audit-logs/list",+ "columns": {+ "id": "Unique identifier for the audit log event.",+ "type": "Event type, e.g. project.created or api_key.deleted.",+ "effective_at": "UTC timestamp of when the event occurred.",+ "actor": "JSON object describing the actor that performed the action (user, API key, or session).",+ "event_data": "JSON object with event-type-specific details.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.pynew file mode 100644index 000000000000..35b28088eb70--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py@@ -0,0 +1,451 @@+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.settings import (+ OPENAI_ENDPOINTS,+ OpenAIEndpointConfig,+ PaginationType,+)++OPENAI_BASE_URL = "https://api.openai.com"+# Entity list endpoints allow up to 100 per page.+ENTITY_PAGE_SIZE = 100+# Floor for the required `start_time` on a full refresh. The OpenAI API launched in mid-2020, so no+# usage or cost data can predate this — starting here rather than the epoch avoids requesting+# decades of empty buckets while still pulling all available history.+DEFAULT_START_TIME = datetime(2020, 1, 1, tzinfo=UTC)+++class OpenAIRetryableError(Exception):+ pass+++class OpenAIResumeConfig:+ # Opaque pagination cursor: an `after` object id for CURSOR endpoints or a `next_page` token+ # for PAGE endpoints. None means "start at the first page".+ cursor: str | None = None+ # Project fan-out only: the project whose resources we were paging when we saved state. A+ # stable id (not a positional index) so projects added/removed between a crash and the retry+ # can't resume us into the wrong project.+ project_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _to_unix_seconds(value: Any) -> int:+ """Convert an incremental watermark (datetime/date/int) to the Unix seconds the API expects."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value+ return int(dt.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ return int(value)+++def _from_unix_seconds(value: Any) -> datetime | None:+ """Convert an epoch-seconds field to a UTC datetime so the column lands as a real timestamp+ (needed for the DateTime incremental watermark and datetime partitioning)."""+ if value is None:+ return None+ return datetime.fromtimestamp(int(value), tz=UTC)+++def _build_url(path: str, params: dict[str, Any], multi_params: dict[str, list[str]] | None = None) -> str:+ """Build a fully-encoded URL. `multi_params` values are repeated (e.g. group_by=a&group_by=b),+ matching the official SDK's query serialization."""+ query: list[tuple[str, str]] = [(k, str(v)) for k, v in params.items() if v is not None]+ if multi_params:+ for key, values in multi_params.items():+ query.extend((key, v) for v in values)+ encoded = urlencode(query)+ url = f"{OPENAI_BASE_URL}{path}"+ return f"{url}?{encoded}" if encoded else url+++@retry(+ retry=retry_if_exception_type(+ (+ OpenAIRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ # The usage/costs endpoints have low (undocumented) rate limits, so back off generously on 429.+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise OpenAIRetryableError(f"OpenAI API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"OpenAI API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # A single cheap probe against the smallest list endpoint confirms the admin key is genuine.+ url = _build_url("/v1/organization/projects", {"limit": 1})+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return False+ # 200 => valid. 403 => valid key without a scope we probed here; still a real key, so accept it+ # at create time (sync-time 403s are caught by get_non_retryable_errors). 401 => bad key.+ return response.status_code in (200, 403)+++def _row_id(*parts: Any) -> str:+ """Deterministic surrogate id for a usage/costs bucket row.++ Hashes only the identity/dimension fields (never the metric values), so a bucket whose metrics+ get restated between runs keeps the same id and merge updates it in place rather than inserting+ a duplicate.+ """+ # Use a sentinel for None so a missing dimension can never collide with an empty-string value.+ joined = "|".join("\x00" if p is None else str(p) for p in parts)+ return hashlib.sha256(joined.encode()).hexdigest()+++def _flatten_bucket_result(+ config: OpenAIEndpointConfig, bucket: dict[str, Any], result: dict[str, Any]+) -> dict[str, Any]:+ """Flatten one grouped result inside a time bucket into a row.++ Metric fields vary per endpoint (tokens, images, seconds, ...), so everything except `object`+ is copied through; single-level nested objects (costs' `amount: {value, currency}`) become+ `<key>_<subkey>` columns.+ """+ row: dict[str, Any] = {+ "id": _row_id(bucket.get("start_time"), *(result.get(dim) for dim in config.group_by)),+ "start_time": _from_unix_seconds(bucket.get("start_time")),+ "end_time": _from_unix_seconds(bucket.get("end_time")),+ }+ for key, value in result.items():+ if key == "object":+ continue+ if isinstance(value, dict):+ for sub_key, sub_value in value.items():+ row[f"{key}_{sub_key}"] = sub_value+ else:+ row[key] = value+ return row+++def _flatten_owner(item: dict[str, Any]) -> dict[str, Any]:+ """API keys carry a nested `owner` object; surface its identity as flat columns.++ Project API keys nest the principal one level deeper (`owner.user` / `owner.service_account`);+ admin API keys carry the fields directly on `owner`.+ """+ owner = item.get("owner")+ if not isinstance(owner, dict):+ return item+ item = {**item}+ item.pop("owner")+ principal = owner.get("user") or owner.get("service_account")+ if not isinstance(principal, dict):+ principal = owner+ item["owner_type"] = owner.get("type")+ item["owner_id"] = principal.get("id")+ item["owner_name"] = principal.get("name")+ return item+++def _normalize_entity(endpoint: str, item: dict[str, Any]) -> dict[str, Any]:+ if endpoint in ("admin_api_keys", "project_api_keys"):+ return _flatten_owner(item)+ if endpoint == "audit_logs":+ return _normalize_audit_log(item)+ return item+++def _normalize_audit_log(item: dict[str, Any]) -> dict[str, Any]:+ """Give audit log rows a stable column set.++ Each event carries its details under a key named after the event type (e.g. `project.created`),+ which would otherwise fan out into one sparse column per event type; fold it into a single+ `event_data` column instead. `effective_at` becomes a real timestamp for the incremental+ watermark and partitioning.+ """+ item = {**item}+ event_type = item.get("type")+ if isinstance(event_type, str) and event_type in item:+ item["event_data"] = item.pop(event_type)+ item["effective_at"] = _from_unix_seconds(item.get("effective_at"))+ return item+++def _bucket_params(+ config: OpenAIEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> tuple[dict[str, Any], dict[str, list[str]]]:+ params: dict[str, Any] = {"bucket_width": config.bucket_width}+ if config.limit is not None:+ params["limit"] = config.limit++ # `start_time` is required. On an incremental run start from the watermark (already shifted+ # back by the pipeline's lookback); otherwise fall back to the API launch era to pull all+ # available history.+ if should_use_incremental_field and db_incremental_field_last_value:+ params["start_time"] = _to_unix_seconds(db_incremental_field_last_value)+ else:+ params["start_time"] = _to_unix_seconds(DEFAULT_START_TIME)++ multi_params = {"group_by": config.group_by} if config.group_by else {}+ return params, multi_params+++def _iter_bucket_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ config: OpenAIEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ params, multi_params = _bucket_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.cursor:+ params["page"] = resume.cursor+ logger.debug(f"OpenAI: resuming {config.name} from page cursor")++ while True:+ url = _build_url(config.path, params, multi_params)+ data = _fetch_page(session, url, headers, logger)+ next_page = data.get("next_page")+ has_more = bool(data.get("has_more"))+ buckets = data.get("data", [])++ for bucket in buckets:+ for result in bucket.get("results", []):+ batcher.batch(_flatten_bucket_result(config, bucket, result))+ # A single batch can split into several ready chunks, so drain them all before+ # the next batch() call (which raises if `_ready` is still populated).+ while batcher.should_yield():+ yield batcher.get_table()+ # Save only when a batch is actually committed, pointing at the next page. A+ # crash then resumes from a page whose predecessors are all in the yielded+ # batch, so no buffered rows are skipped; the overlap merge dedupes on the+ # primary key.+ if has_more and next_page:+ resumable_source_manager.save_state(OpenAIResumeConfig(cursor=next_page))++ # The costs endpoint is known to sometimes return a next_page token for an empty page;+ # treat an empty page as the end of the stream rather than looping on it.+ if not buckets:+ if has_more:+ logger.debug(f"OpenAI: {config.name} returned an empty page with has_more=true, stopping pagination")+ break+ if not has_more or not next_page:+ break+ params["page"] = next_page+++def _iter_cursor_pages(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ path: str,+ base_params: dict[str, Any],+ start_after: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield (items, last_id) for each page of a cursor-paginated entity endpoint."""+ after = start_after+ while True:+ params = {**base_params, "limit": ENTITY_PAGE_SIZE}+ if after:+ params["after"] = after+ url = _build_url(path, params)+ data = _fetch_page(session, url, headers, logger)++ items = data.get("data", [])+ # Fall back to the last item's id: `last_id` isn't documented on every list response.+ last_id = data.get("last_id") or (items[-1].get("id") if items else None)+ yield items, last_id++ if not data.get("has_more") or not last_id:+ break+ after = last_id+++def _iter_entity_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ config: OpenAIEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[Any]:+ base_params: dict[str, Any] = {**config.extra_params}+ if config.name == "audit_logs" and should_use_incremental_field and db_incremental_field_last_value:+ # Bracket-style nested param, matching the official SDK's query serialization. `gte` (not+ # `gt`) so same-second events that landed after the watermark was cut aren't skipped;+ # merge dedupes the boundary overlap on `id`.+ base_params["effective_at[gte]"] = _to_unix_seconds(db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_after = resume.cursor if resume is not None else None++ for items, last_id in _iter_cursor_pages(session, headers, logger, config.path, base_params, start_after):+ for item in items:+ batcher.batch(_normalize_entity(config.name, item))+ while batcher.should_yield():+ yield batcher.get_table()+ if last_id:+ resumable_source_manager.save_state(OpenAIResumeConfig(cursor=last_id))+++def _iter_project_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ config: OpenAIEndpointConfig,+) -> Iterator[Any]:+ """Fan out over every project, emitting the project id on each row for the composite key."""+ project_ids = _list_all_project_ids(session, headers, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = project_ids+ resume_after: str | None = None+ if resume is not None and resume.project_id and resume.project_id in project_ids:+ remaining = project_ids[project_ids.index(resume.project_id) :]+ resume_after = resume.cursor+ logger.debug(f"OpenAI: resuming {config.name} from project_id={resume.project_id}")++ for index, project_id in enumerate(remaining):+ path = config.path.format(project_id=project_id)+ after = resume_after+ resume_after = None # only the resumed-into project uses the saved cursor++ for items, last_id in _iter_cursor_pages(session, headers, logger, path, {}, after):+ for item in items:+ row = {**_normalize_entity(config.name, item), "project_id": project_id}+ batcher.batch(row)+ while batcher.should_yield():+ yield batcher.get_table()+ if last_id:+ resumable_source_manager.save_state(OpenAIResumeConfig(cursor=last_id, project_id=project_id))++ # Flush any incomplete batch before checkpointing to the next project, otherwise a crash+ # between the state save and the final flush would drop this project's buffered rows.+ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()++ if index + 1 < len(remaining):+ resumable_source_manager.save_state(OpenAIResumeConfig(cursor=None, project_id=remaining[index + 1]))+++def _list_all_project_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[str]:+ project_ids: list[str] = []+ for items, _ in _iter_cursor_pages(+ session, headers, logger, "/v1/organization/projects", {"include_archived": "true"}+ ):+ project_ids.extend(item["id"] for item in items if item.get("id"))+ return project_ids+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = OPENAI_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=100 * 1024 * 1024)+ session = make_tracked_session()++ if config.pagination == PaginationType.PAGE:+ yield from _iter_bucket_rows(+ session,+ headers,+ logger,+ batcher,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif config.fan_out_over_projects:+ yield from _iter_project_fan_out_rows(session, headers, logger, batcher, resumable_source_manager, config)+ else:+ yield from _iter_entity_rows(+ session,+ headers,+ logger,+ batcher,+ resumable_source_manager,+ config,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ while batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def openai_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = OPENAI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.pynew file mode 100644index 000000000000..4dce0f43093d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py@@ -0,0 +1,207 @@+from dataclasses import dataclass, field+from enum import Enum+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+++class PaginationType(Enum):+ # Entity list endpoints (users, projects, api_keys, audit_logs, ...) page with an `after`+ # object-id cursor and signal continuation via has_more (+ first_id/last_id in the body).+ CURSOR = "cursor"+ # The usage/costs endpoints page with an opaque `page` token echoed back as `next_page`,+ # alongside has_more. Each page holds time buckets, not rows.+ PAGE = "page"+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class OpenAIEndpointConfig:+ name: str+ path: str+ pagination: PaginationType+ primary_keys: list[str]+ # Stable creation-style timestamp used for datetime partitioning. Never an `updated_at`-style+ # field (OpenAI admin entities don't expose one anyway).+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # `supports_incremental` is only ever True where the API exposes a genuine server-side time+ # filter: `start_time` on the usage/costs endpoints and `effective_at[gte]` on audit logs.+ # Entity lists have no updated-since filter, so they are full-refresh only.+ supports_incremental: bool = False+ # Usage/costs buckets get restated as late usage lands, so append would materialize duplicate+ # rows; they are merge-only. Entity lists are full refresh (no append either).+ supports_append: bool = False+ # Usage/costs buckets arrive oldest-first (verified against the API's pagination examples), so+ # the watermark can checkpoint per batch. Audit logs return newest-first with no order param,+ # so they declare "desc" and the pipeline commits the watermark only when the sync completes.+ sort_mode: SortMode = "asc"+ # Report-only: bucket granularity and the dimensions we group each bucket by.+ bucket_width: Optional[str] = None+ group_by: list[str] = field(default_factory=list)+ limit: Optional[int] = None+ # Re-read window (seconds) applied to the incremental watermark by the pipeline before it+ # reaches the source, so each run re-pulls recently-restated buckets. Merge dedupes them on+ # the primary key.+ default_incremental_lookback_seconds: Optional[int] = None+ # Project-scoped resources have no org-wide list endpoint; they fan out one request per project.+ fan_out_over_projects: bool = False+ # Extra static query params merged into every request (e.g. include_archived on projects).+ extra_params: dict[str, str] = field(default_factory=dict)+ should_sync_default: bool = True+++# Each usage endpoint supports every group_by the API documents for it. Requesting the full set+# gives the richest breakdown; unused dimensions come back null and the row's synthesized `id`+# still stays unique across the group_by combination.+_USAGE_GROUP_BY = ["project_id", "user_id", "api_key_id", "model"]+_COMPLETIONS_GROUP_BY = [*_USAGE_GROUP_BY, "batch", "service_tier"]+_IMAGES_GROUP_BY = [*_USAGE_GROUP_BY, "size", "source"]+_COSTS_GROUP_BY = ["project_id", "line_item", "api_key_id"]++# For 1d buckets the usage endpoints allow at most 31 buckets per page; costs allows 180.+_USAGE_PAGE_LIMIT = 31+_COSTS_PAGE_LIMIT = 180++# One day of restated buckets is re-pulled on every incremental run. A day's bucket keeps+# accumulating until it closes, so a trailing day covers late arrivals; merge dedupes the overlap+# on the synthesized `id`.+_BUCKET_LOOKBACK_SECONDS = 60 * 60 * 24+++def _usage_endpoint(name: str, api_path: str, group_by: list[str]) -> OpenAIEndpointConfig:+ return OpenAIEndpointConfig(+ name=name,+ path=f"/v1/organization/usage/{api_path}",+ pagination=PaginationType.PAGE,+ # `id` is synthesized from the bucket start + every group_by dimension (see openai.py):+ # a non-null, stable key so merge updates a bucket in place as its metrics get restated.+ primary_keys=["id"],+ partition_key="start_time",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("start_time")],+ bucket_width="1d",+ group_by=group_by,+ limit=_USAGE_PAGE_LIMIT,+ default_incremental_lookback_seconds=_BUCKET_LOOKBACK_SECONDS,+ )+++OPENAI_ENDPOINTS: dict[str, OpenAIEndpointConfig] = {+ "usage_completions": _usage_endpoint("usage_completions", "completions", _COMPLETIONS_GROUP_BY),+ "usage_embeddings": _usage_endpoint("usage_embeddings", "embeddings", _USAGE_GROUP_BY),+ "usage_moderations": _usage_endpoint("usage_moderations", "moderations", _USAGE_GROUP_BY),+ "usage_images": _usage_endpoint("usage_images", "images", _IMAGES_GROUP_BY),+ "usage_audio_speeches": _usage_endpoint("usage_audio_speeches", "audio_speeches", _USAGE_GROUP_BY),+ "usage_audio_transcriptions": _usage_endpoint(+ "usage_audio_transcriptions", "audio_transcriptions", _USAGE_GROUP_BY+ ),+ "usage_vector_stores": _usage_endpoint("usage_vector_stores", "vector_stores", ["project_id"]),+ "usage_code_interpreter_sessions": _usage_endpoint(+ "usage_code_interpreter_sessions", "code_interpreter_sessions", ["project_id"]+ ),+ "costs": OpenAIEndpointConfig(+ name="costs",+ path="/v1/organization/costs",+ pagination=PaginationType.PAGE,+ primary_keys=["id"],+ partition_key="start_time",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("start_time")],+ bucket_width="1d", # the costs endpoint only supports daily granularity+ group_by=_COSTS_GROUP_BY,+ limit=_COSTS_PAGE_LIMIT,+ default_incremental_lookback_seconds=_BUCKET_LOOKBACK_SECONDS,+ ),+ "projects": OpenAIEndpointConfig(+ name="projects",+ path="/v1/organization/projects",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="created_at",+ # Include archived projects so the dimension table stays complete (archived projects are+ # still referenced by historical usage/cost rows).+ extra_params={"include_archived": "true"},+ ),+ "users": OpenAIEndpointConfig(+ name="users",+ path="/v1/organization/users",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="added_at",+ ),+ "invites": OpenAIEndpointConfig(+ name="invites",+ path="/v1/organization/invites",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="invited_at",+ ),+ "admin_api_keys": OpenAIEndpointConfig(+ name="admin_api_keys",+ path="/v1/organization/admin_api_keys",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="created_at",+ ),+ # Project-scoped resources fan out one request path per project. Their ids are only documented+ # unique within a project, so the key must carry the project id.+ "project_users": OpenAIEndpointConfig(+ name="project_users",+ path="/v1/organization/projects/{project_id}/users",+ pagination=PaginationType.CURSOR,+ primary_keys=["project_id", "id"],+ partition_key="added_at",+ fan_out_over_projects=True,+ ),+ "project_service_accounts": OpenAIEndpointConfig(+ name="project_service_accounts",+ path="/v1/organization/projects/{project_id}/service_accounts",+ pagination=PaginationType.CURSOR,+ primary_keys=["project_id", "id"],+ partition_key="created_at",+ fan_out_over_projects=True,+ ),+ "project_api_keys": OpenAIEndpointConfig(+ name="project_api_keys",+ path="/v1/organization/projects/{project_id}/api_keys",+ pagination=PaginationType.CURSOR,+ primary_keys=["project_id", "id"],+ partition_key="created_at",+ fan_out_over_projects=True,+ ),+ "project_rate_limits": OpenAIEndpointConfig(+ name="project_rate_limits",+ path="/v1/organization/projects/{project_id}/rate_limits",+ pagination=PaginationType.CURSOR,+ primary_keys=["project_id", "id"],+ fan_out_over_projects=True,+ ),+ "audit_logs": OpenAIEndpointConfig(+ name="audit_logs",+ path="/v1/organization/audit_logs",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="effective_at",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("effective_at")],+ # Audit logs return newest-first and expose no order param, so the pipeline must not+ # checkpoint the watermark per batch — "desc" defers the commit to sync completion.+ sort_mode="desc",+ ),+}++ENDPOINTS = tuple(OPENAI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OPENAI_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.pyindex 7d9e858912f0..c7dd3bb9b301 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py@@ -1,19 +1,43 @@-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 import OpenAISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.openai import (+ OpenAIResumeConfig,+ openai_source,+ validate_credentials as validate_openai_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ OPENAI_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OpenAISource(SimpleSource[OpenAISourceConfig]):+class OpenAISource(ResumableSource[OpenAISourceConfig, OpenAIResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPENAI@@ -24,8 +48,90 @@ class OpenAISource(SimpleSource[OpenAISourceConfig]):name=SchemaExternalDataSourceType.OPEN_AI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="OpenAI",- iconPath="/static/services/openai.png",- keywords=["llm", "ai", "usage", "costs"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your OpenAI Admin API key to pull your organization's API usage, cost, and admin data into the PostHog Data warehouse.++Create an Admin API key (prefixed `sk-admin...`) in your [OpenAI organization settings](https://platform.openai.com/settings/organization/admin-keys). Only organization owners can create one; a regular project API key cannot read organization usage or costs.""",+ iconPath="/static/services/openai.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/openai",+ keywords=["llm", "gpt", "chatgpt", "ai usage", "cost"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Admin API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk-admin...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.openai.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.openai.com": "Your OpenAI Admin API key is invalid or has been revoked. Create a new Admin API key in your OpenAI organization settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.openai.com": "Your OpenAI API key does not have organization admin access. Use an Admin API key (prefixed sk-admin) created by an organization owner, then reconnect.",+ }++ def get_schemas(+ self,+ config: OpenAISourceConfig,+ 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_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_append,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ 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: OpenAISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_openai_credentials(config.api_key):+ return True, None++ return False, "Invalid OpenAI Admin API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAIResumeConfig]:+ return ResumableSourceManager[OpenAIResumeConfig](inputs, OpenAIResumeConfig)++ def source_for_pipeline(+ self,+ config: OpenAISourceConfig,+ resumable_source_manager: ResumableSourceManager[OpenAIResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return openai_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ 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/tests/test_openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.pynew file mode 100644index 000000000000..f84cb033714d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py@@ -0,0 +1,435 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.openai import openai+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.openai import (+ OpenAIResumeConfig,+ _bucket_params,+ _build_url,+ _flatten_bucket_result,+ _flatten_owner,+ _normalize_audit_log,+ _row_id,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.settings import OPENAI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.source import OpenAISource+++class _FakeResumableManager:+ def __init__(self, state: OpenAIResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[OpenAIResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> OpenAIResumeConfig | None:+ return self._state++ def save_state(self, data: OpenAIResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, responses: list[dict], endpoint: str, **kw: Any+) -> list[dict]:+ calls: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return responses[len(calls) - 1]++ monkeypatch.setattr(openai, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="sk-admin-test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kw,+ ):+ rows.extend(table.to_pylist())+ manager._captured_calls = calls # type: ignore[attr-defined]+ return rows+++class TestRowId:+ def test_id_is_stable_across_metric_changes(self) -> None:+ # The surrogate key must depend only on identity dims, never metric values — otherwise a+ # restated bucket would get a new id and merge would insert a duplicate instead of updating.+ a = _row_id(1722470400, "proj_1", "gpt-4o")+ b = _row_id(1722470400, "proj_1", "gpt-4o")+ assert a == b++ def test_id_differs_by_dimension(self) -> None:+ a = _row_id(1722470400, "proj_1", "gpt-4o")+ b = _row_id(1722470400, "proj_2", "gpt-4o")+ assert a != b++ def test_none_and_empty_string_distinguished_positionally(self) -> None:+ # A missing dimension (None) must not collide with an empty-string value at the same+ # position, and positions stay aligned so distinct dimension tuples never collide either.+ assert _row_id(None, "x") != _row_id("", "x")+ assert _row_id(None, "x") != _row_id("x", None)+++class TestBuildUrl:+ def test_repeats_multi_params(self) -> None:+ url = _build_url("/v1/organization/usage/completions", {"limit": 31}, {"group_by": ["model", "project_id"]})+ assert url.count("group_by=") == 2+ assert "limit=31" in url++ def test_drops_none_values(self) -> None:+ url = _build_url("/v1/organization/users", {"limit": 100, "after": None})+ assert "after" not in url+++class TestBucketParams:+ def test_incremental_uses_watermark_as_unix_start_time(self) -> None:+ config = OPENAI_ENDPOINTS["usage_completions"]+ watermark = datetime(2026, 3, 4, 0, 0, 0, tzinfo=UTC)+ params, multi = _bucket_params(+ config, should_use_incremental_field=True, db_incremental_field_last_value=watermark+ )+ assert params["start_time"] == int(watermark.timestamp())+ assert params["bucket_width"] == "1d"+ assert params["limit"] == 31+ assert multi == {"group_by": config.group_by}++ def test_full_refresh_falls_back_to_api_launch_era(self) -> None:+ # Without a watermark we must still send the required start_time; the API launch era pulls+ # all available history without requesting decades of empty pre-launch buckets.+ config = OPENAI_ENDPOINTS["costs"]+ params, _ = _bucket_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None)+ assert params["start_time"] == int(datetime(2020, 1, 1, tzinfo=UTC).timestamp())+ assert params["limit"] == 180+++class TestFlattenBucketResult:+ def test_flattens_nested_amount_and_converts_bucket_times(self) -> None:+ config = OPENAI_ENDPOINTS["costs"]+ bucket = {"start_time": 1722470400, "end_time": 1722556800}+ result = {+ "object": "organization.costs.result",+ "amount": {"value": 12.34, "currency": "usd"},+ "line_item": "GPT-4o mini, input",+ "project_id": "proj_1",+ "api_key_id": None,+ }+ row = _flatten_bucket_result(config, bucket, result)+ assert row["amount_value"] == 12.34+ assert row["amount_currency"] == "usd"+ assert row["line_item"] == "GPT-4o mini, input"+ assert row["start_time"] == datetime(2024, 8, 1, tzinfo=UTC)+ assert row["end_time"] == datetime(2024, 8, 2, tzinfo=UTC)+ assert "object" not in row+ assert row["id"]++ def test_metric_fields_copied_through_per_endpoint(self) -> None:+ config = OPENAI_ENDPOINTS["usage_completions"]+ row = _flatten_bucket_result(+ config,+ {"start_time": 1722470400, "end_time": 1722556800},+ {"input_tokens": 100, "output_tokens": 5, "input_cached_tokens": 50, "model": "gpt-4o", "batch": False},+ )+ assert row["input_tokens"] == 100+ assert row["input_cached_tokens"] == 50+ assert row["model"] == "gpt-4o"+ assert row["batch"] is False+++class TestFlattenOwner:+ def test_project_api_key_owner_principal_is_nested(self) -> None:+ item = {+ "id": "key_1",+ "owner": {"type": "user", "user": {"id": "user_1", "name": "Ada", "email": "[email protected]"}},+ }+ flat = _flatten_owner(item)+ assert flat["owner_type"] == "user"+ assert flat["owner_id"] == "user_1"+ assert flat["owner_name"] == "Ada"+ assert "owner" not in flat++ def test_admin_api_key_owner_fields_are_direct(self) -> None:+ item = {"id": "key_1", "owner": {"type": "service_account", "id": "sa_1", "name": "CI bot"}}+ flat = _flatten_owner(item)+ assert flat["owner_type"] == "service_account"+ assert flat["owner_id"] == "sa_1"+ assert flat["owner_name"] == "CI bot"+++class TestNormalizeAuditLog:+ def test_event_payload_folds_into_event_data_and_effective_at_is_datetime(self) -> None:+ # Each event type carries its details under a key named after the type; without folding,+ # the table would grow one sparse column per event type.+ item = {+ "id": "audit_log-1",+ "type": "project.created",+ "effective_at": 1722470400,+ "actor": {"type": "session"},+ "project.created": {"id": "proj_1", "name": "My project"},+ }+ row = _normalize_audit_log(item)+ assert row["event_data"] == {"id": "proj_1", "name": "My project"}+ assert "project.created" not in row+ assert row["effective_at"] == datetime(2024, 8, 1, tzinfo=UTC)+++class TestBucketPagination:+ def test_follows_next_page_until_has_more_false(self, monkeypatch: Any) -> None:+ responses = [+ {+ "data": [{"start_time": 1, "end_time": 2, "results": [{"model": "a"}]}],+ "has_more": True,+ "next_page": "PAGE2",+ },+ {+ "data": [{"start_time": 2, "end_time": 3, "results": [{"model": "b"}]}],+ "has_more": False,+ "next_page": None,+ },+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "usage_completions")+ assert [r["model"] for r in rows] == ["a", "b"]+ # Second request must carry the page token from the first response.+ assert "page=PAGE2" in manager._captured_calls[1] # type: ignore[attr-defined]++ def test_resumes_from_saved_page_cursor(self, monkeypatch: Any) -> None:+ responses = [+ {+ "data": [{"start_time": 2, "end_time": 3, "results": [{"model": "b"}]}],+ "has_more": False,+ "next_page": None,+ },+ ]+ manager = _FakeResumableManager(OpenAIResumeConfig(cursor="PAGE2"))+ rows = _collect(manager, monkeypatch, responses, "usage_completions")+ assert [r["model"] for r in rows] == ["b"]+ assert "page=PAGE2" in manager._captured_calls[0] # type: ignore[attr-defined]++ def test_empty_page_with_next_page_token_stops_pagination(self, monkeypatch: Any) -> None:+ # The costs endpoint is known to return a next_page token alongside an empty page; without+ # the guard, pagination would loop on the empty tail forever.+ responses = [+ {+ "data": [{"start_time": 1, "end_time": 2, "results": [{"line_item": "x"}]}],+ "has_more": True,+ "next_page": "PAGE2",+ },+ {"data": [], "has_more": True, "next_page": "PAGE3"},+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "costs")+ assert [r["line_item"] for r in rows] == ["x"]+ assert len(manager._captured_calls) == 2 # type: ignore[attr-defined]++ def test_drains_every_chunk_when_a_batch_splits(self, monkeypatch: Any) -> None:+ # A batch can split into several ready chunks (byte/offset caps). Force it with tiny limits:+ # if the loop only pops one chunk per batch, the next batch() raises and rows go missing.+ real_batcher = openai.Batcher++ def tiny_batcher(**_: Any) -> openai.Batcher:+ return real_batcher(logger=MagicMock(), chunk_size=4, chunk_size_bytes=10**12, max_table_bytes=1)++ monkeypatch.setattr(openai, "Batcher", tiny_batcher)++ results = [{"model": f"m{i}"} for i in range(8)]+ responses = [+ {+ "data": [{"start_time": 1, "end_time": 2, "results": results}],+ "has_more": False,+ "next_page": None,+ }+ ]+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "usage_completions")+ assert sorted(r["model"] for r in rows) == [f"m{i}" for i in range(8)]+++class TestEntityPagination:+ def test_cursor_pagination_uses_after_and_stops(self, monkeypatch: Any) -> None:+ responses = [+ {"data": [{"id": "user_1"}], "has_more": True, "last_id": "user_1"},+ {"data": [{"id": "user_2"}], "has_more": False, "last_id": "user_2"},+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "users")+ assert [r["id"] for r in rows] == ["user_1", "user_2"]+ assert "after=user_1" in manager._captured_calls[1] # type: ignore[attr-defined]++ def test_falls_back_to_last_item_id_when_last_id_missing(self, monkeypatch: Any) -> None:+ # `last_id` isn't documented on every list response; the last item's id must keep+ # pagination moving instead of stopping after page one.+ responses = [+ {"data": [{"id": "user_1"}], "has_more": True},+ {"data": [{"id": "user_2"}], "has_more": False},+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, responses, "users")+ assert [r["id"] for r in rows] == ["user_1", "user_2"]+ assert "after=user_1" in manager._captured_calls[1] # type: ignore[attr-defined]++ def test_admin_api_keys_flatten_owner(self, monkeypatch: Any) -> None:+ responses = [+ {+ "data": [{"id": "key_1", "owner": {"type": "user", "id": "user_1", "name": "Ada"}}],+ "has_more": False,+ "last_id": "key_1",+ }+ ]+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "admin_api_keys")+ assert rows[0]["owner_id"] == "user_1"+ assert "owner" not in rows[0]+++class TestAuditLogs:+ def test_incremental_applies_effective_at_filter(self, monkeypatch: Any) -> None:+ responses = [+ {"data": [{"id": "audit_log-1", "type": "project.created", "effective_at": 1722470400}], "has_more": False}+ ]+ manager = _FakeResumableManager()+ watermark = datetime(2026, 3, 4, tzinfo=UTC)+ _collect(+ manager,+ monkeypatch,+ responses,+ "audit_logs",+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ # Bracket-style nested param (URL-encoded), matching the official SDK's serialization.+ assert f"effective_at%5Bgte%5D={int(watermark.timestamp())}" in manager._captured_calls[0] # type: ignore[attr-defined]++ def test_full_refresh_sends_no_effective_at_filter(self, monkeypatch: Any) -> None:+ responses = [+ {"data": [{"id": "audit_log-1", "type": "project.created", "effective_at": 1722470400}], "has_more": False}+ ]+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, responses, "audit_logs")+ assert "effective_at" not in manager._captured_calls[0] # type: ignore[attr-defined]+++class TestProjectFanOut:+ def test_emits_one_row_per_project_resource_with_composite_key(self, monkeypatch: Any) -> None:+ # First response lists projects, then one page per project's users.+ responses = [+ {"data": [{"id": "proj_1"}, {"id": "proj_2"}], "has_more": False, "last_id": "proj_2"},+ {"data": [{"id": "user_1"}], "has_more": False, "last_id": "user_1"},+ {"data": [{"id": "user_1"}], "has_more": False, "last_id": "user_1"},+ ]+ rows = _collect(_FakeResumableManager(), monkeypatch, responses, "project_users")+ assert [(r["project_id"], r["id"]) for r in rows] == [("proj_1", "user_1"), ("proj_2", "user_1")]++ def test_flushes_each_projects_rows_before_checkpointing_next(self, monkeypatch: Any) -> None:+ # A project's buffered rows must be yielded before the resume cursor advances to the next+ # project; otherwise a crash before the final flush would lose them (they'd never be re-read+ # on resume, which starts at the checkpointed next project).+ responses = [+ {"data": [{"id": "proj_1"}, {"id": "proj_2"}], "has_more": False, "last_id": "proj_2"},+ {"data": [{"id": "user_a"}], "has_more": False, "last_id": "user_a"},+ {"data": [{"id": "user_b"}], "has_more": False, "last_id": "user_b"},+ ]+ calls: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return responses[len(calls) - 1]++ monkeypatch.setattr(openai, "_fetch_page", fake_fetch)++ events: list[tuple[str, Any]] = []++ class _RecordingManager(_FakeResumableManager):+ def save_state(self, data: OpenAIResumeConfig) -> None:+ super().save_state(data)+ events.append(("save", data.project_id))++ manager = _RecordingManager()+ for table in get_rows(+ api_key="sk-admin-test",+ endpoint="project_users",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ for row in table.to_pylist():+ events.append(("yield", row["project_id"]))++ assert events.index(("yield", "proj_1")) < events.index(("save", "proj_2"))+++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 (real key, unprobed scope); 401 means a bad key.+ response = MagicMock(status_code=status)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(openai, "make_tracked_session", return_value=session):+ assert validate_credentials("sk-admin-test") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(openai, "make_tracked_session", return_value=session):+ assert validate_credentials("sk-admin-test") is False+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.openai.com/v1/organization/users?limit=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.openai.com/v1/organization/costs",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = OpenAISource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.openai.com', port=443): Read timed out."),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.openai.com/v1/organization/users",+ ),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = OpenAISource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ response = MagicMock(status_code=status, ok=False)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(openai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(openai.OpenAIRetryableError):+ openai._fetch_page(session, "https://api.openai.com/v1/organization/users", {}, MagicMock())+ assert session.get.call_count == 5 # exhausts the retry budget++ def test_client_error_raises_for_status_without_retry(self) -> None:+ response = MagicMock(status_code=401, ok=False, text="unauthorized")+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ openai._fetch_page(session, "https://api.openai.com/v1/organization/users", {}, MagicMock())+ assert session.get.call_count == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.pynew file mode 100644index 000000000000..3e8295025e27--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai_source.py@@ -0,0 +1,131 @@+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.openai import OpenAIResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.openai.source import OpenAISource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_USAGE_ENDPOINTS = [+ "usage_completions",+ "usage_embeddings",+ "usage_moderations",+ "usage_images",+ "usage_audio_speeches",+ "usage_audio_transcriptions",+ "usage_vector_stores",+ "usage_code_interpreter_sessions",+]++_ENTITY_ENDPOINTS = [+ "projects",+ "users",+ "invites",+ "admin_api_keys",+ "project_users",+ "project_service_accounts",+ "project_api_keys",+ "project_rate_limits",+]+++class TestOpenAISourceConfig:+ def test_source_type(self) -> None:+ assert OpenAISource().source_type == ExternalDataSourceType.OPENAI++ def test_config_exposes_single_secret_api_key_field(self) -> None:+ config = OpenAISource().get_source_config+ assert config.name == SchemaExternalDataSourceType.OPEN_AI+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/openai"+ 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 TestOpenAISchemas:+ def test_all_endpoints_present(self) -> None:+ names = {s.name for s in OpenAISource().get_schemas(MagicMock(), team_id=1)}+ assert names == {*_USAGE_ENDPOINTS, *_ENTITY_ENDPOINTS, "costs", "audit_logs"}++ @parameterized.expand([(endpoint,) for endpoint in [*_USAGE_ENDPOINTS, "costs"]])+ def test_bucketed_endpoints_are_incremental_on_start_time(self, endpoint: str) -> None:+ # The usage/costs endpoints have a genuine server-side time filter (start_time). Buckets+ # get restated, so a trailing-day lookback re-reads them and merge dedupes.+ schema = next(s for s in OpenAISource().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++ def test_audit_logs_are_incremental_on_effective_at(self) -> None:+ schema = next(s for s in OpenAISource().get_schemas(MagicMock(), team_id=1) if s.name == "audit_logs")+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["effective_at"]++ @parameterized.expand([(endpoint,) for endpoint in _ENTITY_ENDPOINTS])+ def test_entity_endpoints_are_full_refresh_only(self, endpoint: str) -> None:+ # No updated-since filter exists on the entity lists, so they must not advertise incremental.+ schema = next(s for s in OpenAISource().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 = OpenAISource().get_schemas(MagicMock(), team_id=1, names=["usage_completions"])+ assert [s.name for s in schemas] == ["usage_completions"]+++class TestOpenAIResumableManager:+ def test_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = OpenAISource().get_resumable_source_manager(inputs)+ assert manager._data_class is OpenAIResumeConfig+++class TestOpenAISourceForPipeline:+ def _response(self, endpoint: str) -> object:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = None+ config = MagicMock(api_key="sk-admin-test")+ return OpenAISource().source_for_pipeline(config, MagicMock(), inputs)++ @parameterized.expand(+ [+ ("usage_completions", ["id"], "datetime", "asc"),+ ("costs", ["id"], "datetime", "asc"),+ ("users", ["id"], "datetime", "asc"),+ ("project_users", ["project_id", "id"], "datetime", "asc"),+ ("project_rate_limits", ["project_id", "id"], None, "asc"),+ # Audit logs return newest-first, so the watermark must only commit at sync completion.+ ("audit_logs", ["id"], "datetime", "desc"),+ ]+ )+ def test_primary_keys_partitioning_and_sort_mode(+ self, endpoint: str, primary_keys: list[str], partition_mode: str | None, sort_mode: str+ ) -> None:+ response = self._response(endpoint)+ assert response.name == endpoint # type: ignore[attr-defined]+ assert response.primary_keys == primary_keys # type: ignore[attr-defined]+ assert response.sort_mode == sort_mode # type: ignore[attr-defined]+ assert response.partition_mode == partition_mode # type: ignore[attr-defined]+++class TestDocumentedTables:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog => the source opts into publishing its table list to public docs.+ assert OpenAISource().lists_tables_without_credentials is True+ tables = OpenAISource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert "usage_completions" in names and "costs" in names+ costs = next(t for t in tables if t["name"] == "costs")+ assert "Incremental" in costs["sync_methods"]+ assert costs["description"] # canonical description is surfaced