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(cloudzero): add budgets, insights and recommendation tables (#102933)

Tom Owers18f677fdab38
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 69ebd29f6fb6..06651c651485 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1662,14 +1662,14 @@ Note: The source targets the PMS API v1.2 (base https://api.cloudbeds.com/api/v1
## Cloudzero — gaps
-Today (2): `Costs`, `Dimensions`
+Today (6): `Budgets`, `Costs`, `Dimensions`, `Insights`, `RecommendationTypes`, `Recommendations`
Diffed against: <https://docs.cloudzero.com/reference/getbillingcosts>
-- [ ] `/v2/optimize/recommendations (+ /v2/optimize/recommendation_types)` — Savings recommendations with estimated dollar impact - CloudZero's headline actionable output, and recommendation_types is the lookup that resolves their type IDs (high)
-- [ ] `/v2/insights` — The cost insights backlog (owner, status, estimated savings) - the workflow layer users join back to costs (high)
-- [ ] `/v2/budgets` — Budget definitions needed for any budget-vs-actual analysis against the Costs table already synced (high)
-- [ ] `/unit-cost/v1/telemetry/{stream}/records (and the sum variant, summetrictelemetry)` — Unit metric telemetry supplies the denominators for cost-per-unit economics, the product's core promise; costs alone cannot produce a unit metric (high)
+- [x] `/v2/optimize/recommendations (+ /v2/optimize/recommendation_types)` — Savings recommendations with estimated dollar impact - CloudZero's headline actionable output, and recommendation_types is the lookup that resolves their type IDs (high)
+- [x] `/v2/insights` — The cost insights backlog (owner, status, estimated savings) - the workflow layer users join back to costs (high)
+- [x] `/v2/budgets` — Budget definitions needed for any budget-vs-actual analysis against the Costs table already synced (high)
+- [ ] `/unit-cost/v1/telemetry/{stream}/records (and the sum variant, summetrictelemetry)` — Unit metric telemetry supplies the denominators for cost-per-unit economics, the product's core promise; costs alone cannot produce a unit metric (high). Skipped: the sum variant (`summetrictelemetry`) is a POST that sends telemetry to CloudZero rather than reading it. The records GET is real but not table material: it needs a `telemetry_stream_name` that no endpoint lists, returns only the most recent records capped at 1000 with no pagination, and documents no response schema. It also sits on the separate `/unit-cost/v1` Telemetry API, not the v2 API this source pins.
- [ ] `sumallocationtelemetry / allocation telemetry records` — Allocation drivers used to split shared cost across tenants or teams - needed to reconcile allocated costs (medium)
- [ ] `/v2/views` — Saved cost views define the grouping/filter dimensions the org actually reports on, a lookup for the Dimensions table (medium)
- [ ] `/v2/insights/{insight_id}/comments` — Discussion trail on insights, useful for measuring time-to-action on cost work (low)
diff --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.py
index fef0a2fd53c4..15ce1c01f129 100644
--- 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.py
@@ -10,6 +10,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Budgets": {
+ "description": (
+ "A budget defined in CloudZero: a monthly planned spend limit for a saved view, with "
+ "optional alert thresholds. Sync this alongside Costs to compare planned against actual spend."
+ ),
+ "docs_url": "https://docs.cloudzero.com/reference/getbudgets",
+ "columns": {
+ "id": "Unique identifier for the budget.",
+ "name": "Name given to the budget in CloudZero.",
+ "view": "The saved view the budget applies to, as an object holding the view's `id`.",
+ "granularity": "Period each planned limit covers. CloudZero only supports `monthly`.",
+ "cost_type": "Cost basis the budget is measured against. CloudZero only supports `real_cost`.",
+ "planned_limits": "Planned spend per period, mapping each period's ISO start date to an `amount`.",
+ "alerts": "Alert configuration, mapping a percentage of the planned limit to `Y` or `N`.",
+ "current": "Actual and planned spend for the current period, returned because PostHog requests `expand=current`.",
+ "created": "Unix epoch timestamp of when the budget was created.",
+ "last_updated": "Unix epoch timestamp of the last change to the budget.",
+ },
+ },
"Costs": {
"description": (
"A time-series row of cloud/SaaS spend for a single usage period (hour/day/week/month/year), "
@@ -30,4 +49,74 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"name": "Human-readable name of the dimension shown in the CloudZero Explorer.",
},
},
+ "Insights": {
+ "description": (
+ "A cost insight: a piece of cost work tracked in CloudZero, carrying its estimated dollar "
+ "impact, effort, and status as it moves from new to addressed."
+ ),
+ "docs_url": "https://docs.cloudzero.com/reference/getinsights",
+ "columns": {
+ "id": "Unique identifier for the insight.",
+ "title": "Short title of the insight.",
+ "description": "Longer description of the cost opportunity or anomaly.",
+ "category": "Category the insight belongs to.",
+ "status": "Where the insight is in its workflow: `new`, `in_progress`, `on_hold`, `addressed` or `ignored`.",
+ "effort": "Estimated effort to act on the insight: `not_set`, `low`, `medium` or `high`.",
+ "cost_impact": "Estimated dollar impact of acting on the insight.",
+ "link": "Link to the insight in the CloudZero app.",
+ "created": "Unix epoch timestamp of when the insight was created.",
+ "last_updated": "Unix epoch timestamp of the last change to the insight.",
+ },
+ },
+ "Recommendations": {
+ "description": (
+ "A savings recommendation CloudZero generated for one resource, with the spend it could save "
+ "over the last 30 days. CloudZero only returns recommendations at or above a $1.00 30-day cost "
+ "impact by default, so lower-impact recommendations are not in this table."
+ ),
+ "docs_url": "https://docs.cloudzero.com/reference/get_all_v2_optimize_recommendations_get",
+ "columns": {
+ "recommendation_id": "Unique identifier for the recommendation.",
+ "title": "Short description of the change CloudZero recommends.",
+ "category": "Category of the recommendation, for example `optimization`.",
+ "recommendation_type_id": "Identifier of the recommendation type, joins to the RecommendationTypes table's `id`.",
+ "optimization_id": "Deprecated by CloudZero in favour of `recommendation_type_id`.",
+ "source": "Who produced the recommendation, for example `CloudZero` or `AWS: Trusted Advisor`.",
+ "status": "Progress on the recommendation: `not_started`, `in_progress`, `addressed` or `ignored`.",
+ "effort": "Estimated effort to apply the recommendation: `not_set`, `low`, `medium` or `high`.",
+ "cost_impact_last_30_days": "Spend the recommendation could have saved over the last 30 days.",
+ "realized_savings_last_30_days": "Spend already saved over the last 30 days by applying the recommendation.",
+ "work_item": "Reference to a ticket for this recommendation in an external tracker, for example Jira.",
+ "resource": "Identifier of the cloud resource the recommendation applies to.",
+ "resource_type": "Type of the cloud resource the recommendation applies to.",
+ "resource_name": "Name of the cloud resource the recommendation applies to.",
+ "account": "Cloud accounts the resource belongs to.",
+ "cloud_provider": "Cloud providers the resource belongs to.",
+ "region": "Cloud regions the resource runs in.",
+ "service": "Cloud services the resource belongs to.",
+ "cluster": "Kubernetes clusters the resource belongs to, for Kubernetes recommendations.",
+ "namespace": "Kubernetes namespaces the resource belongs to, for Kubernetes recommendations.",
+ "pod": "Kubernetes pods the resource belongs to, for Kubernetes recommendations.",
+ "created": "Unix epoch timestamp of when CloudZero raised the recommendation.",
+ "addressed_on_ts": "Unix epoch timestamp of when the recommendation was marked addressed.",
+ },
+ },
+ "RecommendationTypes": {
+ "description": (
+ "A recommendation type: the pattern CloudZero evaluates to produce recommendations, such as "
+ "rightsizing an over-provisioned instance. Resolves the `recommendation_type_id` on the "
+ "Recommendations table."
+ ),
+ "docs_url": "https://docs.cloudzero.com/reference/list_all_recommendation_types",
+ "columns": {
+ "id": "Unique identifier of the recommendation type, for example `CIR-AWS-00216`.",
+ "title": "Title of the recommendation type.",
+ "description": "What the recommendation type looks for and why it saves money.",
+ "cloud_provider": "Cloud provider the type applies to: `AWS`, `Azure`, `GCP`, `Kubernetes`, `Databricks` or `Unknown`.",
+ "category": "Category of the type, for example `waste`, `reservation` or `optimization`.",
+ "effort": "Typical effort to act on this type: `not_set`, `low`, `medium` or `high`.",
+ "status": "Whether your organization has the type `enabled` or `disabled`.",
+ "stage": "Maturity of the type in CloudZero: `alpha`, `beta`, `stable` or `unknown`.",
+ },
+ },
}
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.py
index 4d6eca38a08f..d05088bc03dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/cloudzero.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/cloudzero.py
@@ -6,6 +6,7 @@ from dateutil import parser as dateutil_parser
from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.settings import (
DEFAULT_START_DATE,
+ LIST_ENDPOINTS,
RESTATEMENT_WINDOW_DAYS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -13,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+ JSONResponseCursorPaginatorConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
@@ -45,6 +50,35 @@ def _rolling_incremental_start_date(value: Any) -> str:
return _format_iso8601(dt)
+CURSOR_PAGINATOR: JSONResponseCursorPaginatorConfig = {
+ "type": "cursor",
+ "cursor_path": "pagination.cursor.next_cursor",
+ "cursor_param": "cursor",
+ "param_location": "query",
+}
+
+
+def _get_list_resource(name: str) -> EndpointResource:
+ settings = LIST_ENDPOINTS[name]
+ endpoint: Endpoint = {
+ "path": settings["path"],
+ "params": dict(settings["params"]),
+ "data_selector_required": True,
+ }
+ if settings["data_selector"] is not None:
+ endpoint["data_selector"] = settings["data_selector"]
+ if settings["paginated"]:
+ endpoint["paginator"] = CURSOR_PAGINATOR
+
+ return {
+ "name": name,
+ "table_name": settings["table_name"],
+ "write_disposition": "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+
def get_resource(
name: str,
should_use_incremental_field: bool,
@@ -52,21 +86,10 @@ def get_resource(
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",
- }
+ if name in LIST_ENDPOINTS:
+ return _get_list_resource(name)
+ if name != "Costs":
+ raise ValueError(f"Unknown CloudZero endpoint: {name}")
params: dict[str, Any] = {
"start_date": (
@@ -98,12 +121,7 @@ def get_resource(
"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",
- },
+ "paginator": CURSOR_PAGINATOR,
},
"table_format": "delta",
}
@@ -167,8 +185,8 @@ def cloudzero_source(
# Shared with `CloudzeroSource.get_non_retryable_errors` so the same rejection reads the same way
# whether it surfaces while connecting the source or mid-sync.
KEY_REJECTED_MESSAGE = (
- "CloudZero rejected your API key. Check the key is correct and has the billing:read_costs and "
- "billing:read_dimensions scopes, then reconnect."
+ "CloudZero rejected your API key. Check the key is correct and has the read scopes for the "
+ "tables you want to sync, then reconnect."
)
# `validate_via_probe` reports a transport failure as a `None` status, so anything CloudZero did not
# answer itself leaves the key unjudged. Calling it invalid sends someone off to mint a replacement
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py
index 54dbd81a15e5..f2dac6141f89 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudzero/settings.py
@@ -1,8 +1,14 @@
+from typing import Any, TypedDict
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
ENDPOINTS = (
+ "Budgets",
"Costs",
"Dimensions",
+ "Insights",
+ "RecommendationTypes",
+ "Recommendations",
)
INCREMENTAL_ENDPOINTS = ("Costs",)
@@ -18,10 +24,81 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
],
}
+
+class ListEndpointSettings(TypedDict):
+ path: str
+ table_name: str
+ # jsonpath to the row array in the response envelope, or None when the body is a bare array.
+ data_selector: str | None
+ # True for the v2 list envelope, which carries the next page under `pagination.cursor`.
+ # False for endpoints that answer in a single page.
+ paginated: bool
+ params: dict[str, Any]
+
+
+# Read-only list endpoints. `Costs` is not here: it takes user-chosen query options and is the
+# only endpoint with a server-side time filter, so it is built separately in `cloudzero.py`.
+LIST_ENDPOINTS: dict[str, ListEndpointSettings] = {
+ "Budgets": {
+ "path": "/v2/budgets",
+ "table_name": "budgets",
+ "data_selector": "budgets",
+ "paginated": True,
+ # `current` adds the period's actual and planned spend to each budget, which is what
+ # makes a budget-versus-actual comparison against the Costs table possible.
+ "params": {"expand": ["current"]},
+ },
+ "Dimensions": {
+ "path": "/v2/billing/dimensions",
+ "table_name": "dimensions",
+ "data_selector": "dimensions",
+ "paginated": False,
+ "params": {"include_hidden": "true"},
+ },
+ "Insights": {
+ "path": "/v2/insights",
+ "table_name": "insights",
+ "data_selector": "insights",
+ "paginated": True,
+ "params": {},
+ },
+ "RecommendationTypes": {
+ "path": "/v2/optimize/recommendation_types",
+ "table_name": "recommendation_types",
+ # This endpoint answers with a bare JSON array rather than the v2 list envelope.
+ "data_selector": None,
+ "paginated": False,
+ "params": {},
+ },
+ "Recommendations": {
+ "path": "/v2/optimize/recommendations",
+ "table_name": "recommendations",
+ "data_selector": "recommendations",
+ "paginated": True,
+ # CloudZero defaults this endpoint to 60,000 rows per page. A smaller page keeps the
+ # in-memory page bounded and gives the resumable cursor a checkpoint per page.
+ "params": {"limit": 1000},
+ },
+}
+
+# Primary key per endpoint. `Costs` is absent because its key depends on the dimensions the user
+# groups by, so `source_for_pipeline` assembles it.
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "Budgets": ["id"],
+ "Dimensions": ["id"],
+ "Insights": ["id"],
+ "RecommendationTypes": ["id"],
+ "Recommendations": ["recommendation_id"],
+}
+
# Partition key per endpoint (stable business dates only — never a `_at`/`lastSeen`-style field).
PARTITION_KEYS: dict[str, str | None] = {
+ "Budgets": None,
"Costs": "usage_date",
"Dimensions": None,
+ "Insights": None,
+ "RecommendationTypes": None,
+ "Recommendations": None,
}
# CloudZero's earliest documented cost data; used as the start_date floor for a full (non-incremental) sync.
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.py
index 717f399237fd..a605095ab0d6 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
@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.
GRANULARITY_OPTIONS,
INCREMENTAL_FIELDS,
PARTITION_KEYS,
+ PRIMARY_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 (
@@ -118,7 +119,7 @@ class CloudzeroSource(ResumableSource[CloudzeroSourceConfig, CloudzeroResumeConf
group_by=group_by,
)
- primary_keys = ["usage_date", *group_by] if inputs.schema_name == "Costs" else ["id"]
+ primary_keys = ["usage_date", *group_by] if inputs.schema_name == "Costs" else PRIMARY_KEYS[inputs.schema_name]
partition_key = PARTITION_KEYS.get(inputs.schema_name)
return SourceResponse(
@@ -140,8 +141,11 @@ class CloudzeroSource(ResumableSource[CloudzeroSourceConfig, CloudzeroResumeConf
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."
+ "Enter your CloudZero API key. Grant it `billing:read_dimensions` so PostHog can check "
+ "the connection, then add a scope for each table you want to sync: `billing:read_costs` "
+ "for costs, `budgets:read_budgets` for budgets, `insights:read_insights` for insights, "
+ "and `optimize:list_recommendations` plus `optimize:list_recommendation_types` for "
+ "recommendations. You set these in CloudZero under Settings > API Keys."
),
docsUrl="https://posthog.com/docs/cdp/sources/cloudzero",
iconPath="/static/services/cloudzero.png",
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.py
index fcd249e459ab..1929fe067883 100644
--- 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.py
@@ -3,6 +3,7 @@ from collections.abc import Iterable
from datetime import UTC, date, datetime
from typing import Any, cast
+import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -14,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.
CloudzeroResumeConfig,
_rolling_incremental_start_date,
cloudzero_source,
+ get_resource,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -34,7 +36,7 @@ class TestRollingIncrementalStartDate:
assert _rolling_incremental_start_date(value) == expected
-def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+def _make_http_response(body: Any, status_code: int = 200) -> Response:
resp = Response()
resp.status_code = status_code
resp._content = json.dumps(body).encode()
@@ -59,6 +61,18 @@ def _costs_page(next_cursor: str | None, rows: list[dict[str, Any]]) -> dict[str
}
+def _list_page(data_key: str, next_cursor: str | None, rows: list[dict[str, Any]]) -> dict[str, Any]:
+ return {
+ data_key: rows,
+ "pagination": {
+ "cursor": {
+ "next_cursor": next_cursor,
+ "has_next": next_cursor is not None,
+ },
+ },
+ }
+
+
class TestCloudzeroSourceTransport:
"""End-to-end behaviour of ``cloudzero_source`` via ``rest_api_resource``."""
@@ -68,16 +82,18 @@ class TestCloudzeroSourceTransport:
manager: MagicMock,
responses: list[Response],
**kwargs: Any,
- ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ ) -> tuple[list[str], list[dict[str, Any]], 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.
+ Returns ``(sent_urls, sent_params, rows)``, all captured at send-time: the request URLs,
+ shallow copies of ``request.params``, and the flattened rows the resource yielded.
"""
+ sent_urls: list[str] = []
sent_params: list[dict[str, Any]] = []
response_iter = iter(responses)
def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_urls.append(request.url)
sent_params.append(dict(request.params or {}))
return next(response_iter)
@@ -99,8 +115,56 @@ class TestCloudzeroSourceTransport:
should_use_incremental_field=False,
**kwargs,
)
- list(cast(Iterable[Any], resource))
- return mock_session, sent_params
+ pages = list(cast(Iterable[Any], resource))
+ return sent_urls, sent_params, [row for page in pages for row in page]
+
+ @parameterized.expand(
+ [
+ ("Budgets", "/v2/budgets", {"expand": ["current"]}, _list_page("budgets", None, [{"id": "b-1"}])),
+ ("Dimensions", "/v2/billing/dimensions", {"include_hidden": "true"}, {"dimensions": [{"id": "service"}]}),
+ ("Insights", "/v2/insights", {}, _list_page("insights", None, [{"id": "i-1"}])),
+ # This endpoint answers with a bare array, so it carries no envelope key to select on.
+ ("RecommendationTypes", "/v2/optimize/recommendation_types", {}, [{"id": "CIR-AWS-00216"}]),
+ (
+ "Recommendations",
+ "/v2/optimize/recommendations",
+ {"limit": 1000},
+ _list_page("recommendations", None, [{"recommendation_id": "r-1"}]),
+ ),
+ ]
+ )
+ def test_list_endpoint_reads_its_own_path_params_and_envelope(
+ self, endpoint: str, path: str, expected_params: dict[str, Any], body: Any
+ ) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent_urls, sent_params, rows = self._drive(endpoint, manager, [_make_http_response(body)])
+
+ assert sent_urls == [f"https://api.cloudzero.com{path}"]
+ assert sent_params == [expected_params]
+ assert len(rows) == 1
+
+ @parameterized.expand(
+ [
+ ("Budgets", "budgets"),
+ ("Insights", "insights"),
+ ("Recommendations", "recommendations"),
+ ]
+ )
+ def test_paginated_list_endpoint_follows_the_cursor(self, endpoint: str, data_key: str) -> None:
+ # Without the cursor paginator these endpoints would sync only their first page.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_list_page(data_key, "cursor-1", [{"id": "1"}])),
+ _make_http_response(_list_page(data_key, None, [{"id": "2"}])),
+ ]
+ _, sent_params, rows = self._drive(endpoint, manager, responses)
+
+ assert [p.get("cursor") for p in sent_params] == [None, "cursor-1"]
+ assert len(rows) == 2
def test_costs_pages_through_cursor_and_saves_state(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
@@ -111,7 +175,7 @@ class TestCloudzeroSourceTransport:
_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)
+ _, 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"]
@@ -130,7 +194,7 @@ class TestCloudzeroSourceTransport:
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)
+ _, sent_params, _ = self._drive("Costs", manager, responses)
assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]
manager.load_state.assert_called_once()
@@ -153,7 +217,7 @@ class TestCloudzeroSourceTransport:
responses = [
_make_http_response({"dimensions": [{"id": "service", "name": "Service"}]}),
]
- _, sent_params = self._drive("Dimensions", manager, responses)
+ _, sent_params, _ = self._drive("Dimensions", manager, responses)
assert len(sent_params) == 1
manager.load_state.assert_not_called()
@@ -165,7 +229,7 @@ class TestCloudzeroSourceTransport:
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)
+ _, sent_params, _ = self._drive("Costs", manager, responses)
assert sent_params[0]["start_date"] == "2025-01-01T00:00:00+00:00"
@@ -213,7 +277,7 @@ class TestCloudzeroSourceTransport:
_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"])
+ _, sent_params, _ = self._drive("Costs", manager, responses, group_by=["service", "account"])
assert sent_params[0]["group_by"] == ["service", "account"]
@@ -224,7 +288,7 @@ class TestCloudzeroSourceTransport:
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")
+ _, 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"
@@ -273,3 +337,9 @@ class TestValidateCredentials:
_, kwargs = mock_session.get.call_args
assert kwargs["headers"]["Authorization"] == "raw-key-123"
+
+
+class TestGetResource:
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown CloudZero endpoint"):
+ get_resource("NotAnEndpoint", False, "daily", "real_cost", [])
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.py
index 53692cb963f8..36f348a8d7a5 100644
--- 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.py
@@ -54,7 +54,9 @@ class TestGetSchemas:
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"]
+ # Costs is the only endpoint CloudZero lets us filter by time, so every other table
+ # can only be synced by full refresh.
+ assert [name for name, table in tables.items() if table["sync_methods"] != ["Full refresh"]] == ["Costs"]
class TestValidateCredentials:
@@ -118,9 +120,22 @@ class TestResumableWiring:
assert response.partition_keys == ["usage_date"]
assert response.partition_mode == "datetime"
- def test_dimensions_uses_id_primary_key_and_no_partitioning(self) -> None:
+ @parameterized.expand(
+ [
+ ("Budgets", ["id"]),
+ ("Dimensions", ["id"]),
+ ("Insights", ["id"]),
+ ("RecommendationTypes", ["id"]),
+ # CloudZero names the recommendation key `recommendation_id`, not `id`. A wrong key
+ # here seeds duplicate rows that every later merge multi-matches.
+ ("Recommendations", ["recommendation_id"]),
+ ]
+ )
+ def test_non_cost_endpoints_use_their_own_key_and_no_partitioning(
+ self, schema_name: str, expected_primary_keys: list[str]
+ ) -> None:
inputs = MagicMock()
- inputs.schema_name = "Dimensions"
+ inputs.schema_name = schema_name
inputs.team_id = 1
inputs.job_id = "test_job"
inputs.should_use_incremental_field = False
@@ -130,11 +145,11 @@ class TestResumableWiring:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.cloudzero.source.cloudzero_source"
) as mocked:
- mocked.return_value.name = "Dimensions"
+ mocked.return_value.name = schema_name
mocked.return_value.column_hints = None
response = CloudzeroSource().source_for_pipeline(_config(), manager, inputs)
- assert response.primary_keys == ["id"]
+ assert response.primary_keys == expected_primary_keys
assert response.partition_keys is None
assert response.partition_mode is None