: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(mysql): retry connect-time "too many connections" as a transient error (#76522)
Tom Owersbc6cdd94cac5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.pyindex abe1d4facade..6000e3027d9f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py@@ -520,6 +520,23 @@ def _is_transient_vitess_dial_timeout(e: BaseException) -> bool:return _VITESS_DIAL_TOKEN in args_text and _VITESS_DIAL_TIMEOUT_TOKEN in args_text+# MySQL/MariaDB error 1040 (ER_CON_COUNT_ERROR): the server refuses a *new* connection because+# `max_connections` is already reached. A transient capacity condition on the customer's database,+# not a misconfiguration — a slot frees the moment another connection closes — so a fresh attempt+# after a short backoff usually succeeds. Mirrors the Postgres source's "sorry, too many clients+# already" / "remaining connection slots are reserved" handling, which is retried the same way and+# likewise kept out of `get_non_retryable_errors` (see `MySQLSource.get_retryable_errors`).+_TOO_MANY_CONNECTIONS_CODE = 1040+++def _is_transient_too_many_connections(e: BaseException) -> bool:+ """Return True if the server refused a new connection because it's at `max_connections`."""+ if not isinstance(e, pymysql.err.OperationalError):+ return False+ code = e.args[0] if e.args else None+ return code == _TOO_MANY_CONNECTIONS_CODE++def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:"""Open a pymysql connection, retrying a transient drop or timeout on connect.@@ -543,6 +560,7 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:or _is_transient_connect_broken_pipe(e)or _is_transient_packet_sequence_error(e)or _is_transient_vitess_dial_timeout(e)+ or _is_transient_too_many_connections(e)):raisestructlog.get_logger().warning(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.pyindex bd3790529445..8fe8321e685e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py@@ -301,7 +301,11 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase# exhausted; the streaming path's FORCE INDEX fallback does the same for a mid-query drop# (see `_is_bad_plan_error`). Either way, Temporal retries the whole activity next and the# failure is transient and self-recovering, so don't surface it as tracked exception noise.- return {"Lost connection to MySQL server during query"}+ #+ # "Too many connections" (MySQL error 1040) shares the same contract: `_connect_with_transient_retry`+ # retries it in-process too (see `_is_transient_too_many_connections`) — a slot frees the moment+ # another connection closes, mirroring the Postgres source's connection-limit handling.+ return {"Lost connection to MySQL server during query", "Too many connections"}def reconcile_schema_metadata(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex 5da06eb804bf..bbbde3ef15e6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_transient_metadata_query_reset,_is_transient_packet_sequence_error,_is_transient_tablet_unavailable,+ _is_transient_too_many_connections,_is_transient_vitess_dial_timeout,_is_transient_vitess_reparent,_release_streaming_cursor,@@ -1191,6 +1192,27 @@ class TestIsTransientVitessDialTimeout:assert not _is_transient_vitess_dial_timeout(ValueError("dial tcp 10.0.0.1: connection timed out"))+class TestIsTransientTooManyConnections:+ def test_matches_too_many_connections(self):+ assert _is_transient_too_many_connections(pymysql.err.OperationalError(1040, "Too many connections"))++ @pytest.mark.parametrize(+ "code,message",+ [+ (2003, "Can't connect to MySQL server on 'db.example.com' ([Errno 111] Connection refused)"),+ (1045, "Access denied for user"),+ ],+ )+ def test_does_not_match_other_codes(self, code, message):+ assert not _is_transient_too_many_connections(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_too_many_connections(pymysql.err.OperationalError())++ def test_does_not_match_non_operational_error(self):+ assert not _is_transient_too_many_connections(pymysql.err.InternalError(1040, "Too many connections"))++class TestConnectTransientRetry:@pytest.mark.parametrize("fail_count,expected_sleeps",@@ -1340,6 +1362,21 @@ class TestConnectTransientRetry:assert mock_connect.call_count == 2sleep.assert_called_once_with(2)+ def test_retries_too_many_connections_then_succeeds(self, mocker):+ sleep = mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")+ conn = MagicMock()+ conn.__enter__.return_value = conn+ mock_connect = mocker.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ side_effect=[pymysql.err.OperationalError(1040, "Too many connections"), conn],+ )++ with MySQLImplementation().connect(_make_config()) as yielded:+ assert yielded is conn++ assert mock_connect.call_count == 2+ sleep.assert_called_once_with(2)+def test_retries_packet_sequence_error_then_succeeds(self, mocker):sleep = mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")conn = MagicMock()@@ -2033,6 +2070,34 @@ class TestMySQLSourceNonRetryableErrors:is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())assert not is_non_retryable, f"Transient thread-exhaustion error should remain retryable: {error_msg}"+ @pytest.mark.parametrize(+ "error_msg",+ [+ "OperationalError: (1040, 'Too many connections')",+ "Too many connections",+ ],+ )+ def test_too_many_connections_stays_retryable(self, source, error_msg):+ non_retryable = source.get_non_retryable_errors()+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())+ assert not is_non_retryable, f"Too-many-connections error should remain retryable: {error_msg}"++ @pytest.mark.parametrize(+ "error_msg",+ [+ "OperationalError: (1040, 'Too many connections')",+ "Too many connections",+ ],+ )+ def test_too_many_connections_is_classified_retryable(self, source, error_msg):+ # Already retried in-process at connect time (`_is_transient_too_many_connections`); once+ # exhausted it re-raises for Temporal to retry the whole activity. Without this+ # classification `_handle_import_error` logs it at `exception` on every occurrence,+ # flooding error tracking with a self-recovering capacity condition.+ retryable = source.get_retryable_errors()+ is_retryable = any(pattern in error_msg for pattern in retryable)+ assert is_retryable, f"Too-many-connections error should be classified retryable: {error_msg}"+class TestMySQLSourceValidateCredentials:@pytest.fixture