Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add kubecost cloud cost and allocation tables (#113902)

Tom Owersfbee1540a225
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index bf4ee7f2da5a..4fc6157f2b3a 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -736,7 +736,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/koyeb.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kustomer/kustomer.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kustomer/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py
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 8c38098a324d..2e2f77b2a84f 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
@@ -4879,14 +4879,14 @@ Diffed against: <https://raw.githubusercontent.com/koyeb/koyeb-api-client-go/mai
## Kubecost — **thin**
-Today (4): `allocation_by_controller`, `allocation_by_namespace`, `allocation_by_pod`, `assets`
+Today (8): `allocation_by_cluster`, `allocation_by_controller`, `allocation_by_namespace`, `allocation_by_node`, `allocation_by_pod`, `allocation_by_service`, `assets`, `cloud_costs`
Diffed against: <https://docs.kubecost.com/apis/apis-overview>
-- [ ] `GET /model/cloudCost` — cloud provider CUR spend; the entire out-of-cluster half of Kubecost's cost model is absent (high)
-- [ ] `GET /model/allocation?aggregate=cluster` — cluster is the top breakdown dimension and the only aggregation missing from namespace/controller/pod (high)
-- [ ] `GET /model/allocation?aggregate=label:<name>` — label-based chargeback is the standard way teams attribute Kubernetes spend (high)
-- [ ] `GET /model/allocation?aggregate=service and ?aggregate=node` — remaining first-class allocation breakdown dimensions the API documents (medium)
+- [x] `GET /model/cloudCost` — cloud provider CUR spend; the entire out-of-cluster half of Kubecost's cost model is absent (high). Added as `cloud_costs` (unaggregated line items, one-day windows).
+- [x] `GET /model/allocation?aggregate=cluster` — cluster is the top breakdown dimension and the only aggregation missing from namespace/controller/pod (high). Added as `allocation_by_cluster`.
+- [ ] `GET /model/allocation?aggregate=label:<name>` — label-based chargeback is the standard way teams attribute Kubernetes spend (high). Not added: the label name is per deployment, so it is not a fixed table. Pod and controller allocation rows already carry `properties.labels` for label chargeback in SQL.
+- [x] `GET /model/allocation?aggregate=service and ?aggregate=node` — remaining first-class allocation breakdown dimensions the API documents (medium). Added as `allocation_by_service` and `allocation_by_node`.
- [ ] `GET /model/audit/events (Cost Events Audit API)` — cluster-level change history with estimated cost impact, i.e. why spend moved (medium)
- [ ] `GET /model/savings and /model/savings/requestSizingV2` — headline savings-opportunity numbers surfaced in the Savings dashboard (medium)
- [ ] `GET /model/customCost/timeseries (External Costs API)` — third-party service costs joined into total spend (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py
index 48198629eeb5..9e9007bbb87d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/canonical_descriptions.py
@@ -16,7 +16,7 @@ _ALLOCATION_COLUMNS = {
"key": "The allocation's name in the queried aggregation (with special entries like __idle__ for unallocated cluster capacity). Unique per window.",
"window_start": "Start of the one-day query window this row covers (RFC3339). Used as the incremental cursor and partition key.",
"window_end": "End of the one-day query window this row covers (RFC3339).",
- "name": "The name of the allocation, matching the aggregation level (namespace, controller, or pod).",
+ "name": "The name of the allocation, matching the aggregation level (cluster, node, namespace, controller, service, or pod).",
"properties": "Kubernetes metadata for the allocation: cluster, node, namespace, controller, pod, container, labels, and annotations.",
"window": "The queried time window the allocation was computed over, with start and end timestamps.",
"start": "Timestamp of the first observed activity for the allocation within the window.",
@@ -56,6 +56,9 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"allocation_by_namespace": _allocation_entry("namespace"),
"allocation_by_controller": _allocation_entry("controller"),
"allocation_by_pod": _allocation_entry("pod"),
+ "allocation_by_cluster": _allocation_entry("cluster"),
+ "allocation_by_node": _allocation_entry("node"),
+ "allocation_by_service": _allocation_entry("service"),
"assets": {
"description": "Cluster infrastructure costs from the Kubecost Assets API — one row per asset (node, disk, network, load balancer, cluster management fee) per day.",
"docs_url": "https://docs.kubecost.com/apis/monitoring-apis/assets-api",
@@ -83,4 +86,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"totalCost": "Total cumulative cost of the asset over the window.",
},
},
+ "cloud_costs": {
+ "description": "Cloud provider billing costs (e.g. AWS CUR, Azure, GCP billing export) from the Kubecost Cloud Cost API, covering spend inside and outside Kubernetes — one row per billing line item per day.",
+ "docs_url": "https://www.ibm.com/docs/en/kubecost/self-hosted/2.x?topic=apis-cloud-cost-api",
+ "columns": {
+ "key": "The cloud cost item's identifier, built from its billing properties. Unique per window.",
+ "window_start": "Start of the one-day query window this row covers (RFC3339). Used as the incremental cursor and partition key.",
+ "window_end": "End of the one-day query window this row covers (RFC3339).",
+ "properties": "Billing metadata for the item: provider, provider ID, invoice entity, account, region, availability zone, service, category, and labels.",
+ "window": "The time window the cloud cost was computed over, with start and end timestamps.",
+ "listCost": "Cost at the cloud provider's list price, without discounts, with the share of it attributed to Kubernetes (kubernetesPercent).",
+ "netCost": "Cost including discounts and credits, plus one-time and recurring charges, with its Kubernetes share (kubernetesPercent).",
+ "amortizedNetCost": "Net cost with upfront fees removed and amortized across the billing period, with its Kubernetes share (kubernetesPercent).",
+ "invoicedCost": "Cost as invoiced for usage during the billing period, with its Kubernetes share (kubernetesPercent).",
+ "amortizedCost": "Effective cost with upfront payments spread across the billing period, with its Kubernetes share (kubernetesPercent).",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
index 2b7e1992e2cf..8ff38de4252e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/kubecost.py
@@ -132,13 +132,19 @@ def validate_credentials(host: str, api_key: Optional[str]) -> tuple[bool, str |
return True, None
-def _flatten_result_sets(data: Any, requested_window: SyncWindow[str]) -> list[dict[str, Any]]:
- """Flatten Allocation/Assets result sets (dicts keyed by allocation/asset name) into rows.
-
- Windows with no data (e.g. beyond ETL retention) come back as ``data: [null]``,
- so null/non-dict sets are skipped rather than treated as errors.
+def _flatten_result_sets(
+ data: Any, requested_window: SyncWindow[str], result_set_key: Optional[str] = None
+) -> list[dict[str, Any]]:
+ """Flatten result sets (dicts keyed by allocation/asset/cloud cost name) into rows.
+
+ Windows with no data (e.g. beyond ETL retention) come back as ``data: [null]``
+ (or ``cloudCosts: null`` for Cloud Cost), so null/non-dict sets are skipped
+ rather than treated as errors.
"""
rows: list[dict[str, Any]] = []
+ if result_set_key is not None:
+ sets = data.get("sets") if isinstance(data, dict) else None
+ data = [s.get(result_set_key) for s in sets if isinstance(s, dict)] if isinstance(sets, list) else None
if not isinstance(data, list):
return rows
for result_set in data:
@@ -225,7 +231,7 @@ def get_rows(
while day <= today:
window = _day_window(day)
data = call(f"{window.start},{window.end}")
- rows = _flatten_result_sets(data, window)
+ rows = _flatten_result_sets(data, window, config.result_set_key)
if rows:
yield rows
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py
index 825f88ad839a..c21399c78c6c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/settings.py
@@ -1,4 +1,6 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -19,12 +21,15 @@ _WINDOW_INCREMENTAL_FIELDS: list[IncrementalField] = [
]
-@dataclass
+@frozen
class KubecostEndpointConfig:
name: str
path: str
# Extra query params sent on every request (e.g. the Allocation API's `aggregate`).
params: dict[str, str] = field(default_factory=dict)
+ # Set when `data` is an object of `sets`, each holding its result set under this key
+ # (Cloud Cost API), rather than a bare list of result sets (Allocation/Assets APIs).
+ result_set_key: str | None = None
KUBECOST_ENDPOINTS: dict[str, KubecostEndpointConfig] = {
@@ -43,10 +48,31 @@ KUBECOST_ENDPOINTS: dict[str, KubecostEndpointConfig] = {
path="/model/allocation",
params={"aggregate": "pod"},
),
+ "allocation_by_cluster": KubecostEndpointConfig(
+ name="allocation_by_cluster",
+ path="/model/allocation",
+ params={"aggregate": "cluster"},
+ ),
+ "allocation_by_node": KubecostEndpointConfig(
+ name="allocation_by_node",
+ path="/model/allocation",
+ params={"aggregate": "node"},
+ ),
+ "allocation_by_service": KubecostEndpointConfig(
+ name="allocation_by_service",
+ path="/model/allocation",
+ params={"aggregate": "service"},
+ ),
"assets": KubecostEndpointConfig(
name="assets",
path="/model/assets",
),
+ # Unaggregated, so each row is a single billing line item at full granularity.
+ "cloud_costs": KubecostEndpointConfig(
+ name="cloud_costs",
+ path="/model/cloudCost",
+ result_set_key="cloudCosts",
+ ),
}
ENDPOINTS = tuple(KUBECOST_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
index 56eb9f75a934..f7f53d3980d3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kubecost/tests/test_kubecost.py
@@ -136,17 +136,31 @@ class TestGetRows:
with time_machine.travel("2026-07-15T10:00:00Z", tick=False):
yield
+ @pytest.mark.parametrize(
+ "endpoint, data",
+ [
+ ("allocation_by_namespace", [_allocation_set(["__idle__", "argocd"])]),
+ (
+ "cloud_costs",
+ {
+ "sets": [
+ {"cloudCosts": _allocation_set(["__idle__", "argocd"])},
+ {"cloudCosts": None},
+ ],
+ "window": {"start": "null", "end": "null"},
+ },
+ ),
+ ],
+ )
@mock.patch(f"{_MODULE}.make_tracked_session")
- def test_flattens_result_sets_and_injects_key_and_window(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- {"code": 200, "data": [_allocation_set(["__idle__", "argocd"])]}
- )
+ def test_flattens_result_sets_and_injects_key_and_window(self, mock_session, endpoint, data):
+ mock_session.return_value.get.return_value = _response({"code": 200, "data": data})
batches = list(
get_rows(
"https://k.example.com",
"token",
- "allocation_by_namespace",
+ endpoint,
mock.MagicMock(),
_make_manager(),
should_use_incremental_field=True,
@@ -167,7 +181,11 @@ class TestGetRows:
("allocation_by_namespace", "/model/allocation", "namespace"),
("allocation_by_controller", "/model/allocation", "controller"),
("allocation_by_pod", "/model/allocation", "pod"),
+ ("allocation_by_cluster", "/model/allocation", "cluster"),
+ ("allocation_by_node", "/model/allocation", "node"),
+ ("allocation_by_service", "/model/allocation", "service"),
("assets", "/model/assets", None),
+ ("cloud_costs", "/model/cloudCost", None),
],
)
@mock.patch(f"{_MODULE}.make_tracked_session")