: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 3 missing tables to the CircleCI source (#119039)
Tom Owerscdf8d66e138b
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 35cbf0f41397..5c504ca3223a 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@@ -2503,12 +2503,12 @@ Today (7): `component_versions`, `components`, `jobs`, `pipelines`, `projects`,Diffed against: <https://circleci.com/api/v2/openapi.json>- [ ] `organizations/{org_id}/usage_export_job` — credit/usage export per project and job - CircleCI's headline cost metric, absent today (high)-- [ ] `deploy/environments` — deploy environment registry that resolves environment IDs on deploy markers (medium)+- [x] `deploy/environments` — deploy environment registry that resolves environment IDs on deploy markers (medium) — added as `environments`- [x] `deploy/components` — deployed component inventory, the join key for deploy tracking (medium) — added as `components`; the org UUID it requires is resolved from the configured org slug via `/me/collaborations`- [x] `deploy/components/{component_id}/versions` — version history per component - deploy frequency and lead-time analysis (medium) — added as `component_versions`, fanned out per component- [x] `user/{id}` — lookup resolving the actor/trigger user IDs carried on pipelines and workflows (medium) — added as `users`, resolved from the `started_by`/`canceled_by`/`errored_by` ids on workflows (pipeline trigger actors carry only a login, no id)-- [ ] `organizations/{org_id}/groups` — org user groups for grouping build activity by team (low)-- [ ] `me/collaborations` — org/slug lookup that enumerates the orgs a token can see (low)+- [x] `organizations/{org_id}/groups` — org user groups for grouping build activity by team (low) — added as `groups`+- [x] `me/collaborations` — org/slug lookup that enumerates the orgs a token can see (low) — added as `collaborations`- [ ] `projects/{project_id}/pipeline-definitions` — resolves the pipeline definition IDs attached to synced pipelines (low)Note: `organizations/{org_id}/usage_export_job` is POST-only job creation plus a separate polling GET thatdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/canonical_descriptions.pyindex 1869c8910553..3acd4b7c85c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/canonical_descriptions.py@@ -107,4 +107,36 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"avatar_url": "URL of the user's avatar on the version control provider.",},},+ "environments": {+ "description": "A deploy environment of the organization, the target that component versions are deployed to.",+ "docs_url": "https://circleci.com/docs/api/v2/#operation/listEnvironments",+ "columns": {+ "id": "Unique identifier for the environment.",+ "name": "Name of the environment.",+ "description": "Short description given to the environment.",+ "labels": "Labels associated with the environment.",+ "created_at": "Time at which the environment was created.",+ "updated_at": "Time at which the environment was last updated.",+ },+ },+ "groups": {+ "description": "A user group in the organization.",+ "docs_url": "https://circleci.com/docs/api/v2/#operation/getOrganizationGroups",+ "columns": {+ "id": "Unique identifier for the group.",+ "name": "Name of the group.",+ "description": "Description of the group.",+ },+ },+ "collaborations": {+ "description": "An organization that the token's user is a member of or can collaborate on.",+ "docs_url": "https://circleci.com/docs/api/v2/#operation/getCollaborations",+ "columns": {+ "id": "Unique identifier for the organization.",+ "slug": "Slug of the organization, in vcs/org format.",+ "name": "Name of the organization.",+ "vcs-type": "Version control provider of the organization.",+ "avatar_url": "URL of the organization's avatar on the version control provider.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/circleci.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/circleci.pyindex a5cdb4c42b72..596ffd31f8ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/circleci.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/circleci.py@@ -26,14 +26,20 @@ MAX_WORKFLOW_PAGES_PER_PIPELINE = 10MAX_JOB_PAGES_PER_WORKFLOW = 25MAX_COMPONENT_PAGES = 200MAX_VERSION_PAGES_PER_COMPONENT = 25-# The deploy components endpoint is the exception: page size is required and no maximum is-# documented, so we ask for the same ~20 items the other list endpoints return by default.+MAX_ENVIRONMENT_PAGES = 50+MAX_GROUP_PAGES = 50+# The deploy components and environments endpoints are the exception: page size is required and+# no maximum is documented, so we ask for the same ~20 items the other list endpoints return by+# default.COMPONENTS_PAGE_SIZE = 20+ENVIRONMENTS_PAGE_SIZE = 20# CircleCI rate-limits at roughly 1000 requests/minute per token (not officially documented);# 429s carry RateLimit-* headers we honor before retrying.MAX_RATE_LIMIT_SLEEP_SECONDS = 120# Endpoints served by the deploy components scan rather than the pipelines scan.COMPONENT_SCAN_ENDPOINTS = frozenset({"components", "component_versions"})+# Endpoints whose list rows are yielded as-is, with no fan-out.+DIRECT_LIST_ENDPOINTS = frozenset({"pipelines", "components", "environments", "groups", "collaborations"})# Workflow fields naming a CircleCI user, which is how the users stream discovers actor ids.WORKFLOW_ACTOR_FIELDS = ("started_by", "canceled_by", "errored_by")# A version row's identity beyond the component id. None of these are documented as required,@@ -289,16 +295,19 @@ def _iter_pipeline_pages()-def _resolve_org_id(fetch_page: FetchPageFn, org_slug: str) -> str:- # The deploy endpoints take an organization UUID, which the v2 API only exposes through the- # collaborations list for the token's user.- for collaboration in fetch_page(_build_url("/me/collaborations")) or []:+def _fetch_collaborations(fetch_page: FetchPageFn) -> list[dict[str, Any]]:+ return fetch_page(_build_url("/me/collaborations")) or []+++def _resolve_org_id(fetch_page: FetchPageFn, org_slug: str, resource: str = "deploy components") -> str:+ # The deploy and organization endpoints take an organization UUID, which the v2 API only+ # exposes through the collaborations list for the token's user.+ for collaboration in _fetch_collaborations(fetch_page):if collaboration.get("slug") == org_slug and collaboration.get("id"):return collaboration["id"]raise ValueError(- f"CircleCI organization '{org_slug}' was not found for this token, so its deploy "- "components cannot be looked up."+ f"CircleCI organization '{org_slug}' was not found for this token, so its {resource} cannot be looked up.")@@ -319,6 +328,50 @@ def _iter_component_pages()+def _iter_environment_pages(+ fetch_page: FetchPageFn,+ org_slug: str,+ logger: FilteringBoundLogger,+ start_token: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ yield from _iter_pages(+ fetch_page,+ "/deploy/environments",+ {+ "org-id": _resolve_org_id(fetch_page, org_slug, "deploy environments"),+ "page-size": ENVIRONMENTS_PAGE_SIZE,+ },+ logger,+ max_pages=MAX_ENVIRONMENT_PAGES,+ resource="environments",+ start_token=start_token,+ )+++def _iter_group_pages(+ fetch_page: FetchPageFn,+ org_slug: str,+ logger: FilteringBoundLogger,+ start_token: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ org_id = _resolve_org_id(fetch_page, org_slug, "groups")+ yield from _iter_pages(+ fetch_page,+ f"/organizations/{quote(org_id, safe='')}/groups",+ {},+ logger,+ max_pages=MAX_GROUP_PAGES,+ resource="groups",+ start_token=start_token,+ )+++def _iter_collaboration_pages(fetch_page: FetchPageFn) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ # The collaborations list is a bare, unpaginated array covering every organization the token+ # can see, independent of the configured org slug.+ yield _fetch_collaborations(fetch_page), None++def _workflows_for_pipeline(fetch_page: FetchPageFn, pipeline_id: str, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:@@ -649,11 +702,17 @@ def get_rows(if endpoint in COMPONENT_SCAN_ENDPOINTS:pages = _iter_component_pages(fetch_page, org_slug, logger, start_token)+ elif endpoint == "environments":+ pages = _iter_environment_pages(fetch_page, org_slug, logger, start_token)+ elif endpoint == "groups":+ pages = _iter_group_pages(fetch_page, org_slug, logger, start_token)+ elif endpoint == "collaborations":+ pages = _iter_collaboration_pages(fetch_page)else:pages = _iter_pipeline_pages(fetch_page, org_slug, logger, start_token)for items, next_token in pages:- if endpoint == "pipelines":+ if endpoint in DIRECT_LIST_ENDPOINTS:if items:yield itemselif endpoint == "workflows":@@ -664,9 +723,6 @@ def get_rows(yield from _project_rows(fetch_page, items, seen_project_slugs)elif endpoint == "users":yield from _user_rows(fetch_page, items, logger, seen_user_ids)- elif endpoint == "components":- if items:- yield itemselif endpoint == "component_versions":yield from _component_version_rows(fetch_page, items, logger)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/settings.pyindex 2a93711b171a..2a0192886cd9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/settings.py@@ -48,6 +48,18 @@ CIRCLECI_ENDPOINTS: dict[str, CircleCIEndpointConfig] = {# target. last_deployed_at moves on every redeploy, so there is no partition key.primary_keys=["component_id", "environment_id", "namespace", "name"],),+ "environments": CircleCIEndpointConfig(+ name="environments",+ partition_key="created_at",+ ),+ "groups": CircleCIEndpointConfig(+ name="groups",+ ),+ "collaborations": CircleCIEndpointConfig(+ name="collaborations",+ # The spec marks the organization id nullable, while the slug is required and unique.+ primary_keys=["slug"],+ ),"users": CircleCIEndpointConfig(name="users",),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/source.pyindex 3f87f627d1ae..c9778bb75ed6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/source.py@@ -61,7 +61,7 @@ class CircleCISource(ResumableSource[CircleCISourceConfig, CircleCIResumeConfig]name=ExternalDataSourceType.CIRCLECI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="CircleCI",- caption="""Enter your CircleCI personal API token to pull your CircleCI pipelines, workflows, jobs, projects, deploy components, and users into the PostHog Data warehouse.+ caption="""Enter your CircleCI personal API token to pull your CircleCI pipelines, workflows, jobs, projects, deploy components and environments, organization groups, and users into the PostHog Data warehouse.You can create a personal API token in your [CircleCI user settings](https://app.circleci.com/settings/user/tokens). The token has the same access to organizations and projects as your user.""",iconPath="/static/services/circleci.png",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci.pyindex b115f30e781b..898ceb44c4e1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci.py@@ -332,18 +332,79 @@ class TestComponentsRows:@parameterized.expand([- ("slug not visible to the token", [{"id": "other-uuid", "slug": "gh/other"}]),- ("collaboration without an id", [{"id": None, "slug": "gh/posthog"}]),+ (endpoint, name, collaborations)+ for endpoint in ("components", "environments", "groups")+ for name, collaborations in (+ ("slug not visible to the token", [{"id": "other-uuid", "slug": "gh/other"}]),+ ("collaboration without an id", [{"id": None, "slug": "gh/posthog"}]),+ )])- def test_unresolvable_org_raises_with_slug(self, _name, collaborations):- result = _driver().run("components", [ScriptedResponse(json=collaborations)], api_version=CIRCLECI_V2)+ def test_unresolvable_org_raises_with_slug(self, endpoint, _name, collaborations):+ result = _driver().run(endpoint, [ScriptedResponse(json=collaborations)], api_version=CIRCLECI_V2)assert isinstance(result.raised, ValueError)assert "gh/posthog" in str(result.raised)assert result.paths == [COLLABORATIONS_PATH]+class TestOrgListRows:+ @parameterized.expand(+ [+ ("components", "/api/v2/deploy/components", {"org-id": "org-uuid", "page-size": "20"}),+ ("environments", "/api/v2/deploy/environments", {"org-id": "org-uuid", "page-size": "20"}),+ ("groups", "/api/v2/organizations/org-uuid/groups", {}),+ ]+ )+ def test_walks_every_page_of_the_resolved_org(self, endpoint, path, expected_params):+ result = _driver().run(+ endpoint,+ route(+ {+ COLLABORATIONS_PATH: [ScriptedResponse(json=COLLABORATIONS)],+ path: [+ _page([{"id": "a", "created_at": "2026-01-01T00:00:00Z"}], "token-2"),+ _page([], "token-3"),+ _page([{"id": "b", "created_at": "2026-01-02T00:00:00Z"}], None),+ ],+ }+ ),+ api_version=CIRCLECI_V3,+ )++ assert result.raised is None+ assert [row["id"] for row in result.rows] == ["a", "b"]+ assert result.paths == [COLLABORATIONS_PATH, path, path, path]+ list_requests = [request for request in result.requests if request.path == path]+ assert all({key: request.param(key) for key in expected_params} == expected_params for request in list_requests)+ assert [request.param("page-token") for request in list_requests] == [None, "token-2", "token-3"]+ assert result.saved_states == [+ CircleCIResumeConfig(next_page_token="token-2"),+ CircleCIResumeConfig(next_page_token="token-3"),+ ]+++class TestCollaborationsRows:+ def test_yields_every_org_the_token_sees_in_one_request(self):+ collaborations = [+ {"id": "org-uuid", "slug": "gh/posthog", "name": "PostHog", "vcs-type": "github"},+ {"id": "other-uuid", "slug": "bb/other", "name": "Other", "vcs-type": "bitbucket"},+ {"id": None, "slug": "circleci/standalone", "name": "Standalone", "vcs-type": "circleci"},+ ]+ result = _driver().run("collaborations", [ScriptedResponse(json=collaborations)], api_version=CIRCLECI_V3)++ assert result.raised is None+ assert result.rows == collaborations+ assert result.paths == [COLLABORATIONS_PATH]+ assert result.saved_states == []++ def test_empty_collaborations_yield_no_rows(self):+ result = _driver().run("collaborations", [ScriptedResponse(json=[])], api_version=CIRCLECI_V2)++ assert result.raised is None+ assert result.rows == []++class TestComponentVersionsFanOut:def test_versions_carry_component_id_and_never_null_merge_keys(self):result = _driver().run(