: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(query): share safe clickhouse error explanations with mcp (#110117)
posthog[bot]4d31fc309c34
diff --git a/ee/hogai/context/insight/clickhouse_rejections.py b/ee/hogai/context/insight/clickhouse_rejections.pynew file mode 100644index 000000000000..6944d56b7e51--- /dev/null+++ b/ee/hogai/context/insight/clickhouse_rejections.py@@ -0,0 +1,24 @@+"""Explain a ClickHouse rejection whose raw message stays internal.++Some ClickHouse errors embed stored data values in their text, so the query layer keeps that text+internal. Without it, the caller only learns that the query failed and rewrites it by trial and+error. The error name is safe to show, and for the common rejections it is enough to name the fix.+"""++from posthog.errors import internal_ch_error_user_message, is_clickhouse_query_rejection++_CORRECTIONS: dict[str, str] = {+ "UNKNOWN_IDENTIFIER": (+ "Look up the table columns in `system.information_schema.columns`. In a join, prefix each column with its "+ "table alias."+ ),+}+++def describe_clickhouse_rejection(code_name: str | None, message: str | None = None) -> str | None:+ """Name a ClickHouse rejection of the query and its fix, or None if the query did not cause it."""+ if not code_name or not is_clickhouse_query_rejection(code_name):+ return None+ message = message or internal_ch_error_user_message(code_name)+ correction = _CORRECTIONS.get(code_name.upper())+ return f"{message} {correction}" if correction else messagediff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex eda002e356a9..5e3909c79236 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -49,7 +49,15 @@ from posthog.clickhouse.client.execute_async import get_query_statusfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tag_queries, tags_contextfrom posthog.dataclasses import frozen-from posthog.errors import CH_TRANSIENT_ERRORS, ExposedCHQueryError, QueryErrorCategory, classify_query_error+from posthog.errors import (+ CH_TRANSIENT_ERRORS,+ ExposedCHQueryError,+ InternalCHQueryError,+ QueryErrorCategory,+ classify_query_error,+ internal_ch_error_user_message,+ look_up_clickhouse_error_code_meta,+)from posthog.event_usage import EventSourcefrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionMode@@ -58,6 +66,7 @@ from posthog.sync import database_sync_to_asyncfrom products.access_control.backend.facade.user_access_control import UserAccessControlError+from ee.hogai.context.insight.clickhouse_rejections import describe_clickhouse_rejectionfrom ee.hogai.context.insight.format import (NULL_MARKER,TRUNCATED_MARKER,@@ -472,7 +481,13 @@ class AssistantQueryExecutor:# Check for query execution errors before using resultsif query_status.get("error"):- if error_message := query_status.get("error_message"):+ if rejection := describe_clickhouse_rejection(+ query_status.get("error_code"), query_status.get("error_message")+ ):+ raise MaxToolRetryableError(rejection, error_type="validation")+ if error_message := query_status.get("error_message") or internal_ch_error_user_message(+ query_status.get("error_code")+ ):# Async status loses the exception type, so keep retry advice without guessing its category.raise MaxToolRetryableError(error_message, error_type="internal")raise Exception("Query failed")@@ -524,6 +539,10 @@ class AssistantQueryExecutor:raise MaxToolTransientError(err_message, error_type="rate_limited") from errraise MaxToolRetryableError(err_message, error_type=error_type) from errexcept Exception as err:+ if isinstance(err, InternalCHQueryError) and (+ rejection := describe_clickhouse_rejection(look_up_clickhouse_error_code_meta(err).name.lower())+ ):+ raise MaxToolRetryableError(rejection, error_type="validation") from errelapsed = time.time() - start_time# Catch-all for unexpected errors during query execution. Surface the underlying error# text (truncated) so callers can diagnose the failure instead of an opaque message —diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.pyindex 2bcfbb6f5649..e43ee0ef2a33 100644--- a/ee/hogai/context/insight/test/test_query_executor.py+++ b/ee/hogai/context/insight/test/test_query_executor.py@@ -40,7 +40,7 @@ from posthog.hogql.constants import DEFAULT_POSTHOG_AI_RETURNED_ROWSfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context-from posthog.errors import ExposedCHQueryError+from posthog.errors import ExposedCHQueryError, InternalCHQueryErrorfrom posthog.models import Organization, Team, Userfrom ee.hogai.context.insight.context import InsightContext@@ -418,10 +418,29 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):@parameterized.expand([- ("validation", "Unknown field: missing_column", None),- ("timeout", "Query timed out", "error"),- ("memory_limit", "Query memory limit exceeded", "clickhouse_memory_limit_exceeded"),- ("warehouse_connection", "Warehouse connection failed", None),+ ("validation", "Unknown field: missing_column", None, "Unknown field: missing_column"),+ ("timeout", "Query timed out", "error", "Query timed out"),+ (+ "memory_limit",+ "Query memory limit exceeded",+ "clickhouse_memory_limit_exceeded",+ "Query memory limit exceeded",+ ),+ ("warehouse_connection", "Warehouse connection failed", None, "Warehouse connection failed"),+ (+ "known_server_code",+ None,+ "too_many_parts",+ "The database had a temporary problem while it ran this query. "+ "Wait a few minutes, then run the query again. If the problem continues, contact support.",+ ),+ (+ "storage_failure",+ None,+ "s3_error",+ "PostHog couldn't read from storage while running this query. Wait a few minutes, "+ "then run the query again. If the problem continues, contact support.",+ ),])@patch("ee.hogai.context.insight.query_executor.process_query_dict")@@ -429,8 +448,9 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):async def test_async_query_polling_with_error(self,_name: str,- error_message: str,+ error_message: str | None,error_code: str | None,+ expected_message: str,mock_get_query_status: Mock,mock_process_query: Mock,) -> None:@@ -452,10 +472,125 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):with self.assertRaises(MaxToolRetryableError) as context:await self.query_runner.arun_and_format_query(query)- self.assertEqual(str(context.exception), error_message)+ self.assertEqual(str(context.exception), expected_message)self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")self.assertEqual(context.exception.error_type, "internal")+ @parameterized.expand(+ [+ (+ "UNKNOWN_IDENTIFIER",+ None,+ "A column in this query doesn't exist in the data. Check the column names. "+ "If the query uses a view, check that the view still matches its source table. "+ "Look up the table columns in `system.information_schema.columns`. "+ "In a join, prefix each column with its table alias.",+ ),+ (+ "unknown_identifier",+ "Check the column selected by this view.",+ "Check the column selected by this view. "+ "Look up the table columns in `system.information_schema.columns`. "+ "In a join, prefix each column with its table alias.",+ ),+ ("unsupported_method", None, "ClickHouse rejected the query with error UNSUPPORTED_METHOD."),+ ("unsupported_method", "Use a supported query method.", "Use a supported query method."),+ (+ "bad_arguments",+ "This function requires an integer argument.",+ "This function requires an integer argument.",+ ),+ (+ "illegal_type_of_argument",+ "Expected an integer argument",+ "Expected an integer argument",+ ),+ ]+ )+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ @patch("ee.hogai.context.insight.query_executor.get_query_status")+ async def test_async_query_error_code_decides_what_the_agent_reads(+ self, error_code, error_message, expected_message, 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: {+ "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(MaxToolRetryableError) as context:+ await self.query_runner.arun_and_format_query(AssistantHogQLQuery(query="SELECT 1"))+ self.assertEqual(str(context.exception), expected_message)+ self.assertEqual(context.exception.error_type, "validation")+ self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")++ @parameterized.expand(+ [+ (code, code_name, expected_message, expected_exception)+ for code, name, expected_message, expected_exception in [+ (+ 47,+ "unknown_identifier",+ "A column in this query doesn't exist in the data. Check the column names. "+ "If the query uses a view, check that the view still matches its source table. "+ "Look up the table columns in `system.information_schema.columns`. "+ "In a join, prefix each column with its table alias.",+ MaxToolRetryableError,+ ),+ (+ 1,+ "unsupported_method",+ "ClickHouse rejected the query with error UNSUPPORTED_METHOD.",+ MaxToolRetryableError,+ ),+ (+ 62,+ "syntax_error",+ "There was an unknown error running this query: Code: 62.\nstored-secret",+ Exception,+ ),+ ]+ for code_name in [name, None]+ ]+ )+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")+ async def test_internal_clickhouse_query_rejection(+ self, code, code_name, expected_message, expected_exception, mock_process_query+ ):+ mock_process_query.side_effect = InternalCHQueryError("stored-secret", code=code, code_name=code_name)+ with self.assertRaises(expected_exception) as context:+ await self.query_runner.arun_and_format_query(AssistantHogQLQuery(query="SELECT 1"))+ self.assertIs(type(context.exception), expected_exception)+ self.assertEqual(str(context.exception), expected_message)+ if isinstance(context.exception, MaxToolRetryableError):+ self.assertEqual(context.exception.error_type, "validation")+ self.assertEqual(context.exception.retry_hint, " You may retry with adjusted inputs.")++ @parameterized.expand([("keeper_exception",), ("syntax_error",), (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):+ 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": None,+ "error_code": error_code,+ }+ )+ with patch("ee.hogai.context.insight.query_executor.asyncio.sleep"):+ with self.assertRaises(Exception) 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")+@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/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex f3c2c1e56043..1dc6447579b2 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -50842,7 +50842,7 @@},"error_code": {"default": null,- "description": "Stable machine-readable code for the error (the DRF exception code), when known.",+ "description": "Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name.","type": ["string", "null"]},"error_message": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 01f83c3bc653..ec2adef8778b 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2923,7 +2923,7 @@ export type QueryStatus = {/** @default null */error_message: string | null/**- * Stable machine-readable code for the error (the DRF exception code), when known.+ * Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name.* @default null*/error_code: string | nulldiff --git a/posthog/api/query.py b/posthog/api/query.pyindex a20913e7e45c..d503ce0328a5 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -51,7 +51,13 @@ from posthog.clickhouse.client.execute_async import QueryNotFoundError, cancel_qfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tag_value, get_query_tags, tag_queriesfrom posthog.constants import AvailableFeature-from posthog.errors import ExposedCHQueryError, InternalCHQueryError+from posthog.errors import (+ GENERIC_INTERNAL_CH_ERROR_MESSAGE,+ ExposedCHQueryError,+ InternalCHQueryError,+ internal_ch_error_user_message,+ look_up_clickhouse_error_code_meta,+)from posthog.event_usage import EventSource, get_request_analytics_properties, report_user_or_team_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.apply_dashboard_filters import apply_dashboard_filters, apply_dashboard_variables@@ -409,7 +415,9 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)except InternalCHQueryError as e:self.handle_column_ch_error(e)capture_exception(e)- replacement = APIException("ClickHouse error while executing query.")+ error_code = look_up_clickhouse_error_code_meta(e).name+ user_message = internal_ch_error_user_message(error_code)+ replacement = APIException(user_message or GENERIC_INTERNAL_CH_ERROR_MESSAGE)scan_extra = _scan_extra(e)if scan_extra:replacement.extra = scan_extra # type: ignore[attr-defined]@@ -474,17 +482,18 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)detail=MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE,code=MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE,)- query_status_response = QueryStatusResponse(query_status=query_status)-http_code: int = status.HTTP_202_ACCEPTEDif query_status.error:if query_status.error_message:http_code = status.HTTP_400_BAD_REQUEST # An error where a user can likely take an action to resolve itelse:http_code = status.HTTP_500_INTERNAL_SERVER_ERROR # An internal surprise+ # Add safe copy only after choosing the existing HTTP status; internal failures stay 500.+ query_status.error_message = internal_ch_error_user_message(query_status.error_code)elif query_status.complete:http_code = status.HTTP_200_OK+ query_status_response = QueryStatusResponse(query_status=query_status)response = JsonResponse(query_status_response.model_dump(), safe=False, status=http_code)if query_status.bytes_read is not None:_add_query_cost_headers(response, query_status.bytes_read, query_status.budget_remaining_bytes)diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex 3a611e49886a..7da2440ce913 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -123,6 +123,53 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):self.assertNotIn("Retry-After", response)self.assertEqual(mock_capture.called, expect_capture)+ @parameterized.expand(+ [+ (+ "known_code",+ 158,+ "This query reads or returns more data than the limit allows. Use a shorter date range, "+ "add filters, or add a LIMIT clause. Then run the query again.",+ ),+ (+ "unknown_identifier",+ 47,+ "A column in this query doesn't exist in the data. Check the column names. "+ "If the query uses a view, check that the view still matches its source table.",+ ),+ ("unsupported_method", 1, "ClickHouse rejected the query with error UNSUPPORTED_METHOD."),+ ("syntax_error", 62, "ClickHouse error while executing query."),+ ("unknown_code", 999_999, "ClickHouse error while executing query."),+ *[+ (+ storage_error,+ 499,+ "PostHog couldn't read from storage while running this query. Wait a few minutes, "+ "then run the query again. If the problem continues, contact support.",+ f"DB::Exception: {storage_error} reading managed/table.parquet (S3_ERROR)",+ )+ for storage_error in ["SlowDown", "InternalError"]+ ],+ ]+ )+ def test_internal_clickhouse_error_hides_raw_message(+ self, _name, code, expected_detail, raw_message="DB::Exception: raw server detail"+ ):+ error = InternalCHQueryError(raw_message, code=code)++ with (+ patch("posthog.api.query.process_query_model", side_effect=error),+ patch("posthog.api.query.capture_exception") as mock_capture,+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {"query": HogQLQuery(query="select 1").model_dump()},+ )++ self.assertEqual(response.status_code, 500)+ self.assertEqual(response.json()["detail"], expected_detail)+ mock_capture.assert_called_once_with(error)+@parameterized.expand([("timeout", ClickHouseQueryTimeOut("query timed out"), ClickHouseQueryTimeOut.status_code),@@ -1350,18 +1397,58 @@ class TestQueryRetrieve(APIBaseTest):self.assertEqual(response.status_code, 500)self.assertTrue(response.json()["query_status"]["error"])- def test_failed_query_with_exposed_error(self):+ @parameterized.expand(+ [+ (+ "server_failure",+ "too_many_parts",+ "The database had a temporary problem while it ran this query. Wait a few minutes, "+ "then run the query again. If the problem continues, contact support.",+ ),+ (+ "internal_query_rejection",+ "unknown_identifier",+ "A column in this query doesn't exist in the data. Check the column names. "+ "If the query uses a view, check that the view still matches its source table.",+ ),+ ]+ )+ def test_explained_internal_failure_keeps_http_500(self, _name, error_code, message):+ self.redis_client_mock.get.return_value = json.dumps(+ {+ "id": self.valid_query_id,+ "team_id": self.team_id,+ "error": True,+ "error_message": None,+ "error_code": error_code,+ }+ ).encode()+ response = self.client.get(f"/api/environments/{self.team.id}/query/{self.valid_query_id}/")+ self.assertEqual(response.status_code, 500)+ self.assertEqual(response.json()["query_status"]["error_message"], message)+ self.assertEqual(response.json()["query_status"]["error_code"], error_code)++ @parameterized.expand(+ [+ ("validation", "Try changing the time range", None),+ ("timeout", "Query timed out", "error"),+ ("memory_limit", "Query memory limit exceeded", "clickhouse_memory_limit_exceeded"),+ ]+ )+ def test_failed_query_with_exposed_error(self, _name, message, error_code):self.redis_client_mock.get.return_value = json.dumps({"id": self.valid_query_id,"team_id": self.team_id,"error": True,- "error_message": "Try changing the time range",+ "error_message": message,+ "error_code": error_code,}).encode()response = self.client.get(f"/api/environments/{self.team.id}/query/{self.valid_query_id}/")self.assertEqual(response.status_code, 400)self.assertTrue(response.json()["query_status"]["error"])+ self.assertEqual(response.json()["query_status"]["error_message"], message)def test_destroy(self):self.redis_client_mock.get.return_value = json.dumps(diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex cbac05a7de34..29251fc17a66 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -21,7 +21,12 @@ 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+from posthog.errors import (+ ExposedCHQueryError,+ InternalCHQueryError,+ internal_ch_error_user_message,+ look_up_clickhouse_error_code_meta,+)from posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.renderers import SafeJSONRenderer@@ -313,6 +318,11 @@ 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# 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 733f7bb245fe..68a1319f668a 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -29,7 +29,7 @@ from posthog.direct_query_cancellation import (build_direct_query_cancellation_token,is_direct_query_cancellation_requested,)-from posthog.errors import ExposedCHQueryError+from posthog.errors import ExposedCHQueryError, InternalCHQueryErrorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceededfrom posthog.models import Organization, Teamfrom posthog.models.sharing_configuration import SharingConfiguration@@ -424,6 +424,83 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):assert result.error_messageself.assertEqual(result.error_code, ClickHouseQueryMemoryLimitExceeded.default_code)+ @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),+ ]+ )+ def test_async_query_internal_ch_error_code(self, _name, code, 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),+ patch("posthog.clickhouse.client.execute_async.capture_exception") as mock_capture,+ ):+ client.enqueue_process_query_task(+ self.team, self.user.id, query, query_id=query_id, _test_only_bypass_celery=True+ )++ result = client.get_query_status(self.team.id, query_id)+ self.assertTrue(result.error)+ self.assertIsNone(result.error_message)+ self.assertEqual(result.error_code, expected_code)+ mock_capture.assert_called_once_with(error)++ @parameterized.expand(+ [+ (+ "staff_internal_rejection",+ True,+ InternalCHQueryError("Unknown column", code=47),+ "unknown_identifier",+ "Code: 47.\nUnknown column",+ True,+ ),+ (+ "exposed_rejection",+ False,+ ExposedCHQueryError("Expected an integer argument", code=43),+ "illegal_type_of_argument",+ "Expected an integer argument",+ False,+ ),+ (+ "staff_exposed_rejection",+ True,+ ExposedCHQueryError("Expected an integer argument", code=43),+ "illegal_type_of_argument",+ "Expected an integer argument",+ False,+ ),+ ]+ )+ def test_async_query_rejection_code_is_independent_of_message_exposure(+ self, _name, is_staff, error, expected_code, expected_message, captured+ ):+ self.user.is_staff = is_staff+ self.user.save(update_fields=["is_staff"])+ query_id = uuid.uuid4().hex+ with (+ patch("posthog.api.services.query.process_query_dict", side_effect=error),+ patch("posthog.clickhouse.client.execute_async.capture_exception") as mock_capture,+ ):+ client.enqueue_process_query_task(+ self.team, self.user.id, build_query("SELECT 1"), query_id=query_id, _test_only_bypass_celery=True+ )+ result = client.get_query_status(self.team.id, query_id)+ self.assertTrue(result.error)+ self.assertEqual(result.error_code, expected_code)+ self.assertEqual(result.error_message, expected_message)+ self.assertEqual(mock_capture.called, captured)+def test_async_query_server_errors(self):query = build_query("SELECT * FROM events")diff --git a/posthog/errors.py b/posthog/errors.pyindex 2126bbf0b73f..ad93fa659499 100644--- a/posthog/errors.py+++ b/posthog/errors.py@@ -1090,6 +1090,71 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {1004: ErrorCodeMeta("STARTUP_SCRIPTS_ERROR"),}+GENERIC_INTERNAL_CH_ERROR_MESSAGE = "ClickHouse error while executing query."++_TOO_MUCH_DATA_MESSAGE = (+ "This query reads or returns more data than the limit allows. "+ "Use a shorter date range, add filters, or add a LIMIT clause. Then run the query again."+)+_TOO_COMPLEX_MESSAGE = (+ "This query is too complex to run. "+ "Use fewer nested subqueries, conditions, or values in IN lists. Then run the query again."+)+_TEMPORARY_FAILURE_MESSAGE = (+ "The database had a temporary problem while it ran this query. "+ "Wait a few minutes, then run the query again. If the problem continues, contact support."+)++# Fixed copy for internal ClickHouse errors. The raw ClickHouse message stays hidden, because it can+# contain stored data values or server internals.+INTERNAL_CH_ERROR_USER_MESSAGES: dict[str, str] = {+ "TOO_MANY_ROWS": _TOO_MUCH_DATA_MESSAGE,+ "TOO_MANY_ROWS_OR_BYTES": _TOO_MUCH_DATA_MESSAGE,+ "SET_SIZE_LIMIT_EXCEEDED": _TOO_MUCH_DATA_MESSAGE,+ "TOO_MANY_COLUMNS": "This query uses more columns than the limit allows. Select fewer columns, then run the query again.",+ "TOO_DEEP_SUBQUERIES": _TOO_COMPLEX_MESSAGE,+ "TOO_DEEP_AST": _TOO_COMPLEX_MESSAGE,+ "TOO_BIG_AST": _TOO_COMPLEX_MESSAGE,+ "TOO_DEEP_RECURSION": _TOO_COMPLEX_MESSAGE,+ "TOO_MANY_PARTS": _TEMPORARY_FAILURE_MESSAGE,+ "TABLE_IS_READ_ONLY": _TEMPORARY_FAILURE_MESSAGE,+ "NETWORK_ERROR": _TEMPORARY_FAILURE_MESSAGE,+ "SOCKET_TIMEOUT": _TEMPORARY_FAILURE_MESSAGE,+ "ALL_CONNECTION_TRIES_FAILED": _TEMPORARY_FAILURE_MESSAGE,+ "S3_ERROR": (+ "PostHog couldn't read from storage while running this query. "+ "Wait a few minutes, then run the query again. If the problem continues, contact support."+ ),+ "UNKNOWN_IDENTIFIER": (+ "A column in this query doesn't exist in the data. "+ "Check the column names. If the query uses a view, check that the view still matches its source table."+ ),+}+++# The error name holds no stored data values, so it is safe to show for an error the query caused,+# even when the full message is not. Server faults and compiler syntax errors stay out, because+# callers cannot act on them.+def is_clickhouse_query_rejection(code_name: str) -> bool:+ code_name = code_name.upper()+ return code_name != "SYNTAX_ERROR" and any(+ meta.name == code_name and meta.get_category() == QueryErrorCategory.USER_ERROR+ for meta in CLICKHOUSE_ERROR_CODE_LOOKUP.values()+ )+++def internal_ch_error_user_message(code_name: str | None) -> str | None:+ """Return user-safe copy for a known internal ClickHouse error, or None for an unknown error."""+ if not code_name:+ return None+ code_name = code_name.upper()+ if message := INTERNAL_CH_ERROR_USER_MESSAGES.get(code_name):+ return message+ if is_clickhouse_query_rejection(code_name):+ return f"ClickHouse rejected the query with error {code_name}."+ return None++# 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 7ff266de8945..609b4660b28b 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -7265,7 +7265,10 @@ class QueryStatus(BaseModel):)error_code: str | None = Field(default=None,- description=("Stable machine-readable code for the error (the DRF exception code), when known."),+ description=(+ "Stable machine-readable code for the error, when known: the DRF exception"+ " code, or the ClickHouse error name."+ ),)error_message: str | None = Noneexpiration_time: AwareDatetime | None = Nonediff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex e2656618c6bb..eb0ea60dac4e 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1877,7 +1877,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */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 5077e0b0b0b6..13eaee1e2427 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2130,7 +2130,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */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 132f08591cf1..e3e3b09f9507 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -1135,7 +1135,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */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 038d2e5b5d76..283fbe8c5370 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -1742,7 +1742,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */error_code?: string | nullerror_message?: string | nullexpiration_time?: string | nulldiff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.pyindex a21e5f90dd28..8dc2d9bb8cbf 100644--- a/products/posthog_ai/backend/api/test_mcp_tools.py+++ b/products/posthog_ai/backend/api/test_mcp_tools.py@@ -380,18 +380,28 @@ class TestMCPToolsAPI(APIBaseTest):"query_error",None,"Query failed",+ None,"Tool failed: MaxToolRetryableError: Query failed. You may retry with adjusted inputs.",),("missing_error_message",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.",+ ),+ (+ "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.",),("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.",),]@@ -404,6 +414,7 @@ class TestMCPToolsAPI(APIBaseTest):_name: str,polling_error: Exception | None,error_message: str | None,+ error_code: str | None,content: str,mock_query: Mock,mock_status: Mock,@@ -416,6 +427,7 @@ class TestMCPToolsAPI(APIBaseTest):"complete": True,"error": True,"error_message": error_message,+ "error_code": error_code,}response = self.client.post(diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex f9895091de1f..939a22747760 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1057,7 +1057,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */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 90efd12b44fa..95218b0d2f0b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2714,7 +2714,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 (the DRF exception code), when known. */+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */error_code?: string | null;error_message?: string | null;expiration_time?: string | null;