: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): add Spot by Flexera source (#73202)
Tom Owers321a58ee7a2f
diff --git a/frontend/public/services/spot_io.png b/frontend/public/services/spot_io.pngindex 410ba5403c07..b5cd9ffe896e 100644Binary files a/frontend/public/services/spot_io.png and b/frontend/public/services/spot_io.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 008c8d088b25..d8649456e781 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -530,6 +530,7 @@ the row lists both.| spacelift | HTTP (GraphQL) | requests | ✅ || sparkpost | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ |+| spot_io | HTTP | requests + `rest_source.RESTClient` | ✅ || spotlercrm | HTTP | requests + `rest_source.RESTClient` | ✅ || sprig | HTTP | requests + `rest_source.RESTClient` | ✅ || squadcast | HTTP | requests | ✅ |@@ -1290,7 +1291,6 @@ doesn't conflict with concurrent PRs.- sonatype_nexus- spacelift- speedcurve-- spot_io- spotify_ads- sprinklr- sprout_socialdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotio.pyindex 0b7fef6c4a5f..051194dc9880 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotio.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SpotIoSourceConfig(config.Config):- pass+ api_token: str+ account_id: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/canonical_descriptions.pynew file mode 100644index 000000000000..8086d667f64a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/canonical_descriptions.py@@ -0,0 +1,82 @@+"""Canonical, documentation-sourced descriptions for Spot by Flexera endpoints and columns.++Sourced from the official Spot by Flexera OpenAPI reference (https://docs.spot.io/api/). Keyed by+the resource names in `settings.py` `SPOT_IO_ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced Spot table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "elastigroups": {+ "description": (+ "An AWS Elastigroup: a fleet of spot/on-demand EC2 instances managed together for "+ "cost-optimized capacity, with a defined scaling strategy and launch configuration."+ ),+ "docs_url": "https://docs.spot.io/api/?version=v3#tag/Elastigroup-AWS",+ "columns": {+ "id": "Unique identifier of the Elastigroup.",+ "name": "Name of the Elastigroup.",+ "description": "User-provided description of the Elastigroup.",+ "capacity": "Minimum, maximum, and target instance capacity for the group.",+ "strategy": "Risk and on-demand/spot balancing strategy used when provisioning capacity.",+ "compute": "Compute configuration: instance types, availability zones, and launch specification.",+ "scaling": "Scaling policies attached to the group.",+ "scheduling": "Scheduled tasks configured for the group.",+ "createdAt": "Time at which the Elastigroup was created.",+ "updatedAt": "Time at which the Elastigroup was last updated.",+ },+ },+ "ocean_clusters": {+ "description": (+ "An Ocean cluster: the configuration Spot uses to manage a Kubernetes cluster's "+ "worker node capacity across spot, on-demand, and reserved instances."+ ),+ "docs_url": "https://docs.spot.io/api/?version=v3#tag/Ocean-AWS",+ "columns": {+ "id": "Unique identifier of the Ocean cluster.",+ "name": "Name of the Ocean cluster.",+ "controllerClusterId": "Identifier used by the Ocean controller running inside the Kubernetes cluster.",+ "region": "AWS region the cluster runs in.",+ "autoScaler": "Auto-scaling configuration for the cluster's worker nodes.",+ "capacity": "Minimum, maximum, and target worker node capacity for the cluster.",+ "strategy": "Spot/on-demand balancing strategy used when provisioning worker nodes.",+ "compute": "Compute configuration: instance types, availability zones, and launch specification.",+ "createdAt": "Time at which the Ocean cluster was created.",+ "updatedAt": "Time at which the Ocean cluster was last updated.",+ },+ },+ "stateful_nodes": {+ "description": (+ "A Stateful Node: a single persistent EC2 instance managed by Spot with attached "+ "storage and network state preserved across spot interruptions."+ ),+ "docs_url": "https://docs.spot.io/api/?version=v3#tag/Stateful-Node-AWS",+ "columns": {+ "id": "Unique identifier of the Stateful Node.",+ "config": "Instance configuration: region, instance types, and launch specification.",+ "createdAt": "Time at which the Stateful Node was created.",+ "updatedAt": "Time at which the Stateful Node was last updated.",+ },+ },+ "elastigroup_costs": {+ "description": (+ "Per-instance realized cost and savings for an Elastigroup over a rolling 30-day "+ "window, broken down by running time and actual vs. potential (on-demand) spend."+ ),+ "docs_url": "https://docs.spot.io/api/?version=v3#tag/Elastigroup-AWS/paths/~1aws~1ec2~1group~1%7BgroupId%7D~1costs~1detailed/get",+ "columns": {+ "groupId": "Identifier of the Elastigroup this cost entry belongs to.",+ "elastigroup_name": "Name of the Elastigroup this cost entry belongs to.",+ "instanceId": "Identifier of the EC2 instance this cost entry covers.",+ "spotInstanceRequestId": "Identifier of the spot instance request, if the instance was a spot instance.",+ "instanceType": "EC2 instance type (e.g. m5.large).",+ "availabilityZone": "AWS availability zone the instance ran in.",+ "running": "Total running time for the instance over the window.",+ "savings": "Realized savings versus on-demand pricing for the instance over the window.",+ "costs": "Actual and potential (on-demand) cost for the instance over the window.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/settings.pynew file mode 100644index 000000000000..6a08f7b67162--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/settings.py@@ -0,0 +1,83 @@+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++SPOT_IO_BASE_URL = "https://api.spotinst.io"++# The `costs/detailed` endpoint requires a fromDate/toDate window on every call and its rows+# carry no per-row timestamp we could track a real incremental watermark from (each row is one+# instance's totals over the whole window), so every sync re-pulls a fixed trailing window+# rather than advancing a cursor. 30 days keeps the response bounded while covering the typical+# billing-review horizon.+DEFAULT_COST_LOOKBACK_DAYS = 30+++@dataclass+class SpotIoEndpointConfig:+ 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 either a single unpaginated response or a fan-out with no+ # page-size param, 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+++SPOT_IO_ENDPOINTS: dict[str, SpotIoEndpointConfig] = {+ # AWS Elastigroups: spot/on-demand VM fleet definitions. No pagination params documented+ # and no server-side timestamp filter, so this is a small full-refresh entity list that the+ # cost fan-out below resolves `groupId` from.+ "elastigroups": SpotIoEndpointConfig(+ name="elastigroups",+ path="/aws/ec2/group",+ partition_key="createdAt",+ primary_key="id",+ ),+ # Ocean (Kubernetes) cluster configurations. Same full-refresh shape as elastigroups.+ "ocean_clusters": SpotIoEndpointConfig(+ name="ocean_clusters",+ path="/ocean/aws/k8s/cluster",+ partition_key="createdAt",+ primary_key="id",+ ),+ # Stateful Nodes (persistent single-instance workloads). Same full-refresh shape.+ "stateful_nodes": SpotIoEndpointConfig(+ name="stateful_nodes",+ path="/aws/ec2/managedInstance",+ partition_key="createdAt",+ primary_key="id",+ ),+ # Per-instance realized cost/savings for a rolling window, fanned out per elastigroup. The+ # API already returns `groupId` on every row, so no parent field injection is required for+ # identity — only the elastigroup name is pulled in for readability.+ "elastigroup_costs": SpotIoEndpointConfig(+ name="elastigroup_costs",+ path="/aws/ec2/group/{groupId}/costs/detailed",+ primary_key=["groupId", "instanceId"],+ fanout=DependentEndpointConfig(+ parent_name="elastigroups",+ resolve_param="groupId",+ resolve_field="id",+ include_from_parent=["name"],+ parent_field_renames={"name": "elastigroup_name"},+ ),+ ),+}++# Fan-out children are synced directly (never the bare "elastigroups" parent table on its own+# as a schema choice alongside "elastigroup_costs" would double-count); "elastigroups" is still+# exposed as its own top-level table for users who only want the entity list.+ENDPOINTS = tuple(SPOT_IO_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SPOT_IO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/source.pyindex 4199188161b2..22e707b23f2a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/source.py@@ -1,30 +1,136 @@-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 (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.spotio import SpotIoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io import (+ SpotIoResumeConfig,+ spot_io_source,+ validate_credentials as validate_spot_io_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SpotIoSource(SimpleSource[SpotIoSourceConfig]):+class SpotIoSource(ResumableSource[SpotIoSourceConfig, SpotIoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://docs.flexera.com/spot/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SPOTIO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Spot by Flexera authentication failed. Please check your API token.",+ "403 Client Error": "Spot by Flexera API token does not have the required permissions.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SpotIoSourceConfig,+ 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: SpotIoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_spot_io_credentials(config.api_token, config.account_id or None)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SpotIoResumeConfig]:+ return ResumableSourceManager[SpotIoResumeConfig](inputs, SpotIoResumeConfig)++ def source_for_pipeline(+ self,+ config: SpotIoSourceConfig,+ resumable_source_manager: ResumableSourceManager[SpotIoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return spot_io_source(+ api_token=config.api_token,+ account_id=config.account_id or None,+ 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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SPOT_IO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Spot by Flexera (Spotinst)",+ caption="Import Elastigroup and Ocean cloud cost optimization data from your Spot by Flexera account.",+ docsUrl="https://posthog.com/docs/cdp/sources/spot-io",iconPath="/static/services/spot_io.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["spot", "spotinst", "finops", "cloud cost", "kubernetes"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="act-123abcd",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/spot_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/spot_io.pynew file mode 100644index 000000000000..61410abba9a9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/spot_io.py@@ -0,0 +1,192 @@+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.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,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.settings import (+ DEFAULT_COST_LOOKBACK_DAYS,+ SPOT_IO_BASE_URL,+ SPOT_IO_ENDPOINTS,+ SpotIoEndpointConfig,+)++# Spot's response envelope wraps every list under `response.items`, regardless of endpoint.+DATA_SELECTOR = "response.items"+++class SpotIoResumeConfig:+ # Opaque framework checkpoint (fan-out resume state for `elastigroup_costs`; the entity+ # list endpoints have no pagination and are never resumed).+ paginator_state: dict[str, Any]+++def _format_time_value(value: datetime) -> str:+ return value.strftime("%Y-%m-%dT%H:%M:%S.000Z")+++def _cost_window_start() -> str:+ return _format_time_value(datetime.now(UTC) - timedelta(days=DEFAULT_COST_LOOKBACK_DAYS))+++def _cost_window_end() -> str:+ return _format_time_value(datetime.now(UTC))+++def _account_params(account_id: Optional[str]) -> dict[str, Any]:+ return {"accountId": account_id} if account_id else {}+++def _client_config(api_token: str) -> ClientConfig:+ return {+ "base_url": SPOT_IO_BASE_URL,+ "auth": {"type": "bearer", "token": api_token},+ "headers": {"Accept": "application/json"},+ "paginator": SinglePagePaginator(),+ }+++def validate_credentials(api_token: str, account_id: Optional[str] = None) -> tuple[bool, str | None]:+ # Listing Elastigroups is the cheapest authenticated call available (no required params,+ # and an empty group list is still a valid 200), so it doubles as the credential probe.+ res = make_tracked_session(redact_values=(api_token,)).get(+ f"{SPOT_IO_BASE_URL}/aws/ec2/group",+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},+ params=_account_params(account_id),+ timeout=10,+ )+ if res.status_code == 200:+ return True, None+ if res.status_code == 401:+ return False, "Invalid or expired Spot by Flexera API token"+ if res.status_code == 403:+ return False, "Spot by Flexera API token does not have the required permissions"+ return False, f"Spot by Flexera API returned an unexpected status: {res.status_code}"+++def get_resource(endpoint: str, account_id: Optional[str] = None) -> EndpointResource:+ config = SPOT_IO_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": DATA_SELECTOR,+ "paginator": SinglePagePaginator(),+ "params": _account_params(account_id),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(endpoint_config: SpotIoEndpointConfig, 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 spot_io_source(+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SpotIoResumeConfig],+ account_id: Optional[str] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = SPOT_IO_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(SpotIoResumeConfig(paginator_state=dict(state)))++ if endpoint_config.fanout:+ # `costs/detailed` requires fromDate/toDate on every request and its rows carry no+ # per-row timestamp to track a real watermark from, so this is always a fixed rolling+ # window rather than an incremental cursor (see settings.py).+ child_params_extra: dict[str, Any] = {+ "fromDate": _cost_window_start(),+ "toDate": _cost_window_end(),+ **_account_params(account_id),+ }+ parent_fanout = dataclasses.replace(endpoint_config.fanout, parent_params=_account_params(account_id))++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=SPOT_IO_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=parent_fanout,+ client_config=_client_config(api_token),+ 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,+ page_size_param=None,+ parent_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": DATA_SELECTOR},+ child_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": DATA_SELECTOR},+ 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_token),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(endpoint=endpoint, account_id=account_id)],+ }++ 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/spot_io/tests/test_spot_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/tests/test_spot_io.pynew file mode 100644index 000000000000..11220ce7ddf3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/tests/test_spot_io.py@@ -0,0 +1,277 @@+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io import (+ SpotIoResumeConfig,+ _account_params,+ _cost_window_end,+ _cost_window_start,+ _format_time_value,+ get_resource,+ spot_io_source,+ validate_credentials,+)+++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: SpotIoResumeConfig | 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 TestSpotIoDateFormatting:+ def test_format_time_value(self) -> None:+ value = _format_time_value(datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC))+ assert value == "2026-03-01T12:30:45.000Z"++ def test_cost_window_end_is_spot_format(self) -> None:+ value = _cost_window_end()+ assert value.endswith(".000Z")+ # Round-trips using the exact format Spot documents.+ datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.000Z")++ def test_cost_window_start_is_before_end(self) -> None:+ start = datetime.strptime(_cost_window_start(), "%Y-%m-%dT%H:%M:%S.000Z")+ end = datetime.strptime(_cost_window_end(), "%Y-%m-%dT%H:%M:%S.000Z")+ assert start < end+++class TestSpotIoAccountParams:+ @parameterized.expand(+ [+ ("with_account", "act-123", {"accountId": "act-123"}),+ ("no_account", None, {}),+ ("empty_string", "", {}),+ ]+ )+ def test_account_params(self, _name, account_id, expected) -> None:+ assert _account_params(account_id) == expected+++class TestSpotIoGetResource:+ def test_elastigroups_full_refresh(self) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint="elastigroups"))+ assert resource["name"] == "elastigroups"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/aws/ec2/group"+ assert resource["endpoint"]["data_selector"] == "response.items"+ assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)+ assert resource["table_format"] == "delta"+ assert resource["endpoint"]["params"] == {}++ def test_includes_account_id_when_given(self) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint="ocean_clusters", account_id="act-1"))+ assert resource["endpoint"]["params"] == {"accountId": "act-1"}++ def test_rejects_fanout_endpoint(self) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource(endpoint="elastigroup_costs")+++class TestSpotIoValidateCredentials:+ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid or expired Spot by Flexera API token"),+ (403, False, "Spot by Flexera API token does not have the required permissions"),+ (500, False, "Spot by Flexera API returned an unexpected status: 500"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.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_token="token")++ assert result == (expected_valid, expected_message)+ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.spotinst.io/aws/ec2/group"+ assert call.kwargs["headers"]["Authorization"] == "Bearer token"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.make_tracked_session")+ def test_validate_credentials_passes_account_id(self, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_token="token", account_id="act-9")++ call = mock_session.return_value.get.call_args+ assert call.kwargs["params"] == {"accountId": "act-9"}+++class TestSpotIoSourceTopLevel:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.rest_api_resource")+ def test_top_level_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = spot_io_source(+ api_token="token",+ endpoint="elastigroups",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert response.name == "elastigroups"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.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(SpotIoResumeConfig(paginator_state={"offset": 5}))++ spot_io_source(+ api_token="token",+ endpoint="elastigroups",+ 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.spot_io.spot_io.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()++ spot_io_source(+ api_token="token",+ endpoint="elastigroups",+ 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(SpotIoResumeConfig(paginator_state={"offset": 1}))++ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.rest_api_resource")+ def test_passes_account_id_through_resource_config(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()++ spot_io_source(+ api_token="token",+ account_id="act-42",+ endpoint="elastigroups",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ config = mock_rest_api_resource.call_args.args[0]+ assert config["resources"][0]["endpoint"]["params"] == {"accountId": "act-42"}+++class TestSpotIoFanoutRowFormat:+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_elastigroup_costs_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("elastigroups", [{"id": "sig-1", "name": "web-fleet"}]),+ _FakeDltResource(+ "elastigroup_costs",+ [+ {+ "groupId": "sig-1",+ "instanceId": "i-abc",+ "costs": {"actual": 1.5, "potential": 3.0},+ "_elastigroups_name": "web-fleet",+ }+ ],+ ),+ ]++ response = spot_io_source(+ api_token="token",+ endpoint="elastigroup_costs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ rows = list(cast(Any, response.items()))+ assert rows == [+ {+ "groupId": "sig-1",+ "instanceId": "i-abc",+ "costs": {"actual": 1.5, "potential": 3.0},+ "elastigroup_name": "web-fleet",+ }+ ]+ assert response.primary_keys == ["groupId", "instanceId"]+ assert response.partition_mode is None+++class TestSpotIoFanoutWiring:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.build_dependent_resource")+ def test_fanout_wiring(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])+ manager = _make_manager(SpotIoResumeConfig(paginator_state={"completed": []}))++ spot_io_source(+ api_token="token",+ account_id="act-1",+ endpoint="elastigroup_costs",+ 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"] == "response.items"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "response.items"+ assert "fromDate" in kwargs["child_params_extra"]+ assert "toDate" in kwargs["child_params_extra"]+ assert kwargs["child_params_extra"]["accountId"] == "act-1"+ assert kwargs["fanout"].parent_params == {"accountId": "act-1"}+ assert kwargs["resume_hook"] is not None+ assert kwargs["initial_paginator_state"] == {"completed": []}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io.build_dependent_resource")+ def test_fanout_wiring_without_account_id(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])++ spot_io_source(+ api_token="token",+ endpoint="elastigroup_costs",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert "accountId" not in kwargs["child_params_extra"]+ assert kwargs["fanout"].parent_params == {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/tests/test_spot_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/tests/test_spot_io_source.pynew file mode 100644index 000000000000..00e5814609c3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spot_io/tests/test_spot_io_source.py@@ -0,0 +1,148 @@+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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.spotio import SpotIoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.source import SpotIoSource+from products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.spot_io import SpotIoResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSpotIoSource:+ def setup_method(self) -> None:+ self.source = SpotIoSource()+ self.team_id = 123+ self.config = SpotIoSourceConfig(api_token="spot-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SPOTIO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "SpotIo"+ assert config.label == "Spot by Flexera (Spotinst)"+ 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/spot_io.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/spot-io"++ def test_api_token_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_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_account_id_field_is_optional_plain_text(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "account_id")+ assert field.type == SourceFieldInputConfigType.TEXT+ assert field.secret is False+ assert field.required is False++ 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_full_refresh_only(self) -> None:+ # No endpoint has a real per-row server-side timestamp filter to track a watermark from+ # (see settings.py), so every table stays full refresh.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["elastigroups"])+ assert len(schemas) == 1+ assert schemas[0].name == "elastigroups"++ @parameterized.expand(+ [+ "401 Client Error: Unauthorized for url: https://api.spotinst.io/aws/ec2/group",+ "403 Client Error: Forbidden for url: https://api.spotinst.io/aws/ec2/group",+ ]+ )+ 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.spotinst.io/aws/ec2/group" for key in non_retryable+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.source.validate_spot_io_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ config = SpotIoSourceConfig(api_token="spot-token", account_id="act-1")+ result = self.source.validate_credentials(config, self.team_id, schema_name="elastigroup_costs")++ assert result == (True, None)+ mock_validate.assert_called_once_with("spot-token", "act-1")++ def test_validate_credentials_normalizes_empty_account_id(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.source.validate_spot_io_credentials"+ ) as mock_validate:+ mock_validate.return_value = (True, None)+ config = SpotIoSourceConfig(api_token="spot-token", account_id="")+ self.source.validate_credentials(config, self.team_id)+ mock_validate.assert_called_once_with("spot-token", None)++ 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 SpotIoResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.source.spot_io_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_spot_io_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "elastigroup_costs"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = False+ inputs.incremental_field = None+ manager = mock.MagicMock()+ config = SpotIoSourceConfig(api_token="spot-token", account_id="act-1")++ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_spot_io_source.call_args.kwargs+ assert kwargs["api_token"] == "spot-token"+ assert kwargs["account_id"] == "act-1"+ assert kwargs["endpoint"] == "elastigroup_costs"+ assert kwargs["resumable_source_manager"] is manager++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.spot_io.source.spot_io_source")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(+ self, mock_spot_io_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "elastigroups"+ 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_spot_io_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)