: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(postgres): treat SSH handshake EOF as non-retryable (#66310)
Tom Owers714dc6747561
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex 87731a875587..dc88b734b123 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -6,7 +6,7 @@ import timeimport collectionsimport dataclassesfrom collections.abc import Callable, Iterator-from contextlib import _GeneratorContextManager, contextmanager+from contextlib import ExitStack, _GeneratorContextManager, contextmanagerfrom datetime import (UTC,date,@@ -2461,6 +2461,33 @@ def _project_table_columns(return Table(name=table.name, parents=table.parents, columns=filtered, type=table.type, alias=table.alias)+# 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. `_tunnel_with_handshake_translation`+# turns it into this stable, classifiable message (see `PostgresSource.get_non_retryable_errors`) —+# same gateway-configuration class as a wrapped "Could not establish session to SSH gateway".+_SSH_HANDSHAKE_EOF_ERROR = "SSH gateway closed the connection during the SSH handshake"+++@contextmanager+def _tunnel_with_handshake_translation(+ tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],+) -> Iterator[tuple[str, int]]:+ """Enter `tunnel()`, translating a bare paramiko handshake EOFError into a classifiable message.++ The `yield` sits outside the `except` so a failure raised by the body can never be+ misattributed to the tunnel handshake.+ """+ with ExitStack() as stack:+ try:+ host, port = stack.enter_context(tunnel())+ except EOFError as e:+ raise Exception(_SSH_HANDSHAKE_EOF_ERROR) from e+ yield host, port++def postgres_source(tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],user: str,@@ -2490,7 +2517,7 @@ def postgres_source(effective_sslmode = _get_sslmode(require_ssl)- with tunnel() as (host, port):+ with _tunnel_with_handshake_translation(tunnel) as (host, port):def _open_setup_connection() -> psycopg.Connection:try:@@ -2807,7 +2834,7 @@ def postgres_source(# The forced `_ph_xmin` projection isn't part of the discovered columns, so add it to# the Arrow schema (as the leading field, matching the SELECT) for a clean zip.arrow_schema = arrow_schema.insert(0, pa.field(XMIN_PROJECTED_COLUMN, pa.int64(), nullable=False))- with tunnel() as (host, port):+ with _tunnel_with_handshake_translation(tunnel) as (host, port):cursor_factory = psycopg.ServerCursor if not using_read_replica else Nonedef get_connection():diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex d0bf1df656db..1c4b82a44988 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdrop_slot_and_publication,)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (+ _SSH_HANDSHAKE_EOF_ERROR,PostgresImplementation,SSLRequiredError,_rls_active_from_conn,@@ -405,6 +406,18 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa"SSLRequiredError": None,"SSL/TLS connection is required": None,"Could not establish session to SSH gateway": None,+ # 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. `postgres_source` 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 by `SSHTunnel.get_tunnel` when `is_auth_valid()` fails — the SSH tunnel private# key can't be parsed, or password auth is missing a username/password. The auth config# is fixed, so retrying just replays the same invalid credentials. The streaming pathdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex 2a43994510a2..0879ba9c63a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -1,4 +1,4 @@-from collections.abc import Iterable+from collections.abc import Iterable, Iteratorfrom contextlib import contextmanagerfrom datetime import UTC, date, datetime, time, timedelta, timezonefrom typing import Any, cast@@ -53,6 +53,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_MAX_SETUP_CONNECTION_DROPPED_RETRIES,_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,_MIN_RECOVERY_CONFLICT_CHUNK_SIZE,+ _SSH_HANDSHAKE_EOF_ERROR,FORCE_UTF8_CLIENT_ENCODING,METADATA_STATEMENT_TIMEOUT_MS,SSL_REQUIRED_AFTER_DATE,@@ -101,6 +102,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p_safe_close_connection,_schemas_from_conn,_statement_timeout_as_non_retryable,+ _tunnel_with_handshake_translation,_xmin_capable_tables_from_conn,filter_postgres_incremental_fields,get_foreign_keys,@@ -787,6 +789,48 @@ class TestPostgresSourceNonRetryableErrors:assert "QueryTimeoutException" not in matching_keysassert "has an appropriate index" in matching_keys+ def test_ssh_handshake_eof_is_non_retryable(self, source):+ # `_tunnel_with_handshake_translation` turns paramiko's bare, empty-message handshake+ # EOFError into this stable message; without the entry it would match no rule and retry forever.+ 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}"+++def _raise_eof() -> None:+ # Indirection so the `yield` below stays reachable under mypy's warn_unreachable — at runtime+ # this raises before the generator yields, standing in for paramiko's handshake EOFError.+ raise EOFError()+++@contextmanager+def _handshake_eof_tunnel() -> Iterator[tuple[str, int]]:+ _raise_eof()+ yield ("127.0.0.1", 5432)+++@contextmanager+def _body_eof_tunnel() -> Iterator[tuple[str, int]]:+ yield ("127.0.0.1", 5432)+++class TestTunnelWithHandshakeTranslation:+ def test_bare_handshake_eof_is_translated_with_cause(self):+ # The translated message (verified non-retryable in `test_ssh_handshake_eof_is_non_retryable`)+ # replaces the bare EOFError while preserving it as the cause.+ with pytest.raises(Exception, match=_SSH_HANDSHAKE_EOF_ERROR) as exc_info:+ with _tunnel_with_handshake_translation(_handshake_eof_tunnel):+ pass++ assert isinstance(exc_info.value.__cause__, EOFError)++ def test_body_eof_is_not_translated(self):+ # A failure raised by the body (not the handshake) must surface as the original EOFError,+ # never the translated handshake message — guards the `yield`-outside-`except` invariant.+ with pytest.raises(EOFError):+ with _tunnel_with_handshake_translation(_body_eof_tunnel):+ raise EOFError()+class TestPostgresSourceSetupRecoveryConflictRetry:@staticmethod