: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(endpoints): classify ClickHouse query-cost failures separately from system errors (#64920)
Jovan Sakovicf676a3a02c28
diff --git a/products/endpoints/backend/exceptions.py b/products/endpoints/backend/exceptions.pynew file mode 100644index 000000000000..de893992b23a--- /dev/null+++ b/products/endpoints/backend/exceptions.py@@ -0,0 +1,21 @@+from rest_framework import status+from rest_framework.exceptions import APIException+++class EndpointQueryTooExpensive(APIException):+ """A customer query hit a ClickHouse cost guardrail — deterministic, so 400 (not a retry-inviting 5xx)."""++ status_code = status.HTTP_400_BAD_REQUEST+ default_code = "query_performance_limit"+ default_detail = "This query is too expensive to run inline. Narrow its scope or materialize the endpoint."+++class EndpointAtCapacity(APIException):+ """Shared ClickHouse pool momentarily at capacity — transient; materializing gives isolated compute."""++ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_code = "query_capacity"+ default_detail = (+ "Queries are momentarily at capacity — please retry shortly. For consistently heavy "+ "endpoints, materialize to run on dedicated endpoint compute that isn't affected by shared query load."+ )diff --git a/products/endpoints/backend/metrics.py b/products/endpoints/backend/metrics.pyindex 4e0879ead9e9..d049a7e5fa4c 100644--- a/products/endpoints/backend/metrics.py+++ b/products/endpoints/backend/metrics.py@@ -10,7 +10,10 @@ def query_kind_label(query: dict | None) -> str:ENDPOINT_EXECUTION_TOTAL = Counter("posthog_endpoint_execution_total","Endpoint executions that reached query execution (excludes concurrency rejections; see posthog_endpoint_concurrency_rejected_total). "- "status is success, user_error (invalid query/variables in the user's endpoint, returned as 4xx), or error (unexpected system failure)",+ "status is success; user_error (invalid query/variables in the user's endpoint, returned as 4xx); "+ "query_performance (the query hit a ClickHouse cost guardrail — timeout/memory/size/estimated-too-slow — returned as 400); "+ "capacity (shared ClickHouse pool momentarily saturated, returned as 503); "+ 'or error (unexpected system failure). Only error is a system fault — alert on status="error"',labelnames=["execution_type", "query_kind", "status"],)diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.pyindex aba90e04189d..32adc16eb383 100644--- a/products/endpoints/backend/openapi.py+++ b/products/endpoints/backend/openapi.py@@ -82,9 +82,25 @@ def generate_openapi_spec(}},},- "400": {"description": "Invalid request"},+ "400": {+ "description": (+ "Invalid request, or the query is too expensive to run inline. "+ "Query-cost failures carry a stable `code`: `query_timeout`, "+ "`query_memory_limit`, `query_too_large`, or `query_estimated_too_slow` — "+ "narrow the query's scope (e.g. a smaller date range) or materialize the endpoint."+ ),+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}},+ },"401": {"description": "Authentication required"},"404": {"description": "Endpoint not found"},+ "503": {+ "description": (+ "The shared ClickHouse query pool is momentarily at capacity (`code`: "+ "`query_capacity`). Retry shortly; materialize the endpoint to run on dedicated "+ "compute that isn't affected by shared query load."+ ),+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}},+ },},}}@@ -108,6 +124,27 @@ def _build_component_schemas(endpoint: Endpoint, version: EndpointVersion, team_is_materialized = bool(version and version.is_materialized and version.saved_query)schemas: dict = {+ "Error": {+ "type": "object",+ "description": "Error response body.",+ "properties": {+ "type": {+ "type": "string",+ "description": "Coarse error category (e.g. 'validation_error', 'server_error'). Branch on `code`, not `type`.",+ },+ "code": {+ "type": "string",+ "description": "Stable machine-readable error code to branch on, e.g. 'query_timeout' or 'query_capacity'.",+ },+ "detail": {"type": "string", "description": "Human-readable explanation and remediation."},+ "attr": {+ "type": "string",+ "nullable": True,+ "description": "The request field that caused the error, when applicable.",+ },+ },+ "required": ["type", "code", "detail"],+ },"EndpointRunRequest": {"type": "object","properties": {diff --git a/products/endpoints/backend/services/execution.py b/products/endpoints/backend/services/execution.pyindex 9de6a61d6971..90dd02d4741c 100644--- a/products/endpoints/backend/services/execution.py+++ b/products/endpoints/backend/services/execution.py@@ -54,6 +54,13 @@ from posthog.clickhouse.query_tagging import (from posthog.ducklake.common import get_duckgres_server_for_organizationfrom posthog.errors import ExposedCHQueryErrorfrom posthog.event_usage import get_request_analytics_properties, report_user_action+from posthog.exceptions import (+ ClickHouseAtCapacity,+ ClickHouseEstimatedQueryExecutionTimeTooLong,+ ClickHouseQueryMemoryLimitExceeded,+ ClickHouseQuerySizeExceeded,+ ClickHouseQueryTimeOut,+)from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.permissions import is_authenticated_via_project_secret_api_key@@ -61,6 +68,7 @@ from posthog.synthetic_user import SyntheticUserfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_warehouse.backend.data_load.saved_query_service import trigger_saved_query_schedule+from products.endpoints.backend.exceptions import EndpointAtCapacity, EndpointQueryTooExpensivefrom products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchErrorfrom products.endpoints.backend.logs import build_execution_message, log_endpoint_executionfrom products.endpoints.backend.metrics import (@@ -86,6 +94,47 @@ LAST_EXECUTED_THROTTLE = timedelta(minutes=30)ExecutionType = Literal["materialized", "materialized_fallback", "inline", "ducklake", "ducklake_fallback"]+# Deterministic, customer-caused ClickHouse cost guardrails → stable client `code` + remediation.+# Kept out of status="error" so they don't page on-call; surfaced as an actionable 400.+_QUERY_PERFORMANCE_ERRORS: dict[type[Exception], tuple[str, str]] = {+ ClickHouseQueryTimeOut: (+ "query_timeout",+ "This query exceeded the execution time limit. Narrow its scope (e.g. a smaller date range) "+ "or materialize the endpoint for dedicated compute.",+ ),+ ClickHouseQueryMemoryLimitExceeded: (+ "query_memory_limit",+ "This query exceeded the memory limit. Narrow its scope (e.g. a smaller date range) "+ "or materialize the endpoint.",+ ),+ ClickHouseQuerySizeExceeded: (+ "query_too_large",+ # No materialize hint: it re-parses the same SQL, so it can't shrink an oversized query.+ "The query text is too large to execute. Simplify the query.",+ ),+ ClickHouseEstimatedQueryExecutionTimeTooLong: (+ "query_estimated_too_slow",+ "This query is estimated to run too long. Reduce its scope by narrowing the time range "+ "or materialize the endpoint.",+ ),+}++# Cost guardrails + transient capacity: customer problems, not faults. Skipped from capture and+# re-raised past the materialized/ducklake inline fallback.+_QUERY_GUARDRAIL_ERRORS: tuple[type[Exception], ...] = (*_QUERY_PERFORMANCE_ERRORS, ClickHouseAtCapacity)+++def _is_query_guardrail_error(error: BaseException) -> bool:+ return isinstance(error, _QUERY_GUARDRAIL_ERRORS)+++def _query_performance_code_and_detail(error: BaseException) -> tuple[str, str]:+ # isinstance, not dict[type(e)], so a future subclass can't KeyError into a 500.+ for exc_type, code_and_detail in _QUERY_PERFORMANCE_ERRORS.items():+ if isinstance(error, exc_type):+ return code_and_detail+ raise error+def _emit_endpoint_failure_signal(team,@@ -499,6 +548,17 @@ class EndpointExecutionService(PydanticModelMixin):except ConcurrencyLimitExceeded:ENDPOINT_CONCURRENCY_REJECTED_TOTAL.labels(team_id=str(self.team.pk)).inc()raise Throttled(detail="Too many concurrent requests. Please try again later.")+ except tuple(_QUERY_PERFORMANCE_ERRORS) as e:+ execution_status = "query_performance"+ error_label = type(e).__name__+ code, detail = _query_performance_code_and_detail(e)+ logger.warning("Endpoint query hit a performance limit", endpoint_name=endpoint.name, reason=error_label)+ raise EndpointQueryTooExpensive(detail, code=code)+ except ClickHouseAtCapacity:+ execution_status = "capacity"+ error_label = "ClickHouseAtCapacity"+ logger.warning("Endpoint query hit shared ClickHouse capacity", endpoint_name=endpoint.name)+ raise EndpointAtCapacity()except Exception as e:execution_status = "error"error_label = type(e).__name__@@ -512,7 +572,7 @@ class EndpointExecutionService(PydanticModelMixin):ENDPOINT_EXECUTION_TOTAL.labels(execution_type=execution_type, query_kind=query_kind_metric, status=execution_status).inc()- if execution_status in ("error", "user_error"):+ if execution_status in ("error", "user_error", "query_performance", "capacity"):log_endpoint_execution(team_id=self.team.pk,endpoint_id=str(endpoint.id),@@ -709,6 +769,9 @@ class EndpointExecutionService(PydanticModelMixin):return resultexcept Exception as e:+ # Guardrail errors are customer-caused, not faults: skip capture and let execute() classify them.+ if _is_query_guardrail_error(e):+ raiselogger.exception("Materialized endpoint execution failed",endpoint_name=endpoint.name,@@ -814,6 +877,9 @@ class EndpointExecutionService(PydanticModelMixin):except Exception as e:self.handle_column_ch_error(e)+ # Guardrail errors are customer-caused, not faults: skip capture and let execute() classify them.+ if _is_query_guardrail_error(e):+ raiselogger.exception("Inline endpoint execution failed",endpoint_name=endpoint.name,