Skip to content

: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.

fix(postgres): give accurate diagnosis for invalid SSL negotiation response (#64612)

Tom Owers1d830dcd3550
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 08af8059658e..a21ec4f86483 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -383,6 +383,18 @@ def _is_options_startup_param_unsupported(error: BaseException) -> bool:
return any(substring in message for substring in _OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS)
+# libpq reports a non-'S'/'N' byte to its SSLRequest packet as "received invalid response to SSL
+# negotiation: <byte>". The handshake mentions SSL, but the cause is that the host/port doesn't
+# reach a PostgreSQL server speaking the SSL protocol — a wrong port, an HTTP/proxy/edge endpoint,
+# or a TCP proxy fronting a paused/deleted database. Don't mislabel it "SSL not supported": let the
+# raw message reach `get_non_retryable_errors` for an accurate, non-retryable diagnosis.
+_INVALID_SSL_NEGOTIATION_RESPONSE_SUBSTRING = "received invalid response to ssl negotiation"
+
+
+def _is_invalid_ssl_negotiation_response(error: BaseException) -> bool:
+ return _INVALID_SSL_NEGOTIATION_RESPONSE_SUBSTRING in " ".join(str(arg) for arg in error.args).lower()
+
+
def _connect_with_options_fallback(**connect_kwargs: Any) -> psycopg.Connection:
"""`psycopg.connect` that retries without the libpq `options` startup parameter when the
server rejects it.
@@ -440,7 +452,7 @@ def _connect_to_postgres(
**kwargs,
)
except psycopg.OperationalError as e:
- if require_ssl and "SSL" in str(e):
+ if require_ssl and "SSL" in str(e) and not _is_invalid_ssl_negotiation_response(e):
raise SSLRequiredError(
"SSL/TLS connection is required but your database does not support it. "
"Please enable SSL/TLS on your PostgreSQL server or contact your database administrator."
@@ -2192,7 +2204,7 @@ def postgres_source(
options=FORCE_UTF8_CLIENT_ENCODING,
)
except psycopg.OperationalError as e:
- if require_ssl and "SSL" in str(e):
+ if require_ssl and "SSL" in str(e) and not _is_invalid_ssl_negotiation_response(e):
raise SSLRequiredError(
"SSL/TLS connection is required but your database does not support it. "
"Please enable SSL/TLS on your PostgreSQL server or contact your database administrator."
@@ -2478,7 +2490,7 @@ def postgres_source(
options=FORCE_UTF8_CLIENT_ENCODING,
)
except psycopg.OperationalError as e:
- if require_ssl and "SSL" in str(e):
+ if require_ssl and "SSL" in str(e) and not _is_invalid_ssl_negotiation_response(e):
raise SSLRequiredError(
"SSL/TLS connection is required but your database does not support it. "
"Please enable SSL/TLS on your PostgreSQL server or contact your database administrator."
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index 2fa27fcb2343..fd5af3b8085c 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -72,6 +72,11 @@ PostgresErrors = {
"the database system is starting up": "Your database is starting up or recovering. Wait a moment and try again.",
"SSL/TLS connection is required": "SSL/TLS connection is required but your database does not support it. Please enable SSL/TLS on your PostgreSQL server.",
"server does not support SSL, but SSL was required": "SSL/TLS connection is required but your database does not support it. Please enable SSL/TLS on your PostgreSQL server.",
+ # An invalid SSL-negotiation response means the host/port isn't a PostgreSQL server speaking SSL
+ # (wrong port, an HTTP/proxy/edge endpoint, or a TCP proxy fronting a paused/deleted database).
+ # Map it to an actionable message so validation stops surfacing this expected user/upstream
+ # condition as captured error noise. See `get_non_retryable_errors` for the streaming-path twin.
+ "received invalid response to SSL negotiation": "PostHog reached the host and port you configured, but the server didn't respond like a PostgreSQL server speaking SSL. Check that the host and port point at your PostgreSQL server (not an HTTP, proxy, or edge endpoint) and that the database is running.",
"SSL connection has been closed unexpectedly": "The SSL/TLS connection to your database was closed unexpectedly. Check your database's SSL configuration and that the port is correct.",
# libpq reports a server-side socket close during the startup handshake with this wording. During
# credential validation it almost always means the host/port points at something that isn't (or
@@ -321,6 +326,22 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
"speaking TLS (for example an HTTP, proxy, or edge endpoint, or the wrong port). "
"Check your host and port, then re-enable the sync."
),
+ # libpq emits "received invalid response to SSL negotiation: <byte>" when the server
+ # answers its SSLRequest with a byte that isn't 'S'/'N'. In practice the configured
+ # host/port isn't a PostgreSQL server speaking SSL — an HTTP/proxy/edge endpoint, the
+ # wrong port, or a TCP proxy fronting a paused/deleted database — so retrying re-runs
+ # into the same wall. Surfaced raw on both require_ssl paths (postgres.py deliberately
+ # does NOT wrap it as SSLRequiredError, whose "enable SSL" message would be misleading).
+ # Placed before the generic SSL entries so its accurate message wins. The volatile
+ # trailing byte is excluded from the match.
+ "received invalid response to SSL negotiation": (
+ "PostHog reached the host and port you configured, but the server didn't respond "
+ 'like a PostgreSQL server during the SSL handshake ("received invalid response to '
+ "SSL negotiation\"). This usually means the host and port don't point at a "
+ "PostgreSQL server speaking SSL — for example an HTTP, proxy, or edge endpoint, the "
+ "wrong port, or a database that's paused or deleted behind a TCP proxy. Check your "
+ "host and port, then re-enable the sync."
+ ),
"SSLRequiredError": None,
"SSL/TLS connection is required": None,
"Could not establish session to SSH gateway": None,
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 44fcfc116c6f..3af6269d448f 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -56,6 +56,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
SafeTimestampLoader,
SafeTimestamptzLoader,
SafeTimetzLoader,
+ SSLRequiredError,
_build_count_query,
_build_query,
_connect_to_postgres,
@@ -71,6 +72,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (
_get_table_chunk_size,
_has_duplicate_primary_keys,
_is_connection_dropped_error,
+ _is_invalid_ssl_negotiation_response,
_is_options_startup_param_unsupported,
_is_partitioned_table,
_is_read_replica,
@@ -312,6 +314,32 @@ class TestPostgresSourceNonRetryableErrors:
assert friendly, "TLS ALPN rejection error should surface an actionable message"
assert "host and port" in friendly[0]
+ @pytest.mark.parametrize(
+ "error_msg",
+ [
+ # Raw psycopg message (what the activity-level check sees via str(e)). The host/IP, port,
+ # and trailing response byte are volatile; the negotiation text is stable.
+ 'connection failed: connection to server at "66.33.22.254", port 41667 failed: received invalid response to SSL negotiation: I',
+ 'connection failed: connection to server at "10.0.0.1", port 5432 failed: received invalid response to SSL negotiation: H',
+ # Temporal-wrapped message (what the workflow-level check sees) — carries the class name.
+ 'OperationalError: connection failed: connection to server at "66.33.22.254", port 41667 failed: received invalid response to SSL negotiation: I',
+ ],
+ )
+ def test_invalid_ssl_negotiation_response_is_non_retryable(self, source, error_msg):
+ non_retryable = source.get_non_retryable_errors()
+ is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
+ assert is_non_retryable, f"Invalid SSL-negotiation response should be non-retryable: {error_msg}"
+
+ def test_invalid_ssl_negotiation_response_returns_friendly_message(self, source):
+ non_retryable = source.get_non_retryable_errors()
+ error_msg = (
+ 'connection failed: connection to server at "66.33.22.254", port 41667 failed: '
+ "received invalid response to SSL negotiation: I"
+ )
+ friendly = [reason for pattern, reason in non_retryable.items() if pattern in error_msg and reason]
+ assert friendly, "Invalid SSL-negotiation response should surface an actionable message"
+ assert "host and port" in friendly[0]
+
@pytest.mark.parametrize(
"error_msg",
[
@@ -980,6 +1008,49 @@ class TestConnectOptionsStartupParamFallback:
assert exc_info.value.__context__ is None
+class TestInvalidSSLNegotiationResponse:
+ @pytest.mark.parametrize(
+ "message,expected",
+ [
+ ("received invalid response to SSL negotiation: I", True),
+ (
+ 'connection to server at "1.2.3.4", port 41667 failed: received invalid response to SSL negotiation: I',
+ True,
+ ),
+ ("server does not support SSL, but SSL was required", False),
+ ("SSL error: tlsv1 alert no application protocol", False),
+ ("password authentication failed for user", False),
+ ],
+ )
+ def test_detects_invalid_ssl_negotiation_message(self, message, expected):
+ assert _is_invalid_ssl_negotiation_response(psycopg.OperationalError(message)) is expected
+
+ def test_invalid_negotiation_is_not_wrapped_as_ssl_required(self):
+ # require_ssl=True, but the message is a wrong-port/non-Postgres signal — it must surface
+ # raw (so get_non_retryable_errors can give an accurate message), not as the misleading
+ # SSLRequiredError "enable SSL on your server".
+ connect_mock = mock.MagicMock(
+ side_effect=psycopg.OperationalError("received invalid response to SSL negotiation: I")
+ )
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect", connect_mock):
+ with pytest.raises(psycopg.OperationalError) as exc_info:
+ _connect_to_postgres(
+ host="db", port=41667, database="railway", user="postgres", password="x", require_ssl=True
+ )
+ assert not isinstance(exc_info.value, SSLRequiredError)
+ assert "received invalid response to SSL negotiation" in str(exc_info.value)
+
+ def test_genuine_unsupported_ssl_still_raises_ssl_required(self):
+ connect_mock = mock.MagicMock(
+ side_effect=psycopg.OperationalError("server does not support SSL, but SSL was required")
+ )
+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect", connect_mock):
+ with pytest.raises(SSLRequiredError):
+ _connect_to_postgres(
+ host="db", port=5432, database="db", user="postgres", password="x", require_ssl=True
+ )
+
+
class TestStatementTimeoutAsNonRetryable:
@pytest.mark.parametrize(
"should_use_incremental_field,incremental_field,expected_substr",
@@ -1439,6 +1510,14 @@ class TestValidateCredentialsErrorMapping:
"database project is paused or deleted, or the pooler username/host is wrong. Check that "
"your database is active and the connection details are correct.",
),
+ # Invalid SSL-negotiation response — the host/port isn't a Postgres server speaking SSL.
+ (
+ 'connection failed: connection to server at "66.33.22.254", port 41667 failed: '
+ "received invalid response to SSL negotiation: I",
+ "PostHog reached the host and port you configured, but the server didn't respond like a "
+ "PostgreSQL server speaking SSL. Check that the host and port point at your PostgreSQL server "
+ "(not an HTTP, proxy, or edge endpoint) and that the database is running.",
+ ),
# Unmapped errors fall back to the generic message.
(
"some brand new failure",