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(buildkite): sync jobs, teams and test engine tables (#100165)

Tom Owers3f0804e43969
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 66b68b8dc8c3..f618c2944c0b 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
@@ -1066,14 +1066,15 @@ Note: PostHog's registered api_docs_url (https://docs.buildbetter.app/) no longe
## Buildkite — gaps
-Today (4): `agents`, `builds`, `organizations`, `pipelines`
+Today (9): `agents`, `builds`, `jobs`, `organizations`, `pipelines`, `teams`, `test_suite_runs`, `test_suite_tests`, `test_suites`
Diffed against: <https://buildkite.com/docs/llms.txt>
-- [ ] `builds/{number}/jobs` — job-level duration, state, and retry data is the real analytical grain of CI cost and flakiness; builds alone hide it (high)
-- [ ] `analytics/organizations/{org}/suites/{suite}/runs (Test Engine runs)` — test suite run history is Buildkite's headline Test Engine metric and has no equivalent in the current tables (high)
-- [ ] `analytics/organizations/{org}/suites/{suite}/tests (Test Engine tests, label=flaky)` — per-test pass/fail and flaky labelling — the core use case for anyone importing CI data (high)
-- [ ] `organizations/{org}/teams` — lookup table resolving team ownership of the pipelines we already sync (high)
+- [x] `builds/{number}/jobs` — job-level duration, state, and retry data is the real analytical grain of CI cost and flakiness; builds alone hide it (high)
+- [x] `analytics/organizations/{org}/suites/{suite}/runs (Test Engine runs)` — test suite run history is Buildkite's headline Test Engine metric and has no equivalent in the current tables (high)
+- [x] `analytics/organizations/{org}/suites/{suite}/tests (Test Engine tests, label=flaky)` — per-test pass/fail and flaky labelling — the core use case for anyone importing CI data (high)
+- [x] `analytics/organizations/{org}/suites` — the suite list the two Test Engine child tables fan out over, and a lookup in its own right (high)
+- [x] `organizations/{org}/teams` — lookup table resolving team ownership of the pipelines we already sync (high)
- [ ] `organizations/{org}/teams/{team}/pipelines` — membership table joining teams to pipelines, needed to attribute build cost per team (high)
- [ ] `organizations/{org}/members` — lookup resolving the user IDs that appear as build creators and job agents (high)
- [ ] `organizations/{org}/clusters/{cluster}/queues` — lookup resolving the queue an agent or job ran on — required for agent capacity and cost analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/buildkite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/buildkite.py
index 9204c42422a0..c8019925184b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/buildkite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/buildkite.py
@@ -1,6 +1,7 @@
-import dataclasses
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.buildkite.settings import (
BUILDKITE_ENDPOINTS,
@@ -9,10 +10,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildkite.
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.rest_source import (
RESTAPIConfig,
- rest_api_resource,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
HeaderLinkPaginator,
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
@@ -22,10 +32,17 @@ BUILDKITE_BASE_URL = "https://api.buildkite.com"
# Buildkite caps per_page at 100 (default 30).
PAGE_SIZE = 100
+# Test Engine suites are the fan-out parent for both Test Engine child tables.
+SUITE_CHILD_ENDPOINTS = ("test_suite_runs", "test_suite_tests")
+
+@frozen
class BuildkiteResumeConfig:
- next_url: str
+ # Next-page link for a flat list endpoint. None means "start at the first page".
+ next_url: str | None = None
+ # Framework fan-out snapshot ({"completed": [...], "current": ..., "child_state": ...}) for the
+ # single-hop suites -> child fan-out.
+ fanout_state: dict[str, Any] | None = None
def _format_incremental_value(value: Any) -> str:
@@ -69,6 +86,172 @@ def _build_initial_params(
return params
+def _build_created_from(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> str | None:
+ """Window the parent build walk that drives the jobs fan-out.
+
+ Jobs have no time filter of their own, so the cursor a job row carries is its build's
+ creation time and the window is applied to the builds listing that produced it.
+ """
+ if not should_use_incremental_field or not db_incremental_field_last_value:
+ return None
+ return _format_incremental_value(db_incremental_field_last_value)
+
+
+def _client_config(api_access_token: str) -> ClientConfig:
+ return {
+ "base_url": BUILDKITE_BASE_URL,
+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted
+ # from logs; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_access_token},
+ # Buildkite paginates via an RFC 5988 Link header with rel="next".
+ "paginator": HeaderLinkPaginator(),
+ }
+
+
+def _bind_organization(path: str, organization: str) -> str:
+ # `str.format` would raise on the parent placeholders a fan-out child path still carries.
+ return path.replace("{organization}", organization)
+
+
+def _list_endpoint_resource(endpoint: str, organization: str, params: dict[str, Any]) -> EndpointResource:
+ return {
+ "name": endpoint,
+ "endpoint": {
+ "path": _bind_organization(BUILDKITE_ENDPOINTS[endpoint].path, organization),
+ "params": params,
+ # Buildkite list endpoints return a top-level JSON array; a non-list 200 body
+ # means the response shape changed — fail loud instead of syncing garbage.
+ "data_selector_required": True,
+ },
+ }
+
+
+def _test_suites_resource(organization: str) -> EndpointResource:
+ # The suites listing takes no page-size param — it returns the organization's whole suite list.
+ return _list_endpoint_resource("test_suites", organization, {})
+
+
+def _suite_child_resource(endpoint: str, organization: str) -> EndpointResource:
+ return {
+ "name": endpoint,
+ # Runs and tests are only identified within their suite, so carry the suite into the key.
+ "include_from_parent": ["id", "slug"],
+ "endpoint": {
+ "path": _bind_organization(BUILDKITE_ENDPOINTS[endpoint].path, organization),
+ "params": {
+ "suite_slug": {"type": "resolve", "resource": "test_suites", "field": "slug"},
+ "per_page": PAGE_SIZE,
+ },
+ "data_selector_required": True,
+ # A suite deleted between the listing and this fetch 404s; treat it as an empty page
+ # and move to the next suite rather than failing the whole sync.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ "data_map": rename_parent_fields("test_suites", {"id": "suite_id", "slug": "suite_slug"}),
+ }
+
+
+def _flatten_pipeline_slug(row: dict[str, Any]) -> dict[str, Any]:
+ # The jobs path needs the pipeline slug, which a build nests under `pipeline`; flatten it so
+ # both the path binding and include_from_parent can read it off the parent row.
+ pipeline = row.get("pipeline")
+ row["pipeline_slug"] = pipeline.get("slug") if isinstance(pipeline, dict) else None
+ return row
+
+
+def _builds_parent_resource(organization: str, created_from: str | None) -> EndpointResource:
+ params: dict[str, Any] = {"per_page": PAGE_SIZE}
+ if created_from is not None:
+ params["created_from"] = created_from
+ resource = _list_endpoint_resource("builds", organization, params)
+ resource["data_map"] = _flatten_pipeline_slug
+ return resource
+
+
+def _jobs_child_resource(organization: str) -> EndpointResource:
+ return {
+ "name": "jobs",
+ "include_from_parent": ["id", "number", "pipeline_slug", "created_at"],
+ "endpoint": {
+ "path": _bind_organization(BUILDKITE_ENDPOINTS["jobs"].path, organization),
+ "params": {
+ # Both path params bind fields of the same parent build row.
+ "pipeline_slug": {"type": "resolve", "resource": "builds", "field": "pipeline_slug"},
+ "build_number": {"type": "resolve", "resource": "builds", "field": "number"},
+ "per_page": PAGE_SIZE,
+ },
+ # Unlike the other list endpoints, jobs answers with an envelope and paginates on a
+ # cursor URL in the body rather than a Link header.
+ "data_selector": "items",
+ "data_selector_required": True,
+ "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ "data_map": rename_parent_fields(
+ "builds",
+ {
+ "id": "build_id",
+ "number": "build_number",
+ "pipeline_slug": "pipeline_slug",
+ "created_at": "build_created_at",
+ },
+ ),
+ }
+
+
+def _build_resource(
+ api_access_token: str,
+ endpoint: str,
+ resources: list[EndpointResource],
+ team_id: int,
+ job_id: str,
+ db_incremental_field_last_value: Optional[Any],
+ resumable_source_manager: Optional[ResumableSourceManager[BuildkiteResumeConfig]],
+) -> Resource:
+ """Build the resource chain for one endpoint, checkpointing unless resume is off.
+
+ A parent/child pair checkpoints the framework's fan-out snapshot, which skips parents already
+ synced on a restart and resumes the one in progress. A flat listing checkpoints its next-page
+ link. Either way the hook fires AFTER a page is yielded, so a crash re-yields the last page
+ (merge dedupes on the primary key) rather than skipping it.
+ """
+ fans_out = len(resources) > 1
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_access_token),
+ "resources": cast("list[str | EndpointResource]", resources),
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager is not None and resumable_source_manager.can_resume():
+ saved = resumable_source_manager.load_state()
+ if saved is not None:
+ initial_paginator_state = saved.fanout_state if fans_out else _next_url_state(saved.next_url)
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if not state or resumable_source_manager is None:
+ return
+ if fans_out:
+ resumable_source_manager.save_state(BuildkiteResumeConfig(fanout_state=state))
+ elif state.get("next_url"):
+ resumable_source_manager.save_state(BuildkiteResumeConfig(next_url=state["next_url"]))
+
+ built = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint if resumable_source_manager is not None else None,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return next(resource for resource in built if getattr(resource, "name", None) == endpoint)
+
+
+def _next_url_state(next_url: str | None) -> Optional[dict[str, Any]]:
+ return {"next_url": next_url} if next_url else None
+
+
def validate_credentials(
api_access_token: str, organization: str, schema_name: str | None = None
) -> tuple[bool, str | None]:
@@ -81,7 +264,7 @@ def validate_credentials(
"""
if schema_name and schema_name in BUILDKITE_ENDPOINTS:
config = BUILDKITE_ENDPOINTS[schema_name]
- path = config.path.format(organization=organization)
+ path = (config.probe_path or config.path).format(organization=organization)
url = f"{BUILDKITE_BASE_URL}{path}?per_page=1"
else:
url = f"{BUILDKITE_BASE_URL}/v2/organizations/{organization}"
@@ -119,56 +302,34 @@ def buildkite_source(
incremental_field: str | None = None,
) -> SourceResponse:
config = BUILDKITE_ENDPOINTS[endpoint]
+ manager: Optional[ResumableSourceManager[BuildkiteResumeConfig]] = resumable_source_manager
- params = _build_initial_params(
- config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
- )
-
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": BUILDKITE_BASE_URL,
- # Auth (Bearer) is supplied via the framework auth config so its value is redacted
- # from logs; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_access_token},
- # Buildkite paginates via an RFC 5988 Link header with rel="next".
- "paginator": HeaderLinkPaginator(),
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path.format(organization=organization),
- "params": params,
- # Buildkite list endpoints return a top-level JSON array; a non-list 200 body
- # means the response shape changed — fail loud instead of syncing garbage.
- "data_selector_required": True,
- },
- }
- ],
- }
-
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_paginator_state = {"next_url": resume.next_url}
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Persist only when a next page remains; the hook fires AFTER a page is yielded so a crash
- # re-yields the last page (merge dedupes on the primary key) rather than skipping it.
- if state and state.get("next_url"):
- resumable_source_manager.save_state(BuildkiteResumeConfig(next_url=state["next_url"]))
+ if endpoint in SUITE_CHILD_ENDPOINTS:
+ resources = [_test_suites_resource(organization), _suite_child_resource(endpoint, organization)]
+ elif endpoint == "jobs":
+ created_from = _build_created_from(should_use_incremental_field, db_incremental_field_last_value)
+ resources = [_builds_parent_resource(organization, created_from), _jobs_child_resource(organization)]
+ # Resume is deliberately off here: the framework rewrites the full set of completed child
+ # paths on every parent, which an organization's build list makes quadratic. A retry
+ # re-walks the window and merge dedupes on the job id.
+ manager = None
+ else:
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ resources = [_list_endpoint_resource(endpoint, organization, params)]
- resource = rest_api_resource(
- rest_config,
+ resource = _build_resource(
+ api_access_token,
+ endpoint,
+ resources,
team_id,
job_id,
db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ manager,
)
+ partition_key = config.partition_key
return SourceResponse(
name=endpoint,
items=lambda: resource,
@@ -176,7 +337,7 @@ def buildkite_source(
sort_mode=config.sort_mode,
partition_count=1,
partition_size=1,
- partition_mode="datetime" if config.partition_key else None,
- partition_format="week" if config.partition_key else None,
- partition_keys=[config.partition_key] if config.partition_key else None,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="week" 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/buildkite/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/canonical_descriptions.py
index c3a6aa2e77fb..ba0d77951dba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/canonical_descriptions.py
@@ -80,4 +80,107 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"meta_data": "Agent metadata tags used for targeting jobs.",
},
},
+ "jobs": {
+ "description": "A single job within a build — the unit an agent actually runs.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/jobs",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "type": "Kind of job (e.g. script, waiter, manual, trigger).",
+ "name": "Display name of the job.",
+ "step_key": "Key of the pipeline step that produced the job.",
+ "state": "Current state of the job (e.g. scheduled, running, passed, failed, canceled).",
+ "command": "Command the job ran.",
+ "soft_failed": "Whether the job failed but was configured not to fail the build.",
+ "exit_status": "Process exit status of the job, or null if it has not finished.",
+ "agent": "The agent that ran the job.",
+ "agent_query_rules": "Targeting rules used to pick an agent for the job.",
+ "web_url": "URL of the job in the Buildkite web UI.",
+ "log_url": "API URL for the job's log output.",
+ "artifacts_url": "API URL listing the job's artifacts.",
+ "created_at": "Time the job was created (ISO 8601).",
+ "scheduled_at": "Time the job was scheduled (ISO 8601).",
+ "runnable_at": "Time the job became runnable (ISO 8601).",
+ "started_at": "Time the job started running (ISO 8601).",
+ "finished_at": "Time the job finished, or null if still running (ISO 8601).",
+ "expired_at": "Time the job expired without running (ISO 8601).",
+ "concurrency_wait_time_ms": "Milliseconds spent waiting for a concurrency group slot.",
+ "retried": "Whether the job was retried.",
+ "retried_in_job_id": "Identifier of the job this one was retried into.",
+ "retries_count": "Number of times the job has been retried.",
+ "retry_source": "What requested the retry.",
+ "retry_type": "Whether the retry was automatic or manual.",
+ "parallel_group_index": "Index of this job within its parallel group.",
+ "parallel_group_total": "Total number of jobs in its parallel group.",
+ "matrix": "Matrix values the job was expanded with.",
+ "cluster_id": "Identifier of the cluster the job ran on.",
+ "cluster_queue_id": "Identifier of the cluster queue the job ran on.",
+ "build_id": "Identifier of the build the job belongs to.",
+ "build_number": "Number of the build the job belongs to.",
+ "build_created_at": "Time the parent build was created (ISO 8601).",
+ "pipeline_slug": "Slug of the pipeline the job's build ran for.",
+ },
+ },
+ "teams": {
+ "description": "A team within the organization, used to grant access to pipelines and suites.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/teams",
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Display name of the team.",
+ "slug": "URL-friendly identifier for the team within its organization.",
+ "description": "Human-readable description of the team.",
+ "privacy": "Whether the team is visible or secret.",
+ "default": "Whether new organization members join this team automatically.",
+ "created_at": "Time the team was created (ISO 8601).",
+ "created_by": "The user who created the team.",
+ },
+ },
+ "test_suites": {
+ "description": "A Test Engine suite collecting the test results uploaded for a project.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/test-engine/suites",
+ "columns": {
+ "id": "Unique identifier for the suite.",
+ "organization_id": "Identifier of the organization the suite belongs to.",
+ "slug": "URL-friendly identifier for the suite within its organization.",
+ "name": "Display name of the suite.",
+ "url": "API URL for the suite.",
+ "web_url": "URL of the suite in the Buildkite web UI.",
+ "default_branch": "Branch treated as the suite's baseline.",
+ "application_name": "Name of the application the suite covers.",
+ "color": "Display color of the suite.",
+ "emoji": "Display emoji of the suite.",
+ },
+ },
+ "test_suite_runs": {
+ "description": "One upload of test results to a Test Engine suite, usually one per CI build.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/test-engine/runs",
+ "columns": {
+ "id": "Unique identifier for the run.",
+ "branch": "Git branch the run covers.",
+ "commit_sha": "Git commit SHA the run covers.",
+ "state": "Whether the run is still receiving results or has finished.",
+ "result": "Outcome of the run (e.g. passed, failed).",
+ "url": "API URL for the run.",
+ "web_url": "URL of the run in the Buildkite web UI.",
+ "build_id": "Identifier of the build that uploaded the run.",
+ "created_at": "Time the run was created (ISO 8601).",
+ "suite_id": "Identifier of the suite the run belongs to.",
+ "suite_slug": "Slug of the suite the run belongs to.",
+ },
+ },
+ "test_suite_tests": {
+ "description": "An individual test tracked by a Test Engine suite, with the labels applied to it.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/test-engine/tests",
+ "columns": {
+ "id": "Unique identifier for the test.",
+ "url": "API URL for the test.",
+ "web_url": "URL of the test in the Buildkite web UI.",
+ "scope": "Grouping the test belongs to, such as its describe block or class.",
+ "name": "Name of the test.",
+ "location": "File and line the test is defined at.",
+ "file_name": "File the test is defined in.",
+ "labels": "Labels applied to the test, including 'flaky' for tests Buildkite detects as flaky.",
+ "suite_id": "Identifier of the suite the test belongs to.",
+ "suite_slug": "Slug of the suite the test belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/settings.py
index 34b5a3ba89e9..01560ca56b82 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/settings.py
@@ -1,14 +1,18 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@frozen
class BuildkiteEndpointConfig:
name: str
# Path template. ``{organization}`` is filled with the org slug from the source config.
- # Endpoints that aren't org-scoped (e.g. /v2/organizations) carry no placeholder.
+ # Endpoints that aren't org-scoped (e.g. /v2/organizations) carry no placeholder. A fan-out
+ # child keeps its parent placeholders (``{suite_slug}``, ``{pipeline_slug}``,
+ # ``{build_number}``) for the framework to bind per parent row.
path: str
incremental_fields: list[IncrementalField]
# Field used to partition the Delta table. Must be STABLE (set once at creation) — never
@@ -19,11 +23,19 @@ class BuildkiteEndpointConfig:
# Maps an incremental field name to the Buildkite query param that filters on it server-side.
# Only set for endpoints with a genuine server-side timestamp filter.
incremental_param_map: Optional[dict[str, str]] = None
+ # Path the credential probe hits for this endpoint. Fan-out children can't be probed directly
+ # (their path needs a parent row), so they point at the listing that carries the same scope.
+ probe_path: Optional[str] = None
+ # Rows restate after creation, so append would materialize each re-pulled row as a duplicate.
+ merge_only: bool = False
+ should_sync_default: bool = True
+ description: Optional[str] = None
-# Buildkite v2 REST API endpoints. Most resources are nested under an organization slug.
-# Only the builds endpoint exposes a server-side timestamp filter (created_from), so it is the
-# only one that supports incremental sync; the rest are full refresh.
+# Buildkite v2 REST API endpoints. Most resources are nested under an organization slug, and the
+# Test Engine resources live under the /v2/analytics prefix. Only the builds endpoint exposes a
+# server-side timestamp filter (created_from); jobs inherit it through their parent build fan-out,
+# and the rest are full refresh.
BUILDKITE_ENDPOINTS: dict[str, BuildkiteEndpointConfig] = {
"organizations": BuildkiteEndpointConfig(
name="organizations",
@@ -57,12 +69,69 @@ BUILDKITE_ENDPOINTS: dict[str, BuildkiteEndpointConfig] = {
sort_mode="desc",
incremental_param_map={"created_at": "created_from"},
),
+ "jobs": BuildkiteEndpointConfig(
+ name="jobs",
+ path="/v2/organizations/{organization}/pipelines/{pipeline_slug}/builds/{build_number}/jobs",
+ # Job ids are unique organization-wide — Buildkite serves a job by id alone at
+ # /v2/organizations/{org}/jobs/{job.id}, with no pipeline or build in the path.
+ primary_keys=["id"],
+ # Jobs carry no server-side time filter of their own, so the incremental window is applied
+ # to the parent build walk and each job row carries its build's creation time as the cursor.
+ # A job retried onto a build older than the watermark isn't re-fetched, the same trade-off
+ # the builds endpoint already makes.
+ partition_key="build_created_at",
+ incremental_fields=[
+ {
+ "label": "build_created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "build_created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ sort_mode="desc",
+ probe_path="/v2/organizations/{organization}/builds",
+ merge_only=True,
+ should_sync_default=False,
+ description=(
+ "Fetches the jobs of every build, at least one request per build. "
+ "Disabled by default because of the API cost"
+ ),
+ ),
"agents": BuildkiteEndpointConfig(
name="agents",
path="/v2/organizations/{organization}/agents",
partition_key="created_at",
incremental_fields=[],
),
+ "teams": BuildkiteEndpointConfig(
+ name="teams",
+ path="/v2/organizations/{organization}/teams",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "test_suites": BuildkiteEndpointConfig(
+ name="test_suites",
+ path="/v2/analytics/organizations/{organization}/suites",
+ # Suites expose no creation timestamp, so there is nothing stable to partition on.
+ incremental_fields=[],
+ ),
+ "test_suite_runs": BuildkiteEndpointConfig(
+ name="test_suite_runs",
+ path="/v2/analytics/organizations/{organization}/suites/{suite_slug}/runs",
+ primary_keys=["suite_slug", "id"],
+ partition_key="created_at",
+ # Runs come back newest-first per suite and the listing takes no time filter, only build_id.
+ sort_mode="desc",
+ incremental_fields=[],
+ probe_path="/v2/analytics/organizations/{organization}/suites",
+ ),
+ "test_suite_tests": BuildkiteEndpointConfig(
+ name="test_suite_tests",
+ path="/v2/analytics/organizations/{organization}/suites/{suite_slug}/tests",
+ primary_keys=["suite_slug", "id"],
+ incremental_fields=[],
+ probe_path="/v2/analytics/organizations/{organization}/suites",
+ ),
}
ENDPOINTS = tuple(BUILDKITE_ENDPOINTS.keys())
@@ -70,3 +139,13 @@ ENDPOINTS = tuple(BUILDKITE_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in BUILDKITE_ENDPOINTS.items()
}
+
+MERGE_ONLY: tuple[str, ...] = tuple(name for name, config in BUILDKITE_ENDPOINTS.items() if config.merge_only)
+
+SHOULD_SYNC_DEFAULT: dict[str, bool] = {
+ name: config.should_sync_default for name, config in BUILDKITE_ENDPOINTS.items()
+}
+
+DESCRIPTIONS: dict[str, str] = {
+ name: config.description for name, config in BUILDKITE_ENDPOINTS.items() if config.description
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/source.py
index fba98e7fd8ed..9844ce295ed1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/source.py
@@ -18,8 +18,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildkite.
CANONICAL_DESCRIPTIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.buildkite.settings import (
+ DESCRIPTIONS,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ MERGE_ONLY,
+ SHOULD_SYNC_DEFAULT,
)
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 (
@@ -72,6 +75,8 @@ Make sure to grant the following read scopes:
- `read_pipelines`
- `read_builds`
- `read_agents`
+- `read_teams`
+- `read_suites`
""",
iconPath="/static/services/buildkite.png",
fields=cast(
@@ -117,7 +122,14 @@ Make sure to grant the following read scopes:
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=MERGE_ONLY,
+ descriptions=DESCRIPTIONS,
+ should_sync_default=SHOULD_SYNC_DEFAULT,
+ )
def validate_credentials(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite.py
index 8a12ef8acd10..141b4781d197 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite.py
@@ -62,7 +62,7 @@ class TestBuildInitialParams:
)
assert params == {"per_page": 100}
- @parameterized.expand([("organizations",), ("pipelines",), ("agents",)])
+ @parameterized.expand([("organizations",), ("pipelines",), ("agents",), ("teams",), ("test_suites",)])
def test_full_refresh_endpoints_never_get_a_time_filter(self, endpoint: str) -> None:
# These endpoints expose no server-side timestamp filter, so an incremental request must
# not silently add one (it would be ignored by the API and misrepresent the sync).
@@ -259,20 +259,26 @@ class TestBuildkiteSourceResponse:
("pipelines", ["id"], "asc", "created_at"),
("builds", ["id"], "desc", "created_at"),
("agents", ["id"], "asc", "created_at"),
+ ("teams", ["id"], "asc", "created_at"),
+ ("jobs", ["id"], "desc", "build_created_at"),
+ ("test_suite_runs", ["suite_slug", "id"], "desc", "created_at"),
+ # Suites and tests expose no creation timestamp, so they are not partitioned.
+ ("test_suites", ["id"], "asc", None),
+ ("test_suite_tests", ["suite_slug", "id"], "asc", None),
]
)
@mock.patch(CLIENT_SESSION_PATCH)
def test_source_response_shape(
- self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_key: str, MockSession
+ self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_key: str | None, MockSession
) -> None:
MockSession.return_value.headers = {}
response = _source(endpoint, _make_manager())
assert response.name == endpoint
assert response.primary_keys == primary_keys
assert response.sort_mode == sort_mode
- assert response.partition_mode == "datetime"
- assert response.partition_format == "week"
- assert response.partition_keys == [partition_key]
+ assert response.partition_mode == ("datetime" if partition_key else None)
+ assert response.partition_format == ("week" if partition_key else None)
+ assert response.partition_keys == ([partition_key] if partition_key else None)
class TestValidateCredentials:
@@ -326,6 +332,21 @@ class TestValidateCredentials:
validate_credentials("bkua", "my-org", schema_name="agents")
assert captured["url"] == "https://api.buildkite.com/v2/organizations/my-org/agents?per_page=1"
+ @parameterized.expand([("test_suite_runs",), ("test_suite_tests",)])
+ @mock.patch(BUILDKITE_SESSION_PATCH)
+ def test_fanout_schema_probe_targets_the_parent_listing(self, endpoint: str, mock_session) -> None:
+ # A fan-out child's own path needs a parent row, so the probe hits the listing that
+ # carries the same scope. Formatting the child path here would raise on {suite_slug}.
+ captured = self._patch_get(mock_session, 200)
+ validate_credentials("bkua", "my-org", schema_name=endpoint)
+ assert captured["url"] == "https://api.buildkite.com/v2/analytics/organizations/my-org/suites?per_page=1"
+
+ @mock.patch(BUILDKITE_SESSION_PATCH)
+ def test_jobs_schema_probe_targets_the_builds_listing(self, mock_session) -> None:
+ captured = self._patch_get(mock_session, 200)
+ validate_credentials("bkua", "my-org", schema_name="jobs")
+ assert captured["url"] == "https://api.buildkite.com/v2/organizations/my-org/builds?per_page=1"
+
@mock.patch(BUILDKITE_SESSION_PATCH)
def test_source_create_probe_targets_org(self, mock_session) -> None:
captured = self._patch_get(mock_session, 200)
@@ -338,3 +359,165 @@ class TestValidateCredentials:
ok, error = validate_credentials("bkua", "my-org")
assert ok is False
assert error is not None
+
+
+class TestSuiteFanout:
+ @staticmethod
+ def _suites_page() -> Response:
+ return _response([{"id": "s1", "slug": "web"}, {"id": "s2", "slug": "api"}])
+
+ @parameterized.expand([("test_suite_runs", "runs"), ("test_suite_tests", "tests")])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_every_suite(self, endpoint: str, path_segment: str, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [self._suites_page(), _response([{"id": "a"}]), _response([{"id": "b"}])])
+
+ rows = _rows(_source(endpoint, _make_manager()))
+
+ base = "https://api.buildkite.com/v2/analytics/organizations/my-org/suites"
+ assert snapshots[0]["url"] == base
+ # The suites listing takes no page-size param; only the children are paginated.
+ assert snapshots[0]["params"] == {}
+ assert [s["url"] for s in snapshots[1:]] == [f"{base}/web/{path_segment}", f"{base}/api/{path_segment}"]
+ assert snapshots[1]["params"] == {"per_page": 100}
+ # Runs and tests are only identified within their suite, so the suite has to reach the row
+ # for the composite primary key to be unique table-wide.
+ assert [(r["id"], r["suite_id"], r["suite_slug"]) for r in rows] == [
+ ("a", "s1", "web"),
+ ("b", "s2", "api"),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_deleted_suite_does_not_fail_the_sync(self, MockSession) -> None:
+ session = MockSession.return_value
+ gone = Response()
+ gone.status_code = 404
+ gone._content = b'{"message": "Not Found"}'
+ _wire(session, [self._suites_page(), gone, _response([{"id": "b"}])])
+
+ rows = _rows(_source("test_suite_runs", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["b"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_and_resumes_the_fanout_snapshot(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [self._suites_page(), _response([{"id": "a"}]), _response([{"id": "b"}])])
+
+ manager = _make_manager()
+ _rows(_source("test_suite_runs", manager))
+
+ saved = [call.args[0].fanout_state for call in manager.save_state.call_args_list]
+ assert saved[-1]["completed"] == [
+ "/v2/analytics/organizations/my-org/suites/api/runs",
+ "/v2/analytics/organizations/my-org/suites/web/runs",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_suites_already_completed(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [self._suites_page(), _response([{"id": "b"}])])
+
+ resume = BuildkiteResumeConfig(
+ fanout_state={
+ "completed": ["/v2/analytics/organizations/my-org/suites/web/runs"],
+ "current": None,
+ "child_state": None,
+ }
+ )
+ rows = _rows(_source("test_suite_runs", _make_manager(resume)))
+
+ # The suite list is re-fetched each run; only the unfinished suite is fanned out again.
+ assert [s["url"] for s in snapshots[1:]] == [
+ "https://api.buildkite.com/v2/analytics/organizations/my-org/suites/api/runs"
+ ]
+ assert [r["id"] for r in rows] == ["b"]
+
+
+class TestJobsFanout:
+ @staticmethod
+ def _builds_page() -> Response:
+ return _response(
+ [{"id": "b1", "number": 42, "created_at": "2026-03-04T02:58:14Z", "pipeline": {"slug": "web"}}]
+ )
+
+ @staticmethod
+ def _jobs_page(job_ids: list[str], next_url: str | None = None) -> Response:
+ # The jobs endpoint answers with an envelope and paginates on a cursor URL in the body,
+ # unlike every other Buildkite list endpoint.
+ return _response({"items": [{"id": i} for i in job_ids], "links": {"next": next_url} if next_url else {}})
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_binds_both_path_params_from_one_build_row(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [self._builds_page(), self._jobs_page(["j1"])])
+
+ rows = _rows(_source("jobs", _make_manager()))
+
+ assert snapshots[0]["url"] == "https://api.buildkite.com/v2/organizations/my-org/builds"
+ # The pipeline slug is nested under `pipeline` on a build and has to be flattened before
+ # it can bind the path or reach the job row.
+ assert snapshots[1]["url"] == "https://api.buildkite.com/v2/organizations/my-org/pipelines/web/builds/42/jobs"
+ assert rows == [
+ {
+ "id": "j1",
+ "build_id": "b1",
+ "build_number": 42,
+ "build_created_at": "2026-03-04T02:58:14Z",
+ "pipeline_slug": "web",
+ }
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follows_the_body_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ page2 = "https://api.buildkite.com/v2/organizations/my-org/pipelines/web/builds/42/jobs?after=abc"
+ snapshots = _wire(
+ session, [self._builds_page(), self._jobs_page(["j1"], next_url=page2), self._jobs_page(["j2"])]
+ )
+
+ rows = _rows(_source("jobs", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["j1", "j2"]
+ assert snapshots[2]["url"] == page2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_windows_the_parent_build_walk(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [self._builds_page(), self._jobs_page(["j1"])])
+
+ _rows(
+ _source(
+ "jobs",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="build_created_at",
+ )
+ )
+
+ # Jobs carry no server-side time filter, so the watermark has to bound the builds request
+ # that drives the fan-out — otherwise every sync re-walks the whole organization.
+ assert snapshots[0]["params"] == {"per_page": 100, "created_from": "2026-03-04T02:58:14+00:00"}
+ assert "created_from" not in snapshots[1]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_omits_the_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [self._builds_page(), self._jobs_page(["j1"])])
+
+ _rows(_source("jobs", _make_manager()))
+
+ assert snapshots[0]["params"] == {"per_page": 100}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_checkpoints_nothing(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [self._builds_page(), self._jobs_page(["j1"])])
+
+ manager = _make_manager()
+ _rows(_source("jobs", manager))
+
+ # Resume is off for this fan-out: the framework rewrites the full set of completed child
+ # paths on every parent, which an organization's build list makes quadratic.
+ manager.save_state.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py
index f5eeb5ae4f1c..943c43b64229 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py
@@ -31,17 +31,32 @@ class TestBuildkiteSource:
@parameterized.expand(
[
- # Only builds exposes a server-side timestamp filter, so it's the only incremental endpoint.
- ("builds", True),
- ("organizations", False),
- ("pipelines", False),
- ("agents", False),
+ # Builds exposes a server-side timestamp filter, and jobs inherit it through the build
+ # fan-out that drives them. Nothing else has one.
+ ("builds", True, True),
+ ("jobs", True, False),
+ ("organizations", False, False),
+ ("pipelines", False, False),
+ ("agents", False, False),
+ ("teams", False, False),
+ ("test_suites", False, False),
+ ("test_suite_runs", False, False),
+ ("test_suite_tests", False, False),
]
)
- def test_incremental_support_per_endpoint(self, endpoint: str, expected: bool) -> None:
+ def test_incremental_support_per_endpoint(self, endpoint: str, incremental: bool, append: bool) -> None:
schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
- assert schemas[endpoint].supports_incremental is expected
- assert schemas[endpoint].supports_append is expected
+ assert schemas[endpoint].supports_incremental is incremental
+ # A job restates after it is created (state, finished_at) and each incremental run re-walks
+ # the trailing build window, so append would materialize the re-pulled rows as duplicates.
+ assert schemas[endpoint].supports_append is append
+
+ def test_jobs_is_off_by_default_and_says_why(self) -> None:
+ # One request per build is enough API cost that the schema picker must not pre-select it.
+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas["jobs"].should_sync_default is False
+ assert schemas["jobs"].description is not None
+ assert all(s.should_sync_default for s in schemas.values() if s.name != "jobs")
@parameterized.expand(
[