: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(mssql): treat SSH-handshake EOFError as non-retryable (#65778)
Tom Owers2731d63de7fb
diff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.pyindex 207e07167013..c2dd49f81ad3 100644--- a/posthog/temporal/data_imports/sources/mssql/mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py@@ -12,7 +12,7 @@ from __future__ import annotationsimport timeimport collectionsfrom collections.abc import Callable, Iterator-from contextlib import contextmanager+from contextlib import ExitStack, contextmanagerfrom typing import Any, TypeVarimport pyarrow as pa@@ -81,6 +81,14 @@ _MAX_DISCOVERY_CONNECTION_ATTEMPTS = 5_DEADLOCK_VICTIM_ERROR = "was deadlocked on lock resources"_MAX_DEADLOCK_ATTEMPTS = 5+# 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, so+# it escapes as an EOFError whose `str()` is empty, matching no non-retryable rule and retrying+# forever. `connect` translates it into this stable, classifiable message (see+# `MSSQLSource.get_non_retryable_errors`) — same gateway-config class as a wrapped tunnel failure.+_SSH_HANDSHAKE_EOF_ERROR = "SSH gateway closed the connection during the SSH handshake"+def _is_transient_connection_error(error: BaseException) -> bool:"""True for a mid-stream TDS connection death that a fresh connection recovers from."""@@ -344,7 +352,7 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.ConOpens the SSH tunnel (if configured) once, then connects with theMSSQL-wide conventions: 5s login timeout."""- with open_ssh_tunnel(config) as (host, port):+ with self._ssh_tunnel_endpoint(config) as (host, port):with pymssql.connect(server=host,# pymssql requires port to be str@@ -356,6 +364,21 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con) as conn:yield conn+ @contextmanager+ def _ssh_tunnel_endpoint(self, config: MSSQLSourceConfig) -> 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/posthog/temporal/data_imports/sources/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.pyindex 0718c7329a69..61674bcf233f 100644--- a/posthog/temporal/data_imports/sources/mssql/source.py+++ b/posthog/temporal/data_imports/sources/mssql/source.py@@ -18,7 +18,11 @@ from posthog.temporal.data_imports.sources.common.registry import SourceRegistryfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig-from posthog.temporal.data_imports.sources.mssql.mssql import MSSQLImplementation, retry_on_transient_connection_error+from posthog.temporal.data_imports.sources.mssql.mssql import (+ _SSH_HANDSHAKE_EOF_ERROR,+ MSSQLImplementation,+ retry_on_transient_connection_error,+)from products.data_warehouse.backend.types import ExternalDataSourceType@@ -86,6 +90,13 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabase# times across runs before giving up, so a genuinely transient gateway reboot is# absorbed. Postgres already treats 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.",# Raised from the shared `_decimal_array_from_values` fallback in# `pipelines/pipeline/utils.py` when a numeric/decimal/money value exceeds Delta# Lake's decimal budget (precision > 76 or scale > 32). Fixed source-data shape —diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.pyindex c022d4087eab..8d670f95b0cf 100644--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py@@ -8,6 +8,7 @@ from posthog.temporal.data_imports.sources.common.sql import Table, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.predicates import ColumnTypeCategory, ValidatedRowFilterfrom posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfigfrom posthog.temporal.data_imports.sources.mssql.mssql import (+ _SSH_HANDSHAKE_EOF_ERROR,MSSQLColumn,MSSQLImplementation,_build_query,@@ -518,6 +519,36 @@ class TestBuildPipeline:assert streaming_cursor.execute.called+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(+ "posthog.temporal.data_imports.sources.mssql.mssql.open_ssh_tunnel",+ return_value=_RaisingTunnel(),+ )+ mock_connect = mocker.patch("posthog.temporal.data_imports.sources.mssql.mssql.pymssql.connect")++ with pytest.raises(Exception, match=_SSH_HANDSHAKE_EOF_ERROR) as exc_info:+ with MSSQLImplementation().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 = MSSQLSource().get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in non_retryable.keys())++class TestMSSQLSourceNonRetryableErrors:@pytest.mark.parametrize("error_msg",@@ -542,6 +573,8 @@ class TestMSSQLSourceNonRetryableErrors:# Raised by the sshtunnel library when the customer's SSH bastion can't be reached# (wrong host/port, rejected key, firewall) — the import goes through `open_ssh_tunnel`."BaseSSHTunnelForwarderError: Could not establish session to SSH gateway",+ # `connect` translates paramiko's bare handshake EOFError into this message.+ _SSH_HANDSHAKE_EOF_ERROR,],)def test_connection_errors_are_non_retryable(self, error_msg):