: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): drop unsupported `options` startup param for poolers (#64015)
Tom Owers11fda29c4232
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex d9ca04721531..30f8d47a9c2f 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -276,6 +276,41 @@ def _get_sslmode(require_ssl: bool) -> str:return "require" if require_ssl else "prefer"+# Transaction-mode connection poolers reject the libpq `options` startup parameter outright:+# Supabase's Supavisor (port 6543) and PgBouncer in transaction mode report "unsupported startup+# parameter: options", and AWS RDS Proxy reports "RDS Proxy currently doesn't support command-line+# options". We only send `options` to pin client_encoding=UTF8 for Redshift's legacy UNICODE alias+# (see FORCE_UTF8_CLIENT_ENCODING), and Redshift never sits behind these poolers — so when a server+# rejects `options`, dropping it and retrying is safe (UTF8 is the default client encoding for real+# Postgres). The RDS Proxy text uses a typographic apostrophe, so match the apostrophe-free tail.+_OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS = (+ "unsupported startup parameter: options",+ "support command-line options",+)+++def _is_options_startup_param_unsupported(error: BaseException) -> bool:+ if not isinstance(error, psycopg.OperationalError):+ return False+ message = " ".join(str(arg) for arg in error.args).lower()+ return any(substring in message for substring in _OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS)+++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.++ See `_OPTIONS_STARTUP_PARAM_UNSUPPORTED_SUBSTRINGS` for why transaction-mode poolers reject+ `options` and why dropping it is safe.+ """+ try:+ return psycopg.connect(**connect_kwargs)+ except psycopg.OperationalError as e:+ if connect_kwargs.get("options") and _is_options_startup_param_unsupported(e):+ return psycopg.connect(**{k: v for k, v in connect_kwargs.items() if k != "options"})+ raise++def _connect_to_postgres(*,host: str,@@ -296,7 +331,7 @@ def _connect_to_postgres(caller_options = kwargs.pop("options", None)options = f"{FORCE_UTF8_CLIENT_ENCODING} {caller_options}" if caller_options else FORCE_UTF8_CLIENT_ENCODINGtry:- return psycopg.connect(+ return _connect_with_options_fallback(host=host,port=port,dbname=database,@@ -1934,7 +1969,7 @@ def postgres_source(def _open_setup_connection() -> psycopg.Connection:try:- conn = psycopg.connect(+ conn = _connect_with_options_fallback(host=host,port=port,dbname=database,@@ -2192,7 +2227,7 @@ def postgres_source(def get_connection():try:- connection = psycopg.connect(+ connection = _connect_with_options_fallback(host=host,port=port,dbname=database,diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex 6bb005ecf7a0..448dd31ef46f 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -54,6 +54,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (_build_query,_connect_to_postgres,_connect_with_dropped_retry,+ _connect_with_options_fallback,_get_estimated_row_count_for_partitioned_table,_get_partition_settings,_get_partition_settings_for_partitioned_table,@@ -64,6 +65,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (_get_table_chunk_size,_has_duplicate_primary_keys,_is_connection_dropped_error,+ _is_options_startup_param_unsupported,_is_partitioned_table,_is_read_replica,_is_recovery_conflict_error,@@ -597,6 +599,71 @@ class TestConnectForcesUtf8ClientEncoding:assert connect_mock.call_args.kwargs["options"] == f"{FORCE_UTF8_CLIENT_ENCODING} -c statement_timeout=5000"+# Transaction-mode poolers (Supabase Supavisor on :6543, PgBouncer transaction mode, AWS RDS Proxy)+# reject the libpq `options` startup parameter we send to pin client_encoding=UTF8. When they do, we+# drop `options` and retry rather than failing the connection.+class TestConnectOptionsStartupParamFallback:+ @pytest.mark.parametrize(+ "message,expected",+ [+ (+ 'connection to server at "1.2.3.4", port 6543 failed: FATAL: unsupported startup parameter: options',+ True,+ ),+ (+ "connection failed: FATAL: Feature not supported: RDS Proxy currently "+ "doesn’t support command-line options.",+ True,+ ),+ ("password authentication failed for user", False),+ ("server closed the connection unexpectedly", False),+ ],+ )+ def test_detects_options_unsupported_message(self, message, expected):+ assert _is_options_startup_param_unsupported(psycopg.OperationalError(message)) is expected++ def test_non_operational_error_is_not_matched(self):+ assert _is_options_startup_param_unsupported(ValueError("unsupported startup parameter: options")) is False++ def test_retries_without_options_when_pooler_rejects_it(self):+ good_conn = mock.MagicMock()+ connect_mock = mock.MagicMock(+ side_effect=[+ psycopg.OperationalError("FATAL: unsupported startup parameter: options"),+ good_conn,+ ]+ )++ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect", connect_mock):+ result = _connect_with_options_fallback(host="db", options=FORCE_UTF8_CLIENT_ENCODING)++ assert result is good_conn+ assert connect_mock.call_count == 2+ # First attempt carries options, retry drops it entirely.+ assert connect_mock.call_args_list[0].kwargs["options"] == FORCE_UTF8_CLIENT_ENCODING+ assert "options" not in connect_mock.call_args_list[1].kwargs++ def test_does_not_retry_when_no_options_were_sent(self):+ connect_mock = mock.MagicMock(+ side_effect=psycopg.OperationalError("FATAL: unsupported startup parameter: options")+ )++ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect", connect_mock):+ with pytest.raises(psycopg.OperationalError):+ _connect_with_options_fallback(host="db")++ assert connect_mock.call_count == 1++ def test_unrelated_operational_error_is_not_retried(self):+ connect_mock = mock.MagicMock(side_effect=psycopg.OperationalError("password authentication failed for user"))++ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect", connect_mock):+ with pytest.raises(psycopg.OperationalError):+ _connect_with_options_fallback(host="db", options=FORCE_UTF8_CLIENT_ENCODING)++ assert connect_mock.call_count == 1++class TestStatementTimeoutAsNonRetryable:@pytest.mark.parametrize("should_use_incremental_field,incremental_field,expected_substr",