: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 when a TiDB gateway reports no available instances (#111654)
Tom Owers8b7652ec8ec7
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 fadd1d0c45ee..3bd286d45a89 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@@ -841,6 +841,7 @@ def _connect_with_transient_retry(kwargs: dict[str, Any], team_id: int | None) -or _is_transient_packet_sequence_error(e)or _is_transient_vitess_dial_timeout(e)or _is_transient_tiproxy_unavailable(e)+ or _is_transient_no_available_tidb_instances(e)or _is_transient_too_many_connections(e)or _is_transient_cant_create_thread(e)):@@ -910,6 +911,21 @@ def _is_transient_tiproxy_unavailable(e: BaseException) -> bool:return _TIPROXY_UNAVAILABLE_TOKEN in " ".join(str(arg) for arg in e.args)+# A TiDB-fronting gateway's own ER_UNKNOWN_ERROR (1105) wording for the same "no backend reachable"+# condition as the TiProxy case above, just phrased differently — the gateway found zero TiDB+# instances to route to (a scale-down, rolling restart, or momentary control-plane blip) rather+# than failing to reach one it knew about. Same proxy-layer pattern: a fresh attempt recovers once+# a TiDB instance is available again. The message carries no host/port, so match it in full.+_TIDB_NO_AVAILABLE_INSTANCES_TOKEN = "No available TiDB instances, please make sure TiDB is available"+++def _is_transient_no_available_tidb_instances(e: BaseException) -> bool:+ """Return True if a TiDB-fronting gateway reported zero reachable TiDB instances."""+ if not isinstance(e, pymysql.err.OperationalError):+ return False+ return _TIDB_NO_AVAILABLE_INSTANCES_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.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.pyindex 1b9f32bca229..259869c83bcf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/source.py@@ -501,6 +501,12 @@ class MySQLSource(# the rare case where it exhausts that budget so Temporal's own activity retry# can recover it rather than surfacing it as error-tracking noise."TiProxy fails to connect to TiDB",+ # A TiDB-fronting gateway's own 1105 wording for the same "no backend reachable"+ # condition as the TiProxy case above — it found zero TiDB instances to route to+ # rather than failing to reach one it knew about. `_connect_with_transient_retry`+ # already retries it in-process (see `_is_transient_no_available_tidb_instances` in+ # mysql.py); this is the backstop for the rare case where it exhausts that budget.+ "No available TiDB instances, please make sure TiDB is available",# Vitess/PlanetScale vtgate error 1105 raised while a streaming query is in flight:# vtgate's own gRPC client to the backend vttablet was already closing (a tablet# swap during a failover, reparent, or health-check-triggered pool recycle) when thediff --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 841b2e1d6035..56ff956e151c 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@@ -47,6 +47,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_transient_connect_reset,_is_transient_connect_timeout,_is_transient_metadata_query_reset,+ _is_transient_no_available_tidb_instances,_is_transient_packet_sequence_error,_is_transient_tablet_unavailable,_is_transient_tiproxy_unavailable,@@ -1786,6 +1787,24 @@ class TestConnectTransientRetry:assert mock_connect.call_count == 2sleep.assert_called_once_with(2)+ def test_retries_no_available_tidb_instances_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._SourceConnection",+ side_effect=[+ pymysql.err.OperationalError(1105, "No available TiDB instances, please make sure TiDB is available"),+ 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(@@ -1946,6 +1965,34 @@ class TestIsTransientTiproxyUnavailable:assert not _is_transient_tiproxy_unavailable(ValueError("TiProxy fails to connect to TiDB"))+class TestIsTransientNoAvailableTidbInstances:+ def test_matches_no_available_tidb_instances(self):+ assert _is_transient_no_available_tidb_instances(+ pymysql.err.OperationalError(1105, "No available TiDB instances, please make sure TiDB is available")+ )++ @pytest.mark.parametrize(+ "code,message",+ [+ # Other 1105 payloads (Vitess cases, TiProxy's own wording) are not this class.+ (1105, "TiProxy fails to connect to TiDB, please make sure TiDB is available"),+ (1105, "vttablet: rpc error: code = Unavailable desc = node is shutting down"),+ (1045, "Access denied for user"),+ (2003, "Can't connect to MySQL server on 'db.example.com'"),+ ],+ )+ def test_does_not_match_other_errors(self, code, message):+ assert not _is_transient_no_available_tidb_instances(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_no_available_tidb_instances(pymysql.err.OperationalError())++ def test_does_not_match_non_operational_error(self):+ assert not _is_transient_no_available_tidb_instances(+ ValueError("No available TiDB instances, please make sure TiDB is available")+ )++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.@@ -2748,6 +2795,23 @@ class TestMySQLSourceNonRetryableErrors:is_retryable = any(pattern in error_msg for pattern in retryable)assert is_retryable, f"Vitess reparent error should be classified retryable: {error_msg}"+ @pytest.mark.parametrize(+ "error_msg",+ [+ "OperationalError: (1105, 'No available TiDB instances, please make sure TiDB is available')",+ "No available TiDB instances, please make sure TiDB is available",+ ],+ )+ def test_no_available_tidb_instances_is_classified_retryable(self, source, error_msg):+ # `_connect_with_transient_retry` already retries this in-process at connect time (see+ # `_is_transient_no_available_tidb_instances` in mysql.py); once exhausted it re-raises for+ # Temporal to retry the whole activity. Without this classification `_handle_import_error`+ # logs it at `exception` on every occurrence, flooding error tracking with a self-recovering+ # gateway condition.+ retryable = source.get_retryable_errors()+ is_retryable = any(pattern in error_msg for pattern in retryable)+ assert is_retryable, f"No-available-TiDB-instances error should be classified retryable: {error_msg}"+@pytest.mark.parametrize("error_msg",[