: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(temporal): classify a wrapped transient db error by its cause chain (#103834)
posthog[bot]5ae3acb0d7f0
diff --git a/posthog/temporal/common/db_errors.py b/posthog/temporal/common/db_errors.pyindex c2980da6e9f8..c92efb60da5b 100644--- a/posthog/temporal/common/db_errors.py+++ b/posthog/temporal/common/db_errors.py@@ -69,15 +69,28 @@ def _is_too_many_open_files_error(error: BaseException) -> bool:return isinstance(error, OSError) and error.errno in (errno.EMFILE, errno.ENFILE)+# Count the raised error toward the limit so cyclic or very long chains stay bounded.+_MAX_CAUSE_CHAIN_DEPTH = 10++def is_transient_db_error(error: BaseException) -> bool:- if _is_too_many_open_files_error(error):- return True- if not isinstance(error, OperationalError | InterfaceError | InternalError):- return False- sqlstate = getattr(error.__cause__, "sqlstate", None)- if isinstance(sqlstate, str) and (- sqlstate.startswith(_TRANSIENT_SQLSTATE_PREFIXES) or sqlstate in _TRANSIENT_SQLSTATES- ):- return True- message = str(error)- return any(marker in message for marker in _TRANSIENT_DB_ERROR_MARKERS)+ """Check this error and its explicit causes for a transient database failure.++ Ignore `__context__`: an unrelated failure inside an `except` block must stay reportable.+ """+ for _ in range(_MAX_CAUSE_CHAIN_DEPTH):+ if _is_too_many_open_files_error(error):+ return True+ if isinstance(error, OperationalError | InterfaceError | InternalError):+ sqlstate = getattr(error.__cause__, "sqlstate", None)+ if isinstance(sqlstate, str) and (+ sqlstate.startswith(_TRANSIENT_SQLSTATE_PREFIXES) or sqlstate in _TRANSIENT_SQLSTATES+ ):+ return True+ message = str(error)+ if any(marker in message for marker in _TRANSIENT_DB_ERROR_MARKERS):+ return True+ if error.__cause__ is None:+ break+ error = error.__cause__+ return Falsediff --git a/posthog/temporal/common/test_db_errors.py b/posthog/temporal/common/test_db_errors.pyindex 29b66a679707..a773db36bb13 100644--- a/posthog/temporal/common/test_db_errors.py+++ b/posthog/temporal/common/test_db_errors.py@@ -4,6 +4,8 @@ import pytestfrom django.db import InterfaceError, InternalError, OperationalError+from temporalio.exceptions import ApplicationError+from posthog.temporal.common.db_errors import is_transient_db_error@@ -13,6 +15,11 @@ class _WithSqlstate(Exception):self.sqlstate = sqlstate+def _raised_from(error: BaseException, cause: BaseException) -> BaseException:+ error.__cause__ = cause+ return error++@pytest.mark.parametrize("error,expected",[@@ -46,12 +53,51 @@ class _WithSqlstate(Exception):# An unrelated errno (e.g. a real permissions problem) must not be swept up just because# it shares the exception type.(OSError(errno.EACCES, "Permission denied"), False),+ # An activity that re-raises one typed error keeps the drop in __cause__ only.+ (+ _raised_from(+ ApplicationError("Failed to emit $ai_evaluation"),+ OperationalError("server closed the connection unexpectedly"),+ ),+ True,+ ),+ # Two links deep, and the condition is a SQLSTATE rather than a message.+ (+ _raised_from(+ ApplicationError("Failed to emit $ai_evaluation"),+ _raised_from(OperationalError("some driver-specific message"), _WithSqlstate("57P03")),+ ),+ True,+ ),+ # The wrapper must stay reportable when what it hides is a real defect.+ (+ _raised_from(ApplicationError("Failed to emit $ai_evaluation"), KeyError("team_id")),+ False,+ ),],)def test_is_transient_db_error_by_message(error: BaseException, expected: bool) -> None:assert is_transient_db_error(error) is expected[email protected]("suppress_context", [False, True])+def test_is_transient_db_error_ignores_context(suppress_context: bool) -> None:+ error = KeyError("team_id")+ error.__context__ = OperationalError("server closed the connection unexpectedly")+ error.__suppress_context__ = suppress_context++ assert not is_transient_db_error(error)++[email protected]("cycle_length", [1, 2])+def test_is_transient_db_error_handles_cyclic_causes(cycle_length: int) -> None:+ errors = [ValueError("not a database error") for _ in range(cycle_length)]+ for index, error in enumerate(errors):+ error.__cause__ = errors[(index + 1) % cycle_length]++ assert not is_transient_db_error(errors[0])++@pytest.mark.parametrize("error_cls,sqlstate,expected",[