: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 transient connection drops on connect (#64647)
Tom Owers7ca2f9ee5d4b
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.pyindex 4ca20768d08f..aa8a200ae3f8 100644--- a/posthog/temporal/data_imports/sources/mysql/mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py@@ -16,6 +16,7 @@ module-scope primitives.from __future__ import annotations+import timeimport datetimeimport collectionsfrom collections.abc import Iterator@@ -281,6 +282,54 @@ def _is_bad_plan_error(e: pymysql.err.OperationalError) -> bool:return code in (_LOST_CONNECTION_DURING_QUERY_CODE, _OUT_OF_SORT_MEMORY_CODE)+# Number of times `connect` will open a fresh pymysql connection before giving up.+_MAX_CONNECT_ATTEMPTS = 3+++def _is_transient_connect_drop(e: BaseException) -> bool:+ """Return True if the connection was dropped mid-handshake — a transient blip.++ pymysql reports a socket close while reading the server greeting as the same+ 2013 code we see mid-query, but at connect time it means the server hung up+ before the handshake finished (an overloaded server, a proxy idle cull, a+ failover, a momentary network blip) — a fresh attempt recovers. The one 2013+ that is *not* transient is the SSL-version mismatch (a deterministic config+ error, already non-retryable): it arrives with an `[SSL: ...` suffix, so+ exclude that and let it surface.+ """+ if not isinstance(e, pymysql.err.OperationalError):+ return False+ code = e.args[0] if e.args else None+ if code != _LOST_CONNECTION_DURING_QUERY_CODE:+ return False+ return "[SSL:" not in " ".join(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 during the handshake.++ Mirrors the in-process connect retry the Postgres source uses: a momentary+ drop while establishing the connection recovers on a fresh attempt, so retry+ it here with a short backoff instead of failing schema discovery / sync setup+ on the first blip and surfacing it as captured error-tracking noise.+ """+ attempt = 0+ while True:+ try:+ return pymysql.connect(**kwargs)+ except pymysql.err.OperationalError as e:+ attempt += 1+ if attempt >= _MAX_CONNECT_ATTEMPTS or not _is_transient_connect_drop(e):+ raise+ structlog.get_logger().warning(+ "Transient MySQL connection drop during connect; retrying",+ attempt=attempt,+ max_attempts=_MAX_CONNECT_ATTEMPTS,+ exc_info=e,+ )+ time.sleep(attempt)++def _release_streaming_cursor(cursor: SSCursor) -> None:"""Detach an unbuffered cursor from its connection without draining it.@@ -449,7 +498,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con}if read_timeout is not None:kwargs["read_timeout"] = read_timeout- with pymysql.connect(**kwargs) as conn:+ with _connect_with_transient_retry(kwargs) as conn:yield conn# ------------------------------------------------------------------diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex 41c73b56730d..d3cf02ca1ee8 100644--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -14,11 +14,13 @@ from posthog.temporal.data_imports.sources.common.sql import Table, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilterfrom posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfigfrom posthog.temporal.data_imports.sources.mysql.mysql import (+ _MAX_CONNECT_ATTEMPTS,STATEMENT_TIMEOUT_SECONDS,MySQLColumn,MySQLImplementation,_build_query,_is_bad_plan_error,+ _is_transient_connect_drop,_release_streaming_cursor,_safe_convert_date,_safe_convert_datetime,@@ -836,6 +838,93 @@ class TestIsBadPlanError:assert not _is_bad_plan_error(pymysql.err.OperationalError())+class TestIsTransientConnectDrop:+ @pytest.mark.parametrize(+ "message",+ [+ "Lost connection to MySQL server during query",+ "Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)",+ ],+ )+ def test_matches_lost_connection(self, message):+ assert _is_transient_connect_drop(pymysql.err.OperationalError(2013, message))++ def test_does_not_match_ssl_version_mismatch(self):+ # SSL wrong-version arrives wrapped in 2013 but is a deterministic config error+ # (already non-retryable) — retrying just delays the friendly message.+ assert not _is_transient_connect_drop(+ pymysql.err.OperationalError(+ 2013,+ "Lost connection to MySQL server during query "+ "([SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2657))",+ )+ )++ @pytest.mark.parametrize(+ "code,message",+ [+ (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_drop(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_connect_drop(pymysql.err.OperationalError())+++class TestConnectTransientRetry:+ def test_retries_transient_drop_then_succeeds(self, mocker):+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")+ conn = MagicMock()+ conn.__enter__.return_value = conn+ mock_connect = mocker.patch(+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ side_effect=[+ pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"),+ conn,+ ],+ )++ with MySQLImplementation().connect(_make_config()) as yielded:+ assert yielded is conn++ assert mock_connect.call_count == 2+ sleep.assert_called_once_with(1)++ def test_gives_up_after_max_attempts(self, mocker):+ mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")+ mock_connect = mocker.patch(+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ side_effect=pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"),+ )++ with pytest.raises(pymysql.err.OperationalError):+ with MySQLImplementation().connect(_make_config()):+ pass++ assert mock_connect.call_count == _MAX_CONNECT_ATTEMPTS++ def test_does_not_retry_ssl_version_mismatch(self, mocker):+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")+ mock_connect = mocker.patch(+ "posthog.temporal.data_imports.sources.mysql.mysql.pymysql.connect",+ side_effect=pymysql.err.OperationalError(+ 2013,+ "Lost connection to MySQL server during query "+ "([SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2657))",+ ),+ )++ with pytest.raises(pymysql.err.OperationalError):+ with MySQLImplementation().connect(_make_config()):+ pass++ assert mock_connect.call_count == 1+ sleep.assert_not_called()++class TestBuildQueryForceIndex:def test_force_index_hint_omitted_by_default(self):query, _ = _build_query(