: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 Vitess reparent errors during metadata discovery (#70182)
Tom Owers3e90cf3c9c9e
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 12c0e86342c1..1960b826291d 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@@ -475,6 +475,23 @@ def _is_transient_tablet_unavailable(e: BaseException) -> bool:return _GRPC_UNAVAILABLE_TOKEN in " ".join(str(arg) for arg in e.args)+# Vitess/PlanetScale also fails a query against a shard mid-failover with pymysql+# OperationalError(1105) whose message carries "primary is not serving, there may be a+# reparent operation in progress": a planned/emergency reparent is promoting a new primary,+# so the old one briefly stops serving. Like the `code = Unavailable` case this is transient —+# a fresh attempt after a short backoff lands on the newly promoted primary. Key on the stable+# `reparent operation in progress` phrase: the target keyspace/shard/tablet-type prefix is+# volatile, and this stays robust to the primary/master wording difference across Vitess versions.+_VITESS_REPARENT_TOKEN = "reparent operation in progress"+++def _is_transient_vitess_reparent(e: BaseException) -> bool:+ """Return True if a Vitess shard is mid-reparent and its primary is briefly not serving."""+ if not isinstance(e, pymysql.err.OperationalError):+ return False+ return _VITESS_REPARENT_TOKEN in " ".join(str(arg) for arg in e.args)++def _retry_on_transient_tablet_unavailable(operation: Callable[[], _T],logger: FilteringBoundLogger,@@ -488,8 +505,8 @@ def _retry_on_transient_tablet_unavailable(handshake 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- `_is_transient_tablet_unavailable` only matches the gRPC `Unavailable` status.+ noise. Non-transient errors re-raise immediately because the predicates only match+ the gRPC `Unavailable` status or a mid-reparent primary — both self-healing."""attempt = 0while True:@@ -497,7 +514,7 @@ 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):+ if attempt >= max_attempts or not (_is_transient_tablet_unavailable(e) or _is_transient_vitess_reparent(e)):raiselogger.warning("Transient MySQL tablet-unavailable error during metadata discovery; retrying",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 41ebe87828af..98ba6b319f85 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@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_transient_packet_sequence_error,_is_transient_tablet_unavailable,_is_transient_vitess_dial_timeout,+ _is_transient_vitess_reparent,_release_streaming_cursor,_retry_on_transient_tablet_unavailable,_safe_convert_date,@@ -1216,6 +1217,40 @@ class TestIsTransientTabletUnavailable:assert not _is_transient_tablet_unavailable(ValueError("code = Unavailable"))+class TestIsTransientVitessReparent:+ @pytest.mark.parametrize(+ "message",+ [+ # The shape Vitess/PlanetScale surfaces while a shard is mid-failover — the target+ # keyspace/shard prefix varies, the `reparent operation in progress` phrase is stable.+ "unknown: target: keyspace.-.primary: primary is not serving, "+ "there may be a reparent operation in progress",+ # Older Vitess used "master" wording; the tail phrase we match is unchanged.+ "target: keyspace.0.master: master is not serving, there may be a reparent operation in progress",+ ],+ )+ def test_matches_reparent(self, message):+ assert _is_transient_vitess_reparent(pymysql.err.OperationalError(1105, message))++ @pytest.mark.parametrize(+ "code,message",+ [+ # Other 1105 payloads and the tablet-unavailable sibling are not this class.+ (1105, "vttablet: rpc error: code = Unavailable desc = node is shutting down"),+ (1105, "vttablet: rpc error: code = InvalidArgument desc = some bad request"),+ (1045, "Access denied for user"),+ ],+ )+ def test_does_not_match_other_errors(self, code, message):+ assert not _is_transient_vitess_reparent(pymysql.err.OperationalError(code, message))++ def test_does_not_match_error_without_args(self):+ assert not _is_transient_vitess_reparent(pymysql.err.OperationalError())++ def test_does_not_match_non_operational_error(self):+ assert not _is_transient_vitess_reparent(ValueError("reparent operation in progress"))++class TestRetryOnTransientTabletUnavailable:@staticmethoddef _unavailable() -> pymysql.err.OperationalError:@@ -1241,6 +1276,19 @@ class TestRetryOnTransientTabletUnavailable:assert operation.call_count == fail_count + 1assert [c.args[0] for c in sleep.call_args_list] == expected_sleeps+ def test_retries_vitess_reparent_then_succeeds(self, mocker):+ mocker.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.time.sleep")+ reparent = pymysql.err.OperationalError(+ 1105,+ "unknown: target: keyspace.-.primary: primary is not serving, "+ "there may be a reparent operation in progress",+ )+ operation = MagicMock(side_effect=[reparent, "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())