: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 a connection reset during metadata discovery (#72800)
Tom Owersd8408d83395b
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 510b63339a85..ae97158c03e8 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@@ -564,21 +564,43 @@ def _is_transient_vitess_reparent(e: BaseException) -> bool:return _VITESS_REPARENT_TOKEN in " ".join(str(arg) for arg in e.args)+def _is_transient_metadata_query_reset(e: BaseException) -> bool:+ """Return True if a metadata query's connection was reset mid-query — a transient blip.++ `_is_transient_connect_drop` already retries this same 2013 code when it fires inside+ `connect()` (a socket close while reading the server greeting); this predicate covers the+ sibling case where the connection was already established and the reset landed once a real+ query was in flight — e.g. `get_table_metadata`'s small `information_schema.columns` lookup.+ A bare `ConnectionResetError` payload means the socket itself was reset (an overloaded+ server, a proxy/load-balancer cycling its backend, a momentary network blip), not the+ bad-plan filesort-timeout symptom `_is_bad_plan_error` also keys on this code for — that one+ only applies to the streaming data query, which has its own FORCE INDEX fallback. Match the+ stable strerror phrase, not the volatile host.+ """+ 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 _CONNECTION_RESET_TOKEN in " ".join(str(arg) for arg in e.args)++def _retry_on_transient_tablet_unavailable(operation: Callable[[], _T],logger: FilteringBoundLogger,*,max_attempts: int = _MAX_CONNECT_ATTEMPTS,) -> _T:- """Run `operation`, retrying a transient Vitess tablet-unavailable error.+ """Run `operation`, retrying a transient error hit during metadata discovery.Mirrors `_connect_with_transient_retry`, but covers the metadata queries that run ona freshly opened connection: reconnecting alone doesn't help when the vtgatehandshake succeeds and only the first query hits an unavailable tablet, so retry thewhole operation (which reopens the connection) with a bounded backoff instead offailing sync setup on the first blip and surfacing it as captured error-tracking- noise. Non-transient errors re-raise immediately because the predicates only match- the gRPC `Unavailable` status or a mid-reparent primary — both self-healing.+ noise. Non-transient errors re-raise immediately — the predicates only match the gRPC+ `Unavailable` status, a mid-reparent primary, or a plain peer-reset connection drop,+ all self-healing."""attempt = 0while True:@@ -586,10 +608,14 @@ def _retry_on_transient_tablet_unavailable(return operation()except pymysql.err.OperationalError as e:attempt += 1- if attempt >= max_attempts or not (_is_transient_tablet_unavailable(e) or _is_transient_vitess_reparent(e)):+ if attempt >= max_attempts or not (+ _is_transient_tablet_unavailable(e)+ or _is_transient_vitess_reparent(e)+ or _is_transient_metadata_query_reset(e)+ ):raiselogger.warning(- "Transient MySQL tablet-unavailable error during metadata discovery; retrying",+ "Transient MySQL error during metadata discovery; retrying",attempt=attempt,max_attempts=max_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.pyindex e9212251dee5..143b6b28d396 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@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_transient_connect_gone_away,_is_transient_connect_reset,_is_transient_connect_timeout,+ _is_transient_metadata_query_reset,_is_transient_packet_sequence_error,_is_transient_tablet_unavailable,_is_transient_vitess_dial_timeout,@@ -1450,6 +1451,36 @@ class TestIsTransientVitessReparent:assert not _is_transient_vitess_reparent(ValueError("reparent operation in progress"))+class TestIsTransientMetadataQueryReset:+ def test_matches_connection_reset_mid_query(self):+ # A peer reset landing on an already-open connection while a metadata query (e.g.+ # `get_table_metadata`'s information_schema lookup) was in flight — an overloaded+ # server or a proxy/load-balancer cycling its backend, not a bad query plan.+ assert _is_transient_metadata_query_reset(+ pymysql.err.OperationalError(+ 2013, "Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)"+ )+ )++ @pytest.mark.parametrize(+ "code,message",+ [+ # Same code without the peer-reset signature is the bad-plan/filesort-timeout+ # symptom `_is_bad_plan_error` handles instead — must not be absorbed here.+ (2013, "Lost connection to MySQL server during query"),+ (1045, "Access denied for user"),+ ],+ )+ def test_does_not_match_other_errors(self, code, message):+ assert not _is_transient_metadata_query_reset(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_metadata_query_reset(pymysql.err.OperationalError())++ def test_does_not_match_non_operational_error(self):+ assert not _is_transient_metadata_query_reset(ConnectionResetError("[Errno 104] Connection reset by peer"))++class TestRetryOnTransientTabletUnavailable:@staticmethoddef _unavailable() -> pymysql.err.OperationalError:@@ -1488,6 +1519,17 @@ class TestRetryOnTransientTabletUnavailable:assert operation.call_count == 2+ def test_retries_metadata_query_connection_reset_then_succeeds(self, mocker):+ mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")+ reset = pymysql.err.OperationalError(+ 2013, "Lost connection to MySQL server during query ([Errno 104] Connection reset by peer)"+ )+ operation = MagicMock(side_effect=[reset, "ok"])++ assert _retry_on_transient_tablet_unavailable(operation, MagicMock()) == "ok"++ assert operation.call_count == 2+def test_gives_up_after_max_attempts(self, mocker):mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")operation = MagicMock(side_effect=self._unavailable())