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): recover from out-of-sort-memory via FORCE INDEX fallback (#63737)

Tom Owers74925b77a19d
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.py
index 12575f040396..fab8d1b8c474 100644
--- a/posthog/temporal/data_imports/sources/mysql/mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py
@@ -8,7 +8,7 @@ thin PostHog-layer wrapper that just holds an instance and validates
credentials.
Module-level free helpers (`_build_query`, `_sanitize_identifier`,
-`_safe_convert_date`, `_safe_convert_datetime`, `_is_bad_plan_timeout`)
+`_safe_convert_date`, `_safe_convert_datetime`, `_is_bad_plan_error`)
are pure functions used by `MySQLImplementation` and exercised directly
by unit tests. They take no MySQL-driver state and are fine as
module-scope primitives.
@@ -80,6 +80,15 @@ STATEMENT_TIMEOUT_SECONDS = 600 # 10 mins
# before any rows stream back.
_LOST_CONNECTION_DURING_QUERY_CODE = 2013
+# pymysql error code for "Out of sort memory, consider increasing server sort
+# buffer size" — the same bad plan (full scan + filesort over the incremental
+# field) seen from the other side: the filesort completes its planning but the
+# server's `sort_buffer_size` is too small to hold the sort, so MySQL aborts
+# before streaming. Forcing the incremental-field index lets MySQL read rows in
+# index order and skip the filesort entirely, so the same FORCE INDEX fallback
+# resolves it.
+_OUT_OF_SORT_MEMORY_CODE = 1038
+
def _safe_convert_date(obj: Any) -> datetime.date | None:
"""Convert MySQL date, returning None for invalid dates like '0000-00-00'."""
@@ -196,14 +205,24 @@ def _build_query(
return result.sql, params
-def _is_bad_plan_timeout(e: pymysql.err.OperationalError) -> bool:
- """Return True if the error suggests we hit a bad-plan-induced query timeout.
+def _is_bad_plan_error(e: pymysql.err.OperationalError) -> bool:
+ """Return True if the error is a symptom of MySQL filesorting the incremental
+ `ORDER BY` instead of using an index — recoverable via the FORCE INDEX fallback.
+
+ Matches two codes, both signalling the optimizer picked a full scan + filesort
+ over the incremental field:
+
+ - `2013` (lost connection during query): the filesort preparation outran a
+ middlebox / server-side query timeout before any rows streamed back.
+ - `1038` (out of sort memory): the filesort itself overran the server's
+ `sort_buffer_size`.
- Narrowly matches `OperationalError(2013, ...)`. Other `OperationalError`s
- (access denied, table missing, etc.) should propagate untouched.
+ Forcing the incremental-field index makes MySQL read rows in index order and
+ skip the filesort, resolving both. Other `OperationalError`s (access denied,
+ table missing, etc.) should propagate untouched.
"""
code = e.args[0] if e.args else None
- return code == _LOST_CONNECTION_DURING_QUERY_CODE
+ return code in (_LOST_CONNECTION_DURING_QUERY_CODE, _OUT_OF_SORT_MEMORY_CODE)
def _release_streaming_cursor(cursor: SSCursor) -> None:
@@ -864,22 +883,22 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
yield chunk
return
except pymysql.err.OperationalError as e:
- if not _is_bad_plan_timeout(e):
+ if not _is_bad_plan_error(e):
raise
if yielded_any:
logger.warning(
- f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}) "
+ f"Streaming query died with a bad query plan (error {e.args[0] if e.args else '?'}) "
f"after already yielding rows — skipping FORCE INDEX fallback to avoid duplicates."
)
raise
logger.warning(
- f"Streaming query died with bad-plan timeout (error {e.args[0] if e.args else '?'}). "
+ f"Streaming query died with a bad query plan (error {e.args[0] if e.args else '?'}). "
f"Attempting FORCE INDEX fallback."
)
if not should_use_incremental_field or not incremental_field:
# Without an incremental field there's no cursor to force an index on.
logger.warning(
- "Bad-plan timeout hit, but sync has no incremental field — cannot apply FORCE INDEX fallback."
+ "Bad query plan hit, but sync has no incremental field — cannot apply FORCE INDEX fallback."
)
raise
@@ -891,13 +910,13 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con
if not force_index_name:
logger.warning(
- f"Bad-plan timeout hit and no usable index on "
+ f"Bad query plan hit and no usable index on "
f"{schema}.{table_name}.{incremental_field} — cannot apply FORCE INDEX fallback. "
f"Customer should add an index on the incremental field."
)
raise
- logger.warning(f"Retrying streaming query with FORCE INDEX ({force_index_name}) after bad-plan timeout")
+ logger.warning(f"Retrying streaming query with FORCE INDEX ({force_index_name}) after bad query plan")
yield from _stream_with_optional_force_index(force_index_name)
name = NamingConvention.normalize_identifier(table_name)
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 dd7f1f3ba77a..c2ec5bdb39e9 100644
--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py
@@ -15,7 +15,7 @@ from posthog.temporal.data_imports.sources.mysql.mysql import (
MySQLColumn,
MySQLImplementation,
_build_query,
- _is_bad_plan_timeout,
+ _is_bad_plan_error,
_release_streaming_cursor,
_safe_convert_date,
_safe_convert_datetime,
@@ -635,9 +635,16 @@ class TestStreamingCursorTeardown:
assert ss_cursor.connection is None
-class TestIsBadPlanTimeout:
+class TestIsBadPlanError:
def test_matches_error_2013(self):
- assert _is_bad_plan_timeout(pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"))
+ assert _is_bad_plan_error(pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"))
+
+ def test_matches_error_1038_out_of_sort_memory(self):
+ # Out of sort memory is the same bad plan (filesort over the incremental
+ # field) seen from the other side — the FORCE INDEX fallback resolves it.
+ assert _is_bad_plan_error(
+ pymysql.err.OperationalError(1038, "Out of sort memory, consider increasing server sort buffer size")
+ )
@pytest.mark.parametrize(
"code,message",
@@ -647,10 +654,10 @@ class TestIsBadPlanTimeout:
],
)
def test_does_not_match_other_error_codes(self, code, message):
- assert not _is_bad_plan_timeout(pymysql.err.OperationalError(code, message))
+ assert not _is_bad_plan_error(pymysql.err.OperationalError(code, message))
def test_does_not_match_error_without_args(self):
- assert not _is_bad_plan_timeout(pymysql.err.OperationalError())
+ assert not _is_bad_plan_error(pymysql.err.OperationalError())
class TestBuildQueryForceIndex: