: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): stop dead-connection cascade in failure signal (#94594)
Jovan Sakovicd05a7f22d0fb
diff --git a/products/endpoints/backend/logic/execution.py b/products/endpoints/backend/logic/execution.pyindex 60fa78ab0a01..4365e25d75f2 100644--- a/products/endpoints/backend/logic/execution.py+++ b/products/endpoints/backend/logic/execution.py@@ -15,6 +15,7 @@ from datetime import datetime, timedeltafrom typing import Literal, Union, castfrom django.conf import settings+from django.db import InterfaceError, OperationalErrorfrom django.utils import timezoneimport structlog@@ -130,6 +131,50 @@ def _is_query_guardrail_error(error: BaseException) -> bool:return isinstance(error, _QUERY_GUARDRAIL_ERRORS)+# Connection loss outside SQLSTATE class 08 (connection_exception).+_CONNECTION_LOSS_SQLSTATES = frozenset(+ {+ "57P01", # admin_shutdown+ "57P02", # crash_shutdown+ "57P03", # cannot_connect_now+ }+)+++def _pg_sqlstate(error: BaseException) -> str | None:+ """The Postgres SQLSTATE behind a Django database error, when the server reported one.++ psycopg3 exposes it as ``sqlstate`` and psycopg2 as ``pgcode``, and Django re-raises its+ own wrapper ``from`` the driver error, so the code sits on the cause.+ """+ for candidate in (error, error.__cause__):+ for attr in ("sqlstate", "pgcode"):+ code = getattr(candidate, attr, None)+ if isinstance(code, str):+ return code+ return None+++def _is_db_connection_error(error: BaseException) -> bool:+ """Whether an error reflects a dropped/dead Postgres connection rather than a code fault.++ Transient connection loss is an infra condition, not a bug — re-reporting it to error+ tracking from the failure-handling path just adds noise to the real root cause.+ """+ if isinstance(error, InterfaceError):+ return True+ if not isinstance(error, OperationalError):+ return False+ sqlstate = _pg_sqlstate(error)+ # A dropped connection is detected client-side, so libpq reports no SQLSTATE. When the+ # server did answer, the connection was alive: only class 08 and the shutdown codes mean+ # it went away. A statement timeout (57014) or a deadlock (40P01) is a real fault, and+ # must keep reaching error tracking.+ if sqlstate is None:+ return True+ return sqlstate.startswith("08") or sqlstate in _CONNECTION_LOSS_SQLSTATES++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():@@ -214,18 +259,25 @@ def _emit_endpoint_failure_signal(},)except Exception as signal_exc:+ # endpoint.name / team_id are already-loaded scalars, so logging here can't itself+ # touch the (possibly dead) connection. Pull team_id off the endpoint FK column to+ # avoid lazily reloading endpoint.team.logger.exception("Failed to emit endpoint failure signal",endpoint_name=endpoint.name,- team_id=team.id,+ team_id=endpoint.team_id,signal_error_class=type(signal_exc).__name__,signal_error=str(signal_exc),)+ # A dropped connection is the infra root cause, not a new fault — re-reporting it here+ # just buries the real error under cascade noise. Log it and move on.+ if _is_db_connection_error(signal_exc):+ returncapture_exception(signal_exc,{"product": Product.ENDPOINTS,- "team_id": team.id,+ "team_id": endpoint.team_id,"endpoint_name": endpoint.name,"signal_emission": True,},diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.pyindex 8a6bc1bec287..f5cdca9b04aa 100644--- a/products/endpoints/backend/tests/test_endpoint_execution.py+++ b/products/endpoints/backend/tests/test_endpoint_execution.py@@ -3,8 +3,10 @@ from datetime import timedeltafrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest import mock+from django.db import InterfaceError, OperationalErrorfrom django.utils import timezone+import psycopgfrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.response import Response@@ -16,12 +18,21 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.errors import CHQueryErrorNoCommonTypefrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery-from products.endpoints.backend.logic.execution import EndpointExecutionService+from products.endpoints.backend.logic.execution import EndpointExecutionService, _emit_endpoint_failure_signal+from products.endpoints.backend.models import Endpointfrom products.endpoints.backend.tests.conftest import create_endpoint_with_versionfrom products.product_analytics.backend.facade.models import InsightVariablefrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+def _django_pg_error(sqlstate: str) -> OperationalError:+ # Django re-raises its own wrapper `from` the psycopg error, so the SQLSTATE the server+ # reported sits on the cause rather than on the Django exception.+ error = OperationalError("database error")+ error.__cause__ = psycopg.errors.lookup(sqlstate)("database error")+ return error++class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):"""Tests for the endpoint execution API.@@ -2267,8 +2278,6 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):def test_emit_failure_signal_swallows_errors(self):"""Signal emission must never mask the original exception."""- from products.endpoints.backend.logic.execution import _emit_endpoint_failure_signal-endpoint = self._make_simple_hogql_endpoint("failure_signal_swallow")with mock.patch(@@ -2277,6 +2286,48 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):):_emit_endpoint_failure_signal(self.team, endpoint, RuntimeError("original"), materialized=False, version=1)+ def test_endpoint_path_does_not_lazily_load_team(self):+ # endpoint_path must build from the team_id FK column, never a lazy team load. A lazy+ # reload on a dead connection is what turned a single transient Postgres failure into+ # a KeyError/OperationalError cascade during error handling.+ endpoint = self._make_simple_hogql_endpoint("path_no_team_load")+ fresh = Endpoint.objects.get(pk=endpoint.pk) # team relation not yet cached++ with self.assertNumQueries(0):+ path = fresh.endpoint_path++ self.assertEqual(path, f"/api/projects/{self.team.id}/endpoints/{fresh.name}/run")++ @parameterized.expand(+ [+ # A dropped connection is the infra root cause, so re-reporting it would bury the+ # real error under cascade noise.+ ("connection_dropped", OperationalError("server closed the connection unexpectedly"), False),+ ("connection_failure", _django_pg_error("08006"), False),+ ("admin_shutdown", _django_pg_error("57P01"), False),+ ("connection_closed", InterfaceError("connection already closed"), False),+ # The server answered, so the connection was alive — these are real faults and+ # have to stay visible in error tracking.+ ("statement_timeout", _django_pg_error("57014"), True),+ ("deadlock", _django_pg_error("40P01"), True),+ ("not_a_database_error", RuntimeError("signal layer exploded"), True),+ ]+ )+ def test_emit_failure_signal_capture_by_error_class(self, name, signal_error, expect_captured):+ endpoint = self._make_simple_hogql_endpoint(f"failure_signal_capture_{name}")++ with (+ mock.patch(+ "products.signals.backend.facade.api.emit_signal",+ side_effect=signal_error,+ ),+ mock.patch("products.endpoints.backend.logic.execution.capture_exception") as mock_capture,+ ):+ # Must not raise — the original error is never masked by the failed emission.+ _emit_endpoint_failure_signal(self.team, endpoint, RuntimeError("original"), materialized=False, version=1)++ self.assertEqual(mock_capture.called, expect_captured)+def _make_fresh_materialized_endpoint(self, name: str, query: dict):"""Endpoint whose current version has a fresh, Completed materialization."""saved_query = DataWarehouseSavedQuery.objects.create(