: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): force UTF8 client encoding so UNICODE-reporting servers connect (#63777)
Tom Owers9a455cb30793
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.pyindex 2b888b988043..f384e065b281 100644--- a/posthog/temporal/data_imports/sources/postgres/postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py@@ -102,6 +102,13 @@ class SSLRequiredError(Exception):pass+# libpq connection option that pins the client encoding to UTF8. Some Postgres-wire-compatible+# engines (notably Amazon Redshift) report their `client_encoding` as the legacy alias `UNICODE`,+# which psycopg3's encoding map doesn't recognise — decoding the first query result then raises+# `NotSupportedError: codec not available in Python: 'UNICODE'`. Forcing the encoding sidesteps it.+FORCE_UTF8_CLIENT_ENCODING = "-c client_encoding=UTF8"++# Substrings PgBouncer / libpq use when the upstream backend connection died# mid-stream. We hit these when a long-running sync holds a server-side cursor# (and thus an open transaction) idle across the slow delta-merge phase and the@@ -262,6 +269,13 @@ def _connect_to_postgres(**kwargs: Any,) -> psycopg.Connection:sslmode = _get_sslmode(require_ssl)+ # Redshift (and other Postgres-wire-compatible engines) report `client_encoding` as the legacy+ # alias `UNICODE`, which psycopg3's encoding map doesn't recognise — it raises+ # `NotSupportedError: codec not available in Python: 'UNICODE'` the first time it decodes a query+ # result. Pinning the client encoding makes the server report `UTF8` instead, which psycopg maps+ # cleanly. We always force UTF8 and append any caller-supplied `options` after it.+ 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(host=host,@@ -278,6 +292,7 @@ def _connect_to_postgres(keepalives_idle=30,keepalives_interval=10,keepalives_count=5,+ options=options,**kwargs,)except psycopg.OperationalError as e:@@ -1915,6 +1930,7 @@ def postgres_source(keepalives_idle=30,keepalives_interval=10,keepalives_count=5,+ options=FORCE_UTF8_CLIENT_ENCODING,)except psycopg.OperationalError as e:if require_ssl and "SSL" in str(e):@@ -2173,6 +2189,7 @@ def postgres_source(keepalives_idle=30,keepalives_interval=10,keepalives_count=5,+ options=FORCE_UTF8_CLIENT_ENCODING,)except psycopg.OperationalError as e:if require_ssl and "SSL" in str(e):diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.pyindex af78fafa876e..9da578fa749e 100644--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py@@ -40,6 +40,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import ()from posthog.temporal.data_imports.sources.postgres.postgres import (_MAX_SETUP_RECOVERY_CONFLICT_RETRIES,+ FORCE_UTF8_CLIENT_ENCODING,SSL_REQUIRED_AFTER_DATE,JsonAsStringLoader,PostgresDiscoveredSchema,@@ -51,6 +52,7 @@ from posthog.temporal.data_imports.sources.postgres.postgres import (SafeTimestamptzLoader,_build_count_query,_build_query,+ _connect_to_postgres,_connect_with_dropped_retry,_get_estimated_row_count_for_partitioned_table,_get_partition_settings,@@ -525,6 +527,36 @@ class TestConnectWithDroppedRetry:assert connect.call_count == 3+# Redshift (and other Postgres-wire engines) report `client_encoding` as the legacy alias+# `UNICODE`, which psycopg3 can't decode — it raises `NotSupportedError: codec not available in+# Python: 'UNICODE'`. We pin the client encoding to UTF8 on connect to avoid the crash.+class TestConnectForcesUtf8ClientEncoding:+ def test_connect_pins_client_encoding_to_utf8(self):+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect") as connect_mock:+ _connect_to_postgres(+ host="redshift-cluster.example.com",+ port=5439,+ database="dev",+ user="user",+ password="password",+ )++ assert connect_mock.call_args.kwargs["options"] == FORCE_UTF8_CLIENT_ENCODING++ def test_caller_supplied_options_are_appended_after_utf8(self):+ with patch("posthog.temporal.data_imports.sources.postgres.postgres.psycopg.connect") as connect_mock:+ _connect_to_postgres(+ host="db.example.com",+ port=5432,+ database="postgres",+ user="user",+ password="password",+ options="-c statement_timeout=5000",+ )++ assert connect_mock.call_args.kwargs["options"] == f"{FORCE_UTF8_CLIENT_ENCODING} -c statement_timeout=5000"++class TestStatementTimeoutAsNonRetryable:@pytest.mark.parametrize("should_use_incremental_field,incremental_field,expected_substr",