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): add k6 cloud labels and test run distribution tables (#112546)

Tom Owers5a142405accd
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 865664bd2577..a5b434cf0af4 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -727,7 +727,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/justsift/justsift.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/justsift/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kandji/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/katana/katana.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/katana/settings.py
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 51c49a2bcdf9..0a44448ac3f0 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
@@ -4669,8 +4669,8 @@ Diffed against: <https://api.k6.io/cloud/v6/openapi>
- [ ] `test_runs/{id}/query_aggregate_k6` — aggregated metric values per test run — the headline pass/fail numbers (p95 http_req_duration, error rate) that make test_runs analyzable (high)
- [ ] `test_runs/{id}/metrics` — metric metadata per run (name, type, origin); the join key for any metric value query (high)
- [ ] `test_runs/{id}/series` — per-metric time series within a run, for trend and regression charts (medium)
-- [ ] `test_runs/{id}/distribution` — breakdown of a run across load zones — the only per-zone dimension available (medium)
-- [ ] `labels` — lookup table resolving the label keys/values attached to projects and load tests (medium)
+- [x] `test_runs/{id}/distribution` — node allocation and percentage breakdown by load zone (medium)
+- [x] `labels` — lookup table of the organization's label keys (id, key, description); the values set on projects are not returned by this endpoint (medium)
- [ ] `test_runs/{id}/labels` — label dimensions present on a run's metrics (url, status, scenario, method), needed to slice metric data (medium)
Note: Two API versions in play: the resource endpoints PostHog syncs are /cloud/v6/\* (spec at https://api.k6.io/cloud/v6/openapi), but all metrics endpoints are /cloud/v5/\* and are documented only in prose at https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/metrics/ — not in the OpenAPI file. The v5 metrics endpoints use an unusual OData-ish call syntax, e.g. /cloud/v5/test_runs/:id/query_aggregate_k6(:parameters), and offer an /ms alias to dodge ad blockers.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/canonical_descriptions.py
index b87bbe624d9a..5771313f6250 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/canonical_descriptions.py
@@ -83,4 +83,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"public": "Whether the load zone is public or private.",
},
},
+ "labels": {
+ "description": "A label key defined for the organization, used to label projects.",
+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",
+ "columns": {
+ "id": "Label key ID.",
+ "key": "Label key name.",
+ "description": "Label key description.",
+ },
+ },
+ "test_run_distribution": {
+ "description": "Distribution of nodes across the load generators for a test run, one row per load zone.",
+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",
+ "columns": {
+ "test_run_id": "ID of the load test run.",
+ "test_run_created": "Date and time when the test run was started.",
+ "load_zone": "Name of the load zone.",
+ "percentage": "Percentage of the total load handled by this load zone.",
+ "nodes": "List of nodes allocated to this load zone, each with its size and public IP address.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py
index 7b24b760ebb6..b5ecbeb57807 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py
@@ -1,6 +1,7 @@
import dataclasses
+from collections.abc import Iterable
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from urllib.parse import urlencode, urljoin, urlparse
from requests import Response
@@ -10,22 +11,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BaseNextUrlPaginator,
SinglePagePaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
+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,
+ Endpoint,
+)
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
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import K6_CLOUD_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import (
+ K6_CLOUD_ENDPOINTS,
+ PAGE_SIZE,
+ K6CloudEndpointConfig,
+)
# Grafana Cloud k6 pins the current REST API under a single global host + version path.
K6_CLOUD_HOST = "api.k6.io"
K6_CLOUD_BASE_URL = f"https://{K6_CLOUD_HOST}/cloud/v6"
-# $top caps at 1000 rows per page (the documented maximum).
-PAGE_SIZE = 1000
REQUEST_TIMEOUT_SECONDS = 60
@@ -119,6 +129,74 @@ class K6NextLinkPaginator(BaseNextUrlPaginator):
self._has_next_page = True
+def _client_config(api_token: str, stack_id: str) -> ClientConfig:
+ return {
+ "base_url": K6_CLOUD_BASE_URL,
+ # Auth (Bearer) goes through the framework auth config so its value is redacted from
+ # errors/logs; only the non-secret stack id + accept headers are set here.
+ "headers": {"X-Stack-Id": stack_id, "Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_token},
+ "request_timeout": (10, REQUEST_TIMEOUT_SECONDS),
+ }
+
+
+def _explode_distribution(row: dict[str, Any]) -> list[dict[str, Any]]:
+ """Turn one `{"distribution": {<load_zone>: {...}}}` body into one row per load zone."""
+ # The spec marks `distribution` as required, so a 200 without it is a shape change. Fail
+ # loudly instead of dropping the run's rows from a full refresh.
+ if "distribution" not in row:
+ raise ValueError(f"k6 Cloud: distribution response for test run {row['test_run_id']} has no `distribution`")
+ zones = row["distribution"] or {}
+ return [
+ {
+ "test_run_id": row["test_run_id"],
+ "test_run_created": row["test_run_created"],
+ "load_zone": load_zone,
+ "percentage": zone.get("percentage"),
+ "nodes": zone.get("nodes"),
+ }
+ for load_zone, zone in zones.items()
+ ]
+
+
+def _source_response(endpoint: str, config: K6CloudEndpointConfig, resource: Iterable[Any]) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def _distribution_source(
+ api_token: str, stack_id: str, endpoint: str, config: K6CloudEndpointConfig, team_id: int, job_id: str
+) -> SourceResponse:
+ assert config.fanout is not None
+ resource = build_dependent_resource(
+ endpoint_configs=K6_CLOUD_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_token, stack_id),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={
+ "data_selector": "value",
+ "data_selector_required": True,
+ "paginator": K6NextLinkPaginator(),
+ },
+ # The body is one object keyed by load zone, so no selector: the whole body is the row.
+ child_endpoint_extra={"paginator": SinglePagePaginator()},
+ page_size_param=None,
+ )
+ return _source_response(endpoint, config, cast(Resource, resource).add_map(_explode_distribution))
+
+
def k6_cloud_source(
api_token: str,
stack_id: str,
@@ -129,6 +207,8 @@ def k6_cloud_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = K6_CLOUD_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _distribution_source(api_token, stack_id, endpoint, config, team_id, job_id)
params: dict[str, Any] = {}
if config.paginated:
@@ -154,13 +234,7 @@ def k6_cloud_source(
}
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": K6_CLOUD_BASE_URL,
- # Auth (Bearer) goes through the framework auth config so its value is redacted from
- # errors/logs; only the non-secret stack id + accept headers are set here.
- "headers": {"X-Stack-Id": stack_id, "Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_token},
- },
+ "client": _client_config(api_token, stack_id),
"resources": [{"name": endpoint, "endpoint": endpoint_config}],
}
@@ -186,16 +260,7 @@ def k6_cloud_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime" if config.partition_key else None,
- partition_format="month" if config.partition_key else None,
- partition_keys=[config.partition_key] if config.partition_key else None,
- )
+ return _source_response(endpoint, config, resource)
def validate_credentials(api_token: str, stack_id: str, schema_name: Optional[str] = None) -> tuple[bool, bool]:
@@ -206,6 +271,9 @@ def validate_credentials(api_token: str, stack_id: str, schema_name: Optional[st
accept access gaps at source-create time but reject them for a specific schema.
"""
config = K6_CLOUD_ENDPOINTS.get(schema_name) if schema_name else None
+ if config is not None and config.fanout is not None:
+ # A fan-out path needs a test run id, so probe the parent listing it reads instead.
+ config = K6_CLOUD_ENDPOINTS[config.fanout.parent_name]
if config is not None:
# For a specific schema, probe that endpoint so the check reflects real access.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py
index 2d4d42fff39b..86e67f1fcdc9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py
@@ -1,10 +1,16 @@
from dataclasses import dataclass
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# $top caps at 1000 rows per page (the documented maximum).
+PAGE_SIZE = 1000
-@dataclass
+
+@dataclass(frozen=True)
class K6CloudEndpointConfig:
name: str
path: str
@@ -25,6 +31,9 @@ class K6CloudEndpointConfig:
# `@nextLink` URL in the response). `load_zones` returns every row in one page.
paginated: bool = True
should_sync_default: bool = True
+ fanout: Optional[DependentEndpointConfig] = None
+ page_size: int = PAGE_SIZE
+ default_incremental_field: Optional[str] = None
def _created_incremental_field() -> list[IncrementalField]:
@@ -38,9 +47,6 @@ def _created_incremental_field() -> list[IncrementalField]:
]
-# Streams mirror the canonical Grafana Cloud k6 v6 resources a user actually wants in a
-# warehouse: Projects, Load tests, Test runs, Schedules, and Load zones. Metrics/scripts/
-# limits are per-run detail endpoints that require fan-out and are left out of this alpha.
K6_CLOUD_ENDPOINTS: dict[str, K6CloudEndpointConfig] = {
# Test runs are the natural incremental stream: `/cloud/v6/test_runs` exposes
# `created_after` (inclusive) as a server-side filter on the immutable `created`
@@ -94,6 +100,36 @@ K6_CLOUD_ENDPOINTS: dict[str, K6CloudEndpointConfig] = {
paginated=False,
should_sync_default=False,
),
+ "labels": K6CloudEndpointConfig(
+ name="labels",
+ path="/labels",
+ primary_keys=["id"],
+ incremental_fields=[],
+ paginated=False,
+ should_sync_default=False,
+ ),
+ # One row per load zone per test run, with the nodes allocated in that zone. The endpoint
+ # returns a single object keyed by load zone, so it costs one request per test run and is
+ # off by default. It stays full refresh: a run that has not started yet answers 404, and an
+ # incremental cursor on `created` would move past it before its nodes exist.
+ "test_run_distribution": K6CloudEndpointConfig(
+ name="test_run_distribution",
+ path="/test_runs/{test_run_id}/distribution",
+ primary_keys=["test_run_id", "load_zone"],
+ partition_key="test_run_created",
+ incremental_fields=[],
+ paginated=False,
+ should_sync_default=False,
+ fanout=DependentEndpointConfig(
+ parent_name="test_runs",
+ resolve_param="test_run_id",
+ resolve_field="id",
+ include_from_parent=["id", "created"],
+ parent_field_renames={"id": "test_run_id", "created": "test_run_created"},
+ parent_params={"$top": str(PAGE_SIZE)},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
}
ENDPOINTS = tuple(K6_CLOUD_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud.py
index 41ae964115b4..fbbe23a25b46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud.py
@@ -45,6 +45,14 @@ def _response(
return resp
+def _raw_response(url: str, body: Any, *, status: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp.url = url
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _make_manager(resume_state: K6CloudResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -170,6 +178,7 @@ class TestPagination:
_rows(_source("test_runs", _make_manager()))
assert params[0]["$top"] == "1000"
+ assert session.send.call_args.kwargs["timeout"] == (10, 60)
@mock.patch(CLIENT_SESSION_PATCH)
def test_load_zones_has_no_top_param(self, MockSession: mock.MagicMock) -> None:
@@ -222,6 +231,127 @@ class TestPagination:
_rows(_source("load_zones", _make_manager()))
+class TestDistributionFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_explodes_each_run_into_one_row_per_load_zone(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ runs_url = "https://api.k6.io/cloud/v6/test_runs"
+ params, urls = _wire(
+ session,
+ [
+ _response(
+ runs_url,
+ [
+ {"id": 11, "created": "2026-03-04T02:58:14Z"},
+ {"id": 12, "created": "2026-03-05T08:00:00Z"},
+ {"id": 13, "created": "2026-03-06T09:00:00Z"},
+ ],
+ ),
+ _raw_response(
+ f"{runs_url}/11/distribution",
+ {
+ "distribution": {
+ "amazon:us:ashburn": {
+ "percentage": 60,
+ "nodes": [{"size": "m5.large", "public_ip": "192.0.2.1"}],
+ },
+ "amazon:eu:dublin": {
+ "percentage": 40,
+ "nodes": [{"size": "m5.large", "public_ip": "192.0.2.2"}],
+ },
+ }
+ },
+ ),
+ # A run without distribution data answers 404; the fan-out must skip it, not fail.
+ _raw_response(
+ f"{runs_url}/12/distribution",
+ {"error": {"message": "Resource matching query does not exist."}},
+ status=404,
+ ),
+ _raw_response(
+ f"{runs_url}/13/distribution",
+ {"distribution": {"amazon:us:ashburn": {"percentage": 100, "nodes": []}}},
+ ),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("test_run_distribution", manager))
+
+ assert rows == [
+ {
+ "test_run_id": 11,
+ "test_run_created": "2026-03-04T02:58:14Z",
+ "load_zone": "amazon:us:ashburn",
+ "percentage": 60,
+ "nodes": [{"size": "m5.large", "public_ip": "192.0.2.1"}],
+ },
+ {
+ "test_run_id": 11,
+ "test_run_created": "2026-03-04T02:58:14Z",
+ "load_zone": "amazon:eu:dublin",
+ "percentage": 40,
+ "nodes": [{"size": "m5.large", "public_ip": "192.0.2.2"}],
+ },
+ {
+ "test_run_id": 13,
+ "test_run_created": "2026-03-06T09:00:00Z",
+ "load_zone": "amazon:us:ashburn",
+ "percentage": 100,
+ "nodes": [],
+ },
+ ]
+ assert urls == [
+ runs_url,
+ f"{K6_CLOUD_BASE_URL}/test_runs/11/distribution",
+ f"{K6_CLOUD_BASE_URL}/test_runs/12/distribution",
+ f"{K6_CLOUD_BASE_URL}/test_runs/13/distribution",
+ ]
+ # `$top` pages the parent listing only; the distribution endpoint takes no query params.
+ assert params[0]["$top"] == "1000"
+ assert all(not p for p in params[1:])
+ assert all(call.kwargs["timeout"] == (10, 60) for call in session.send.call_args_list)
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follows_parent_next_link(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ runs_url = "https://api.k6.io/cloud/v6/test_runs"
+ next_url = "https://api.k6.io/cloud/v6/test_runs?$skip=1000&$top=1000"
+ zone = {"distribution": {"amazon:us:ashburn": {"percentage": 100, "nodes": []}}}
+ _params, urls = _wire(
+ session,
+ [
+ _response(runs_url, [{"id": 1, "created": "2026-03-04T00:00:00Z"}], next_link=next_url),
+ _raw_response(f"{runs_url}/1/distribution", zone),
+ _response(next_url, [{"id": 2, "created": "2026-03-05T00:00:00Z"}]),
+ _raw_response(f"{runs_url}/2/distribution", zone),
+ ],
+ )
+
+ rows = _rows(_source("test_run_distribution", _make_manager()))
+
+ assert [row["test_run_id"] for row in rows] == [1, 2]
+ assert urls[2] == next_url
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_success_body_without_distribution_raises(self, MockSession: mock.MagicMock) -> None:
+ # A 200 without the required key is a shape change; silently emitting no rows would drop the
+ # run from a full refresh.
+ session = MockSession.return_value
+ runs_url = "https://api.k6.io/cloud/v6/test_runs"
+ _wire(
+ session,
+ [
+ _response(runs_url, [{"id": 1, "created": "2026-03-04T00:00:00Z"}]),
+ _raw_response(f"{runs_url}/1/distribution", {}),
+ ],
+ )
+
+ with pytest.raises(ValueError, match="has no `distribution`"):
+ _rows(_source("test_run_distribution", _make_manager()))
+
+
class TestIncremental:
@mock.patch(CLIENT_SESSION_PATCH)
def test_created_after_added_when_last_value_present(self, MockSession: mock.MagicMock) -> None:
@@ -350,6 +480,14 @@ class TestValidateCredentials:
mock_session.return_value.get.side_effect = Exception("boom")
assert validate_credentials("tok", "1") == (False, False)
+ def test_fan_out_schema_probes_parent_listing(self) -> None:
+ response = mock.MagicMock()
+ response.status_code = 200
+ with mock.patch(K6_SESSION_PATCH) as mock_session:
+ mock_session.return_value.get.return_value = response
+ validate_credentials("tok", "1", "test_run_distribution")
+ assert mock_session.return_value.get.call_args[0][0] == f"{K6_CLOUD_BASE_URL}/test_runs?%24top=1"
+
def test_schemaless_probe_hits_auth_endpoint(self) -> None:
response = mock.MagicMock()
response.status_code = 200