: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): treat SSH handshake EOF as non-retryable (#65962)
Tom Owersaaebcfface15
diff --git a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambrindex a1c0325ab25a..0839c952c78f 100644--- a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr+++ b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr@@ -11,14 +11,6 @@OR query @? '$.** ? (@.kind == "InsightVizNode" &&(!exists(@.version) || @.version == null || @.version < 4)- )'- OR query @? '$.** ? (- @.kind == "RetentionQuery" &&- (!exists(@.version) || @.version == null || @.version < 2)- )'- OR query @? '$.** ? (- @.kind == "StickinessQuery" &&- (!exists(@.version) || @.version == null || @.version < 2))'OR query @? '$.** ? (@.kind == "TrendsQuery" &&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 41bfe4b47c49..252a06411dfc 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@@ -20,7 +20,7 @@ import timeimport datetimeimport collectionsfrom collections.abc import Callable, Iterator-from contextlib import contextmanager+from contextlib import ExitStack, contextmanagerfrom typing import Any, TypeVarfrom django.conf import settings@@ -318,6 +318,17 @@ _CANT_CONNECT_TO_SERVER_CODE = 2003# Postgres source, which retries its own "SSL connection has been closed unexpectedly" on connect._SSL_UNEXPECTED_EOF_TOKEN = "[SSL: UNEXPECTED_EOF_WHILE_READING]"+# paramiko raises a bare, message-less EOFError from `start_client` when the SSH gateway accepts+# the TCP connection but closes it during the SSH handshake — a non-SSH service on the port, a+# bastion refusing PostHog's IPs, or a proxy that resets the stream. sshtunnel doesn't wrap it+# (it only translates *auth* failures into BaseSSHTunnelForwarderError), so it escapes with an+# empty `str()`, matching no non-retryable rule and retrying forever. `connect` translates it into+# this stable, classifiable message (see `MySQLSource.get_non_retryable_errors`) — same+# gateway-configuration class as a wrapped "Could not establish session to SSH gateway" failure.+# Distinct from the `[SSL: UNEXPECTED_EOF_WHILE_READING]` token above, which is a transient drop in+# the *database* TLS handshake (deliberately kept retryable).+_SSH_HANDSHAKE_EOF_ERROR = "SSH gateway closed the connection during the SSH handshake"+def _is_transient_connect_drop(e: BaseException) -> bool:"""Return True if the connection was dropped mid-handshake — a transient blip.@@ -604,7 +615,7 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conif config.using_ssl:ssl_ca = "/etc/ssl/cert.pem" if settings.DEBUG else "/etc/ssl/certs/ca-certificates.crt"- with open_ssh_tunnel(config) as (host, port):+ with self._ssh_tunnel_endpoint(config) as (host, port):kwargs: dict[str, Any] = {"host": host,"port": port,@@ -621,6 +632,21 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conwith _connect_with_transient_retry(kwargs) as conn:yield conn+ @contextmanager+ def _ssh_tunnel_endpoint(self, config: MySQLSourceConfig) -> Iterator[tuple[str, int]]:+ """Yield the `(host, port)` to connect to, going through the SSH tunnel if configured.++ Translates a bare paramiko handshake `EOFError` into `_SSH_HANDSHAKE_EOF_ERROR`. The+ `yield` sits outside the `except` so a failure raised by the connection body can never be+ misattributed to the tunnel handshake.+ """+ with ExitStack() as stack:+ try:+ host, port = stack.enter_context(open_ssh_tunnel(config))+ except EOFError as e:+ raise Exception(_SSH_HANDSHAKE_EOF_ERROR) from e+ yield host, port+# ------------------------------------------------------------------# Listing — batch queries run once during `get_schemas`# ------------------------------------------------------------------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.pyindex 9570e5c399ad..df62fe4f592d 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@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MySQLSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (+ _SSH_HANDSHAKE_EOF_ERROR,MySQLImplementation,get_connection_metadata as get_mysql_connection_metadata,)@@ -195,6 +196,13 @@ class MySQLSource(SQLSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatabase# retrying and reporting the customer's gateway misconfig as error-tracking noise.# Postgres and MSSQL already treat this identical error as non-retryable."Could not establish session to SSH gateway": "Could not connect to your SSH tunnel. Check that the SSH host, port, and credentials are correct, the bastion host is running and reachable, and that PostHog's IP addresses are allowed through its firewall.",+ # paramiko raises a bare, message-less EOFError when the SSH gateway accepts the TCP+ # connection but drops it mid-handshake (a non-SSH service on the port, the bastion+ # refusing PostHog's IPs, a proxy resetting the stream). sshtunnel doesn't wrap it, so+ # without translation it surfaces as an empty-message crash that matches no rule and+ # retries forever. `connect` re-raises it as `_SSH_HANDSHAKE_EOF_ERROR` — same+ # gateway-configuration class as "Could not establish session to SSH gateway" above.+ _SSH_HANDSHAKE_EOF_ERROR: "Could not connect to your SSH tunnel — the gateway accepted the connection but closed it during the SSH handshake. Check that the SSH host and port point to an SSH server (not the database port), that the bastion is running and reachable, and that PostHog's IP addresses are allowed through its firewall, then re-enable the sync.",# MySQL/MariaDB error 1129 (ER_HOST_IS_BLOCKED): the server has blocked our import# host because aborted/interrupted connections from it exceeded `max_connect_errors`.# The block is server-side state that only a DB admin can clear (FLUSH HOSTS /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.pyindex d5dd67dfcd8f..9cf7095319eb 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@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sqlfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MySQLSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql import (_MAX_CONNECT_ATTEMPTS,+ _SSH_HANDSHAKE_EOF_ERROR,STATEMENT_TIMEOUT_SECONDS,MySQLColumn,MySQLImplementation,@@ -1361,6 +1362,12 @@ class TestMySQLSourceNonRetryableErrors:is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())assert is_non_retryable, f"SSH gateway failure should be non-retryable: {error_msg}"+ def test_ssh_handshake_eof_is_non_retryable(self, source):+ # `connect` translates paramiko's bare handshake EOFError into this message.+ non_retryable = source.get_non_retryable_errors()+ is_non_retryable = any(pattern in _SSH_HANDSHAKE_EOF_ERROR for pattern in non_retryable.keys())+ assert is_non_retryable, f"SSH handshake EOF should be non-retryable: {_SSH_HANDSHAKE_EOF_ERROR}"+@pytest.mark.parametrize("error_msg",[@@ -1560,3 +1567,35 @@ class TestMySQLSourceValidateCredentials:assert valid is Falseassert error is not Nonecapture.assert_called_once()+++class _RaisingTunnel:+ """Context manager whose `__enter__` raises, standing in for paramiko's handshake EOFError."""++ def __enter__(self):+ raise EOFError()++ def __exit__(self, *args):+ return False+++class TestConnectSSHTunnel:+ def test_bare_handshake_eof_is_translated_and_non_retryable(self, mocker):+ mocker.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.open_ssh_tunnel",+ return_value=_RaisingTunnel(),+ )+ mock_connect = mocker.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql.pymysql.connect"+ )++ with pytest.raises(Exception, match=_SSH_HANDSHAKE_EOF_ERROR) as exc_info:+ with MySQLImplementation().connect(_make_config()):+ pass++ # Cause preserved, the database connection is never attempted, and the translated+ # message is classified non-retryable so the sync stops instead of retrying forever.+ assert isinstance(exc_info.value.__cause__, EOFError)+ mock_connect.assert_not_called()+ non_retryable = MySQLSource().get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in non_retryable.keys())