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(data-warehouse): implement buildkite import source (#65626)

Tom Owers48179421e2cb
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index f866812c4a2a..c907051c0891 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -64,6 +64,7 @@ the row lists both.
| brevo | HTTP | requests | ✅ |
| brex | HTTP | requests | ✅ |
| buildbetter | HTTP | requests | ✅ |
+| buildkite | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -300,7 +301,6 @@ doesn't conflict with concurrent PRs.
- breezometer
- breezy_hr
- bugsnag
-- buildkite
- bunny
- buzzsprout
- cal_com
diff --git a/posthog/temporal/data_imports/sources/buildkite/buildkite.py b/posthog/temporal/data_imports/sources/buildkite/buildkite.py
new file mode 100644
index 000000000000..8983e3f26147
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/buildkite/buildkite.py
@@ -0,0 +1,253 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.buildkite.settings import BUILDKITE_ENDPOINTS, BuildkiteEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BUILDKITE_BASE_URL = "https://api.buildkite.com"
+# Buildkite caps per_page at 100 (default 30).
+PAGE_SIZE = 100
+# The batcher flushes every CHUNK_SIZE items. State is saved only after a flush, pointing at the
+# next page, so the batcher must never flush mid-page — otherwise items after the flush point but
+# before the page end would be skipped on resume. Keeping CHUNK_SIZE an exact multiple of PAGE_SIZE
+# guarantees flushes land on page boundaries; the assertion below makes the dependency explicit.
+CHUNK_SIZE = 2000
+
+
+class BuildkiteRetryableError(Exception):
+ pass
+
+
+class BuildkiteResumeConfig:
+ next_url: str
+
+
+def _get_headers(api_access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Format an incremental cursor as ISO 8601, which Buildkite's *_from filters expect."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _parse_next_url(link_header: str) -> str | None:
+ """Return the URL with rel="next" from Buildkite's RFC 5988 Link header, if any."""
+ if not link_header:
+ return None
+ for part in link_header.split(","):
+ match = re.search(r'<([^>]+)>;\s*rel="next"', part.strip())
+ if match:
+ return match.group(1)
+ return None
+
+
+def _resolve_incremental_param(
+ config: BuildkiteEndpointConfig,
+ incremental_field: str | None,
+) -> str | None:
+ """Map the user-chosen incremental field to its server-side filter param, if supported."""
+ if not config.incremental_param_map:
+ return None
+ field_name = incremental_field
+ if field_name is None and config.incremental_fields:
+ field_name = config.incremental_fields[0]["field"]
+ if field_name is None:
+ return None
+ return config.incremental_param_map.get(field_name)
+
+
+def _build_initial_params(
+ config: BuildkiteEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"per_page": PAGE_SIZE}
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ param = _resolve_incremental_param(config, incremental_field)
+ if param:
+ params[param] = _format_incremental_value(db_incremental_field_last_value)
+
+ return params
+
+
+def _build_initial_url(config: BuildkiteEndpointConfig, organization: str, params: dict[str, Any]) -> str:
+ path = config.path.format(organization=organization)
+ if not params:
+ return f"{BUILDKITE_BASE_URL}{path}"
+ return f"{BUILDKITE_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(
+ api_access_token: str, organization: str, schema_name: str | None = None
+) -> tuple[bool, str | None]:
+ """Probe the Buildkite API to confirm the token is genuine and the org is reachable.
+
+ At source-create (``schema_name`` is None) a 403 is accepted: the token is valid but may simply
+ lack ``read_organizations`` while still holding the scopes for the endpoints the user wants to
+ sync. When checking a specific schema, a 403 means the token can't read that resource, so it
+ fails.
+ """
+ if schema_name and schema_name in BUILDKITE_ENDPOINTS:
+ config = BUILDKITE_ENDPOINTS[schema_name]
+ path = config.path.format(organization=organization)
+ url = f"{BUILDKITE_BASE_URL}{path}?per_page=1"
+ else:
+ url = f"{BUILDKITE_BASE_URL}/v2/organizations/{organization}"
+
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_access_token), timeout=10)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Buildkite API access token"
+ if response.status_code == 403:
+ if schema_name:
+ return False, f"Your Buildkite API access token lacks the scope needed to read '{schema_name}'"
+ return True, None
+ if response.status_code == 404:
+ return False, f"Organization '{organization}' not found or not accessible"
+
+ try:
+ message = response.json().get("message", response.text)
+ except Exception:
+ message = response.text
+ return False, message
+
+
+@retry(
+ retry=retry_if_exception_type((BuildkiteRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> requests.Response:
+ response = session.get(page_url, headers=headers, timeout=60)
+
+ # Org-level rate limit is 200 req/min; Buildkite returns 429 with RateLimit-Reset on exceed.
+ # Back off and retry on 429 and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BuildkiteRetryableError(f"Buildkite API error (retryable): status={response.status_code}, url={page_url}")
+
+ if not response.ok:
+ logger.error(f"Buildkite API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response
+
+
+def get_rows(
+ api_access_token: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BuildkiteResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = BUILDKITE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_access_token)
+ assert CHUNK_SIZE % PAGE_SIZE == 0, (
+ "CHUNK_SIZE must be a multiple of PAGE_SIZE so the batcher only flushes at page boundaries"
+ )
+ batcher = Batcher(logger=logger, chunk_size=CHUNK_SIZE, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session()
+
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ logger.debug(f"Buildkite: resuming from URL: {url}")
+ else:
+ url = _build_initial_url(config, organization, params)
+
+ while True:
+ response = _fetch_page(session, url, headers, logger)
+ data = response.json()
+ # Buildkite list endpoints return a top-level JSON array.
+ if not isinstance(data, list) or not data:
+ break
+
+ next_url = _parse_next_url(response.headers.get("Link", ""))
+
+ for item in data:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the
+ # last page rather than skipping it — merge dedupes on the primary key.
+ if next_url:
+ resumable_source_manager.save_state(BuildkiteResumeConfig(next_url=next_url))
+
+ if not next_url:
+ break
+
+ url = next_url
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def buildkite_source(
+ api_access_token: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BuildkiteResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = BUILDKITE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_access_token=api_access_token,
+ organization=organization,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/buildkite/canonical_descriptions.py b/posthog/temporal/data_imports/sources/buildkite/canonical_descriptions.py
new file mode 100644
index 000000000000..7f98b5e46148
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/buildkite/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Curated from the Buildkite v2 REST API docs (https://buildkite.com/docs/apis/rest-api).
+# Keyed by the endpoint/schema name from settings.ENDPOINTS.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "A Buildkite organization the API access token can read.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/organizations",
+ "columns": {
+ "id": "Unique identifier for the organization.",
+ "slug": "URL-friendly identifier used in API paths and the web UI.",
+ "name": "Display name of the organization.",
+ "web_url": "URL of the organization in the Buildkite web UI.",
+ "url": "API URL for the organization.",
+ "pipelines_url": "API URL listing the organization's pipelines.",
+ "agents_url": "API URL listing the organization's agents.",
+ "created_at": "Time the organization was created (ISO 8601).",
+ },
+ },
+ "pipelines": {
+ "description": "A pipeline defines the steps Buildkite runs for a project's builds.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/pipelines",
+ "columns": {
+ "id": "Unique identifier for the pipeline.",
+ "slug": "URL-friendly identifier for the pipeline within its organization.",
+ "name": "Display name of the pipeline.",
+ "repository": "Git repository URL the pipeline builds.",
+ "web_url": "URL of the pipeline in the Buildkite web UI.",
+ "url": "API URL for the pipeline.",
+ "builds_url": "API URL listing the pipeline's builds.",
+ "default_branch": "Branch builds run against by default.",
+ "description": "Human-readable description of the pipeline.",
+ "created_at": "Time the pipeline was created (ISO 8601).",
+ "archived_at": "Time the pipeline was archived, or null if active (ISO 8601).",
+ "builds_count": "Total number of builds run for the pipeline.",
+ "running_builds_count": "Number of builds currently running.",
+ "scheduled_builds_count": "Number of builds currently scheduled.",
+ "visibility": "Whether the pipeline is public or private.",
+ },
+ },
+ "builds": {
+ "description": "A single run of a pipeline, made up of one or more jobs.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/builds",
+ "columns": {
+ "id": "Unique identifier for the build.",
+ "number": "Sequential build number within its pipeline.",
+ "state": "Current state of the build (e.g. running, passed, failed, canceled).",
+ "blocked": "Whether the build is blocked waiting on a manual unblock step.",
+ "message": "Commit message or build message associated with the build.",
+ "commit": "Git commit SHA the build ran against.",
+ "branch": "Git branch the build ran against.",
+ "web_url": "URL of the build in the Buildkite web UI.",
+ "url": "API URL for the build.",
+ "created_at": "Time the build was created (ISO 8601).",
+ "scheduled_at": "Time the build was scheduled (ISO 8601).",
+ "started_at": "Time the build started running (ISO 8601).",
+ "finished_at": "Time the build finished, or null if still running (ISO 8601).",
+ "creator": "The user or trigger that created the build.",
+ "pipeline": "The pipeline this build belongs to.",
+ "jobs": "The jobs that make up the build.",
+ "source": "What triggered the build (e.g. ui, api, webhook, schedule).",
+ },
+ },
+ "agents": {
+ "description": "A connected Buildkite agent that runs jobs for the organization.",
+ "docs_url": "https://buildkite.com/docs/apis/rest-api/agents",
+ "columns": {
+ "id": "Unique identifier for the agent.",
+ "name": "Name the agent registered with.",
+ "connection_state": "Current connection state of the agent (e.g. connected, disconnected, lost).",
+ "hostname": "Hostname of the machine running the agent.",
+ "ip_address": "IP address the agent connected from.",
+ "version": "Version of the Buildkite agent software.",
+ "web_url": "URL of the agent in the Buildkite web UI.",
+ "url": "API URL for the agent.",
+ "created_at": "Time the agent connected (ISO 8601).",
+ "last_job_finished_at": "Time the agent last finished a job (ISO 8601).",
+ "meta_data": "Agent metadata tags used for targeting jobs.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/buildkite/settings.py b/posthog/temporal/data_imports/sources/buildkite/settings.py
new file mode 100644
index 000000000000..2fc3ac35212d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/buildkite/settings.py
@@ -0,0 +1,72 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+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.
+ path: str
+ incremental_fields: list[IncrementalField]
+ # Field used to partition the Delta table. Must be STABLE (set once at creation) — never
+ # ``updated_at`` style fields, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # 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
+
+
+# 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_ENDPOINTS: dict[str, BuildkiteEndpointConfig] = {
+ "organizations": BuildkiteEndpointConfig(
+ name="organizations",
+ path="/v2/organizations",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "pipelines": BuildkiteEndpointConfig(
+ name="pipelines",
+ path="/v2/organizations/{organization}/pipelines",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "builds": BuildkiteEndpointConfig(
+ name="builds",
+ path="/v2/organizations/{organization}/builds",
+ partition_key="created_at",
+ # The builds list returns newest-first by created_at and accepts a `created_from` filter
+ # (ISO 8601). We sync incrementally by passing created_from=<watermark> and paginating the
+ # bounded window newest-first. `created_at` is immutable; a build's state/finished_at mutate
+ # after it first appears, so a build that finishes after newer builds have landed won't be
+ # re-fetched once it drops below the watermark. Full refresh re-pulls everything.
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ sort_mode="desc",
+ incremental_param_map={"created_at": "created_from"},
+ ),
+ "agents": BuildkiteEndpointConfig(
+ name="agents",
+ path="/v2/organizations/{organization}/agents",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(BUILDKITE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BUILDKITE_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/buildkite/source.py b/posthog/temporal/data_imports/sources/buildkite/source.py
index 23a3e029a5c2..bb5ad2d0f237 100644
--- a/posthog/temporal/data_imports/sources/buildkite/source.py
+++ b/posthog/temporal/data_imports/sources/buildkite/source.py
@@ -1,31 +1,142 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.buildkite.buildkite import (
+ BuildkiteResumeConfig,
+ buildkite_source,
+ validate_credentials as validate_buildkite_credentials,
+)
+from posthog.temporal.data_imports.sources.buildkite.canonical_descriptions import CANONICAL_DESCRIPTIONS
+from posthog.temporal.data_imports.sources.buildkite.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import BuildkiteSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BuildkiteSource(SimpleSource[BuildkiteSourceConfig]):
+class BuildkiteSource(ResumableSource[BuildkiteSourceConfig, BuildkiteResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BUILDKITE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The token is sent to api.buildkite.com against <organization>, so retargeting the
+ # organization must force re-entry of the token.
+ return ["organization"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BUILDKITE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Buildkite",
- iconPath="/static/services/buildkite.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Buildkite API access token and organization slug to sync your CI/CD data into the PostHog Data warehouse.
+
+You can create an API access token in your [Buildkite account settings](https://buildkite.com/user/api-access-tokens).
+
+Make sure to grant the following read scopes:
+- `read_organizations`
+- `read_pipelines`
+- `read_builds`
+- `read_agents`
+""",
+ iconPath="/static/services/buildkite.png",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_access_token",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="bkua_...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization slug",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-organization",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can't satisfy a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.buildkite.com": "Your Buildkite API access token is invalid or has been revoked. Create a new token in your Buildkite account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.buildkite.com": "Your Buildkite API access token is missing the read scope needed to sync this data. Grant the required read scopes in your Buildkite account settings, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BuildkiteSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: BuildkiteSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_buildkite_credentials(config.api_access_token, config.organization, schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BuildkiteResumeConfig]:
+ return ResumableSourceManager[BuildkiteResumeConfig](inputs, BuildkiteResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BuildkiteSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BuildkiteResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return buildkite_source(
+ api_access_token=config.api_access_token,
+ organization=config.organization,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite.py b/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite.py
new file mode 100644
index 000000000000..e7c9df737391
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite.py
@@ -0,0 +1,278 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.buildkite import buildkite
+from posthog.temporal.data_imports.sources.buildkite.buildkite import (
+ CHUNK_SIZE,
+ PAGE_SIZE,
+ BuildkiteResumeConfig,
+ _build_initial_params,
+ _build_initial_url,
+ _format_incremental_value,
+ _parse_next_url,
+ buildkite_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.buildkite.settings import BUILDKITE_ENDPOINTS
+
+
+class TestFormatIncrementalValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:
+ assert _format_incremental_value(value) == expected
+
+
+class TestParseNextUrl:
+ def test_returns_next_url(self) -> None:
+ header = (
+ '<https://api.buildkite.com/v2/organizations/o/builds?page=2&per_page=100>; rel="next", '
+ '<https://api.buildkite.com/v2/organizations/o/builds?page=5&per_page=100>; rel="last"'
+ )
+ assert _parse_next_url(header) == "https://api.buildkite.com/v2/organizations/o/builds?page=2&per_page=100"
+
+ def test_last_page_has_no_next(self) -> None:
+ header = '<https://api.buildkite.com/v2/organizations/o/builds?page=1&per_page=100>; rel="prev"'
+ assert _parse_next_url(header) is None
+
+ def test_empty_header(self) -> None:
+ assert _parse_next_url("") is None
+
+
+class TestBuildInitialParams:
+ def test_builds_incremental_maps_to_created_from(self) -> None:
+ params = _build_initial_params(
+ BUILDKITE_ENDPOINTS["builds"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert params["per_page"] == buildkite.PAGE_SIZE
+ assert params["created_from"] == "2026-03-04T02:58:14+00:00"
+
+ def test_builds_full_refresh_has_no_filter(self) -> None:
+ params = _build_initial_params(
+ BUILDKITE_ENDPOINTS["builds"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert params == {"per_page": buildkite.PAGE_SIZE}
+
+ @parameterized.expand([("organizations",), ("pipelines",), ("agents",)])
+ 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).
+ params = _build_initial_params(
+ BUILDKITE_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert params == {"per_page": buildkite.PAGE_SIZE}
+
+
+class TestBuildInitialUrl:
+ def test_org_scoped_path_is_formatted(self) -> None:
+ url = _build_initial_url(BUILDKITE_ENDPOINTS["builds"], "my-org", {"per_page": 100})
+ assert url == "https://api.buildkite.com/v2/organizations/my-org/builds?per_page=100"
+
+ def test_non_org_scoped_path_ignores_placeholder(self) -> None:
+ url = _build_initial_url(BUILDKITE_ENDPOINTS["organizations"], "my-org", {"per_page": 100})
+ assert url == "https://api.buildkite.com/v2/organizations?per_page=100"
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int, body: Any, link: str = "") -> None:
+ self.status_code = status_code
+ self._body = body
+ self.headers = {"Link": link} if link else {}
+ self.text = ""
+
+ def json(self) -> Any:
+ return self._body
+
+
+class TestValidateCredentials:
+ @staticmethod
+ def _patch_get(monkeypatch: Any, response: _FakeResponse) -> dict[str, str]:
+ captured: dict[str, str] = {}
+
+ def fake_get(url: str, headers: dict[str, str], timeout: int) -> _FakeResponse:
+ captured["url"] = url
+ return response
+
+ session = MagicMock()
+ session.get = fake_get
+ monkeypatch.setattr(buildkite, "make_tracked_session", lambda *a, **k: session)
+ return captured
+
+ def test_success(self, monkeypatch: Any) -> None:
+ self._patch_get(monkeypatch, _FakeResponse(200, {"slug": "my-org"}))
+ assert validate_credentials("bkua", "my-org") == (True, None)
+
+ def test_invalid_token(self, monkeypatch: Any) -> None:
+ self._patch_get(monkeypatch, _FakeResponse(401, {"message": "Authentication required"}))
+ ok, error = validate_credentials("bkua", "my-org")
+ assert ok is False
+ assert error is not None and "invalid" in error.lower()
+
+ def test_forbidden_accepted_at_source_create(self, monkeypatch: Any) -> None:
+ # A valid token may lack read_organizations while still holding the per-endpoint scopes the
+ # user wants — so a 403 at source-create (schema_name=None) must not block connecting.
+ self._patch_get(monkeypatch, _FakeResponse(403, {"message": "Forbidden"}))
+ assert validate_credentials("bkua", "my-org") == (True, None)
+
+ def test_forbidden_rejected_for_specific_schema(self, monkeypatch: Any) -> None:
+ self._patch_get(monkeypatch, _FakeResponse(403, {"message": "Forbidden"}))
+ ok, error = validate_credentials("bkua", "my-org", schema_name="builds")
+ assert ok is False
+ assert error is not None and "builds" in error
+
+ def test_org_not_found(self, monkeypatch: Any) -> None:
+ self._patch_get(monkeypatch, _FakeResponse(404, {"message": "Not Found"}))
+ ok, error = validate_credentials("bkua", "missing-org")
+ assert ok is False
+ assert error is not None and "missing-org" in error
+
+ def test_schema_probe_targets_endpoint_path(self, monkeypatch: Any) -> None:
+ captured = self._patch_get(monkeypatch, _FakeResponse(200, []))
+ validate_credentials("bkua", "my-org", schema_name="agents")
+ assert captured["url"] == "https://api.buildkite.com/v2/organizations/my-org/agents?per_page=1"
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BuildkiteResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BuildkiteResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BuildkiteResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BuildkiteResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ monkeypatch: Any, manager: _FakeResumableManager, pages: dict[str, _FakeResponse], **kwargs: Any
+) -> tuple[list[dict], list[str]]:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> _FakeResponse:
+ fetched.append(url)
+ return pages[url]
+
+ monkeypatch.setattr(buildkite, "make_tracked_session", lambda *a, **k: MagicMock())
+ monkeypatch.setattr(buildkite, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_access_token="bkua",
+ organization="my-org",
+ endpoint=kwargs.pop("endpoint", "pipelines"),
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(table.to_pylist())
+ return rows, fetched
+
+
+class TestGetRows:
+ def test_follows_link_header_pagination(self, monkeypatch: Any) -> None:
+ page1 = "https://api.buildkite.com/v2/organizations/my-org/pipelines?per_page=100"
+ page2 = "https://api.buildkite.com/v2/organizations/my-org/pipelines?page=2&per_page=100"
+ pages = {
+ page1: _FakeResponse(200, [{"id": "p1"}, {"id": "p2"}], link=f'<{page2}>; rel="next"'),
+ page2: _FakeResponse(200, [{"id": "p3"}]),
+ }
+ rows, fetched = _collect(monkeypatch, _FakeResumableManager(), pages, endpoint="pipelines")
+ assert [r["id"] for r in rows] == ["p1", "p2", "p3"]
+ assert fetched == [page1, page2]
+
+ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:
+ page1 = "https://api.buildkite.com/v2/organizations/my-org/agents?per_page=100"
+ pages = {page1: _FakeResponse(200, [])}
+ rows, fetched = _collect(monkeypatch, _FakeResumableManager(), pages, endpoint="agents")
+ assert rows == []
+ assert fetched == [page1]
+
+ def test_resumes_from_saved_state(self, monkeypatch: Any) -> None:
+ resume_url = "https://api.buildkite.com/v2/organizations/my-org/pipelines?page=3&per_page=100"
+ pages = {resume_url: _FakeResponse(200, [{"id": "p9"}])}
+ manager = _FakeResumableManager(BuildkiteResumeConfig(next_url=resume_url))
+ rows, fetched = _collect(monkeypatch, manager, pages, endpoint="pipelines")
+ # Resume must start at the saved URL, not the freshly-built first-page URL.
+ assert fetched == [resume_url]
+ assert [r["id"] for r in rows] == ["p9"]
+
+ def test_saves_state_after_yielding_a_batch(self, monkeypatch: Any) -> None:
+ # Mirror the real API contract: Buildkite caps per_page at PAGE_SIZE, so the batcher only
+ # reaches its CHUNK_SIZE buffer after CHUNK_SIZE / PAGE_SIZE consecutive full pages. State is
+ # saved at that page boundary, pointing at the NEXT page, so a crash re-yields the last page
+ # rather than skipping it. CHUNK_SIZE must be a multiple of PAGE_SIZE for this to hold.
+ assert CHUNK_SIZE % PAGE_SIZE == 0
+ full_pages = CHUNK_SIZE // PAGE_SIZE
+
+ base = "https://api.buildkite.com/v2/organizations/my-org/builds?per_page=100"
+
+ def page_url(n: int) -> str:
+ return base if n == 1 else f"{base}&page={n}"
+
+ # full_pages pages of PAGE_SIZE items each fill exactly one chunk; the boundary page after
+ # them holds the final straggler row.
+ boundary_page = page_url(full_pages + 1)
+ pages = {
+ page_url(n): _FakeResponse(
+ 200,
+ [{"id": f"b{(n - 1) * PAGE_SIZE + i}"} for i in range(PAGE_SIZE)],
+ link=f'<{page_url(n + 1)}>; rel="next"',
+ )
+ for n in range(1, full_pages + 1)
+ }
+ pages[boundary_page] = _FakeResponse(200, [{"id": "b-last"}])
+
+ manager = _FakeResumableManager()
+ rows, _fetched = _collect(monkeypatch, manager, pages, endpoint="builds")
+ assert len(rows) == CHUNK_SIZE + 1
+ assert manager.saved == [BuildkiteResumeConfig(next_url=boundary_page)]
+
+
+class TestBuildkiteSourceResponse:
+ @parameterized.expand(
+ [
+ ("organizations", ["id"], "asc", "created_at"),
+ ("pipelines", ["id"], "asc", "created_at"),
+ ("builds", ["id"], "desc", "created_at"),
+ ("agents", ["id"], "asc", "created_at"),
+ ]
+ )
+ def test_source_response_shape(
+ self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_key: str
+ ) -> None:
+ response = buildkite_source(
+ api_access_token="bkua",
+ organization="my-org",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
diff --git a/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py b/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py
new file mode 100644
index 000000000000..86695a710db4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/buildkite/tests/test_buildkite_source.py
@@ -0,0 +1,164 @@
+from typing import Any
+
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from posthog.temporal.data_imports.sources.buildkite.buildkite import BuildkiteResumeConfig
+from posthog.temporal.data_imports.sources.buildkite.canonical_descriptions import CANONICAL_DESCRIPTIONS
+from posthog.temporal.data_imports.sources.buildkite.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.buildkite.source import BuildkiteSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import BuildkiteSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config() -> BuildkiteSourceConfig:
+ return BuildkiteSourceConfig(api_access_token="bkua_test", organization="my-org")
+
+
+class TestBuildkiteSource:
+ def setup_method(self) -> None:
+ self.source = BuildkiteSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BUILDKITE
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ field_names = {f.name for f in config.fields}
+ assert field_names == {"api_access_token", "organization"}
+ # The token is the secret; the org slug is not.
+ by_name = {f.name: f for f in config.fields}
+ token_field = by_name["api_access_token"]
+ org_field = by_name["organization"]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert isinstance(org_field, SourceFieldInputConfig)
+ assert token_field.secret is True
+ assert org_field.secret is False
+
+ def test_connection_host_fields_includes_organization(self) -> None:
+ # The token is sent to api.buildkite.com against <organization>, so retargeting the
+ # organization must force re-entry of the token.
+ assert self.source.connection_host_fields == ["organization"]
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = {s.name for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas == set(ENDPOINTS)
+
+ @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),
+ ]
+ )
+ def test_incremental_support_per_endpoint(self, endpoint: str, expected: 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
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["builds"])
+ assert [s.name for s in schemas] == ["builds"]
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.buildkite.com/v2/organizations/my-org/builds?per_page=100",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.buildkite.com/v2/organizations/my-org/agents",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.buildkite.com', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.buildkite.com/v2"),
+ ("rate_limited", "Buildkite API error (retryable): status=429"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ # Each declared endpoint should have a curated description so it isn't sent to the LLM.
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BuildkiteResumeConfig
+
+ def test_validate_credentials_delegates_with_org_and_token(self) -> None:
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.buildkite.source.validate_buildkite_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ result = self.source.validate_credentials(_config(), team_id=self.team_id, schema_name="builds")
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("bkua_test", "my-org", "builds")
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "builds"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "created_at"
+ manager = MagicMock()
+
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.buildkite.source.buildkite_source", side_effect=fake_source
+ ):
+ self.source.source_for_pipeline(_config(), manager, inputs)
+
+ assert captured["api_access_token"] == "bkua_test"
+ assert captured["organization"] == "my-org"
+ assert captured["endpoint"] == "builds"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert captured["incremental_field"] == "created_at"
+ assert captured["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "pipelines"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = None
+
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.buildkite.source.buildkite_source", side_effect=fake_source
+ ):
+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert captured["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 56554662c64c..c86a531a2c9c 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -498,7 +498,8 @@ class BuildBetterSourceConfig(config.Config):
@config.config
class BuildkiteSourceConfig(config.Config):
- pass
+ api_access_token: str
+ organization: str
@config.config