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.

fix(data-imports): stop grouping OpenAI costs by api_key_id (#71784)

Tom Owers95aef37d5c7c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
index 4dce0f43093d..cfa3898f3d18 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/settings.py
@@ -66,7 +66,9 @@ class OpenAIEndpointConfig:
_USAGE_GROUP_BY = ["project_id", "user_id", "api_key_id", "model"]
_COMPLETIONS_GROUP_BY = [*_USAGE_GROUP_BY, "batch", "service_tier"]
_IMAGES_GROUP_BY = [*_USAGE_GROUP_BY, "size", "source"]
-_COSTS_GROUP_BY = ["project_id", "line_item", "api_key_id"]
+# The costs endpoint only accepts project_id and line_item. The SDK types also list api_key_id,
+# but requesting it makes the live API reject the whole request with a 400.
+_COSTS_GROUP_BY = ["project_id", "line_item"]
# For 1d buckets the usage endpoints allow at most 31 buckets per page; costs allows 180.
_USAGE_PAGE_LIMIT = 31
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
index f84cb033714d..c893efe2045a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py
@@ -113,6 +113,13 @@ class TestBucketParams:
assert params["start_time"] == int(datetime(2020, 1, 1, tzinfo=UTC).timestamp())
assert params["limit"] == 180
+ def test_costs_groups_only_by_dimensions_the_api_accepts(self) -> None:
+ # api_key_id grouping is rejected by the live costs endpoint with a 400 that fails the whole
+ # sync, even though the SDK types list it.
+ config = OPENAI_ENDPOINTS["costs"]
+ _, multi = _bucket_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert multi == {"group_by": ["project_id", "line_item"]}
+
class TestFlattenBucketResult:
def test_flattens_nested_amount_and_converts_bucket_times(self) -> None: