: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(mcp): wait out a busy query service and give crashes an id (#106260)
posthog[bot]792ad4a64c7c
diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 27c084e9b75d..aad17d82b8f4 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -59,7 +59,12 @@ from posthog.errors import (look_up_clickhouse_error_code_meta,)from posthog.event_usage import EventSource-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from posthog.exceptions import (+ TRANSIENT_QUERY_ERROR_CODES,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+ QueryRanConcurrently,+)from posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionModefrom posthog.models import Teamfrom posthog.sync import database_sync_to_async@@ -488,6 +493,15 @@ class AssistantQueryExecutor:# Check for query execution errors before using resultsif query_status.get("error"):+ if query_status.get("error_code") in TRANSIENT_QUERY_ERROR_CODES:+ raise MaxToolTransientError(+ query_status.get("error_message") or "The query service was too busy to run this query.",+ error_type=(+ "api_5xx"+ if query_status.get("error_code") == QueryRanConcurrently.default_code+ else "rate_limited"+ ),+ )error_code = query_status.get("error_code")cached_error_type: MaxToolErrorType = ("memory_limit" if error_code == ClickHouseQueryMemoryLimitExceeded.default_code else "internal"@@ -511,7 +525,7 @@ class AssistantQueryExecutor:raise MaxToolAccessDeniedError(err.resource, err.required_level) from errexcept (PermissionDenied, TableAccessDeniedError) as err:raise MaxToolFatalError(str(err), error_type="permission") from err- except (*CH_TRANSIENT_ERRORS, ConcurrencyLimitExceeded) as err:+ except (*CH_TRANSIENT_ERRORS, ConcurrencyLimitExceeded, QueryRanConcurrently) as err:error_type: MaxToolErrorType = ("rate_limited" if classify_query_error(err) == QueryErrorCategory.RATE_LIMITED else "api_5xx")diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex e5aa915b2c87..235cbd5bb4a4 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -39,8 +39,10 @@ from posthog.schema import (from posthog.hogql.constants import DEFAULT_POSTHOG_AI_RETURNED_ROWSfrom posthog.hogql.errors import ExposedHogQLError+from posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_contextfrom posthog.errors import CHQueryErrorIllegalTypeOfArgument, ExposedCHQueryError, InternalCHQueryError+from posthog.exceptions import ClickHouseAtCapacity, QueryRanConcurrentlyfrom posthog.models import Organization, Team, Userfrom ee.hogai.context.insight.context import InsightContext@@ -51,7 +53,7 @@ from ee.hogai.context.insight.query_executor import (get_example_prompt,is_supported_query,)-from ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolFatalError, MaxToolRetryableError, MaxToolTransientErrorfrom ee.hogai.utils.query import validate_assistant_query@@ -644,6 +646,56 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertIs(type(context.exception), Exception)self.assertEqual(str(context.exception), "There was an unknown error running this query: Query failed")+ @parameterized.expand(+ [+ ("at_capacity", "clickhouse_at_capacity", ClickHouseAtCapacity.default_detail, None, "rate_limited"),+ ("ran_concurrently", "query_ran_concurrently", QueryRanConcurrently.default_detail, None, "api_5xx"),+ ("concurrency_limit_without_message", "clickhouse_at_capacity", None, None, "rate_limited"),+ ("direct_capacity", None, ClickHouseAtCapacity.default_detail, ClickHouseAtCapacity(), "rate_limited"),+ ("direct_shared_failure", None, QueryRanConcurrently.default_detail, QueryRanConcurrently(), "api_5xx"),+ (+ "direct_concurrency_limit",+ None,+ str(ConcurrencyLimitExceeded()),+ ConcurrencyLimitExceeded(),+ "rate_limited",+ ),+ ]+ )+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ @patch("ee.hogai.context.insight.query_executor.get_query_status")+ async def test_temporary_query_failures_ask_the_agent_to_wait(+ self,+ _name: str,+ error_code: str | None,+ error_message: str | None,+ raised_error: Exception | None,+ expected_error_type: str,+ mock_get_query_status: Mock,+ mock_process_query: Mock,+ ) -> None:+ mock_process_query.side_effect = raised_error+ mock_process_query.return_value = {"query_status": {"id": "test-query-id", "complete": False}}+ mock_get_query_status.return_value = Mock(+ model_dump=lambda mode: {+ "id": "test-query-id",+ "complete": True,+ "error": True,+ "error_message": error_message,+ "error_code": error_code,+ }+ )++ with patch("ee.hogai.context.insight.query_executor.asyncio.sleep"):+ with self.assertRaises(MaxToolTransientError) as context:+ await self.query_runner.arun_and_format_query(AssistantTrendsQuery(series=[]))++ self.assertEqual(context.exception.error_type, expected_error_type)+ self.assertEqual(context.exception.retry_hint, " You may retry this operation once without changes.")+ self.assertIn(+ error_message if raised_error is not None else error_message or "too busy", str(context.exception)+ )+@override_settings(TEST=False)@patch("ee.hogai.context.insight.query_executor.process_query_dict")async def test_execution_mode_in_production(self, mock_process_query):diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 68a1319f668a..43ad52d01b67 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -23,6 +23,7 @@ from posthog.clickhouse.client import ()from posthog.clickhouse.client.async_task_chain import execute_task_chain, task_chain_contextfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, execute_process_query+from posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tags, tag_queriesfrom posthog.constants import AvailableFeaturefrom posthog.direct_query_cancellation import (@@ -30,7 +31,7 @@ from posthog.direct_query_cancellation import (is_direct_query_cancellation_requested,)from posthog.errors import ExposedCHQueryError, InternalCHQueryError-from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, QueryRanConcurrentlyfrom posthog.models import Organization, Teamfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import User@@ -72,13 +73,25 @@ class TestQueryStatusManager(SimpleTestCase):self.query_status.expiration_time = None # We don't care about expiration time in this testself.assertEqual(self.manager.get_query_status(True), self.query_status)- def test_process_query_task_on_failure_marks_status_errored(self):+ @parameterized.expand(+ [+ ("at_capacity", ClickHouseAtCapacity(), ClickHouseAtCapacity.default_detail, "clickhouse_at_capacity"),+ (+ "ran_concurrently",+ QueryRanConcurrently(),+ QueryRanConcurrently.default_detail,+ "query_ran_concurrently",+ ),+ ("concurrency_limit", ConcurrencyLimitExceeded(), None, "clickhouse_at_capacity"),+ ]+ )+ def test_process_query_task_on_failure_marks_status_errored(self, _name, exc, error_message, error_code):from posthog.tasks.tasks import process_query_taskself.manager.store_query_status(self.query_status)process_query_task.on_failure(- exc=ClickHouseAtCapacity(),+ exc=exc,task_id="celery-task-id",args=(self.team_id, None, self.query_id),kwargs={},@@ -88,7 +101,8 @@ class TestQueryStatusManager(SimpleTestCase):result = self.manager.get_query_status()self.assertTrue(result.complete)self.assertTrue(result.error)- self.assertEqual(result.error_message, ClickHouseAtCapacity.default_detail)+ self.assertEqual(result.error_message, error_message)+ self.assertEqual(result.error_code, error_code)self.assertIsNotNone(result.end_time)def test_store_clickhouse_query_progress(self):diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex 2b895c49c181..1c71a1cb73fd 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -86,6 +86,7 @@ class DatabaseSchemaUnavailable(APIException):class ClickHouseAtCapacity(APIException):wait: intstatus_code = 503+ default_code = "clickhouse_at_capacity"default_detail = ("Queries are a little too busy right now. We're working to free up resources. Please try again later.")@@ -105,6 +106,10 @@ class QueryRanConcurrently(APIException):default_detail = "This query was already running and its result couldn't be reused. Try again in a moment."+# Failures that clear on their own. A caller that reads one of these codes should wait and run the same query again.+TRANSIENT_QUERY_ERROR_CODES = frozenset({ClickHouseAtCapacity.default_code, QueryRanConcurrently.default_code})++class ClickHouseEstimatedQueryExecutionTimeTooLong(APIException):status_code = 512 # Custom error codedefault_detail = "Estimated query execution time is too long. Try reducing its scope by changing the time range."diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 22618f3d430e..a17f485cd02a 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -425,6 +425,11 @@ def _process_query_task_failure(if isinstance(exc, APIException):# User-safe message (e.g. ClickHouseAtCapacity's "try again later" copy)query_status.error_message = str(exc.detail)+ codes = exc.get_codes()+ if isinstance(codes, str):+ query_status.error_code = codes+ elif isinstance(exc, ConcurrencyLimitExceeded):+ query_status.error_code = ClickHouseAtCapacity.default_codequery_status.end_time = datetime.datetime.now(datetime.UTC)manager.store_query_status(query_status)diff --git a/products/posthog_ai/backend/api/mcp_tools.py b/products/posthog_ai/backend/api/mcp_tools.pyindex b96f3f5f3ad0..406b7610f293 100644--- a/products/posthog_ai/backend/api/mcp_tools.py+++ b/products/posthog_ai/backend/api/mcp_tools.py@@ -1,5 +1,6 @@import jsonfrom typing import cast+from uuid import uuid4from django.conf import settingsfrom django.views.generic import View@@ -23,6 +24,7 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, tags_contextfrom posthog.event_usage import get_event_source+from posthog.exceptions_capture import exception_contextfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.renderers import SafeJSONRenderer@@ -168,10 +170,15 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):status=status.HTTP_400_BAD_REQUEST,)+ error_id = str(uuid4())try:async def execute_tool() -> str | MCPToolResult:- with tags_context(feature=Feature.MCP, team_id=self.team.pk, org_id=self.team.organization_id):+ # Lower layers may capture the exception before it reaches this handler.+ with (+ exception_context(error_id=error_id),+ tags_context(feature=Feature.MCP, team_id=self.team.pk, org_id=self.team.organization_id),+ ):return await tool.execute(validated_args)result = async_to_sync(execute_tool)()@@ -185,12 +192,17 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):})except Exception as e:- logger.exception("Error calling tool", extra={"tool_name": tool_name, "error": str(e)})- capture_exception(e, properties={"tag": "mcp", "args": args_data})+ logger.exception(+ "Error calling tool", extra={"tool_name": tool_name, "error": str(e), "error_id": error_id}+ )+ capture_exception(e, properties={"tag": "mcp", "args": args_data, "error_id": error_id})return Response({"success": False,- "content": "The tool raised an internal error. Do not immediately retry the tool call.",+ "content": (+ "The tool raised an internal error. Do not immediately retry the tool call. "+ f"Error id: {error_id}"+ ),})diff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.pyindex 92317714d303..e9c0eefd1112 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -37,6 +37,7 @@ from posthog.exceptions import (ClickHouseQuerySizeExceeded,ClickHouseQueryTimeOut,)+from posthog.exceptions_capture import ambient_exception_properties, capture_exceptionfrom posthog.models import Organization, Teamfrom products.access_control.backend.facade.user_access_control import UserAccessControlError@@ -230,9 +231,36 @@ class TestMCPToolsAPI(APIBaseTest):expected["error_type"] = error_typeelse:self.assertEqual(mock_capture.call_args.args, (error,))+ error_id = mock_capture.call_args.kwargs["properties"]["error_id"]+ expected["content"] = f"{content} Error id: {error_id}"self.assertEqual(response.json(), expected)mock_runner_cls.return_value.run.assert_called_once()+ @patch("posthoganalytics.api_key", "test-key")+ @patch("posthoganalytics.capture_exception")+ @patch("ee.hogai.utils.helpers.TeamTaxonomyQueryRunner")+ def test_error_id_is_available_to_upstream_exception_capture(self, mock_runner_cls, mock_capture):+ error = RuntimeError("private backend detail")+ context_before = ambient_exception_properties().copy()++ def capture_and_raise(*args, **kwargs):+ capture_exception(error)+ raise error++ mock_runner_cls.return_value.run.side_effect = capture_and_raise+ response = self.client.post(+ f"/api/environments/{self.team.id}/mcp_tools/read_taxonomy/",+ {"args": {"query": {"kind": "events"}}},+ format="json",+ )++ self.assertEqual(response.status_code, 200)+ first_capture = mock_capture.call_args_list[0]+ self.assertIs(first_capture.args[0], error)+ error_id = first_capture.kwargs["properties"]["error_id"]+ self.assertTrue(response.json()["content"].endswith(f"Error id: {error_id}"))+ self.assertEqual(ambient_exception_properties(), context_before)+@parameterized.expand([("without_code", None, {}),@@ -514,8 +542,9 @@ class TestMCPToolsAPI(APIBaseTest):expected["error_code"] = expected_error_codeself.assertEqual(response.json(), expected)+ @patch("products.posthog_ai.backend.api.mcp_tools.capture_exception")@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)- def test_invoke_tool_unexpected_error_returns_internal_error(self, mock_execute):+ def test_invoke_tool_unexpected_error_returns_internal_error(self, mock_execute, mock_capture):mock_execute.side_effect = RuntimeError("unexpected")response = self.client.post(@@ -525,11 +554,12 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)+ error_id = mock_capture.call_args.kwargs["properties"]["error_id"]self.assertEqual(response.json(),{"success": False,- "content": "The tool raised an internal error. Do not immediately retry the tool call.",+ "content": f"The tool raised an internal error. Do not immediately retry the tool call. Error id: {error_id}",},)