: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(data-imports): retry MSSQL row-count probe on deadlock instead of capturing (#72387)
Tom Owers52c05328222b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.pyindex 456bfab7c88c..ddce3ab4d88a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py@@ -824,6 +824,46 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Concapture_exception(e)return None+ def get_rows_to_sync(+ self,+ cursor: pymssql.Cursor,+ inner_query: str,+ inner_query_args: Any,+ logger: FilteringBoundLogger,+ ) -> int:+ """Count the rows the given `inner_query` will produce. Returns 0 on error.++ Runs before any rows are streamed, so a 1205 deadlock victim here is exactly as+ safe to rerun as the main read query — wrap it in the same `retry_on_deadlock`+ rather than falling straight through to the base class's catch-all, which would+ give up on the first lock conflict instead of recovering an accurate count.+ """+ try:+ query = f"SELECT COUNT(*) FROM ({inner_query}) as t"++ def _run() -> Any:+ cursor.execute(query, inner_query_args)+ return cursor.fetchone()++ row = retry_on_deadlock(_run, logger=logger)++ if row is None:+ logger.debug("get_rows_to_sync: No results returned. Using 0 as rows to sync")+ return 0++ rows_to_sync_int = int(row[0] or 0)+ logger.debug(f"get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")+ return rows_to_sync_int+ except Exception as e:+ # This COUNT(*) is a best-effort estimate for progress reporting and partition+ # sizing. It shares its FROM/WHERE with the real streaming query, so any genuine+ # problem (missing column, bad incremental field, permissions) resurfaces there+ # and is classified through the normal retryable/non-retryable path. Capturing it+ # here too would only flood error tracking with handled duplicates, so log at+ # debug and fall back to 0.+ logger.debug(f"get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)+ return 0+# ------------------------------------------------------------------# Pipeline build — the dlt `SourceResponse` for a single table# ------------------------------------------------------------------diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.pyindex e210f01dc0ae..98d01f73164b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py@@ -465,6 +465,39 @@ class TestFetchAverageRowSize:assert result is None+class TestGetRowsToSync:+ 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_returns_count_from_cursor(self, impl, cursor, logger):+ cursor.fetchone.return_value = (42,)+ assert impl.get_rows_to_sync(cursor, "SELECT id FROM t", {}, logger) == 42++ def test_retries_deadlock_and_recovers_count(self, impl, cursor, logger, mocker):+ # Runs before any rows stream, so a 1205 here is exactly as safe to rerun as the+ # main read query — this used to fall straight to 0 instead of retrying.+ mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql.time.sleep")+ cursor.execute.side_effect = [self._deadlock_victim(), None]+ cursor.fetchone.return_value = (7,)+ assert impl.get_rows_to_sync(cursor, "SELECT id FROM t", {}, logger) == 7+ assert cursor.execute.call_count == 2++ def test_falls_back_to_zero_without_capturing_on_persistent_error(self, impl, cursor, logger, mocker):+ # This COUNT(*) shares its FROM/WHERE with the real streaming query, so a genuine+ # problem resurfaces (and is captured) there. Capturing it here too would flood+ # error tracking with a handled duplicate of a transient/benign probe failure.+ capture = mocker.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql.capture_exception"+ )+ cursor.execute.side_effect = RuntimeError("boom")+ assert impl.get_rows_to_sync(cursor, "SELECT id FROM t", {}, logger) == 0+ capture.assert_not_called()++# ---------------------------------------------------------------------------# End-to-end build_pipeline — wired through MSSQLImplementation# ---------------------------------------------------------------------------