: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_insights import source (#71192)
Tom Owerse8019075f04b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 31f324c03c4e..7a61fb627e36 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -136,6 +136,7 @@ the row lists both.| confluent_cloud | HTTP | requests | ✅ || chartmogul | HTTP | requests | ✅ || circleci | HTTP | requests | ✅ |+| circleci_insights | HTTP | requests | ✅ || cimis | HTTP | requests | ✅ || cisco_duo | HTTP | requests (hand-rolled HMAC-SHA1 request signing) | ✅ || cloudflare | HTTP | requests | ✅ |@@ -634,7 +635,6 @@ doesn't conflict with concurrent PRs.- chift- chorus- cin7-- circleci_insights- cisco_meraki- clarifai- clazardiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/canonical_descriptions.pynew file mode 100644index 000000000000..a26f6a5c3265--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/canonical_descriptions.py@@ -0,0 +1,75 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "workflow_metrics": {+ "description": "Aggregated metrics for each workflow in a project over the configured reporting window: run counts, success rate, duration percentiles, credits consumed, MTTR, and throughput.",+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getProjectWorkflowMetrics",+ "columns": {+ "name": "The name of the workflow.",+ "metrics": "Metrics aggregated over the reporting window: total/successful/failed runs, success rate, duration percentiles (min, mean, median, p95, max), total credits used, MTTR, and throughput.",+ "window_start": "The start of the aggregation window for the workflow's metrics.",+ "window_end": "The end of the aggregation window for the workflow's metrics.",+ "project_id": "The unique ID of the project the workflow belongs to.",+ "project_slug": "The project slug (vcs/org/repo) the workflow belongs to, as configured on the source.",+ },+ },+ "workflow_runs": {+ "description": "Individual recent runs of each workflow, with duration, status, branch, and credits consumed. CircleCI retains run-level Insights data for roughly 90 days.",+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getProjectWorkflowRuns",+ "columns": {+ "id": "The unique ID of the workflow run.",+ "branch": "The VCS branch the run was triggered on.",+ "duration": "The duration of the run, in seconds.",+ "status": "The outcome of the run (e.g. success, failed, canceled).",+ "created_at": "The date and time the run was created.",+ "stopped_at": "The date and time the run stopped.",+ "credits_used": "The number of credits the run consumed.",+ "is_approval": "Whether the run is an approval workflow.",+ "workflow_name": "The name of the workflow the run belongs to.",+ "project_slug": "The project slug (vcs/org/repo) the run belongs to, as configured on the source.",+ },+ },+ "job_metrics": {+ "description": "Aggregated metrics for each job of each workflow in a project over the configured reporting window: run counts, success rate, duration percentiles, credits consumed, and throughput.",+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getWorkflowJobMetrics",+ "columns": {+ "name": "The name of the job.",+ "metrics": "Metrics aggregated over the reporting window: total/successful/failed runs, success rate, duration percentiles (min, mean, median, p95, max), total credits used, and throughput.",+ "window_start": "The start of the aggregation window for the job's metrics.",+ "window_end": "The end of the aggregation window for the job's metrics.",+ "workflow_name": "The name of the workflow the job belongs to.",+ "project_slug": "The project slug (vcs/org/repo) the job belongs to, as configured on the source.",+ },+ },+ "flaky_tests": {+ "description": "Tests CircleCI has detected as flaky in a project: tests that pass and fail across runs with no code change, with where they flake and how often.",+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getFlakyTests",+ "columns": {+ "test_name": "The name of the flaky test.",+ "classname": "The class or suite the flaky test belongs to.",+ "file": "The source file of the flaky test, when reported.",+ "job_name": "The name of the job the test most recently flaked in.",+ "job_number": "The number of the job the test most recently flaked in.",+ "workflow_name": "The name of the workflow the test most recently flaked in.",+ "workflow_id": "The ID of the workflow run the test most recently flaked in.",+ "workflow_created_at": "The date and time of the workflow run the test most recently flaked in.",+ "pipeline_number": "The number of the pipeline the test most recently flaked in.",+ "times_flaked": "How many times the test has flaked.",+ "time_wasted": "The time wasted on the test's flakiness, in seconds.",+ "source": "The source of the flaky-test detection.",+ "project_slug": "The project slug (vcs/org/repo) the flaky test belongs to, as configured on the source.",+ },+ },+ "org_summary_metrics": {+ "description": "Per-project summary metrics and trends across an organization over the configured reporting window, from the org-level Insights summary. Requires the token to have org membership.",+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getOrgSummaryData",+ "columns": {+ "project_name": "The name of the project the metrics belong to.",+ "metrics": "Summary metrics for the project over the reporting window (throughput, duration, success rate, credits).",+ "trends": "Trends for the project's metrics relative to the previous window.",+ "org_slug": "The organization slug (vcs/org) derived from the configured project slugs.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/circleci_insights.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/circleci_insights.pynew file mode 100644index 000000000000..659c3e26c50a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/circleci_insights.py@@ -0,0 +1,510 @@+import re+import dataclasses+from collections.abc import Callable, Iterator+from datetime import date, datetime+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.settings import (+ CIRCLECI_INSIGHTS_ENDPOINTS,+ DEFAULT_REPORTING_WINDOW,+ REPORTING_WINDOWS,+)+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++CIRCLECI_BASE_URL = "https://circleci.com/api/v2"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Insights list endpoints return token-paginated pages (~250 runs / ~20 aggregates per page).+# Aggregate listings are one row per workflow/job name so stay tiny; runs are bounded by+# CircleCI's ~90-day Insights retention, so the caps below are generous runaway guards.+MAX_METRIC_PAGES = 100+MAX_RUN_PAGES_PER_WORKFLOW = 500+# CircleCI rate-limits per token (not officially documented); 429s carry RateLimit-* headers+# we honor before retrying.+MAX_RATE_LIMIT_SLEEP_SECONDS = 120++PROJECT_SLUG_RE = re.compile(r"^[^/\s]+/[^/\s]+/[^/\s]+$")+++class CircleciInsightsRetryableError(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, CircleciInsightsRetryableError) and exc.retry_after:+ return exc.retry_after+ return _EXPONENTIAL_WAIT(retry_state)+++class CircleciInsightsResumeConfig:+ # Project slug (or org slug for org-level endpoints) the sync was working through.+ slug: str+ # Workflow the fan-out was inside, for per-workflow endpoints.+ workflow_name: str | None = None+ # Page token to resume the in-progress listing from.+ next_page_token: str | None = None+ # True once every page of `slug` has been yielded, so a resume skips it entirely+ # instead of re-syncing it from the start.+ slug_done: bool = False+++def parse_project_slugs(raw: str) -> list[str]:+ """Split the user-entered project slugs field (comma/newline separated) into an ordered,+ de-duplicated list of `vcs/org/repo` slugs."""+ slugs: list[str] = []+ for part in re.split(r"[,\n]", raw or ""):+ slug = part.strip().strip("/")+ if slug and slug not in slugs:+ slugs.append(slug)+ return slugs+++def org_slugs_from_projects(project_slugs: list[str]) -> list[str]:+ """Derive the org slugs (`vcs/org`) covered by the configured project slugs."""+ orgs: list[str] = []+ for slug in project_slugs:+ parts = slug.split("/")+ if len(parts) < 2:+ continue+ org = f"{parts[0]}/{parts[1]}"+ if org not in orgs:+ orgs.append(org)+ return orgs+++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 _format_start_date(value: Any) -> str | None:+ """Format the incremental cursor as the date-only ISO 8601 string the `start-date` param+ accepts. Date-only granularity re-reads the watermark day on every sync; the overlap is+ deduped by the primary-key merge and avoids any ambiguity in the API's datetime parsing."""+ if isinstance(value, datetime):+ return value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ if isinstance(value, str) and value:+ return value[:10]+ return None+++def validate_credentials(api_token: str, project_slugs_raw: str) -> tuple[bool, str | None]:+ """Confirm the token with /me, then confirm each configured project slug resolves against+ the Insights API."""+ project_slugs = parse_project_slugs(project_slugs_raw)+ if not project_slugs:+ return False, "Enter at least one project slug in `vcs/org/repo` format, e.g. `gh/your-org/your-repo`."++ for slug in project_slugs:+ if not PROJECT_SLUG_RE.match(slug):+ return (+ False,+ f"Project slug '{slug}' is not in the expected `vcs/org/repo` format, e.g. `gh/your-org/your-repo`.",+ )++ 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."++ for slug in project_slugs:+ try:+ response = session.get(+ _build_url(+ f"/insights/{quote(slug, safe='/')}/workflows",+ {"reporting-window": "last-24-hours"},+ ),+ 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 project '{slug}' was not found or is not accessible with this token. "+ "Use the `vcs/org/repo` format, e.g. `gh/your-org/your-repo`.",+ )++ 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((CircleciInsightsRetryableError, 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 Insights: rate limited, retrying after {sleep_seconds}s. url={url}")+ raise CircleciInsightsRetryableError(+ f"CircleCI API rate limited: status=429, url={url}", retry_after=sleep_seconds+ )++ if response.status_code >= 500:+ raise CircleciInsightsRetryableError(+ f"CircleCI API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"CircleCI Insights 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 Insights 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 Insights: page cap reached for {resource}, stopping pagination. "+ f"max_pages={max_pages}, path={path}"+ )+ return++ page_token = next_token+++def _branch_params(all_branches: bool) -> dict[str, Any]:+ # Omitting the param means the project's default branch; all-branches=true widens to every branch.+ return {"all-branches": "true"} if all_branches else {}+++def _discover_workflow_names(+ fetch_page: FetchPageFn,+ project_slug: str,+ all_branches: bool,+ logger: FilteringBoundLogger,+) -> list[str]:+ """List the workflow names Insights knows for a project, from the workflow metrics listing.+ Always uses the widest reporting window so fan-out doesn't miss workflows that only ran+ early in the retention period."""+ names: list[str] = []+ for items, _ in _iter_pages(+ fetch_page,+ f"/insights/{quote(project_slug, safe='/')}/workflows",+ {"reporting-window": "last-90-days", **_branch_params(all_branches)},+ logger,+ max_pages=MAX_METRIC_PAGES,+ resource=f"workflow discovery for {project_slug}",+ ):+ for item in items:+ name = item.get("name")+ if name and name not in names:+ names.append(name)+ return names+++def _validate_reporting_window(reporting_window: str | None) -> str:+ if reporting_window in REPORTING_WINDOWS:+ return reporting_window+ return DEFAULT_REPORTING_WINDOW+++def get_rows(+ api_token: str,+ project_slugs_raw: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleciInsightsResumeConfig],+ reporting_window: str | None = None,+ all_branches: bool = False,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ if endpoint not in CIRCLECI_INSIGHTS_ENDPOINTS:+ raise ValueError(f"Unknown CircleCI Insights endpoint: {endpoint}")++ config = CIRCLECI_INSIGHTS_ENDPOINTS[endpoint]+ window = _validate_reporting_window(reporting_window)+ project_slugs = parse_project_slugs(project_slugs_raw)+ slugs = org_slugs_from_projects(project_slugs) if config.org_level else project_slugs++ fetch_page = _make_fetch_page(api_token, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.slug not in slugs:+ # The configured slugs changed since the state was saved; start from scratch.+ resume = None+ if resume is not None:+ logger.debug(f"CircleCI Insights: resuming {endpoint} from slug {resume.slug}")++ for slug in slugs:+ slug_resume: CircleciInsightsResumeConfig | None = None+ if resume is not None:+ if slug != resume.slug:+ # Slugs before the resume point were fully synced before the interruption.+ continue+ slug_resume, resume = resume, None+ if slug_resume.slug_done:+ continue++ if endpoint == "workflow_metrics":+ yield from _project_workflow_metrics_rows(+ fetch_page, slug, window, all_branches, logger, resumable_source_manager, slug_resume+ )+ elif endpoint in ("workflow_runs", "job_metrics"):+ yield from _project_workflow_fan_out_rows(+ fetch_page,+ slug,+ endpoint,+ window,+ all_branches,+ logger,+ resumable_source_manager,+ slug_resume,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif endpoint == "flaky_tests":+ yield from _project_flaky_tests_rows(fetch_page, slug, logger)+ elif endpoint == "org_summary_metrics":+ yield from _org_summary_rows(fetch_page, slug, window, logger)++ # Mark the slug fully synced so a resume moves straight to the next one.+ resumable_source_manager.save_state(CircleciInsightsResumeConfig(slug=slug, slug_done=True))+++def _project_workflow_metrics_rows(+ fetch_page: FetchPageFn,+ project_slug: str,+ window: str,+ all_branches: bool,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleciInsightsResumeConfig],+ slug_resume: CircleciInsightsResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ start_token = slug_resume.next_page_token if slug_resume is not None else None+ for items, next_token in _iter_pages(+ fetch_page,+ f"/insights/{quote(project_slug, safe='/')}/workflows",+ {"reporting-window": window, **_branch_params(all_branches)},+ logger,+ max_pages=MAX_METRIC_PAGES,+ resource=f"workflow metrics for {project_slug}",+ start_token=start_token,+ ):+ if items:+ yield [{**item, "project_slug": project_slug} for item in items]+ # Save state after the page's rows have been yielded, so a crash re-yields the+ # in-progress page (merge dedupes on primary key) instead of skipping it.+ if next_token:+ resumable_source_manager.save_state(+ CircleciInsightsResumeConfig(slug=project_slug, next_page_token=next_token)+ )+++def _project_workflow_fan_out_rows(+ fetch_page: FetchPageFn,+ project_slug: str,+ endpoint: str,+ window: str,+ all_branches: bool,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleciInsightsResumeConfig],+ slug_resume: CircleciInsightsResumeConfig | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ config = CIRCLECI_INSIGHTS_ENDPOINTS[endpoint]+ workflow_names = _discover_workflow_names(fetch_page, project_slug, all_branches, logger)++ params: dict[str, Any] = {**_branch_params(all_branches)}+ if config.takes_reporting_window:+ params["reporting-window"] = window+ if endpoint == "workflow_runs" and should_use_incremental_field:+ start_date = _format_start_date(db_incremental_field_last_value)+ if start_date:+ # Server-side filter: every page of the runs listing only returns runs created on+ # or after this date (the filter rides along with the page token on later pages).+ params["start-date"] = start_date++ max_pages = MAX_RUN_PAGES_PER_WORKFLOW if endpoint == "workflow_runs" else MAX_METRIC_PAGES++ resume_workflow = slug_resume.workflow_name if slug_resume is not None else None+ if resume_workflow is not None and resume_workflow not in workflow_names:+ # The workflow disappeared from the listing since the state was saved; walk them all.+ resume_workflow = None++ for workflow_name in workflow_names:+ start_token: str | None = None+ if resume_workflow is not None:+ if workflow_name != resume_workflow:+ # Workflows before the resume point were fully synced before the interruption.+ continue+ start_token = slug_resume.next_page_token if slug_resume is not None else None+ resume_workflow = None++ path = config.path.format(slug=quote(project_slug, safe="/"), workflow_name=quote(workflow_name, safe=""))+ for items, next_token in _iter_pages(+ fetch_page,+ path,+ params,+ logger,+ max_pages=max_pages,+ resource=f"{endpoint} for {project_slug} workflow {workflow_name}",+ start_token=start_token,+ ):+ if items:+ yield [{**item, "project_slug": project_slug, "workflow_name": workflow_name} for item in items]+ if next_token:+ resumable_source_manager.save_state(+ CircleciInsightsResumeConfig(+ slug=project_slug, workflow_name=workflow_name, next_page_token=next_token+ )+ )+++def _project_flaky_tests_rows(+ fetch_page: FetchPageFn,+ project_slug: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ data = fetch_page(_build_url(f"/insights/{quote(project_slug, safe='/')}/flaky-tests"))+ flaky_tests = data.get("flaky_tests") or []+ if flaky_tests:+ yield [{**item, "project_slug": project_slug} for item in flaky_tests]+++def _org_summary_rows(+ fetch_page: FetchPageFn,+ org_slug: str,+ window: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ # The org summary endpoint is auth-gated (org membership required), so its response shape+ # could not be verified against the live API; parsing follows the documented+ # {org_data, org_project_data} envelope and degrades to zero rows on an unexpected shape.+ data = fetch_page(_build_url(f"/insights/{quote(org_slug, safe='/')}/summary", {"reporting-window": window}))+ project_rows = data.get("org_project_data")+ if not isinstance(project_rows, list):+ logger.warning(f"CircleCI Insights: unexpected org summary response shape for {org_slug}, syncing zero rows")+ return+ rows = [{**item, "org_slug": org_slug} for item in project_rows if isinstance(item, dict)]+ if rows:+ yield rows+++def circleci_insights_source(+ api_token: str,+ project_slugs_raw: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CircleciInsightsResumeConfig],+ reporting_window: str | None = None,+ all_branches: bool = False,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CIRCLECI_INSIGHTS_ENDPOINTS[endpoint]+ partition_key: Optional[str] = config.partition_key++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ project_slugs_raw=project_slugs_raw,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ reporting_window=reporting_window,+ all_branches=all_branches,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys),+ # The runs listing returns newest-first with no sort param (verified live); the+ # aggregate listings have no meaningful row order.+ sort_mode="desc" if endpoint == "workflow_runs" else "asc",+ partition_count=1 if partition_key else None,+ partition_size=1 if partition_key else None,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/settings.pynew file mode 100644index 000000000000..44844a052689--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/settings.py@@ -0,0 +1,104 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Reporting windows the Insights aggregate endpoints accept. CircleCI retains Insights data+# for roughly 90 days, so last-90-days is both the default and the maximum coverage.+REPORTING_WINDOWS = (+ "last-24-hours",+ "last-7-days",+ "last-30-days",+ "last-60-days",+ "last-90-days",+)+DEFAULT_REPORTING_WINDOW = "last-90-days"+++@dataclass+class CircleciInsightsEndpointConfig:+ name: str+ # Path template relative to the API base; {slug} is the project slug (or org slug for+ # org-level endpoints) and {workflow_name} is filled per workflow during fan-out.+ path: str+ # Composite by default: Insights rows are aggregates keyed by name within a project (and+ # workflow), not globally unique ids, so most keys include the injected parent identifiers.+ primary_keys: list[str]+ # Stable creation-time field for datetime partitioning. Only workflow_runs rows carry one;+ # the aggregate tables are rolling-window snapshots with no stable per-row timestamp.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Fan-out endpoints are fetched once per workflow name discovered from the project's+ # workflow metrics listing.+ fan_out_workflows: bool = False+ # Whether the endpoint accepts the reporting-window query param.+ takes_reporting_window: bool = False+ # Org-level endpoints iterate the org slugs derived from the configured project slugs+ # (vcs/org/repo -> vcs/org) instead of the project slugs themselves.+ org_level: bool = False+ # Whether the endpoint accepts branch filtering (branch / all-branches params).+ takes_branch_params: bool = False+ should_sync_default: bool = True+++CIRCLECI_INSIGHTS_ENDPOINTS: dict[str, CircleciInsightsEndpointConfig] = {+ "workflow_metrics": CircleciInsightsEndpointConfig(+ name="workflow_metrics",+ path="/insights/{slug}/workflows",+ primary_keys=["project_slug", "name"],+ takes_reporting_window=True,+ takes_branch_params=True,+ ),+ "workflow_runs": CircleciInsightsEndpointConfig(+ name="workflow_runs",+ path="/insights/{slug}/workflows/{workflow_name}",+ # Workflow run ids are UUIDs, unique across projects and workflows.+ primary_keys=["id"],+ partition_key="created_at",+ # The runs endpoint honors a server-side start-date filter (verified with a live+ # probe: start-date drops older runs from the response), so incremental sync+ # genuinely reduces the data fetched. Rows come back newest-first.+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ fan_out_workflows=True,+ takes_branch_params=True,+ ),+ "job_metrics": CircleciInsightsEndpointConfig(+ name="job_metrics",+ path="/insights/{slug}/workflows/{workflow_name}/jobs",+ primary_keys=["project_slug", "workflow_name", "name"],+ fan_out_workflows=True,+ takes_reporting_window=True,+ takes_branch_params=True,+ ),+ "flaky_tests": CircleciInsightsEndpointConfig(+ name="flaky_tests",+ path="/insights/{slug}/flaky-tests",+ # A test is reported once per (workflow, job) it flakes in; the test identity is+ # classname + test_name, neither of which is unique on its own.+ primary_keys=["project_slug", "workflow_name", "job_name", "classname", "test_name"],+ ),+ "org_summary_metrics": CircleciInsightsEndpointConfig(+ name="org_summary_metrics",+ path="/insights/{slug}/summary",+ primary_keys=["org_slug", "project_name"],+ takes_reporting_window=True,+ org_level=True,+ # The org summary endpoint requires org membership (it 401s without auth, so its+ # response shape could not be verified against the live API) and may be plan-gated.+ # Off by default so a fresh source doesn't enable a table whose first sync may 403.+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(CIRCLECI_INSIGHTS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CIRCLECI_INSIGHTS_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/source.pyindex 735dda86860a..47524fcb5fb7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/source.py@@ -1,13 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights import (+ CircleciInsightsResumeConfig,+ circleci_insights_source,+ validate_credentials as validate_circleci_insights_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.settings import (+ CIRCLECI_INSIGHTS_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (CircleciInsightsSourceConfig,)@@ -15,18 +39,146 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CircleciInsightsSource(SimpleSource[CircleciInsightsSourceConfig]):+class CircleciInsightsSource(ResumableSource[CircleciInsightsSourceConfig, CircleciInsightsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CIRCLECIINSIGHTS+ @property+ def connection_host_fields(self) -> list[str]:+ # project_slugs selects which projects the stored token reads from; changing it must+ # require re-entering the secret so a preserved token can't be retargeted at other+ # projects or orgs the token can access.+ return ["project_slugs"]++ 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 configured projects.",+ "404 Client Error: Not Found for url: https://circleci.com": "CircleCI resource not found. Please verify the project slugs and that your token can access them.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CIRCLECI_INSIGHTS,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="CircleCI",+ label="CircleCI Insights",+ caption="""Enter your CircleCI personal API token and project slugs to pull pipeline health metrics — workflow and job durations, success rates, credit usage, recent runs, and flaky tests — from the CircleCI Insights API into the PostHog Data warehouse.++You can create a personal API token in your [CircleCI user settings](https://app.circleci.com/settings/user/tokens). Note that CircleCI retains Insights data for roughly 90 days.""",iconPath="/static/services/circleci_insights.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/circleci-insights",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["ci", "flaky tests"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="Personal API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="project_slugs",+ label="Project slugs",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="gh/your-org/your-repo",+ caption="Comma-separated project slugs in `vcs/org/repo` format, e.g. `gh/your-org/your-repo`. You can find a project's slug in its URL on CircleCI.",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="reporting_window",+ label="Reporting window for aggregated metrics",+ required=False,+ defaultValue="last-90-days",+ options=[+ SourceFieldSelectConfigOption(label="Last 24 hours", value="last-24-hours"),+ SourceFieldSelectConfigOption(label="Last 7 days", value="last-7-days"),+ SourceFieldSelectConfigOption(label="Last 30 days", value="last-30-days"),+ SourceFieldSelectConfigOption(label="Last 60 days", value="last-60-days"),+ SourceFieldSelectConfigOption(label="Last 90 days", value="last-90-days"),+ ],+ ),+ SourceFieldSelectConfig(+ name="branch_scope",+ label="Branch scope",+ required=False,+ defaultValue="default_branch",+ options=[+ SourceFieldSelectConfigOption(label="Default branch only", value="default_branch"),+ SourceFieldSelectConfigOption(label="All branches", value="all_branches"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CircleciInsightsSourceConfig,+ 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, []),+ should_sync_default=CIRCLECI_INSIGHTS_ENDPOINTS[endpoint].should_sync_default,+ detected_primary_keys=CIRCLECI_INSIGHTS_ENDPOINTS[endpoint].primary_keys,+ )+ 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: CircleciInsightsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_circleci_insights_credentials(config.api_token, config.project_slugs)++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[CircleciInsightsResumeConfig]:+ return ResumableSourceManager[CircleciInsightsResumeConfig](inputs, CircleciInsightsResumeConfig)++ def source_for_pipeline(+ self,+ config: CircleciInsightsSourceConfig,+ resumable_source_manager: ResumableSourceManager[CircleciInsightsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return circleci_insights_source(+ api_token=config.api_token,+ project_slugs_raw=config.project_slugs,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ reporting_window=config.reporting_window,+ all_branches=config.branch_scope == "all_branches",+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights.pynew file mode 100644index 000000000000..e497d8c1992a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights.py@@ -0,0 +1,580 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights import (+ CircleciInsightsResumeConfig,+ CircleciInsightsRetryableError,+ _format_start_date,+ circleci_insights_source,+ get_rows,+ org_slugs_from_projects,+ parse_project_slugs,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.settings import (+ CIRCLECI_INSIGHTS_ENDPOINTS,+ ENDPOINTS,+)++PATCH_SESSION = "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights.make_tracked_session"+++def _make_manager(resume_state: CircleciInsightsResumeConfig | 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:+ path = urlparse(url).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]+++def _rows(batches: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:+ return [row for batch in batches for row in batch]+++class TestSlugParsing:+ @parameterized.expand(+ [+ ("gh/posthog/posthog", ["gh/posthog/posthog"]),+ ("gh/a/b, gh/a/c", ["gh/a/b", "gh/a/c"]),+ ("gh/a/b\ngh/a/c", ["gh/a/b", "gh/a/c"]),+ (" gh/a/b ,, gh/a/b ", ["gh/a/b"]),+ ("/gh/a/b/", ["gh/a/b"]),+ ("", []),+ (" ,\n ", []),+ ]+ )+ def test_parse_project_slugs(self, raw, expected):+ assert parse_project_slugs(raw) == expected++ def test_org_slugs_deduped_in_order(self):+ assert org_slugs_from_projects(["gh/a/one", "gh/a/two", "bb/b/three"]) == ["gh/a", "bb/b"]+++class TestFormatStartDate:+ @parameterized.expand(+ [+ (datetime(2026, 7, 1, 13, 30, tzinfo=UTC), "2026-07-01"),+ (date(2026, 7, 1), "2026-07-01"),+ ("2026-07-01T13:30:00Z", "2026-07-01"),+ (None, None),+ ("", None),+ ]+ )+ def test_formats_as_date_only(self, value, expected):+ assert _format_start_date(value) == expected+++class TestValidateCredentials:+ @mock.patch(PATCH_SESSION)+ def test_bad_slug_format_short_circuits_without_network(self, mock_session):+ is_valid, error = validate_credentials("token", "not-a-slug")++ assert is_valid is False+ assert error is not None and "not-a-slug" in error+ mock_session.return_value.get.assert_not_called()++ @mock.patch(PATCH_SESSION)+ def test_empty_slugs_rejected(self, mock_session):+ is_valid, error = validate_credentials("token", " ")++ assert is_valid is False+ assert error is not None+ mock_session.return_value.get.assert_not_called()++ @parameterized.expand(+ [+ (401, None, False),+ (200, 404, False),+ (200, 403, False),+ (200, 200, True),+ ]+ )+ @mock.patch(PATCH_SESSION)+ def test_status_mapping(self, me_status, project_status, expected, mock_session):+ responses = [_response({}, status_code=me_status)]+ if project_status is not None:+ responses.append(_response(_page([], None), status_code=project_status))+ mock_session.return_value.get.side_effect = responses++ is_valid, error = validate_credentials("token", "gh/posthog/posthog")++ assert is_valid is expected+ assert (error is None) is expected++ @mock.patch(PATCH_SESSION)+ def test_probes_every_project_and_names_the_broken_one(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=200), # /me+ _response(_page([], None), status_code=200), # first project ok+ _response({}, status_code=404), # second project missing+ ]++ is_valid, error = validate_credentials("token", "gh/posthog/posthog, gh/posthog/nope")++ assert is_valid is False+ assert error is not None and "gh/posthog/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/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", "gh/posthog/posthog")++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Circle-Token"] == "token"+++class TestWorkflowMetricsRows:+ @mock.patch(PATCH_SESSION)+ def test_paginates_and_injects_project_slug_across_projects(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": [+ _page([{"name": "ci"}], "token-2"),+ _page([{"name": "release"}], None),+ ],+ "/api/v2/insights/gh/a/two/workflows": _page([{"name": "deploy"}], None),+ },+ )++ manager = _make_manager()+ batches = list(get_rows("token", "gh/a/one, gh/a/two", "workflow_metrics", mock.MagicMock(), manager))+ rows = _rows(batches)++ assert [(row["project_slug"], row["name"]) for row in rows] == [+ ("gh/a/one", "ci"),+ ("gh/a/one", "release"),+ ("gh/a/two", "deploy"),+ ]+ first_url = _requested_urls(mock_session)[0]+ assert parse_qs(urlparse(first_url).query)["reporting-window"] == ["last-90-days"]+ second_url = _requested_urls(mock_session)[1]+ assert parse_qs(urlparse(second_url).query)["page-token"] == ["token-2"]++ @mock.patch(PATCH_SESSION)+ def test_reporting_window_and_all_branches_passed_through(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/one/workflows": _page([], None)})++ manager = _make_manager()+ list(+ get_rows(+ "token",+ "gh/a/one",+ "workflow_metrics",+ mock.MagicMock(),+ manager,+ reporting_window="last-7-days",+ all_branches=True,+ )+ )++ query = parse_qs(urlparse(_requested_urls(mock_session)[0]).query)+ assert query["reporting-window"] == ["last-7-days"]+ assert query["all-branches"] == ["true"]++ @mock.patch(PATCH_SESSION)+ def test_state_saved_after_each_page_and_on_project_completion(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": [+ _page([{"name": "ci"}], "token-2"),+ _page([{"name": "release"}], None),+ ]+ },+ )++ manager = _make_manager()+ rows = get_rows("token", "gh/a/one", "workflow_metrics", mock.MagicMock(), manager)++ next(rows)+ manager.save_state.assert_not_called()+ next(rows)+ saved = manager.save_state.call_args.args[0]+ assert saved.next_page_token == "token-2"+ with pytest.raises(StopIteration):+ next(rows)+ final = manager.save_state.call_args.args[0]+ assert final.slug == "gh/a/one"+ assert final.slug_done is True++ @mock.patch(PATCH_SESSION)+ def test_resume_skips_completed_project(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/two/workflows": _page([{"name": "deploy"}], None)})++ manager = _make_manager(CircleciInsightsResumeConfig(slug="gh/a/one", slug_done=True))+ batches = list(get_rows("token", "gh/a/one, gh/a/two", "workflow_metrics", mock.MagicMock(), manager))++ assert [row["project_slug"] for row in _rows(batches)] == ["gh/a/two"]+ assert all("gh/a/one" not in url for url in _requested_urls(mock_session))++ @mock.patch(PATCH_SESSION)+ def test_resume_mid_project_starts_at_saved_token(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None)})++ manager = _make_manager(CircleciInsightsResumeConfig(slug="gh/a/one", next_page_token="resume-token"))+ list(get_rows("token", "gh/a/one", "workflow_metrics", 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_resume_with_unknown_slug_starts_over(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None)})++ manager = _make_manager(CircleciInsightsResumeConfig(slug="gh/gone/away", next_page_token="stale"))+ batches = list(get_rows("token", "gh/a/one", "workflow_metrics", mock.MagicMock(), manager))++ assert [row["name"] for row in _rows(batches)] == ["ci"]+ first_url = _requested_urls(mock_session)[0]+ assert "page-token" not in parse_qs(urlparse(first_url).query)++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown CircleCI Insights endpoint"):+ list(get_rows("token", "gh/a/one", "nope", mock.MagicMock(), _make_manager()))+++class TestWorkflowRunsFanOut:+ @mock.patch(PATCH_SESSION)+ def test_runs_fetched_per_discovered_workflow_with_parent_fields(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}, {"name": "release"}], None),+ "/api/v2/insights/gh/a/one/workflows/ci": _page(+ [{"id": "r1", "created_at": "2026-07-01T00:00:00Z"}], None+ ),+ "/api/v2/insights/gh/a/one/workflows/release": _page(+ [{"id": "r2", "created_at": "2026-07-02T00:00:00Z"}], None+ ),+ },+ )++ batches = list(get_rows("token", "gh/a/one", "workflow_runs", mock.MagicMock(), _make_manager()))+ rows = _rows(batches)++ assert [(row["id"], row["project_slug"], row["workflow_name"]) for row in rows] == [+ ("r1", "gh/a/one", "ci"),+ ("r2", "gh/a/one", "release"),+ ]++ @mock.patch(PATCH_SESSION)+ def test_incremental_passes_start_date_to_run_pages_only(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),+ "/api/v2/insights/gh/a/one/workflows/ci": _page([], None),+ },+ )++ list(+ get_rows(+ "token",+ "gh/a/one",+ "workflow_runs",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 1, 12, 0, tzinfo=UTC),+ )+ )++ urls = _requested_urls(mock_session)+ discovery_query = parse_qs(urlparse(urls[0]).query)+ runs_query = parse_qs(urlparse(urls[1]).query)+ # Discovery always scans the full retention window so no workflow is missed.+ assert discovery_query["reporting-window"] == ["last-90-days"]+ assert "start-date" not in discovery_query+ assert runs_query["start-date"] == ["2026-07-01"]++ @mock.patch(PATCH_SESSION)+ def test_full_refresh_sends_no_start_date(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),+ "/api/v2/insights/gh/a/one/workflows/ci": _page([], None),+ },+ )++ list(get_rows("token", "gh/a/one", "workflow_runs", mock.MagicMock(), _make_manager()))++ runs_query = parse_qs(urlparse(_requested_urls(mock_session)[1]).query)+ assert "start-date" not in runs_query++ @mock.patch(PATCH_SESSION)+ def test_resume_mid_workflow_skips_earlier_workflows(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page(+ [{"name": "ci"}, {"name": "release"}, {"name": "deploy"}], None+ ),+ "/api/v2/insights/gh/a/one/workflows/release": _page([{"id": "r2"}], None),+ "/api/v2/insights/gh/a/one/workflows/deploy": _page([{"id": "r3"}], None),+ },+ )++ manager = _make_manager(+ CircleciInsightsResumeConfig(slug="gh/a/one", workflow_name="release", next_page_token="wf-token")+ )+ batches = list(get_rows("token", "gh/a/one", "workflow_runs", mock.MagicMock(), manager))++ assert [row["id"] for row in _rows(batches)] == ["r2", "r3"]+ assert any(url.endswith("release?page-token=wf-token") for url in _requested_urls(mock_session))+ # Workflows after the resume point start from their first page.+ deploy_urls = [url for url in _requested_urls(mock_session) if "/workflows/deploy" in url]+ assert "page-token" not in parse_qs(urlparse(deploy_urls[0]).query)++ @mock.patch(PATCH_SESSION)+ def test_state_saved_with_workflow_position(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),+ "/api/v2/insights/gh/a/one/workflows/ci": [+ _page([{"id": "r1"}], "run-token-2"),+ _page([{"id": "r2"}], None),+ ],+ },+ )++ manager = _make_manager()+ list(get_rows("token", "gh/a/one", "workflow_runs", mock.MagicMock(), manager))++ mid_save = manager.save_state.call_args_list[0].args[0]+ assert mid_save.slug == "gh/a/one"+ assert mid_save.workflow_name == "ci"+ assert mid_save.next_page_token == "run-token-2"+++class TestJobMetricsFanOut:+ @mock.patch(PATCH_SESSION)+ def test_job_rows_carry_parents_and_reporting_window(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),+ "/api/v2/insights/gh/a/one/workflows/ci/jobs": _page([{"name": "build"}, {"name": "test"}], None),+ },+ )++ batches = list(+ get_rows(+ "token", "gh/a/one", "job_metrics", mock.MagicMock(), _make_manager(), reporting_window="last-30-days"+ )+ )+ rows = _rows(batches)++ assert [(row["project_slug"], row["workflow_name"], row["name"]) for row in rows] == [+ ("gh/a/one", "ci", "build"),+ ("gh/a/one", "ci", "test"),+ ]+ jobs_url = next(url for url in _requested_urls(mock_session) if "/jobs" in url)+ assert parse_qs(urlparse(jobs_url).query)["reporting-window"] == ["last-30-days"]+++class TestFlakyTestsRows:+ @mock.patch(PATCH_SESSION)+ def test_unwraps_envelope_and_injects_project_slug(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/one/flaky-tests": {+ "flaky_tests": [{"test_name": "t1", "classname": "c", "job_name": "j", "workflow_name": "w"}],+ "total_flaky_tests": 1,+ }+ },+ )++ batches = list(get_rows("token", "gh/a/one", "flaky_tests", mock.MagicMock(), _make_manager()))+ rows = _rows(batches)++ assert rows == [+ {+ "test_name": "t1",+ "classname": "c",+ "job_name": "j",+ "workflow_name": "w",+ "project_slug": "gh/a/one",+ }+ ]++ @mock.patch(PATCH_SESSION)+ def test_no_flaky_tests_yields_nothing(self, mock_session):+ _route_session(+ mock_session, {"/api/v2/insights/gh/a/one/flaky-tests": {"flaky_tests": [], "total_flaky_tests": 0}}+ )++ assert list(get_rows("token", "gh/a/one", "flaky_tests", mock.MagicMock(), _make_manager())) == []+++class TestOrgSummaryRows:+ @mock.patch(PATCH_SESSION)+ def test_projects_collapse_to_one_org_fetch(self, mock_session):+ _route_session(+ mock_session,+ {+ "/api/v2/insights/gh/a/summary": {+ "org_data": {"metrics": {}},+ "org_project_data": [{"project_name": "one"}, {"project_name": "two"}],+ }+ },+ )++ batches = list(+ get_rows("token", "gh/a/one, gh/a/two", "org_summary_metrics", mock.MagicMock(), _make_manager())+ )+ rows = _rows(batches)++ assert [(row["org_slug"], row["project_name"]) for row in rows] == [("gh/a", "one"), ("gh/a", "two")]+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(PATCH_SESSION)+ def test_unexpected_shape_syncs_zero_rows(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/summary": {"message": "no insights"}})+ logger = mock.MagicMock()++ batches = list(get_rows("token", "gh/a/one", "org_summary_metrics", logger, _make_manager()))++ assert batches == []+ logger.warning.assert_called_once()+++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([{"name": "ci"}], None)),+ ]++ batches = list(get_rows("token", "gh/a/one", "workflow_metrics", mock.MagicMock(), _make_manager()))++ assert [row["name"] for row in _rows(batches)] == ["ci"]+ 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([{"name": "ci"}], None)),+ ]++ batches = list(get_rows("token", "gh/a/one", "workflow_metrics", mock.MagicMock(), _make_manager()))++ assert [row["name"] for row in _rows(batches)] == ["ci"]+ assert mock_session.return_value.get.call_count == 2++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights.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(CircleciInsightsRetryableError):+ list(get_rows("token", "gh/a/one", "workflow_metrics", 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/a/one", "workflow_metrics", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.get.call_count == 1+++class TestPageCap:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights.MAX_METRIC_PAGES",+ 2,+ )+ @mock.patch(PATCH_SESSION)+ def test_page_cap_stops_pagination_and_logs(self, mock_session):+ _route_session(mock_session, {"/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], "always-more")})+ logger = mock.MagicMock()++ batches = list(get_rows("token", "gh/a/one", "workflow_metrics", logger, _make_manager()))++ assert len(batches) == 2+ logger.warning.assert_called_once()+ assert "page cap" in logger.warning.call_args.args[0]+++class TestCircleciInsightsSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_response_metadata_per_endpoint(self, endpoint):+ config = CIRCLECI_INSIGHTS_ENDPOINTS[endpoint]+ response = circleci_insights_source("token", "gh/a/one", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ 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++ def test_workflow_runs_declares_desc_sort(self):+ # The runs listing returns newest-first; declaring asc would corrupt the+ # incremental watermark checkpointing.+ response = circleci_insights_source("token", "gh/a/one", "workflow_runs", mock.MagicMock(), _make_manager())+ assert response.sort_mode == "desc"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights_source.pynew file mode 100644index 000000000000..5565465638ce--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/circleci_insights/tests/test_circleci_insights_source.py@@ -0,0 +1,163 @@+from datetime import UTC, datetime++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.circleci_insights import (+ CircleciInsightsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.source import (+ CircleciInsightsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ CircleciInsightsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCircleciInsightsSource:+ def setup_method(self):+ self.source = CircleciInsightsSource()+ self.team_id = 123+ self.config = CircleciInsightsSourceConfig(+ api_token="circle-token",+ project_slugs="gh/posthog/posthog, gh/posthog/posthog.com",+ reporting_window="last-90-days",+ branch_scope="all_branches",+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CIRCLECIINSIGHTS++ def test_get_source_config_is_released_alpha(self):+ config = self.source.get_source_config++ assert config.name.value == "CircleciInsights"+ assert config.label == "CircleCI Insights"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/circleci-insights"++ def test_fields(self):+ config = self.source.get_source_config++ assert [f.name for f in config.fields] == ["api_token", "project_slugs", "reporting_window", "branch_scope"]++ token_field = next(f for f in config.fields if f.name == "api_token")+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ window_field = next(f for f in config.fields if f.name == "reporting_window")+ assert isinstance(window_field, SourceFieldSelectConfig)+ assert window_field.defaultValue == "last-90-days"++ def test_connection_host_fields_includes_project_slugs(self):+ # The token is sent to circleci.com scoped to <project_slugs>, so retargeting the+ # project slugs must force re-entry of the token.+ assert self.source.connection_host_fields == ["project_slugs"]++ 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_only_workflow_runs_advertises_incremental(self, endpoint):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ expected = endpoint == "workflow_runs"++ # Only the runs endpoint has a server-side timestamp filter (start-date); the+ # aggregate endpoints are rolling-window snapshots and stay full refresh.+ assert schemas[endpoint].supports_incremental is expected+ assert bool(INCREMENTAL_FIELDS.get(endpoint)) is expected++ def test_org_summary_is_deselected_by_default(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["org_summary_metrics"].should_sync_default is False+ assert schemas["workflow_runs"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["flaky_tests"])+ assert [schema.name for schema in schemas] == ["flaky_tests"]++ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://circleci.com/api/v2/insights/gh/a/b/workflows", True),+ ("403 Client Error: Forbidden for url: https://circleci.com/api/v2/insights/gh/a/summary", True),+ ("404 Client Error: Not Found for url: https://circleci.com/api/v2/insights/gh/a/b/flaky-tests", True),+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers", False),+ ("500 Server Error for url: https://circleci.com/api/v2/insights/gh/a/b/workflows", False),+ ("429 Client Error: Too Many Requests for url: https://circleci.com/api/v2/insights", False),+ ]+ )+ def test_non_retryable_errors_match_only_permanent_failures(self, observed_error, should_match):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors) is should_match++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.source.validate_circleci_insights_credentials"+ )+ def test_validate_credentials_plumbs_token_and_slugs(self, mock_validate):+ mock_validate.return_value = (True, None)++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_validate.assert_called_once_with(self.config.api_token, self.config.project_slugs)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CircleciInsightsResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.source.circleci_insights_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "workflow_runs"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = datetime(2026, 7, 1, tzinfo=UTC)+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "circle-token"+ assert kwargs["project_slugs_raw"] == self.config.project_slugs+ assert kwargs["endpoint"] == "workflow_runs"+ assert kwargs["reporting_window"] == "last-90-days"+ assert kwargs["all_branches"] is True+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == datetime(2026, 7, 1, tzinfo=UTC)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.circleci_insights.source.circleci_insights_source"+ )+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "workflow_runs"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = datetime(2026, 7, 1, tzinfo=UTC)++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex c862e93e9e54..14fbbc629467 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -867,7 +867,12 @@ class CircleCISourceConfig(config.Config):@config.configclass CircleciInsightsSourceConfig(config.Config):- pass+ api_token: str+ project_slugs: str+ reporting_window: Literal["last-24-hours", "last-7-days", "last-30-days", "last-60-days", "last-90-days"] | None = (+ config.value(default="last-90-days")+ )+ branch_scope: Literal["default_branch", "all_branches"] | None = config.value(default="default_branch")@config.config