: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 reset by peer instead of giving up (#72195)
Tom Owers86a2997f26de
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 c1fca512b08e..41d4e7a3414b 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@@ -411,6 +411,28 @@ def _is_transient_connect_dns_failure(e: BaseException) -> bool:return _DNS_TEMPORARY_FAILURE_TOKEN in " ".join(str(arg) for arg in e.args)+# ECONNRESET at connect time: the peer sent a RST while the connection was being established, so+# pymysql wraps the underlying `ConnectionResetError` as the 2003 "Can't connect to MySQL server+# on '<host>' ([Errno 104] Connection reset by peer)" failure. Unlike a refused connection+# (ECONNREFUSED, "Connection refused") or a failed DNS lookup — deterministic host/port misconfig+# that stay non-retryable via the "Can't connect to MySQL server on" classifier — a reset means+# something *was* reachable (an overloaded server, or a TCP proxy/load balancer in front of the DB+# that accepts then resets while its backend is cycling or briefly down) and dropped us mid-connect,+# so a fresh attempt usually recovers. Match the stable strerror phrase, not the volatile host or+# the platform-specific [Errno NNN] prefix.+_CONNECTION_RESET_TOKEN = "Connection reset by peer"+++def _is_transient_connect_reset(e: BaseException) -> bool:+ """Return True if the peer reset the connection during connect — a transient blip."""+ if not isinstance(e, pymysql.err.OperationalError):+ return False+ code = e.args[0] if e.args else None+ if code != _CANT_CONNECT_CODE:+ return False+ return _CONNECTION_RESET_TOKEN in " ".join(str(arg) for arg in e.args)++# pymysql raises this `InternalError` from `_read_packet` when an incoming packet's# sequence number doesn't match the expected one (it `_force_close()`s the socket first)._PACKET_SEQUENCE_ERROR_PHRASE = "Packet sequence number wrong"@@ -470,6 +492,7 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:_is_transient_connect_drop(e)or _is_transient_connect_timeout(e)or _is_transient_connect_dns_failure(e)+ or _is_transient_connect_reset(e)or _is_transient_packet_sequence_error(e)or _is_transient_vitess_dial_timeout(e)):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 a6a0c40fb8d3..1f35a01ab92a 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@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_bad_plan_error,_is_transient_connect_dns_failure,_is_transient_connect_drop,+ _is_transient_connect_reset,_is_transient_connect_timeout,_is_transient_packet_sequence_error,_is_transient_tablet_unavailable,@@ -994,6 +995,43 @@ class TestIsTransientConnectDnsFailure:assert not _is_transient_connect_dns_failure(pymysql.err.OperationalError())+class TestIsTransientConnectReset:+ def test_matches_connection_reset_on_connect(self):+ # ECONNRESET at connect time — the peer sent a RST mid-connect (an overloaded server, or a+ # TCP proxy that accepts then resets while its backend is down). A transient blip that must+ # be retried in-process rather than surfacing as the non-retryable "Can't connect" config error.+ assert _is_transient_connect_reset(+ pymysql.err.OperationalError(+ 2003, "Can't connect to MySQL server on 'db.example.com' ([Errno 104] Connection reset by peer)"+ )+ )++ @pytest.mark.parametrize(+ "message",+ [+ # Refused connection and failed DNS lookup are also 2003 but deterministic host/port+ # misconfig — they must stay non-retryable, not be absorbed here.+ "Can't connect to MySQL server on 'db.example.com' ([Errno 111] Connection refused)",+ "Can't connect to MySQL server on 'nope.example.com' ([Errno -2] Name or service not known)",+ ],+ )+ def test_does_not_match_permanent_connect_errors(self, message):+ assert not _is_transient_connect_reset(pymysql.err.OperationalError(2003, message))++ @pytest.mark.parametrize(+ "code,message",+ [+ (2013, "Lost connection to MySQL server during query"),+ (1045, "Access denied for user"),+ ],+ )+ def test_does_not_match_other_error_codes(self, code, message):+ assert not _is_transient_connect_reset(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_connect_reset(pymysql.err.OperationalError())++class TestIsTransientPacketSequenceError:@pytest.mark.parametrize("message",@@ -1102,6 +1140,26 @@ class TestConnectTransientRetry:assert mock_connect.call_count == 2sleep.assert_called_once_with(2)+ def test_retries_connection_reset_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(+ 2003, "Can't connect to MySQL server on 'db.example.com' ([Errno 104] Connection reset by peer)"+ ),+ 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_connect_timeout_then_succeeds(self, mocker):sleep = mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")conn = MagicMock()