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(usage-report): gracefully handle an unmapped region in the AI credits queries (#86944)

Roy Cohen7552918bc68b
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 8f3ca6ce612f..132852a232ba 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -23,6 +23,7 @@ from posthog.test.base import (
from unittest.mock import MagicMock, Mock, patch
from django.apps import apps
+from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.test import SimpleTestCase, TestCase
from django.utils.timezone import now
@@ -62,11 +63,14 @@ from posthog.tasks.usage_report import (
_get_mcp_analytics_event_metric_counts,
_get_team_report,
_get_teams_for_usage_reports,
+ _get_teams_with_ai_credits_for_products,
capture_event,
capture_report,
get_all_event_metrics_in_period,
get_instance_metadata,
+ get_teams_with_ai_credits_used_in_period,
get_teams_with_billable_event_count_in_period,
+ get_teams_with_posthog_code_credits_used_in_period,
get_teams_with_query_metric,
has_non_zero_usage,
send_all_org_usage_reports,
@@ -3565,6 +3569,31 @@ class TestErrorTrackingUsageReport(ClickhouseDestroyTablesMixin, TestCase, Click
assert org_2_report["teams"][str(self.org_2_team_3.pk)]["exceptions_captured_in_period"] == 7
+class TestAICreditsRegionHandling(SimpleTestCase):
+ @patch("posthog.tasks.usage_report.get_instance_region")
+ def test_ai_credits_on_dev_region_returns_empty(self, mock_region: MagicMock) -> None:
+ mock_region.return_value = "DEV"
+
+ period = get_previous_day(at=now() + relativedelta(days=1))
+
+ assert get_teams_with_ai_credits_used_in_period(period.start, period.end) == []
+ assert get_teams_with_posthog_code_credits_used_in_period(period.start, period.end) == []
+
+ @patch("posthog.tasks.usage_report.get_instance_region")
+ def test_ai_credits_on_unexpected_region_raises(self, mock_region: MagicMock) -> None:
+ mock_region.return_value = "APAC"
+ period_end = now()
+ period_start = period_end - timedelta(days=1)
+
+ with self.assertRaisesRegex(ImproperlyConfigured, "APAC"):
+ _get_teams_with_ai_credits_for_products(
+ period_start,
+ period_end,
+ ai_products=[],
+ usage_report_tag="test",
+ )
+
+
@freeze_time("2022-01-10T10:00:00Z")
class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
def setUp(self) -> None:
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index e89e058db2ac..f697882662a2 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -11,6 +11,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Optional, TypedDict, Union
from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.db.models import Count, F, Q, Sum
from django.db.models.functions import Coalesce
@@ -1756,6 +1757,13 @@ def _get_teams_with_ai_credits_for_products(
assert region is not None, "Region must be set in production infrastructure"
return []
+ if region == "DEV":
+ # Hosted DEV has no internal team containing AI billing events.
+ return []
+
+ if region not in CLOUD_REGION_TO_TEAM_ID or region not in CLOUD_REGION_TO_URL:
+ raise ImproperlyConfigured(f"AI credit usage reporting is not configured for CLOUD_DEPLOYMENT={region!r}")
+
team_to_query = CLOUD_REGION_TO_TEAM_ID[region]
region_filter_params = build_ai_billing_region_filter(team_to_query, CLOUD_REGION_TO_URL[region])
if region_filter_params is None: