: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 kubecost import source (#71157)
Tom Owers6451ca08799b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d04b56705745..85a8fe3554cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -259,6 +259,7 @@ the row lists both.| klaviyo | HTTP | requests | ✅ || koyeb | HTTP | requests | ✅ || kong_konnect | HTTP | requests | ✅ |+| kubecost | HTTP | requests | ✅ || lago | HTTP | requests | ✅ || lambda_labs | HTTP | requests | ✅ || langfuse | HTTP | requests | ✅ |@@ -722,7 +723,6 @@ doesn't conflict with concurrent PRs.- klaus- knock- koyeb-- kubecost- kyve- lacework- lambda_labsdiff --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 37ad0e67d821..8eab3fc864a5 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@@ -2291,7 +2291,8 @@ class KoyebSourceConfig(config.Config):@config.configclass KubecostSourceConfig(config.Config):- pass+ host: str+ api_key: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.pynew file mode 100644index 000000000000..48198629eeb5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py@@ -0,0 +1,86 @@+"""Canonical, documentation-sourced descriptions for Kubecost endpoints and columns.++Sourced from the official Kubecost API reference (https://docs.kubecost.com/apis).+Keyed by the endpoint names in `settings.py` `KUBECOST_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Kubecost table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+ CanonicalEndpoint,+)++_ALLOCATION_DOCS_URL = "https://docs.kubecost.com/apis/monitoring-apis/api-allocation"++_ALLOCATION_COLUMNS = {+ "key": "The allocation's name in the queried aggregation (with special entries like __idle__ for unallocated cluster capacity). Unique per window.",+ "window_start": "Start of the one-day query window this row covers (RFC3339). Used as the incremental cursor and partition key.",+ "window_end": "End of the one-day query window this row covers (RFC3339).",+ "name": "The name of the allocation, matching the aggregation level (namespace, controller, or pod).",+ "properties": "Kubernetes metadata for the allocation: cluster, node, namespace, controller, pod, container, labels, and annotations.",+ "window": "The queried time window the allocation was computed over, with start and end timestamps.",+ "start": "Timestamp of the first observed activity for the allocation within the window.",+ "end": "Timestamp of the last observed activity for the allocation within the window.",+ "minutes": "Number of minutes the allocation was running during the window.",+ "cpuCores": "Average number of CPU cores allocated while running.",+ "cpuCoreHours": "Cumulative CPU core-hours allocated over the window.",+ "cpuCost": "Cost of the CPU allocated to the workload over the window.",+ "cpuEfficiency": "Ratio of CPU usage to CPU requested (usage / requested).",+ "gpuCount": "Average number of GPUs allocated while running.",+ "gpuHours": "Cumulative GPU-hours allocated over the window.",+ "gpuCost": "Cost of the GPUs allocated to the workload over the window.",+ "ramBytes": "Average bytes of RAM allocated while running.",+ "ramByteHours": "Cumulative RAM byte-hours allocated over the window.",+ "ramCost": "Cost of the RAM allocated to the workload over the window.",+ "ramEfficiency": "Ratio of RAM usage to RAM requested (usage / requested).",+ "pvBytes": "Average bytes of persistent volume storage allocated while running.",+ "pvCost": "Cost of persistent volume storage allocated to the workload over the window.",+ "networkCost": "Cost of network transfer attributed to the workload over the window.",+ "loadBalancerCost": "Cost of load balancers attributed to the workload over the window.",+ "sharedCost": "Shared costs (e.g. cluster overhead) distributed to the allocation.",+ "externalCost": "Out-of-cluster costs attributed to the allocation via external billing integrations.",+ "totalCost": "Total cumulative cost of the allocation over the window.",+ "totalEfficiency": "Cost-weighted average of CPU and RAM efficiency.",+}+++def _allocation_entry(level: str) -> CanonicalEndpoint:+ return {+ "description": f"Kubernetes workload cost and usage from the Kubecost Allocation API, aggregated by {level} — one row per {level} per day.",+ "docs_url": _ALLOCATION_DOCS_URL,+ "columns": dict(_ALLOCATION_COLUMNS),+ }+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "allocation_by_namespace": _allocation_entry("namespace"),+ "allocation_by_controller": _allocation_entry("controller"),+ "allocation_by_pod": _allocation_entry("pod"),+ "assets": {+ "description": "Cluster infrastructure costs from the Kubecost Assets API — one row per asset (node, disk, network, load balancer, cluster management fee) per day.",+ "docs_url": "https://docs.kubecost.com/apis/monitoring-apis/assets-api",+ "columns": {+ "key": "The asset's fully qualified identifier (provider/account/service/cluster/type/…). Unique per window.",+ "window_start": "Start of the one-day query window this row covers (RFC3339). Used as the incremental cursor and partition key.",+ "window_end": "End of the one-day query window this row covers (RFC3339).",+ "type": "The asset type: Node, Disk, Network, LoadBalancer, ClusterManagement, or Cloud.",+ "properties": "Asset metadata: cloud provider, account, project, service, cluster, and name.",+ "labels": "Kubernetes and cloud provider labels attached to the asset.",+ "window": "The queried time window the asset cost was computed over, with start and end timestamps.",+ "start": "Timestamp of the first observed activity for the asset within the window.",+ "end": "Timestamp of the last observed activity for the asset within the window.",+ "minutes": "Number of minutes the asset was running during the window.",+ "cpuCores": "Number of CPU cores on the asset (nodes).",+ "cpuCoreHours": "Cumulative CPU core-hours provided by the asset over the window.",+ "cpuCost": "Cost of the asset's CPU over the window.",+ "gpuCost": "Cost of the asset's GPUs over the window.",+ "ramBytes": "Bytes of RAM on the asset (nodes).",+ "ramByteHours": "Cumulative RAM byte-hours provided by the asset over the window.",+ "ramCost": "Cost of the asset's RAM over the window.",+ "discount": "Percentage discount applied to the asset's cost (e.g. negotiated or sustained-use discounts).",+ "preemptible": "Whether the node is a preemptible/spot instance (nodes).",+ "adjustment": "Cost adjustment applied during reconciliation with cloud-billing data.",+ "totalCost": "Total cumulative cost of the asset over the window.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.pynew file mode 100644index 000000000000..04eacff45eba--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py@@ -0,0 +1,270 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import 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.kubecost.settings import (+ DEFAULT_BACKFILL_DAYS,+ INCREMENTAL_LOOKBACK_DAYS,+ KUBECOST_ENDPOINTS,+)++# Kubecost aggregates cost data at query time, so responses for large clusters can be slow.+REQUEST_TIMEOUT_SECONDS = 180+MAX_RETRY_ATTEMPTS = 5+++class KubecostRetryableError(Exception):+ pass+++class KubecostResumeConfig:+ # The next unfetched day (yyyy-mm-dd) of the day-by-day window walk.+ next_date: Optional[str] = None+++def normalize_host(host: str) -> str:+ """Normalize the Kubecost API URL and reject anything that isn't plain http(s).++ Accepts the address with or without the trailing `/model` prefix the cost-model+ API is served under (`http://kubecost.example.com` and+ `http://kubecost.example.com/model` both work).+ """+ host = host.strip()+ if not host:+ raise ValueError("Kubecost API URL is required")+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ if host.endswith("/model"):+ host = host[: -len("/model")]+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid Kubecost API URL: {host}")+ return host+++def hostname_of(host: str) -> str:+ return urlparse(normalize_host(host)).hostname or ""+++_PLAINTEXT_API_KEY_ERROR = (+ "An API key can only be sent to an https:// URL. Use HTTPS for the Kubecost API URL or remove the API key."+)+++def _check_api_key_transport(base_url: str, api_key: Optional[str]) -> str | None:+ """The API key rides an `Authorization: Bearer` header, so it must never go over plaintext HTTP."""+ if api_key and not base_url.startswith("https://"):+ return _PLAINTEXT_API_KEY_ERROR+ return None+++def _get_session(api_key: Optional[str]) -> requests.Session:+ # `host` is user-supplied, so pin redirects off: validation and the outbound+ # request must stay on the same target (SSRF defense-in-depth).+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else None+ return make_tracked_session(+ headers=headers,+ redact_values=(api_key,) if api_key else (),+ allow_redirects=False,+ )+++def _to_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _day_window(day: date) -> tuple[str, str]:+ start = f"{day.isoformat()}T00:00:00Z"+ end = f"{(day + timedelta(days=1)).isoformat()}T00:00:00Z"+ return start, end+++def validate_credentials(host: str, api_key: Optional[str]) -> tuple[bool, str | None]:+ """Confirm the cost-model API is reachable and the credentials (if any) are accepted."""+ base_url = normalize_host(host)+ transport_error = _check_api_key_transport(base_url, api_key)+ if transport_error is not None:+ return False, transport_error++ try:+ response = _get_session(api_key).get(+ f"{base_url}/model/allocation",+ params={"window": "1d", "aggregate": "namespace", "accumulate": "true"},+ timeout=30,+ )+ except Exception:+ return False, "Unable to reach the Kubecost API. Check that the URL is correct and publicly reachable."++ if response.status_code in (401, 403):+ return False, "Kubecost authentication failed. Please check your API key."+ if response.status_code != 200:+ return False, f"Kubecost API returned an unexpected status ({response.status_code})."++ try:+ body = response.json()+ except ValueError:+ return False, "The URL did not return a Kubecost API response. Check that it points at the cost-model API."+ if not isinstance(body, dict) or body.get("code") != 200:+ message = body.get("message") if isinstance(body, dict) else None+ return False, f"Kubecost API error: {message or 'unexpected response'}"++ return True, None+++def _flatten_result_sets(data: Any, requested_window: tuple[str, str]) -> list[dict[str, Any]]:+ """Flatten Allocation/Assets result sets (dicts keyed by allocation/asset name) into rows.++ Windows with no data (e.g. beyond ETL retention) come back as ``data: [null]``,+ so null/non-dict sets are skipped rather than treated as errors.+ """+ requested_start, requested_end = requested_window+ rows: list[dict[str, Any]] = []+ if not isinstance(data, list):+ return rows+ for result_set in data:+ if not isinstance(result_set, dict):+ continue+ for key, item in result_set.items():+ if not isinstance(item, dict):+ continue+ window = item.get("window")+ if not isinstance(window, dict):+ window = {}+ rows.append(+ {+ **item,+ "key": key,+ "window_start": window.get("start") or requested_start,+ "window_end": window.get("end") or requested_end,+ }+ )+ return rows+++def get_rows(+ host: str,+ api_key: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[KubecostResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = KUBECOST_ENDPOINTS[endpoint]+ base_url = normalize_host(host)+ transport_error = _check_api_key_transport(base_url, api_key)+ if transport_error is not None:+ raise ValueError(transport_error)+ session = _get_session(api_key)+ url = f"{base_url}{config.path}"++ @retry(+ retry=retry_if_exception_type((KubecostRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def call(window: str) -> Any:+ response = session.get(+ url,+ params={**config.params, "window": window, "accumulate": "true"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise KubecostRetryableError(f"Kubecost API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"Kubecost API error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ body = response.json()+ if not isinstance(body, dict) or body.get("code") != 200:+ message = body.get("message") if isinstance(body, dict) else body+ raise ValueError(f"Kubecost API error: {message}")+ return body.get("data")++ # No cursor or pagination: the query window itself is the incremental filter, so we+ # walk contiguous one-day windows oldest-first. Recent days restate as cloud-billing+ # reconciliation lands, so incremental runs re-pull a trailing lookback window.+ today = datetime.now(tz=UTC).date()+ start = today - timedelta(days=DEFAULT_BACKFILL_DAYS)+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ start = watermark - timedelta(days=INCREMENTAL_LOOKBACK_DAYS)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.next_date:+ resumed = _to_date(resume_config.next_date)+ if resumed is not None and resumed > start:+ start = resumed+ logger.debug(f"Kubecost: resuming {endpoint} from {start.isoformat()}")++ day = start+ while day <= today:+ window_start, window_end = _day_window(day)+ data = call(f"{window_start},{window_end}")+ rows = _flatten_result_sets(data, (window_start, window_end))+ if rows:+ yield rows++ day = day + timedelta(days=1)+ if day <= today:+ # Save state AFTER yielding so a crash re-yields the in-flight day+ # (merge dedupes on (key, window_start)).+ resumable_source_manager.save_state(KubecostResumeConfig(next_date=day.isoformat()))+++def kubecost_source(+ host: str,+ api_key: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[KubecostResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ api_key=api_key,+ 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,+ ),+ # The result-set key is only unique within one window, so the window start is+ # part of the key. `window_start` never changes for a given row, making it a+ # stable partition key too.+ primary_keys=["key", "window_start"],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=["window_start"],+ # Days are walked oldest-first; the cursor only moves forward.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.pynew file mode 100644index 000000000000..825f88ad839a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py@@ -0,0 +1,56 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Default history pulled on the first sync. Days beyond the deployment's configured+# ETL retention return empty sets, so over-asking is harmless.+DEFAULT_BACKFILL_DAYS = 90+# Kubecost restates recent days as cloud-billing reconciliation lands, so incremental+# syncs re-pull a trailing window and merge on (key, window_start).+INCREMENTAL_LOOKBACK_DAYS = 3++_WINDOW_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "window_start",+ "type": IncrementalFieldType.DateTime,+ "field": "window_start",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class KubecostEndpointConfig:+ name: str+ path: str+ # Extra query params sent on every request (e.g. the Allocation API's `aggregate`).+ params: dict[str, str] = field(default_factory=dict)+++KUBECOST_ENDPOINTS: dict[str, KubecostEndpointConfig] = {+ "allocation_by_namespace": KubecostEndpointConfig(+ name="allocation_by_namespace",+ path="/model/allocation",+ params={"aggregate": "namespace"},+ ),+ "allocation_by_controller": KubecostEndpointConfig(+ name="allocation_by_controller",+ path="/model/allocation",+ params={"aggregate": "controller"},+ ),+ "allocation_by_pod": KubecostEndpointConfig(+ name="allocation_by_pod",+ path="/model/allocation",+ params={"aggregate": "pod"},+ ),+ "assets": KubecostEndpointConfig(+ name="assets",+ path="/model/assets",+ ),+}++ENDPOINTS = tuple(KUBECOST_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: list(_WINDOW_INCREMENTAL_FIELDS) for name in KUBECOST_ENDPOINTS+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/source.pyindex e1d65f5dc0a7..4c2c9d7b9054 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/source.py@@ -1,30 +1,160 @@-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.mixins import ValidateDatabaseHostMixinfrom 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 KubecostSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.kubecost import (+ KubecostResumeConfig,+ hostname_of,+ kubecost_source,+ validate_credentials as validate_kubecost_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class KubecostSource(SimpleSource[KubecostSourceConfig]):+class KubecostSource(ResumableSource[KubecostSourceConfig, KubecostResumeConfig], ValidateDatabaseHostMixin):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KUBECOST+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` determines where the stored API key is sent; retargeting it+ # must re-require the key.+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Kubecost authentication failed. Please check your API key.",+ "403 Client Error: Forbidden for url": "Kubecost denied access. Please check your API key's permissions.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.KUBECOST,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Kubecost (IBM / Apptio)",+ caption="""Connect your Kubecost deployment to pull Kubernetes cost allocation and infrastructure asset costs into the PostHog Data warehouse.++Enter the URL where your Kubecost cost-model API is reachable (e.g. `https://kubecost.example.com` — with or without the `/model` suffix). Self-hosted Kubecost ships with no built-in auth, so the API must be exposed to PostHog, typically behind an ingress or auth proxy. If your deployment or proxy requires a token (e.g. Kubecost Cloud), provide it as the API key and it is sent as a bearer token — this requires an `https://` URL so the key is never sent in plaintext.""",iconPath="/static/services/kubecost.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/kubecost",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["kubernetes", "k8s", "finops", "opencost", "apptio"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Kubecost API URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://kubecost.example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key (optional)",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: KubecostSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ 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: KubecostSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)+ except ValueError:+ return False, "Invalid Kubecost API URL"+ if not host_valid:+ return False, host_error++ return validate_kubecost_credentials(config.host, config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KubecostResumeConfig]:+ return ResumableSourceManager[KubecostResumeConfig](inputs, KubecostResumeConfig)++ def source_for_pipeline(+ self,+ config: KubecostSourceConfig,+ resumable_source_manager: ResumableSourceManager[KubecostResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Kubecost host")++ return kubecost_source(+ host=config.host,+ api_key=config.api_key,+ 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/kubecost/tests/test_kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.pynew file mode 100644index 000000000000..d483f9152f16--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py@@ -0,0 +1,342 @@+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.kubecost import (+ KubecostResumeConfig,+ get_rows,+ hostname_of,+ kubecost_source,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.settings import (+ DEFAULT_BACKFILL_DAYS,+ ENDPOINTS,+ INCREMENTAL_LOOKBACK_DAYS,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.kubecost"+++def _make_manager(resume_state: KubecostResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ return resp+++def _allocation_set(names: list[str]) -> dict[str, Any]:+ return {+ name: {+ "name": name,+ "window": {"start": "2026-07-14T00:00:00Z", "end": "2026-07-15T00:00:00Z"},+ "totalCost": 1.5,+ }+ for name in names+ }+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://kubecost.example.com", "https://kubecost.example.com"),+ ("kubecost.example.com", "https://kubecost.example.com"),+ ("https://kubecost.example.com/", "https://kubecost.example.com"),+ # The cost-model API prefix is re-appended per request, so a URL+ # entered with it must not produce `/model/model` paths.+ ("https://kubecost.example.com/model", "https://kubecost.example.com"),+ ("http://kubecost.internal:9090/model/", "http://kubecost.internal:9090"),+ ],+ )+ def test_valid_hosts(self, value, expected):+ assert normalize_host(value) == expected++ @pytest.mark.parametrize("value", ["", " ", "ftp://example.com", "https://"])+ def test_invalid_hosts_raise(self, value):+ with pytest.raises(ValueError):+ normalize_host(value)++ def test_hostname_of(self):+ assert hostname_of("https://kubecost.example.com/model") == "kubecost.example.com"+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [_allocation_set(["argocd"])]})++ is_valid, error = validate_credentials("https://kubecost.example.com", "token")++ assert is_valid is True+ assert error is None+ assert mock_session.call_args.kwargs["headers"] == {"Authorization": "Bearer token"}+ url = mock_session.return_value.get.call_args.args[0]+ assert url == "https://kubecost.example.com/model/allocation"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_no_api_key_sends_no_auth_header(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ is_valid, _ = validate_credentials("https://kubecost.example.com", None)++ assert is_valid is True+ assert mock_session.call_args.kwargs["headers"] is None++ @pytest.mark.parametrize(+ "status_code, expected_error",+ [+ (401, "authentication failed"),+ (403, "authentication failed"),+ (404, "unexpected status"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_http_error_statuses(self, mock_session, status_code, expected_error):+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)++ is_valid, error = validate_credentials("https://kubecost.example.com", "token")++ assert is_valid is False+ assert expected_error in (error or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_error_envelope_fails_validation(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 500, "message": "boom"})++ is_valid, error = validate_credentials("https://kubecost.example.com", "token")++ assert is_valid is False+ assert "boom" in (error or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_non_json_response_fails_validation(self, mock_session):+ resp = _response({})+ resp.json.side_effect = ValueError("not json")+ mock_session.return_value.get.return_value = resp++ is_valid, error = validate_credentials("https://kubecost.example.com", "token")++ assert is_valid is False+ assert "did not return a Kubecost API response" in (error or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_unreachable_host_fails_validation(self, mock_session):+ mock_session.return_value.get.side_effect = ConnectionError("nope")++ is_valid, error = validate_credentials("https://kubecost.example.com", "token")++ assert is_valid is False+ assert "Unable to reach" in (error or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_api_key_over_plain_http_fails_before_any_request(self, mock_session):+ # The bearer token must never ride a plaintext connection.+ is_valid, error = validate_credentials("http://kubecost.example.com", "token")++ assert is_valid is False+ assert "https" in (error or "")+ mock_session.return_value.get.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_plain_http_without_api_key_is_allowed(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ is_valid, error = validate_credentials("http://kubecost.example.com", None)++ assert is_valid is True+ assert error is None+++@freeze_time("2026-07-15T10:00:00Z")+class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_flattens_result_sets_and_injects_key_and_window(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ {"code": 200, "data": [_allocation_set(["__idle__", "argocd"])]}+ )++ batches = list(+ get_rows(+ "https://k.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T00:00:00Z",+ )+ )++ rows = [row for batch in batches for row in batch]+ assert {row["key"] for row in rows} == {"__idle__", "argocd"}+ # The server-reported window is preferred for the composite key columns.+ assert all(row["window_start"] == "2026-07-14T00:00:00Z" for row in rows)+ assert all(row["window_end"] == "2026-07-15T00:00:00Z" for row in rows)+ assert all(row["totalCost"] == 1.5 for row in rows)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_null_result_sets_are_skipped(self, mock_session):+ # Windows beyond the deployment's ETL retention come back as `data: [null]`.+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ batches = list(+ get_rows(+ "https://k.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T00:00:00Z",+ )+ )++ assert batches == []++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_walks_lookback_window_oldest_first(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ list(+ get_rows(+ "https://k.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-15T00:00:00Z",+ )+ )++ calls = mock_session.return_value.get.call_args_list+ # Watermark day minus the lookback, through today inclusive.+ assert len(calls) == INCREMENTAL_LOOKBACK_DAYS + 1+ windows = [call.kwargs["params"]["window"] for call in calls]+ assert windows[0] == "2026-07-12T00:00:00Z,2026-07-13T00:00:00Z"+ assert windows[-1] == "2026-07-15T00:00:00Z,2026-07-16T00:00:00Z"+ assert windows == sorted(windows)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_starts_at_default_backfill(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ list(get_rows("https://k.example.com", None, "assets", mock.MagicMock(), _make_manager()))++ calls = mock_session.return_value.get.call_args_list+ assert len(calls) == DEFAULT_BACKFILL_DAYS + 1++ @pytest.mark.parametrize(+ "endpoint, expected_path, expected_aggregate",+ [+ ("allocation_by_namespace", "/model/allocation", "namespace"),+ ("allocation_by_controller", "/model/allocation", "controller"),+ ("allocation_by_pod", "/model/allocation", "pod"),+ ("assets", "/model/assets", None),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_endpoint_path_and_params(self, mock_session, endpoint, expected_path, expected_aggregate):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ list(+ get_rows(+ "https://k.example.com",+ "token",+ endpoint,+ mock.MagicMock(),+ _make_manager(KubecostResumeConfig(next_date="2026-07-15")),+ )+ )++ call = mock_session.return_value.get.call_args+ assert call.args[0] == f"https://k.example.com{expected_path}"+ assert call.kwargs["params"].get("aggregate") == expected_aggregate+ assert call.kwargs["params"]["accumulate"] == "true"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_date_supersedes_older_start(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [None]})++ manager = _make_manager(KubecostResumeConfig(next_date="2026-07-15"))+ list(get_rows("https://k.example.com", "token", "allocation_by_namespace", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_count == 1+ window = mock_session.return_value.get.call_args.kwargs["params"]["window"]+ assert window == "2026-07-15T00:00:00Z,2026-07-16T00:00:00Z"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_state_saved_after_each_yielded_day(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 200, "data": [_allocation_set(["argocd"])]})++ manager = _make_manager()+ list(+ get_rows(+ "https://k.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-14T00:00:00Z",+ )+ )++ saved_dates = [call.args[0].next_date for call in manager.save_state.call_args_list]+ # State points at the next unfetched day; no state after the final day.+ assert saved_dates == ["2026-07-12", "2026-07-13", "2026-07-14", "2026-07-15"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_api_key_over_plain_http_raises_before_any_request(self, mock_session):+ with pytest.raises(ValueError, match="https"):+ list(+ get_rows(+ "http://kubecost.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ _make_manager(),+ )+ )+ mock_session.return_value.get.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_error_envelope_raises(self, mock_session):+ mock_session.return_value.get.return_value = _response({"code": 400, "message": "bad request"})++ with pytest.raises(ValueError, match="bad request"):+ list(+ get_rows(+ "https://k.example.com",+ "token",+ "allocation_by_namespace",+ mock.MagicMock(),+ _make_manager(KubecostResumeConfig(next_date="2026-07-15")),+ )+ )+++class TestKubecostSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = kubecost_source("https://k.example.com", "token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ # The result-set key is only unique within one window, so the window+ # start must be part of the composite key.+ assert response.primary_keys == ["key", "window_start"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["window_start"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost_source.pynew file mode 100644index 000000000000..4329cdf5e627--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost_source.py@@ -0,0 +1,166 @@+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 KubecostSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.kubecost import KubecostResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.source import KubecostSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestKubecostSource:+ def setup_method(self):+ self.source = KubecostSource()+ self.team_id = 123+ self.config = KubecostSourceConfig(host="https://kubecost.example.com", api_key="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.KUBECOST++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Kubecost"+ assert config.label == "Kubecost (IBM / Apptio)"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/kubecost.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/kubecost"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "api_key"]++ def test_api_key_field_is_optional_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ # Self-hosted Kubecost ships with no built-in auth, so the key must stay optional.+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is False++ def test_connection_host_fields_cover_host(self):+ # The API URL decides where the stored key gets sent.+ assert self.source.connection_host_fields == ["host"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://kubecost.example.com/model/allocation",+ "403 Client Error: Forbidden for url: https://kubecost.example.com/model/allocation",+ ],+ )+ def test_non_retryable_errors_match_known_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://kubecost.example.com/model/allocation"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Every endpoint is incremental via the injected per-day window_start.+ assert all(schema.supports_incremental for schema in schemas.values())+ assert [f["field"] for f in schemas["allocation_by_namespace"].incremental_fields] == ["window_start"]+ assert schemas["assets"].incremental_fields == INCREMENTAL_FIELDS["assets"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["assets"])+ assert len(schemas) == 1+ assert schemas[0].name == "assets"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.source.validate_kubecost_credentials"+ )+ @mock.patch.object(KubecostSource, "is_database_host_valid")+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = (True, None)++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_host_valid.assert_called_once_with("kubecost.example.com", self.team_id)+ mock_validate.assert_called_once_with("https://kubecost.example.com", "token")++ @mock.patch.object(KubecostSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Host is not allowed"++ def test_validate_credentials_rejects_invalid_url(self):+ config = KubecostSourceConfig(host="ftp://nope", api_key="token")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid Kubecost API URL"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.source.validate_kubecost_credentials"+ )+ @mock.patch.object(KubecostSource, "is_database_host_valid")+ def test_validate_credentials_bad_key(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = (False, "Kubecost authentication failed. Please check your API key.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "authentication failed" in (error_message or "")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is KubecostResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.kubecost.source.kubecost_source")+ @mock.patch.object(KubecostSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_kubecost_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "allocation_by_namespace"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-14T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_kubecost_source.assert_called_once()+ kwargs = mock_kubecost_source.call_args.kwargs+ assert kwargs["host"] == "https://kubecost.example.com"+ assert kwargs["api_key"] == "token"+ assert kwargs["endpoint"] == "allocation_by_namespace"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-14T00:00:00Z"++ @mock.patch.object(KubecostSource, "is_database_host_valid")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.schema_name = "assets"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)