: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(queries): stop customer SQL errors reporting as faults (#113660)
posthog[bot]81a81cafc5fd
diff --git a/posthog/hogql_queries/user_query_errors.py b/posthog/hogql_queries/user_query_errors.pynew file mode 100644index 000000000000..b5f85aa00ce0--- /dev/null+++ b/posthog/hogql_queries/user_query_errors.py@@ -0,0 +1,47 @@+from rest_framework.exceptions import ValidationError++from posthog.hogql import errors as hogql_errors+from posthog.hogql.errors import ExposedHogQLError++from posthog.errors import (+ CHQueryErrorCannotParseUuid,+ CHQueryErrorIllegalAggregation,+ CHQueryErrorIllegalTypeOfArgument,+ CHQueryErrorInvalidJoinOnExpression,+ CHQueryErrorNoCommonType,+ CHQueryErrorNotAnAggregate,+ CHQueryErrorNumberOfArgumentsDoesntMatch,+ CHQueryErrorTooManyBytes,+ CHQueryErrorTypeMismatch,+ CHQueryErrorUnknownFunction,+ CHQueryErrorUnknownIdentifier,+ CHQueryErrorUnknownTable,+ CHQueryErrorUnsupportedMethod,+ ExposedCHQueryError,+)+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQuerySizeExceeded, ClickHouseQueryTimeOut++USER_QUERY_ERRORS: tuple[type[Exception], ...] = (+ ExposedHogQLError,+ hogql_errors.QueryError,+ hogql_errors.SyntaxError,+ ValidationError,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQueryTimeOut,+ ExposedCHQueryError,+ CHQueryErrorIllegalTypeOfArgument,+ CHQueryErrorNoCommonType,+ CHQueryErrorNotAnAggregate,+ CHQueryErrorUnknownFunction,+ CHQueryErrorTypeMismatch,+ CHQueryErrorIllegalAggregation,+ CHQueryErrorNumberOfArgumentsDoesntMatch,+ CHQueryErrorUnknownIdentifier,+ CHQueryErrorTooManyBytes,+ CHQueryErrorCannotParseUuid,+ ClickHouseQuerySizeExceeded,+ CHQueryErrorUnsupportedMethod,+ hogql_errors.ResolutionError,+ CHQueryErrorInvalidJoinOnExpression,+ CHQueryErrorUnknownTable,+)diff --git a/posthog/tasks/exporter.py b/posthog/tasks/exporter.pyindex 9e7ec15181c1..f5627ab1ea1e 100644--- a/posthog/tasks/exporter.py+++ b/posthog/tasks/exporter.py@@ -15,7 +15,7 @@ from products.exports.backend.facade.exporters import get_export_format_handlerfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.source_authentication import assert_export_authorizationfrom products.exports.backend.tasks.failure_handler import (- USER_QUERY_ERRORS,+ FAILURE_TYPE_USER,InvalidExportContext,classify_failure_type,)@@ -163,7 +163,7 @@ def export_asset_direct(exported_asset.failure_type = Noneexported_asset.save(update_fields=["exception", "exception_type", "failure_type"])except Exception as e:- is_user_error = isinstance(e, USER_QUERY_ERRORS)+ is_user_error = classify_failure_type(e) == FAILURE_TYPE_USERif is_user_error:logger.warning(diff --git a/posthog/tasks/test/test_exporter.py b/posthog/tasks/test/test_exporter.pyindex 877ca4391839..e7851aa573fb 100644--- a/posthog/tasks/test/test_exporter.py+++ b/posthog/tasks/test/test_exporter.py@@ -12,6 +12,7 @@ from parameterized import parameterizedfrom posthog.hogql.errors import QueryErrorfrom posthog.constants import AvailableFeature+from posthog.errors import CHQueryErrorS3FileChangedDuringReadfrom posthog.event_usage import EventSourcefrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.models import OrganizationMembership, User@@ -261,9 +262,18 @@ class TestExportAssetFailureRecording(APIBaseTest):assert asset.exception_type == "QueryError"assert asset.failure_type == "user"+ @parameterized.expand(+ [+ (ClickHouseAtCapacity(),),+ (CHQueryErrorS3FileChangedDuringRead("A warehouse file changed during the read.", code=499),),+ ]+ )+ @patch("posthog.tasks.exporter.posthoganalytics.capture")@patch("products.exports.backend.tasks.image_exporter.export_image")- def test_transient_error_records_failure_without_retry(self, mock_export_direct: MagicMock) -> None:- mock_export_direct.side_effect = ClickHouseAtCapacity()+ def test_transient_error_records_failure_without_retry(+ self, error: Exception, mock_export_direct: MagicMock, mock_capture: MagicMock+ ) -> None:+ mock_export_direct.side_effect = errorasset = ExportedAsset.objects.create(team=self.team,@@ -276,6 +286,8 @@ class TestExportAssetFailureRecording(APIBaseTest):assert mock_export_direct.call_count == 1asset.refresh_from_db()- assert asset.exception == ClickHouseAtCapacity.default_detail- assert asset.exception_type == "ClickHouseAtCapacity"+ assert asset.exception == str(error)+ assert asset.exception_type == type(error).__name__assert asset.failure_type == FAILURE_TYPE_SYSTEM+ failed_event = next(c for c in mock_capture.call_args_list if c.kwargs["event"] == "export failed")+ assert failed_event.kwargs["properties"]["is_user_error"] is Falsediff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex a5d1498e93ee..a3a766ba79d2 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -16,6 +16,7 @@ from django.conf import settingsimport aiohttpimport pyarrow as pa+from clickhouse_driver.errors import ServerExceptionfrom structlog import get_loggerfrom temporalio import activity@@ -25,6 +26,7 @@ import posthog.temporal.common.asyncpa as asyncpafrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.client.connection import MAX_QUERY_SIZE_BYTES, ClickHouseCredentialsfrom posthog.clickhouse.query_tagging import QueryTags, TemporalTags, get_query_tags+from posthog.errors import QueryErrorCategory, classify_query_errorfrom posthog.security.outbound_proxy import internal_requests_sessionif typing.TYPE_CHECKING:@@ -169,6 +171,7 @@ class ClickHouseClientNotConnected(Exception):super().__init__("ClickHouseClient is not connected. Are you running in a context manager?")+_CLICKHOUSE_ERROR_CODE_PATTERN = re.compile(r"\bCode:\s*(\d+)\b")_CLICKHOUSE_ERROR_START = re.compile(r"(?:(?:std::exception|Poco::Exception)\. )?Code: \d+[.,] ")# ClickHouse 25+ wraps the error in "__exception__" lines and closes it with "<size> <tag>"._CLICKHOUSE_ERROR_TRAILER = re.compile(r"(\r?\n\d+ \w+)?\r?\n__exception__\s*$")@@ -189,9 +192,11 @@ def extract_clickhouse_error(payload: bytes) -> str | None:class ClickHouseError(Exception):"""Base Exception representing anything going wrong with ClickHouse."""- def __init__(self, error_message, query: str | None = None, query_id: str | None = None):+ def __init__(self, error_message: str, query: str | None = None, query_id: str | None = None):self.query = queryself.query_id = query_id+ code_match = _CLICKHOUSE_ERROR_CODE_PATTERN.search(error_message)+ self.code = int(code_match.group(1)) if code_match else Nonesuper().__init__(error_message)@@ -258,6 +263,14 @@ class ClickHouseTooManySimultaneousQueriesError(ClickHouseError):super().__init__(error_message, query, query_id)+class ClickHouseQueryPlanningError(ClickHouseError):+ """Exception raised when a DESCRIBE probe cannot plan a rewritten query."""+++class ClickHouseUserQueryError(ClickHouseError):+ """Exception raised when ClickHouse rejects a permanently invalid user query."""++class ClickHouseCheckQueryStatusError(ClickHouseError):"""Exception raised when checking the status of a query fails."""@@ -454,6 +467,13 @@ class ClickHouseClient:for error_code, exc_class in ERROR_CODE_TO_EXCEPTION.items():if error_code in error_message:raise exc_class(error_message, query=query, query_id=query_id)++ code_match = _CLICKHOUSE_ERROR_CODE_PATTERN.search(error_message)+ if code_match:+ code = int(code_match.group(1))+ server_error = ServerException(error_message, code=code)+ if classify_query_error(server_error) == QueryErrorCategory.USER_ERROR:+ raise ClickHouseUserQueryError(error_message, query=query, query_id=query_id)raise ClickHouseError(error_message, query=query, query_id=query_id)@classmethoddiff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex b57efea65630..e5b65b82e9a3 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -43,6 +43,7 @@ from posthog.settings.base_variables import TESTfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.clickhouse import (ClickHouseError,+ ClickHouseQueryPlanningError,ClickHouseQueryTimeoutError,ClickHouseTooManySimultaneousQueriesError,get_client as get_clickhouse_client,@@ -163,15 +164,20 @@ async def _describe_columns() -> list[_DescribedColumn]:"""A select list is ordered and may repeat a name, so the probe returns a list, not a mapping.`_reject_duplicate_output_columns` is what turns a repeat into a readable error."""- async with _clickhouse_query_semaphore, get_clickhouse_client() as client:- async with client.apost_query(- query=f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw",- query_parameters=query_parameters,- query_id=str(uuid.uuid4()),- settings=query_settings,- external_tables=external_tables,- ) as ch_response:- table_describe_response = await ch_response.content.read()+ try:+ async with _clickhouse_query_semaphore, get_clickhouse_client() as client:+ async with client.apost_query(+ query=f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw",+ query_parameters=query_parameters,+ query_id=str(uuid.uuid4()),+ settings=query_settings,+ external_tables=external_tables,+ ) as ch_response:+ table_describe_response = await ch_response.content.read()+ except ClickHouseError as error:+ if error.code != 8 or query_settings is None:+ raise+ raise ClickHouseQueryPlanningError(str(error), query=error.query, query_id=error.query_id) from errorcolumns: list[_DescribedColumn] = []for line in table_describe_response.decode("utf-8").splitlines():column_name, ch_type = line.strip().split("\t")@@ -733,7 +739,7 @@ async def hogql_table(described_columns = await _describe_columns(printed, context.values, DESCRIBE_QUERY_SETTINGS, list(context.external_tables.values()))- except ClickHouseError as error:+ except ClickHouseQueryPlanningError as error:# ClickHouse cannot plan some shapes once GLOBAL is gone, such as an IN subquery inside an# aggregate function. The untouched query is the one that runs, so it always describes.await logger.awarning(diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.pyindex 80aae7377792..6b5407094c5a 100644--- a/posthog/temporal/data_modeling/workflows/materialize_view.py+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py@@ -75,6 +75,7 @@ from products.warehouse_sources.backend.facade.hooks import (# these indicate problems with the query or data, not transient issuesNON_RETRYABLE_ERRORS = ["CHQueryErrorMemoryLimitExceeded",+ "ClickHouseUserQueryError","CannotCoerceColumnException","InvalidNodeTypeException","NodeNotFoundException",diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 99f5e0e07aa2..0a4c2cb8e815 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -2139,7 +2139,8 @@ class _EmptyArrowClient:self.describe_settings: dict[str, str] | None = Noneself.describe_query: str | None = Noneself.describe_calls: list[tuple[str, dict[str, str] | None]] = []- self.reject_describe_with_settings = False+ self.describe_error: Exception | None = None+ self.arrow_error: Exception | None = Noneself.arrow_query: str | None = Noneasync def astream_query_as_arrow(@@ -2153,6 +2154,8 @@ class _EmptyArrowClient:) -> AsyncIterator[pa.RecordBatch]:self.arrow_query_calls += 1self.arrow_query = query+ if self.arrow_error is not None:+ raise self.arrow_errorif on_schema is not None:on_schema(self.schema)return@@ -2170,8 +2173,8 @@ class _EmptyArrowClient:) -> AsyncIterator[Any]:if query.startswith("DESCRIBE TABLE"):self.describe_calls.append((query, settings))- if self.reject_describe_with_settings and settings is not None:- raise ClickHouseError("Code: 8. DB::Exception: Cannot find column in source stream", query=query)+ if self.describe_error is not None and settings is not None:+ raise self.describe_errorself.describe_settings = settingsself.describe_query = querybody = self.describe_body@@ -2540,10 +2543,25 @@ class TestHogqlTableDescribeSettings:assert client.describe_query is not None and global_function not in client.describe_queryassert client.arrow_query is not None and global_function in client.arrow_query- async def test_describe_probe_falls_back_to_the_untouched_query(self, ateam: Team) -> None:+ @pytest.mark.parametrize(+ "describe_error,should_fallback",+ [+ (+ ClickHouseError("Code: 8. DB::Exception: Cannot find column in source stream"),+ True,+ ),+ (+ ClickHouseTooManySimultaneousQueriesError("Code: 202. DB::Exception: Too many simultaneous queries"),+ False,+ ),+ ],+ )+ async def test_describe_probe_only_falls_back_for_planning_errors(+ self, ateam: Team, describe_error: Exception, should_fallback: bool+ ) -> None:client = _EmptyArrowClient(pa.schema([pa.field("distinct_id", pa.string())]))client.describe_body = b"distinct_id\tString\n"- client.reject_describe_with_settings = True+ client.describe_error = describe_errorquery = "SELECT distinct_id FROM events WHERE distinct_id IN (SELECT distinct_id FROM events WHERE event = 'x')"@contextlib.asynccontextmanager@@ -2553,14 +2571,38 @@ class TestHogqlTableDescribeSettings:with unittest.mock.patch("posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client):- batches = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]+ if should_fallback:+ batches = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]+ assert batches[0][1] == [("distinct_id", "String")]+ else:+ with pytest.raises(type(describe_error)):+ _ = [batch async for batch in hogql_table(query, ateam, LOGGER.bind())]- assert [settings for _, settings in client.describe_calls] == [- {"distributed_product_mode": "allow", "prefer_global_in_and_join": "0"},- None,+ expected_settings: list[dict[str, str] | None] = [+ {"distributed_product_mode": "allow", "prefer_global_in_and_join": "0"}]- assert "globalIn(" in client.describe_calls[1][0]- assert batches[0][1] == [("distinct_id", "String")]+ if should_fallback:+ expected_settings.append(None)+ assert "globalIn(" in client.describe_calls[1][0]+ assert [settings for _, settings in client.describe_calls] == expected_settings++ async def test_arrow_query_preserves_a_generic_column_error(self, ateam: Team) -> None:+ client = _EmptyArrowClient(pa.schema([pa.field("distinct_id", pa.string())]))+ client.describe_body = b"distinct_id\tString\n"+ client.arrow_error = ClickHouseError("Code: 8. DB::Exception: Cannot find column in source stream")++ @contextlib.asynccontextmanager+ async def fake_get_client(*args, **kwargs):+ yield client++ with unittest.mock.patch(+ "posthog.temporal.data_modeling.activities.materialize_view.get_clickhouse_client", fake_get_client+ ):+ with pytest.raises(ClickHouseError) as error:+ _ = [batch async for batch in hogql_table("SELECT distinct_id FROM events", ateam, LOGGER.bind())]++ assert error.value is client.arrow_error+ assert client.arrow_query_calls == 1class TestHogqlTableDuplicateOutputColumns:diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.pyindex ec362b46abfc..efbd9cc13366 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py@@ -241,6 +241,10 @@ class TestQualityGateBranching:started = [call.args[0].__name__ for call in execute_activity.await_args_list]assert "publish_queryable_table_activity" in startedassert "succeed_materialization_activity" in started+ materialize_call = next(+ call for call in execute_activity.await_args_list if call.args[0].__name__ == "materialize_view_activity"+ )+ assert "ClickHouseUserQueryError" in materialize_call.kwargs["retry_policy"].non_retryable_error_typesasync def test_an_audit_that_reached_no_verdict_leaves_the_node_to_the_sweep(self):# Returning zero here would publish and also claim the node was audited, so the DAG'sdiff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.pyindex f8cc6bd912e4..576ca2ae63e1 100644--- a/posthog/temporal/tests/test_clickhouse.py+++ b/posthog/temporal/tests/test_clickhouse.py@@ -24,6 +24,7 @@ from posthog.temporal.common.clickhouse import (ClickHouseTooManyBytesError,ClickHouseTooManySimultaneousQueriesError,ClickHouseUnknownTableError,+ ClickHouseUserQueryError,add_log_comment_param,encode_clickhouse_data,)@@ -197,6 +198,14 @@ def _mock_internal_session_post(return_value):"Code: 60. DB::Exception: Table posthog.missing_table does not exist. (UNKNOWN_TABLE)",ClickHouseUnknownTableError,),+ (+ "Code: 8. DB::Exception: Cannot find column in source stream. (THERE_IS_NO_COLUMN) (version x.x.x.x (official build))",+ ClickHouseError,+ ),+ (+ "Code: 215. DB::Exception: Column `value` is not under aggregate function and not in GROUP BY keys. (NOT_AN_AGGREGATE) (version x.x.x.x (official build))",+ ClickHouseUserQueryError,+ ),],ids=["MEMORY_LIMIT_EXCEEDED",@@ -205,15 +214,18 @@ def _mock_internal_session_post(return_value):"TIMEOUT_EXCEEDED","ALL_REPLICAS_ARE_STALE","UNKNOWN_TABLE",+ "THERE_IS_NO_COLUMN",+ "NOT_AN_AGGREGATE",],)def test_clickhouse_error_code_maps_to_exception(clickhouse_client, error_text, expected_exception):"""Server-side ClickHouse error codes map to the matching client exception class."""mock_response = MagicMock(status_code=500, text=error_text)with _mock_internal_session_post(mock_response):- with pytest.raises(expected_exception):+ with pytest.raises(ClickHouseError) as error_info:with clickhouse_client.post_query("SELECT 1", query_parameters={}, query_id=None):pass+ assert type(error_info.value) is expected_exceptiondef test_post_query_disables_http_compression(clickhouse_client):diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex 865a48576a6e..92bb3db80370 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -55,7 +55,12 @@ from posthog.clickhouse.query_tagging import (tag_queries,tags_context,)-from posthog.errors import ExposedCHQueryError+from posthog.errors import (+ CHQueryErrorUnknownIdentifier,+ CHQueryErrorUnknownTable,+ CHQueryErrorUnsupportedMethod,+ ExposedCHQueryError,+)from posthog.event_usage import get_request_analytics_properties, report_user_actionfrom posthog.exceptions import (APIQueriesBudgetExceeded,@@ -66,6 +71,7 @@ from posthog.exceptions import (ClickHouseQueryTimeOut,)from posthog.exceptions_capture import capture_exception+from posthog.hogql_queries.user_query_errors import USER_QUERY_ERRORSfrom posthog.models import Team, Userfrom posthog.permissions import is_authenticated_via_project_secret_api_keyfrom posthog.schema_migrations.upgrade import upgrade@@ -125,29 +131,23 @@ _QUERY_PERFORMANCE_ERRORS: dict[type[Exception], tuple[str, str]] = {),}-# Cost guardrails, budget refusals and transient capacity: customer problems, not faults. Skipped-# from capture and re-raised past the materialized/ducklake inline fallback.-_QUERY_GUARDRAIL_ERRORS: tuple[type[Exception], ...] = (+_ENDPOINT_USER_QUERY_ERRORS = tuple(+ error for error in USER_QUERY_ERRORS if error not in (CHQueryErrorUnknownIdentifier, CHQueryErrorUnsupportedMethod)+)++_NON_REPORTABLE_QUERY_ERRORS: tuple[type[Exception], ...] = (*_QUERY_PERFORMANCE_ERRORS,+ *_ENDPOINT_USER_QUERY_ERRORS,ClickHouseAtCapacity,APIQueriesBudgetExceeded,+ ConcurrencyLimitExceeded,)-def _is_query_guardrail_error(error: BaseException) -> bool:- return isinstance(error, _QUERY_GUARDRAIL_ERRORS)---# ClickHouse cannot parse a value the customer sent (e.g. a bad date variable). execute() returns a 400.-_CUSTOMER_INPUT_ERROR_CODES = frozenset(- {"cannot_parse_date", "cannot_parse_datetime", "cannot_parse_number", "decimal_overflow"}-)---def _is_customer_input_error(error: BaseException) -> bool:- if isinstance(error, ValidationError):- return True- return isinstance(error, ExposedCHQueryError) and error.code_name in _CUSTOMER_INPUT_ERROR_CODES+def _is_non_reportable_query_error(error: Exception, *, materialized: bool) -> bool:+ if materialized and isinstance(error, CHQueryErrorUnknownTable):+ return False+ return isinstance(error, _NON_REPORTABLE_QUERY_ERRORS)# Connection loss outside SQLSTATE class 08 (connection_exception).@@ -916,8 +916,7 @@ class EndpointExecutionService(PydanticModelMixin):return resultexcept Exception as e:- # Guardrail and input errors are customer-caused, not faults: skip capture and let execute() classify them.- if _is_query_guardrail_error(e) or _is_customer_input_error(e):+ if _is_non_reportable_query_error(e, materialized=True):raiselogger.exception("Materialized endpoint execution failed",@@ -1026,8 +1025,7 @@ class EndpointExecutionService(PydanticModelMixin):except Exception as e:self.handle_column_ch_error(e)- # Guardrail and input errors are customer-caused, not faults: skip capture and let execute() classify them.- if _is_query_guardrail_error(e) or _is_customer_input_error(e):+ if _is_non_reportable_query_error(e, materialized=False):raiselogger.exception("Inline endpoint execution failed",diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 7e6394e0f3b4..8413c5d2d483 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -22,7 +22,14 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tags-from posthog.errors import CHQueryErrorNoCommonType, wrap_clickhouse_query_error+from posthog.errors import (+ CHQueryErrorNoCommonType,+ CHQueryErrorNotAnAggregate,+ CHQueryErrorUnknownIdentifier,+ CHQueryErrorUnknownTable,+ CHQueryErrorUnsupportedMethod,+ wrap_clickhouse_query_error,+)from posthog.exceptions import APIQueriesBudgetExceeded, ClickHouseAtCapacityfrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery@@ -159,6 +166,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):None,"HogQL column `missing_property` could not be resolved",None,+ False,),("clickhouse",@@ -166,6 +174,15 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):"no_common_type","There is no supertype for types String, UInt64","Stack trace",+ False,+ ),+ (+ "materialized_clickhouse",+ "DB::Exception: Column `value` is not under aggregate function and not in GROUP BY keys",+ "not_an_aggregate",+ "Column `value` is not under aggregate function",+ None,+ True,),])@@ -176,6 +193,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):code_name: str | None,expected_detail: str,forbidden_detail: str | None,+ is_materialized: bool,):endpoint = create_endpoint_with_version(name=f"{_name}_safe_error",@@ -184,16 +202,23 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):created_by=self.user,is_active=True,)- error = (- CHQueryErrorNoCommonType(message, code=386, code_name=code_name)- if code_name- else ExposedHogQLError(message)- )+ error: Exception+ if code_name == "not_an_aggregate":+ error = CHQueryErrorNotAnAggregate(message, code=215, code_name=code_name)+ elif code_name:+ error = CHQueryErrorNoCommonType(message, code=386, code_name=code_name)+ else:+ error = ExposedHogQLError(message)++ if is_materialized:+ self._materialize_endpoint(endpoint)with (mock.patch("products.endpoints.backend.logic.execution.process_query_model", side_effect=error),- mock.patch("products.endpoints.backend.logic.execution.capture_exception"),- mock.patch("products.endpoints.backend.logic.execution._emit_endpoint_failure_signal"),+ mock.patch("products.endpoints.backend.logic.execution.capture_exception") as mock_capture,+ mock.patch(+ "products.endpoints.backend.logic.execution._emit_endpoint_failure_signal"+ ) as mock_failure_signal,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"@@ -205,6 +230,8 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self.assertNotIn("Query execution failed.", detail)if forbidden_detail:self.assertNotIn(forbidden_detail, detail)+ mock_capture.assert_not_called()+ mock_failure_signal.assert_not_called()def test_budget_refusal_does_not_count_as_an_endpoint_error(self):endpoint = create_endpoint_with_version(@@ -281,7 +308,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):[("cannot_parse_datetime", 41, False),("cannot_parse_number", 72, False),- ("no_common_type", 386, True),+ ("no_common_type", 386, False),])def test_customer_input_errors_skip_error_tracking(self, _name: str, code: int, expect_capture: bool):@@ -2470,14 +2497,27 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):after = REGISTRY.get_sample_value("posthog_endpoint_materialization_event_total", labels) or 0.0self.assertEqual(after - before, 0.0)- def test_inline_endpoint_failure_emits_signal(self):+ @parameterized.expand(+ [+ ("runtime", RuntimeError("synthetic failure")),+ (+ "unknown_identifier",+ CHQueryErrorUnknownIdentifier("DB::Exception: Unknown identifier", code=47),+ ),+ (+ "unsupported_method",+ CHQueryErrorUnsupportedMethod("DB::Exception: Unsupported method", code=1),+ ),+ ]+ )+ def test_inline_endpoint_failure_emits_signal(self, _name: str, boom: Exception):"""When inline execution raises, we emit a Signal for self-driving diagnostics."""- endpoint = self._make_simple_hogql_endpoint("failure_emits_signal")- boom = RuntimeError("synthetic failure")+ endpoint = self._make_simple_hogql_endpoint(f"failure_emits_signal_{_name}")with (mock.patch("products.endpoints.backend.logic.execution.process_query_model", side_effect=boom),mock.patch("products.endpoints.backend.logic.execution._emit_endpoint_failure_signal") as mock_emit,+ mock.patch("products.endpoints.backend.logic.execution.capture_exception") as mock_capture,):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",@@ -2486,6 +2526,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)+ mock_capture.assert_called_once()mock_emit.assert_called_once()args, kwargs = mock_emit.call_argsself.assertEqual(args[0].id, self.team.id)@@ -2637,14 +2678,23 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):]self.assertEqual(len(breakdown_signal_calls), 1, "expected a breakdown-limit-exceeded signal")- def test_materialized_failure_falls_back_to_inline(self):+ @parameterized.expand(+ [+ ("runtime", RuntimeError("materialized table exploded")),+ (+ "unknown_table",+ CHQueryErrorUnknownTable("DB::Exception: Unknown table", code=60, code_name="unknown_table"),+ ),+ ]+ )+ def test_materialized_failure_falls_back_to_inline(self, _name: str, materialized_error: Exception):"""A materialized execution failure must fall back to inline execution, not 500."""endpoint = self._make_fresh_materialized_endpoint(- "mat-fallback", {"kind": "HogQLQuery", "query": "SELECT count() FROM events"}+ f"mat-fallback-{_name}", {"kind": "HogQLQuery", "query": "SELECT count() FROM events"})inline_response = Response({"results": [[1]], "columns": ["count()"]})- outcomes: list[Response | Exception] = [RuntimeError("materialized table exploded"), inline_response]+ outcomes: list[Response | Exception] = [materialized_error, inline_response]workloads_seen: list[str | None] = []def run_query(*args, **kwargs) -> Response:@@ -2654,9 +2704,13 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):raise outcomereturn outcome- with mock.patch.object(- EndpointExecutionService, "_execute_query_and_respond", side_effect=run_query- ) as mock_exec:+ with (+ mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", side_effect=run_query+ ) as mock_exec,+ mock.patch("products.endpoints.backend.logic.execution.capture_exception") as mock_capture,+ mock.patch("products.endpoints.backend.logic.execution._emit_endpoint_failure_signal") as mock_signal,+ ):response = self.client.post(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json")@@ -2667,6 +2721,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):self.assertNotEqual(workloads_seen[1], Workload.ENDPOINTS, "the inline fallback must not run on the endpoints cluster")+ mock_capture.assert_called_once()+ mock_signal.assert_called_once()+ self.assertTrue(mock_signal.call_args.kwargs["materialized"])def test_materialized_cache_ttl_derived_from_modeling_jobs(self):"""v2 DAG runs record success in DataModelingJob but never write saved_query.last_run_at.diff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.pyindex 580ee2f03bd7..24673271cb70 100644--- a/products/exports/backend/tasks/failure_handler.py+++ b/products/exports/backend/tasks/failure_handler.py@@ -6,39 +6,12 @@ from django.db import OperationalErrorfrom billiard.exceptions import SoftTimeLimitExceededfrom clickhouse_driver.errors import SocketTimeoutError-from rest_framework.exceptions import ValidationErrorfrom urllib3.exceptions import MaxRetryError, ProtocolError, ReadTimeoutError-from posthog.hogql.errors import (- QueryError,- ResolutionError,- SyntaxError as HogQLSyntaxError,-)-from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded-from posthog.errors import (- CH_TRANSIENT_ERRORS,- CHQueryErrorCannotParseUuid,- CHQueryErrorIllegalAggregation,- CHQueryErrorIllegalTypeOfArgument,- CHQueryErrorInvalidJoinOnExpression,- CHQueryErrorNoCommonType,- CHQueryErrorNotAnAggregate,- CHQueryErrorNumberOfArgumentsDoesntMatch,- CHQueryErrorTooManyBytes,- CHQueryErrorTypeMismatch,- CHQueryErrorUnknownFunction,- CHQueryErrorUnknownIdentifier,- CHQueryErrorUnknownTable,- CHQueryErrorUnsupportedMethod,-)-from posthog.exceptions import (- ClickHouseAtCapacity,- ClickHouseClusterMemoryLimitExceeded,- ClickHouseQueryMemoryLimitExceeded,- ClickHouseQuerySizeExceeded,- ClickHouseQueryTimeOut,-)+from posthog.errors import CH_TRANSIENT_ERRORS+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded+from posthog.hogql_queries.user_query_errors import USER_QUERY_ERRORS as COMMON_USER_QUERY_ERRORSfrom posthog.query_creator_access import CreatorLeftOrganizationErrorfrom posthog.storage.object_storage import ObjectStorageError@@ -212,26 +185,7 @@ EXCEPTIONS_TO_RETRY = ()USER_QUERY_ERRORS = (- QueryError,- HogQLSyntaxError,- ValidationError, # DRF validation of the user's query (e.g. a funnel with fewer than two steps)- ClickHouseQueryMemoryLimitExceeded, # Users should reduce the date range on their query (or materialise)- ClickHouseQueryTimeOut, # Users should switch to materialised queries if they run into this- CHQueryErrorIllegalTypeOfArgument,- CHQueryErrorNoCommonType,- CHQueryErrorNotAnAggregate,- CHQueryErrorUnknownFunction,- CHQueryErrorTypeMismatch,- CHQueryErrorIllegalAggregation,- CHQueryErrorNumberOfArgumentsDoesntMatch,- CHQueryErrorUnknownIdentifier,- CHQueryErrorTooManyBytes,- CHQueryErrorCannotParseUuid,- ClickHouseQuerySizeExceeded,- CHQueryErrorUnsupportedMethod,- ResolutionError,- CHQueryErrorInvalidJoinOnExpression,- CHQueryErrorUnknownTable,+ *COMMON_USER_QUERY_ERRORS,ExcelColumnLimitExceeded,InvalidExportContext,UserAccessControlError, # The export creator has no access to a resource the query needs@@ -284,10 +238,12 @@ def classify_failure_type(exception: Exception | str) -> str:if isinstance(exception, Exception):if isinstance(exception, TIMEOUT_ERRORS) or _is_playwright_timeout(exception):return FAILURE_TYPE_TIMEOUT_GENERATION- if isinstance(exception, USER_QUERY_ERRORS):- return FAILURE_TYPE_USER+ # Some transient errors subclass a user-query error (a file change mid-read is an+ # ExposedCHQueryError), so retryable types win, matching the name path below.if isinstance(exception, EXCEPTIONS_TO_RETRY):return FAILURE_TYPE_SYSTEM+ if isinstance(exception, USER_QUERY_ERRORS):+ return FAILURE_TYPE_USERreturn FAILURE_TYPE_UNKNOWN# Stored exception-class names (historical rows, backfill) only carry the name, so fall back todiff --git a/products/exports/backend/tasks/test/test_failure_handler.py b/products/exports/backend/tasks/test/test_failure_handler.pyindex 69a78ee052ce..e3df69065b76 100644--- a/products/exports/backend/tasks/test/test_failure_handler.py+++ b/products/exports/backend/tasks/test/test_failure_handler.py@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError as DjangoValidationErrorfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError+from posthog.errors import CHQueryErrorS3FileChangedDuringReadfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceededfrom products.exports.backend.tasks.failure_handler import (@@ -116,6 +117,16 @@ class TestClassifyFailureType(TestCase):# Stored rows only carry the class name, so the string path stays purely name-based.assert classify_failure_type("ValidationError") == FAILURE_TYPE_USER+ @parameterized.expand(+ [+ (CHQueryErrorS3FileChangedDuringRead("A warehouse file changed during the read.", code=499),),+ (ClickHouseClusterMemoryLimitExceeded(),),+ ]+ )+ def test_transient_errors_that_subclass_user_errors_classify_as_system(self, exception: Exception) -> None:+ assert classify_failure_type(exception) == FAILURE_TYPE_SYSTEM+ assert classify_failure_type(type(exception).__name__) == FAILURE_TYPE_SYSTEM+class TestExportSloFailureDetails(TestCase):@parameterized.expand(