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(warehouse_sources): support circleci API version v3 (#113239)

Tom Owers95ba37a7f053
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index d26e785dd619..377e380f8e51 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -57,7 +57,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
3. **Dispatch on `SourceInputs.api_version`** at the request layer:
- Keep it minimal. If the version is just a header/URL segment and response shapes are compatible, thread the version string down to where the client/URL is built (see Stripe: `StripeSource.source_for_pipeline` passes `self.resolve_api_version(inputs.api_version)` → `stripe_source(...)` → `StripeClient(stripe_version=...)`). Resolve through `resolve_api_version` at the source class — never hardcode a fallback version in the request layer.
- Only introduce per-version modules/branches where behavior genuinely diverges (different pagination, different field mapping). Keep all version branching inside the source's own directory — never in shared layers.
- - A source can front several vendor API families versioned on independent tracks, so a source-level bump may move only a subset of its endpoints (and change auth for just those) — dispatch path and auth per endpoint against the resolved pin, leave the rest on their existing wire, and keep the table set identical, rather than rewriting every endpoint to the new label. The verifiable subset can also be what bounds the move: when the new version's wire is documented (paths, auth, response shape) for only some of the source's endpoints, move those to the new wire and leave the rest on their still-served legacy wire under the new default — the table set stays identical, and no endpoint ships a guessed shape. Blocking the whole bump because part of the wire is undocumented is the wrong call when the vendor still serves the old paths.
+ - A source can front several vendor API families versioned on independent tracks, so a source-level bump may move only a subset of its endpoints (and change auth for just those) — dispatch path and auth per endpoint against the resolved pin, leave the rest on their existing wire, and keep the table set identical, rather than rewriting every endpoint to the new label. The verifiable subset can also be what bounds the move: when the new version's wire is documented (paths, auth, response shape) for only some of the source's endpoints, move those to the new wire and leave the rest on their still-served legacy wire under the new default — the table set stays identical, and no endpoint ships a guessed shape. Blocking the whole bump because part of the wire is undocumented is the wrong call when the vendor still serves the old paths. Count an endpoint the vendor marks experimental, or whose list schema documents only ids, as undocumented here. When a new-version lookup takes an identifier whose format the docs leave unstated (a slug filter), resolve the id through the old version's documented lookup instead of guessing the format.
- When the new version renames endpoints, changes primary keys, or reshapes responses, the divergence must actually be branched — never leave the old single-version request path serving the new default. All the relevant surfaces can vary by version: `get_rows` receives the resolved pin in `inputs.api_version`; credential fields can key off `default_version`.
- Conversely, don't add inert scaffolding: an `api_version` param no caller varies, or a version→URL map with identical values, is a review finding, not forward-compat. Declaration-only (`supported_versions`/`default_version` and nothing else) is the correct shape just when the gate above passed on a non-wire reason — the old label is being retired, the vendor switches behavior account-side rather than per request, or the source already reads the vendor's newest generation under the framework's legacy unversioned label (verify the request paths the source actually builds, not the label — a legacy label can already ride the new wire, so the new label just formalizes it for new rows and both resolve identically). If the gate passed on nothing at all, there is no PR. When no-header requests resolve to a version bound to the credential account-side (not a moving "latest"), threading a version header is not merely inert — it overrides the customer's chosen version, the silent move this framework exists to prevent — so stay declaration-only and don't send one.
- **Discovery and probe paths receive the pin — consume it.** The framework passes the resolved pin as the `api_version` parameter of `get_schemas`, `validate_credentials`, `get_endpoint_permissions`, and the webhook management methods. A multi-version source MUST build its discovery/probe/webhook clients from that parameter, not from `default_version` or a hardcoded header — otherwise a pinned source discovers/reconciles under the wrong version and its tables can disappear, duplicate, or fail reconciliation. Resolve it with `self.resolve_api_version(api_version)` — callers with a row pass an already-resolved value (mirroring `SourceInputs.api_version`), so the source-side resolve only covers pre-creation calls that pass `None`. Ignoring the parameter is only correct when you can state why the version makes no difference to that path.
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 124b85a66210..a5cdb4c42b72 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
@@ -13,7 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+CIRCLECI_V2 = "v2"
+CIRCLECI_V3 = "v3"
CIRCLECI_BASE_URL = "https://circleci.com/api/v2"
+CIRCLECI_V3_BASE_URL = "https://circleci.com/api/v3"
REQUEST_TIMEOUT_SECONDS = 60
MAX_RETRIES = 5
# Most CircleCI v2 list endpoints return ~20 items per page and don't accept a page-size param,
@@ -36,6 +39,15 @@ 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")
+# Endpoints a v3 pin reads from the v3 API. v3 can only look up the calling user, and its deploy
+# component listings are experimental and document no attributes, so the other endpoints stay on
+# the v2 API under a v3 pin.
+V3_ENDPOINTS = frozenset({"pipelines", "workflows", "jobs", "projects"})
+# v3 list endpoints document 50 as the page[limit] maximum for projects; runs, workflows and jobs
+# document no bounds, so they use the server default.
+V3_PROJECTS_PAGE_LIMIT = 50
+MAX_V3_PROJECT_PAGES = 100
+MAX_V3_RUN_PAGES_PER_PROJECT = 50
class CircleCIRetryableError(Exception):
@@ -66,7 +78,9 @@ class CircleCIResumeConfig:
# 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
+ next_page_token: str | None = None
+ # v3 page[cursor] for the org's projects listing, which drives every v3 stream.
+ page_cursor: str | None = None
def _get_headers(api_token: str) -> dict[str, str]:
@@ -76,11 +90,22 @@ def _get_headers(api_token: str) -> dict[str, str]:
}
-def _build_url(path: str, params: dict[str, Any] | None = None) -> str:
+def _get_v3_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, params: dict[str, Any] | None = None, base_url: str = CIRCLECI_BASE_URL) -> 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)}"
+ return f"{base_url}{path}"
+ return f"{base_url}{path}?{urlencode(clean_params)}"
+
+
+def _build_v3_url(path: str, params: dict[str, Any] | None = None) -> str:
+ return _build_url(path, params, base_url=CIRCLECI_V3_BASE_URL)
def _rate_limit_sleep_seconds(response: requests.Response) -> int:
@@ -98,7 +123,7 @@ def _rate_limit_sleep_seconds(response: requests.Response) -> int:
return 0
-def validate_credentials(api_token: str, org_slug: str | None = None) -> tuple[bool, str | None]:
+def validate_credentials(api_token: str, org_slug: str | None, api_version: str) -> 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)
@@ -114,6 +139,9 @@ def validate_credentials(api_token: str, org_slug: str | None = None) -> tuple[b
if not org_slug:
return True, None
+ if api_version == CIRCLECI_V3:
+ return _validate_v3_org(session, api_token, org_slug)
+
try:
response = session.get(
_build_url("/pipeline", {"org-slug": org_slug}),
@@ -123,18 +151,56 @@ def validate_credentials(api_token: str, org_slug: str | None = None) -> tuple[b
except Exception:
return False, "Could not reach the CircleCI API. Please try again."
+ if response.status_code != 200:
+ return False, _org_not_found_message(org_slug)
+
+ return True, None
+
+
+def _org_not_found_message(org_slug: str) -> str:
+ return (
+ 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`."
+ )
+
+
+def _validate_v3_org(session: requests.Session, api_token: str, org_slug: str) -> tuple[bool, str | None]:
+ try:
+ response = session.get(_build_url("/me/collaborations"), headers=_get_headers(api_token), timeout=10)
+ except Exception:
+ return False, "Could not reach the CircleCI API. Please try again."
+
+ collaborations = response.json() if response.status_code == 200 else []
+ org_id = next(
+ (c.get("id") for c in collaborations or [] if c.get("slug") == org_slug and c.get("id")),
+ None,
+ )
+ if not org_id:
+ return False, _org_not_found_message(org_slug)
+
+ try:
+ response = session.get(
+ _build_v3_url("/projects", {"filter[org_id]": org_id, "page[limit]": 1}),
+ headers=_get_v3_headers(api_token),
+ 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`.",
+ f"CircleCI API v3 denied access to the projects of organization '{org_slug}'. "
+ "Please check that your token can access the organization.",
)
return True, None
-def _make_fetch_page(api_token: str, logger: FilteringBoundLogger) -> FetchPageFn:
- headers = _get_headers(api_token)
+def _make_fetch_page(
+ api_token: str, logger: FilteringBoundLogger, headers: dict[str, str] | None = None
+) -> FetchPageFn:
+ headers = headers or _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,))
@@ -377,16 +443,198 @@ def _user_rows(
yield [user]
+def _iter_v3_pages(
+ fetch_page: FetchPageFn,
+ path: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+ max_pages: int,
+ resource: str,
+ start_cursor: str | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Yield ``(items, next_cursor)`` per page of a cursor-paginated v3 list endpoint."""
+ cursor = start_cursor
+ pages_fetched = 0
+
+ while True:
+ data = fetch_page(_build_v3_url(path, {**params, "page[cursor]": cursor}))
+ items = data.get("data") or []
+ # Some v3 collections (jobs) are not paginated and carry no page member at all.
+ next_cursor = (data.get("page") or {}).get("next")
+ pages_fetched += 1
+
+ yield items, next_cursor
+
+ if not next_cursor:
+ return
+
+ if next_cursor == cursor:
+ raise ValueError(
+ f"CircleCI returned the same page cursor 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}"
+ )
+ return
+
+ cursor = next_cursor
+
+
+def _v3_row(item: dict[str, Any]) -> dict[str, Any]:
+ # v3 wraps each resource as {id, attributes, references}. Attributes become top-level columns
+ # so partition keys such as created_at sit where they do on v2 rows.
+ return {**(item.get("attributes") or {}), "id": item["id"], "references": item.get("references") or {}}
+
+
+def _v3_runs_for_project(
+ fetch_page: FetchPageFn, project_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ # v3 calls a pipeline execution a run (a v3 pipeline is the definition), and it lists runs
+ # per project only, so the pipelines table walks the org's projects.
+ for runs, _ in _iter_v3_pages(
+ fetch_page,
+ "/runs",
+ {"filter[project_id]": project_id},
+ logger,
+ max_pages=MAX_V3_RUN_PAGES_PER_PROJECT,
+ resource=f"runs of project {project_id}",
+ ):
+ if runs:
+ yield [_v3_row(run) for run in runs]
+
+
+def _v3_workflows_for_run(
+ fetch_page: FetchPageFn, run_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ for workflows, _ in _iter_v3_pages(
+ fetch_page,
+ "/workflows",
+ {"filter[run_id]": run_id},
+ logger,
+ max_pages=MAX_WORKFLOW_PAGES_PER_PIPELINE,
+ resource=f"workflows of run {run_id}",
+ ):
+ if workflows:
+ yield [_v3_row(workflow) for workflow in workflows]
+
+
+def _v3_jobs_for_workflow(
+ fetch_page: FetchPageFn, workflow_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ for jobs, _ in _iter_v3_pages(
+ fetch_page,
+ "/jobs",
+ {"filter[workflow_id]": workflow_id},
+ logger,
+ max_pages=MAX_JOB_PAGES_PER_WORKFLOW,
+ resource=f"jobs of workflow {workflow_id}",
+ ):
+ if jobs:
+ yield [_v3_row(job) for job in jobs]
+
+
+def _v3_run_rows(
+ fetch_page: FetchPageFn, endpoint: str, projects: list[dict[str, Any]], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ for project in projects:
+ for runs in _v3_runs_for_project(fetch_page, project["id"], logger):
+ if endpoint == "pipelines":
+ yield runs
+ continue
+ for run in runs:
+ for workflows in _v3_workflows_for_run(fetch_page, run["id"], logger):
+ if endpoint == "workflows":
+ yield workflows
+ continue
+ for workflow in workflows:
+ for jobs in _v3_jobs_for_workflow(fetch_page, workflow["id"], logger):
+ # v3 jobs have no creation timestamp either, so they keep the v2
+ # workflow_created_at partition key.
+ yield [
+ {
+ **job,
+ "run_id": run["id"],
+ "workflow_id": workflow["id"],
+ "workflow_created_at": workflow.get("created_at"),
+ }
+ for job in jobs
+ ]
+
+
+def _stage_cursor_before_last_batch(
+ batches: Iterator[list[dict[str, Any]]],
+ resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],
+ next_cursor: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ # The pipeline commits staged state right after it writes a batch, so the next projects cursor
+ # is staged before the page's last batch. Holding one batch back finds that last batch.
+ previous: list[dict[str, Any]] | None = None
+ for batch in batches:
+ if previous is not None:
+ yield previous
+ previous = batch
+
+ if next_cursor:
+ resumable_source_manager.save_state(CircleCIResumeConfig(page_cursor=next_cursor))
+
+ if previous is not None:
+ yield previous
+
+
+def _get_v3_rows(
+ api_token: str,
+ org_slug: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ fetch_page = _make_fetch_page(api_token, logger, _get_v3_headers(api_token))
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_cursor = resume_config.page_cursor if resume_config is not None else None
+ if start_cursor is not None:
+ logger.debug(f"CircleCI: resuming {endpoint} from saved projects page cursor")
+
+ # v3 does not document the slug format filter[slug] takes on /orgs, so the org UUID comes
+ # from the v2 collaborations list that already resolves it for the deploy endpoints.
+ org_id = _resolve_org_id(_make_fetch_page(api_token, logger), org_slug)
+
+ for projects, next_cursor in _iter_v3_pages(
+ fetch_page,
+ "/projects",
+ {"filter[org_id]": org_id, "page[limit]": V3_PROJECTS_PAGE_LIMIT},
+ logger,
+ max_pages=MAX_V3_PROJECT_PAGES,
+ resource="projects",
+ start_cursor=start_cursor,
+ ):
+ if endpoint == "projects":
+ batches: Iterator[list[dict[str, Any]]] = iter(
+ [[_v3_row(project) for project in projects]] if projects else []
+ )
+ else:
+ batches = _v3_run_rows(fetch_page, endpoint, projects, logger)
+
+ yield from _stage_cursor_before_last_batch(batches, resumable_source_manager, next_cursor)
+
+
def get_rows(
api_token: str,
org_slug: str,
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
if endpoint not in CIRCLECI_ENDPOINTS:
raise ValueError(f"Unknown CircleCI endpoint: {endpoint}")
+ if api_version == CIRCLECI_V3 and endpoint in V3_ENDPOINTS:
+ yield from _get_v3_rows(api_token, org_slug, endpoint, logger, resumable_source_manager)
+ return
+
fetch_page = _make_fetch_page(api_token, logger)
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -434,6 +682,7 @@ def circleci_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[CircleCIResumeConfig],
+ api_version: str,
) -> SourceResponse:
config = CIRCLECI_ENDPOINTS[endpoint]
partition_key: Optional[str] = config.partition_key
@@ -446,6 +695,7 @@ def circleci_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ api_version=api_version,
),
primary_keys=list(config.primary_keys),
# No v2 list endpoint takes a sort param, and the ones that document an order return
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 c5346780c6e2..7c8b0e58aa98 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
@@ -8,6 +8,8 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfigType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.circleci.circleci import (
+ CIRCLECI_V2,
+ CIRCLECI_V3,
CircleCIResumeConfig,
circleci_source,
validate_credentials as validate_circleci_credentials,
@@ -34,9 +36,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
class CircleCISource(ResumableSource[CircleCISourceConfig, CircleCIResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("v2",)
- default_version = "v2"
- api_docs_url = "https://circleci.com/docs/api/v2/"
+ supported_versions = (CIRCLECI_V2, CIRCLECI_V3)
+ default_version = CIRCLECI_V3
+ api_docs_url = "https://circleci.com/docs/api/v3/"
@property
def source_type(self) -> ExternalDataSourceType:
@@ -47,6 +49,7 @@ class CircleCISource(ResumableSource[CircleCISourceConfig, CircleCIResumeConfig]
"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.",
+ "410 Client Error: Gone for url: https://circleci.com": "CircleCI no longer serves an API route this source uses. Please contact support to move this source to a supported CircleCI API version.",
}
@property
@@ -124,7 +127,7 @@ You can create a personal API token in your [CircleCI user settings](https://app
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_circleci_credentials(config.api_token, config.org_slug)
+ return validate_circleci_credentials(config.api_token, config.org_slug, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CircleCIResumeConfig]:
return ResumableSourceManager[CircleCIResumeConfig](inputs, CircleCIResumeConfig)
@@ -141,4 +144,5 @@ You can create a personal API token in your [CircleCI user settings](https://app
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
)
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 107ca621a731..f54fb2f81ec4 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
@@ -8,8 +8,11 @@ import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.circleci.circleci import (
+ CIRCLECI_V2,
+ CIRCLECI_V3,
COMPONENTS_PAGE_SIZE,
MAX_PIPELINE_PAGES,
+ V3_PROJECTS_PAGE_LIMIT,
CircleCIResumeConfig,
CircleCIRetryableError,
_build_url,
@@ -121,7 +124,7 @@ class TestValidateCredentials:
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")
+ is_valid, error = validate_credentials("token", "gh/posthog", CIRCLECI_V2)
assert is_valid is expected
assert (error is None) is expected
@@ -130,7 +133,7 @@ class TestValidateCredentials:
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)
+ is_valid, error = validate_credentials("token", None, CIRCLECI_V2)
assert is_valid is True
assert error is None
@@ -143,7 +146,7 @@ class TestValidateCredentials:
_response({}, status_code=404),
]
- is_valid, error = validate_credentials("token", "gh/nope")
+ is_valid, error = validate_credentials("token", "gh/nope", CIRCLECI_V2)
assert is_valid is False
assert error is not None
@@ -153,7 +156,7 @@ class TestValidateCredentials:
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")
+ is_valid, error = validate_credentials("token", "gh/posthog", CIRCLECI_V2)
assert is_valid is False
assert error is not None
@@ -162,11 +165,35 @@ class TestValidateCredentials:
def test_sends_circle_token_header(self, mock_session):
mock_session.return_value.get.return_value = _response({}, status_code=200)
- validate_credentials("token", None)
+ validate_credentials("token", None, CIRCLECI_V2)
headers = mock_session.return_value.get.call_args.kwargs["headers"]
assert headers["Circle-Token"] == "token"
+ @parameterized.expand(
+ [
+ ("valid", [{"id": "org-uuid", "slug": "gh/posthog"}], 200, True),
+ ("org not visible to the token", [{"id": "other-uuid", "slug": "gh/other"}], None, False),
+ ("v3 rejects the token", [{"id": "org-uuid", "slug": "gh/posthog"}], 401, False),
+ ]
+ )
+ @mock.patch(PATCH_SESSION)
+ def test_v3_probes_org_projects_with_bearer_token(self, _name, collaborations, v3_status, expected, mock_session):
+ responses = [_response({}), _response(collaborations)]
+ if v3_status is not None:
+ responses.append(_response({"data": [], "page": {"next": None}}, status_code=v3_status))
+ mock_session.return_value.get.side_effect = responses
+
+ is_valid, error = validate_credentials("token", "gh/posthog", CIRCLECI_V3)
+
+ assert is_valid is expected
+ assert (error is None) is expected
+ if v3_status is not None:
+ v3_call = mock_session.return_value.get.call_args_list[-1]
+ assert urlparse(v3_call.args[0]).path == "/api/v3/projects"
+ assert parse_qs(urlparse(v3_call.args[0]).query)["filter[org_id]"] == ["org-uuid"]
+ assert v3_call.kwargs["headers"]["Authorization"] == "Bearer token"
+
class TestPipelinesRows:
@mock.patch(PATCH_SESSION)
@@ -182,7 +209,7 @@ class TestPipelinesRows:
)
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))
+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2))
assert [item["id"] for batch in batches for item in batch] == ["p1", "p2", "p3"]
urls = _requested_urls(mock_session)
@@ -197,7 +224,7 @@ class TestPipelinesRows:
_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))
+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2))
first_url = _requested_urls(mock_session)[0]
assert parse_qs(urlparse(first_url).query)["page-token"] == ["resume-token"]
@@ -215,7 +242,7 @@ class TestPipelinesRows:
)
manager = _make_manager()
- rows = get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager)
+ rows = get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2)
next(rows)
manager.save_state.assert_not_called()
@@ -241,7 +268,7 @@ class TestPipelinesRows:
logger = mock.MagicMock()
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "pipelines", logger, manager))
+ batches = list(get_rows("token", "gh/posthog", "pipelines", logger, manager, CIRCLECI_V2))
assert len(batches) == 2
assert mock_session.return_value.get.call_count == 2
@@ -254,14 +281,14 @@ class TestPipelinesRows:
_route_session(mock_session, {"/api/v2/pipeline": _page([], None)})
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))
+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2))
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()))
+ list(get_rows("token", "gh/posthog", "nope", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
class TestRetryBehavior:
@@ -276,7 +303,7 @@ class TestRetryBehavior:
]
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))
+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2))
assert [item["id"] for batch in batches for item in batch] == ["p1"]
mock_sleep.assert_called_once_with(7)
@@ -289,7 +316,7 @@ class TestRetryBehavior:
]
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager))
+ batches = list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V2))
assert [item["id"] for batch in batches for item in batch] == ["p1"]
assert mock_session.return_value.get.call_count == 2
@@ -300,7 +327,7 @@ class TestRetryBehavior:
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()))
+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
@mock.patch(PATCH_SESSION)
def test_4xx_raises_immediately(self, mock_session):
@@ -309,7 +336,7 @@ class TestRetryBehavior:
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()))
+ list(get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
assert mock_session.return_value.get.call_count == 1
@@ -330,7 +357,7 @@ class TestWorkflowsFanOut:
},
)
- batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
rows = [row for batch in batches for row in batch]
assert [row["id"] for row in rows] == ["w1", "w2"]
@@ -350,7 +377,7 @@ class TestWorkflowsFanOut:
},
)
- batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
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]
@@ -375,7 +402,7 @@ class TestWorkflowsFanOut:
)
logger = mock.MagicMock()
- batches = list(get_rows("token", "gh/posthog", "workflows", logger, _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "workflows", logger, _make_manager(), CIRCLECI_V2))
assert len([row for batch in batches for row in batch]) == 2
logger.warning.assert_called_once()
@@ -396,7 +423,7 @@ class TestWorkflowsFanOut:
)
manager = _make_manager()
- list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), manager))
+ list(get_rows("token", "gh/posthog", "workflows", mock.MagicMock(), manager, CIRCLECI_V2))
manager.save_state.assert_called_once()
assert manager.save_state.call_args.args[0].next_page_token == "pipeline-token-2"
@@ -422,7 +449,7 @@ class TestJobsFanOut:
},
)
- batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
rows = [row for batch in batches for row in batch]
assert [row["id"] for row in rows] == ["j1", "j2"]
@@ -447,7 +474,7 @@ class TestJobsFanOut:
},
)
- batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
rows = [row for batch in batches for row in batch]
assert [(row["id"], row["pipeline_id"], row["workflow_id"]) for row in rows] == [
@@ -476,7 +503,7 @@ class TestJobsFanOut:
)
logger = mock.MagicMock()
- batches = list(get_rows("token", "gh/posthog", "jobs", logger, _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "jobs", logger, _make_manager(), CIRCLECI_V2))
assert len([row for batch in batches for row in batch]) == 2
logger.warning.assert_called_once()
@@ -504,7 +531,7 @@ class TestProjectsRows:
},
)
- batches = list(get_rows("token", "gh/posthog", "projects", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "projects", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
rows = [row for batch in batches for row in batch]
assert [row["id"] for row in rows] == ["proj-1", "proj-2"]
@@ -517,8 +544,10 @@ COLLABORATIONS = [[{"id": "org-uuid", "slug": "gh/posthog", "name": "PostHog"}]]
class TestComponentsRows:
+ # v3 deploy component listings are experimental, so a v3 pin keeps reading them from v2.
+ @parameterized.expand([(CIRCLECI_V2,), (CIRCLECI_V3,)])
@mock.patch(PATCH_SESSION)
- def test_org_slug_resolved_to_org_id_and_paginated(self, mock_session):
+ def test_org_slug_resolved_to_org_id_and_paginated(self, api_version, mock_session):
_route_session(
mock_session,
{
@@ -531,7 +560,7 @@ class TestComponentsRows:
)
manager = _make_manager()
- batches = list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager))
+ batches = list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager, api_version))
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]
@@ -558,7 +587,7 @@ class TestComponentsRows:
)
manager = _make_manager(CircleCIResumeConfig(next_page_token="resume-token"))
- list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager))
+ list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), manager, CIRCLECI_V2))
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"]
@@ -574,7 +603,7 @@ class TestComponentsRows:
_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()))
+ list(get_rows("token", "gh/posthog", "components", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
class TestComponentVersionsFanOut:
@@ -602,7 +631,9 @@ class TestComponentVersionsFanOut:
},
)
- batches = list(get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager()))
+ batches = list(
+ get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager(), CIRCLECI_V2)
+ )
rows = [row for batch in batches for row in batch]
assert [(row["component_id"], row["name"]) for row in rows] == [
@@ -631,7 +662,7 @@ class TestComponentVersionsFanOut:
)
with pytest.raises(ValueError, match="same page token twice"):
- list(get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager()))
+ list(get_rows("token", "gh/posthog", "component_versions", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
class TestUsersRows:
@@ -655,7 +686,7 @@ class TestUsersRows:
},
)
- batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
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
@@ -676,16 +707,137 @@ class TestUsersRows:
mock_session.return_value.get.side_effect = get
- batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager()))
+ batches = list(get_rows("token", "gh/posthog", "users", mock.MagicMock(), _make_manager(), CIRCLECI_V2))
assert [row["id"] for batch in batches for row in batch] == ["u2"]
+def _v3_page(items: list[dict[str, Any]], next_cursor: str | None = None) -> dict[str, Any]:
+ return {"data": items, "page": {"next": next_cursor, "prev": None}}
+
+
+class TestV3Rows:
+ @mock.patch(PATCH_SESSION)
+ def test_pipelines_walk_org_projects_into_runs(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v3/projects": [
+ _v3_page([{"id": "proj-1", "attributes": {"name": "posthog"}}], "projects-cursor-2"),
+ _v3_page([{"id": "proj-2", "attributes": {"name": "other"}}]),
+ ],
+ "/api/v3/runs": [
+ _v3_page(
+ [
+ {
+ "id": "run-1",
+ "attributes": {"number": 7, "created_at": "2026-01-01T00:00:00Z", "phase": "ended"},
+ "references": {"project": {"id": "proj-1"}},
+ }
+ ],
+ "runs-cursor-2",
+ ),
+ _v3_page([{"id": "run-2", "attributes": {"number": 8, "created_at": "2026-01-02T00:00:00Z"}}]),
+ _v3_page([{"id": "run-3", "attributes": {"number": 1, "created_at": "2026-01-03T00:00:00Z"}}]),
+ ],
+ },
+ )
+
+ manager = _make_manager()
+ batches = []
+ saves_seen_at_yield = []
+ for batch in get_rows("token", "gh/posthog", "pipelines", mock.MagicMock(), manager, CIRCLECI_V3):
+ batches.append(batch)
+ saves_seen_at_yield.append(manager.save_state.call_count)
+ rows = [row for batch in batches for row in batch]
+
+ # The next projects cursor is staged before the first page's last batch, so the pipeline
+ # commits it together with that batch.
+ assert saves_seen_at_yield == [0, 1, 1]
+
+ assert [row["id"] for row in rows] == ["run-1", "run-2", "run-3"]
+ # Attributes are lifted to top-level columns so the created_at partition key resolves.
+ assert rows[0]["created_at"] == "2026-01-01T00:00:00Z"
+ assert rows[0]["number"] == 7
+ assert rows[0]["references"] == {"project": {"id": "proj-1"}}
+
+ calls = mock_session.return_value.get.call_args_list
+ v3_calls = [call for call in calls if "/api/v3/" in call.args[0]]
+ assert all(call.kwargs["headers"]["Authorization"] == "Bearer token" for call in v3_calls)
+ queries = [(urlparse(call.args[0]).path, parse_qs(urlparse(call.args[0]).query)) for call in v3_calls]
+ assert queries == [
+ ("/api/v3/projects", {"filter[org_id]": ["org-uuid"], "page[limit]": [str(V3_PROJECTS_PAGE_LIMIT)]}),
+ ("/api/v3/runs", {"filter[project_id]": ["proj-1"]}),
+ ("/api/v3/runs", {"filter[project_id]": ["proj-1"], "page[cursor]": ["runs-cursor-2"]}),
+ (
+ "/api/v3/projects",
+ {
+ "filter[org_id]": ["org-uuid"],
+ "page[limit]": [str(V3_PROJECTS_PAGE_LIMIT)],
+ "page[cursor]": ["projects-cursor-2"],
+ },
+ ),
+ ("/api/v3/runs", {"filter[project_id]": ["proj-2"]}),
+ ]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].page_cursor == "projects-cursor-2"
+
+ @mock.patch(PATCH_SESSION)
+ def test_resumes_projects_scan_from_saved_cursor(self, mock_session):
+ _route_session(
+ mock_session,
+ {COLLABORATIONS_PATH: COLLABORATIONS, "/api/v3/projects": _v3_page([{"id": "proj-9", "attributes": {}}])},
+ )
+
+ manager = _make_manager(CircleCIResumeConfig(page_cursor="resume-cursor"))
+ batches = list(get_rows("token", "gh/posthog", "projects", mock.MagicMock(), manager, CIRCLECI_V3))
+
+ assert [row["id"] for batch in batches for row in batch] == ["proj-9"]
+ projects_url = next(url for url in _requested_urls(mock_session) if "/api/v3/projects" in url)
+ assert parse_qs(urlparse(projects_url).query)["page[cursor]"] == ["resume-cursor"]
+
+ @mock.patch(PATCH_SESSION)
+ def test_job_rows_carry_parent_identifiers(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ COLLABORATIONS_PATH: COLLABORATIONS,
+ "/api/v3/projects": _v3_page([{"id": "proj-1", "attributes": {}}]),
+ "/api/v3/runs": _v3_page([{"id": "run-1", "attributes": {}}]),
+ "/api/v3/workflows": _v3_page(
+ [{"id": "wf-1", "attributes": {"name": "build", "created_at": "2026-01-01T00:00:00Z"}}]
+ ),
+ # The v3 jobs collection is not paginated, so it carries no page member.
+ "/api/v3/jobs": {
+ "data": [
+ {
+ "id": "job-1",
+ "attributes": {"name": "test", "number": 42, "phase": "ended", "type": "build"},
+ "references": {"workflow": {"id": "wf-1"}, "project": {"id": "proj-1"}},
+ }
+ ]
+ },
+ },
+ )
+
+ batches = list(get_rows("token", "gh/posthog", "jobs", mock.MagicMock(), _make_manager(), CIRCLECI_V3))
+ rows = [row for batch in batches for row in batch]
+
+ assert len(rows) == 1
+ assert rows[0]["id"] == "job-1"
+ assert rows[0]["number"] == 42
+ assert rows[0]["run_id"] == "run-1"
+ assert rows[0]["workflow_id"] == "wf-1"
+ assert rows[0]["workflow_created_at"] == "2026-01-01T00:00:00Z"
+ assert parse_qs(urlparse(_requested_urls(mock_session)[-1]).query) == {"filter[workflow_id]": ["wf-1"]}
+
+
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())
+ response = circleci_source("token", "gh/posthog", endpoint, mock.MagicMock(), _make_manager(), CIRCLECI_V2)
assert response.name == endpoint
assert response.primary_keys == list(config.primary_keys)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci_source.py
index 7132339392ef..f39dd1d244a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci/tests/test_circleci_source.py
@@ -1,3 +1,7 @@
+from urllib.parse import urlparse
+
+from unittest import mock
+
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.circleci.settings import (
@@ -58,5 +62,29 @@ class TestCircleCISource:
assert len(schemas) == 1
assert schemas[0].name == "pipelines"
+ @parameterized.expand(
+ [
+ ("v2", "/api/v2/pipeline"),
+ ("v3", "/api/v3/projects"),
+ # An unpinned call (pre-creation validation) resolves to the v3 default.
+ (None, "/api/v3/projects"),
+ ]
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci.circleci.make_tracked_session"
+ )
+ def test_validate_credentials_probes_the_pinned_api(self, api_version, expected_org_probe_path, mock_session):
+ collaborations = mock.MagicMock(status_code=200)
+ collaborations.json.return_value = [{"id": "org-uuid", "slug": "gh/posthog"}]
+ ok = mock.MagicMock(status_code=200)
+ mock_session.return_value.get.side_effect = lambda url, **kwargs: (
+ collaborations if "/me/collaborations" in url else ok
+ )
+
+ assert self.source.validate_credentials(self.config, self.team_id, api_version=api_version) == (True, None)
+
+ last_url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(last_url).path == expected_org_probe_path
+
def test_get_schemas_filtered_unknown_name_returns_empty(self):
assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []