Skip to content

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

feat(circleci-insights): add the four remaining insights tables (#102939)

Tom Owers6adaeb75bc01
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b77df3881ba2..fb74b61efa4d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1503,17 +1503,17 @@ The current v2 spec has no artifacts or test-metadata endpoints (those lived in
## CircleciInsights — gaps
-Today (5): `flaky_tests`, `job_metrics`, `org_summary_metrics`, `workflow_metrics`, `workflow_runs`
+Today (9): `branches`, `flaky_tests`, `job_metrics`, `job_timeseries`, `org_summary_metrics`, `workflow_metrics`, `workflow_runs`, `workflow_summary`, `workflow_test_metrics`
Diffed against: <https://circleci.com/api/v2/openapi.json>
-- [ ] `insights/{project-slug}/workflows/{workflow-name}/test-metrics` — per-test duration and failure metrics - the main test-health breakdown beyond flaky tests (high)
-- [ ] `insights/time-series/{project-slug}/workflows/{workflow-name}/jobs` — granular job timeseries, the only source of point-in-time job trends rather than window aggregates (high)
-- [ ] `insights/{project-slug}/branches` — branch dimension lookup for slicing every other insights metric (medium)
-- [ ] `insights/{project-slug}/workflows/{workflow-name}/summary` — workflow summary with trend deltas, complements the raw workflow metrics (medium)
+- [x] `insights/{project-slug}/workflows/{workflow-name}/test-metrics` — per-test duration and failure metrics - the main test-health breakdown beyond flaky tests (high)
+- [x] `insights/time-series/{project-slug}/workflows/{workflow-name}/jobs` — granular job timeseries, the only source of point-in-time job trends rather than window aggregates (high)
+- [x] `insights/{project-slug}/branches` — branch dimension lookup for slicing every other insights metric (medium)
+- [x] `insights/{project-slug}/workflows/{workflow-name}/summary` — workflow summary with trend deltas, complements the raw workflow metrics (medium)
- [ ] `insights/pages/{project-slug}/summary` — project-level workflow rollup used by the Insights UI landing page (low)
-Note: All five Insights tables map cleanly onto spec paths; the gaps are the remaining Insights operations in the same spec.
+Note: All nine Insights tables map cleanly onto spec paths; the gap is the remaining Insights operation in the same spec.
## CiscoDuo — gaps
diff --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.py
index a26f6a5c3265..30f5bf780029 100644
--- 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.py
@@ -15,6 +15,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"project_slug": "The project slug (vcs/org/repo) the workflow belongs to, as configured on the source.",
},
},
+ "workflow_summary": {
+ "description": "Summary metrics for each workflow in a project, with the trend for each metric against the previous window. Complements workflow_metrics, which carries the raw aggregates without trends.",
+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getProjectWorkflowsPageData",
+ "columns": {
+ "workflow_name": "The name of the workflow the summary describes.",
+ "project_slug": "The project slug (vcs/org/repo) the workflow belongs to, as configured on the source.",
+ "metrics": "Metrics for the workflow over the summary window: total/successful/failed/completed runs, success rate, duration percentiles (min, mean, median, p95, max, standard deviation), total credits used, MTTR, throughput, and the window bounds.",
+ "trends": "The change in each metric against the previous window, as a ratio: total runs, failed runs, success rate, p95 and median duration, total credits used, MTTR, and throughput.",
+ },
+ },
"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",
@@ -43,6 +53,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"project_slug": "The project slug (vcs/org/repo) the job belongs to, as configured on the source.",
},
},
+ "job_timeseries": {
+ "description": "Daily timeseries of metrics for each job in a workflow, giving point-in-time job trends rather than a single window aggregate. Daily buckets are retained for roughly 90 days. The endpoint has no all-branches option, so these rows cover the project's default branch even when the source is set to all branches.",
+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getJobTimeseries",
+ "columns": {
+ "name": "The name of the job the bucket describes.",
+ "timestamp": "The start of the interval the metrics were aggregated over.",
+ "min_started_at": "The start time of the earliest job run in the interval.",
+ "max_ended_at": "The end time of the latest job run in the interval.",
+ "metrics": "Metrics for the job over the interval: total/successful/failed runs, throughput, median and total credits used, and duration metrics (min, median, max, p95, total).",
+ "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",
@@ -62,6 +85,33 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"project_slug": "The project slug (vcs/org/repo) the flaky test belongs to, as configured on the source.",
},
},
+ "workflow_test_metrics": {
+ "description": "Per-test duration and failure metrics for a workflow, covering the tests CircleCI reports as most failed and slowest. Calculated from the workflow's 10 most recent runs, so this is a snapshot rather than a history.",
+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getProjectWorkflowTestMetrics",
+ "columns": {
+ "test_name": "The name of the test.",
+ "classname": "The class or suite the test belongs to.",
+ "file": "The source file of the test, when reported.",
+ "source": "The source of the test result, as reported by the test runner.",
+ "job_name": "The name of the job the test runs in.",
+ "total_runs": "How many times the test ran across the runs the metrics cover.",
+ "failed_runs": "How many of those runs the test failed in.",
+ "p95_duration": "The 95th percentile duration of the test, in seconds.",
+ "flaky": "Whether CircleCI has detected the test as flaky.",
+ "workflow_name": "The name of the workflow the test runs in.",
+ "project_slug": "The project slug (vcs/org/repo) the test belongs to, as configured on the source.",
+ },
+ },
+ "branches": {
+ "description": "The branches Insights holds data for in a project, as a dimension for slicing the other Insights tables by branch. The API returns at most 5,000 branches per project.",
+ "docs_url": "https://circleci.com/docs/api/v2/index.html#operation/getAllInsightsBranches",
+ "columns": {
+ "branch": "The name of the VCS branch.",
+ "org_id": "The unique ID of the organization the project belongs to.",
+ "project_id": "The unique ID of the project the branch belongs to.",
+ "project_slug": "The project slug (vcs/org/repo) the branch 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",
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.py
index ec73d4a5cffb..219749b40af8 100644
--- 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.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_i
CIRCLECI_INSIGHTS_ENDPOINTS,
DEFAULT_REPORTING_WINDOW,
REPORTING_WINDOWS,
+ CircleciInsightsEndpointConfig,
)
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
@@ -22,10 +23,12 @@ 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.
+# Aggregate listings are one row per workflow/job name so stay tiny; the row-level listings 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
+MAX_ROW_PAGES_PER_WORKFLOW = 500
+# Endpoints whose rows are individual runs or interval buckets rather than one aggregate per name.
+ROW_LEVEL_FAN_OUT_ENDPOINTS = ("workflow_runs", "job_timeseries")
# CircleCI rate-limits per token (not officially documented); 429s carry RateLimit-* headers
# we honor before retrying.
MAX_RATE_LIMIT_SLEEP_SECONDS = 120
@@ -133,6 +136,16 @@ def _format_start_date(value: Any) -> str | None:
return None
+def _format_start_date_param(value: Any, needs_timestamp: bool) -> str | None:
+ """Format the incremental cursor for the `start-date` query param. Midnight UTC of the cursor
+ day re-reads the same watermark day as the date-only form, so the overlap the primary-key
+ merge dedupes is unchanged."""
+ start_date = _format_start_date(value)
+ if start_date is None or not needs_timestamp:
+ return start_date
+ return f"{start_date}T00:00:00Z"
+
+
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."""
@@ -256,6 +269,19 @@ def _branch_params(all_branches: bool) -> dict[str, Any]:
return {"all-branches": "true"} if all_branches else {}
+def _endpoint_params(
+ config: CircleciInsightsEndpointConfig,
+ window: str,
+ all_branches: bool,
+) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.extra_params)
+ if config.takes_branch_params:
+ params.update(_branch_params(all_branches))
+ if config.takes_reporting_window:
+ params["reporting-window"] = window
+ return params
+
+
def _discover_workflow_names(
fetch_page: FetchPageFn,
project_slug: str,
@@ -329,7 +355,7 @@ def get_rows(
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"):
+ elif endpoint in ("workflow_runs", "job_metrics", "job_timeseries"):
yield from _project_workflow_fan_out_rows(
fetch_page,
slug,
@@ -342,8 +368,14 @@ def get_rows(
should_use_incremental_field,
db_incremental_field_last_value,
)
+ elif endpoint in ("workflow_summary", "workflow_test_metrics"):
+ yield from _project_workflow_object_fan_out_rows(
+ fetch_page, slug, endpoint, window, all_branches, logger, resumable_source_manager, slug_resume
+ )
elif endpoint == "flaky_tests":
yield from _project_flaky_tests_rows(fetch_page, slug, logger)
+ elif endpoint == "branches":
+ yield from _project_branches_rows(fetch_page, slug, logger)
elif endpoint == "org_summary_metrics":
yield from _org_summary_rows(fetch_page, slug, window, logger)
@@ -364,7 +396,7 @@ def _project_workflow_metrics_rows(
for items, next_token in _iter_pages(
fetch_page,
f"/insights/{quote(project_slug, safe='/')}/workflows",
- {"reporting-window": window, **_branch_params(all_branches)},
+ _endpoint_params(CIRCLECI_INSIGHTS_ENDPOINTS["workflow_metrics"], window, all_branches),
logger,
max_pages=MAX_METRIC_PAGES,
resource=f"workflow metrics for {project_slug}",
@@ -395,17 +427,22 @@ def _project_workflow_fan_out_rows(
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)
+ params: dict[str, Any] = _endpoint_params(config, window, all_branches)
+ if all_branches and not config.takes_branch_params:
+ # The endpoint takes a single `branch` name but no `all-branches`, and CircleCI scopes an
+ # omitted branch to the default one, so the branch setting cannot reach these rows.
+ logger.warning(
+ f"CircleCI Insights: {endpoint} has no all-branches param, so its rows cover the "
+ f"default branch only. project={project_slug}"
+ )
+ if config.takes_start_date and should_use_incremental_field:
+ start_date = _format_start_date_param(db_incremental_field_last_value, config.start_date_needs_timestamp)
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).
+ # Server-side filter: every page only returns rows dated 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
+ max_pages = MAX_ROW_PAGES_PER_WORKFLOW if endpoint in ROW_LEVEL_FAN_OUT_ENDPOINTS 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:
@@ -441,6 +478,74 @@ def _project_workflow_fan_out_rows(
)
+def _workflow_summary_row(data: dict[str, Any], project_slug: str, workflow_name: str) -> dict[str, Any]:
+ # `workflow_names` in the response lists every workflow in the project, so it describes the
+ # project rather than this row and is dropped.
+ return {
+ "project_slug": project_slug,
+ "workflow_name": workflow_name,
+ "metrics": data.get("metrics"),
+ "trends": data.get("trends"),
+ }
+
+
+def _workflow_test_metrics_rows(data: dict[str, Any], project_slug: str, workflow_name: str) -> list[dict[str, Any]]:
+ """Flatten the test-metrics response into one row per test. The API reports the same row shape
+ under both `most_failed_tests` and `slowest_tests`, and a test can appear in both, so the lists
+ are merged on test identity — the delta merge only dedupes across syncs, not within a batch."""
+ rows: dict[tuple[Any, ...], dict[str, Any]] = {}
+ for key in ("most_failed_tests", "slowest_tests"):
+ for item in data.get(key) or []:
+ if not isinstance(item, dict):
+ continue
+ identity = (item.get("job_name"), item.get("classname"), item.get("test_name"))
+ rows.setdefault(identity, {**item, "project_slug": project_slug, "workflow_name": workflow_name})
+ return list(rows.values())
+
+
+def _project_workflow_object_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,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over a project's workflows for endpoints that return a single object per workflow
+ instead of a paginated listing, so resume granularity is one workflow."""
+ config = CIRCLECI_INSIGHTS_ENDPOINTS[endpoint]
+ workflow_names = _discover_workflow_names(fetch_page, project_slug, all_branches, logger)
+ params = _endpoint_params(config, window, all_branches)
+
+ 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:
+ if resume_workflow is not None:
+ if workflow_name != resume_workflow:
+ # Workflows before the resume point were fully synced before the interruption.
+ continue
+ resume_workflow = None
+
+ path = config.path.format(slug=quote(project_slug, safe="/"), workflow_name=quote(workflow_name, safe=""))
+ data = fetch_page(_build_url(path, params))
+
+ if endpoint == "workflow_summary":
+ rows = [_workflow_summary_row(data, project_slug, workflow_name)]
+ else:
+ rows = _workflow_test_metrics_rows(data, project_slug, workflow_name)
+
+ if rows:
+ yield rows
+ resumable_source_manager.save_state(
+ CircleciInsightsResumeConfig(slug=project_slug, workflow_name=workflow_name)
+ )
+
+
def _project_flaky_tests_rows(
fetch_page: FetchPageFn,
project_slug: str,
@@ -452,6 +557,32 @@ def _project_flaky_tests_rows(
yield [{**item, "project_slug": project_slug} for item in flaky_tests]
+def _project_branches_rows(
+ fetch_page: FetchPageFn,
+ project_slug: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ # The response is a bare list of branch names alongside the org and project ids, so each
+ # name becomes a row carrying those ids as the dimension's attributes.
+ data = fetch_page(_build_url(f"/insights/{quote(project_slug, safe='/')}/branches"))
+ branches = data.get("branches")
+ if not isinstance(branches, list):
+ logger.warning(f"CircleCI Insights: unexpected branches response shape for {project_slug}, syncing zero rows")
+ return
+ rows = [
+ {
+ "project_slug": project_slug,
+ "branch": branch,
+ "org_id": data.get("org_id"),
+ "project_id": data.get("project_id"),
+ }
+ for branch in branches
+ if isinstance(branch, str) and branch
+ ]
+ if rows:
+ yield rows
+
+
def _org_summary_rows(
fetch_page: FetchPageFn,
org_slug: str,
@@ -499,9 +630,7 @@ def circleci_insights_source(
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",
+ sort_mode=config.sort_mode,
partition_count=1 if partition_key else None,
partition_size=1 if partition_key else None,
partition_mode="datetime" 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.py
index 44844a052689..e29bc92ac637 100644
--- 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.py
@@ -1,6 +1,9 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Reporting windows the Insights aggregate endpoints accept. CircleCI retains Insights data
@@ -15,7 +18,7 @@ REPORTING_WINDOWS = (
DEFAULT_REPORTING_WINDOW = "last-90-days"
-@dataclass
+@frozen
class CircleciInsightsEndpointConfig:
name: str
# Path template relative to the API base; {slug} is the project slug (or org slug for
@@ -24,7 +27,7 @@ class CircleciInsightsEndpointConfig:
# 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;
+ # Stable timestamp field for datetime partitioning. Only the row-level tables 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)
@@ -36,8 +39,19 @@ class CircleciInsightsEndpointConfig:
# 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).
+ # Whether the endpoint accepts branch filtering (the branch / all-branches params). Note the
+ # time-series endpoints take a single `branch` name but no `all-branches`, so they stay off.
takes_branch_params: bool = False
+ # Whether the endpoint accepts the server-side `start-date` filter used for incremental sync.
+ takes_start_date: bool = False
+ # Whether `start-date` needs the full RFC 3339 timestamp. The runs endpoint accepts the
+ # date-only form; the time-series endpoint is only documented for a timestamp.
+ start_date_needs_timestamp: bool = False
+ # Fixed query params the endpoint always needs.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Row order the API returns. The row-level listings declare desc, which defers the
+ # incremental watermark commit to the end of the sync — see the per-endpoint comments.
+ sort_mode: SortMode = "asc"
should_sync_default: bool = True
@@ -49,6 +63,13 @@ CIRCLECI_INSIGHTS_ENDPOINTS: dict[str, CircleciInsightsEndpointConfig] = {
takes_reporting_window=True,
takes_branch_params=True,
),
+ "workflow_summary": CircleciInsightsEndpointConfig(
+ name="workflow_summary",
+ path="/insights/{slug}/workflows/{workflow_name}/summary",
+ primary_keys=["project_slug", "workflow_name"],
+ fan_out_workflows=True,
+ takes_branch_params=True,
+ ),
"workflow_runs": CircleciInsightsEndpointConfig(
name="workflow_runs",
path="/insights/{slug}/workflows/{workflow_name}",
@@ -68,6 +89,8 @@ CIRCLECI_INSIGHTS_ENDPOINTS: dict[str, CircleciInsightsEndpointConfig] = {
],
fan_out_workflows=True,
takes_branch_params=True,
+ takes_start_date=True,
+ sort_mode="desc",
),
"job_metrics": CircleciInsightsEndpointConfig(
name="job_metrics",
@@ -77,6 +100,32 @@ CIRCLECI_INSIGHTS_ENDPOINTS: dict[str, CircleciInsightsEndpointConfig] = {
takes_reporting_window=True,
takes_branch_params=True,
),
+ "job_timeseries": CircleciInsightsEndpointConfig(
+ name="job_timeseries",
+ path="/insights/time-series/{slug}/workflows/{workflow_name}/jobs",
+ # One bucket per job per interval, so the interval timestamp is part of the row identity.
+ primary_keys=["project_slug", "workflow_name", "name", "timestamp"],
+ partition_key="timestamp",
+ # The endpoint takes a server-side `start-date` filter, so incremental sync genuinely
+ # narrows what is fetched. The bucket timestamp never moves once emitted.
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ],
+ fan_out_workflows=True,
+ takes_start_date=True,
+ start_date_needs_timestamp=True,
+ # Hourly buckets are only retained for 48 hours, which a scheduled sync cannot rely on;
+ # daily buckets match the ~90-day retention the rest of the source works against.
+ extra_params={"granularity": "daily"},
+ # The endpoint documents no row order. Desc defers the watermark commit to the end of the
+ # sync, which is correct whichever order the API returns.
+ sort_mode="desc",
+ ),
"flaky_tests": CircleciInsightsEndpointConfig(
name="flaky_tests",
path="/insights/{slug}/flaky-tests",
@@ -84,6 +133,20 @@ CIRCLECI_INSIGHTS_ENDPOINTS: dict[str, CircleciInsightsEndpointConfig] = {
# classname + test_name, neither of which is unique on its own.
primary_keys=["project_slug", "workflow_name", "job_name", "classname", "test_name"],
),
+ "workflow_test_metrics": CircleciInsightsEndpointConfig(
+ name="workflow_test_metrics",
+ path="/insights/{slug}/workflows/{workflow_name}/test-metrics",
+ # A test is reported per job it runs in, and neither classname nor test name is unique
+ # on its own.
+ primary_keys=["project_slug", "workflow_name", "job_name", "classname", "test_name"],
+ fan_out_workflows=True,
+ takes_branch_params=True,
+ ),
+ "branches": CircleciInsightsEndpointConfig(
+ name="branches",
+ path="/insights/{slug}/branches",
+ primary_keys=["project_slug", "branch"],
+ ),
"org_summary_metrics": CircleciInsightsEndpointConfig(
name="org_summary_metrics",
path="/insights/{slug}/summary",
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.py
index e497d8c1992a..45e106096e37 100644
--- 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.py
@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.circleci_i
CircleciInsightsResumeConfig,
CircleciInsightsRetryableError,
_format_start_date,
+ _format_start_date_param,
circleci_insights_source,
get_rows,
org_slugs_from_projects,
@@ -101,6 +102,16 @@ class TestFormatStartDate:
def test_formats_as_date_only(self, value, expected):
assert _format_start_date(value) == expected
+ @parameterized.expand(
+ [
+ (datetime(2026, 7, 1, 13, 30, tzinfo=UTC), False, "2026-07-01"),
+ (datetime(2026, 7, 1, 13, 30, tzinfo=UTC), True, "2026-07-01T00:00:00Z"),
+ (None, True, None),
+ ]
+ )
+ def test_timestamp_form_keeps_the_same_watermark_day(self, value, needs_timestamp, expected):
+ assert _format_start_date_param(value, needs_timestamp) == expected
+
class TestValidateCredentials:
@mock.patch(PATCH_SESSION)
@@ -423,6 +434,212 @@ class TestJobMetricsFanOut:
assert parse_qs(urlparse(jobs_url).query)["reporting-window"] == ["last-30-days"]
+class TestJobTimeseriesFanOut:
+ @mock.patch(PATCH_SESSION)
+ def test_buckets_carry_parents_and_request_daily_granularity(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),
+ "/api/v2/insights/time-series/gh/a/one/workflows/ci/jobs": _page(
+ [
+ {"name": "build", "timestamp": "2026-07-01T00:00:00Z"},
+ {"name": "test", "timestamp": "2026-07-01T00:00:00Z"},
+ ],
+ None,
+ ),
+ },
+ )
+
+ batches = list(get_rows("token", "gh/a/one", "job_timeseries", mock.MagicMock(), _make_manager()))
+ rows = _rows(batches)
+
+ assert [(row["project_slug"], row["workflow_name"], row["name"], row["timestamp"]) for row in rows] == [
+ ("gh/a/one", "ci", "build", "2026-07-01T00:00:00Z"),
+ ("gh/a/one", "ci", "test", "2026-07-01T00:00:00Z"),
+ ]
+ timeseries_url = next(url for url in _requested_urls(mock_session) if "time-series" in url)
+ query = parse_qs(urlparse(timeseries_url).query)
+ # Hourly buckets are only retained for 48 hours, so a scheduled sync must ask for daily.
+ assert query["granularity"] == ["daily"]
+ assert "reporting-window" not in query
+
+ @mock.patch(PATCH_SESSION)
+ def test_all_branches_widens_discovery_but_not_the_timeseries_request(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),
+ "/api/v2/insights/time-series/gh/a/one/workflows/ci/jobs": _page([], None),
+ },
+ )
+
+ logger = mock.MagicMock()
+ list(get_rows("token", "gh/a/one", "job_timeseries", logger, _make_manager(), all_branches=True))
+
+ urls = _requested_urls(mock_session)
+ assert parse_qs(urlparse(urls[0]).query)["all-branches"] == ["true"]
+ assert "all-branches" not in parse_qs(urlparse(urls[1]).query)
+ # The setting silently cannot reach these rows, so the sync log has to say so.
+ assert "default branch only" in logger.warning.call_args.args[0]
+
+ @parameterized.expand([(True, ["2026-07-01T00:00:00Z"]), (False, None)])
+ @mock.patch(PATCH_SESSION)
+ def test_start_date_sent_only_on_incremental(self, incremental, expected, mock_session):
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),
+ "/api/v2/insights/time-series/gh/a/one/workflows/ci/jobs": _page([], None),
+ },
+ )
+
+ list(
+ get_rows(
+ "token",
+ "gh/a/one",
+ "job_timeseries",
+ mock.MagicMock(),
+ _make_manager(),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=datetime(2026, 7, 1, 12, 0, tzinfo=UTC),
+ )
+ )
+
+ query = parse_qs(urlparse(_requested_urls(mock_session)[1]).query)
+ assert query.get("start-date") == expected
+
+
+class TestWorkflowSummaryFanOut:
+ @mock.patch(PATCH_SESSION)
+ def test_one_row_per_workflow_keeping_metrics_and_trends(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/summary": {
+ "metrics": {"total_runs": 10},
+ "trends": {"total_runs": 1.5},
+ "workflow_names": ["ci", "release"],
+ },
+ "/api/v2/insights/gh/a/one/workflows/release/summary": {
+ "metrics": {"total_runs": 2},
+ "trends": {"total_runs": 0.5},
+ "workflow_names": ["ci", "release"],
+ },
+ },
+ )
+
+ batches = list(get_rows("token", "gh/a/one", "workflow_summary", mock.MagicMock(), _make_manager()))
+
+ # workflow_names describes the project rather than the row, so it is dropped.
+ assert _rows(batches) == [
+ {
+ "project_slug": "gh/a/one",
+ "workflow_name": "ci",
+ "metrics": {"total_runs": 10},
+ "trends": {"total_runs": 1.5},
+ },
+ {
+ "project_slug": "gh/a/one",
+ "workflow_name": "release",
+ "metrics": {"total_runs": 2},
+ "trends": {"total_runs": 0.5},
+ },
+ ]
+
+ @mock.patch(PATCH_SESSION)
+ def test_state_saved_per_workflow_and_resume_skips_earlier_ones(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/summary": {"metrics": {}, "trends": {}},
+ "/api/v2/insights/gh/a/one/workflows/deploy/summary": {"metrics": {}, "trends": {}},
+ },
+ )
+
+ manager = _make_manager(CircleciInsightsResumeConfig(slug="gh/a/one", workflow_name="release"))
+ batches = list(get_rows("token", "gh/a/one", "workflow_summary", mock.MagicMock(), manager))
+
+ assert [row["workflow_name"] for row in _rows(batches)] == ["release", "deploy"]
+ assert all("/workflows/ci/summary" not in url for url in _requested_urls(mock_session))
+ saved_workflows = [call.args[0].workflow_name for call in manager.save_state.call_args_list]
+ assert saved_workflows[:2] == ["release", "deploy"]
+
+
+class TestWorkflowTestMetricsFanOut:
+ @mock.patch(PATCH_SESSION)
+ def test_merges_the_two_test_lists_on_test_identity(self, mock_session):
+ shared = {"job_name": "test", "classname": "suite.A", "test_name": "t1", "failed_runs": 4, "p95_duration": 9.0}
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/insights/gh/a/one/workflows": _page([{"name": "ci"}], None),
+ "/api/v2/insights/gh/a/one/workflows/ci/test-metrics": {
+ "average_test_count": 12,
+ "most_failed_tests": [shared],
+ "slowest_tests": [
+ shared,
+ {"job_name": "test", "classname": "suite.B", "test_name": "t2", "p95_duration": 30.0},
+ ],
+ },
+ },
+ )
+
+ batches = list(get_rows("token", "gh/a/one", "workflow_test_metrics", mock.MagicMock(), _make_manager()))
+ rows = _rows(batches)
+
+ # The same test appears in both lists; the delta merge only dedupes across syncs, so a
+ # duplicate here would seed duplicate rows under the composite primary key.
+ assert [(row["classname"], row["test_name"]) for row in rows] == [("suite.A", "t1"), ("suite.B", "t2")]
+ assert all(row["project_slug"] == "gh/a/one" and row["workflow_name"] == "ci" for row in rows)
+
+ @mock.patch(PATCH_SESSION)
+ def test_no_tests_reported_yields_nothing(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/test-metrics": {"average_test_count": 0},
+ },
+ )
+
+ assert list(get_rows("token", "gh/a/one", "workflow_test_metrics", mock.MagicMock(), _make_manager())) == []
+
+
+class TestBranchesRows:
+ @mock.patch(PATCH_SESSION)
+ def test_branch_names_become_rows_with_project_identifiers(self, mock_session):
+ _route_session(
+ mock_session,
+ {
+ "/api/v2/insights/gh/a/one/branches": {
+ "org_id": "org-1",
+ "project_id": "proj-1",
+ "branches": ["master", "feature/x", "", None],
+ }
+ },
+ )
+
+ batches = list(get_rows("token", "gh/a/one", "branches", mock.MagicMock(), _make_manager()))
+
+ assert _rows(batches) == [
+ {"project_slug": "gh/a/one", "branch": "master", "org_id": "org-1", "project_id": "proj-1"},
+ {"project_slug": "gh/a/one", "branch": "feature/x", "org_id": "org-1", "project_id": "proj-1"},
+ ]
+
+ @mock.patch(PATCH_SESSION)
+ def test_unexpected_shape_syncs_zero_rows(self, mock_session):
+ _route_session(mock_session, {"/api/v2/insights/gh/a/one/branches": {"message": "no insights"}})
+ logger = mock.MagicMock()
+
+ assert list(get_rows("token", "gh/a/one", "branches", logger, _make_manager())) == []
+ logger.warning.assert_called_once()
+
+
class TestFlakyTestsRows:
@mock.patch(PATCH_SESSION)
def test_unwraps_envelope_and_injects_project_slug(self, mock_session):
@@ -573,8 +790,9 @@ class TestCircleciInsightsSourceResponse:
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())
+ @parameterized.expand([("workflow_runs",), ("job_timeseries",)])
+ def test_row_level_endpoints_declare_desc_sort(self, endpoint):
+ # These are the incremental endpoints. Desc defers the watermark commit to the end of
+ # the sync; asc would checkpoint per batch, which fan-out over workflows makes unsafe.
+ response = circleci_insights_source("token", "gh/a/one", endpoint, 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.py
index c35567091848..80773139b362 100644
--- 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.py
@@ -38,12 +38,13 @@ class TestCircleciInsightsSource:
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):
+ def test_only_start_date_endpoints_advertise_incremental(self, endpoint):
schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
- expected = endpoint == "workflow_runs"
+ expected = endpoint in ("workflow_runs", "job_timeseries")
- # Only the runs endpoint has a server-side timestamp filter (start-date); the
- # aggregate endpoints are rolling-window snapshots and stay full refresh.
+ # Only the endpoints with a server-side timestamp filter (start-date) can sync
+ # incrementally; 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