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): stop retrying an unavoidable-sort lost connection (#79525)

Tom Owersf3aec6b59f01
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.py
index f64a213b725c..0792f5cc1ee0 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
@@ -104,6 +104,22 @@ _LOST_CONNECTION_DURING_QUERY_CODE = 2013
# resolves it.
_OUT_OF_SORT_MEMORY_CODE = 1038
+# Raised in place of the raw pymysql 2013 when a lost-connection bad plan can't be dodged by the
+# FORCE INDEX fallback because the incremental field has no usable index. The un-indexed full-table
+# sort re-times-out on every run, so it's deterministic — distinct from a genuine transient mid-query
+# drop, which the raw 2013 stays retryable for. `MySQLSource.get_non_retryable_errors` matches this
+# marker to pause the schema with an actionable message.
+UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR = "MySQL lost the connection during an unavoidable full-table sort"
+
+
+class MySQLUnavoidableFilesortError(Exception):
+ """A lost-connection bad plan (error 2013) the FORCE INDEX fallback can't avoid — the incremental
+ field has no usable index, so every run repeats the same doomed full-table sort."""
+
+ def __init__(self, message: str = UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR) -> None:
+ super().__init__(message)
+
+
# pymysql error code for "Can't connect to MySQL server on '...'" — raised at
# connect time when the socket connect can't be established. The parenthesised
# suffix carries the underlying cause (a timeout vs. a refused connection vs. a
@@ -1548,6 +1564,12 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
f"{schema}.{table_name}.{incremental_field} — cannot apply FORCE INDEX fallback. "
f"Customer should add an index on the incremental field."
)
+ # A lost connection here recurs every run: with no usable index the incremental
+ # sort is unavoidable and re-times-out. Re-raise it as a deterministic error so
+ # the schema is paused with guidance instead of looping. Out-of-sort-memory
+ # (1038) is already classified by its own code, so leave it raw.
+ if e.args and e.args[0] == _LOST_CONNECTION_DURING_QUERY_CODE:
+ raise MySQLUnavoidableFilesortError() from e
raise
logger.warning(f"Retrying streaming query with FORCE INDEX ({force_index_name}) after bad query plan")
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.py
index 52b615d37d31..5d8987303638 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
@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mysql import MySQLSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (
_SSH_HANDSHAKE_EOF_ERROR,
+ UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR,
MySQLImplementation,
get_connection_metadata as get_mysql_connection_metadata,
)
@@ -303,6 +304,12 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase
# locale-independent error code (the trailing message text is translated on non-English
# servers) so it catches both the raw pymysql string and the wrapped `(1038, ...)` form.
"(1038,": "Your MySQL/MariaDB server ran out of sort buffer memory while ordering this table by its incremental field (error 1038). We try to avoid the sort by forcing the incremental field's index, but this table has no usable index on that field. Add an index on the incremental field, raise the server's 'sort_buffer_size', or switch this table to a full re-sync, then resync.",
+ # MySQL/MariaDB error 2013 (lost connection during query) that escapes the in-activity
+ # FORCE INDEX fallback because the incremental field has no usable index (see
+ # `MySQLUnavoidableFilesortError` in mysql.py). The un-indexed full-table sort re-times-out
+ # every run, so it's deterministic — unlike the generic transient 2013 drop, which stays
+ # retryable. Match the stable marker, which carries no host or query text.
+ UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR: "Your MySQL/MariaDB server closed the connection while ordering this table by its incremental field (error 2013). We try to avoid the sort by forcing the incremental field's index, but this table has no usable index on that field. Add an index on the incremental field, or switch this table to a full re-sync, then resync.",
# MySQL/MariaDB error 3 (EE_WRITE): the server hit ENOSPC writing a temporary file to
# its own temp directory (e.g. `/rdsdbdata/tmp/...`) — almost always a large filesort
# spilling the `ORDER BY <incremental_field>` sort to disk. The server's temp filesystem
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.py
index 2aefb8d2c98d..fe85bce32b13 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
@@ -21,8 +21,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq
_MAX_CONNECT_ATTEMPTS,
_SSH_HANDSHAKE_EOF_ERROR,
STATEMENT_TIMEOUT_SECONDS,
+ UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR,
MySQLColumn,
MySQLImplementation,
+ MySQLUnavoidableFilesortError,
_build_query,
_is_bad_plan_error,
_is_transient_cant_create_thread,
@@ -874,6 +876,35 @@ class TestStreamingReopensDroppedConnection:
assert ss_cursor.execute.called
+class TestUnavoidableFilesortFallback:
+ """A bad-plan 2013 that the FORCE INDEX fallback can't dodge — no usable index on the
+ incremental field — is deterministic, so it must fail non-retryably instead of looping."""
+
+ def test_lost_connection_with_no_usable_index_is_non_retryable(self, build_pipeline_mocks, mocker):
+ _, _, ss_cursor = build_pipeline_mocks
+ # The streaming query dies with a bad-plan 2013 before any row streams...
+ ss_cursor.execute.side_effect = pymysql.err.OperationalError(
+ 2013, "Lost connection to MySQL server during query"
+ )
+ # ...and the incremental field has no index to force, so the sort can't be avoided.
+ mocker.patch.object(MySQLImplementation, "find_index_for_cursor", return_value=None)
+
+ source = MySQLImplementation().build_pipeline(
+ _make_config(),
+ _make_inputs(
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ incremental_field_type=IncrementalFieldType.DateTime,
+ ),
+ )
+ with pytest.raises(MySQLUnavoidableFilesortError):
+ list(source.items()) # type: ignore[arg-type] # MySQL source is always sync
+
+ # The raised marker is classified non-retryable, so the schema is paused, not looped.
+ non_retryable = MySQLSource().get_non_retryable_errors()
+ assert any(pattern in UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR for pattern in non_retryable.keys())
+
+
class TestIsBadPlanError:
def test_matches_error_2013(self):
assert _is_bad_plan_error(pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"))