: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(billing): add posthog_code usage reporting (#61018)
Joshua Snydereafb0efb1419
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 4a0adae5479f..06562dcba542 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -70,6 +70,7 @@ class Product(StrEnum):MOBILE_REPLAY = "mobile_replay"PIPELINE_DESTINATIONS = "pipeline_destinations"PLATFORM_AND_SUPPORT = "platform_and_support"+ POSTHOG_CODE = "posthog_code"PRODUCT_ANALYTICS = "product_analytics"REPLAY = "replay"REPLAY_VISION = "replay_vision"diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 753853ad464e..899293b00c00 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -4400,6 +4400,154 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouseself.assertFalse(has_non_zero_usage(UsageReportCounters(**zero)))self.assertTrue(has_non_zero_usage(UsageReportCounters(**{**zero, "signals_credits_used_in_period": 5})))+ @patch("posthog.tasks.usage_report.get_instance_region")+ def test_posthog_code_ai_product_excluded_from_ai_credits(self, mock_region: MagicMock) -> None:+ """Generations tagged ai_product='posthog_code' must not count toward PostHog AI credits."""+ from posthog.tasks.usage_report import get_teams_with_ai_credits_used_in_period++ mock_region.return_value = "US"+ 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++ # Billable generation tagged as posthog_code — should be excluded from PostHog AI credits.+ _create_event(+ event="$ai_generation",+ team=analytics_team,+ distinct_id="user_posthog_code",+ timestamp=period_start + relativedelta(hours=1),+ properties={+ "team_id": self.org_1_team_1.id,+ "$ai_trace_id": "trace_posthog_code",+ "$ai_total_cost_usd": 5.0,+ "$ai_billable": True,+ "ai_product": "posthog_code",+ "$group_1": "https://us.posthog.com",+ },+ )++ flush_persons_and_events()++ result = get_teams_with_ai_credits_used_in_period(period_start, period_end)++ self.assertEqual(result, [])++ @patch("posthog.tasks.usage_report.get_instance_region")+ def test_posthog_code_credits_only_counts_posthog_code_events(self, mock_region: MagicMock) -> None:+ """The posthog_code query only counts generations tagged ai_product='posthog_code'."""+ from posthog.tasks.usage_report import get_teams_with_posthog_code_credits_used_in_period++ mock_region.return_value = "US"+ 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++ # PostHog Code event — should appear only in posthog_code credits+ _create_event(+ event="$ai_generation",+ team=analytics_team,+ distinct_id="user_posthog_code",+ timestamp=period_start + relativedelta(hours=1),+ properties={+ "team_id": self.org_1_team_1.id,+ "$ai_trace_id": "trace_posthog_code",+ "$ai_total_cost_usd": 2.0,+ "$ai_billable": True,+ "ai_product": "posthog_code",+ "$group_1": "https://us.posthog.com",+ },+ )++ # Event tagged with a different ai_product — must never leak into posthog_code credits.+ _create_event(+ event="$ai_generation",+ team=analytics_team,+ distinct_id="user_signals",+ timestamp=period_start + relativedelta(hours=2),+ properties={+ "team_id": self.org_1_team_1.id,+ "$ai_trace_id": "trace_signals",+ "$ai_total_cost_usd": 1.0,+ "$ai_billable": True,+ "ai_product": "signals",+ "$group_1": "https://us.posthog.com",+ },+ )++ flush_persons_and_events()++ posthog_code_result = get_teams_with_posthog_code_credits_used_in_period(period_start, period_end)++ # posthog_code: 2.0 USD * 100 * 1.2 = 240 — only the posthog_code event, not the signals one.+ self.assertEqual(posthog_code_result, [(self.org_1_team_1.id, 240)])++ @parameterized.expand(+ [+ ("billable", True, 480),+ ("non_billable", False, None),+ ]+ )+ @patch("posthog.tasks.usage_report.get_instance_region")+ def test_posthog_code_credits_billable_fallback(+ self, _name: str, billable: bool, expected_credits: int | None, mock_region: MagicMock+ ) -> None:+ """A traceless posthog_code generation bills via the empty-trace fallback only when billable.++ PostHog Code never emits a matching $ai_trace event, so the LEFT JOIN never matches and the+ empty-trace fallback is what makes posthog_code billable at all — but only for $ai_billable=true.+ """+ from posthog.tasks.usage_report import get_teams_with_posthog_code_credits_used_in_period++ mock_region.return_value = "US"+ 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++ _create_event(+ event="$ai_generation",+ team=analytics_team,+ distinct_id="user_posthog_code",+ timestamp=period_start + relativedelta(hours=1),+ properties={+ "team_id": self.org_1_team_1.id,+ "$ai_trace_id": "trace_posthog_code",+ "$ai_total_cost_usd": 4.0, # 4.0 USD * 100 * 1.2 = 480 credits+ "$ai_billable": billable,+ "ai_product": "posthog_code",+ "$group_1": "https://us.posthog.com",+ },+ )++ flush_persons_and_events()++ result = get_teams_with_posthog_code_credits_used_in_period(period_start, period_end)++ expected = [(self.org_1_team_1.id, expected_credits)] if expected_credits is not None else []+ self.assertEqual(result, expected)++ def test_has_non_zero_usage_counts_posthog_code_credits(self) -> None:+ """A posthog_code-only org must survive has_non_zero_usage so its report still reaches billing."""+ import dataclasses++ from posthog.tasks.usage_report import UsageReportCounters, has_non_zero_usage++ zero = {field.name: 0 for field in dataclasses.fields(UsageReportCounters)}++ self.assertFalse(has_non_zero_usage(UsageReportCounters(**zero)))+ self.assertTrue(has_non_zero_usage(UsageReportCounters(**{**zero, "posthog_code_credits_used_in_period": 5})))+class TestSendUsage(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):def setUp(self) -> None:diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex a97759dd430d..c9260748994e 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -217,6 +217,9 @@ class UsageReportCounters:# Signals Billing Credits (flat credits per report whose implementation shipped a PR)signals_credits_used_in_period: int+ # PostHog Code Billing Credits (PostHog Code product usage — same cost math as ai_credits, scoped to ai_product='posthog_code')+ posthog_code_credits_used_in_period: int+# CDP Deliveryhog_function_calls_in_period: inthog_function_fetch_calls_in_period: int@@ -1168,6 +1171,9 @@ POSTHOG_AI_PRODUCTS = ["surveys",]+# ai_product values billed as PostHog Code credits.+POSTHOG_CODE_AI_PRODUCTS = ["posthog_code"]+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."""@@ -1392,6 +1398,22 @@ def get_teams_with_signals_credits_used_in_period(return get_signals_billing_credits_by_team(begin, end)+@timed_log()+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)+def get_teams_with_posthog_code_credits_used_in_period(+ begin: datetime,+ end: datetime,+) -> list[tuple[int, int]]:+ """PostHog Code billing credits — only events tagged with ai_product='posthog_code'."""+ return _get_teams_with_ai_credits_for_products(+ begin,+ end,+ ai_products=POSTHOG_CODE_AI_PRODUCTS,+ usage_report_tag="posthog_code_credits",+ product_tag=Product.POSTHOG_CODE,+ )++dwh_pricing_free_period_start = datetime(2025, 10, 29, 0, 0, 0, tzinfo=UTC)dwh_pricing_free_period_end = datetime(2025, 11, 6, 0, 0, 0, tzinfo=UTC)@@ -2104,6 +2126,7 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:or report.ai_event_count_in_period > 0or report.ai_credits_used_in_period > 0or report.signals_credits_used_in_period > 0+ or report.posthog_code_credits_used_in_period > 0or report.logs_bytes_in_period > 0or report.workflow_emails_sent_in_period > 0or report.workflow_push_sent_in_period > 0@@ -2365,6 +2388,9 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st"teams_with_signals_credits_used_in_period": get_teams_with_signals_credits_used_in_period(period_start, period_end),+ "teams_with_posthog_code_credits_used_in_period": get_teams_with_posthog_code_credits_used_in_period(+ period_start, period_end+ ),"teams_with_active_hog_destinations_in_period": get_teams_with_active_hog_destinations_in_period(),"teams_with_active_hog_transformations_in_period": get_teams_with_active_hog_transformations_in_period(),"teams_with_workflow_emails_sent_in_period": get_teams_with_workflow_emails_sent_in_period(@@ -2538,6 +2564,7 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounterai_event_count_in_period=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),ai_credits_used_in_period=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),signals_credits_used_in_period=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),+ posthog_code_credits_used_in_period=all_data["teams_with_posthog_code_credits_used_in_period"].get(team.id, 0),active_hog_destinations_in_period=all_data["teams_with_active_hog_destinations_in_period"].get(team.id, 0),active_hog_transformations_in_period=all_data["teams_with_active_hog_transformations_in_period"].get(team.id, 0diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex 640030b03774..8421b5c1ad78 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -72,6 +72,7 @@ from posthog.tasks.usage_report import (get_teams_with_logs_records_in_period,get_teams_with_logs_retention_bytes_in_period,get_teams_with_mobile_billable_recording_count_in_period,+ get_teams_with_posthog_code_credits_used_in_period,get_teams_with_query_metric,get_teams_with_recording_bytes_in_period,get_teams_with_recording_count_in_period,@@ -433,6 +434,10 @@ QUERIES: list[QuerySpec] = [name="teams_with_signals_credits_used_in_period",fn=get_teams_with_signals_credits_used_in_period,),+ QuerySpec(+ name="teams_with_posthog_code_credits_used_in_period",+ fn=get_teams_with_posthog_code_credits_used_in_period,+ ),# ---- ClickHouse: workflows / messaging ----------------------------------QuerySpec(name="teams_with_workflow_emails_sent_in_period",