: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
fix(phai): run /usage billing period lookup off the event loop (#63658)
Chris Volzer29c9f39861a7
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/command.py b/ee/hogai/chat_agent/slash_commands/commands/usage/command.pyindex 68b2dfb9c6d0..5be9ceb34058 100644--- a/ee/hogai/chat_agent/slash_commands/commands/usage/command.py+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/command.py@@ -8,6 +8,8 @@ from posthoganalytics import capture_exceptionfrom posthog.schema import AssistantMessage+from posthog.sync import database_sync_to_async+from ee.hogai.chat_agent.slash_commands.commands import SlashCommandfrom ee.hogai.chat_agent.slash_commands.commands.usage.queries import (format_usage_message,@@ -34,13 +36,15 @@ class UsageCommand(SlashCommand):messages=[AssistantMessage(content="Unable to retrieve conversation information.", id=str(uuid4()))])- conversation_start = await sync_to_async(get_conversation_start_time)(conversation_id)+ conversation_start = await database_sync_to_async(get_conversation_start_time)(conversation_id)if not conversation_start:return PartialAssistantState(messages=[AssistantMessage(content="Unable to retrieve conversation start time.", id=str(uuid4()))])- usage_period = get_ai_usage_period(self._team, config.get("configurable", {}).get("billing_context"))+ usage_period = await database_sync_to_async(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,@@ -73,4 +77,4 @@ class UsageCommand(SlashCommand):except Exception as e:capture_exception(e)- raise Exception("PostHog AI usage information query failed. Please try again later.")+ raise Exception("PostHog AI usage information query failed. Please try again later.") from ediff --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.pyindex 3b8feb798906..2596749b1f62 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@@ -1,3 +1,4 @@+import asynciofrom datetime import UTC, datetime, timedeltafrom typing import castfrom uuid import uuid4@@ -5,10 +6,17 @@ from uuid import uuid4from posthog.test.base import BaseTestfrom unittest.mock import patch+from django.core.exceptions import SynchronousOnlyOperation++from asgiref.sync import async_to_sync+from langchain_core.runnables import RunnableConfigfrom parameterized import parameterized+from posthog.schema import AssistantMessage, HumanMessage+from products.posthog_ai.backend.models.assistant import Conversation+from ee.hogai.chat_agent.slash_commands.commands.usage.command import UsageCommandfrom ee.hogai.chat_agent.slash_commands.commands.usage.queries import (CLOUD_REGION_TO_TEAM_ID,CLOUD_REGION_TO_URL,@@ -23,6 +31,7 @@ from ee.hogai.chat_agent.slash_commands.commands.usage.queries import (get_ga_launch_date,get_past_month_start,)+from ee.hogai.utils.types import AssistantStateclass TestUsage(BaseTest):@@ -274,6 +283,55 @@ class TestUsage(BaseTest):self.assertEqual(usage_period.end, now)self.assertEqual(usage_period.query_start, datetime(2025, 11, 20, tzinfo=UTC))+ def test_execute_runs_usage_period_off_event_loop(self):+ # Without a billing context, get_ai_usage_period falls back to team.organization.usage, a sync+ # ORM access. It must run off the event loop or Django raises SynchronousOnlyOperation, which the+ # command would swallow into a generic failure. This guard mimics that check: it raises only when+ # get_ai_usage_period executes directly on the running loop.+ conversation = Conversation.objects.create(team=self.team, user=self.user)+ config = RunnableConfig(configurable={"thread_id": str(conversation.id)})+ state = AssistantState(messages=[HumanMessage(content="/usage")])++ def usage_period_guarded(*args, **kwargs):+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return AiUsagePeriod(+ label="Past 30 days",+ start=datetime(2026, 5, 1, tzinfo=UTC),+ end=datetime(2026, 6, 1, tzinfo=UTC),+ query_start=datetime(2026, 5, 1, tzinfo=UTC),+ )+ raise SynchronousOnlyOperation(+ "You cannot call this from an async context - use a thread or sync_to_async."+ )++ with (+ patch(+ "ee.hogai.chat_agent.slash_commands.commands.usage.command.get_ai_usage_period",+ side_effect=usage_period_guarded,+ ),+ patch(+ "ee.hogai.chat_agent.slash_commands.commands.usage.command.get_ai_credits_for_conversation",+ return_value=10,+ ),+ patch(+ "ee.hogai.chat_agent.slash_commands.commands.usage.command.get_ai_credits_for_team",+ return_value=100,+ ),+ patch(+ "ee.hogai.chat_agent.slash_commands.commands.usage.command.get_ai_free_tier_credits",+ return_value=2000,+ ),+ ):+ result = async_to_sync(UsageCommand(self.team, self.user).execute)(config, state)++ message = result.messages[0]+ assert isinstance(message, AssistantMessage)+ content = cast(str, message.content)+ self.assertIn("PostHog AI usage", content)+ self.assertNotIn("query failed", content)+def test_format_usage_message_no_usage(self):"""Test formatting when no credits have been used."""message = format_usage_message(