: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 CircleCI source (#62655)
Tom Owers3bd4c6e00add
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c597086b148a..a40bc9e3dc18 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -60,6 +60,7 @@ the row lists both.| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || confluence | HTTP | requests | ✅ || chartmogul | HTTP | requests | ✅ |+| circleci | HTTP | requests | ✅ || clerk | HTTP | requests + `rest_source.RESTClient` | ✅ || clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ || clickup | HTTP | requests | ✅ |@@ -205,7 +206,6 @@ doesn't conflict with concurrent PRs.- campaign_manager_360- checkout_com- chorus-- circleci- clari- cloudflare- cockroachdbdiff --git a/posthog/temporal/data_imports/sources/circleci/circleci.py b/posthog/temporal/data_imports/sources/circleci/circleci.pynew file mode 100644index 000000000000..ae3215a03022--- /dev/null+++ b/posthog/temporal/data_imports/sources/circleci/circleci.py@@ -0,0 +1,324 @@+import dataclasses+from collections.abc import Callable, Iterator+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.circleci.settings import CIRCLECI_ENDPOINTS+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++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,+# 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+# 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+++class CircleCIRetryableError(Exception):+ def __init__(self, message: str, retry_after: int = 0) -> None:+ super().__init__(message)+ # Seconds the API asked us to wait (from Retry-After/RateLimit-Reset); 0 when unknown.+ self.retry_after = retry_after+++FetchPageFn = Callable[[str], dict[str, Any]]++_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=60)+++def _retry_wait(retry_state: RetryCallState) -> float:+ # Honor the API's Retry-After exactly once; otherwise back off exponentially. Doing the+ # wait here (rather than time.sleep inside fetch_page) avoids stacking both delays.+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, CircleCIRetryableError) and exc.retry_after:+ return exc.retry_after+ return _EXPONENTIAL_WAIT(retry_state)+++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.+ next_page_token: str+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Circle-Token": api_token,+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any] | None = None) -> str:+ clean_params = {key: value for key, value in (params or {}).items() if value is not None}+ if not clean_params:+ return f"{CIRCLECI_BASE_URL}{path}"+ return f"{CIRCLECI_BASE_URL}{path}?{urlencode(clean_params)}"+++def _rate_limit_sleep_seconds(response: requests.Response) -> int:+ # Prefer Retry-After, fall back to RateLimit-Reset. Header semantics (seconds-to-wait vs+ # epoch) aren't officially documented, so anything outside a sane window is clamped.+ for header in ("retry-after", "ratelimit-reset", "x-ratelimit-reset"):+ raw = response.headers.get(header)+ if raw is None:+ continue+ try:+ seconds = int(float(raw))+ except (TypeError, ValueError):+ continue+ return max(0, min(seconds, MAX_RATE_LIMIT_SLEEP_SECONDS))+ return 0+++def validate_credentials(api_token: str, org_slug: str | None = None) -> tuple[bool, str | None]:+ """Confirm the token with /me, then (when provided) confirm the org slug resolves."""+ session = make_tracked_session(redact_values=(api_token,))+ headers = _get_headers(api_token)++ try:+ response = session.get(f"{CIRCLECI_BASE_URL}/me", headers=headers, timeout=10)+ except Exception:+ return False, "Could not reach the CircleCI API. Please try again."++ if response.status_code != 200:+ return False, "Invalid CircleCI API token. Please check your personal API token."++ if not org_slug:+ return True, None++ try:+ response = session.get(+ _build_url("/pipeline", {"org-slug": org_slug}),+ headers=headers,+ timeout=10,+ )+ except Exception:+ return False, "Could not reach the CircleCI API. Please try again."++ if response.status_code != 200:+ return (+ False,+ f"CircleCI organization '{org_slug}' was not found or is not accessible with this token. "+ "Use the `vcs/org` format, e.g. `gh/your-org`.",+ )++ return True, None+++def _make_fetch_page(api_token: str, logger: FilteringBoundLogger) -> FetchPageFn:+ headers = _get_headers(api_token)+ # Single session reused across pages/retries so connection pooling and per-session+ # tracking hold; redact_values masks the token regardless of header-name denylists.+ session = make_tracked_session(redact_values=(api_token,))++ @retry(+ retry=retry_if_exception_type((CircleCIRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(url: str) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429:+ sleep_seconds = _rate_limit_sleep_seconds(response)+ logger.debug(f"CircleCI: rate limited, retrying after {sleep_seconds}s. url={url}")+ raise CircleCIRetryableError(f"CircleCI API rate limited: status=429, url={url}", retry_after=sleep_seconds)++ if response.status_code >= 500:+ raise CircleCIRetryableError(f"CircleCI API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"CircleCI API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ return fetch_page+++def _iter_pages(+ fetch_page: FetchPageFn,+ path: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+ max_pages: int,+ resource: str,+ start_token: str | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield ``(items, next_page_token)`` per page of a token-paginated v2 list endpoint."""+ page_token = start_token+ pages_fetched = 0++ while True:+ data = fetch_page(_build_url(path, {**params, "page-token": page_token}))+ items = data.get("items") or []+ next_token = data.get("next_page_token")+ pages_fetched += 1++ yield items, next_token++ if not next_token:+ return++ if pages_fetched >= max_pages:+ logger.warning(+ f"CircleCI: page cap reached for {resource}, stopping pagination. max_pages={max_pages}, path={path}"+ )+ return++ page_token = next_token+++def _iter_pipeline_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,+ "/pipeline",+ {"org-slug": org_slug},+ logger,+ max_pages=MAX_PIPELINE_PAGES,+ resource="pipelines",+ start_token=start_token,+ )+++def _workflows_for_pipeline(+ fetch_page: FetchPageFn, pipeline_id: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ for workflows, _ in _iter_pages(+ fetch_page,+ f"/pipeline/{pipeline_id}/workflow",+ {},+ logger,+ max_pages=MAX_WORKFLOW_PAGES_PER_PIPELINE,+ resource=f"workflows of pipeline {pipeline_id}",+ ):+ if workflows:+ yield workflows+++def _jobs_for_workflow(+ fetch_page: FetchPageFn, workflow_id: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ for jobs, _ in _iter_pages(+ fetch_page,+ f"/workflow/{workflow_id}/job",+ {},+ logger,+ max_pages=MAX_JOB_PAGES_PER_WORKFLOW,+ resource=f"jobs of workflow {workflow_id}",+ ):+ if jobs:+ yield jobs+++def get_rows(+ api_token: str,+ org_slug: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ if endpoint not in CIRCLECI_ENDPOINTS:+ raise ValueError(f"Unknown CircleCI endpoint: {endpoint}")++ fetch_page = _make_fetch_page(api_token, logger)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_token = resume_config.next_page_token if resume_config is not None else None+ 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.+ seen_project_slugs: set[str] = set()++ for pipelines, next_token in _iter_pipeline_pages(fetch_page, org_slug, logger, start_token):+ if endpoint == "pipelines":+ if pipelines:+ yield pipelines+ elif endpoint == "workflows":+ for pipeline in pipelines:+ for workflows in _workflows_for_pipeline(fetch_page, pipeline["id"], logger):+ yield workflows+ elif endpoint == "jobs":+ for pipeline in pipelines:+ for workflows in _workflows_for_pipeline(fetch_page, pipeline["id"], logger):+ for workflow in workflows:+ for jobs in _jobs_for_workflow(fetch_page, workflow["id"], logger):+ # Job rows only carry project_slug natively; inject parent+ # identifiers plus the workflow's created_at as a stable+ # partition key (jobs expose no creation timestamp of their+ # own, and started_at is null for unstarted/approval jobs).+ yield [+ {+ **job,+ "pipeline_id": pipeline["id"],+ "workflow_id": workflow["id"],+ "workflow_created_at": workflow.get("created_at"),+ }+ for job in jobs+ ]+ elif endpoint == "projects":+ # v2 has no "list projects in org" endpoint, so distinct project slugs are+ # discovered from the pipelines scan and resolved via GET /project/{slug}.+ for pipeline in pipelines:+ project_slug = pipeline.get("project_slug")+ if not project_slug or project_slug in seen_project_slugs:+ continue+ seen_project_slugs.add(project_slug)+ project = fetch_page(_build_url(f"/project/{quote(project_slug, safe='/')}"))+ yield [project]++ # 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.+ if next_token:+ resumable_source_manager.save_state(CircleCIResumeConfig(next_page_token=next_token))+++def circleci_source(+ api_token: str,+ org_slug: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],+) -> SourceResponse:+ config = CIRCLECI_ENDPOINTS[endpoint]+ partition_key: Optional[str] = config.partition_key++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ org_slug=org_slug,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=[config.primary_key],+ # The API always returns newest-first and exposes no sort param.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/circleci/settings.py b/posthog/temporal/data_imports/sources/circleci/settings.pynew file mode 100644index 000000000000..2f5a45d82377--- /dev/null+++ b/posthog/temporal/data_imports/sources/circleci/settings.py@@ -0,0 +1,44 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField+++@dataclass+class CircleCIEndpointConfig:+ name: str+ primary_key: str = "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.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++# CircleCI API v2 list endpoints (pipelines/workflows/jobs) expose no server-side timestamp+# filter — they always return newest-first with token pagination — so every stream is full+# refresh with hard page caps. Only the insights endpoints take start/end date params (with a+# 90-day lookback), and those are a deliberate follow-up.+CIRCLECI_ENDPOINTS: dict[str, CircleCIEndpointConfig] = {+ "pipelines": CircleCIEndpointConfig(+ name="pipelines",+ partition_key="created_at",+ ),+ "workflows": CircleCIEndpointConfig(+ name="workflows",+ partition_key="created_at",+ ),+ "jobs": CircleCIEndpointConfig(+ name="jobs",+ partition_key="workflow_created_at",+ ),+ "projects": CircleCIEndpointConfig(+ name="projects",+ ),+}++ENDPOINTS = tuple(CIRCLECI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CIRCLECI_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/circleci/source.py b/posthog/temporal/data_imports/sources/circleci/source.pyindex 66cae7d04bfb..9c297f469e13 100644--- a/posthog/temporal/data_imports/sources/circleci/source.py+++ b/posthog/temporal/data_imports/sources/circleci/source.py@@ -1,29 +1,119 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.circleci.circleci import (+ CircleCIResumeConfig,+ circleci_source,+ validate_credentials as validate_circleci_credentials,+)+from posthog.temporal.data_imports.sources.circleci.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import CircleCISourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class CircleCISource(SimpleSource[CircleCISourceConfig]):+class CircleCISource(ResumableSource[CircleCISourceConfig, CircleCIResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CIRCLECI+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://circleci.com": "CircleCI authentication failed. Please check that your personal API token is valid and not expired.",+ "403 Client Error: Forbidden for url: https://circleci.com": "CircleCI denied access. Please check that your token has access to the organization and its projects.",+ "404 Client Error: Not Found for url: https://circleci.com": "CircleCI resource not found. Please verify the organization slug and that your token can access it.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CIRCLE_CI,label="CircleCI",+ caption="""Enter your CircleCI personal API token to pull your CircleCI pipelines, workflows, jobs, and projects 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",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/circleci",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="Personal API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="org_slug",+ label="Organization slug",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="gh/your-org",+ caption="The organization slug in `vcs/org` format, e.g. `gh/your-org`. You can find it under **Organization settings** in CircleCI.",+ secret=False,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: CircleCISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(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: CircleCISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_circleci_credentials(config.api_token, config.org_slug)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CircleCIResumeConfig]:+ return ResumableSourceManager[CircleCIResumeConfig](inputs, CircleCIResumeConfig)++ def source_for_pipeline(+ self,+ config: CircleCISourceConfig,+ resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return circleci_source(+ api_token=config.api_token,+ org_slug=config.org_slug,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/circleci/tests/test_circleci.py b/posthog/temporal/data_imports/sources/circleci/tests/test_circleci.pynew file mode 100644index 000000000000..af29a78ae00b--- /dev/null+++ b/posthog/temporal/data_imports/sources/circleci/tests/test_circleci.py@@ -0,0 +1,499 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from parameterized import parameterized++from posthog.temporal.data_imports.sources.circleci.circleci import (+ MAX_PIPELINE_PAGES,+ CircleCIResumeConfig,+ CircleCIRetryableError,+ _build_url,+ _rate_limit_sleep_seconds,+ circleci_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.circleci.settings import CIRCLECI_ENDPOINTS, ENDPOINTS++PATCH_SESSION = "posthog.temporal.data_imports.sources.circleci.circleci.make_tracked_session"+++def _make_manager(resume_state: CircleCIResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: dict[str, Any], status_code: int = 200, headers: dict[str, str] | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.headers = headers or {}+ response.json.return_value = body+ return response+++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."""+ state: dict[str, int] = {}++ def get(url: str, **kwargs: Any) -> mock.MagicMock:+ parsed = urlparse(url)+ path = parsed.path+ body = routes[path]+ if isinstance(body, list):+ index = min(state.get(path, 0), len(body) - 1)+ state[path] = index + 1+ return _response(body[index])+ return _response(body)++ mock_session.return_value.get.side_effect = get+++def _requested_urls(mock_session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in mock_session.return_value.get.call_args_list]+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/me") == "https://circleci.com/api/v2/me"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/pipeline", {"org-slug": "gh/posthog", "page-token": None})+ assert url == "https://circleci.com/api/v2/pipeline?org-slug=gh%2Fposthog"+++class TestRateLimitSleep:+ @parameterized.expand(+ [+ ({"retry-after": "5"}, 5),+ ({"ratelimit-reset": "30"}, 30),+ ({"x-ratelimit-reset": "12"}, 12),+ ({"retry-after": "9999"}, 120),+ ({"retry-after": "-3"}, 0),+ ({"retry-after": "not-a-number"}, 0),+ ({}, 0),+ ]+ )+ def test_sleep_seconds_from_headers(self, headers, expected):+ response = mock.MagicMock()+ response.headers = headers+ assert _rate_limit_sleep_seconds(response) == expected++ def test_retry_after_preferred_over_ratelimit_reset(self):+ response = mock.MagicMock()+ response.headers = {"retry-after": "3", "ratelimit-reset": "60"}+ assert _rate_limit_sleep_seconds(response) == 3+++class TestValidateCredentials:+ @parameterized.expand(+ [+ (200, 200, True),+ (401, None, False),+ (403, None, False),+ (200, 404, False),+ (200, 403, False),+ ]+ )+ @mock.patch(PATCH_SESSION)+ def test_status_mapping(self, me_status, pipeline_status, expected, mock_session):+ responses = [_response({}, status_code=me_status)]+ if pipeline_status is not None:+ responses.append(_response(_page([], None), status_code=pipeline_status))+ mock_session.return_value.get.side_effect = responses++ is_valid, error = validate_credentials("token", "gh/posthog")++ assert is_valid is expected+ assert (error is None) is expected++ @mock.patch(PATCH_SESSION)+ def test_skips_org_probe_without_org_slug(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ is_valid, error = validate_credentials("token", None)++ assert is_valid is True+ assert error is None+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(PATCH_SESSION)+ def test_invalid_org_message_mentions_slug(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=200),+ _response({}, status_code=404),+ ]++ is_valid, error = validate_credentials("token", "gh/nope")++ assert is_valid is False+ assert error is not None+ assert "gh/nope" in error++ @mock.patch(PATCH_SESSION)+ def test_swallows_connection_errors(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, error = validate_credentials("token", "gh/posthog")++ assert is_valid is False+ assert error is not None++ @mock.patch(PATCH_SESSION)+ def test_sends_circle_token_header(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ validate_credentials("token", None)++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Circle-Token"] == "token"+++class TestPipelinesRows:+ @mock.patch(PATCH_SESSION)+ def test_paginates_via_next_page_token(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": [+ _page([{"id": "p1"}, {"id": "p2"}], "token-2"),+ _page([{"id": "p3"}], None),+ ]+ },+ )++ manager = _make_manager()+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["p1", "p2", "p3"]+ urls = _requested_urls(mock_session)+ assert parse_qs(urlparse(urls[0]).query) == {"org-slug": ["gh/posthog"]}+ assert parse_qs(urlparse(urls[1]).query) == {"org-slug": ["gh/posthog"], "page-token": ["token-2"]}+ # State saved only while a next page exists, with the next page's token.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_page_token == "token-2"++ @mock.patch(PATCH_SESSION)+ def test_resumes_from_saved_state(self, mock_session):+ _route_session(mock_session, {"/api/v2/pipeline": [_page([{"id": "p9"}], None)]})++ manager = _make_manager(CircleCIResumeConfig(next_page_token="resume-token"))+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))++ first_url = _requested_urls(mock_session)[0]+ assert parse_qs(urlparse(first_url).query)["page-token"] == ["resume-token"]++ @mock.patch(PATCH_SESSION)+ def test_state_saved_after_yield_not_before(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": [+ _page([{"id": "p1"}], "token-2"),+ _page([], None),+ ]+ },+ )++ manager = _make_manager()+ rows = get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager)++ next(rows)+ manager.save_state.assert_not_called()+ with pytest.raises(StopIteration):+ next(rows)+ manager.save_state.assert_called_once()++ @mock.patch("posthog.temporal.data_imports.sources.circleci.circleci.MAX_PIPELINE_PAGES", 2)+ @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")})+ logger = mock.MagicMock()++ manager = _make_manager()+ batches = list(get_rows("token", "gh/posthog", "pipelines", logger, manager))++ assert len(batches) == 2+ assert mock_session.return_value.get.call_count == 2+ logger.warning.assert_called_once()+ assert "page cap" in logger.warning.call_args.args[0]++ @mock.patch(PATCH_SESSION)+ def test_empty_response_yields_nothing(self, mock_session):+ _route_session(mock_session, {"/api/v2/pipeline": _page([], None)})++ manager = _make_manager()+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown CircleCI endpoint"):+ list(get_rows("token", "gh/posthog", "nope", mock.MagicMock(), _make_manager()))+++class TestRetryBehavior:+ # Patch the sleep tenacity actually uses; the wait time is computed by `_retry_wait`, so a+ # single sleep of exactly `retry_after` proves we honor the header without double-waiting.+ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch(PATCH_SESSION)+ def test_429_honors_rate_limit_headers_then_retries(self, mock_session, mock_sleep):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=429, headers={"retry-after": "7"}),+ _response(_page([{"id": "p1"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["p1"]+ mock_sleep.assert_called_once_with(7)++ @mock.patch(PATCH_SESSION)+ def test_5xx_retries_then_succeeds(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=503),+ _response(_page([{"id": "p1"}], None)),+ ]++ manager = _make_manager()+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["p1"]+ assert mock_session.return_value.get.call_count == 2++ @mock.patch("posthog.temporal.data_imports.sources.circleci.circleci.MAX_RETRIES", 2)+ @mock.patch(PATCH_SESSION)+ def test_persistent_5xx_raises_after_max_retries(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=500)++ with pytest.raises(CircleCIRetryableError):+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), _make_manager()))++ @mock.patch(PATCH_SESSION)+ def test_4xx_raises_immediately(self, mock_session):+ response = _response({}, status_code=401)+ response.raise_for_status.side_effect = Exception("401 Client Error")+ mock_session.return_value.get.return_value = response++ with pytest.raises(Exception, match="401 Client Error"):+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.get.call_count == 1+++class TestWorkflowsFanOut:+ @mock.patch(PATCH_SESSION)+ def test_workflows_fetched_per_pipeline(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page([{"id": "p1"}, {"id": "p2"}], None),+ "/api/v2/pipeline/p1/workflow": _page(+ [{"id": "w1", "pipeline_id": "p1", "created_at": "2026-01-01T00:00:00Z"}], None+ ),+ "/api/v2/pipeline/p2/workflow": _page(+ [{"id": "w2", "pipeline_id": "p2", "created_at": "2026-01-02T00:00:00Z"}], None+ ),+ },+ )++ batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager()))+ rows = [row for batch in batches for row in batch]++ assert [row["id"] for row in rows] == ["w1", "w2"]+ # Workflow rows natively carry their parent pipeline identifier.+ assert [row["pipeline_id"] for row in rows] == ["p1", "p2"]++ @mock.patch(PATCH_SESSION)+ def test_workflow_pagination_per_pipeline(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page([{"id": "p1"}], None),+ "/api/v2/pipeline/p1/workflow": [+ _page([{"id": "w1", "pipeline_id": "p1"}], "wf-token"),+ _page([{"id": "w2", "pipeline_id": "p1"}], None),+ ],+ },+ )++ batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == ["w1", "w2"]+ workflow_urls = [url for url in _requested_urls(mock_session) if "/workflow" in url]+ assert parse_qs(urlparse(workflow_urls[1]).query)["page-token"] == ["wf-token"]++ @mock.patch("posthog.temporal.data_imports.sources.circleci.circleci.MAX_WORKFLOW_PAGES_PER_PIPELINE", 2)+ @mock.patch(PATCH_SESSION)+ def test_child_page_cap_logs_and_moves_on(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page([{"id": "p1"}], None),+ "/api/v2/pipeline/p1/workflow": _page([{"id": "w", "pipeline_id": "p1"}], "always-more"),+ },+ )+ logger = mock.MagicMock()++ batches = list(get_rows("token", "gh/posthog", "workflows", logger, _make_manager()))++ assert len([row for batch in batches for row in batch]) == 2+ logger.warning.assert_called_once()+ assert "p1" in logger.warning.call_args.args[0]++ @mock.patch(PATCH_SESSION)+ def test_saves_pipeline_scan_state_after_fanout_page(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": [+ _page([{"id": "p1"}], "pipeline-token-2"),+ _page([], None),+ ],+ "/api/v2/pipeline/p1/workflow": _page([{"id": "w1", "pipeline_id": "p1"}], None),+ },+ )++ manager = _make_manager()+ list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_page_token == "pipeline-token-2"+++class TestJobsFanOut:+ @mock.patch(PATCH_SESSION)+ def test_job_rows_carry_parent_identifiers(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page([{"id": "p1", "project_slug": "gh/posthog/posthog"}], None),+ "/api/v2/pipeline/p1/workflow": _page(+ [{"id": "w1", "pipeline_id": "p1", "created_at": "2026-01-01T00:00:00Z"}], None+ ),+ "/api/v2/workflow/w1/job": _page(+ [+ {"id": "j1", "job_number": 42, "project_slug": "gh/posthog/posthog", "status": "success"},+ {"id": "j2", "job_number": None, "project_slug": "gh/posthog/posthog", "status": "blocked"},+ ],+ None,+ ),+ },+ )++ batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager()))+ rows = [row for batch in batches for row in batch]++ assert [row["id"] for row in rows] == ["j1", "j2"]+ for row in rows:+ assert row["pipeline_id"] == "p1"+ assert row["workflow_id"] == "w1"+ assert row["workflow_created_at"] == "2026-01-01T00:00:00Z"+ # Native job fields are preserved alongside the injected parent identifiers.+ assert row["project_slug"] == "gh/posthog/posthog"++ @mock.patch(PATCH_SESSION)+ def test_jobs_traverse_every_workflow_of_every_pipeline(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page([{"id": "p1"}, {"id": "p2"}], None),+ "/api/v2/pipeline/p1/workflow": _page([{"id": "w1"}, {"id": "w2"}], None),+ "/api/v2/pipeline/p2/workflow": _page([{"id": "w3"}], None),+ "/api/v2/workflow/w1/job": _page([{"id": "j1"}], None),+ "/api/v2/workflow/w2/job": _page([{"id": "j2"}], None),+ "/api/v2/workflow/w3/job": _page([{"id": "j3"}], None),+ },+ )++ batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager()))+ rows = [row for batch in batches for row in batch]++ assert [(row["id"], row["pipeline_id"], row["workflow_id"]) for row in rows] == [+ ("j1", "p1", "w1"),+ ("j2", "p1", "w2"),+ ("j3", "p2", "w3"),+ ]++ @mock.patch("posthog.temporal.data_imports.sources.circleci.circleci.MAX_JOB_PAGES_PER_WORKFLOW", 2)+ @mock.patch(PATCH_SESSION)+ def test_job_page_cap_logs_workflow_identifier(self, mock_session):+ _route_session(+ mock_session,+ {+ "/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"),+ },+ )+ logger = mock.MagicMock()++ batches = list(get_rows("token", "gh/posthog", "jobs", logger, _make_manager()))++ assert len([row for batch in batches for row in batch]) == 2+ logger.warning.assert_called_once()+ assert "w1" in logger.warning.call_args.args[0]+++class TestProjectsRows:+ @mock.patch(PATCH_SESSION)+ def test_distinct_project_slugs_resolved_once(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/pipeline": _page(+ [+ {"id": "p1", "project_slug": "gh/posthog/posthog"},+ {"id": "p2", "project_slug": "gh/posthog/posthog"},+ {"id": "p3", "project_slug": "gh/posthog/posthog.com"},+ {"id": "p4"},+ ],+ None,+ ),+ "/api/v2/project/gh/posthog/posthog": {"id": "proj-1", "slug": "gh/posthog/posthog"},+ "/api/v2/project/gh/posthog/posthog.com": {"id": "proj-2", "slug": "gh/posthog/posthog.com"},+ },+ )++ batches = list(get_rows("token", "gh/posthog", "projects", mock.MagicMock(), _make_manager()))+ rows = [row for batch in batches for row in batch]++ assert [row["id"] for row in rows] == ["proj-1", "proj-2"]+ project_urls = [url for url in _requested_urls(mock_session) if "/project/" in url]+ assert len(project_urls) == 2+++class TestCircleCISourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_response_metadata_per_endpoint(self, endpoint):+ config = CIRCLECI_ENDPOINTS[endpoint]+ response = circleci_source("token", "gh/posthog", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @parameterized.expand([(config,) for config in CIRCLECI_ENDPOINTS.values()])+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key in {"created_at", "workflow_created_at"}++ def test_pipeline_page_cap_is_bounded(self):+ assert MAX_PIPELINE_PAGES <= 1000diff --git a/posthog/temporal/data_imports/sources/circleci/tests/test_circleci_source.py b/posthog/temporal/data_imports/sources/circleci/tests/test_circleci_source.pynew file mode 100644index 000000000000..1e47c4e26a16--- /dev/null+++ b/posthog/temporal/data_imports/sources/circleci/tests/test_circleci_source.py@@ -0,0 +1,137 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.circleci.circleci import CircleCIResumeConfig+from posthog.temporal.data_imports.sources.circleci.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.circleci.source import CircleCISource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import CircleCISourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestCircleCISource:+ def setup_method(self):+ self.source = CircleCISource()+ self.team_id = 123+ self.config = CircleCISourceConfig(api_token="circle-token", org_slug="gh/posthog")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CIRCLECI++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "CircleCI"+ assert config.label == "CircleCI"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/circleci.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_token", "org_slug"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_org_slug_field_is_required_text(self):+ config = self.source.get_source_config+ org_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "org_slug")+ assert org_field.type == SourceFieldInputConfigType.TEXT+ assert org_field.secret is False+ assert org_field.required is True++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://circleci.com/api/v2/pipeline?org-slug=gh%2Fposthog",),+ ("403 Client Error: Forbidden for url: https://circleci.com/api/v2/workflow/abc/job",),+ ("404 Client Error: Not Found for url: https://circleci.com/api/v2/project/gh/posthog/posthog",),+ ]+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",),+ ("500 Server Error for url: https://circleci.com/api/v2/pipeline",),+ ("429 Client Error: Too Many Requests for url: https://circleci.com/api/v2/pipeline",),+ ]+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_no_endpoint_advertises_incremental(self, endpoint):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ # No CircleCI v2 list endpoint has a server-side timestamp filter, so all are full refresh.+ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False+ assert schemas[endpoint].incremental_fields == []+ assert INCREMENTAL_FIELDS.get(endpoint) is None++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["pipelines"])+ assert len(schemas) == 1+ assert schemas[0].name == "pipelines"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @parameterized.expand(+ [+ ((True, None), True, None),+ ((False, "Invalid CircleCI API token. Please check your personal API token."), False, "Invalid"),+ ]+ )+ @mock.patch("posthog.temporal.data_imports.sources.circleci.source.validate_circleci_credentials")+ def test_validate_credentials(self, mock_return, expected_valid, expected_message_prefix, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if expected_message_prefix is None:+ assert error_message is None+ else:+ assert error_message is not None+ assert error_message.startswith(expected_message_prefix)+ mock_validate.assert_called_once_with(self.config.api_token, self.config.org_slug)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CircleCIResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.circleci.source.circleci_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_circleci_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "pipelines"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_circleci_source.assert_called_once()+ kwargs = mock_circleci_source.call_args.kwargs+ assert kwargs["api_token"] == "circle-token"+ assert kwargs["org_slug"] == "gh/posthog"+ assert kwargs["endpoint"] == "pipelines"+ assert kwargs["logger"] is inputs.logger+ assert kwargs["resumable_source_manager"] is managerdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex ce344c86b49b..8c872e5387f6 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -321,7 +321,8 @@ class ChorusSourceConfig(config.Config):@config.configclass CircleCISourceConfig(config.Config):- pass+ api_token: str+ org_slug: str@config.config