: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): don't drain streaming cursor on early teardown (#63061)
Tom Owerse23d362a1dee
diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.pyindex 32dacf6eb4f2..12575f040396 100644--- a/posthog/temporal/data_imports/sources/mysql/mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py@@ -206,6 +206,26 @@ def _is_bad_plan_timeout(e: pymysql.err.OperationalError) -> bool:return code == _LOST_CONNECTION_DURING_QUERY_CODE+def _release_streaming_cursor(cursor: SSCursor) -> None:+ """Detach an unbuffered cursor from its connection without draining it.++ PyMySQL's `SSCursor.close()` (and its `__del__`) finishes the unbuffered+ query by reading every outstanding row packet from the server via+ `_finish_unbuffered_query`. When we abandon a stream early — a cancelled+ Temporal activity injects `GeneratorExit`, or the FORCE INDEX fallback+ restarts the query — that drain runs against a connection that is already+ going away and raises `OperationalError(2013, 'Lost connection to MySQL+ server during query')` from inside the teardown path, masking the real+ reason iteration stopped. Clearing the connection reference is exactly what+ PyMySQL does once a query is fully consumed, so the cursor's later+ `close`/`__del__` becomes a no-op and the owning `with self.connect(...)`+ block closes the socket cleanly.+ """+ # PyMySQL clears this same attribute once a query is fully consumed; the+ # stub types it non-optional, so we mirror that runtime behaviour here.+ cursor.connection = None # type: ignore[assignment] # ty: ignore[invalid-assignment]++class MySQLColumn(Column):"""`Column` for a MySQL source — carries enough type info to build a PyArrow field.@@ -786,7 +806,8 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con)except Exception as e:logger.warning(f"Failed to set session timeouts on MySQL sync connection: {e}")- with streaming_connection.cursor(SSCursor) as ss_cursor:+ ss_cursor = streaming_connection.cursor(SSCursor)+ try:query, args = _build_query(schema,table_name,@@ -819,6 +840,12 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conbreakyield table_from_iterator((dict(zip(column_names, row)) for row in batch), arrow_schema)+ finally:+ # Tear the streaming cursor down without draining the rest of+ # the unbuffered result set — see `_release_streaming_cursor`.+ # Closing it normally here would reissue the lost-connection+ # error over a cancellation or the FORCE INDEX restart.+ _release_streaming_cursor(ss_cursor)def get_rows() -> Iterator[Any]:# Track whether any batch reached the pipeline. If one did,diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex 6e9ba1f36e63..b1d44ef52337 100644--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -1,4 +1,6 @@import datetime+from collections.abc import Generator+from typing import castimport pytestfrom unittest.mock import MagicMock@@ -14,6 +16,7 @@ from posthog.temporal.data_imports.sources.mysql.mysql import (MySQLImplementation,_build_query,_is_bad_plan_timeout,+ _release_streaming_cursor,_safe_convert_date,_safe_convert_datetime,_sanitize_identifier,@@ -584,6 +587,54 @@ class TestStreamingConnectionTimeouts:assert ss_cursor.execute.called+class TestReleaseStreamingCursor:+ def test_detaches_cursor_without_closing(self):+ cursor = MagicMock()+ _release_streaming_cursor(cursor)+ assert cursor.connection is None+ cursor.close.assert_not_called()+++class TestStreamingCursorTeardown:+ """The streaming SSCursor must be torn down without draining its unbuffered+ result set, so an early exit can't resurface a lost-connection error over+ the real reason iteration stopped."""++ def test_early_close_does_not_drain_or_raise(self, build_pipeline_mocks):+ _, _, ss_cursor = build_pipeline_mocks+ # Every fetch returns a row, so the generator stays suspended at a yield+ # until we close it — mimicking a sync cancelled mid-stream.+ ss_cursor.fetchmany.return_value = [(1,)]+ ss_cursor.close.side_effect = pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query")++ source = MySQLImplementation().build_pipeline(_make_config(), _make_inputs())+ # MySQL source is always sync, so items() yields a plain generator.+ rows = cast(Generator, source.items())+ next(rows) # pull the first batch, suspend at the yield++ # A cancelled activity closes the generator early — this must not raise.+ rows.close()++ ss_cursor.close.assert_not_called()+ assert ss_cursor.connection is None++ def test_midstream_error_propagates_without_draining(self, build_pipeline_mocks):+ _, _, ss_cursor = build_pipeline_mocks+ # First fetch yields a batch, the second loses the connection mid-stream.+ ss_cursor.fetchmany.side_effect = [+ [(1,)],+ pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"),+ ]+ ss_cursor.close.side_effect = AssertionError("cursor must not be drained on teardown")++ source = MySQLImplementation().build_pipeline(_make_config(), _make_inputs())+ with pytest.raises(pymysql.err.OperationalError):+ list(source.items()) # type: ignore[arg-type] # MySQL source is always sync++ ss_cursor.close.assert_not_called()+ assert ss_cursor.connection is None++class TestIsBadPlanTimeout:def test_matches_error_2013(self):assert _is_bad_plan_timeout(pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query"))