: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): add 4 missing tables to the OpenAI source (#120064)
Tom Owers9984eaf1f31e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 70f7f5f7967a..3557e09f93d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -8721,8 +8721,8 @@ Diffed against: <https://raw.githubusercontent.com/openai/openai-openapi/master/- [ ] `/models` — lookup resolving the model IDs that appear in every usage\_\* and costs row (high)- [ ] `/chat/completions (list stored completions)` — per-request log with model, tokens and metadata - the finest-grained usage fact table available (high)-- [ ] `/organization/groups and /organization/groups/{id}/users` — group membership table resolving which users belong to which group (high)-- [ ] `/organization/roles and /organization/users/{id}/roles` — role assignments for the users we already sync (medium)+- [x] `/organization/groups and /organization/groups/{id}/users` — group membership table resolving which users belong to which group (high)+- [x] `/organization/roles and /organization/users/{id}/roles` — role assignments for the users we already sync (medium)- [ ] `/organization/projects/{id}/groups` — project-to-group membership, complements the project_users table we sync (medium)- [ ] `/batches` — batch job records with request counts and completion status (medium)- [ ] `/fine_tuning/jobs (+ /events, /checkpoints)` — training job history, cost and status over time (medium)diff --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.pyindex 974185b5cc11..612e5c102b96 100644--- 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.py@@ -239,6 +239,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"max_tokens_per_1_minute": "Maximum tokens allowed per minute.",},},+ "groups": {+ "description": "Groups of users in your OpenAI organization, used to grant access and roles in bulk.",+ "docs_url": f"{_API_DOCS}/groups/list",+ "columns": {+ "id": "Unique identifier for the group.",+ "name": "Display name of the group.",+ "created_at": "Unix timestamp (seconds) of when the group was created.",+ "is_scim_managed": "Whether the group is managed through SCIM by your identity provider.",+ "group_type": "Type of the group: group or tenant_group.",+ },+ },+ "group_users": {+ "description": "Membership of each group: one row per user in a group.",+ "docs_url": f"{_API_DOCS}/group-users/list",+ "columns": {+ "group_id": "ID of the group the user belongs to.",+ "id": "ID of the user.",+ "name": "Name of the user.",+ "email": "Email address of the user, or null.",+ },+ },+ "roles": {+ "description": "Roles configured for your OpenAI organization, including predefined roles managed by OpenAI.",+ "docs_url": f"{_API_DOCS}/roles/list",+ "columns": {+ "id": "Unique identifier for the role.",+ "name": "Unique name of the role.",+ "description": "Description of the role, or null.",+ "permissions": "JSON array of the permissions the role grants.",+ "resource_type": "Resource type the role is bound to, e.g. api.organization or api.project.",+ "predefined_role": "Whether the role is predefined and managed by OpenAI.",+ },+ },+ "user_roles": {+ "description": "Organization roles assigned to each user, directly or through a group.",+ "docs_url": f"{_API_DOCS}/user-organization-role-assignments/list",+ "columns": {+ "user_id": "ID of the user the role is assigned to.",+ "id": "ID of the role.",+ "name": "Name of the role.",+ "permissions": "JSON array of the permissions the role grants.",+ "resource_type": "Resource type the role applies to.",+ "predefined_role": "Whether the role is predefined by OpenAI.",+ "description": "Description of the role, or null.",+ "created_at": "Unix timestamp (seconds) of when the role was created, or null.",+ "updated_at": "Unix timestamp (seconds) of when the role was last updated, or null.",+ "created_by": "ID of the actor who created the role, or null.",+ "created_by_user_obj": "JSON object with details of the user who created the role, or null.",+ "metadata": "JSON object of metadata stored on the role, or null.",+ "assignment_sources": "JSON array of the principals (such as groups) the assignment is inherited from, or null.",+ },+ },"audit_logs": {"description": "User actions and configuration changes within your OpenAI organization.","docs_url": f"{_API_DOCS}/audit-logs/list",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.pyindex 4c2e11174da4..a5285bc85103 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py@@ -59,9 +59,10 @@ class OpenAIResumeConfig:class _EntityPaginator(BasePaginator):- """Entity list pagination: an `after` object-id cursor.+ """Entity list pagination: an `after` cursor.- `last_id` drives the next page, falling back to the last item's id (`last_id` isn't documented on+ The groups and roles lists return an opaque `next` cursor; the other lists return `last_id`.+ Either drives the next page, falling back to the last item's id (`last_id` isn't documented onevery list response) so pagination keeps moving. `has_more` is the authoritative stop signal —the API returns a `last_id` on the final page too, so a missing token alone can't be trusted."""@@ -89,9 +90,13 @@ class _EntityPaginator(BasePaginator):self._has_next_page = Falsereturnitems = 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+ cursor = (+ body.get("next")+ or body.get("last_id")+ or (items[-1].get("id") if items and isinstance(items[-1], dict) else None)+ )+ if body.get("has_more") and cursor:+ self._after = cursorself._has_next_page = Trueelse:self._has_next_page = False@@ -313,13 +318,13 @@ def _make_bucket_data_map(config: OpenAIEndpointConfig) -> Callable[[dict[str, Areturn _explode-def _make_fanout_data_map(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]]:- # Project-scoped resource ids are only unique within a project, so the composite key carries the- # project id (injected by the fan-out as `_projects_id`).+def _make_fanout_data_map(endpoint: str, parent: str, parent_key: str) -> Callable[[dict[str, Any]], dict[str, Any]]:+ # Parent-scoped resource ids are only unique within their parent, so the composite key carries+ # the parent id (injected by the fan-out as `_<parent>_id`).def _stamp(row: dict[str, Any]) -> dict[str, Any]:- project_id = row.pop("_projects_id", None)+ parent_id = row.pop(f"_{parent}_id", None)row = _normalize_entity(endpoint, row)- row["project_id"] = project_id+ row[parent_key] = parent_idreturn rowreturn _stamp@@ -411,21 +416,22 @@ def openai_source(resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneitems: Optional[Callable[[], Iterable[Any]]] = None- if config.fan_out_over_projects:- # Project-scoped resources have no org-wide list endpoint; enumerate the projects and fetch- # the resource per project. Archived ones are left out: OpenAI rejects every project-scoped- # read under an archived project, which would fail the whole schema on the first one. The- # `projects` table keeps them (see its `extra_params`) so historical usage/cost rows still- # resolve their project.- projects_config = OPENAI_ENDPOINTS["projects"]+ if config.fan_out_parent is not None and config.fan_out_parent_key is not None:+ # Parent-scoped resources have no org-wide list endpoint; enumerate the parent and fetch+ # the resource per parent row. Archived projects are left out: OpenAI rejects every+ # project-scoped read under an archived project, which would fail the whole schema on the+ # first one. The `projects` table keeps them (see its `extra_params`) so historical+ # usage/cost rows still resolve their project.+ parent = config.fan_out_parent+ parent_config = OPENAI_ENDPOINTS[parent]rest_config: RESTAPIConfig = {"client": client_config,"resource_defaults": None,"resources": [{- "name": "projects",+ "name": parent,"endpoint": {- "path": projects_config.path,+ "path": parent_config.path,"params": {"limit": ENTITY_PAGE_SIZE},"data_selector": "data","paginator": _EntityPaginator(),@@ -437,13 +443,13 @@ def openai_source("path": config.path,"params": {"limit": ENTITY_PAGE_SIZE,- "project_id": {"type": "resolve", "resource": "projects", "field": "id"},+ config.fan_out_parent_key: {"type": "resolve", "resource": parent, "field": "id"},},"data_selector": "data","paginator": _EntityPaginator(),},"include_from_parent": ["id"],- "data_map": _make_fanout_data_map(endpoint),+ "data_map": _make_fanout_data_map(endpoint, parent, config.fan_out_parent_key),},],}@@ -456,14 +462,15 @@ def openai_source(if state:resumable_source_manager.save_state(OpenAIResumeConfig(fanout_state=state))- def skip_failing_project(path: str, exc: Exception) -> None:- # A single project whose resource keeps returning a transient 5xx (after the client+ def skip_failing_parent(path: str, exc: Exception) -> None:+ # A single parent whose resource keeps returning a transient 5xx (after the client# exhausts its retries) would otherwise fail the whole schema, with no workaround for the- # user. Skip that project, record it, and let every other project's rows land; the next+ # user. Skip that parent, record it, and let every other parent's rows land; the next# sync re-attempts the skipped one once OpenAI recovers.logger.warning(- "openai_source.skipped_failing_project",+ "openai_source.skipped_failing_parent",endpoint=endpoint,+ parent=parent,path=path,error=str(exc),)@@ -475,7 +482,7 @@ def openai_source(db_incremental_field_last_value,resume_hook=save_fanout_checkpoint,initial_paginator_state=initial_fanout_state,- on_parent_error=skip_failing_project,+ on_parent_error=skip_failing_parent,)resource = next(r for r in resources if r.name == endpoint)else: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.pyindex 5d18f06df075..74ec437bfdc3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py@@ -1,7 +1,9 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom enum import Enumfrom typing import Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -24,7 +26,7 @@ def _datetime_incremental_field(name: str) -> IncrementalField:}-@dataclass+@frozenclass OpenAIEndpointConfig:name: strpath: str@@ -53,8 +55,11 @@ class OpenAIEndpointConfig:# 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+ # Parent-scoped resources have no org-wide list endpoint; they fan out one request per row of+ # the named parent endpoint (e.g. "projects"). `fan_out_parent_key` names both the path+ # placeholder the parent id fills and the column that carries it on each row.+ fan_out_parent: Optional[str] = None+ fan_out_parent_key: Optional[str] = None# 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@@ -168,7 +173,8 @@ OPENAI_ENDPOINTS: dict[str, OpenAIEndpointConfig] = {pagination=PaginationType.CURSOR,primary_keys=["project_id", "id"],partition_key="added_at",- fan_out_over_projects=True,+ fan_out_parent="projects",+ fan_out_parent_key="project_id",),"project_service_accounts": OpenAIEndpointConfig(name="project_service_accounts",@@ -176,7 +182,8 @@ OPENAI_ENDPOINTS: dict[str, OpenAIEndpointConfig] = {pagination=PaginationType.CURSOR,primary_keys=["project_id", "id"],partition_key="created_at",- fan_out_over_projects=True,+ fan_out_parent="projects",+ fan_out_parent_key="project_id",),"project_api_keys": OpenAIEndpointConfig(name="project_api_keys",@@ -184,14 +191,46 @@ OPENAI_ENDPOINTS: dict[str, OpenAIEndpointConfig] = {pagination=PaginationType.CURSOR,primary_keys=["project_id", "id"],partition_key="created_at",- fan_out_over_projects=True,+ fan_out_parent="projects",+ fan_out_parent_key="project_id",),"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,+ fan_out_parent="projects",+ fan_out_parent_key="project_id",+ ),+ "groups": OpenAIEndpointConfig(+ name="groups",+ path="/v1/organization/groups",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "group_users": OpenAIEndpointConfig(+ name="group_users",+ path="/v1/organization/groups/{group_id}/users",+ pagination=PaginationType.CURSOR,+ primary_keys=["group_id", "id"],+ fan_out_parent="groups",+ fan_out_parent_key="group_id",+ ),+ "roles": OpenAIEndpointConfig(+ name="roles",+ path="/v1/organization/roles",+ pagination=PaginationType.CURSOR,+ primary_keys=["id"],+ ),+ # Role assignments carry a nullable `created_at`, so there is no stable partition key.+ "user_roles": OpenAIEndpointConfig(+ name="user_roles",+ path="/v1/organization/users/{user_id}/roles",+ pagination=PaginationType.CURSOR,+ primary_keys=["user_id", "id"],+ fan_out_parent="users",+ fan_out_parent_key="user_id",),"audit_logs": OpenAIEndpointConfig(name="audit_logs",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.pyindex 3fa827e328b4..24b5031a30ee 100644--- 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.py@@ -162,21 +162,35 @@ class TestBucketPagination:class TestEntityPagination:- def test_cursor_pagination_uses_after_and_stops(self) -> None:+ @parameterized.expand(+ [+ ("last_id", "users", {"last_id": "user_1"}, {"last_id": "user_2"}, "user_1"),+ # Groups and roles return an opaque `next` cursor that need not equal the last row's id.+ ("next_cursor", "roles", {"next": "cursor_abc"}, {"next": None}, "cursor_abc"),+ ]+ )+ def test_cursor_pagination_uses_after_and_stops(+ self,+ _name: str,+ endpoint: str,+ first_cursor: dict[str, Any],+ last_cursor: dict[str, Any],+ expected_after: str,+ ) -> None:result = _driver().run(- "users",+ endpoint,[- _entity_page([{"id": "user_1"}], has_more=True, last_id="user_1"),- # Final page still carries a last_id — has_more must stop the walk with no extra call.- _entity_page([{"id": "user_2"}], has_more=False, last_id="user_2"),+ ScriptedResponse(json={"data": [{"id": "row_1"}], "has_more": True, **first_cursor}),+ # Final page may still carry a cursor — has_more must stop the walk with no extra call.+ ScriptedResponse(json={"data": [{"id": "row_2"}], "has_more": False, **last_cursor}),],)assert result.raised is None- assert [row["id"] for row in result.rows] == ["user_1", "user_2"]- assert result.params("after") == [None, "user_1"]+ assert [row["id"] for row in result.rows] == ["row_1", "row_2"]+ assert result.params("after") == [None, expected_after]assert result.params("limit") == ["100", "100"]- assert result.saved_states == [OpenAIResumeConfig(cursor="user_1")]+ assert result.saved_states == [OpenAIResumeConfig(cursor=expected_after)]def test_resumes_from_saved_after_cursor(self) -> None:result = _driver().run(@@ -250,6 +264,36 @@ class TestProjectFanOut:final = result.saved_states[-1].fanout_stateassert final["completed"] == [PROJECT_USERS_PATH.format(project_id="proj_2")]+ @parameterized.expand(+ [+ ("project_users", "/v1/organization/projects", PROJECT_USERS_PATH, "project_id"),+ ("group_users", "/v1/organization/groups", "/v1/organization/groups/{parent_id}/users", "group_id"),+ ("user_roles", "/v1/organization/users", "/v1/organization/users/{parent_id}/roles", "user_id"),+ ]+ )+ def test_child_rows_carry_their_parent_id(+ self, endpoint: str, parent_path: str, child_path: str, parent_key: str+ ) -> None:+ # Child ids repeat across parents (one user sits in many groups), so a row without its+ # parent id would collide on the composite primary key.+ child_paths = {child_path.format(parent_id=p, project_id=p): p for p in ("parent_1", "parent_2")}++ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == parent_path:+ return _entity_page([{"id": "parent_1"}, {"id": "parent_2"}], has_more=False)+ if request.path in child_paths:+ return _entity_page([{"id": "shared_child"}], has_more=False)+ raise AssertionError(f"Unexpected request: {request.path}")++ result = _driver().run(endpoint, respond)++ assert result.raised is None+ assert sorted((row[parent_key], row["id"]) for row in result.rows) == [+ ("parent_1", "shared_child"),+ ("parent_2", "shared_child"),+ ]+ assert not any(key.startswith("_") for row in result.rows for key in row)+def test_saved_state_shapes_still_parse(self) -> None:# ResumableSourceManager._load_json does dataclass(**saved) — every historical shape must# keep parsing after the migration.