:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement k6_cloud import source (#67828)
Tom Owersc8b6667cc2d3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cb89d49c6d91..ae1c89162b23 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -190,6 +190,7 @@ the row lists both.| jira | HTTP | requests | ✅ || jotform | HTTP | requests | ✅ || justcall | HTTP | requests | ✅ |+| k6_cloud | HTTP | requests | ✅ || katana | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || lago | HTTP | requests | ✅ |@@ -497,7 +498,6 @@ doesn't conflict with concurrent PRs.- jobnimbus- judgeme_reviews- justsift-- k6_cloud- kafka- keka- kisidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 7386bcd5ecc3..a79e1d4f7462 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1720,7 +1720,8 @@ class JustSiftSourceConfig(config.Config):@config.configclass K6CloudSourceConfig(config.Config):- pass+ api_token: str+ stack_id: str@config.configdiff --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.pynew file mode 100644index 000000000000..b87bbe624d9a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/canonical_descriptions.py@@ -0,0 +1,86 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken verbatim from the Grafana Cloud k6 v6 OpenAPI spec+# (https://api.k6.io/cloud/v6/openapi). Keyed by the endpoint name from `get_schemas`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "test_runs": {+ "description": "A single execution of a load test, including its status, result, and billable duration.",+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",+ "columns": {+ "id": "ID of the test run.",+ "test_id": "ID of the parent test.",+ "project_id": "ID of the parent project.",+ "started_by": "Email of the user who started the test if started with a user token.",+ "created": "Date and time when the test run was started.",+ "ended": "Date and time when the test run ended. Unset if the test is still running.",+ "note": "User-defined note for the test run.",+ "retention_expiry": "Timestamp after which the test run results are deleted.",+ "cost": "Test run cost details. The cost is available only after test run validation.",+ "status": "Current test run status.",+ "status_details": "Details of the current test run status.",+ "status_history": "List of test run status objects sorted by the status start time.",+ "distribution": "Load zones configured for the test and the corresponding distribution percentages.",+ "result": "Test run result: passed, failed, or error.",+ "options": "The original options object if available.",+ "max_vus": "The maximum number of total VUs (browser and protocol) at any stage of the execution plan.",+ "max_browser_vus": "The maximum number of browser VUs at any stage of the execution plan.",+ "estimated_duration": "The estimated duration of the test run in seconds.",+ "execution_duration": "The real billable duration of the test run in seconds.",+ "is_starred": "Whether the test run is starred for quick access.",+ },+ },+ "projects": {+ "description": "A project groups load tests, test runs, and members within a Grafana Cloud k6 stack.",+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",+ "columns": {+ "id": "Project ID.",+ "name": "Project name.",+ "is_default": "Whether this project is used as default when no explicit project ID is provided.",+ "grafana_folder_uid": "Grafana folder UID.",+ "created": "The date when the project was created.",+ "updated": "The date when the project was last updated.",+ "labels": "Project labels.",+ },+ },+ "load_tests": {+ "description": "A load test definition (script and configuration) that can be run to produce test runs.",+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",+ "columns": {+ "id": "ID of the load test.",+ "project_id": "ID of the parent project.",+ "name": "Unique name of the test within the project.",+ "baseline_test_run_id": "ID of a baseline test run used for results comparison.",+ "k6_version": "Identifier of the k6 version used to run the test.",+ "created": "The date when the test was created.",+ "updated": "The date when the test was last updated.",+ },+ },+ "schedules": {+ "description": "A schedule that triggers a load test to run once or on a recurring basis.",+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",+ "columns": {+ "id": "ID of the schedule.",+ "load_test_id": "ID of the test to run.",+ "starts": "The date on which the schedule will start running the test.",+ "recurrence_rule": "The schedule recurrence settings. Null if the test runs only once.",+ "cron": "The cron schedule to trigger the test periodically. Null if the test runs only once.",+ "deactivated": "Whether the schedule is deactivated.",+ "next_run": "The date of the next scheduled test run. Null if the schedule is expired.",+ "created_by": "The email of the user who created the schedule if applicable.",+ },+ },+ "load_zones": {+ "description": "A geographic load zone that test traffic can be generated from.",+ "docs_url": "https://grafana.com/docs/grafana-cloud/testing/k6/reference/cloud-rest-api/",+ "columns": {+ "id": "ID of the load zone.",+ "name": "Name of the load zone.",+ "k6_load_zone_id": "ID used to identify the load zone in the k6 scripts.",+ "available": "Whether the load zone can be used to start tests.",+ "custom_load_runner_image": "Custom load runner image. Only set for private load zones.",+ "public": "Whether the load zone is public or private.",+ },+ },+}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.pynew file mode 100644index 000000000000..dd62f18e36c3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/k6_cloud.py@@ -0,0 +1,240 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urljoin, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import (+ K6_CLOUD_ENDPOINTS,+ 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+++class K6CloudRetryableError(Exception):+ pass+++class K6CloudResumeConfig:+ # Absolute `@nextLink` URL to fetch next. The server encodes the original filter and+ # `$skip` offset into it, so resuming replays exactly where we stopped.+ next_url: str+++def _get_headers(api_token: str, stack_id: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "X-Stack-Id": stack_id,+ "Accept": "application/json",+ }+++def _format_rfc3339(value: Any) -> str:+ """Format an incremental value as the RFC 3339 timestamp k6's `created_after` expects."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")+ return str(value)+++def _build_initial_params(+ config: K6CloudEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ params: dict[str, str] = {}++ if config.paginated:+ params["$top"] = str(PAGE_SIZE)++ if config.order_by:+ params["$orderby"] = config.order_by++ if config.time_filter_param and should_use_incremental_field and db_incremental_field_last_value is not None:+ # `created_after` is inclusive, so the boundary row is re-fetched each sync and+ # deduped on the `id` primary key by the merge.+ params[config.time_filter_param] = _format_rfc3339(db_incremental_field_last_value)++ return params+++@retry(+ retry=retry_if_exception_type((K6CloudRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: Optional[dict[str, str]],+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise K6CloudRetryableError(f"k6 Cloud API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"k6 Cloud API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str, stack_id: str, schema_name: Optional[str] = None) -> tuple[bool, bool]:+ """Probe Grafana Cloud k6 to confirm the token + stack id work.++ Returns ``(is_valid, is_forbidden)``. ``is_forbidden`` distinguishes a 403+ (token is genuine but lacks access) from a 401 (bad token) so the caller can+ 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:+ # For a specific schema, probe that endpoint so the check reflects real access.+ params = {"$top": "1"} if config.paginated else {}+ url = f"{K6_CLOUD_BASE_URL}{config.path}"+ if params:+ url = f"{url}?{urlencode(params)}"+ else:+ # `/auth` validates the token and stack access without touching any resource.+ url = f"{K6_CLOUD_BASE_URL}/auth"++ try:+ with make_tracked_session() as session:+ response = session.get(url, headers=_get_headers(api_token, stack_id), timeout=REQUEST_TIMEOUT_SECONDS)+ except Exception:+ return False, False++ if response.status_code == 403:+ return False, True++ return response.status_code == 200, False+++def get_rows(+ api_token: str,+ stack_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[K6CloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = K6_CLOUD_ENDPOINTS[endpoint]+ headers = _get_headers(api_token, stack_id)++ initial_params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ # The `@nextLink` is an absolute URL that already carries the filter + `$skip` offset,+ # so on resume (and on every page after the first) we fetch it with no extra params.+ if resume_config is not None and resume_config.next_url:+ # Resume state comes back from Redis, so re-pin it to the k6 origin before we send the token.+ url: str = _require_k6_origin(resume_config.next_url)+ params: Optional[dict[str, str]] = None+ logger.debug(f"k6 Cloud: resuming {endpoint} from saved next link")+ else:+ url = f"{K6_CLOUD_BASE_URL}{config.path}"+ params = initial_params++ # One session reused across every page so urllib3 keeps the connection alive; the `with`+ # closes it promptly even if the consumer abandons the generator early.+ with make_tracked_session() as session:+ while True:+ data = _fetch_page(session, url, params, headers, logger)++ # Fail fast if the payload is missing `value` — an empty table is a bug, not a valid sync.+ items = data["value"]+ next_url = data.get("@nextLink")++ if items:+ yield items+ # Save state only after yielding, so a crash re-yields the last page rather+ # than skipping it (merge dedupes on the primary key). Only persist when more+ # pages remain — there's nothing to resume into on the final page.+ if config.paginated and next_url:+ resumable_source_manager.save_state(K6CloudResumeConfig(next_url=_absolute_url(url, next_url)))++ if not config.paginated or not next_url:+ break++ # Advance to the next page before the next fetch, otherwise we loop on this page.+ url = _absolute_url(url, next_url)+ params = None+++def _require_k6_origin(url: str) -> str:+ """Reject any pagination/resume URL that doesn't point at the k6 API origin.++ `@nextLink` is attacker-influenceable response data and resume state is loaded back from+ Redis, so before we send the bearer token + stack id to a URL we confirm its scheme is+ https and its host is the k6 API host. Otherwise a tampered link could exfiltrate the+ stored credential to an attacker-controlled or internal server.+ """+ parsed = urlparse(url)+ if parsed.scheme != "https" or parsed.hostname != K6_CLOUD_HOST:+ raise ValueError(f"k6 Cloud: refusing to follow non-k6 URL: {url}")+ return url+++def _absolute_url(current_url: str, next_link: str) -> str:+ """Resolve `@nextLink` against the current URL, then pin it to the k6 origin.++ Relative links are joined onto the current (already-pinned) URL; absolute links are taken+ as-is. Either way the result must resolve to the k6 API host — `_require_k6_origin` rejects+ a tampered link before we send credentials to it.+ """+ resolved = next_link if next_link.startswith(("http://", "https://")) else urljoin(current_url, next_link)+ return _require_k6_origin(resolved)+++def k6_cloud_source(+ api_token: str,+ stack_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[K6CloudResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = K6_CLOUD_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ stack_id=stack_id,+ 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,+ ),+ 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,+ )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.pynew file mode 100644index 000000000000..2d4d42fff39b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/settings.py@@ -0,0 +1,103 @@+from dataclasses import dataclass+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class K6CloudEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField]+ # Stable datetime field used for partitioning. Must never change for a row+ # (so `created`, never `updated`). `None` disables partitioning.+ partition_key: Optional[str] = None+ # Name of the server-side timestamp filter query param (e.g. `created_after`).+ # Only set when the API genuinely filters on it — this is what enables+ # incremental sync. `None` => full refresh only.+ time_filter_param: Optional[str] = None+ # Value sent as `$orderby` for a stable ascending page order. Only set on+ # endpoints that document the field — the top-level `test_runs` endpoint+ # rejects `$orderby`, so it stays `None` there.+ order_by: Optional[str] = None+ # Whether the endpoint uses `$skip`/`$top` offset pagination (followed via the+ # `@nextLink` URL in the response). `load_zones` returns every row in one page.+ paginated: bool = True+ should_sync_default: bool = True+++def _created_incremental_field() -> list[IncrementalField]:+ return [+ {+ "label": "created",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++# 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`+ # timestamp. The endpoint offers no `$orderby`, but it is offset-paginated+ # ($skip/$top), which requires a deterministic server order; k6 assigns+ # monotonically increasing ids at creation and the documented sibling endpoint+ # `/cloud/v6/load_tests/{id}/test_runs` defaults to ascending `created`, so we+ # treat the collection as ascending-by-creation and advance the cursor on `created`.+ "test_runs": K6CloudEndpointConfig(+ name="test_runs",+ path="/test_runs",+ primary_keys=["id"],+ partition_key="created",+ time_filter_param="created_after",+ incremental_fields=_created_incremental_field(),+ ),+ # Projects and Load tests both carry a stable `created` timestamp but expose no+ # server-side time filter (only `$orderby`/`name`), so they are full refresh only.+ # `$orderby=created` keeps offset pagination stable across pages.+ "projects": K6CloudEndpointConfig(+ name="projects",+ path="/projects",+ primary_keys=["id"],+ partition_key="created",+ order_by="created",+ incremental_fields=[],+ ),+ "load_tests": K6CloudEndpointConfig(+ name="load_tests",+ path="/load_tests",+ primary_keys=["id"],+ partition_key="created",+ order_by="created",+ incremental_fields=[],+ ),+ # Schedules have no `created` timestamp (only `starts`/`next_run`, both mutable), so+ # partitioning is disabled. Offset-paginated, no time filter -> full refresh.+ "schedules": K6CloudEndpointConfig(+ name="schedules",+ path="/schedules",+ primary_keys=["id"],+ incremental_fields=[],+ ),+ # Load zones is a small reference table returned in a single page (no $skip/$top,+ # no @nextLink) with no timestamps. Full refresh, off by default as lookup data.+ "load_zones": K6CloudEndpointConfig(+ name="load_zones",+ path="/load_zones",+ primary_keys=["id"],+ incremental_fields=[],+ paginated=False,+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(K6_CLOUD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in K6_CLOUD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/source.pyindex 9add794270e5..3c6c9d66d43f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/source.py@@ -1,30 +1,166 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import K6CloudSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.k6_cloud import (+ K6CloudResumeConfig,+ k6_cloud_source,+ validate_credentials as validate_k6_cloud_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ K6_CLOUD_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class K6CloudSource(SimpleSource[K6CloudSourceConfig]):+class K6CloudSource(ResumableSource[K6CloudSourceConfig, K6CloudResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.K6CLOUD+ @property+ def connection_host_fields(self) -> list[str]:+ # `stack_id` selects which Grafana Cloud k6 stack the stored bearer token is sent to, so+ # retargeting it must re-require the token — otherwise the credential could be reused+ # against a different stack.+ return ["stack_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.K6_CLOUD,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="K6 Cloud",+ label="Grafana Cloud k6",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Grafana Cloud k6 API token and stack ID to pull your load testing data into the PostHog Data warehouse.++Create a Personal API token (or use a Grafana Stack API token) and find your stack ID under **Testing & synthetics → Performance → Settings** in Grafana Cloud.""",iconPath="/static/services/k6_cloud.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/k6-cloud",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Personal or Stack API token",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="stack_id",+ label="Stack ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="12345",+ secret=False,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid/revoked token or wrong stack id surfaces as a requests HTTPError when+ # `fetch_page` calls `raise_for_status()`. Retrying can never fix a credential+ # problem, so stop the sync. Match the stable status text + base host, not the+ # per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.k6.io": "Your Grafana Cloud k6 API token is invalid or has been revoked. Create a new token, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.k6.io": "Your Grafana Cloud k6 API token does not have access to this data or stack. Check the token and stack ID, then reconnect.",+ }++ def get_schemas(+ self,+ config: K6CloudSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = K6_CLOUD_ENDPOINTS[endpoint]+ has_incremental = endpoint_config.time_filter_param is not None and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(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: K6CloudSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ is_valid, is_forbidden = validate_k6_cloud_credentials(config.api_token, config.stack_id, schema_name)+ if is_valid:+ return True, None++ # A 403 at source-create means the token is genuine but lacks access to the probed+ # resource — accept it so users can still connect and pick the tables they can read.+ # For a specific schema the missing access is real, so reject it.+ if is_forbidden and schema_name is None:+ return True, None+ if is_forbidden:+ return False, f"Your k6 API token does not have access to the {schema_name} table"++ return False, "Invalid k6 API token or stack ID"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[K6CloudResumeConfig]:+ return ResumableSourceManager[K6CloudResumeConfig](inputs, K6CloudResumeConfig)++ def source_for_pipeline(+ self,+ config: K6CloudSourceConfig,+ resumable_source_manager: ResumableSourceManager[K6CloudResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return k6_cloud_source(+ api_token=config.api_token,+ stack_id=config.stack_id,+ 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,+ )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.pynew file mode 100644index 000000000000..e750bb148355--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud.py@@ -0,0 +1,279 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud import k6_cloud+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.k6_cloud import (+ K6CloudResumeConfig,+ _absolute_url,+ _build_initial_params,+ _format_rfc3339,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import K6_CLOUD_ENDPOINTS+++class TestFormatRfc3339:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),+ ("microseconds", datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),+ ("string_passthrough", "some-cursor", "some-cursor"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ result = _format_rfc3339(value)+ assert result == expected+ assert "+00:00" not in result+++class TestBuildInitialParams:+ def test_test_runs_incremental_adds_created_after_and_no_orderby(self) -> None:+ # The top-level test_runs endpoint rejects $orderby, so it must never be sent there.+ params = _build_initial_params(+ K6_CLOUD_ENDPOINTS["test_runs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert params["created_after"] == "2026-03-04T02:58:14.000Z"+ assert params["$top"] == "1000"+ assert "$orderby" not in params++ def test_test_runs_full_refresh_has_no_time_filter(self) -> None:+ params = _build_initial_params(+ K6_CLOUD_ENDPOINTS["test_runs"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert "created_after" not in params++ def test_projects_sends_orderby_but_no_time_filter(self) -> None:+ # Projects has no server-side time filter, so passing a last value must not add one.+ params = _build_initial_params(+ K6_CLOUD_ENDPOINTS["projects"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params["$orderby"] == "created"+ assert "created_after" not in params++ def test_load_zones_is_not_paginated(self) -> None:+ params = _build_initial_params(+ K6_CLOUD_ENDPOINTS["load_zones"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert "$top" not in params+++class TestAbsoluteUrl:+ @parameterized.expand(+ [+ (+ "absolute_https",+ "https://api.k6.io/cloud/v6/test_runs",+ "https://api.k6.io/cloud/v6/test_runs?$skip=1000",+ "https://api.k6.io/cloud/v6/test_runs?$skip=1000",+ ),+ (+ "relative_path",+ "https://api.k6.io/cloud/v6/test_runs",+ "/cloud/v6/test_runs?$skip=1000",+ "https://api.k6.io/cloud/v6/test_runs?$skip=1000",+ ),+ ]+ )+ def test_absolute_url(self, _name: str, current: str, next_link: str, expected: str) -> None:+ assert _absolute_url(current, next_link) == expected++ @parameterized.expand(+ [+ ("other_host", "https://evil.example.com/steal"),+ ("relative_to_other_host", "//evil.example.com/steal"),+ ("http_scheme", "http://api.k6.io/cloud/v6/test_runs"),+ ]+ )+ def test_rejects_non_k6_next_link(self, _name: str, next_link: str) -> None:+ # A tampered `@nextLink` must never redirect the credential-bearing request off the k6 origin.+ with pytest.raises(ValueError):+ _absolute_url("https://api.k6.io/cloud/v6/test_runs", next_link)+++class _FakeResumableManager:+ def __init__(self, state: K6CloudResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[K6CloudResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> K6CloudResumeConfig | None:+ return self._state++ def save_state(self, data: K6CloudResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str) -> list[dict]:+ def fake_fetch(session: Any, url: str, params: Any, headers: Any, logger: Any) -> dict:+ return pages[url]++ monkeypatch.setattr(k6_cloud, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ api_token="tok",+ stack_id="1",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_follows_next_link_pagination(self, monkeypatch: Any) -> None:+ next_url = "https://api.k6.io/cloud/v6/test_runs?$skip=1000&$top=1000"+ pages = {+ "https://api.k6.io/cloud/v6/test_runs": {+ "value": [{"id": 1}, {"id": 2}],+ "@nextLink": next_url,+ },+ next_url: {"value": [{"id": 3}], "@nextLink": None},+ }+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, pages, "test_runs")+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ def test_saves_state_after_each_page_except_last(self, monkeypatch: Any) -> None:+ next_url = "https://api.k6.io/cloud/v6/test_runs?$skip=1000&$top=1000"+ pages = {+ "https://api.k6.io/cloud/v6/test_runs": {"value": [{"id": 1}], "@nextLink": next_url},+ next_url: {"value": [{"id": 2}], "@nextLink": None},+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages, "test_runs")+ # State is saved once (after the first page); the final page has no next link to persist.+ assert [s.next_url for s in manager.saved] == [next_url]++ def test_resumes_from_saved_next_link(self, monkeypatch: Any) -> None:+ resume_url = "https://api.k6.io/cloud/v6/test_runs?$skip=2000&$top=1000"+ pages = {resume_url: {"value": [{"id": 9}], "@nextLink": None}}+ manager = _FakeResumableManager(K6CloudResumeConfig(next_url=resume_url))+ rows = self._collect(manager, monkeypatch, pages, "test_runs")+ assert rows == [{"id": 9}]++ def test_rejects_poisoned_resume_url(self, monkeypatch: Any) -> None:+ # Resume state is loaded from Redis; a poisoned next link must not leak credentials off-origin.+ manager = _FakeResumableManager(K6CloudResumeConfig(next_url="https://evil.example.com/steal"))+ with pytest.raises(ValueError):+ self._collect(manager, monkeypatch, {}, "test_runs")++ def test_missing_value_key_raises(self, monkeypatch: Any) -> None:+ # A 200 whose body lacks `value` is an unexpected format — fail loud rather than empty the table.+ pages = {"https://api.k6.io/cloud/v6/load_zones": {"@nextLink": None}}+ manager = _FakeResumableManager()+ with pytest.raises(KeyError):+ self._collect(manager, monkeypatch, pages, "load_zones")++ def test_non_paginated_endpoint_reads_single_page(self, monkeypatch: Any) -> None:+ # load_zones returns everything in one response with no @nextLink and never saves state.+ pages = {+ "https://api.k6.io/cloud/v6/load_zones": {"value": [{"id": 1}, {"id": 2}]},+ }+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, pages, "load_zones")+ assert rows == [{"id": 1}, {"id": 2}]+ assert manager.saved == []+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 503),+ ]+ )+ def test_retryable_status_is_retried_then_succeeds(self, _name: str, status: int) -> None:+ bad = MagicMock()+ bad.status_code = status+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"value": []}++ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(k6_cloud._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = k6_cloud._fetch_page(session, "https://api.k6.io/cloud/v6/test_runs", None, {}, MagicMock())++ assert result == {"value": []}+ assert session.get.call_count == 2++ def test_client_error_raises_immediately(self) -> None:+ # A 401/403 is not retryable — raise_for_status must surface it on the first attempt.+ error_response = requests.Response()+ error_response.status_code = 401+ bad = MagicMock()+ bad.status_code = 401+ bad.ok = False+ bad.text = "unauthorized"+ bad.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=error_response)++ session = MagicMock()+ session.get.return_value = bad++ with pytest.raises(requests.HTTPError):+ k6_cloud._fetch_page(session, "https://api.k6.io/cloud/v6/test_runs", None, {}, MagicMock())+ assert session.get.call_count == 1+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, (True, False)),+ ("bad_token", 401, None, (False, False)),+ ("forbidden", 403, None, (False, True)),+ ("forbidden_schema", 403, "test_runs", (False, True)),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, schema_name: str | None, expected: tuple[bool, bool]+ ) -> None:+ response = MagicMock()+ response.status_code = status+ # `validate_credentials` opens the session as a context manager, so the `with` target+ # must be the same mock we configure `.get` on.+ session = MagicMock()+ session.__enter__.return_value = session+ session.get.return_value = response++ with patch.object(k6_cloud, "make_tracked_session", return_value=session):+ assert validate_credentials("tok", "1", schema_name) == expected++ def test_network_error_is_invalid_not_forbidden(self) -> None:+ session = MagicMock()+ session.__enter__.return_value = session+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(k6_cloud, "make_tracked_session", return_value=session):+ assert validate_credentials("tok", "1") == (False, False)++ def test_schemaless_probe_hits_auth_endpoint(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.__enter__.return_value = session+ session.get.return_value = response+ with patch.object(k6_cloud, "make_tracked_session", return_value=session):+ validate_credentials("tok", "1")+ assert session.get.call_args[0][0].endswith("/cloud/v6/auth")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud_source.pynew file mode 100644index 000000000000..00b5e9bd82a1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/k6_cloud/tests/test_k6_cloud_source.py@@ -0,0 +1,153 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import K6CloudSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.k6_cloud import K6CloudResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.source import K6CloudSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"test_runs"}+++def _make_inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = overrides.get("schema_name", "test_runs")+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)+ return inputs+++class TestK6CloudSource:+ def setup_method(self) -> None:+ self.source = K6CloudSource()+ self.team_id = 123+ self.config = K6CloudSourceConfig(api_token="tok", stack_id="12345")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.K6CLOUD++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "K6Cloud"+ assert config.label == "Grafana Cloud k6"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/k6-cloud"+ assert len(config.fields) == 2++ api_token_field = config.fields[0]+ assert isinstance(api_token_field, SourceFieldInputConfig)+ assert api_token_field.name == "api_token"+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_token_field.secret is True++ stack_id_field = config.fields[1]+ assert isinstance(stack_id_field, SourceFieldInputConfig)+ assert stack_id_field.name == "stack_id"+ assert stack_id_field.secret is False++ def test_stack_id_is_a_connection_host_field(self) -> None:+ # `stack_id` routes the stored token to a specific k6 stack, so changing it must re-require+ # the secret — guards against credential retargeting across stacks.+ assert self.source.connection_host_fields == ["stack_id"]++ def test_get_schemas_matches_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ expected_incremental = endpoint in INCREMENTAL_ENDPOINTS+ assert schema.supports_incremental is expected_incremental+ assert schema.supports_append is expected_incremental+ if expected_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["created"]+ else:+ assert schema.incremental_fields == []++ def test_load_zones_off_by_default(self) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == "load_zones")+ assert schema.should_sync_default is False++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["projects"])+ assert [s.name for s in schemas] == ["projects"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog -> the public docs table list must render.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @pytest.mark.parametrize("expected_key", ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "mock_return, schema_name, expected_valid, expected_has_message",+ [+ ((True, False), None, True, False),+ ((False, False), None, False, True), # 401 bad token/stack+ ((False, True), None, True, False), # 403 at source-create -> accepted+ ((False, True), "test_runs", False, True), # 403 for a specific schema -> rejected+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.source.validate_k6_cloud_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: tuple[bool, bool],+ schema_name: str | None,+ expected_valid: bool,+ expected_has_message: bool,+ ) -> None:+ mock_validate.return_value = mock_return+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ assert is_valid is expected_valid+ assert (message is not None) is expected_has_message+ mock_validate.assert_called_once_with(self.config.api_token, self.config.stack_id, schema_name)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is K6CloudResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.source.k6_cloud_source")+ def test_source_for_pipeline_passes_arguments(self, mock_k6_cloud_source: mock.MagicMock) -> None:+ inputs = _make_inputs(+ schema_name="test_runs",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_k6_cloud_source.call_args+ assert kwargs["api_token"] == self.config.api_token+ assert kwargs["stack_id"] == self.config.stack_id+ assert kwargs["endpoint"] == "test_runs"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.k6_cloud.source.k6_cloud_source")+ def test_source_for_pipeline_drops_last_value_when_not_incremental(+ self, mock_k6_cloud_source: mock.MagicMock+ ) -> None:+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="ignored")+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ _, kwargs = mock_k6_cloud_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None