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(mysql): retry connect when server drops us mid-handshake (#72185)

Tom Owers7849efa90c96
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.py
index bc16b4df21e6..4f9c90112c6b 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
@@ -369,6 +369,23 @@ def _is_transient_connect_drop(e: BaseException) -> bool:
return False
+# pymysql error code 2006 (CR_SERVER_GONE_ERROR): the server closed the socket while pymysql was
+# writing to it — `_write_bytes` wraps the underlying `ConnectionResetError` / `BrokenPipeError`
+# as "MySQL server has gone away (<os error>)". Mid-handshake (sending the auth packet) this is the
+# write-side sibling of the 2013 read-side drop above: an overloaded server, a proxy/load-balancer
+# idle cull, or a failover reset the connection, all of which a fresh attempt recovers from. Unlike
+# 2013 there's no deterministic-config subcase to exclude, so match the bare code.
+_SERVER_GONE_AWAY_CODE = 2006
+
+
+def _is_transient_connect_gone_away(e: BaseException) -> bool:
+ """Return True if the server went away while establishing the connection — a transient blip."""
+ if not isinstance(e, pymysql.err.OperationalError):
+ return False
+ code = e.args[0] if e.args else None
+ return code == _SERVER_GONE_AWAY_CODE
+
+
def _is_transient_connect_timeout(e: BaseException) -> bool:
"""Return True if the initial connect timed out — a transient blip.
@@ -490,6 +507,7 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
attempt += 1
if attempt >= _MAX_CONNECT_ATTEMPTS or not (
_is_transient_connect_drop(e)
+ or _is_transient_connect_gone_away(e)
or _is_transient_connect_timeout(e)
or _is_transient_connect_dns_failure(e)
or _is_transient_connect_reset(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.py
index 417907801e77..50c7587ee9b4 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_gone_away,
_is_transient_connect_reset,
_is_transient_connect_timeout,
_is_transient_packet_sequence_error,
@@ -948,6 +949,34 @@ class TestIsTransientConnectDrop:
assert not _is_transient_connect_drop(pymysql.err.OperationalError())
+class TestIsTransientConnectGoneAway:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "MySQL server has gone away (ConnectionResetError(104, 'Connection reset by peer'))",
+ "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))",
+ ],
+ )
+ def test_matches_server_gone_away(self, message):
+ # The server reset the socket mid-handshake — the write-side sibling of the 2013 read-side
+ # drop, transient, so the in-process retry must catch it instead of surfacing it as noise.
+ assert _is_transient_connect_gone_away(pymysql.err.OperationalError(2006, message))
+
+ @pytest.mark.parametrize(
+ "code,message",
+ [
+ (2013, "Lost connection to MySQL server during query"),
+ (2003, "Can't connect to MySQL server on 'db.example.com'"),
+ (1045, "Access denied for user"),
+ ],
+ )
+ def test_does_not_match_other_error_codes(self, code, message):
+ assert not _is_transient_connect_gone_away(pymysql.err.OperationalError(code, message))
+
+ def test_does_not_match_error_without_args(self):
+ assert not _is_transient_connect_gone_away(pymysql.err.OperationalError())
+
+
class TestIsTransientConnectTimeout:
@pytest.mark.parametrize(
"message",
@@ -1187,6 +1216,26 @@ class TestConnectTransientRetry:
assert mock_connect.call_count == 2
sleep.assert_called_once_with(2)
+ def test_retries_server_gone_away_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(
+ 2006, "MySQL server has gone away (ConnectionResetError(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()