Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(circleci): add deploy component and user tables (#102929)

Tom Owerse98306366cec
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.md
index 06651c651485..922452148868 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
@@ -1490,14 +1490,16 @@ 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)
-- [ ] `deploy/components` — deployed component inventory, the join key for deploy tracking (medium)
-- [ ] `deploy/components/{component_id}/versions` — version history per component - deploy frequency and lead-time analysis (medium)
-- [ ] `user/{id}` — lookup resolving the actor/trigger user IDs carried on pipelines and workflows (medium)
+- [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)
- [ ] `projects/{project_id}/pipeline-definitions` — resolves the pipeline definition IDs attached to synced pipelines (low)
-Note: The current v2 spec has no artifacts or test-metadata endpoints (those lived in v1.1), so no gap there. Insights paths exist in the same spec but belong to the separate CircleciInsights source. Source is fully static (CIRCLECI_ENDPOINTS), no dynamic discovery.
+Note: `organizations/{org_id}/usage_export_job` is POST-only job creation plus a separate polling GET that
+returns presigned CSV URLs, not a readable list endpoint, so it is not a warehouse table in this source's shape.
+The current v2 spec has no artifacts or test-metadata endpoints (those lived in v1.1), so no gap there. Insights paths exist in the same spec but belong to the separate CircleciInsights source. Source is fully static (CIRCLECI_ENDPOINTS), no dynamic discovery.
## CircleciInsights — gaps
diff --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.py
index 1f7fda744337..1869c8910553 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
@@ -68,4 +68,43 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"vcs_info": "Version control details for the project (provider, default branch, URL).",
},
},
+ "components": {
+ "description": "A deployed component — a deployable unit of a project tracked by CircleCI releases.",
+ "docs_url": "https://circleci.com/docs/api/v2/#operation/listComponents",
+ "columns": {
+ "id": "Unique identifier for the component.",
+ "name": "Name of the component.",
+ "project_id": "Identifier of the project the component belongs to.",
+ "labels": "Key/value labels associated with the component.",
+ "release_count": "Number of releases recorded for the component.",
+ "created_at": "Time at which the component was created.",
+ "updated_at": "Time at which the component was last updated.",
+ },
+ },
+ "component_versions": {
+ "description": "A version of a component deployed to an environment, one row per deploy target.",
+ "docs_url": "https://circleci.com/docs/api/v2/#operation/listComponentVersions",
+ "columns": {
+ "component_id": "Identifier of the component the version belongs to.",
+ "name": "Version name, for example 1.0.0.",
+ "environment_id": "Identifier of the environment the version was deployed to.",
+ "namespace": "Namespace the version was deployed in.",
+ "is_live": "Whether the version is currently live.",
+ "pipeline_id": "Identifier of the pipeline that deployed the version.",
+ "workflow_id": "Identifier of the workflow that deployed the version.",
+ "job_id": "Identifier of the job that deployed the version.",
+ "job_number": "Number of the job that deployed the version.",
+ "last_deployed_at": "Time at which the version was last deployed.",
+ },
+ },
+ "users": {
+ "description": "A CircleCI user referenced as the actor on a workflow.",
+ "docs_url": "https://circleci.com/docs/api/v2/#operation/getUser",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "login": "Login of the user on the version control provider.",
+ "name": "Name of the user.",
+ "avatar_url": "URL of the user'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.py
index 7d7deca6c5ff..124b85a66210 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
@@ -1,4 +1,3 @@
-import dataclasses
from collections.abc import Callable, Iterator
from typing import Any, Optional
from urllib.parse import quote, urlencode
@@ -7,6 +6,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.circleci.settings import CIRCLECI_ENDPOINTS
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
@@ -15,14 +16,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
CIRCLECI_BASE_URL = "https://circleci.com/api/v2"
REQUEST_TIMEOUT_SECONDS = 60
MAX_RETRIES = 5
-# CircleCI v2 list endpoints return ~20 items per page and don't accept a page-size param,
+# Most CircleCI v2 list endpoints return ~20 items per page and don't accept a page-size param,
# so the caps below bound the scan in pages, not rows.
MAX_PIPELINE_PAGES = 500
MAX_WORKFLOW_PAGES_PER_PIPELINE = 10
MAX_JOB_PAGES_PER_WORKFLOW = 25
+MAX_COMPONENT_PAGES = 200
+MAX_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.
+COMPONENTS_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"})
+# 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,
+# and a null merge key re-inserts the row on every sync, so they collapse to an empty string.
+VERSION_KEY_FIELDS = ("environment_id", "namespace", "name")
class CircleCIRetryableError(Exception):
@@ -32,7 +45,8 @@ class CircleCIRetryableError(Exception):
self.retry_after = retry_after
-FetchPageFn = Callable[[str], dict[str, Any]]
+# Returns the decoded body: an object for most endpoints, a list for /me/collaborations.
+FetchPageFn = Callable[[str], Any]
_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=60)
@@ -46,11 +60,12 @@ def _retry_wait(retry_state: RetryCallState) -> float:
return _EXPONENTIAL_WAIT(retry_state)
+@frozen
class CircleCIResumeConfig:
- # Page token for the top-level pipelines scan. Fan-out streams (workflows/jobs/projects)
- # also resume on this token: children of fully processed pipeline pages have already been
- # yielded, and the in-progress page is re-yielded then deduped on primary key.
+ # Page token for the endpoint's top-level scan (pipelines, or deploy components for the
+ # components streams). Fan-out streams also resume on it: children of fully processed
+ # parent pages have already been yielded, and the in-progress page is re-yielded then
+ # deduped on primary key. Resume state is keyed per job, so the two scans never mix.
next_page_token: str
@@ -130,7 +145,7 @@ def _make_fetch_page(api_token: str, logger: FilteringBoundLogger) -> FetchPageF
wait=_retry_wait,
reraise=True,
)
- def fetch_page(url: str) -> dict[str, Any]:
+ def fetch_page(url: str) -> Any:
response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code == 429:
@@ -174,6 +189,14 @@ def _iter_pages(
if not next_token:
return
+ if next_token == page_token:
+ # CircleCI ends a list with a null next_page_token, never with a repeat, so the
+ # endpoint ignored our page-token and is serving the same page again. Stopping
+ # here would publish a truncated table on a full refresh, so fail the run.
+ raise ValueError(
+ f"CircleCI returned the same page token twice for {resource}, so pagination cannot advance. path={path}"
+ )
+
if pages_fetched >= max_pages:
logger.warning(
f"CircleCI: page cap reached for {resource}, stopping pagination. max_pages={max_pages}, path={path}"
@@ -200,6 +223,36 @@ 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 []:
+ 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."
+ )
+
+
+def _iter_component_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/components",
+ {"org-id": _resolve_org_id(fetch_page, org_slug), "page-size": COMPONENTS_PAGE_SIZE},
+ logger,
+ max_pages=MAX_COMPONENT_PAGES,
+ resource="components",
+ start_token=start_token,
+ )
+
+
def _workflows_for_pipeline(
fetch_page: FetchPageFn, pipeline_id: str, logger: FilteringBoundLogger
) -> Iterator[list[dict[str, Any]]]:
@@ -273,6 +326,57 @@ def _project_rows(
yield [project]
+def _component_version_rows(
+ fetch_page: FetchPageFn, components: list[dict[str, Any]], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ for component in components:
+ component_id = component["id"]
+ for versions, _ in _iter_pages(
+ fetch_page,
+ f"/deploy/components/{component_id}/versions",
+ {},
+ logger,
+ max_pages=MAX_VERSION_PAGES_PER_COMPONENT,
+ resource=f"versions of component {component_id}",
+ ):
+ if versions:
+ yield [
+ {
+ **version,
+ "component_id": component_id,
+ **{key: version.get(key) or "" for key in VERSION_KEY_FIELDS},
+ }
+ for version in versions
+ ]
+
+
+def _user_rows(
+ fetch_page: FetchPageFn,
+ pipelines: list[dict[str, Any]],
+ logger: FilteringBoundLogger,
+ seen_user_ids: set[str],
+) -> Iterator[list[dict[str, Any]]]:
+ # v2 has no "list users in org" endpoint, so the actor ids carried on workflows are
+ # resolved one at a time via GET /user/{id}.
+ for pipeline in pipelines:
+ for workflows in _workflows_for_pipeline(fetch_page, pipeline["id"], logger):
+ for workflow in workflows:
+ for field_name in WORKFLOW_ACTOR_FIELDS:
+ user_id = workflow.get(field_name)
+ if not user_id or user_id in seen_user_ids:
+ continue
+ seen_user_ids.add(user_id)
+ try:
+ user = fetch_page(_build_url(f"/user/{quote(str(user_id), safe='')}"))
+ except requests.HTTPError as error:
+ # A workflow can name an actor whose CircleCI account is gone; one
+ # stale id must not fail the whole stream.
+ if error.response is not None and error.response.status_code == 404:
+ continue
+ raise
+ yield [user]
+
+
def get_rows(
api_token: str,
org_slug: str,
@@ -290,20 +394,33 @@ def get_rows(
if start_token is not None:
logger.debug(f"CircleCI: resuming {endpoint} from saved pipelines page token")
- # Project slugs already emitted by the projects stream this run. Lost on resume, which
- # only causes re-fetch/re-yield of a few project rows — merge dedupes on primary key.
+ # Project slugs and user ids already emitted this run. Lost on resume, which only causes
+ # re-fetch/re-yield of a few rows — merge dedupes on primary key.
seen_project_slugs: set[str] = set()
+ seen_user_ids: set[str] = set()
+
+ if endpoint in COMPONENT_SCAN_ENDPOINTS:
+ pages = _iter_component_pages(fetch_page, org_slug, logger, start_token)
+ else:
+ pages = _iter_pipeline_pages(fetch_page, org_slug, logger, start_token)
- for pipelines, next_token in _iter_pipeline_pages(fetch_page, org_slug, logger, start_token):
+ for items, next_token in pages:
if endpoint == "pipelines":
- if pipelines:
- yield pipelines
+ if items:
+ yield items
elif endpoint == "workflows":
- yield from _workflow_rows(fetch_page, pipelines, logger)
+ yield from _workflow_rows(fetch_page, items, logger)
elif endpoint == "jobs":
- yield from _job_rows(fetch_page, pipelines, logger)
+ yield from _job_rows(fetch_page, items, logger)
elif endpoint == "projects":
- yield from _project_rows(fetch_page, pipelines, seen_project_slugs)
+ 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 items
+ elif endpoint == "component_versions":
+ yield from _component_version_rows(fetch_page, items, logger)
# Save state after the page's rows (and any fan-out children) have been yielded, so a
# crash re-yields the in-progress page instead of skipping it.
@@ -330,8 +447,9 @@ def circleci_source(
logger=logger,
resumable_source_manager=resumable_source_manager,
),
- primary_keys=[config.primary_key],
- # The API always returns newest-first and exposes no sort param.
+ primary_keys=list(config.primary_keys),
+ # No v2 list endpoint takes a sort param, and the ones that document an order return
+ # newest-first. Every stream is full refresh, so this is advisory.
sort_mode="desc",
partition_count=1,
partition_size=1,
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.py
index a12bc9c813ed..2a93711b171a 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
@@ -1,13 +1,15 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@frozen
class CircleCIEndpointConfig:
name: str
- primary_key: str = "id"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Stable creation-time field used for datetime partitioning. Jobs don't expose their own
# creation timestamp, so they partition on the parent workflow's created_at injected by
# the transport.
@@ -35,6 +37,20 @@ CIRCLECI_ENDPOINTS: dict[str, CircleCIEndpointConfig] = {
"projects": CircleCIEndpointConfig(
name="projects",
),
+ "components": CircleCIEndpointConfig(
+ name="components",
+ partition_key="created_at",
+ ),
+ "component_versions": CircleCIEndpointConfig(
+ name="component_versions",
+ # A version payload carries no id of its own, and the same version name can be live in
+ # several environments and namespaces, so identity is the component plus the deploy
+ # target. last_deployed_at moves on every redeploy, so there is no partition key.
+ primary_keys=["component_id", "environment_id", "namespace", "name"],
+ ),
+ "users": CircleCIEndpointConfig(
+ name="users",
+ ),
}
ENDPOINTS = tuple(CIRCLECI_ENDPOINTS.keys())
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.py
index c65460ca44d4..c5346780c6e2 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
@@ -55,7 +55,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, and projects into the PostHog Data warehouse.
+ caption="""Enter your CircleCI personal API token to pull your CircleCI pipelines, workflows, jobs, projects, deploy components, 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.py
index 77fd2e3506f1..107ca621a731 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
@@ -4,9 +4,11 @@ from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
+import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.circleci.circleci import (
+ COMPONENTS_PAGE_SIZE,
MAX_PIPELINE_PAGES,
CircleCIResumeConfig,
CircleCIRetryableError,
@@ -46,8 +48,11 @@ def _page(items: list[dict[str, Any]], next_token: str | None) -> dict[str, Any]
return {"items": items, "next_page_token": next_token}
-def _route_session(mock_session: mock.MagicMock, routes: dict[str, list[dict[str, Any]] | dict[str, Any]]) -> None:
- """Route GET calls by path; values are either a body dict or a list of bodies consumed in order."""
+def _route_session(mock_session: mock.MagicMock, routes: dict[str, Any]) -> None:
+ """Route GET calls by path; values are either a body or a list of bodies consumed in order.
+
+ A body that is itself a JSON array therefore has to be wrapped in a one-element list.
+ """
state: dict[str, int] = {}
def get(url: str, **kwargs: Any) -> mock.MagicMock:
@@ -223,7 +228,16 @@ class TestPipelinesRows:
)
@mock.patch(PATCH_SESSION)
def test_page_cap_stops_pagination_and_logs(self, mock_session):
- _route_session(mock_session, {"/api/v2/pipeline": _page([{"id": "p"}], "always-more")})
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/pipeline": [
+ _page([{"id": "p1"}], "t2"),
+ _page([{"id": "p2"}], "t3"),
+ _page([{"id": "p3"}], "t4"),
+ ]
+ },
+ )
logger = mock.MagicMock()
manager = _make_manager()
@@ -233,6 +247,7 @@ class TestPipelinesRows:
assert mock_session.return_value.get.call_count == 2
logger.warning.assert_called_once()
assert "page cap" in logger.warning.call_args.args[0]
+ assert "pipelines" in logger.warning.call_args.args[0]
@mock.patch(PATCH_SESSION)
def test_empty_response_yields_nothing(self, mock_session):
@@ -351,7 +366,11 @@ class TestWorkflowsFanOut:
mock_session,
{
"/api/v2/pipeline": _page([{"id": "p1"}], None),
- "/api/v2/pipeline/p1/workflow": _page([{"id": "w", "pipeline_id": "p1"}], "always-more"),
+ "/api/v2/pipeline/p1/workflow": [
+ _page([{"id": "wa", "pipeline_id": "p1"}], "t2"),
+ _page([{"id": "wb", "pipeline_id": "p1"}], "t3"),
+ _page([{"id": "wc", "pipeline_id": "p1"}], "t4"),
+ ],
},
)
logger = mock.MagicMock()
@@ -360,6 +379,7 @@ class TestWorkflowsFanOut:
assert len([row for batch in batches for row in batch]) == 2
logger.warning.assert_called_once()
+ assert "page cap" in logger.warning.call_args.args[0]
assert "p1" in logger.warning.call_args.args[0]
@mock.patch(PATCH_SESSION)
@@ -447,7 +467,11 @@ class TestJobsFanOut:
{
"/api/v2/pipeline": _page([{"id": "p1"}], None),
"/api/v2/pipeline/p1/workflow": _page([{"id": "w1"}], None),
- "/api/v2/workflow/w1/job": _page([{"id": "j"}], "always-more"),
+ "/api/v2/workflow/w1/job": [
+ _page([{"id": "ja"}], "t2"),
+ _page([{"id": "jb"}], "t3"),
+ _page([{"id": "jc"}], "t4"),
+ ],
},
)
logger = mock.MagicMock()
@@ -456,6 +480,7 @@ class TestJobsFanOut:
assert len([row for batch in batches for row in batch]) == 2
logger.warning.assert_called_once()
+ assert "page cap" in logger.warning.call_args.args[0]
assert "w1" in logger.warning.call_args.args[0]
@@ -487,6 +512,175 @@ class TestProjectsRows:
assert len(project_urls) == 2
+COLLABORATIONS_PATH = "/api/v2/me/collaborations"
+COLLABORATIONS = [[{"id": "org-uuid", "slug": "gh/posthog", "name": "PostHog"}]]
+
+
+class TestComponentsRows:
+ @mock.patch(PATCH_SESSION)
+ def test_org_slug_resolved_to_org_id_and_paginated(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v2/deploy/components": [
+ _page([{"id": "c1"}], "components-token-2"),
+ _page([{"id": "c2"}], None),
+ ],
+ },
+ )
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["c1", "c2"]
+ component_urls = [url for url in _requested_urls(mock_session) if "/deploy/components" in url]
+ assert parse_qs(urlparse(component_urls[0]).query) == {
+ "org-id": ["org-uuid"],
+ "page-size": [str(COMPONENTS_PAGE_SIZE)],
+ }
+ # The required page size is repeated on every page, not just the first.
+ assert parse_qs(urlparse(component_urls[1]).query) == {
+ "org-id": ["org-uuid"],
+ "page-size": [str(COMPONENTS_PAGE_SIZE)],
+ "page-token": ["components-token-2"],
+ }
+ assert manager.save_state.call_args.args[0].next_page_token == "components-token-2"
+
+ @mock.patch(PATCH_SESSION)
+ def test_resumes_from_saved_component_page_token(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v2/deploy/components": [_page([{"id": "c9"}], None)],
+ },
+ )
+
+ manager = _make_manager(CircleCIResumeConfig(next_page_token="resume-token"))
+ list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager))
+
+ component_url = next(url for url in _requested_urls(mock_session) if "/deploy/components" in url)
+ assert parse_qs(urlparse(component_url).query)["page-token"] == ["resume-token"]
+
+ @parameterized.expand(
+ [
+ ("slug not visible to the token", [[{"id": "other-uuid", "slug": "gh/other"}]]),
+ ("collaboration without an id", [[{"id": None, "slug": "gh/posthog"}]]),
+ ]
+ )
+ @mock.patch(PATCH_SESSION)
+ def test_unresolvable_org_raises_with_slug(self, _name, collaborations, mock_session):
+ _route_session(mock_session, {COLLABORATIONS_PATH: collaborations})
+
+ with pytest.raises(ValueError, match="gh/posthog"):
+ list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), _make_manager()))
+
+
+class TestComponentVersionsFanOut:
+ @mock.patch(PATCH_SESSION)
+ def test_versions_carry_component_id_and_never_null_merge_keys(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v2/deploy/components": _page([{"id": "c1"}, {"id": "c2"}], None),
+ "/api/v2/deploy/components/c1/versions": _page(
+ [
+ {
+ "name": "1.0.0",
+ "environment_id": "env-1",
+ "namespace": "default",
+ "is_live": True,
+ "last_deployed_at": "2026-01-01T00:00:00Z",
+ },
+ {"name": "1.0.1", "environment_id": None},
+ ],
+ None,
+ ),
+ "/api/v2/deploy/components/c2/versions": _page([{"name": "2.0.0", "environment_id": "env-2"}], None),
+ },
+ )
+
+ batches = list(get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager()))
+ rows = [row for batch in batches for row in batch]
+
+ assert [(row["component_id"], row["name"]) for row in rows] == [
+ ("c1", "1.0.0"),
+ ("c1", "1.0.1"),
+ ("c2", "2.0.0"),
+ ]
+ # Native fields survive the injection.
+ assert rows[0]["is_live"] is True
+ assert rows[0]["namespace"] == "default"
+ # A missing part of the composite key becomes "" so merges match instead of re-inserting.
+ assert rows[1]["environment_id"] == ""
+ assert rows[1]["namespace"] == ""
+
+ @mock.patch(PATCH_SESSION)
+ def test_repeated_page_token_fails_the_run(self, mock_session):
+ # The versions endpoint documents no page-token param; if it ignores ours it hands
+ # back the same token forever. Truncating there would publish a partial table.
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v2/deploy/components": _page([{"id": "c1"}], None),
+ "/api/v2/deploy/components/c1/versions": _page([{"name": "1.0.0"}], "same-token"),
+ },
+ )
+
+ with pytest.raises(ValueError, match="same page token twice"):
+ list(get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager()))
+
+
+class TestUsersRows:
+ @mock.patch(PATCH_SESSION)
+ def test_distinct_actor_ids_resolved_once(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/pipeline": _page([{"id": "p1"}], None),
+ "/api/v2/pipeline/p1/workflow": _page(
+ [
+ {"id": "w1", "started_by": "u1", "canceled_by": "u2"},
+ {"id": "w2", "started_by": "u1", "errored_by": "u3"},
+ {"id": "w3", "started_by": None},
+ ],
+ None,
+ ),
+ "/api/v2/user/u1": {"id": "u1", "login": "one"},
+ "/api/v2/user/u2": {"id": "u2", "login": "two"},
+ "/api/v2/user/u3": {"id": "u3", "login": "three"},
+ },
+ )
+
+ batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["u1", "u2", "u3"]
+ assert len([url for url in _requested_urls(mock_session) if "/user/" in url]) == 3
+
+ @mock.patch(PATCH_SESSION)
+ def test_deleted_actor_is_skipped(self, mock_session):
+ missing = _response({}, status_code=404)
+ missing.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=missing)
+ bodies = {
+ "/api/v2/pipeline": _page([{"id": "p1"}], None),
+ "/api/v2/pipeline/p1/workflow": _page([{"id": "w1", "started_by": "gone", "canceled_by": "u2"}], None),
+ "/api/v2/user/u2": {"id": "u2", "login": "two"},
+ }
+
+ def get(url: str, **kwargs: Any) -> mock.MagicMock:
+ path = urlparse(url).path
+ return missing if path == "/api/v2/user/gone" else _response(bodies[path])
+
+ mock_session.return_value.get.side_effect = get
+
+ batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager()))
+
+ assert [row["id"] for batch in batches for row in batch] == ["u2"]
+
+
class TestCircleCISourceResponse:
@parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
def test_response_metadata_per_endpoint(self, endpoint):
@@ -494,7 +688,7 @@ class TestCircleCISourceResponse:
response = circleci_source("token", "gh/posthog", endpoint, mock.MagicMock(), _make_manager())
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == list(config.primary_keys)
assert response.sort_mode == "desc"
if config.partition_key:
assert response.partition_mode == "datetime"