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(billing): resolve AI usage region group dynamically (#60981)

Chris Volzer19da02813885
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index 23131fc3ed1f..f791369d11e3 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -226,7 +226,7 @@ class TestQuotaLimiting(BaseTest):
self.organization.save()
time.sleep(1)
- with self.assertNumQueries(FuzzyInt(3, 6)):
+ with self.assertNumQueries(FuzzyInt(3, 7)):
quota_limited_orgs, quota_limiting_suspended_orgs, _stats = update_all_orgs_billing_quotas()
assert patch_capture.call_count == 0 # No events should be captured since org won't be limited
assert quota_limited_orgs["events"] == {}
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/command.py b/ee/hogai/chat_agent/slash_commands/commands/usage/command.py
index b2c9707eca1b..68b2dfb9c6d0 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/command.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/command.py
@@ -14,8 +14,8 @@ from ee.hogai.chat_agent.slash_commands.commands.usage.queries import (
get_ai_credits_for_conversation,
get_ai_credits_for_team,
get_ai_free_tier_credits,
+ get_ai_usage_period,
get_conversation_start_time,
- get_past_month_start,
)
from ee.hogai.utils.types import AssistantState, PartialAssistantState
@@ -40,30 +40,33 @@ class UsageCommand(SlashCommand):
messages=[AssistantMessage(content="Unable to retrieve conversation start time.", id=str(uuid4()))]
)
- past_month_start = get_past_month_start()
- now = timezone.now()
+ usage_period = get_ai_usage_period(self._team, config.get("configurable", {}).get("billing_context"))
conversation_credits = await sync_to_async(get_ai_credits_for_conversation, thread_sensitive=False)(
team_id=self._team.id,
conversation_id=conversation_id,
begin=conversation_start,
- end=now,
+ end=timezone.now(),
)
- past_month_credits = await sync_to_async(get_ai_credits_for_team, thread_sensitive=False)(
- team_id=self._team.id,
- begin=past_month_start,
- end=now,
+ period_credits = (
+ await sync_to_async(get_ai_credits_for_team, thread_sensitive=False)(
+ team_id=self._team.id,
+ begin=usage_period.query_start,
+ end=usage_period.end,
+ )
+ if usage_period.query_start < usage_period.end
+ else 0
)
free_tier_credits = get_ai_free_tier_credits(self._team.id)
usage_message = format_usage_message(
conversation_credits=conversation_credits,
- past_month_credits=past_month_credits,
+ period_credits=period_credits,
free_tier_credits=free_tier_credits,
conversation_start=conversation_start,
- past_month_start=past_month_start,
+ usage_period=usage_period,
)
return PartialAssistantState(messages=[AssistantMessage(content=usage_message, id=str(uuid4()))])
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
index 8efb5d5ce11d..2d3a295113f9 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
@@ -1,23 +1,31 @@
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from uuid import UUID
+import dateutil.parser
import posthoganalytics
+from pydantic import ValidationError
+
+from posthog.schema import MaxBillingContext
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.models.group_type_mapping import get_group_types_for_team
from posthog.tasks.usage_report import (
AI_BILLING_EXCLUDED_TOOLS,
AI_COST_MARKUP_PERCENT,
CLOUD_REGION_TO_TEAM_ID,
CLOUD_REGION_TO_URL,
+ build_ai_billing_region_filter,
)
from posthog.utils import get_instance_region
from products.posthog_ai.backend.models.assistant import Conversation
+if TYPE_CHECKING:
+ from posthog.models import Team
+
# Default free tier limit in credits
DEFAULT_FREE_TIER_CREDITS = 2000
@@ -30,23 +38,13 @@ CH_BILLING_SETTINGS = {
"max_execution_time": 60, # 1 minute
}
-# Name of the group type whose value is the customer cloud URL (e.g. https://eu.posthog.com).
-# Sent via `event_usage.groups(...)` when capturing $ai_trace / $ai_generation events.
-INSTANCE_GROUP_TYPE = "instance"
-
-def _get_instance_group_type_index(team_id: int) -> int | None:
- """Resolve the $group_N index that holds the cloud URL for the given internal AI events team.
-
- group_type_index is assigned in the order group types were registered per project,
- so the same `instance` group lives at different indexes between the EU (team 1)
- and US (team 2) internal projects.
- """
- for mapping in get_group_types_for_team(team_id):
- if mapping.get("group_type") == INSTANCE_GROUP_TYPE:
- index = mapping.get("group_type_index")
- return int(index) if index is not None else None
- return None
+@dataclass(frozen=True)
+class AiUsagePeriod:
+ label: str
+ start: datetime
+ end: datetime
+ query_start: datetime
def _get_billing_config_payload() -> dict | None:
@@ -154,13 +152,14 @@ def get_ai_credits(
# Only filter by region in production (EU/US) - local dev events don't have region set.
# The $group_N index for the `instance` group differs across internal projects,
# so resolve it from the destination team rather than hard-coding $group_1.
- is_production = region in ["EU", "US"]
- instance_group_index = _get_instance_group_type_index(team_to_query) if is_production else None
- region_filter = (
- f"AND JSONExtractString(properties, '$group_{instance_group_index}') = %(region_url)s"
- if instance_group_index is not None
- else ""
- )
+ region_filter_clause = ""
+ region_filter_params: dict[str, str] = {}
+ if region in CLOUD_REGION_TO_TEAM_ID:
+ region_filter = build_ai_billing_region_filter(team_to_query, CLOUD_REGION_TO_URL[region_value])
+ if region_filter is None:
+ return 0
+ region_filter_params = region_filter
+ region_filter_clause = "AND JSONExtractString(properties, %(region_group_property)s) = %(region_url)s"
# Session filter expression for PREWHERE (must NOT use alias)
session_filter_prewhere = (
@@ -227,7 +226,7 @@ def get_ai_credits(
FROM events
PREWHERE
team_id = %(team_to_query)s
- {region_filter}
+ {region_filter_clause}
AND timestamp >= %(begin)s
AND timestamp < %(end)s
AND event = '$ai_trace'
@@ -250,7 +249,7 @@ def get_ai_credits(
FROM events
PREWHERE
team_id = %(team_to_query)s
- {region_filter}
+ {region_filter_clause}
AND timestamp >= %(begin)s
AND timestamp < %(end)s
AND event = '$ai_generation'
@@ -277,11 +276,9 @@ def get_ai_credits(
"end": end,
"markup_multiplier": 1 + AI_COST_MARKUP_PERCENT,
"excluded_tools": AI_BILLING_EXCLUDED_TOOLS,
+ **region_filter_params,
}
- if instance_group_index is not None:
- params["region_url"] = CLOUD_REGION_TO_URL[region_value]
-
if conversation_id:
params["session_id"] = str(conversation_id)
@@ -312,19 +309,99 @@ def get_past_month_start() -> datetime:
return max(thirty_days_ago, ga_launch_date)
+def _parse_period_datetime(value: object) -> datetime | None:
+ if not isinstance(value, str):
+ return None
+
+ try:
+ parsed = dateutil.parser.isoparse(value)
+ except (ValueError, TypeError):
+ return None
+
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.astimezone(UTC)
+
+
+def _build_billing_period(start_value: object, end_value: object) -> tuple[datetime, datetime] | None:
+ start = _parse_period_datetime(start_value)
+ end = _parse_period_datetime(end_value)
+
+ if start is None or end is None or start >= end:
+ return None
+
+ return start, end
+
+
+def _get_billing_period_from_context(
+ billing_context: MaxBillingContext | dict[str, object] | None,
+) -> tuple[datetime, datetime] | None:
+ if not billing_context:
+ return None
+
+ try:
+ context = (
+ billing_context
+ if isinstance(billing_context, MaxBillingContext)
+ else MaxBillingContext.model_validate(billing_context)
+ )
+ except ValidationError:
+ return None
+
+ if not context.billing_period:
+ return None
+
+ return _build_billing_period(
+ context.billing_period.current_period_start,
+ context.billing_period.current_period_end,
+ )
+
+
+def _get_billing_period_from_organization(team: "Team") -> tuple[datetime, datetime] | None:
+ usage = team.organization.usage
+ if not isinstance(usage, dict):
+ return None
+
+ period = usage.get("period")
+ if not isinstance(period, list) or len(period) < 2:
+ return None
+
+ return _build_billing_period(period[0], period[1])
+
+
+def get_ai_usage_period(team: "Team", billing_context: MaxBillingContext | dict[str, object] | None) -> AiUsagePeriod:
+ billing_period = _get_billing_period_from_context(billing_context) or _get_billing_period_from_organization(team)
+ if billing_period:
+ period_start, period_end = billing_period
+ return AiUsagePeriod(
+ label="Billing period",
+ start=period_start,
+ end=period_end,
+ query_start=max(period_start, get_ga_launch_date()),
+ )
+
+ start = get_past_month_start()
+ return AiUsagePeriod(
+ label="Past 30 days",
+ start=start,
+ end=datetime.now(UTC),
+ query_start=start,
+ )
+
+
def format_usage_message(
conversation_credits: int,
- past_month_credits: int,
+ period_credits: int,
free_tier_credits: int,
conversation_start: Optional[datetime] = None,
- past_month_start: Optional[datetime] = None,
+ usage_period: Optional[AiUsagePeriod] = None,
) -> str:
"""
Format the usage information into a user-friendly message with a compact layout
and a simple progress bar against the free tier for the current team_id.
"""
- remaining = free_tier_credits - past_month_credits
- used = past_month_credits
+ remaining = free_tier_credits - period_credits
+ used = period_credits
# Unicode progress bar (20 segments)
bar_segments = 20
@@ -337,19 +414,30 @@ def format_usage_message(
lines: list[str] = [f"## {POSTHOG_AI_USAGE_REPORT_ASSISTANT_MESSAGE_TITLE}", ""]
- # Determine if GA cap is active
+ if usage_period is None:
+ fallback_start = get_past_month_start()
+ usage_period = AiUsagePeriod(
+ label="Past 30 days",
+ start=fallback_start,
+ end=datetime.now(UTC),
+ query_start=fallback_start,
+ )
ga_launch_date = get_ga_launch_date()
- ga_cap_active = past_month_start is not None and past_month_start.date() == ga_launch_date.date()
- past_30_label = "**Past 30 days**" + (f" (since {ga_launch_date.strftime('%Y-%m-%d')})" if ga_cap_active else "")
+ ga_cap_active = usage_period.start < ga_launch_date and usage_period.query_start.date() == ga_launch_date.date()
+ period_label = f"**{usage_period.label}**"
+ if usage_period.label == "Billing period":
+ period_label += f" ({usage_period.start.strftime('%Y-%m-%d')} to {usage_period.end.strftime('%Y-%m-%d')})"
+ if ga_cap_active:
+ period_label += f" (since {ga_launch_date.strftime('%Y-%m-%d')})"
lines.append(f"**Current conversation**: {conversation_credits:,} credits\n")
- lines.append(f"{past_30_label}: {past_month_credits:,} credits\n")
+ lines.append(f"{period_label}: {period_credits:,} credits\n")
lines.append(f"**Free tier limit**: {free_tier_credits:,} credits\n")
# Progress bar + percent
if free_tier_credits > 0:
pct_label = f"{percent:.0f}% of free tier" if percent <= 999 else "999%+ of free tier"
- lines.append(f"**Usage this period**: {bar} {pct_label}\n")
+ lines.append(f"**{usage_period.label} usage**: {bar} {pct_label}\n")
# Remaining or overage
if remaining >= 0:
@@ -362,13 +450,24 @@ def format_usage_message(
if conversation_start:
lines.append(f"_Conversation since_: {conversation_start.astimezone(UTC).strftime('%Y-%m-%d %H:%M UTC')}\n")
+ if usage_period.label == "Billing period":
+ lines.append(f"_Billing period resets on_: {usage_period.end.strftime('%Y-%m-%d %H:%M UTC')}\n")
+
lines.append("")
+ if usage_period.label == "Billing period":
+ lines.append(
+ "_Current conversation resets when you start a new chat; billing period usage resets at the end of this billing period._"
+ )
+ else:
+ lines.append(
+ "_Current conversation resets when you start a new chat; past 30 days is rolling usage for this project because billing period information is unavailable._"
+ )
lines.append("_Note: Usage data depends on AI trace ingestion and may lag slightly behind real-time activity._")
# Add GA cap explanation if active
if ga_cap_active:
lines.append(
- f"\n_Past 30 days usage is calculated from PostHog AI general availability date ({ga_launch_date.strftime('%b %d, %Y')}) "
+ f"\n_{usage_period.label} usage is calculated from PostHog AI general availability date ({ga_launch_date.strftime('%b %d, %Y')}) "
"as usage before this date is not counted._"
)
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
index de2f67cb8101..3b8feb798906 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
@@ -14,9 +14,11 @@ from ee.hogai.chat_agent.slash_commands.commands.usage.queries import (
CLOUD_REGION_TO_URL,
DEFAULT_FREE_TIER_CREDITS,
DEFAULT_GA_LAUNCH_DATE,
+ AiUsagePeriod,
format_usage_message,
get_ai_credits,
get_ai_free_tier_credits,
+ get_ai_usage_period,
get_conversation_start_time,
get_ga_launch_date,
get_past_month_start,
@@ -97,25 +99,20 @@ class TestUsage(BaseTest):
end = datetime(2026, 5, 2, tzinfo=UTC)
conversation_id = uuid4()
- group_mappings = (
- [
- {"group_type": "organization", "group_type_index": 0},
- {"group_type": "instance", "group_type_index": instance_group_index},
- ]
- if instance_group_index is not None
- else []
- )
-
with (
patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_instance_region") as mock_region,
patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.sync_execute") as mock_sync_execute,
patch(
- "ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_group_types_for_team"
- ) as mock_group_types,
+ "ee.hogai.chat_agent.slash_commands.commands.usage.queries.build_ai_billing_region_filter"
+ ) as mock_region_filter,
):
mock_region.return_value = region
mock_sync_execute.return_value = [(42,)]
- mock_group_types.return_value = group_mappings
+ if expected_region_url is not None:
+ mock_region_filter.return_value = {
+ "region_group_property": f"$group_{instance_group_index}",
+ "region_url": expected_region_url,
+ }
credits = get_ai_credits(team_id=133393, begin=begin, end=end, conversation_id=conversation_id)
@@ -126,17 +123,17 @@ class TestUsage(BaseTest):
if expected_region_url is None:
self.assertNotIn("region_url", params)
self.assertNotIn("%(region_url)s", query)
- mock_group_types.assert_not_called()
+ mock_region_filter.assert_not_called()
else:
self.assertEqual(params["region_url"], expected_region_url)
- mock_group_types.assert_called_once_with(expected_team_to_query)
+ self.assertEqual(params["region_group_property"], f"$group_{instance_group_index}")
+ mock_region_filter.assert_called_once_with(expected_team_to_query, expected_region_url)
self.assertIn(
- f"AND JSONExtractString(properties, '$group_{instance_group_index}') = %(region_url)s",
+ "AND JSONExtractString(properties, %(region_group_property)s) = %(region_url)s",
query,
)
- def test_get_ai_credits_skips_region_filter_when_instance_group_missing(self):
- """If the destination team has no `instance` group registered, skip the region filter rather than match nothing."""
+ def test_get_ai_credits_returns_zero_when_instance_group_missing(self):
begin = datetime(2026, 5, 1, tzinfo=UTC)
end = datetime(2026, 5, 2, tzinfo=UTC)
conversation_id = uuid4()
@@ -145,18 +142,16 @@ class TestUsage(BaseTest):
patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_instance_region") as mock_region,
patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.sync_execute") as mock_sync_execute,
patch(
- "ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_group_types_for_team",
- return_value=[{"group_type": "organization", "group_type_index": 0}],
+ "ee.hogai.chat_agent.slash_commands.commands.usage.queries.build_ai_billing_region_filter",
+ return_value=None,
),
):
mock_region.return_value = "EU"
- mock_sync_execute.return_value = [(0,)]
- get_ai_credits(team_id=133393, begin=begin, end=end, conversation_id=conversation_id)
+ credits = get_ai_credits(team_id=133393, begin=begin, end=end, conversation_id=conversation_id)
- query, params = mock_sync_execute.call_args[0][:2]
- self.assertNotIn("region_url", params)
- self.assertNotIn("%(region_url)s", query)
+ self.assertEqual(credits, 0)
+ mock_sync_execute.assert_not_called()
def test_get_conversation_start_time_exists(self):
"""Test retrieving conversation start time for existing conversation."""
@@ -218,28 +213,102 @@ class TestUsage(BaseTest):
past_month_start = get_past_month_start()
self.assertEqual(past_month_start, DEFAULT_GA_LAUNCH_DATE)
+ def test_get_ai_usage_period_from_billing_context(self):
+ billing_context = {
+ "billing_period": {
+ "current_period_start": "2026-05-02T14:51:12Z",
+ "current_period_end": "2026-06-02T14:51:12Z",
+ "interval": "month",
+ },
+ "billing_plan": "paid",
+ "has_active_subscription": True,
+ "is_deactivated": False,
+ "products": [],
+ "settings": {"autocapture_on": True, "active_destinations": 0},
+ "subscription_level": "paid",
+ }
+
+ usage_period = get_ai_usage_period(self.team, billing_context)
+
+ self.assertEqual(usage_period.label, "Billing period")
+ self.assertEqual(usage_period.start, datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC))
+ self.assertEqual(usage_period.end, datetime(2026, 6, 2, 14, 51, 12, tzinfo=UTC))
+ self.assertEqual(usage_period.query_start, datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC))
+
+ def test_get_ai_usage_period_from_organization_usage(self):
+ self.organization.usage = {
+ "period": ["2026-05-02T14:51:12Z", "2026-06-02T14:51:12Z"],
+ }
+
+ usage_period = get_ai_usage_period(self.team, None)
+
+ self.assertEqual(usage_period.label, "Billing period")
+ self.assertEqual(usage_period.start, datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC))
+ self.assertEqual(usage_period.end, datetime(2026, 6, 2, 14, 51, 12, tzinfo=UTC))
+ self.assertEqual(usage_period.query_start, datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC))
+
+ @patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.posthoganalytics.get_feature_flag_payload")
+ def test_get_ai_usage_period_caps_query_start_at_ga_launch(self, mock_payload):
+ mock_payload.return_value = None
+ self.organization.usage = {
+ "period": ["2025-11-01T00:00:00Z", "2025-12-01T00:00:00Z"],
+ }
+
+ usage_period = get_ai_usage_period(self.team, None)
+
+ self.assertEqual(usage_period.label, "Billing period")
+ self.assertEqual(usage_period.start, datetime(2025, 11, 1, tzinfo=UTC))
+ self.assertEqual(usage_period.end, datetime(2025, 12, 1, tzinfo=UTC))
+ self.assertEqual(usage_period.query_start, DEFAULT_GA_LAUNCH_DATE)
+
+ def test_get_ai_usage_period_falls_back_to_past_month(self):
+ now = datetime(2025, 12, 20, tzinfo=UTC)
+ with patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.datetime") as mock_datetime:
+ mock_datetime.side_effect = lambda *args, **kw: datetime(*args, **kw)
+ mock_datetime.now.return_value = now
+
+ usage_period = get_ai_usage_period(self.team, None)
+
+ self.assertEqual(usage_period.label, "Past 30 days")
+ self.assertEqual(usage_period.start, datetime(2025, 11, 20, tzinfo=UTC))
+ self.assertEqual(usage_period.end, now)
+ self.assertEqual(usage_period.query_start, datetime(2025, 11, 20, tzinfo=UTC))
+
def test_format_usage_message_no_usage(self):
"""Test formatting when no credits have been used."""
message = format_usage_message(
conversation_credits=0,
- past_month_credits=0,
+ period_credits=0,
free_tier_credits=2000,
+ usage_period=AiUsagePeriod(
+ label="Billing period",
+ start=datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC),
+ end=datetime(2026, 6, 2, 14, 51, 12, tzinfo=UTC),
+ query_start=datetime(2026, 5, 2, 14, 51, 12, tzinfo=UTC),
+ ),
)
self.assertIn("**Current conversation**: 0 credits", message)
- self.assertIn("**Past 30 days**: 0 credits", message)
+ self.assertIn("**Billing period** (2026-05-02 to 2026-06-02): 0 credits", message)
self.assertIn("**Free tier limit**: 2,000 credits", message)
self.assertIn("**Remaining**: 2,000 credits", message)
self.assertIn("0% of free tier", message)
+ self.assertIn("_Billing period resets on_: 2026-06-02 14:51 UTC", message)
def test_format_usage_message_partial_usage(self):
"""Test formatting with partial usage."""
message = format_usage_message(
conversation_credits=50,
- past_month_credits=500,
+ period_credits=500,
free_tier_credits=2000,
+ usage_period=AiUsagePeriod(
+ label="Billing period",
+ start=datetime(2026, 5, 2, tzinfo=UTC),
+ end=datetime(2026, 6, 2, tzinfo=UTC),
+ query_start=datetime(2026, 5, 2, tzinfo=UTC),
+ ),
)
self.assertIn("**Current conversation**: 50 credits", message)
- self.assertIn("**Past 30 days**: 500 credits", message)
+ self.assertIn("**Billing period** (2026-05-02 to 2026-06-02): 500 credits", message)
self.assertIn("**Remaining**: 1,500 credits", message)
self.assertIn("25% of free tier", message)
@@ -247,8 +316,14 @@ class TestUsage(BaseTest):
"""Test formatting when over the free tier limit."""
message = format_usage_message(
conversation_credits=100,
- past_month_credits=2500,
+ period_credits=2500,
free_tier_credits=2000,
+ usage_period=AiUsagePeriod(
+ label="Billing period",
+ start=datetime(2026, 5, 2, tzinfo=UTC),
+ end=datetime(2026, 6, 2, tzinfo=UTC),
+ query_start=datetime(2026, 5, 2, tzinfo=UTC),
+ ),
)
self.assertIn("**Overage**: 500 credits over limit", message)
self.assertIn("125% of free tier", message)
@@ -259,9 +334,14 @@ class TestUsage(BaseTest):
mock_payload.return_value = None
message = format_usage_message(
conversation_credits=10,
- past_month_credits=100,
+ period_credits=100,
free_tier_credits=2000,
- past_month_start=DEFAULT_GA_LAUNCH_DATE,
+ usage_period=AiUsagePeriod(
+ label="Billing period",
+ start=datetime(2025, 11, 1, tzinfo=UTC),
+ end=datetime(2025, 12, 1, tzinfo=UTC),
+ query_start=DEFAULT_GA_LAUNCH_DATE,
+ ),
)
self.assertIn(f"since {DEFAULT_GA_LAUNCH_DATE.strftime('%Y-%m-%d')}", message)
self.assertIn(
@@ -273,7 +353,7 @@ class TestUsage(BaseTest):
conv_start = datetime(2025, 11, 18, 10, 30, tzinfo=UTC)
message = format_usage_message(
conversation_credits=25,
- past_month_credits=200,
+ period_credits=200,
free_tier_credits=2000,
conversation_start=conv_start,
)
@@ -283,7 +363,7 @@ class TestUsage(BaseTest):
"""Test that progress bar is rendered correctly."""
message = format_usage_message(
conversation_credits=0,
- past_month_credits=1000,
+ period_credits=1000,
free_tier_credits=2000,
)
self.assertIn("█" * 10, message)
@@ -293,7 +373,7 @@ class TestUsage(BaseTest):
"""Test progress bar when at 100% usage."""
message = format_usage_message(
conversation_credits=0,
- past_month_credits=2000,
+ period_credits=2000,
free_tier_credits=2000,
)
self.assertIn("█" * 20, message)
diff --git a/frontend/src/scenes/max/slash-commands.tsx b/frontend/src/scenes/max/slash-commands.tsx
index ca588aafa416..07daf3724615 100644
--- a/frontend/src/scenes/max/slash-commands.tsx
+++ b/frontend/src/scenes/max/slash-commands.tsx
@@ -32,7 +32,7 @@ export const MAX_SLASH_COMMANDS: SlashCommand[] = [
},
{
name: SlashCommandName.SlashUsage,
- description: 'View AI credit usage for this conversation',
+ description: 'View AI credit usage for this conversation and billing period',
icon: <IconActivity />,
},
{
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index c31220001c6b..fb01f644c590 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -2984,6 +2984,14 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
materialize("events", "$exception_values")
materialize("events", "region")
+ def _setup_instance_group_mapping(self, team: Team, group_type_index: int = 1) -> None:
+ create_group_type_mapping_without_created_at(
+ team=team,
+ project_id=team.project_id,
+ group_type="instance",
+ group_type_index=group_type_index,
+ )
+
@patch("posthog.tasks.usage_report.get_ph_client")
@patch("posthog.tasks.usage_report.send_report_to_billing_service")
def test_llm_observability_usage_metrics(
@@ -3083,6 +3091,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3143,6 +3152,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3200,6 +3210,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self._setup_teams()
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3259,6 +3270,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self._setup_teams()
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3318,6 +3330,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self._setup_teams()
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3384,6 +3397,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3449,6 +3463,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3522,6 +3537,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3618,6 +3634,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Create analytics team (team_id=2 for billing)
analytics_org = Organization.objects.create(name="PostHog Analytics")
analytics_team = Team.objects.create(pk=2, organization=analytics_org, name="Analytics")
+ self._setup_instance_group_mapping(analytics_team)
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
@@ -3666,8 +3683,31 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
self.assertEqual(result[0][0], self.org_1_team_1.id)
self.assertEqual(result[0][1], 60)
+ @patch("posthog.tasks.usage_report.sync_execute")
+ @patch("posthog.tasks.usage_report.get_ai_billing_instance_group_type_index", return_value=None)
+ @patch("posthog.tasks.usage_report.get_instance_region", return_value="EU")
+ def test_ai_credits_returns_no_rows_when_instance_group_missing(
+ self,
+ mock_region: MagicMock,
+ mock_instance_group_type_index: MagicMock,
+ mock_sync_execute: MagicMock,
+ ) -> None:
+ from posthog.tasks.usage_report import get_teams_with_ai_credits_used_in_period
+
+ period_start, period_end = get_previous_day(at=now() + relativedelta(days=1))
+
+ result = get_teams_with_ai_credits_used_in_period(period_start, period_end)
+
+ self.assertEqual(result, [])
+ mock_region.assert_called_once()
+ mock_instance_group_type_index.assert_called_once_with(1)
+ mock_sync_execute.assert_not_called()
+
+ @patch("posthog.tasks.usage_report.get_ai_billing_instance_group_type_index", return_value=1)
@patch("posthog.tasks.usage_report.get_instance_region")
- def test_ai_credits_uses_correct_team_for_us_region(self, mock_region: MagicMock) -> None:
+ def test_ai_credits_uses_correct_team_for_us_region(
+ self, mock_region: MagicMock, mock_instance_group_type_index: MagicMock
+ ) -> None:
"""Test that US region uses team_id=2 and filters only US events.
In US deployment, team_id=2 contains BOTH US and EU traces, so region filtering is critical.
@@ -3747,13 +3787,17 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# Expected: Only US trace should count: 1.0 USD * 100 * 1.2 = 120 credits
# EU trace should be filtered out despite being in team_id=2
+ mock_instance_group_type_index.assert_called_once_with(2)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][0], self.org_1_team_1.id)
self.assertEqual(result[0][1], 120)
+ @patch("posthog.tasks.usage_report.get_ai_billing_instance_group_type_index", return_value=2)
@patch("posthog.tasks.usage_report.get_instance_region")
- def test_ai_credits_uses_correct_team_for_eu_region(self, mock_region: MagicMock) -> None:
- """Test that EU region uses team_id=1 and filters only EU events.
+ def test_ai_credits_uses_correct_team_for_eu_region(
+ self, mock_region: MagicMock, mock_instance_group_type_index: MagicMock
+ ) -> None:
+ """Test that EU region uses team_id=1 and filters only EU events using the configured instance group.
In EU deployment, team_id=1 should only contain EU traces.
"""
@@ -3779,7 +3823,8 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
properties={
"$ai_trace_id": "trace_eu",
"$ai_output_state": {"messages": [{"tool_calls": [{"name": "query_executor"}]}]},
- "$group_1": "https://eu.posthog.com",
+ "$group_1": "not-the-instance-group",
+ "$group_2": "https://eu.posthog.com",
},
)
@@ -3792,7 +3837,8 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
properties={
"$ai_trace_id": "trace_us_in_eu",
"$ai_output_state": {"messages": [{"tool_calls": [{"name": "query_executor"}]}]},
- "$group_1": "https://us.posthog.com",
+ "$group_1": "not-the-instance-group",
+ "$group_2": "https://us.posthog.com",
},
)
@@ -3807,7 +3853,8 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
"$ai_trace_id": "trace_eu",
"$ai_total_cost_usd": 2.0,
"$ai_billable": True,
- "$group_1": "https://eu.posthog.com",
+ "$group_1": "not-the-instance-group",
+ "$group_2": "https://eu.posthog.com",
},
)
@@ -3822,7 +3869,8 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
"$ai_trace_id": "trace_us_in_eu",
"$ai_total_cost_usd": 3.0,
"$ai_billable": True,
- "$group_1": "https://us.posthog.com",
+ "$group_1": "not-the-instance-group",
+ "$group_2": "https://us.posthog.com",
},
)
@@ -3831,6 +3879,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
result = get_teams_with_ai_credits_used_in_period(period_start, period_end)
# Expected: Only EU trace should count: 2.0 USD * 100 * 1.2 = 240 credits
+ mock_instance_group_type_index.assert_called_once_with(1)
self.assertEqual(len(result), 1)
self.assertEqual(result[0][0], self.org_1_team_1.id)
self.assertEqual(result[0][1], 240)
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 7af6e82a0eb2..2338678f55d0 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -33,6 +33,7 @@ from posthog.constants import FlagRequestType
from posthog.exceptions_capture import capture_exception
from posthog.logging.timing import timed_log
from posthog.models import GroupTypeMapping, OrganizationMembership, User
+from posthog.models.group_type_mapping import get_group_types_for_team
from posthog.models.organization import Organization
from posthog.models.property.util import get_property_string_expr
from posthog.models.team.team import Team
@@ -1078,6 +1079,7 @@ def get_teams_with_ai_event_count_in_period(
AI_COST_MARKUP_PERCENT = 0.2
# Tools excluded from AI billing (traces with only these tools are not billed)
AI_BILLING_EXCLUDED_TOOLS = ["summarize_sessions", "search"]
+AI_BILLING_INSTANCE_GROUP_TYPE = "instance"
# Region-to-team mapping for where AI events are stored
CLOUD_REGION_TO_TEAM_ID = {
"EU": 1,
@@ -1089,6 +1091,23 @@ CLOUD_REGION_TO_URL = {
}
+def get_ai_billing_instance_group_type_index(team_id: int) -> int | None:
+ """Resolve the $group_N index that holds the customer cloud URL for the internal AI events team."""
+ for mapping in get_group_types_for_team(team_id):
+ if mapping.get("group_type") == AI_BILLING_INSTANCE_GROUP_TYPE:
+ index = mapping.get("group_type_index")
+ return int(index) if index is not None else None
+ return None
+
+
+def build_ai_billing_region_filter(team_id: int, region_url: str) -> dict[str, str] | None:
+ instance_group_index = get_ai_billing_instance_group_type_index(team_id)
+ if instance_group_index is None:
+ return None
+
+ return {"region_group_property": f"$group_{instance_group_index}", "region_url": region_url}
+
+
@timed_log()
@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
def get_teams_with_ai_credits_used_in_period(
@@ -1115,7 +1134,7 @@ def get_teams_with_ai_credits_used_in_period(
6. Convert 1:1 to credits
Events are stored in team 1 (EU) or team 2 (US), with the actual team (on which we group by) in properties.
- We filter by $group_1 which contains the region URL (https://eu.posthog.com or https://us.posthog.com).
+ We filter by the configured `instance` group column, which contains the region URL.
"""
region = get_instance_region()
@@ -1129,6 +1148,9 @@ def get_teams_with_ai_credits_used_in_period(
return []
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:
+ return []
with tags_context(
product=Product.MAX_AI, feature=Feature.USAGE_REPORT, usage_report="ai_credits", kind="usage_report"
@@ -1185,7 +1207,7 @@ def get_teams_with_ai_credits_used_in_period(
PREWHERE
-- data inside PostHog project used as ground truth for billing (depends on region)
team_id = %(team_to_query)s
- AND JSONExtractString(properties, '$group_1') = %(region_url)s
+ AND JSONExtractString(properties, %(region_group_property)s) = %(region_url)s
AND timestamp >= %(begin)s
AND timestamp < %(end)s
AND event = '$ai_trace'
@@ -1209,7 +1231,7 @@ def get_teams_with_ai_credits_used_in_period(
PREWHERE
-- data inside PostHog project used as ground truth for billing (depends on region)
team_id = %(team_to_query)s
- AND JSONExtractString(properties, '$group_1') = %(region_url)s
+ AND JSONExtractString(properties, %(region_group_property)s) = %(region_url)s
AND timestamp >= %(begin)s
AND timestamp < %(end)s
AND event = '$ai_generation'
@@ -1239,11 +1261,11 @@ def get_teams_with_ai_credits_used_in_period(
""",
{
"team_to_query": team_to_query,
- "region_url": CLOUD_REGION_TO_URL[region],
"begin": begin,
"end": end,
"markup_multiplier": 1 + AI_COST_MARKUP_PERCENT,
"excluded_tools": AI_BILLING_EXCLUDED_TOOLS,
+ **region_filter_params,
},
workload=Workload.OFFLINE,
settings=CH_BILLING_SETTINGS,