: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(mcp): record a code for internal execute-sql failures (#120074)
Vasco de Krijgerc4b0c57976a9
diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.pyindex 7722c08cc4a1..72ffc7aed767 100644--- a/ee/hogai/context/insight/context.py+++ b/ee/hogai/context/insight/context.py@@ -8,7 +8,7 @@ from posthog.sync import database_sync_to_asyncfrom products.product_analytics.backend.facade.models import Insight-from ee.hogai.context.insight.query_executor import execute_and_format_query, get_clickhouse_error_code+from ee.hogai.context.insight.query_executor import execute_and_format_query, internal_error_codefrom ee.hogai.tool_errors import MaxToolError, MaxToolRetryableErrorfrom ee.hogai.utils.helpers import build_insight_urlfrom ee.hogai.utils.prompt import format_prompt_string@@ -112,7 +112,7 @@ class InsightContext:raiseelse:raise MaxToolRetryableError(- error_message, error_type="internal", error_code=get_clickhouse_error_code(e.__cause__)+ error_message, error_type="internal", error_code=internal_error_code(e.__cause__ or e)) from ereturn format_prompt_string(diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex ad0d0d540d97..ddf632607e1c 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -1,9 +1,10 @@+import reimport jsonimport timeimport asynciofrom dataclasses import fieldfrom datetime import UTC, datetime-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Any, Optionalfrom django.conf import settingsfrom django.core.serializers.json import DjangoJSONEncoder@@ -45,6 +46,7 @@ from posthog.hogql.errors import (SyntaxError as HogQLSyntaxError,TableAccessDeniedError,)+from posthog.hogql.transforms.trino.errors import TrinoLoweringErrorfrom posthog.api.services.query import process_query_dictfrom posthog.clickhouse.client.execute_async import get_query_status@@ -57,8 +59,9 @@ from posthog.errors import (InternalCHQueryError,QueryErrorCategory,classify_query_error,+ error_code_from_type,internal_ch_error_user_message,- look_up_clickhouse_error_code_meta,+ unwrap_exposed_hogql_error,)from posthog.event_usage import EventSourcefrom posthog.exceptions import (@@ -132,22 +135,33 @@ HOGQL_ERROR_CODES_BY_MESSAGE_PREFIX = (("Unsupported function call", "hogql_unsupported_function"),)+RECORDABLE_STATUS_ERROR_CODE = re.compile(r"[a-z][a-z0-9_]{0,99}")++QUERY_RESULT_ERROR_CODE = "query_result_error"++HOGQL_INPUT_ERROR_CODES = frozenset({QueryError.code_name, HogQLSyntaxError.code_name, TrinoLoweringError.code_name})+def get_clickhouse_error_code(error: BaseException | None) -> str | None:if not isinstance(error, InternalCHQueryError):return None- code = look_up_clickhouse_error_code_meta(error).name.lower()+ code = error_code_from_type(error)return code if internal_ch_error_user_message(code) else None+def _hogql_code_from_message(message: str) -> str | None:+ for prefix, code in HOGQL_ERROR_CODES_BY_MESSAGE_PREFIX:+ if message.startswith(prefix):+ return code+ return None++def hogql_error_code(error: BaseException | None) -> str | None:"""Return a code for a HogQL error that holds no caller input, or None for any other error."""if not isinstance(error, BaseHogQLError):return None- message = str(error)- for prefix, code in HOGQL_ERROR_CODES_BY_MESSAGE_PREFIX:- if message.startswith(prefix):- return code+ if code := _hogql_code_from_message(str(error)):+ return codeif isinstance(error, ExposedHogQLError):return error.code_nameif isinstance(error, HogQLNotImplementedError):@@ -157,19 +171,48 @@ def hogql_error_code(error: BaseException | None) -> str | None:return "hogql_internal_error"-def _hogql_tool_error(error: ExposedHogQLError) -> MaxToolError:- cause: BaseException = error- seen: set[int] = set()- while type(cause) is ExposedHogQLError and cause.__cause__ is not None and id(cause) not in seen:- seen.add(id(cause))- cause = cause.__cause__+def internal_error_code(error: BaseException) -> str:+ """Return a code for an internal failure that holds no caller input."""+ return hogql_error_code(error) or error_code_from_type(error)++def _hogql_tool_error(error: ExposedHogQLError) -> MaxToolError:+ cause = unwrap_exposed_hogql_error(error)if isinstance(cause, TableAccessDeniedError):return MaxToolFatalError(str(error), error_type="permission")if isinstance(cause, (QueryError, HogQLSyntaxError)):return MaxToolRetryableError(str(error), error_type="validation", error_code=hogql_error_code(cause))# User-safe errors can also describe outages; only known input errors should skip exception capture.- return MaxToolRetryableError(str(error), error_type="internal")+ return MaxToolRetryableError(str(error), error_type="internal", error_code=internal_error_code(cause))+++def _query_status_tool_error(query_status: dict[str, Any]) -> MaxToolError:+ error_code: str | None = query_status.get("error_code")+ error_message: str | None = query_status.get("error_message")+ if error_code in TRANSIENT_QUERY_ERROR_CODES:+ return MaxToolTransientError(+ error_message or "The query service was too busy to run this query.",+ error_type="api_5xx" if error_code == QueryRanConcurrently.default_code else "rate_limited",+ )+ error_code = error_code.lower() if error_code and error_code != APIException.default_code else None+ if error_code and not RECORDABLE_STATUS_ERROR_CODE.fullmatch(error_code):+ error_code = None+ if error_code == TableAccessDeniedError.code_name:+ return MaxToolFatalError(error_message or "Table access denied.", error_type="permission")+ if error_message and error_code in HOGQL_INPUT_ERROR_CODES:+ return MaxToolRetryableError(+ error_message, error_type="validation", error_code=_hogql_code_from_message(error_message) or error_code+ )+ if rejection := describe_clickhouse_rejection(error_code, error_message):+ return MaxToolRetryableError(rejection, error_type="validation", error_code=error_code)+ # Async status loses the exception type, so keep retry advice without guessing its category.+ error_type: MaxToolErrorType = (+ "memory_limit" if error_code == ClickHouseQueryMemoryLimitExceeded.default_code else "internal"+ )+ message = (+ error_message or internal_ch_error_user_message(error_code) or "The query failed because of an internal error"+ )+ return MaxToolRetryableError(message, error_type=error_type, error_code=error_code)@frozen@@ -521,28 +564,7 @@ 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"- )- error_code = (- error_code.lower() if error_code and internal_ch_error_user_message(error_code) else None- )- if rejection := describe_clickhouse_rejection(error_code, query_status.get("error_message")):- raise MaxToolRetryableError(rejection, error_type="validation", error_code=error_code)- if error_message := query_status.get("error_message") or internal_ch_error_user_message(error_code):- # Async status loses the exception type, so keep retry advice without guessing its category.- raise MaxToolRetryableError(error_message, error_type=cached_error_type, error_code=error_code)- raise Exception("Query failed")+ raise _query_status_tool_error(query_status)# Use the completed query resultsresponse_dict = query_status["results"]@@ -591,14 +613,11 @@ class AssistantQueryExecutor:raise MaxToolFatalError(err_message, error_type="api_5xx") from errelif isinstance(err, APIException) and err.status_code == 429:raise MaxToolTransientError(err_message, error_type="rate_limited") from err- raise MaxToolRetryableError(- err_message,- error_type=error_type,- error_code=get_clickhouse_error_code(err),- ) from err+ error_code = internal_error_code(err) if error_type == "internal" else get_clickhouse_error_code(err)+ raise MaxToolRetryableError(err_message, error_type=error_type, error_code=error_code) from errexcept Exception as err:if isinstance(err, InternalCHQueryError):- error_code = look_up_clickhouse_error_code_meta(err).name.lower()+ error_code = error_code_from_type(err)if rejection := describe_clickhouse_rejection(error_code):raise MaxToolRetryableError(rejection, error_type="validation", error_code=error_code) from errelapsed = time.time() - start_time@@ -620,7 +639,7 @@ class AssistantQueryExecutor:# table, indistinguishable from "zero rows matched". Surface it as an error, mirroring the# `query_status.error` check the async-polling branch above already does.if isinstance(response_dict, dict) and (error := response_dict.get("error")):- raise MaxToolRetryableError(str(error), error_type="internal")+ raise MaxToolRetryableError(str(error), error_type="internal", error_code=QUERY_RESULT_ERROR_CODE)total_elapsed = time.time() - start_timeif debug_timing:diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex 19bc57077b4e..b7a06276bc5c 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -330,7 +330,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):@parameterized.expand([- ("outage_without_code", ExposedHogQLError("Warehouse connection failed"), "internal", None),+ ("outage", ExposedHogQLError("Warehouse connection failed"), "internal", "hogql_error"),("unresolved_field", QueryError("Unable to resolve field: plan"), "validation", "hogql_unresolved_field"),("syntax", HogQLSyntaxError("mismatched input 'FORM'"), "validation", "hogql_syntax_error"),(@@ -356,7 +356,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):@parameterized.expand([- ("unknown", ExposedCHQueryError("ClickHouse error"), "ClickHouse error", "internal", None),+ ("unknown", ExposedCHQueryError("ClickHouse error"), "ClickHouse error", "internal", "unknown_exception"),("argument_type",CHQueryErrorIllegalTypeOfArgument("Expected an integer argument", code=43),@@ -383,7 +383,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):ExposedCHQueryError("Server failure", code=99999, code_name="caller-supplied-name"),"Server failure","internal",- None,+ "unknown_exception",),])@@ -449,6 +449,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertEqual(str(context.exception), "Query has hit the max execution time before completing.")self.assertEqual(context.exception.error_type, "internal")+ self.assertEqual(context.exception.error_code, "query_result_error")self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")@patch("ee.hogai.context.insight.query_executor.process_query_dict")@@ -508,7 +509,7 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):"Query memory limit exceeded","clickhouse_memory_limit_exceeded","Query memory limit exceeded",- None,+ "clickhouse_memory_limit_exceeded",expected_error_type="memory_limit",),("warehouse_connection", "Warehouse connection failed", None, "Warehouse connection failed", None),@@ -671,10 +672,19 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):self.assertEqual(context.exception.error_code, expected_code)self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")- @parameterized.expand([("keeper_exception",), ("syntax_error",), (None,)])+ @parameterized.expand(+ [+ ("keeper_exception", "keeper_exception"),+ ("syntax_error", "syntax_error"),+ ("UNKNOWN_EXCEPTION", "unknown_exception"),+ (None, None),+ ]+ )@patch("ee.hogai.context.insight.query_executor.process_query_dict")@patch("ee.hogai.context.insight.query_executor.get_query_status")- async def test_async_server_fault_stays_unknown(self, error_code, mock_get_query_status, mock_process_query):+ async def test_async_server_fault_stays_unknown(+ self, error_code, expected_code, mock_get_query_status, mock_process_query+ ):mock_process_query.return_value = {"query_status": {"id": "test-query-id", "complete": False}}mock_get_query_status.return_value = Mock(model_dump=lambda mode: {@@ -686,10 +696,11 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):})with patch("ee.hogai.context.insight.query_executor.asyncio.sleep"):- with self.assertRaises(Exception) as context:+ with self.assertRaises(MaxToolRetryableError) as context:await self.query_runner.arun_and_format_query(AssistantHogQLQuery(query="SELECT 1"))- self.assertIs(type(context.exception), Exception)- self.assertEqual(str(context.exception), "There was an unknown error running this query: Query failed")+ self.assertEqual(str(context.exception), "The query failed because of an internal error")+ self.assertEqual(context.exception.error_type, "internal")+ self.assertEqual(context.exception.error_code, expected_code)@parameterized.expand([diff --git a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py b/ee/hogai/tools/execute_sql/test/test_mcp_tool.pyindex 76485ff557f6..be101332bc3b 100644--- a/ee/hogai/tools/execute_sql/test/test_mcp_tool.py+++ b/ee/hogai/tools/execute_sql/test/test_mcp_tool.py@@ -120,6 +120,13 @@ class TestExecuteSQLMCPTool(ClickhouseTestMixin, NonAtomicBaseTest):self.assertIn("validation failed", str(ctx.exception).lower())self.assertEqual(ctx.exception.error_code, expected_code)+ async def test_unreadable_result_type_names_its_class(self) -> None:+ with self.assertRaises(MaxToolRetryableError) as ctx:+ await self.tool.execute(ExecuteSQLMCPToolArgs(query="SELECT argMinState(event, timestamp) FROM events"))++ self.assertEqual(ctx.exception.error_type, "internal")+ self.assertEqual(ctx.exception.error_code, "unhandled_unknown_type_error")+@parameterized.expand([("trailing_tokens", "SELECT 1 FROM events LIMIT 1 blah", "blah"),diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex ce8365cd8844..22ba373f773d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -50349,7 +50349,7 @@},"error_code": {"default": null,- "description": "Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name.",+ "description": "Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified.","type": ["string", "null"]},"error_message": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 59e6e5274d01..08083d742d2f 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2949,7 +2949,8 @@ export type QueryStatus = {/** @default null */error_message: string | null/**- * Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name.+ * Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name,+ * the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified.* @default null*/error_code: string | nulldiff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex 29251fc17a66..92ed6fca50d0 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -21,12 +21,7 @@ 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 build_direct_query_cancellation_token, request_direct_query_cancellation-from posthog.errors import (- ExposedCHQueryError,- InternalCHQueryError,- internal_ch_error_user_message,- look_up_clickhouse_error_code_meta,-)+from posthog.errors import ExposedCHQueryError, InternalCHQueryError, error_code_from_type, unwrap_exposed_hogql_errorfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.renderers import SafeJSONRenderer@@ -318,11 +313,13 @@ def execute_process_query(is_user_safe_error = isinstance(err, APIException | ExposedHogQLError | ExposedCHQueryError | UserAccessControlError)- error_code = (- look_up_clickhouse_error_code_meta(err).name.lower() if isinstance(err, InternalCHQueryError) else None- )- if internal_ch_error_user_message(error_code):- query_status.error_code = error_code+ if isinstance(err, InternalCHQueryError) or not is_user_safe_error:+ query_status.error_code = error_code_from_type(err)+ elif isinstance(err, ExposedHogQLError):+ cause = unwrap_exposed_hogql_error(err)+ query_status.error_code = (+ cause.code_name if isinstance(cause, ExposedHogQLError) else error_code_from_type(cause)+ )# A stopped run's scan rides on the status so a dead tile can show the advice, with the cache key# for polling. Only for a real user: a shared link must not see the project's data volume.if user_id:diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 43ad52d01b67..e2f113eb7dc6 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -14,7 +14,7 @@ from parameterized import parameterizedfrom posthog.schema import ClickhouseQueryProgress, QueryStatusfrom posthog.hogql.constants import DEFAULT_POSTHOG_AI_RETURNED_ROWS-from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.api_queries_budget import QueryCost, record_request_query_costfrom posthog.clickhouse.client import (@@ -39,6 +39,12 @@ from posthog.redis import get_clientfrom posthog.shared_link_user import SharedLinkUser+def _exposed_from(cause: Exception, message: str) -> ExposedHogQLError:+ error = ExposedHogQLError(message)+ error.__cause__ = cause+ return error++def build_query(sql):return {"kind": "HogQLQuery",@@ -422,6 +428,7 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):self.assertIsNotNone(result.end_time)assert result.error_messageself.assertRegex(result.error_message, "trailing tokens after expression")+ self.assertEqual(result.error_code, "hogql_syntax_error")def test_async_query_user_safe_error_carries_error_code(self):query = build_query("SELECT * FROM events")@@ -440,19 +447,28 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):@parameterized.expand([- ("unknown_identifier", 47, "unknown_identifier"),- ("unsupported_method", 1, "unsupported_method"),- ("syntax_error", 62, None),- ("query_was_cancelled", 394, None),- ("temporary_server_fault", 252, "too_many_parts"),- ("unknown_server_fault", 999_999, None),+ # code_name can be lost when an internal error is re-raised from another thread.+ ("without_user_copy", InternalCHQueryError("DB::Exception: stored-secret", code=62), "syntax_error"),+ (+ "temporary_server_fault",+ InternalCHQueryError("DB::Exception: stored-secret", code=252),+ "too_many_parts",+ ),+ (+ "unknown_server_fault",+ InternalCHQueryError("DB::Exception: stored-secret", code=999_999),+ "unknown_exception",+ ),+ (+ "python_error",+ json.JSONDecodeError("stored-secret", "stored-secret", 0),+ "unhandled_json_decode_error",+ ),])- def test_async_query_internal_ch_error_code(self, _name, code, expected_code):+ def test_async_query_internal_error_code(self, _name, error, expected_code):query = build_query("SELECT * FROM events")query_id = uuid.uuid4().hex- # code_name can be lost when an internal error is re-raised from another thread.- error = InternalCHQueryError("DB::Exception: stored-secret", code=code)with (patch("posthog.api.services.query.process_query_dict", side_effect=error),@@ -494,6 +510,22 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):"Expected an integer argument",False,),+ (+ "wrapped_database_error",+ False,+ _exposed_from(ConnectionError("stored-secret"), "Warehouse connection failed"),+ "unhandled_connection_error",+ "Warehouse connection failed",+ False,+ ),+ (+ "wrapped_query_error",+ False,+ _exposed_from(QueryError("Unknown table `evnts`."), "Warehouse SQL is invalid"),+ "hogql_query_error",+ "Warehouse SQL is invalid",+ False,+ ),])def test_async_query_rejection_code_is_independent_of_message_exposure(diff --git a/posthog/errors.py b/posthog/errors.pyindex 236d9d8dc70a..10a86bd72283 100644--- a/posthog/errors.py+++ b/posthog/errors.py@@ -86,6 +86,8 @@ def clickhouse_error_type(e: Exception) -> str:STORAGE_FILE_URI_PATTERN = re.compile(r"\(in file/uri ([^)]+)\)")+_ACRONYM_BOUNDARY = re.compile(r"([A-Z]+)([A-Z][a-z])")+_WORD_BOUNDARY = re.compile(r"([a-z0-9])([A-Z])")BAD_GET_TYPE_MISMATCH_PATTERN = re.compile(r"\bBad get: has (?P<actual>[A-Za-z][A-Za-z0-9_]{0,63}), "r"requested (?P<expected>[A-Za-z][A-Za-z0-9_]{0,63})(?:\.|$)"@@ -1183,6 +1185,27 @@ def internal_ch_error_user_message(code_name: str | None) -> str | None:return None+def error_code_from_type(error: BaseException) -> str:+ """Return a code for an error from its type alone, since its message can quote stored data.++ A ClickHouse error gets its error name. Any other error gets `unhandled_<exception class>`.+ """+ if isinstance(error, ServerException):+ return look_up_clickhouse_error_code_meta(error).name.lower()+ class_name = _WORD_BOUNDARY.sub(r"\1_\2", _ACRONYM_BOUNDARY.sub(r"\1_\2", type(error).__name__))+ return f"unhandled_{class_name.lower()}"+++def unwrap_exposed_hogql_error(error: ExposedHogQLError) -> BaseException:+ """Return the first cause that is not a plain `ExposedHogQLError` wrapper, such as a database adapter's error."""+ cause: BaseException = error+ seen: set[int] = set()+ while type(cause) is ExposedHogQLError and cause.__cause__ is not None and id(cause) not in seen:+ seen.add(id(cause))+ cause = cause.__cause__+ return cause++# Transient ClickHouse infrastructure errors that are safe to retry.# This can be used in things like celery `autoretry_for` to increase resiliency.# Capacity errors (codes 202/439) are wrapped as ClickHouseAtCapacity by wrap_clickhouse_query_error.diff --git a/posthog/schema.py b/posthog/schema.pyindex 000d05fc1bfd..53b87b7905a5 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -7670,7 +7670,8 @@ class QueryStatus(BaseModel):default=None,description=("Stable machine-readable code for the error, when known: the DRF exception"- " code, or the ClickHouse error name."+ " code, the ClickHouse error name, the HogQL error code, or"+ " `unhandled_<exception class>` for a failure that no handler classified."),)error_message: str | None = Nonediff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 8d174572ed54..fef61c790b2f 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1883,7 +1883,7 @@ export interface QueryStatusApi {end_time?: string | null/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex d6116a9de74c..734ccd9c178c 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2370,7 +2370,7 @@ export interface QueryStatusApi {end_time?: string | null/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.tsindex ea7f65658052..405425c83e68 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -1208,7 +1208,7 @@ export interface QueryStatusApi {end_time?: string | null/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex 13fda7332c15..a71188dcdc35 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1749,7 +1749,7 @@ export interface QueryStatusApi {end_time?: string | null/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/products/posthog_ai/backend/api/mcp_tools.py b/products/posthog_ai/backend/api/mcp_tools.pyindex 406b7610f293..23d995686cc8 100644--- a/products/posthog_ai/backend/api/mcp_tools.py+++ b/products/posthog_ai/backend/api/mcp_tools.py@@ -23,6 +23,7 @@ from posthog.api.documentation import _FallbackSerializerfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, tags_context+from posthog.errors import error_code_from_typefrom posthog.event_usage import get_event_sourcefrom posthog.exceptions_capture import exception_contextfrom posthog.models.team.team import Team@@ -203,6 +204,8 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):"The tool raised an internal error. Do not immediately retry the tool call. "f"Error id: {error_id}"),+ "error_type": "internal",+ "error_code": error_code_from_type(e),})diff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.pyindex 5cc9229e1400..32ff110fbc0c 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -112,6 +112,7 @@ class TestMCPToolsAPI(APIBaseTest):"success": False,"content": "Tool failed: MaxToolRetryableError: Invalid connectionId: no direct-query-capable data source with this id in this team, or you don't have access to it.. You may retry with adjusted inputs.","error_type": "internal",+ "error_code": "hogql_error",},)@@ -189,17 +190,19 @@ class TestMCPToolsAPI(APIBaseTest):"rate_limited","Tool failed: MaxToolTransientError: We're under heavy load right now and couldn't finish this query. Please try again in a few minutes. You may retry this operation once without changes.",),- (+ param("cancelled",CHQueryErrorQueryWasCancelled("private backend detail", code=394),- None,+ "internal","The tool raised an internal error. Do not immediately retry the tool call.",+ error_code="query_was_cancelled",),- (+ param("unknown",RuntimeError("private backend detail"),- None,+ "internal","The tool raised an internal error. Do not immediately retry the tool call.",+ error_code="unhandled_runtime_error",),])@@ -209,10 +212,12 @@ class TestMCPToolsAPI(APIBaseTest):self,_name: str,error: Exception | None,- error_type: str | None,+ error_type: str,content: str,mock_runner_cls: Mock,mock_capture: Mock,+ *,+ error_code: str | None = None,) -> None:if error is None:error = OperationalError("canceling statement due to statement timeout")@@ -226,13 +231,12 @@ class TestMCPToolsAPI(APIBaseTest):)self.assertEqual(response.status_code, 200)- expected = {"success": False, "content": content}- if error_type is not None:- expected["error_type"] = error_type- else:+ expected = {"success": False, "content": content, "error_type": error_type}+ if error_code is not None: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}"+ expected["error_code"] = error_codeself.assertEqual(response.json(), expected)mock_runner_cls.return_value.run.assert_called_once()@@ -348,10 +352,11 @@ class TestMCPToolsAPI(APIBaseTest):"Tool failed: MaxToolRetryableError: Unknown field: missing_column. You may retry with adjusted inputs.",error_code="hogql_query_error",),- (+ param(HogQLNotImplementedError("QueryVisitor has no method visit_select_query"),"internal","Tool failed: MaxToolRetryableError: QueryVisitor has no method visit_select_query. You may retry with adjusted inputs.",+ error_code="hogql_not_implemented",),param(CHQueryErrorIllegalTypeOfArgument("Illegal argument type", code=43),@@ -359,10 +364,11 @@ class TestMCPToolsAPI(APIBaseTest):"Tool failed: MaxToolRetryableError: Illegal argument type. You may retry with adjusted inputs.",error_code="illegal_type_of_argument",),- (+ param(CHQueryErrorCorruptedParquetMetadata("Warehouse file metadata is corrupt", code=1001),"internal","Tool failed: MaxToolRetryableError: Warehouse file metadata is corrupt. You may retry with adjusted inputs.",+ error_code="std_exception",),param(CHQueryErrorS3FileChangedDuringRead("Warehouse file changed while reading", code=499),@@ -382,10 +388,11 @@ class TestMCPToolsAPI(APIBaseTest):"Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Code: 252.\nToo many parts. You may retry with adjusted inputs.",error_code="too_many_parts",),- (+ param(InternalCHQueryError("Unknown failure", code=99999, code_name="s3_error"),"internal","Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Code: 99999.\nUnknown failure. You may retry with adjusted inputs.",+ error_code="unknown_exception",),(_wrapped_hogql_error(TableAccessDeniedError("restricted_table"), "Warehouse table access denied"),@@ -401,20 +408,23 @@ class TestMCPToolsAPI(APIBaseTest):"Tool failed: MaxToolRetryableError: Warehouse SQL is invalid. You may retry with adjusted inputs.",error_code="hogql_query_error",),- (+ param(_wrapped_hogql_error(ConnectionError("connection refused"), "Warehouse connection failed"),"internal","Tool failed: MaxToolRetryableError: Warehouse connection failed. You may retry with adjusted inputs.",+ error_code="unhandled_connection_error",),- (+ param(ExposedHogQLError("Managed warehouse is not available"),"internal","Tool failed: MaxToolRetryableError: Managed warehouse is not available. You may retry with adjusted inputs.",+ error_code="hogql_error",),- (+ param(ValueError("Invalid query result encoding"),"internal","Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Invalid query result encoding. You may retry with adjusted inputs.",+ error_code="unhandled_value_error",),])@@ -450,14 +460,41 @@ class TestMCPToolsAPI(APIBaseTest):None,None,None,- "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query failed. You may retry with adjusted inputs.",+ "Tool failed: MaxToolRetryableError: The query failed because of an internal error. You may retry with adjusted inputs.",),- (+ param("query_was_cancelled",None,None,"query_was_cancelled",- "Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query failed. You may retry with adjusted inputs.",+ "Tool failed: MaxToolRetryableError: The query failed because of an internal error. You may retry with adjusted inputs.",+ expected_error_code="query_was_cancelled",+ ),+ param(+ "trino_unsupported",+ None,+ "[T001] PIVOT is not supported by the Trino backend",+ "hogql_trino_unsupported",+ "Tool failed: MaxToolRetryableError: [T001] PIVOT is not supported by the Trino backend. You may retry with adjusted inputs.",+ expected_error_code="hogql_trino_unsupported",+ expected_error_type="validation",+ ),+ param(+ "table_access_denied",+ None,+ "Access to the table is denied",+ "table_access_denied",+ "Tool failed: MaxToolFatalError: Access to the table is denied.",+ expected_error_type="permission",+ ),+ param(+ "hogql_query_error",+ None,+ "Unable to resolve field: plan",+ "hogql_query_error",+ "Tool failed: MaxToolRetryableError: Unable to resolve field: plan. You may retry with adjusted inputs.",+ expected_error_code="hogql_unresolved_field",+ expected_error_type="validation",),param("storage_error",@@ -488,6 +525,7 @@ class TestMCPToolsAPI(APIBaseTest):"clickhouse_memory_limit_exceeded","Tool failed: MaxToolRetryableError: Query memory limit exceeded. You may retry with adjusted inputs.",expected_error_type="memory_limit",+ expected_error_code="clickhouse_memory_limit_exceeded",),param("legacy_memory_message",@@ -496,12 +534,13 @@ class TestMCPToolsAPI(APIBaseTest):None,"Tool failed: MaxToolRetryableError: Query memory limit exceeded. You may retry with adjusted inputs.",),- (+ param("polling_error",ConnectionError("Query status unavailable"),None,None,"Tool failed: MaxToolRetryableError: Error executing query: There was an unknown error running this query: Query status unavailable. You may retry with adjusted inputs.",+ expected_error_code="unhandled_connection_error",),])@@ -563,6 +602,8 @@ class TestMCPToolsAPI(APIBaseTest):{"success": False,"content": f"The tool raised an internal error. Do not immediately retry the tool call. Error id: {error_id}",+ "error_type": "internal",+ "error_code": "unhandled_runtime_error",},)diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 60c34ef60898..e6ddda0b1be3 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1417,7 +1417,7 @@ export interface QueryStatusApi {end_time?: string | null/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex abe752ab64ad..b7a2225ae595 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2888,7 +2888,7 @@ export namespace Schemas {end_time?: string | null;/** If the query failed, this will be set to true. More information can be found in the error_message field. */error?: boolean | null;- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name, the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified. */error_code?: string | null;error_message?: string | null;expiration_time?: string | null;