Skip to content

: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.

fix(mssql): rerun read query when chosen as deadlock victim (#65498)

Tom Owers5d3a297fc0bc
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.py
index 3e6ff2d0b03e..207e07167013 100644
--- a/posthog/temporal/data_imports/sources/mssql/mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py
@@ -74,6 +74,13 @@ _T = TypeVar("_T")
_TRANSIENT_CONNECTION_ERROR = "DBPROCESS is dead or not enabled"
_MAX_DISCOVERY_CONNECTION_ATTEMPTS = 5
+# SQL Server error 1205 — this session was picked as the deadlock victim and its transaction was
+# rolled back to break a lock cycle with a concurrent process. SQL Server's own guidance is to
+# rerun the transaction: lock contention is momentary, so re-running the identical query usually
+# succeeds. Transient lock contention, not a config or data problem.
+_DEADLOCK_VICTIM_ERROR = "was deadlocked on lock resources"
+_MAX_DEADLOCK_ATTEMPTS = 5
+
def _is_transient_connection_error(error: BaseException) -> bool:
"""True for a mid-stream TDS connection death that a fresh connection recovers from."""
@@ -81,6 +88,12 @@ def _is_transient_connection_error(error: BaseException) -> bool:
return _TRANSIENT_CONNECTION_ERROR in message
+def _is_deadlock_victim_error(error: BaseException) -> bool:
+ """True for a SQL Server 1205 deadlock-victim error that a rerun recovers from."""
+ message = " ".join(str(arg) for arg in error.args) if error.args else str(error)
+ return _DEADLOCK_VICTIM_ERROR in message
+
+
def retry_on_transient_connection_error(
operation: Callable[[], _T],
*,
@@ -111,6 +124,36 @@ def retry_on_transient_connection_error(
time.sleep(min(2 * attempt, 30))
+def retry_on_deadlock(
+ operation: Callable[[], _T],
+ *,
+ max_attempts: int = _MAX_DEADLOCK_ATTEMPTS,
+ logger: FilteringBoundLogger | None = None,
+) -> _T:
+ """Run `operation`, rerunning it with bounded backoff when SQL Server picks us as the deadlock victim.
+
+ A 1205 rolls back our transaction to break the lock cycle, so rerunning the identical query is
+ safe and usually succeeds once the contending process releases its locks. Used around the read
+ query before any rows are streamed — retrying mid-stream would re-yield already-emitted rows.
+ Anything other than a deadlock victim re-raises immediately.
+ """
+ attempt = 0
+ while True:
+ try:
+ return operation()
+ except pymssql.Error as e:
+ attempt += 1
+ if attempt >= max_attempts or not _is_deadlock_victim_error(e):
+ raise
+ (logger or structlog.get_logger()).warning(
+ "MSSQL query chosen as deadlock victim; rerunning",
+ 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.
@@ -819,7 +862,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con
logger.debug(f"MS SQL query: {query} with args: {args}")
- cursor.execute(query, args)
+ retry_on_deadlock(lambda: cursor.execute(query, args), logger=logger)
column_names = [column[0] for column in cursor.description or []]
diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
index 6db896d2e8ce..c022d4087eab 100644
--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py
@@ -11,8 +11,10 @@ from posthog.temporal.data_imports.sources.mssql.mssql import (
MSSQLColumn,
MSSQLImplementation,
_build_query,
+ _is_deadlock_victim_error,
_is_transient_connection_error,
filter_mssql_incremental_fields,
+ retry_on_deadlock,
retry_on_transient_connection_error,
)
from posthog.temporal.data_imports.sources.mssql.source import MSSQLSource
@@ -705,3 +707,75 @@ class TestGetSchemasRetriesTransientDrop:
assert schemas == []
assert get_columns.call_count == 2
+
+
+class TestIsDeadlockVictimError:
+ @pytest.mark.parametrize(
+ "error",
+ [
+ # Real pymssql shape: SQL Server error 1205 carried as (code, bytes) args.
+ pymssql.OperationalError(
+ 1205,
+ b"Transaction (Process ID 116) was deadlocked on lock resources with another process and has "
+ b"been chosen as the deadlock victim. Rerun the transaction.DB-Lib error message 20018, "
+ b"severity 13:\nGeneral SQL Server error: Check messages from the SQL Server\n",
+ ),
+ # The SQL-Server-message rendering of the same deadlock.
+ pymssql.OperationalError(
+ "SQL Server message 1205, severity 13, state 52, procedure b'`\\x17\\x15\\xcc\\xfe\\xff', "
+ "line 1:\nb'Transaction (Process ID 116) was deadlocked on lock resources with another process "
+ "and has been chosen as the deadlock victim. Rerun the transaction."
+ ),
+ ],
+ )
+ def test_matches_deadlock_victim(self, error):
+ assert _is_deadlock_victim_error(error)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ # A connection death is transient too, but recovers via a fresh connect — not a rerun.
+ pymssql.OperationalError(
+ 20047, b"DB-Lib error message 20047, severity 9:\nDBPROCESS is dead or not enabled\n"
+ ),
+ pymssql.OperationalError("Login failed for user 'reporting'."),
+ pymssql.OperationalError("Invalid object name 'dbo.orders'."),
+ pymssql.OperationalError(),
+ ],
+ )
+ def test_does_not_match_other_errors(self, error):
+ assert not _is_deadlock_victim_error(error)
+
+
+class TestRetryOnDeadlock:
+ def _deadlock_victim(self) -> pymssql.OperationalError:
+ return pymssql.OperationalError(
+ 1205,
+ b"Transaction (Process ID 116) was deadlocked on lock resources with another process and has been "
+ b"chosen as the deadlock victim. Rerun the transaction.",
+ )
+
+ def test_retries_then_succeeds(self, mocker):
+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.time.sleep")
+ operation = MagicMock(side_effect=[self._deadlock_victim(), "ok"])
+
+ assert retry_on_deadlock(operation) == "ok"
+ assert operation.call_count == 2
+ sleep.assert_called_once()
+
+ def test_does_not_retry_non_deadlock(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_deadlock(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._deadlock_victim())
+
+ with pytest.raises(pymssql.OperationalError):
+ retry_on_deadlock(operation, max_attempts=3)
+ assert operation.call_count == 3