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 tablet-unavailable errors in-process (#65281)

Tom Owers72ffcbd623ab
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.py
index 863384f222f5..d7d1c56b6261 100644
--- a/posthog/temporal/data_imports/sources/mysql/mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py
@@ -19,9 +19,9 @@ from __future__ import annotations
import time
import datetime
import collections
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
-from typing import Any
+from typing import Any, TypeVar
from django.conf import settings
@@ -61,7 +61,7 @@ from posthog.temporal.data_imports.sources.common.sql.incremental import Increme
from posthog.temporal.data_imports.sources.common.sql.location import normalize_namespace, resolve_source_location
from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig
-from products.data_warehouse.backend.types import IncrementalFieldType
+from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
__all__ = [
"MySQLColumn",
@@ -333,6 +333,62 @@ def _connect_with_transient_retry(kwargs: dict[str, Any]) -> pymysql.Connection:
time.sleep(min(2 * attempt, 30))
+_T = TypeVar("_T")
+
+# Vitess/PlanetScale vtgate wraps a momentarily-unreachable backend tablet (a failover,
+# restart, or rollout) as pymysql OperationalError(1105) carrying the gRPC status
+# `code = Unavailable`. 1105 is MySQL's generic ER_UNKNOWN_ERROR catch-all, so we key on
+# the stable `code = Unavailable` token rather than the bare code — the volatile
+# target/host/port and other 1105 payloads stay untouched.
+_GRPC_UNAVAILABLE_TOKEN = "code = Unavailable"
+
+
+def _is_transient_tablet_unavailable(e: BaseException) -> bool:
+ """Return True if a Vitess vtgate reported its backend tablet transiently unavailable.
+
+ gRPC `Unavailable` is the canonical retry-me status: the tablet is briefly
+ unreachable (failover, restart) even though the vtgate handshake succeeded, so the
+ first query after connect fails with a 1105 `code = Unavailable`. A fresh attempt
+ after a short backoff usually lands on a healthy tablet.
+ """
+ if not isinstance(e, pymysql.err.OperationalError):
+ return False
+ return _GRPC_UNAVAILABLE_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.
+
+ Mirrors `_connect_with_transient_retry`, but covers the metadata queries that run on
+ a freshly opened connection: reconnecting alone doesn't help when the vtgate
+ handshake succeeds and only the first query hits an unavailable tablet, so retry the
+ whole operation (which reopens the connection) with a bounded backoff instead of
+ failing 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.
+ """
+ attempt = 0
+ while True:
+ try:
+ return operation()
+ except pymysql.err.OperationalError as e:
+ attempt += 1
+ if attempt >= max_attempts or not _is_transient_tablet_unavailable(e):
+ raise
+ logger.warning(
+ "Transient MySQL tablet-unavailable error during metadata discovery; retrying",
+ attempt=attempt,
+ max_attempts=max_attempts,
+ exc_info=e,
+ )
+ time.sleep(min(2 * attempt, 30))
+
+
def _release_streaming_cursor(cursor: SSCursor) -> None:
"""Detach an unbuffered cursor from its connection without draining it.
@@ -996,39 +1052,49 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
enabled_columns = inputs.enabled_columns
row_filters = inputs.row_filters
- with self.connect(config) as connection:
- with connection.cursor() as cursor:
- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
- full_table = self.get_table_metadata(cursor, schema, table_name)
-
- # Resolve PKs before the projection so probe/sample queries match the streaming SELECT.
- if primary_keys is None and "id" in full_table:
- primary_keys = ["id"]
-
- projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
- table = project_arrow_columns(full_table, projected)
- arrow_schema = table.to_arrow_schema()
- logger.debug(f"Source schema: {arrow_schema}")
-
- inner_query, inner_query_args = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- enabled_columns=enabled_columns,
- primary_keys=primary_keys,
- row_filters=row_filters,
- )
+ def _discover_metadata() -> tuple[list[str] | None, pa.Schema, int, PartitionSettings | None, int]:
+ with self.connect(config) as connection:
+ with connection.cursor() as cursor:
+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)
+ full_table = self.get_table_metadata(cursor, schema, table_name)
- rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)
- chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)
- partition_settings = (
- self.get_partition_settings(cursor, schema, table_name, logger)
- if should_use_incremental_field
- else None
- )
+ # Resolve PKs before the projection so probe/sample queries match the streaming SELECT.
+ if primary_keys is None and "id" in full_table:
+ primary_keys = ["id"]
+
+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
+ table = project_arrow_columns(full_table, projected)
+ arrow_schema = table.to_arrow_schema()
+ logger.debug(f"Source schema: {arrow_schema}")
+
+ inner_query, inner_query_args = _build_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ row_filters=row_filters,
+ )
+
+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)
+ chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)
+ partition_settings = (
+ self.get_partition_settings(cursor, schema, table_name, logger)
+ if should_use_incremental_field
+ else None
+ )
+ return primary_keys, arrow_schema, chunk_size, partition_settings, rows_to_sync
+
+ # A PlanetScale/Vitess tablet can be momentarily unavailable even once the vtgate
+ # handshake succeeds, so retry the whole metadata-discovery block (reopening the
+ # connection) on a transient `code = Unavailable` rather than failing setup on the
+ # first blip — see `_retry_on_transient_tablet_unavailable`.
+ primary_keys, arrow_schema, chunk_size, partition_settings, rows_to_sync = (
+ _retry_on_transient_tablet_unavailable(_discover_metadata, logger)
+ )
def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:
"""Open a fresh connection and stream rows.
diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
index 61b322b32f90..28e32aa24c23 100644
--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -21,7 +21,9 @@ from posthog.temporal.data_imports.sources.mysql.mysql import (
_build_query,
_is_bad_plan_error,
_is_transient_connect_drop,
+ _is_transient_tablet_unavailable,
_release_streaming_cursor,
+ _retry_on_transient_tablet_unavailable,
_safe_convert_date,
_safe_convert_datetime,
_sanitize_identifier,
@@ -933,6 +935,89 @@ class TestConnectTransientRetry:
sleep.assert_not_called()
+class TestIsTransientTabletUnavailable:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ # The shape Vitess/PlanetScale vtgate surfaces when a backend tablet is briefly
+ # unreachable (failover/restart) — the target keyspace, host, and port vary, the
+ # `code = Unavailable` gRPC token is the stable signal.
+ "unknown: target: keyspace.-.primary: vttablet: rpc error: code = Unavailable "
+ 'desc = connection error: desc = "transport: Error while dialing: dial tcp '
+ '0.0.0.0:0: connect: connection refused"',
+ "vttablet: rpc error: code = Unavailable desc = node is shutting down",
+ ],
+ )
+ def test_matches_grpc_unavailable(self, message):
+ assert _is_transient_tablet_unavailable(pymysql.err.OperationalError(1105, message))
+
+ @pytest.mark.parametrize(
+ "code,message",
+ [
+ # Other gRPC statuses ride the same 1105 ER_UNKNOWN_ERROR catch-all but are not the
+ # transient "tablet briefly down" class, so they must not be absorbed here.
+ (1105, "vttablet: rpc error: code = InvalidArgument desc = some bad request"),
+ (1105, "vttablet: rpc error: code = ResourceExhausted desc = grpc: trying to send too large"),
+ # Config/credential errors stay untouched.
+ (1045, "Access denied for user"),
+ (2003, "Can't connect to MySQL server on 'db.example.com'"),
+ ],
+ )
+ def test_does_not_match_non_unavailable_errors(self, code, message):
+ assert not _is_transient_tablet_unavailable(pymysql.err.OperationalError(code, message))
+
+ def test_does_not_match_error_without_args(self):
+ assert not _is_transient_tablet_unavailable(pymysql.err.OperationalError())
+
+ def test_does_not_match_non_operational_error(self):
+ assert not _is_transient_tablet_unavailable(ValueError("code = Unavailable"))
+
+
+class TestRetryOnTransientTabletUnavailable:
+ @staticmethod
+ def _unavailable() -> pymysql.err.OperationalError:
+ return pymysql.err.OperationalError(
+ 1105,
+ "unknown: target: keyspace.-.primary: vttablet: rpc error: code = Unavailable "
+ 'desc = connection error: desc = "transport: Error while dialing: connect: connection refused"',
+ )
+
+ @pytest.mark.parametrize(
+ "fail_count,expected_sleeps",
+ [
+ (1, [2]),
+ (3, [2, 4, 6]),
+ ],
+ )
+ def test_retries_then_succeeds(self, mocker, fail_count, expected_sleeps):
+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ operation = MagicMock(side_effect=[self._unavailable()] * fail_count + ["ok"])
+
+ assert _retry_on_transient_tablet_unavailable(operation, MagicMock()) == "ok"
+
+ assert operation.call_count == fail_count + 1
+ assert [c.args[0] for c in sleep.call_args_list] == expected_sleeps
+
+ def test_gives_up_after_max_attempts(self, mocker):
+ mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ operation = MagicMock(side_effect=self._unavailable())
+
+ with pytest.raises(pymysql.err.OperationalError):
+ _retry_on_transient_tablet_unavailable(operation, MagicMock())
+
+ assert operation.call_count == _MAX_CONNECT_ATTEMPTS
+
+ def test_does_not_retry_non_transient_error(self, mocker):
+ sleep = mocker.patch("posthog.temporal.data_imports.sources.mysql.mysql.time.sleep")
+ operation = MagicMock(side_effect=pymysql.err.OperationalError(1045, "Access denied for user"))
+
+ with pytest.raises(pymysql.err.OperationalError):
+ _retry_on_transient_tablet_unavailable(operation, MagicMock())
+
+ assert operation.call_count == 1
+ sleep.assert_not_called()
+
+
class TestBuildQueryForceIndex:
def test_force_index_hint_omitted_by_default(self):
query, _ = _build_query(