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 CAST AI source (#73183)

Tom Owersda606af38bd9
diff --git a/frontend/public/services/cast_ai.png b/frontend/public/services/cast_ai.png
index 87468ff28f9e..4389fbdc3e75 100644
Binary files a/frontend/public/services/cast_ai.png and b/frontend/public/services/cast_ai.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index a7c178fee6b8..c113e97cdf6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -124,6 +124,7 @@ the row lists both.
| canny | HTTP | requests | ✅ |
| capsule_crm | HTTP | requests | ✅ |
| care_quality_commission | HTTP | requests | ✅ |
+| cast_ai | HTTP | requests + `rest_source.RESTClient` | ✅ |
| census | HTTP | requests + `rest_source.RESTClient` | ✅ |
| chameleon | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -824,7 +825,6 @@ doesn't conflict with concurrent PRs.
- captivate
- cart_com
- cashfree
-- cast_ai
- castor_edc
- catchpoint
- cdc_open_data
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/canonical_descriptions.py
new file mode 100644
index 000000000000..6384cbaa06f8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/canonical_descriptions.py
@@ -0,0 +1,90 @@
+"""Canonical, documentation-sourced descriptions for CAST AI endpoints and columns.
+
+Sourced from the official CAST AI API reference (https://api.cast.ai/v1/spec). Keyed by the
+resource names in `settings.py` `CASTAI_ENDPOINTS`, which match the `ExternalDataSchema.name` of
+a synced CAST AI table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Cost fields shared by both the cluster-level and per-workload cost breakdowns.
+_COST_BREAKDOWN_COLUMNS = {
+ "costOnDemand": "Average hourly cost of on-demand instances for the given time bucket.",
+ "costSpot": "Average hourly cost of spot instances for the given time bucket.",
+ "costSpotFallback": "Average hourly cost of spot-fallback instances for the given time bucket.",
+ "cpuCountOnDemand": "Average number of CPUs on on-demand instances for the given time bucket.",
+ "cpuCountSpot": "Average number of CPUs on spot instances for the given time bucket.",
+ "cpuCountSpotFallback": "Average number of CPUs on spot-fallback instances for the given time bucket.",
+ "cpuCostOnDemand": "Average hourly CPU cost of on-demand instances for the given time bucket.",
+ "cpuCostSpot": "Average hourly CPU cost of spot instances for the given time bucket.",
+ "cpuCostSpotFallback": "Average hourly CPU cost of spot-fallback instances for the given time bucket.",
+ "ramCostOnDemand": "Average hourly RAM cost of on-demand instances for the given time bucket.",
+ "ramCostSpot": "Average hourly RAM cost of spot instances for the given time bucket.",
+ "ramCostSpotFallback": "Average hourly RAM cost of spot-fallback instances for the given time bucket.",
+ "ramGibOnDemand": "Average number of RAM GiB on on-demand instances for the given time bucket.",
+ "ramGibSpot": "Average number of RAM GiB on spot instances for the given time bucket.",
+ "ramGibSpotFallback": "Average number of RAM GiB on spot-fallback instances for the given time bucket.",
+ "gpuCostOnDemand": "Average hourly GPU cost of on-demand instances for the given time bucket.",
+ "gpuCostSpot": "Average hourly GPU cost of spot instances for the given time bucket.",
+ "gpuCostSpotFallback": "Average hourly GPU cost of spot-fallback instances for the given time bucket.",
+ "gpuCountOnDemand": "Average number of GPUs on on-demand instances for the given time bucket.",
+ "gpuCountSpot": "Average number of GPUs on spot instances for the given time bucket.",
+ "gpuCountSpotFallback": "Average number of GPUs on spot-fallback instances for the given time bucket.",
+ "storageGib": "Average number of provisioned storage GiB for the given time bucket.",
+ "storageCost": "Average hourly storage cost for the given time bucket.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "clusters": {
+ "description": "A Kubernetes cluster connected to CAST AI for cost monitoring and optimization.",
+ "docs_url": "https://docs.cast.ai/docs/cluster-management",
+ "columns": {
+ "id": "Unique identifier of the cluster.",
+ "name": "Name of the cluster.",
+ "organizationId": "Identifier of the CAST AI organization the cluster belongs to.",
+ "credentialsId": "Identifier of the cloud credentials used to manage the cluster.",
+ "createdAt": "Time at which the cluster was registered with CAST AI.",
+ "region": "Cloud provider region the cluster runs in.",
+ "status": "Onboarding/connection status of the cluster (e.g. ready, disconnected).",
+ "agentSnapshotReceivedAt": "Time the CAST AI agent last reported cluster state.",
+ "agentStatus": "Health status of the CAST AI agent running in the cluster.",
+ "providerType": "Cloud provider the cluster runs on (e.g. eks, gke, aks).",
+ "deletedAt": "Time at which the cluster was disconnected/deleted, if applicable.",
+ "kubernetesVersion": "Version of Kubernetes the cluster is running.",
+ "managedBy": "How the cluster's nodes are managed (e.g. CAST AI, Karpenter).",
+ },
+ },
+ "cluster_cost_reports": {
+ "description": (
+ "Historical compute cost for a cluster, bucketed by time interval and broken down "
+ "by on-demand, spot, and spot-fallback instance cost."
+ ),
+ "docs_url": "https://docs.cast.ai/docs/cost-reports",
+ "columns": {
+ "cluster_id": "Identifier of the cluster this cost entry belongs to.",
+ "timestamp": "Start of the time bucket this cost entry covers.",
+ "totalCpuCostOnDemand": "Total on-demand CPU cost for the time bucket.",
+ "totalRamCostOnDemand": "Total on-demand RAM cost for the time bucket.",
+ "totalGpuCostOnDemand": "Total on-demand GPU cost for the time bucket.",
+ "totalStorageCost": "Total storage cost for the time bucket.",
+ **_COST_BREAKDOWN_COLUMNS,
+ },
+ },
+ "cluster_savings_history": {
+ "description": (
+ "Historical comparison of a cluster's real cost against CAST AI's estimated optimal "
+ "cost under different optimization strategies, used to track realized and available savings."
+ ),
+ "docs_url": "https://docs.cast.ai/docs/cost-reports",
+ "columns": {
+ "cluster_id": "Identifier of the cluster this savings entry belongs to.",
+ "createdAt": "Time this savings snapshot was recorded.",
+ "current": "Cluster's actual cost as currently configured.",
+ "optimizedSpotInstances": "Estimated cost if fully optimized using spot instances.",
+ "optimizedLayman": "Estimated cost under CAST AI's balanced (non-spot) optimization strategy.",
+ "optimizedSpotOnly": "Estimated cost under a spot-only optimization strategy.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/cast_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/cast_ai.py
new file mode 100644
index 000000000000..0dd001ff31cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/cast_ai.py
@@ -0,0 +1,211 @@
+import dataclasses
+from collections.abc import Iterable
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional, cast
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.settings import (
+ CASTAI_BASE_URL,
+ CASTAI_ENDPOINTS,
+ COST_REPORT_STEP_SECONDS,
+ DEFAULT_LOOKBACK_DAYS,
+ CastAiEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+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 (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class CastAiResumeConfig:
+ # Opaque framework checkpoint (fan-out resume state for the two report endpoints; the
+ # "clusters" list has no pagination and is never resumed).
+ paginator_state: dict[str, Any]
+
+
+def _format_time_value(value: Any) -> str:
+ """Format an incremental watermark, or our own default lookback, as RFC 3339 UTC."""
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ return normalized.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _default_lookback_start() -> str:
+ return _format_time_value(datetime.now(UTC) - timedelta(days=DEFAULT_LOOKBACK_DAYS))
+
+
+def _now() -> str:
+ return _format_time_value(datetime.now(UTC))
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": CASTAI_BASE_URL,
+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-API-Key", "location": "header"},
+ "headers": {"Accept": "application/json"},
+ # X-API-Key is a custom header requests keeps across origins, so never follow a
+ # redirect that could hand the CAST AI key to another host.
+ "allow_redirects": False,
+ }
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # ListClusters is the cheapest authenticated call available (no required params, and an
+ # empty cluster list is still a valid 200), so it doubles as the credential probe.
+ res = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(
+ f"{CASTAI_BASE_URL}/v1/kubernetes/external-clusters",
+ headers={"X-API-Key": api_key, "Accept": "application/json"},
+ timeout=10,
+ )
+ if res.status_code == 200:
+ return True, None
+ if res.status_code in (401, 403):
+ return False, "Invalid or unauthorized CAST AI API key"
+ return False, f"CAST AI API returned an unexpected status: {res.status_code}"
+
+
+def get_resource(endpoint: str) -> EndpointResource:
+ config = CASTAI_ENDPOINTS[endpoint]
+ if config.fanout:
+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "data_selector": "items",
+ "paginator": SinglePagePaginator(),
+ }
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def _report_incremental_config_factory(start_param: str, end_param: str) -> Any:
+ end_value = _now()
+
+ def factory(field: str) -> IncrementalConfig:
+ return {
+ "cursor_path": field,
+ "start_param": start_param,
+ "end_param": end_param,
+ "initial_value": _default_lookback_start(),
+ "end_value": end_value,
+ "convert": _format_time_value,
+ }
+
+ return factory
+
+
+def _make_source_response(endpoint_config: CastAiEndpointConfig, items_fn: Any) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=items_fn,
+ primary_keys=endpoint_config.primary_key
+ if isinstance(endpoint_config.primary_key, list)
+ else [endpoint_config.primary_key],
+ sort_mode=endpoint_config.sort_mode,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def cast_ai_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CastAiResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = CASTAI_ENDPOINTS[endpoint]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = resume_config.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's somewhere to resume to; the Redis TTL handles cleanup.
+ if state:
+ resumable_source_manager.save_state(CastAiResumeConfig(paginator_state=dict(state)))
+
+ if endpoint_config.fanout:
+ start_param, end_param = (
+ ("startTime", "endTime") if endpoint == "cluster_cost_reports" else ("fromDate", "toDate")
+ )
+ # These reports require a time window on every request (full refresh included) so the
+ # literal defaults below are always present; when incremental sync is enabled the
+ # framework's incremental config overwrites them with the real last-synced watermark.
+ child_params_extra: dict[str, Any] = {
+ start_param: _default_lookback_start(),
+ end_param: _now(),
+ }
+ if endpoint == "cluster_cost_reports":
+ child_params_extra["stepSeconds"] = COST_REPORT_STEP_SECONDS
+
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=CASTAI_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=endpoint_config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=_report_incremental_config_factory(start_param, end_param),
+ page_size_param=None,
+ parent_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "items"},
+ child_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "items"},
+ child_params_extra=child_params_extra,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ return _make_source_response(endpoint_config, lambda: dependent_resource)
+
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {"write_disposition": "replace"},
+ "resources": [get_resource(endpoint=endpoint)],
+ }
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _make_source_response(endpoint_config, lambda: resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/settings.py
new file mode 100644
index 000000000000..21385d44a80b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/settings.py
@@ -0,0 +1,101 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+CASTAI_BASE_URL = "https://api.cast.ai"
+
+# Cost/savings report endpoints have no documented maximum window, and CAST AI accounts are
+# usually onboarded well within the last year, so 30 days is a reasonable first-sync backfill
+# that won't request an unbounded/huge response.
+DEFAULT_LOOKBACK_DAYS = 30
+
+# `/cost` buckets by stepSeconds; hourly keeps a 30 day window to ~720 rows per cluster while
+# still being useful for cost trend analysis. Not documented as configurable elsewhere, so this
+# is our own choice, not a vendor default.
+COST_REPORT_STEP_SECONDS = 3600
+
+TIMESTAMP_INCREMENTAL: IncrementalField = {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+CREATED_AT_INCREMENTAL: IncrementalField = {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+@dataclass
+class CastAiEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None
+ # Unused: every endpoint here is an unpaginated single-response report/list, so callers
+ # always pass page_size_param=None. Kept only to satisfy the shared fan-out helper's protocol.
+ page_size: int = 0
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_key: str | list[str] = "id"
+ fanout: DependentEndpointConfig | None = None
+
+
+CASTAI_ENDPOINTS: dict[str, CastAiEndpointConfig] = {
+ # Org-wide entity list. No pagination params documented and no server-side timestamp filter,
+ # so this stays a small full-refresh table that fan-out children resolve `clusterId` from.
+ "clusters": CastAiEndpointConfig(
+ name="clusters",
+ path="/v1/kubernetes/external-clusters",
+ partition_key="createdAt",
+ primary_key="id",
+ ),
+ "cluster_cost_reports": CastAiEndpointConfig(
+ name="cluster_cost_reports",
+ path="/v1/cost-reports/clusters/{clusterId}/cost",
+ incremental_fields=[TIMESTAMP_INCREMENTAL],
+ default_incremental_field="timestamp",
+ partition_key="timestamp",
+ # The row identifier is only unique within a cluster (one entry per time bucket), and
+ # this table aggregates every cluster, so the cluster id is part of the key.
+ primary_key=["cluster_id", "timestamp"],
+ fanout=DependentEndpointConfig(
+ parent_name="clusters",
+ resolve_param="clusterId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "cluster_id"},
+ ),
+ ),
+ "cluster_savings_history": CastAiEndpointConfig(
+ name="cluster_savings_history",
+ path="/v1/cost-reports/clusters/{clusterId}/estimated-savings-history",
+ incremental_fields=[CREATED_AT_INCREMENTAL],
+ default_incremental_field="createdAt",
+ partition_key="createdAt",
+ primary_key=["cluster_id", "createdAt"],
+ fanout=DependentEndpointConfig(
+ parent_name="clusters",
+ resolve_param="clusterId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "cluster_id"},
+ ),
+ ),
+}
+
+# Fan-out children are synced directly (never the bare "clusters" parent table on its own as a
+# schema choice alongside them would double-count); "clusters" is still exposed as its own
+# top-level table for users who only want the entity list.
+ENDPOINTS = tuple(CASTAI_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CASTAI_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/source.py
index 1600b502ec37..98e59f2e8c76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/source.py
@@ -1,30 +1,127 @@
-from typing import cast
+from typing import Optional, cast
from 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.cast_ai.cast_ai import (
+ CastAiResumeConfig,
+ cast_ai_source,
+ validate_credentials as validate_castai_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.castai import CastAiSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CastAiSource(SimpleSource[CastAiSourceConfig]):
+class CastAiSource(ResumableSource[CastAiSourceConfig, CastAiResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.cast.ai/docs/api-access"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CASTAI
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "CAST AI authentication failed. Please check your API key.",
+ "403 Client Error": "CAST AI API key does not have the required permissions.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: CastAiSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: CastAiSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_castai_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CastAiResumeConfig]:
+ return ResumableSourceManager[CastAiResumeConfig](inputs, CastAiResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CastAiSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CastAiResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return cast_ai_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CAST_AI,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="CAST AI",
+ caption="Import Kubernetes cost and savings reports from your CAST AI organization.",
+ docsUrl="https://posthog.com/docs/cdp/sources/cast-ai",
iconPath="/static/services/cast_ai.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["kubernetes", "finops", "k8s"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai.py
new file mode 100644
index 000000000000..e9c31620e1f6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai.py
@@ -0,0 +1,302 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from unittest.mock import Mock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai import (
+ CastAiResumeConfig,
+ _client_config,
+ _default_lookback_start,
+ _format_time_value,
+ _now,
+ _report_incremental_config_factory,
+ cast_ai_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.settings import COST_REPORT_STEP_SECONDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+
+
+class _FakeDltResource:
+ def __init__(self, name: str, rows: list[dict]) -> None:
+ self.name = name
+ self._rows = rows
+
+ def add_map(self, mapper):
+ self._rows = [mapper(dict(row)) for row in self._rows]
+ return self
+
+ def __iter__(self):
+ return iter(self._rows)
+
+
+def _make_manager(resume_state: CastAiResumeConfig | None = None) -> Mock:
+ manager = Mock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+class TestCastAiDateFormatting:
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),
+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),
+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ ]
+ )
+ def test_format_time_value(self, _name, value, expected) -> None:
+ assert _format_time_value(value) == expected
+
+ def test_now_is_rfc3339(self) -> None:
+ value = _now()
+ assert value.endswith("Z")
+ # Round-trips as RFC 3339 without raising.
+ datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
+
+ def test_default_lookback_start_is_before_now(self) -> None:
+ start = datetime.strptime(_default_lookback_start(), "%Y-%m-%dT%H:%M:%SZ")
+ now = datetime.strptime(_now(), "%Y-%m-%dT%H:%M:%SZ")
+ assert start < now
+
+
+class TestCastAiIncrementalConfigFactory:
+ def test_produces_start_and_end_params(self) -> None:
+ factory = _report_incremental_config_factory("startTime", "endTime")
+ config = factory("timestamp")
+
+ assert config["cursor_path"] == "timestamp"
+ assert config["start_param"] == "startTime"
+ assert config["end_param"] == "endTime"
+ assert config["convert"] is _format_time_value
+ # initial_value/end_value are RFC 3339 strings usable as literal query params.
+ datetime.strptime(cast(str, config["initial_value"]), "%Y-%m-%dT%H:%M:%SZ")
+ datetime.strptime(cast(str, config["end_value"]), "%Y-%m-%dT%H:%M:%SZ")
+
+ def test_end_value_is_stable_across_calls(self) -> None:
+ # Both report endpoints must request the same "now" snapshot within one sync, so the
+ # value is captured once at factory-creation time, not per field.
+ factory = _report_incremental_config_factory("fromDate", "toDate")
+ assert factory("createdAt")["end_value"] == factory("timestamp")["end_value"]
+
+
+class TestCastAiGetResource:
+ def test_clusters_full_refresh(self) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint="clusters"))
+ assert resource["name"] == "clusters"
+ assert resource["write_disposition"] == "replace"
+ assert resource["endpoint"]["path"] == "/v1/kubernetes/external-clusters"
+ assert resource["endpoint"]["data_selector"] == "items"
+ assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)
+ assert resource["table_format"] == "delta"
+
+ def test_rejects_fanout_endpoint(self) -> None:
+ import pytest
+
+ with pytest.raises(ValueError, match="Fan-out endpoint"):
+ get_resource(endpoint="cluster_cost_reports")
+
+
+class TestCastAiValidateCredentials:
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid or unauthorized CAST AI API key"),
+ (403, False, "Invalid or unauthorized CAST AI API key"),
+ (500, False, "CAST AI API returned an unexpected status: 500"),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, status, expected_valid, expected_message, mock_session) -> None:
+ mock_session.return_value.get.return_value = Mock(status_code=status)
+
+ result = validate_credentials(api_key="key")
+
+ assert result == (expected_valid, expected_message)
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.cast.ai/v1/kubernetes/external-clusters"
+ assert call.kwargs["headers"]["X-API-Key"] == "key"
+ # The X-API-Key header survives cross-origin redirects, so the probe must not follow them.
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+ def test_client_config_disables_redirects(self) -> None:
+ # Same guard for the sync path: RESTClient reads allow_redirects from the client config.
+ assert _client_config(api_key="key")["allow_redirects"] is False
+
+
+class TestCastAiSourceTopLevel:
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.rest_api_resource")
+ def test_top_level_response(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ response = cast_ai_source(
+ api_key="key",
+ endpoint="clusters",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ assert response.name == "clusters"
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.rest_api_resource")
+ def test_resumes_from_saved_state(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = _make_manager(CastAiResumeConfig(paginator_state={"offset": 5}))
+
+ cast_ai_source(
+ api_key="key",
+ endpoint="clusters",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ kwargs = mock_rest_api_resource.call_args.kwargs
+ assert kwargs["initial_paginator_state"] == {"offset": 5}
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.rest_api_resource")
+ def test_saves_checkpoints_after_batches(self, mock_rest_api_resource) -> None:
+ mock_rest_api_resource.return_value = Mock()
+ manager = _make_manager()
+
+ cast_ai_source(
+ api_key="key",
+ endpoint="clusters",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
+ resume_hook({"offset": 1})
+ manager.save_state.assert_called_once_with(CastAiResumeConfig(paginator_state={"offset": 1}))
+
+ manager.save_state.reset_mock()
+ resume_hook(None)
+ manager.save_state.assert_not_called()
+
+
+class TestCastAiFanoutRowFormat:
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+ )
+ def test_cluster_cost_reports_row_format(self, mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [
+ _FakeDltResource("clusters", [{"id": "cluster-1"}]),
+ _FakeDltResource(
+ "cluster_cost_reports",
+ [{"timestamp": "2026-03-01T00:00:00Z", "costOnDemand": "1.5", "_clusters_id": "cluster-1"}],
+ ),
+ ]
+
+ response = cast_ai_source(
+ api_key="key",
+ endpoint="cluster_cost_reports",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ rows = list(cast(Any, response.items()))
+ assert rows == [{"timestamp": "2026-03-01T00:00:00Z", "costOnDemand": "1.5", "cluster_id": "cluster-1"}]
+ assert response.primary_keys == ["cluster_id", "timestamp"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["timestamp"]
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+ )
+ def test_cluster_savings_history_row_format(self, mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [
+ _FakeDltResource("clusters", [{"id": "cluster-9"}]),
+ _FakeDltResource(
+ "cluster_savings_history",
+ [{"createdAt": "2026-03-01T00:00:00Z", "current": {"cost": "9"}, "_clusters_id": "cluster-9"}],
+ ),
+ ]
+
+ response = cast_ai_source(
+ api_key="key",
+ endpoint="cluster_savings_history",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ )
+
+ rows = list(cast(Any, response.items()))
+ assert rows == [{"createdAt": "2026-03-01T00:00:00Z", "current": {"cost": "9"}, "cluster_id": "cluster-9"}]
+ assert response.primary_keys == ["cluster_id", "createdAt"]
+
+
+class TestCastAiFanoutWiring:
+ @parameterized.expand(
+ [
+ ("cluster_cost_reports", "startTime", "endTime", True),
+ ("cluster_savings_history", "fromDate", "toDate", False),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.build_dependent_resource")
+ def test_fanout_wiring_per_endpoint(
+ self, endpoint, start_param, end_param, expects_step_seconds, mock_build_dependent_resource
+ ) -> None:
+ mock_build_dependent_resource.return_value = iter([])
+ manager = _make_manager(CastAiResumeConfig(paginator_state={"completed": []}))
+
+ cast_ai_source(
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["page_size_param"] is None
+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], SinglePagePaginator)
+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], SinglePagePaginator)
+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "items"
+ assert kwargs["child_endpoint_extra"]["data_selector"] == "items"
+ assert start_param in kwargs["child_params_extra"]
+ assert end_param in kwargs["child_params_extra"]
+ assert ("stepSeconds" in kwargs["child_params_extra"]) is expects_step_seconds
+ if expects_step_seconds:
+ assert kwargs["child_params_extra"]["stepSeconds"] == COST_REPORT_STEP_SECONDS
+ assert kwargs["resume_hook"] is not None
+ assert kwargs["initial_paginator_state"] == {"completed": []}
+
+ @parameterized.expand(
+ [
+ ("incremental", True, datetime(2026, 3, 1, tzinfo=UTC)),
+ ("first_sync", True, None),
+ ("non_incremental", False, datetime(2026, 3, 1, tzinfo=UTC)),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai.build_dependent_resource")
+ def test_passes_watermark(
+ self, _name, should_use_incremental_field, last_value, mock_build_dependent_resource
+ ) -> None:
+ mock_build_dependent_resource.return_value = iter([])
+
+ cast_ai_source(
+ api_key="key",
+ endpoint="cluster_cost_reports",
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ incremental_field="timestamp",
+ )
+
+ kwargs = mock_build_dependent_resource.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == last_value
+ assert kwargs["incremental_field"] == "timestamp"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai_source.py
new file mode 100644
index 000000000000..9fab9db937b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cast_ai/tests/test_cast_ai_source.py
@@ -0,0 +1,136 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.cast_ai import CastAiResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.source import CastAiSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.castai import CastAiSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCastAiSource:
+ def setup_method(self) -> None:
+ self.source = CastAiSource()
+ self.team_id = 123
+ self.config = CastAiSourceConfig(api_key="castai-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CASTAI
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "CastAi"
+ assert config.label == "CAST AI"
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # The source ships visible: unreleasedSource hides the connector from every user.
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/cast_ai.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cast-ai"
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_get_schemas_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_semantics(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ # No server-side timestamp filter is documented for listing clusters, so it stays
+ # full refresh.
+ assert schemas["clusters"].supports_incremental is False
+ assert schemas["clusters"].incremental_fields == []
+
+ for name, field_name in (("cluster_cost_reports", "timestamp"), ("cluster_savings_history", "createdAt")):
+ assert schemas[name].supports_incremental is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == [field_name]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["clusters"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "clusters"
+
+ @parameterized.expand(
+ [
+ "401 Client Error: Unauthorized for url: https://api.cast.ai/v1/kubernetes/external-clusters",
+ "403 Client Error: Forbidden for url: https://api.cast.ai/v1/kubernetes/external-clusters",
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_non_retryable_errors_ignore_transient_failures(self) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(
+ key in "500 Server Error for url: https://api.cast.ai/v1/kubernetes/external-clusters"
+ for key in non_retryable
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.source.validate_castai_credentials"
+ )
+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="cluster_cost_reports")
+
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("castai-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CastAiResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.source.cast_ai_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_cast_ai_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "cluster_cost_reports"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "timestamp"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_cast_ai_source.call_args.kwargs
+ assert kwargs["api_key"] == "castai-key"
+ assert kwargs["endpoint"] == "cluster_cost_reports"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "timestamp"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cast_ai.source.cast_ai_source")
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(
+ self, mock_cast_ai_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "cluster_cost_reports"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_cast_ai_source.call_args.kwargs
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/castai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/castai.py
index 6da9749a989b..c4b4b39e7629 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/castai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/castai.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class CastAiSourceConfig(config.Config):
- pass
+ api_key: str