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 transient packet-sequence error on connect (#65706)

Tom Owersaf9a5a663c85
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 252a06411dfc..ba032cb78887 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
@@ -378,6 +378,26 @@ def _is_transient_connect_timeout(e: BaseException) -> bool:
return "timed out" 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"
+
+
+def _is_transient_packet_sequence_error(e: BaseException) -> bool:
+ """Return True if the handshake stream desynced mid-exchange — a transient blip.
+
+ A packet-sequence mismatch during connect means the server's handshake reply
+ arrived out of order or truncated (an overloaded server, a proxy/load balancer
+ interfering, a momentary network blip) and pymysql force-closed the dead socket.
+ It's the same transient class as the 2013 drop above and a fresh attempt recovers,
+ but it surfaces as `InternalError`, not `OperationalError`, so it needs its own
+ predicate. Match the stable phrase, not the volatile got/expected packet numbers.
+ """
+ if not isinstance(e, pymysql.err.InternalError):
+ return False
+ return any(_PACKET_SEQUENCE_ERROR_PHRASE in str(arg) for arg in e.args)
+
+
def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
"""Open a pymysql connection, retrying a transient drop or timeout on connect.
@@ -390,14 +410,16 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
while True:
try:
return pymysql.connect(**kwargs)
- except pymysql.err.OperationalError as e:
+ except pymysql.err.DatabaseError as e:
attempt += 1
if attempt >= _MAX_CONNECT_ATTEMPTS or not (
- _is_transient_connect_drop(e) or _is_transient_connect_timeout(e)
+ _is_transient_connect_drop(e)
+ or _is_transient_connect_timeout(e)
+ or _is_transient_packet_sequence_error(e)
):
raise
structlog.get_logger().warning(
- "Transient MySQL connect error (drop or timeout); retrying",
+ "Transient MySQL connection error during connect; retrying",
attempt=attempt,
max_attempts=_MAX_CONNECT_ATTEMPTS,
exc_info=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 9cf7095319eb..d17eed6e3afe 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
@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq
_is_bad_plan_error,
_is_transient_connect_drop,
_is_transient_connect_timeout,
+ _is_transient_packet_sequence_error,
_is_transient_tablet_unavailable,
_release_streaming_cursor,
_retry_on_transient_tablet_unavailable,
@@ -935,6 +936,31 @@ class TestIsTransientConnectTimeout:
assert not _is_transient_connect_timeout(pymysql.err.OperationalError())
+class TestIsTransientPacketSequenceError:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Packet sequence number wrong - got 2 expected 3",
+ "Packet sequence number wrong - got 0 expected 1",
+ ],
+ )
+ def test_matches_packet_sequence_error(self, message):
+ assert _is_transient_packet_sequence_error(pymysql.err.InternalError(message))
+
+ def test_does_not_match_other_internal_error(self):
+ assert not _is_transient_packet_sequence_error(pymysql.err.InternalError("some other internal error"))
+
+ def test_does_not_match_operational_error(self):
+ # The packet-sequence error is an `InternalError`; a 2013 drop is an `OperationalError`
+ # handled by `_is_transient_connect_drop`, so this predicate must not also claim it.
+ assert not _is_transient_packet_sequence_error(
+ pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query")
+ )
+
+ def test_does_not_match_error_without_args(self):
+ assert not _is_transient_packet_sequence_error(pymysql.err.InternalError())
+
+
class TestConnectTransientRetry:
@pytest.mark.parametrize(
"fail_count,expected_sleeps",
@@ -1000,6 +1026,24 @@ class TestConnectTransientRetry:
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()
+ 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.InternalError("Packet sequence number wrong - got 2 expected 3"),
+ 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_does_not_retry_connection_refused(self, mocker):
sleep = mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")
mock_connect = mocker.patch(
@@ -1016,6 +1060,20 @@ class TestConnectTransientRetry:
assert mock_connect.call_count == 1
sleep.assert_not_called()
+ def test_does_not_retry_non_transient_internal_error(self, mocker):
+ sleep = mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ mock_connect = mocker.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.pymysql.connect",
+ side_effect=pymysql.err.InternalError("some other internal error"),
+ )
+
+ with pytest.raises(pymysql.err.InternalError):
+ with MySQLImplementation().connect(_make_config()):
+ pass
+
+ assert mock_connect.call_count == 1
+ sleep.assert_not_called()
+
def test_gives_up_after_max_attempts(self, mocker):
mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")
mock_connect = mocker.patch(