: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(data-warehouse): limit silent waits in mysql and mssql row reads (#113556)
Tom Owersbcf9de2c95e6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.pyindex a93eaf034095..6d4d2c4389ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/deadline.py@@ -1,13 +1,21 @@+import queueimport threadingimport contextvars-from collections.abc import Callable+from collections.abc import Callable, Generator, Iteratorfrom concurrent.futures import Future-from typing import TypeVar+from typing import Any, TypeVarfrom django.db import connections_T = TypeVar("_T")+_EXHAUSTED: Any = object()++# How long the caller waits for the reader thread to close its iterator after a read that ended+# without a deadline. The close releases the connection of the read, so the caller waits for it,+# but not without limit.+ITERATOR_CLOSE_GRACE_SECONDS = 30+class DeadlineExceededError(Exception):"""The operation gave no answer before its deadline."""@@ -46,3 +54,72 @@ def run_with_deadline(operation: Callable[[], _T], *, timeout_seconds: float, thif not outcome.done():raise DeadlineExceededError(timeout_seconds)return outcome.result()+++def iterate_with_deadline(+ make_iterator: Callable[[], Iterator[_T]],+ *,+ first_item_timeout_seconds: float,+ next_item_timeout_seconds: float,+ thread_name: str,+) -> Generator[_T]:+ """Yield the items of `make_iterator()`, and raise `DeadlineExceededError` when one does not come in time.++ For a read through a driver that has no timeout of its own. The limits apply to the wait for+ one item, not to the read as a whole, so a long read that keeps giving items never reaches+ them. The first item has its own limit because it includes the connect and the query.++ The iterator runs on one daemon thread, and it advances only while the caller waits for the+ next item. Code around each `yield` of the iterator thus runs in the same order, relative to+ the caller, as it does without this wrapper.++ At a deadline the caller stops waiting, and the thread stays in its driver call. When that+ call returns, the thread closes the iterator. `make_iterator` must own every resource that+ the iterator uses.+ """+ next_requests: queue.SimpleQueue[bool] = queue.SimpleQueue()+ outcomes: queue.SimpleQueue[Future[_T]] = queue.SimpleQueue()+ context = contextvars.copy_context()++ def _read() -> None:+ iterator: Iterator[_T] | None = None+ try:+ while next_requests.get():+ outcome: Future[_T] = Future()+ try:+ if iterator is None:+ iterator = make_iterator()+ outcome.set_result(next(iterator, _EXHAUSTED))+ except BaseException as e:+ outcome.set_exception(e)+ outcomes.put(outcome)+ finally:+ close = getattr(iterator, "close", None)+ try:+ if close is not None:+ close()+ finally:+ # Django connections are per thread, and nothing else closes the ones this thread opened.+ connections.close_all()++ thread = threading.Thread(target=context.run, args=(_read,), name=thread_name, daemon=True)+ thread.start()+ abandoned = False+ timeout_seconds = first_item_timeout_seconds+ try:+ while True:+ next_requests.put(True)+ try:+ outcome = outcomes.get(timeout=timeout_seconds)+ except queue.Empty:+ abandoned = True+ raise DeadlineExceededError(timeout_seconds) from None+ item = outcome.result()+ if item is _EXHAUSTED:+ return+ yield item+ timeout_seconds = next_item_timeout_seconds+ finally:+ next_requests.put(False)+ if not abandoned:+ thread.join(ITERATOR_CLOSE_GRACE_SECONDS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.pyindex 8c108efe9c52..098884f1f540 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_deadline.py@@ -1,10 +1,12 @@import threadingimport contextvars+from collections.abc import Generator, Iteratorimport pytestfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (DeadlineExceededError,+ iterate_with_deadline,run_with_deadline,)@@ -36,3 +38,97 @@ def test_an_operation_that_hangs_raises_at_the_deadline_and_does_not_hold_the_caassert error.value.timeout_seconds == 0.05abandoned = [thread for thread in threading.enumerate() if thread.name == "hung-driver-call"]assert all(thread.daemon for thread in abandoned)+++def _iterate(make_iterator, *, first: float = 5, following: float = 5) -> Generator:+ return iterate_with_deadline(+ make_iterator, first_item_timeout_seconds=first, next_item_timeout_seconds=following, thread_name="reader"+ )+++def test_iterator_advances_only_while_the_caller_waits_for_the_next_item() -> None:+ # A read that ran ahead of the caller would stage a resume checkpoint for a batch that the+ # caller did not take yet.+ events: list[str] = []+ _REQUEST_ID.set("from-caller")++ def _read() -> Iterator[int]:+ for item in range(3):+ events.append(f"read {item} for {_REQUEST_ID.get()}")+ yield item+ events.append("end")++ for item in _iterate(_read):+ events.append(f"took {item}")++ assert events == [+ "read 0 for from-caller",+ "took 0",+ "read 1 for from-caller",+ "took 1",+ "read 2 for from-caller",+ "took 2",+ "end",+ ]+++def test_iterator_error_reaches_the_caller_after_the_items_before_it() -> None:+ def _read() -> Iterator[int]:+ yield 1+ raise TimeoutError("driver timeout")++ taken: list[int] = []+ with pytest.raises(TimeoutError, match="driver timeout"):+ for item in _iterate(_read):+ taken.append(item)++ assert taken == [1]+++ "items_before_the_hang, expected_timeout",+ [(0, 0.05), (2, 0.07)],+ ids=["first_item", "later_item"],+)+def test_a_silent_iterator_raises_at_the_deadline_and_is_closed_when_its_call_returns(+ items_before_the_hang: int, expected_timeout: float+) -> None:+ release = threading.Event()+ closed = threading.Event()++ def _read() -> Iterator[int]:+ try:+ yield from range(items_before_the_hang)+ release.wait()+ yield -1+ finally:+ closed.set()++ taken: list[int] = []+ try:+ with pytest.raises(DeadlineExceededError) as error:+ for item in _iterate(_read, first=0.05, following=0.07):+ taken.append(item)+ assert not closed.is_set()+ finally:+ release.set()++ assert taken == list(range(items_before_the_hang))+ assert error.value.timeout_seconds == expected_timeout+ assert closed.wait(5)+++def test_a_caller_that_stops_early_closes_the_iterator() -> None:+ closed = threading.Event()++ def _read() -> Iterator[int]:+ try:+ yield from range(10)+ finally:+ closed.set()++ items = _iterate(_read)+ assert next(items) == 0+ items.close()++ assert closed.is_set()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.pyindex 1c1c59699f49..8313e181d17d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/mssql.py@@ -41,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers)from products.warehouse_sources.backend.temporal.data_imports.sources.common.deadline import (DeadlineExceededError,+ iterate_with_deadline,run_with_deadline,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import open_ssh_tunnel@@ -94,10 +95,27 @@ MSSQL_LOGIN_TIMEOUT_SECONDS = 5# The longest a metadata statement waits for a lock before SQL Server ends it with error 1222. The# catalog views wait behind a schema modification lock, so an open DDL transaction on the server-# blocks them without limit. Set on the metadata connections only. The connection that reads the-# rows keeps the server default.+# blocks them without limit.MSSQL_METADATA_LOCK_TIMEOUT_MS = 60_000+# The same limit for the connection that reads the rows. The server default is to wait without+# limit, so a read behind a long transaction of the customer's workload held its worker until that+# transaction ended. It is longer than the metadata limit because a read that waits and then+# continues loses nothing, and a read that fails starts again from its last checkpoint.+MSSQL_ROW_READ_LOCK_TIMEOUT_MS = 300_000++# Client-side limits on the wait for one batch of rows. pymssql cannot limit a query on one+# connection (see the note on `dbsettime` below), so the read runs under `iterate_with_deadline`.+# The limits are on one silent wait and not on the read, so a long read that keeps returning rows+# never reaches them. The first batch includes the connect, the catalog re-read, and the query,+# which sorts the full result of an incremental read before it returns a row. Both are above+# `MSSQL_ROW_READ_LOCK_TIMEOUT_MS`, so a lock wait ends with the error of the server first.+MSSQL_FIRST_BATCH_DEADLINE_SECONDS = 1800+MSSQL_NEXT_BATCH_DEADLINE_SECONDS = 600++# Stable prefix, matched by `MSSQLSource.get_retryable_errors`.+MSSQL_ROW_READ_TIMEOUT_ERROR = "SQL Server sent no rows"+# Client-side limits on the work that runs before the first row is read. pymssql has no limit that# can do this job: its `timeout` argument calls the DB-Library function `dbsettime`, which applies# to every connection in the process, so it would also end the row read of each other MSSQL import@@ -119,6 +137,26 @@ class MSSQLMetadataTimeoutError(NonReportableError):super().__init__(f"{MSSQL_METADATA_TIMEOUT_ERROR} while PostHog {action} (waited {timeout_seconds:g} seconds)")+class MSSQLRowReadTimeoutError(Exception):+ """SQL Server sent no batch of rows before the deadline. A later attempt can succeed."""++ def __init__(self, timeout_seconds: float) -> None:+ super().__init__(f"{MSSQL_ROW_READ_TIMEOUT_ERROR} for {timeout_seconds:g} seconds, so PostHog ended the read")+++def read_rows_with_deadline(read: Callable[[], Iterator[_T]]) -> Iterator[_T]:+ """Yield the batches of `read()`, and raise `MSSQLRowReadTimeoutError` when one does not come in time."""+ try:+ yield from iterate_with_deadline(+ read,+ first_item_timeout_seconds=MSSQL_FIRST_BATCH_DEADLINE_SECONDS,+ next_item_timeout_seconds=MSSQL_NEXT_BATCH_DEADLINE_SECONDS,+ thread_name="mssql-row-read",+ )+ except DeadlineExceededError as e:+ raise MSSQLRowReadTimeoutError(e.timeout_seconds) from e++def run_metadata_with_deadline(operation: Callable[[], _T], *, action: str, timeout_seconds: float) -> _T:"""Run connect-and-read metadata work, and raise `MSSQLMetadataTimeoutError` when it hangs."""try:@@ -629,7 +667,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conconfig: MSSQLSourceConfig,*,team_id: int | None = None,- lock_timeout_ms: int | None = MSSQL_METADATA_LOCK_TIMEOUT_MS,+ lock_timeout_ms: int = MSSQL_METADATA_LOCK_TIMEOUT_MS,) -> Iterator[pymssql.Connection]:"""Open a pymssql connection for the duration of the context.@@ -637,7 +675,8 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.ConMSSQL-wide conventions: `MSSQL_LOGIN_TIMEOUT_SECONDS` login timeout.`lock_timeout_ms` limits how long each statement on this connection waits for a lock.- The default suits metadata work. Pass None for the connection that reads the rows.+ The default suits metadata work. The connection that reads the rows passes+ `MSSQL_ROW_READ_LOCK_TIMEOUT_MS`.The hostname goes to pymssql as is. `pymssql.connect` takes one `server`, which FreeTDSuses both to dial and as the login server name, so there is no way to dial a pinned@@ -654,9 +693,8 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conpassword=config.password,login_timeout=MSSQL_LOGIN_TIMEOUT_SECONDS,) as conn:- if lock_timeout_ms is not None:- with conn.cursor() as cursor:- cursor.execute(f"SET LOCK_TIMEOUT {int(lock_timeout_ms)}")+ with conn.cursor() as cursor:+ cursor.execute(f"SET LOCK_TIMEOUT {int(lock_timeout_ms)}")yield conn@contextmanager@@ -1374,7 +1412,9 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conlogger.debug(f"MSSQL incremental resume: {incremental_field} >= {resume_value}")last_value, resumed = resume_value, True- with self.connect(config, team_id=inputs.team_id, lock_timeout_ms=None) as streaming_connection:+ with self.connect(+ config, team_id=inputs.team_id, lock_timeout_ms=MSSQL_ROW_READ_LOCK_TIMEOUT_MS+ ) as streaming_connection:projection = _refreshed_projection(streaming_connection)arrow_schema = projection.table.to_arrow_schema()with streaming_connection.cursor() as cursor:@@ -1429,7 +1469,9 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conif last_key is not None:logger.debug(f"MSSQL keyset resume: {key_columns} > {last_key}")- with self.connect(config, team_id=inputs.team_id, lock_timeout_ms=None) as connection:+ with self.connect(+ config, team_id=inputs.team_id, lock_timeout_ms=MSSQL_ROW_READ_LOCK_TIMEOUT_MS+ ) as connection:# Each page is its own transaction, so the walk holds no transaction open on the# source between pages.connection.autocommit(True)@@ -1493,7 +1535,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conreturn SourceResponse(name=location.response_name,- items=items,+ items=functools.partial(read_rows_with_deadline, items),primary_keys=primary_keys,partition_count=setup.partition_settings.partition_count if setup.partition_settings else None,partition_size=setup.partition_settings.partition_size if setup.partition_settings else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.pyindex f90605ddb4cd..10db41ffb30f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/source.py@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssq_SSH_HANDSHAKE_EOF_ERROR,_TABLE_NOT_FOUND_ERROR,MSSQL_METADATA_TIMEOUT_ERROR,+ MSSQL_ROW_READ_TIMEOUT_ERROR,MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS,MSSQLImplementation,MSSQLMetadataTimeoutError,@@ -120,6 +121,10 @@ class MSSQLSource(# catalog or on the table. The lock belongs to the customer's own workload and goes# away when that transaction ends."Lock request time out period exceeded",+ # The client-side limit on the wait for one batch of rows. The server was reachable+ # and then sent nothing, so the next attempt, which continues from the last+ # checkpoint where the read has one, can succeed.+ MSSQL_ROW_READ_TIMEOUT_ERROR,}def get_non_retryable_errors(self) -> dict[str, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.pyindex ef0f7ba62196..7ecbc2b65442 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mssql/tests/test_mssql.py@@ -8,6 +8,7 @@ import pymssqlfrom products.warehouse_sources.backend.temporal.data_imports.discover_schemas_workflow import (DISCOVER_SCHEMAS_ACTIVITY_TIMEOUT,)+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errorsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Table, TableStatsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (@@ -18,10 +19,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mssql import MSSQLSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mssql.mssql import (_SSH_HANDSHAKE_EOF_ERROR,+ MSSQL_LOGIN_TIMEOUT_SECONDS,+ MSSQL_METADATA_LOCK_TIMEOUT_MS,+ MSSQL_ROW_READ_LOCK_TIMEOUT_MS,MSSQL_SCHEMA_DISCOVERY_DEADLINE_SECONDS,MSSQLColumn,MSSQLImplementation,MSSQLMetadataTimeoutError,+ MSSQLRowReadTimeoutError,_build_query,filter_mssql_incremental_fields,retry_on_deadlock,@@ -409,6 +414,11 @@ def build_pipeline_mocks(mocker):return mock_connect, streaming_cursor+def _drain_source():+ source = MSSQLImplementation().build_pipeline(_make_config(), _make_inputs())+ list(source.items()) # type: ignore[arg-type]++class TestBuildPipeline:def test_setup_that_hangs_at_connect_raises_a_non_retryable_timeout(self, build_pipeline_mocks, mocker):mock_connect, _ = build_pipeline_mocks@@ -424,6 +434,54 @@ class TestBuildPipeline:assert error_message_matches(str(error.value), MSSQLSource().get_non_retryable_errors())+ @pytest.mark.parametrize(+ "hangs_at, batches_before_the_hang",+ [("execute", 0), ("fetchmany", 0), ("fetchmany", 1)],+ ids=["query", "first_fetch", "later_fetch"],+ )+ def test_row_read_that_goes_silent_raises_a_retryable_timeout(+ self, build_pipeline_mocks, mocker, hangs_at, batches_before_the_hang+ ):+ _, streaming_cursor = build_pipeline_mocks+ release = threading.Event()+ # One full batch of the 1000 row chunk size for each batch before the hang.+ answers = [[(n,) for n in range(1000)] for _ in range(batches_before_the_hang)]++ def _answer_then_hang(*args):+ # Every connection of the fixture shares this cursor, and each one sets its lock timeout.+ if args and str(args[0]).startswith("SET LOCK_TIMEOUT"):+ return None+ return answers.pop(0) if answers else release.wait()++ getattr(streaming_cursor, hangs_at).side_effect = _answer_then_hang+ mocker.patch(f"{_MSSQL_MODULE}.MSSQL_FIRST_BATCH_DEADLINE_SECONDS", 0.05)+ mocker.patch(f"{_MSSQL_MODULE}.MSSQL_NEXT_BATCH_DEADLINE_SECONDS", 0.05)+ source = MSSQLImplementation().build_pipeline(_make_config(), _make_inputs())++ batches = []+ try:+ with pytest.raises(MSSQLRowReadTimeoutError) as error:+ for batch in source.items(): # type: ignore[union-attr]+ batches.append(batch)+ finally:+ release.set()++ assert len(batches) == batches_before_the_hang+ message = str(error.value)+ assert error_message_matches(message, MSSQLSource().get_retryable_errors())+ assert not error_message_matches(message, {**Any_Source_Errors, **MSSQLSource().get_non_retryable_errors()})++ def test_row_read_connection_limits_its_lock_wait(self, build_pipeline_mocks, mocker):+ connect = mocker.spy(MSSQLImplementation, "connect")+ _drain_source()++ # Metadata, row count, then the connection that reads the rows.+ assert [call.kwargs.get("lock_timeout_ms") for call in connect.call_args_list] == [+ None,+ None,+ MSSQL_ROW_READ_LOCK_TIMEOUT_MS,+ ]+@pytest.mark.parametrize("fails", [False, True], ids=["count_hangs", "count_connection_fails"])def test_row_count_fault_costs_the_estimate_and_not_the_import(self, build_pipeline_mocks, mocker, fails):release = threading.Event()@@ -444,6 +502,36 @@ class TestBuildPipeline:assert source.rows_to_sync == 0+class TestConnectTimeouts:+ @pytest.mark.parametrize(+ "connect_kwargs, expected_statements",+ [+ ({}, [f"SET LOCK_TIMEOUT {MSSQL_METADATA_LOCK_TIMEOUT_MS}"]),+ (+ {"lock_timeout_ms": MSSQL_ROW_READ_LOCK_TIMEOUT_MS},+ [f"SET LOCK_TIMEOUT {MSSQL_ROW_READ_LOCK_TIMEOUT_MS}"],+ ),+ ],+ ids=["metadata_connection", "row_reading_connection"],+ )+ def test_connect_limits_the_login_and_the_lock_wait_but_not_the_query(+ self, mocker, connect_kwargs, expected_statements+ ):+ mocker.patch(f"{_MSSQL_MODULE}.open_ssh_tunnel").return_value.__enter__.return_value = ("localhost", 1433)+ connection = MagicMock()+ connection.__enter__.return_value = connection+ cursor = connection.cursor.return_value.__enter__.return_value+ mock_connect = mocker.patch(f"{_MSSQL_MODULE}.pymssql.connect", return_value=connection)++ with MSSQLImplementation().connect(_make_config(), **connect_kwargs):+ pass++ assert mock_connect.call_args.kwargs["login_timeout"] == MSSQL_LOGIN_TIMEOUT_SECONDS+ # pymssql applies `timeout` to every connection in the process, the row reads included.+ assert "timeout" not in mock_connect.call_args.kwargs+ assert [call.args[0] for call in cursor.execute.call_args_list] == expected_statements++class _RaisingTunnel:"""Context manager whose `__enter__` raises, standing in for paramiko's handshake EOFError."""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 2548899e5928..10d7cde61bfb 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@@ -125,6 +125,31 @@ STATEMENT_TIMEOUT_SECONDS = 600 # 10 mins# `start_to_close_timeout` of its Temporal activity.METADATA_READ_TIMEOUT_SECONDS = 300+# PyMySQL applies `read_timeout` to each socket read, not to a statement. It is thus a limit on one+# silent wait: a read that keeps receiving rows never reaches it, and a server that goes silent+# ends with error 2013 after this long. The limits above are sized for a slow query. The ones+# below cover the two waits that those limits made too long.+#+# The TCP connect and the DNS lookup.+CONNECT_TIMEOUT_SECONDS = 10+# The server greeting and the login. Without it they wait for the read timeout of the caller, so a+# server that accepts the socket and then says nothing costs up to 10 minutes for each of the+# connect attempts.+HANDSHAKE_READ_TIMEOUT_SECONDS = 30+# One send of a statement. PyMySQL has no default, and a statement is small.+WRITE_TIMEOUT_SECONDS = 60++# TCP options that end a connection whose peer went away: a dead peer on an idle socket in about+# 80 seconds, and data that the peer never acknowledges in 60. Both stay quiet while the peer+# answers at the TCP level, so neither ends a statement that the server still works on. Each is+# set only where the platform has it.+_TCP_LIVENESS_OPTIONS: tuple[tuple[str, int], ...] = (+ ("TCP_KEEPIDLE", 30),+ ("TCP_KEEPINTVL", 10),+ ("TCP_KEEPCNT", 5),+ ("TCP_USER_TIMEOUT", 60_000),+)+# pymysql error code for "Lost connection to MySQL server during query" — the# symptom we see when the optimizer picks a bad plan (full scan + filesort) and# the filesort preparation exceeds a middlebox / server-side query timeout@@ -773,9 +798,44 @@ class _FieldCharsetResult(MySQLResult):self.converters[index] = (_field_encoding(field.charsetnr, connection_encoding), converter) # type: ignore[attr-defined]+def _set_tcp_liveness(sock: socket.socket) -> None:+ try:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)+ for name, value in _TCP_LIVENESS_OPTIONS:+ option = getattr(socket, name, None)+ if option is not None:+ sock.setsockopt(socket.IPPROTO_TCP, option, value)+ except OSError as e:+ # Best-effort: the read timeout still limits each wait on a socket that refuses an option.+ structlog.get_logger().debug("Could not set TCP liveness options on a MySQL socket", error=str(e))++class _SourceConnection(pymysql.Connection):"""A pymysql connection that reads every result through `_FieldCharsetResult`."""+ def connect(self, sock: socket.socket | None = None) -> None:+ # pymysql keeps the read timeout in a private attribute and has no setter for it.+ read_timeout: float | None = getattr(self, "_read_timeout", None)+ handshake_read_timeout = (+ HANDSHAKE_READ_TIMEOUT_SECONDS+ if read_timeout is None+ else min(read_timeout, HANDSHAKE_READ_TIMEOUT_SECONDS)+ )+ self._configured_read_timeout = read_timeout+ setattr(self, "_read_timeout", handshake_read_timeout) # noqa: B010+ try:+ super().connect(sock)+ finally:+ setattr(self, "_read_timeout", read_timeout) # noqa: B010+ _set_tcp_liveness(self._sock) # type: ignore[attr-defined]++ def _request_authentication(self) -> None:+ super()._request_authentication() # type: ignore[misc]+ # pymysql runs SET NAMES, `init_command` and the autocommit setup right after the login,+ # inside `connect`, so they get the configured limit and not the handshake limit.+ if hasattr(self, "_configured_read_timeout"):+ setattr(self, "_read_timeout", self._configured_read_timeout) # noqa: B010+def _read_query_result(self, unbuffered: bool = False) -> int:# Mirrors `pymysql.Connection._read_query_result` (1.1.1) with the result class swapped.self._result = None@@ -814,7 +874,20 @@ class _TLSRequiredConnection(_SourceConnection):"The MySQL server did not offer a TLS connection. Turn off certificate ""verification for this source, or enable TLS on the server.",)- super()._request_authentication() # type: ignore[misc]+ super()._request_authentication()+++def connection_timeouts(read_timeout: int) -> dict[str, int]:+ """The pymysql timeout arguments of every source connection.++ `read_timeout` has no default and no None on purpose: a connection without it waits on a silent+ server for as long as the socket stays open.+ """+ return {+ "connect_timeout": CONNECT_TIMEOUT_SECONDS,+ "read_timeout": read_timeout,+ "write_timeout": WRITE_TIMEOUT_SECONDS,+ }def _new_connection(kwargs: dict[str, Any], **extra: Any) -> pymysql.Connection:@@ -1193,7 +1266,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conself,config: MySQLSourceConfig,*,- read_timeout: int | None = METADATA_READ_TIMEOUT_SECONDS,+ read_timeout: int = METADATA_READ_TIMEOUT_SECONDS,autocommit: bool = False,team_id: int | None = None,) -> Iterator[pymysql.Connection]:@@ -1230,7 +1303,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con"database": config.database,"user": config.user,"password": config.password,- "connect_timeout": 10,+ **connection_timeouts(read_timeout),"ssl_ca": ssl_ca,# pymysql resolves `ssl_ca` on its own to `verify_mode=CERT_NONE`, so only an# explicit True verifies. None leaves that prior behavior untouched.@@ -1240,8 +1313,6 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Con"autocommit": autocommit,"init_command": "SET workload = 'OLAP';" if host.endswith("psdb.cloud") else None,}- if read_timeout is not None:- kwargs["read_timeout"] = read_timeoutwith _connect_with_transient_retry(kwargs, team_id) as conn:yield conndiff --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 79511a438b51..0281f472afe4 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@@ -17,6 +17,8 @@ from sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import HostNotAllowedErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import SafeSQL, Table, TableStatsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.keyset import KeysetResumeState@@ -31,9 +33,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_MAX_CONNECT_ATTEMPTS,_MYSQL_SAFE_CONVERSIONS,_SSH_HANDSHAKE_EOF_ERROR,+ CONNECT_TIMEOUT_SECONDS,+ HANDSHAKE_READ_TIMEOUT_SECONDS,METADATA_READ_TIMEOUT_SECONDS,STATEMENT_TIMEOUT_SECONDS,UNAVOIDABLE_FILESORT_LOST_CONNECTION_ERROR,+ WRITE_TIMEOUT_SECONDS,MySQLColumn,MySQLImplementation,MySQLUnavoidableFilesortError,@@ -61,12 +66,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_safe_convert_date,_safe_convert_datetime,_sanitize_identifier,+ _SourceConnection,_TLSRequiredConnection,)from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.source import (_INVALID_CREDENTIALS_ERROR,MySQLSource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.planetscale_mysql.source import (+ PlanetScaleMySQLSource,+)from products.warehouse_sources.backend.types import IncrementalFieldType# ---------------------------------------------------------------------------@@ -1042,6 +1051,82 @@ class TestStreamingConnectionTimeouts:_drain_source()assert mock_connect.call_args_list[0].kwargs["read_timeout"] == METADATA_READ_TIMEOUT_SECONDS+ def test_every_connection_limits_the_connect_and_the_write(self, build_pipeline_mocks):+ mock_connect, _, _ = build_pipeline_mocks+ _drain_source()+ for call in mock_connect.call_args_list:+ assert call.kwargs["connect_timeout"] == CONNECT_TIMEOUT_SECONDS+ assert call.kwargs["write_timeout"] == WRITE_TIMEOUT_SECONDS++ @pytest.mark.parametrize(+ "read_timeout, handshake_read_timeout",+ [(STATEMENT_TIMEOUT_SECONDS, HANDSHAKE_READ_TIMEOUT_SECONDS), (20, 20)],+ ids=["slow_query_limit_is_not_used_for_the_login", "a_shorter_limit_is_kept"],+ )+ def test_handshake_has_its_own_read_timeout(self, mocker, read_timeout, handshake_read_timeout):+ # A server that accepts the socket and never sends its greeting is retried as a transient+ # drop, so with the query limit each of those attempts waited 10 minutes.+ during_handshake: list[float] = []++ def fake_connect(self, sock=None):+ during_handshake.append(self._read_timeout)+ self._sock = sock++ mocker.patch.object(pymysql.Connection, "connect", fake_connect)+ sock = MagicMock()+ connection = _SourceConnection(defer_connect=True, read_timeout=read_timeout)++ connection.connect(sock)++ assert during_handshake == [handshake_read_timeout]+ assert connection._read_timeout == read_timeout # type: ignore[attr-defined]+ sock.setsockopt.assert_any_call(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)++ def test_connection_setup_queries_use_the_configured_read_timeout(self, mocker):+ # pymysql sends SET NAMES, `init_command` and the autocommit setup inside `connect`, after the login.+ seen: dict[str, float] = {}++ def fake_get_server_information(self):+ seen["greeting"] = self._read_timeout++ def fake_request_authentication(self):+ seen["login"] = self._read_timeout++ def fake_connect(self, sock=None):+ self._sock = sock+ self._get_server_information()+ self._request_authentication()+ seen["setup_queries"] = self._read_timeout++ mocker.patch.object(pymysql.Connection, "connect", fake_connect)+ mocker.patch.object(pymysql.Connection, "_get_server_information", fake_get_server_information)+ mocker.patch.object(pymysql.Connection, "_request_authentication", fake_request_authentication)+ connection = _SourceConnection(defer_connect=True, read_timeout=STATEMENT_TIMEOUT_SECONDS)++ connection.connect(MagicMock())++ assert seen == {+ "greeting": HANDSHAKE_READ_TIMEOUT_SECONDS,+ "login": HANDSHAKE_READ_TIMEOUT_SECONDS,+ "setup_queries": STATEMENT_TIMEOUT_SECONDS,+ }++ @pytest.mark.parametrize(+ "error, kept_out_of_error_tracking",+ [+ # pymysql's wording when a socket read reaches `read_timeout`.+ (pymysql.err.OperationalError(2013, "Lost connection to MySQL server during query (timed out)"), True),+ # pymysql's wording when a socket write reaches `write_timeout`.+ (pymysql.err.OperationalError(2006, "MySQL server has gone away (TimeoutError('timed out'))"), False),+ ],+ ids=["read_timeout", "write_timeout"],+ )+ @pytest.mark.parametrize("source_class", [MySQLSource, PlanetScaleMySQLSource])+ def test_driver_timeout_is_retryable(self, source_class, error, kept_out_of_error_tracking):+ source = source_class()+ assert error_message_matches(str(error), source.get_retryable_errors()) is kept_out_of_error_tracking+ assert not error_message_matches(str(error), {**Any_Source_Errors, **source.get_non_retryable_errors()})+def test_set_session_timeouts_are_executed(self, build_pipeline_mocks):_, setup_cursor, _ = build_pipeline_mocks_drain_source()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.pyindex 94d7a79e62a6..f518de907671 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/planetscale_mysql.py@@ -9,8 +9,10 @@ import pymysqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mysql import MySQLSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (_MYSQL_SAFE_CONVERSIONS,+ METADATA_READ_TIMEOUT_SECONDS,MySQLImplementation,_connect_with_transient_retry,+ connection_timeouts,)# Vitess' default OLTP workload caps a SELECT at 100,000 rows and aborts it after 20 seconds,@@ -31,7 +33,7 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):self,config: MySQLSourceConfig,*,- read_timeout: int | None = None,+ read_timeout: int = METADATA_READ_TIMEOUT_SECONDS,autocommit: bool = False,team_id: int | None = None,) -> Iterator[pymysql.Connection]:@@ -48,7 +50,7 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):"database": config.database,"user": config.user,"password": config.password,- "connect_timeout": 10,+ **connection_timeouts(read_timeout),"ssl_ca": ssl_ca,# PlanetScale serves a publicly trusted certificate for the connect host, so both# chain and hostname verification can be required. Without `ssl_verify_identity`@@ -64,8 +66,6 @@ class PlanetScaleMySQLImplementation(MySQLImplementation):"autocommit": autocommit,"init_command": _VITESS_OLAP_INIT_COMMAND,}- if read_timeout is not None:- kwargs["read_timeout"] = read_timeout# `ssl_verify_identity` checks the certificate against `host`, which the pinned socket# leaves as the hostname.with _connect_with_transient_retry(kwargs, team_id) as conn:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.pyindex 765a3f23c7e3..4feb44bfafc3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/planetscale_mysql/test_planetscale_mysql.py@@ -8,6 +8,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.planetscalemysql import (PlanetScaleMySQLSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (+ CONNECT_TIMEOUT_SECONDS,+ METADATA_READ_TIMEOUT_SECONDS,+ WRITE_TIMEOUT_SECONDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.planetscale_mysql.planetscale_mysql import (PlanetScaleMySQLImplementation,)@@ -75,9 +80,13 @@ def test_port_is_coerced_to_int(port):assert kwargs["port"] == 3306-def test_read_timeout_is_only_sent_when_requested():+def test_every_connection_has_a_read_timeout():+ # The metadata connections of the shared MySQL code pass no read timeout. Without a default+ # here they wait on a silent server for as long as the socket stays open.with _connect(_config()) as kwargs:- assert "read_timeout" not in kwargs+ assert kwargs["read_timeout"] == METADATA_READ_TIMEOUT_SECONDS+ assert kwargs["connect_timeout"] == CONNECT_TIMEOUT_SECONDS+ assert kwargs["write_timeout"] == WRITE_TIMEOUT_SECONDSwith _connect(_config(), read_timeout=600) as kwargs:assert kwargs["read_timeout"] == 600