: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 CloudZero source (#73185)
Tom Owers356c70ad9492
diff --git a/frontend/public/services/cloudzero.png b/frontend/public/services/cloudzero.pngindex c7a6d437ee23..e8a7ba5f0af8 100644Binary files a/frontend/public/services/cloudzero.png and b/frontend/public/services/cloudzero.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 2f6f3f2df107..0b670108a413 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -126,6 +126,7 @@ the row lists both.| checkmarx | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ || churnkey | HTTP | requests | ✅ |+| cloudzero | HTTP | requests + `rest_source.RESTClient` | ✅ || coassemble | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || codacy | HTTP | requests | ✅ |@@ -839,7 +840,6 @@ doesn't conflict with concurrent PRs.- cloudability- cloudbeds- cloudsmith-- cloudzero- clover- coassemble- cockroachdbdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/canonical_descriptions.pynew file mode 100644index 000000000000..fef0a2fd53c4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/canonical_descriptions.py@@ -0,0 +1,33 @@+"""Canonical, documentation-sourced descriptions for CloudZero endpoints and columns.++Sourced from the official CloudZero API v2 reference (https://docs.cloudzero.com/reference).+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced CloudZero 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 = {+ "Costs": {+ "description": (+ "A time-series row of cloud/SaaS spend for a single usage period (hour/day/week/month/year), "+ "optionally broken down by one or more CostFormation dimensions (e.g. service, account)."+ ),+ "docs_url": "https://docs.cloudzero.com/reference/getbillingcosts",+ "columns": {+ "usage_date": "Start of the usage period this row covers, as an ISO 8601 datetime.",+ "cost": "Cost for the usage period (and dimension breakdown, if grouped), in the configured cost_type.",+ "projected_row_count": "Projected total number of rows for the query, only present when include_projected_row_count is requested.",+ },+ },+ "Dimensions": {+ "description": "A CostFormation dimension available to group or filter cost data by (e.g. service, account, team).",+ "docs_url": "https://docs.cloudzero.com/reference/getbillingdimensions",+ "columns": {+ "id": "Dimension identifier, used as a `group_by` value or a `filters` key when querying costs.",+ "name": "Human-readable name of the dimension shown in the CloudZero Explorer.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/cloudzero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/cloudzero.pynew file mode 100644index 000000000000..81142520c627--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/cloudzero.py@@ -0,0 +1,171 @@+import dataclasses+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++from dateutil import parser as dateutil_parser++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.settings import (+ DEFAULT_START_DATE,+ RESTATEMENT_WINDOW_DAYS,+)+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.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++CLOUDZERO_BASE_URL = "https://api.cloudzero.com"+++class CloudzeroResumeConfig:+ next_cursor: str+++def _to_datetime(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time())+ return dateutil_parser.parse(str(value))+++def _format_iso8601(value: datetime) -> str:+ if value.tzinfo is None:+ value = value.replace(tzinfo=UTC)+ return value.astimezone(UTC).isoformat()+++def _rolling_incremental_start_date(value: Any) -> str:+ """Roll the incremental `start_date` back a few days to recapture CloudZero cost restatements."""+ dt = _to_datetime(value) - timedelta(days=RESTATEMENT_WINDOW_DAYS)+ return _format_iso8601(dt)+++def get_resource(+ name: str,+ should_use_incremental_field: bool,+ granularity: str,+ cost_type: str,+ group_by: list[str],+) -> EndpointResource:+ if name == "Dimensions":+ return {+ "name": "Dimensions",+ "table_name": "dimensions",+ "write_disposition": "replace",+ "endpoint": {+ "data_selector": "dimensions",+ "path": "/v2/billing/dimensions",+ "params": {+ "include_hidden": "true",+ },+ "data_selector_required": True,+ },+ "table_format": "delta",+ }++ params: dict[str, Any] = {+ "start_date": (+ {+ "type": "incremental",+ "cursor_path": "usage_date",+ "initial_value": DEFAULT_START_DATE,+ "convert": _rolling_incremental_start_date,+ }+ if should_use_incremental_field+ else DEFAULT_START_DATE+ ),+ "granularity": granularity,+ "cost_type": cost_type,+ }+ if group_by:+ # CloudZero accepts `group_by` as a repeated query param (one per dimension id).+ params["group_by"] = group_by++ return {+ "name": "Costs",+ "table_name": "costs",+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ },+ "endpoint": {+ "data_selector": "costs",+ "path": "/v2/billing/costs",+ "params": params,+ "data_selector_required": True,+ "paginator": {+ "type": "cursor",+ "cursor_path": "pagination.cursor.next_cursor",+ "cursor_param": "cursor",+ "param_location": "query",+ },+ },+ "table_format": "delta",+ }+++def cloudzero_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CloudzeroResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+ granularity: str = "daily",+ cost_type: str = "real_cost",+ group_by: Optional[list[str]] = None,+):+ config: RESTAPIConfig = {+ "client": {+ "base_url": CLOUDZERO_BASE_URL,+ "auth": {+ # CloudZero puts the raw API key in `Authorization` — no `Bearer` prefix.+ "type": "api_key",+ "name": "Authorization",+ "api_key": api_key,+ "location": "header",+ },+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ },+ },+ "resources": [get_resource(endpoint, should_use_incremental_field, granularity, cost_type, group_by or [])],+ }++ 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 = {"cursor": resume_config.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the manager's TTL (24h) already+ # matches CloudZero's own cursor validity window, so an expired resume naturally falls+ # back to a fresh query rather than replaying a stale (410 Expired Cache) cursor.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(CloudzeroResumeConfig(next_cursor=str(state["cursor"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(api_key: str) -> bool:+ res = make_tracked_session(redact_values=(api_key,)).get(+ f"{CLOUDZERO_BASE_URL}/v2/billing/dimensions",+ headers={"Authorization": api_key},+ )+ return res.status_code == 200diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.pynew file mode 100644index 000000000000..54dbd81a15e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py@@ -0,0 +1,45 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++ENDPOINTS = (+ "Costs",+ "Dimensions",+)++INCREMENTAL_ENDPOINTS = ("Costs",)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "Costs": [+ {+ "label": "usage_date",+ "type": IncrementalFieldType.DateTime,+ "field": "usage_date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}++# Partition key per endpoint (stable business dates only — never a `_at`/`lastSeen`-style field).+PARTITION_KEYS: dict[str, str | None] = {+ "Costs": "usage_date",+ "Dimensions": None,+}++# CloudZero's earliest documented cost data; used as the start_date floor for a full (non-incremental) sync.+DEFAULT_START_DATE = "2025-01-01T00:00:00+00:00"++# CloudZero can restate historical costs after the fact, so incremental syncs roll the start_date+# back by this many days to recapture any values that changed since the last sync.+RESTATEMENT_WINDOW_DAYS = 7++GRANULARITY_OPTIONS = ("hourly", "daily", "weekly", "monthly", "yearly")++COST_TYPE_OPTIONS = (+ "billed_cost",+ "discounted_cost",+ "amortized_cost",+ "discounted_amortized_cost",+ "real_cost",+ "on_demand_cost",+ "invoiced_amortized_cost",+ "usage_amount",+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/source.pyindex 663b3e4bf2a3..4ad45037bfdc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/source.py@@ -1,32 +1,198 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.cloudzero.cloudzero import (+ CloudzeroResumeConfig,+ cloudzero_source,+ validate_credentials as validate_cloudzero_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.settings import (+ COST_TYPE_OPTIONS,+ ENDPOINTS,+ GRANULARITY_OPTIONS,+ INCREMENTAL_FIELDS,+ PARTITION_KEYS,+)+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.cloudzero import (CloudzeroSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _parse_group_by(group_by: str | None) -> list[str]:+ if not group_by:+ return []+ return [dimension.strip() for dimension in group_by.split(",") if dimension.strip()]++@SourceRegistry.register-class CloudzeroSource(SimpleSource[CloudzeroSourceConfig]):+class CloudzeroSource(ResumableSource[CloudzeroSourceConfig, CloudzeroResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.cloudzero.com/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLOUDZERO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "403 Client Error: Forbidden": "CloudZero authentication failed. Please check your API key and its assigned scopes.",+ "Unauthorized": "CloudZero authentication failed. Please check your API key and its assigned scopes.",+ "410 Client Error: Gone": (+ "CloudZero's paged result cache expired (results are only valid for 24 hours). "+ "Please retry the sync to start a fresh query."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CloudzeroSourceConfig,+ 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: CloudzeroSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_cloudzero_credentials(config.api_key):+ return True, None++ return False, "Invalid credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloudzeroResumeConfig]:+ return ResumableSourceManager[CloudzeroResumeConfig](inputs, CloudzeroResumeConfig)++ def source_for_pipeline(+ self,+ config: CloudzeroSourceConfig,+ resumable_source_manager: ResumableSourceManager[CloudzeroResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ group_by = _parse_group_by(config.group_by)+ resource = cloudzero_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,+ granularity=config.granularity,+ cost_type=config.cost_type,+ group_by=group_by,+ )++ primary_keys = ["usage_date", *group_by] if inputs.schema_name == "Costs" else ["id"]+ partition_key = PARTITION_KEYS.get(inputs.schema_name)++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=primary_keys,+ column_hints=resource.column_hints,+ partition_count=1 if partition_key else None,+ partition_size=1 if partition_key else None,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CLOUDZERO,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="CloudZero",+ caption=(+ "Enter your CloudZero API key. The key must be granted the `billing:read_costs` and "+ "`billing:read_dimensions` scopes in CloudZero under Settings > API Keys."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/cloudzero",iconPath="/static/services/cloudzero.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["cloud cost", "finops", "billing"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="granularity",+ label="Granularity",+ required=True,+ defaultValue="daily",+ options=[+ SourceFieldSelectConfigOption(label=option.capitalize(), value=option)+ for option in GRANULARITY_OPTIONS+ ],+ ),+ SourceFieldSelectConfig(+ name="cost_type",+ label="Cost type",+ required=True,+ defaultValue="real_cost",+ options=[+ SourceFieldSelectConfigOption(label=option.replace("_", " ").capitalize(), value=option)+ for option in COST_TYPE_OPTIONS+ ],+ ),+ SourceFieldInputConfig(+ name="group_by",+ label="Group costs by dimensions (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="e.g. service,account",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero.pynew file mode 100644index 000000000000..13437d96bc12--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero.py@@ -0,0 +1,261 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.cloudzero import (+ CloudzeroResumeConfig,+ _rolling_incremental_start_date,+ cloudzero_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class TestRollingIncrementalStartDate:+ @parameterized.expand(+ [+ ("datetime", datetime(2026, 1, 15, 12, 0, 0, tzinfo=UTC), "2026-01-08T12:00:00+00:00"),+ ("date", date(2026, 1, 15), "2026-01-08T00:00:00+00:00"),+ ("iso_string", "2026-01-15T12:00:00+00:00", "2026-01-08T12:00:00+00:00"),+ ("naive_datetime", datetime(2026, 1, 15, 12, 0, 0), "2026-01-08T12:00:00+00:00"),+ ]+ )+ def test_rolls_back_by_restatement_window(self, _name: str, value: Any, expected: str) -> None:+ # CloudZero can restate historical costs, so the incremental start_date must roll back+ # a fixed window rather than resuming exactly where the last sync left off.+ assert _rolling_incremental_start_date(value) == expected+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _costs_page(next_cursor: str | None, rows: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "costs": rows,+ "pagination": {+ "page_count": 1,+ "item_count": len(rows),+ "total_count": len(rows),+ "cursor": {+ "next_cursor": next_cursor,+ "previous_cursor": None,+ "has_next": next_cursor is not None,+ "has_previous": False,+ },+ },+ }+++class TestCloudzeroSourceTransport:+ """End-to-end behaviour of ``cloudzero_source`` via ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ **kwargs: Any,+ ) -> tuple[MagicMock, list[dict[str, Any]]]:+ """Drive ``cloudzero_source`` with a mocked HTTP session.++ Returns ``(mock_session, sent_params)`` where ``sent_params`` is a list of shallow+ copies of ``request.params`` captured at send-time.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = cloudzero_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ **kwargs,+ )+ list(cast(Iterable[Any], resource))+ return mock_session, sent_params++ def test_costs_pages_through_cursor_and_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_costs_page("cursor-1", [{"usage_date": "2025-01-01T00:00:00+00:00", "cost": 1.0}])),+ _make_http_response(_costs_page("cursor-2", [{"usage_date": "2025-01-02T00:00:00+00:00", "cost": 2.0}])),+ _make_http_response(_costs_page(None, [{"usage_date": "2025-01-03T00:00:00+00:00", "cost": 3.0}])),+ ]+ _, sent_params = self._drive("Costs", manager, responses)++ cursors_sent = [p.get("cursor") for p in sent_params]+ assert cursors_sent == [None, "cursor-1", "cursor-2"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ CloudzeroResumeConfig(next_cursor="cursor-1"),+ CloudzeroResumeConfig(next_cursor="cursor-2"),+ ]++ def test_costs_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CloudzeroResumeConfig(next_cursor="cursor-resumed")++ responses = [+ _make_http_response(_costs_page(None, [{"usage_date": "2025-01-04T00:00:00+00:00", "cost": 4.0}])),+ ]+ _, sent_params = self._drive("Costs", manager, responses)++ assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]+ manager.load_state.assert_called_once()++ def test_costs_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_costs_page(None, [{"usage_date": "2025-01-05T00:00:00+00:00", "cost": 5.0}])),+ ]+ self._drive("Costs", manager, responses)++ manager.save_state.assert_not_called()++ def test_dimensions_endpoint_does_not_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"dimensions": [{"id": "service", "name": "Service"}]}),+ ]+ _, sent_params = self._drive("Dimensions", manager, responses)++ assert len(sent_params) == 1+ manager.load_state.assert_not_called()++ def test_full_refresh_uses_default_start_date(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_costs_page(None, [{"usage_date": "2025-01-05T00:00:00+00:00", "cost": 5.0}])),+ ]+ _, sent_params = self._drive("Costs", manager, responses)++ assert sent_params[0]["start_date"] == "2025-01-01T00:00:00+00:00"++ def test_incremental_rolls_start_date_back_from_watermark(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_costs_page(None, [{"usage_date": "2026-01-15T00:00:00+00:00", "cost": 5.0}])),+ ]+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = cloudzero_source(+ api_key="test-key",+ endpoint="Costs",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value="2026-01-15T00:00:00+00:00",+ should_use_incremental_field=True,+ )+ list(cast(Iterable[Any], resource))++ assert sent_params[0]["start_date"] == "2026-01-08T00:00:00+00:00"++ def test_group_by_sent_as_repeated_query_param(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(+ _costs_page(None, [{"usage_date": "2025-01-05T00:00:00+00:00", "service": "ec2", "cost": 5.0}])+ ),+ ]+ _, sent_params = self._drive("Costs", manager, responses, group_by=["service", "account"])++ assert sent_params[0]["group_by"] == ["service", "account"]++ def test_granularity_and_cost_type_are_forwarded(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_costs_page(None, [{"usage_date": "2025-01-05T00:00:00+00:00", "cost": 5.0}])),+ ]+ _, sent_params = self._drive("Costs", manager, responses, granularity="monthly", cost_type="billed_cost")++ assert sent_params[0]["granularity"] == "monthly"+ assert sent_params[0]["cost_type"] == "billed_cost"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("forbidden", 403, False),+ ("unauthorized", 401, False),+ ]+ )+ def test_status_code_maps_to_validity(self, _name: str, status_code: int, expected: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.cloudzero.make_tracked_session"+ ) as mock_make_session:+ mock_response = MagicMock()+ mock_response.status_code = status_code+ mock_make_session.return_value.get.return_value = mock_response++ assert validate_credentials("test-key") is expected++ def test_sends_raw_api_key_without_bearer_prefix(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.cloudzero.make_tracked_session"+ ) as mock_make_session:+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = mock_response++ validate_credentials("raw-key-123")++ _, kwargs = mock_session.get.call_args+ assert kwargs["headers"]["Authorization"] == "raw-key-123"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero_source.pynew file mode 100644index 000000000000..8717f0671165--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/tests/test_cloudzero_source.py@@ -0,0 +1,230 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.cloudzero import CloudzeroResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.source import (+ CloudzeroSource,+ _parse_group_by,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(+ api_key: str = "key", granularity: str = "daily", cost_type: str = "real_cost", group_by: str | None = None+) -> Any:+ config = MagicMock()+ config.api_key = api_key+ config.granularity = granularity+ config.cost_type = cost_type+ config.group_by = group_by+ return config+++class TestParseGroupBy:+ @parameterized.expand(+ [+ ("none", None, []),+ ("empty_string", "", []),+ ("single", "service", ["service"]),+ ("multiple", "service,account", ["service", "account"]),+ ("whitespace_and_blank_entries", " service , , account ", ["service", "account"]),+ ]+ )+ def test_parse_group_by(self, _name: str, raw: str | None, expected: list[str]) -> None:+ assert _parse_group_by(raw) == expected+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert CloudzeroSource().source_type == ExternalDataSourceType.CLOUDZERO++ def test_config_is_visible_and_alpha(self) -> None:+ config = CloudzeroSource().get_source_config+ # A finished source must not be hidden from users.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cloudzero"++ def test_fields(self) -> None:+ fields = CloudzeroSource().get_source_config.fields+ input_fields = {f.name: f for f in fields if isinstance(f, SourceFieldInputConfig)}+ select_fields = {f.name: f for f in fields if isinstance(f, SourceFieldSelectConfig)}++ assert set(input_fields) == {"api_key", "group_by"}+ assert input_fields["api_key"].required is True+ assert input_fields["api_key"].secret is True+ assert input_fields["group_by"].required is False+ assert input_fields["group_by"].secret is False++ assert set(select_fields) == {"granularity", "cost_type"}+ assert select_fields["granularity"].defaultValue == "daily"+ assert select_fields["cost_type"].defaultValue == "real_cost"++ def test_api_version_metadata(self) -> None:+ assert CloudzeroSource.supported_versions == ("v2",)+ assert CloudzeroSource.default_version == "v2"+ assert CloudzeroSource.api_docs_url.startswith("https://")+++class TestGetSchemas:+ def test_only_costs_is_incremental(self) -> None:+ schemas = {s.name: s for s in CloudzeroSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ assert schemas["Costs"].supports_incremental is True+ assert [f["field"] for f in schemas["Costs"].incremental_fields] == ["usage_date"]+ assert schemas["Dimensions"].supports_incremental is False++ def test_names_filter(self) -> None:+ schemas = CloudzeroSource().get_schemas(_config(), team_id=1, names=["Dimensions"])+ assert {s.name for s in schemas} == {"Dimensions"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O) — public docs render the table list.+ assert CloudzeroSource.lists_tables_without_credentials is True+ tables = {t["name"]: t for t in CloudzeroSource().get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert "Incremental" in tables["Costs"]["sync_methods"]+ assert tables["Dimensions"]["sync_methods"] == ["Full refresh"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", True, (True, None)),+ ("invalid", False, (False, "Invalid credentials")),+ ]+ )+ def test_plumbs_transport_result(+ self, _name: str, transport_result: bool, expected: tuple[bool, str | None]+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.source.validate_cloudzero_credentials",+ return_value=transport_result,+ ) as mocked:+ assert CloudzeroSource().validate_credentials(_config(), team_id=1) == expected+ mocked.assert_called_once_with("key")+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ manager = CloudzeroSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CloudzeroResumeConfig++ @parameterized.expand(+ [+ ("incremental", True, "2026-01-01T00:00:00+00:00"),+ # A stale watermark must not leak into a full-refresh run.+ ("full_refresh", False, None),+ ]+ )+ def test_source_for_pipeline_plumbs_arguments(+ self, _name: str, should_use_incremental_field: bool, expected_last_value: Any+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = "Costs"+ inputs.team_id = 1+ inputs.job_id = "test_job"+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"+ manager = MagicMock()+ config = _config(group_by="service, account")++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.source.cloudzero_source"+ ) as mocked:+ mocked.return_value.name = "Costs"+ mocked.return_value.column_hints = None+ response = CloudzeroSource().source_for_pipeline(config, manager, inputs)++ mocked.assert_called_once_with(+ api_key="key",+ endpoint="Costs",+ team_id=1,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ granularity="daily",+ cost_type="real_cost",+ group_by=["service", "account"],+ )+ # Composite key must include every group_by dimension, since rows with the same+ # usage_date differ only by their dimension values.+ assert response.primary_keys == ["usage_date", "service", "account"]+ assert response.partition_keys == ["usage_date"]+ assert response.partition_mode == "datetime"++ def test_dimensions_uses_id_primary_key_and_no_partitioning(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "Dimensions"+ inputs.team_id = 1+ inputs.job_id = "test_job"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.source.cloudzero_source"+ ) as mocked:+ mocked.return_value.name = "Dimensions"+ mocked.return_value.column_hints = None+ response = CloudzeroSource().source_for_pipeline(_config(), manager, inputs)++ assert response.primary_keys == ["id"]+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.cloudzero.com/v2/billing/costs?start_date=2025-01-01",+ ),+ ("unauthorized", "Unauthorized for url: https://api.cloudzero.com/v2/billing/dimensions"),+ (+ "expired_cache",+ "410 Client Error: Gone for url: https://api.cloudzero.com/v2/billing/costs?cursor=abc",+ ),+ ]+ )+ def test_permanent_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = CloudzeroSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.cloudzero.com/v2/billing/costs"),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.cloudzero.com/v2/billing/costs",+ ),+ ("bad_request", "400 Client Error: Bad Request for url: https://api.cloudzero.com/v2/billing/costs"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = CloudzeroSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestCanonicalDescriptions:+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:+ # Every documented table must map to a real endpoint, or its descriptions never apply.+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)++ def test_source_exposes_canonical_descriptions(self) -> None:+ assert CloudzeroSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONSdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudzero.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudzero.pyindex ec73ed19c70e..df322f46436c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudzero.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudzero.py@@ -1,9 +1,23 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass CloudzeroSourceConfig(config.Config):- pass+ api_key: str+ granularity: Literal["hourly", "daily", "weekly", "monthly", "yearly"] = config.value(default="daily")+ cost_type: Literal[+ "billed_cost",+ "discounted_cost",+ "amortized_cost",+ "discounted_amortized_cost",+ "real_cost",+ "on_demand_cost",+ "invoiced_amortized_cost",+ "usage_amount",+ ] = config.value(default="real_cost")+ group_by: str | None = None