: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(mssql): retry transient DBPROCESS-dead drops during schema discovery (#65050)
Tom Owers5be6cbea43dd
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.pyindex 9598ddf680f7..3e6ff2d0b03e 100644--- a/posthog/temporal/data_imports/sources/mssql/mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py@@ -9,10 +9,11 @@ just holds an instance and validates credentials.from __future__ import annotations+import timeimport collections-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom contextlib import contextmanager-from typing import Any+from typing import Any, TypeVarimport pyarrow as paimport pymssql@@ -65,6 +66,50 @@ _IDENTIFIER_QUOTER = BracketIdentifierQuoter()# fixed database roles (db_owner, db_datareader, …), which also surface as schemas.SYSTEM_MSSQL_SCHEMAS = ("sys", "guest", "INFORMATION_SCHEMA")+_T = TypeVar("_T")++# DB-Lib error 20047 — "DBPROCESS is dead or not enabled". The TDS connection died mid-stream (an+# idle cull, a failover, a brief network blip), leaving pymssql's dbprocess dead so the in-flight+# fetch raises. A fresh connection recovers, so this is transient rather than a config error.+_TRANSIENT_CONNECTION_ERROR = "DBPROCESS is dead or not enabled"+_MAX_DISCOVERY_CONNECTION_ATTEMPTS = 5+++def _is_transient_connection_error(error: BaseException) -> bool:+ """True for a mid-stream TDS connection death that a fresh connection recovers from."""+ message = " ".join(str(arg) for arg in error.args) if error.args else str(error)+ return _TRANSIENT_CONNECTION_ERROR in message+++def retry_on_transient_connection_error(+ operation: Callable[[], _T],+ *,+ max_attempts: int = _MAX_DISCOVERY_CONNECTION_ATTEMPTS,+) -> _T:+ """Run `operation`, retrying a transient MSSQL connection death with bounded backoff.++ Mirrors the in-process discovery retry the Postgres and MySQL sources use: a momentary+ connection death recovers on a fresh connect-and-discover cycle, so retry it here instead of+ failing schema discovery on the first blip and surfacing it as captured error-tracking noise.+ Permanent errors re-raise immediately — `_is_transient_connection_error` only matches the+ transient mid-stream drop.+ """+ attempt = 0+ while True:+ try:+ return operation()+ except pymssql.Error as e:+ attempt += 1+ if attempt >= max_attempts or not _is_transient_connection_error(e):+ raise+ structlog.get_logger().warning(+ "Transient MSSQL connection death during schema discovery; retrying",+ attempt=attempt,+ max_attempts=max_attempts,+ exc_info=e,+ )+ time.sleep(min(2 * attempt, 30))+def _non_system_schema_clause(column: str) -> tuple[str, dict[str, str]]:"""Predicate excluding MSSQL system schemas + the fixed `db_*` database roles.diff --git a/posthog/temporal/data_imports/sources/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.pyindex a52eacb8ddbd..0718c7329a69 100644--- a/posthog/temporal/data_imports/sources/mssql/source.py+++ b/posthog/temporal/data_imports/sources/mssql/source.py@@ -15,9 +15,10 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.data_imports.sources.common.base import FieldTypefrom posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixinfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig-from posthog.temporal.data_imports.sources.mssql.mssql import MSSQLImplementation+from posthog.temporal.data_imports.sources.mssql.mssql import MSSQLImplementation, retry_on_transient_connection_errorfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -98,6 +99,26 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase"Source column type changed": "A column's type changed in your source database (for example an integer column was widened to bigint) and no longer fits the type we stored. We can't widen an existing column in place — please reset and fully re-sync this table to adopt the new type.",}+ def get_schemas(+ self,+ config: MSSQLSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Schema discovery opens a fresh connection on its own periodic cadence. A transient TDS+ # connection death mid-fetch (DB-Lib 20047, "DBPROCESS is dead or not enabled") recovers on+ # a fresh connection, so retry the whole connect-and-discover cycle in-process rather than+ # failing the discovery activity — and surfacing captured error-tracking noise — on the+ # first blip.+ def discover() -> list[SourceSchema]:+ return super(MSSQLSource, self).get_schemas(+ config, team_id, with_counts=with_counts, names=names, force_refresh=force_refresh+ )++ return retry_on_transient_connection_error(discover)+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.pyindex 844ea2975595..6db896d2e8ce 100644--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py@@ -1,6 +1,8 @@import pytestfrom unittest.mock import MagicMock+import pymssql+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom posthog.temporal.data_imports.sources.common.sql import Table, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilter@@ -9,7 +11,9 @@ from posthog.temporal.data_imports.sources.mssql.mssql import (MSSQLColumn,MSSQLImplementation,_build_query,+ _is_transient_connection_error,filter_mssql_incremental_fields,+ retry_on_transient_connection_error,)from posthog.temporal.data_imports.sources.mssql.source import MSSQLSource@@ -605,3 +609,99 @@ class TestMSSQLSourceNonRetryableErrors:def test_conversion_failed_is_non_retryable(self, error_msg):non_retryable = MSSQLSource().get_non_retryable_errors()assert any(pattern in error_msg for pattern in non_retryable.keys()), error_msg+++class TestIsTransientConnectionError:+ @pytest.mark.parametrize(+ "error",+ [+ # Real pymssql shape: DB-Lib error 20047 carried as (code, bytes) args.+ pymssql.OperationalError(+ 20047, b"DB-Lib error message 20047, severity 9:\nDBPROCESS is dead or not enabled\n"+ ),+ # The SQL-Server-message rendering of the same drop.+ pymssql.OperationalError(+ "SQL Server message 20047, severity 9, state 0, procedure b'\\xc0\\xaa\\x12\\x08\\xff\\xff', "+ "line 0:\nb'DB-Lib error message 20047, severity 9:\nDBPROCESS is dead or not enabled\n'"+ ),+ ],+ )+ def test_matches_dbprocess_dead(self, error):+ assert _is_transient_connection_error(error)++ @pytest.mark.parametrize(+ "error",+ [+ # Persistent failures must stay non-retryable, not be absorbed as transient.+ pymssql.OperationalError("Login failed for user 'reporting'."),+ pymssql.OperationalError("Invalid object name 'dbo.orders'."),+ pymssql.OperationalError("The SELECT permission was denied on the object 'X'."),+ pymssql.OperationalError(+ "DB-Lib error message 20009, severity 9:\nUnable to connect: Adaptive Server is "+ "unavailable or does not exist (db.example.com)"+ ),+ pymssql.OperationalError(),+ ],+ )+ def test_does_not_match_other_errors(self, error):+ assert not _is_transient_connection_error(error)+++class TestRetryOnTransientConnectionError:+ def _dbprocess_dead(self) -> pymssql.OperationalError:+ return pymssql.OperationalError(+ 20047, b"DB-Lib error message 20047, severity 9:\nDBPROCESS is dead or not enabled\n"+ )++ def test_retries_then_succeeds(self, mocker):+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.time.sleep")+ operation = MagicMock(side_effect=[self._dbprocess_dead(), "ok"])++ assert retry_on_transient_connection_error(operation) == "ok"+ assert operation.call_count == 2+ sleep.assert_called_once()++ def test_does_not_retry_non_transient(self, mocker):+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.time.sleep")+ operation = MagicMock(side_effect=pymssql.OperationalError("Login failed for user 'reporting'."))++ with pytest.raises(pymssql.OperationalError):+ retry_on_transient_connection_error(operation)+ assert operation.call_count == 1+ sleep.assert_not_called()++ def test_gives_up_after_max_attempts(self, mocker):+ mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.time.sleep")+ operation = MagicMock(side_effect=self._dbprocess_dead())++ with pytest.raises(pymssql.OperationalError):+ retry_on_transient_connection_error(operation, max_attempts=3)+ assert operation.call_count == 3+++class TestGetSchemasRetriesTransientDrop:+ def test_get_schemas_retries_then_recovers(self, mocker):+ # A transient DBPROCESS death mid-discovery must retry the whole connect-and-discover cycle+ # in-process instead of failing the activity on the first blip.+ mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.time.sleep")+ mock_conn = MagicMock()+ mock_conn.__enter__.return_value = mock_conn+ mocker.patch(+ "posthog.temporal.data_imports.sources.mssql.mssql.pymssql.connect",+ return_value=mock_conn,+ )+ get_columns = mocker.patch.object(+ MSSQLImplementation,+ "get_columns",+ side_effect=[+ pymssql.OperationalError(+ 20047, b"DB-Lib error message 20047, severity 9:\nDBPROCESS is dead or not enabled\n"+ ),+ {},+ ],+ )++ schemas = MSSQLSource().get_schemas(_make_config(), team_id=1)++ assert schemas == []+ assert get_columns.call_count == 2