: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): retry transient dropped connection on CDC connect (#63748)
Tom Owersa4ffc87f711e
diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/posthog/temporal/data_imports/sources/postgres/cdc/stream_reader.pyindex 756f4157dfb9..618e666616d7 100644--- a/posthog/temporal/data_imports/sources/postgres/cdc/stream_reader.py+++ b/posthog/temporal/data_imports/sources/postgres/cdc/stream_reader.py@@ -7,23 +7,27 @@ approach — batch reads on a schedule.from __future__ import annotations-import loggingfrom collections.abc import Iteratorfrom contextlib import AbstractContextManagerfrom dataclasses import dataclassfrom typing import TYPE_CHECKINGimport psycopg+import structlogfrom psycopg import sqlfrom posthog.temporal.data_imports.cdc.types import ChangeEventfrom posthog.temporal.data_imports.sources.postgres.cdc.decoder import PgOutputDecoder-from posthog.temporal.data_imports.sources.postgres.postgres import _connect_to_postgres, get_primary_key_columns+from posthog.temporal.data_imports.sources.postgres.postgres import (+ _connect_to_postgres,+ _connect_with_dropped_retry,+ get_primary_key_columns,+)if TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-logger = logging.getLogger(__name__)+logger = structlog.get_logger(__name__)@dataclass(frozen=True, slots=True)@@ -73,12 +77,21 @@ class PgCDCStreamReader:self._effective_host, self._effective_port = tunnel_cm.__enter__()self._tunnel_cm = tunnel_cm- self._conn = _connect_to_postgres(- host=self._effective_host,- port=self._effective_port,- database=self._params.database,- user=self._params.user,- password=self._params.password,+ # The initial connect reaches the source through the just-opened SSH tunnel /+ # connection pooler, either of which can drop the first connection with a+ # transient "server closed the connection unexpectedly". Mirror the non-CDC+ # read paths and absorb those drops in-process instead of failing the whole+ # extraction activity; permanent errors (auth, SSL-required) are re-raised+ # immediately by the helper.+ self._conn = _connect_with_dropped_retry(+ lambda: _connect_to_postgres(+ host=self._effective_host,+ port=self._effective_port,+ database=self._params.database,+ user=self._params.user,+ password=self._params.password,+ ),+ logger,)def read_changes(self) -> Iterator[ChangeEvent]:@@ -142,7 +155,7 @@ class PgCDCStreamReader:finally:advance_conn.close()- logger.info("Advanced slot %s to position %s", self._params.slot_name, position)+ logger.info("advanced_slot", slot_name=self._params.slot_name, position=position)def get_primary_key_columns(self, schema_name: str, table_names: list[str]) -> dict[str, list[str]]:"""Query information_schema for PK columns of the given tables.diff --git a/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.pynew file mode 100644index 000000000000..69851bb8eb44--- /dev/null+++ b/posthog/temporal/data_imports/sources/postgres/cdc/tests/test_stream_reader.py@@ -0,0 +1,66 @@+import pytest+from unittest import mock+from unittest.mock import patch++import psycopg++from posthog.temporal.data_imports.sources.postgres.cdc.stream_reader import PgCDCConnectionParams, PgCDCStreamReader+++def params():+ return PgCDCConnectionParams(+ host="localhost",+ port=5432,+ database="postgres",+ user="postgres",+ password="password",+ slot_name="posthog_slot",+ publication_name="posthog_pub",+ )+++class TestPgCDCStreamReaderConnect:+ def test_connect_retries_transient_dropped_connection(self, params):+ good_conn = mock.MagicMock()+ connect = mock.MagicMock(+ side_effect=[+ # The exact transient drop surfaced in production when the SSH tunnel /+ # pooler closes the first connection before it is established.+ psycopg.OperationalError("server closed the connection unexpectedly"),+ good_conn,+ ]+ )++ reader = PgCDCStreamReader(params)+ with (+ patch(+ "posthog.temporal.data_imports.sources.postgres.cdc.stream_reader._connect_to_postgres",+ connect,+ ),+ patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"),+ ):+ reader.connect()++ assert reader._conn is good_conn+ assert connect.call_count == 2++ def test_connect_does_not_retry_permanent_error(self, params):+ connect = mock.MagicMock(+ side_effect=psycopg.OperationalError(+ 'connection to server at "10.0.0.1" failed: FATAL: password authentication failed'+ )+ )++ reader = PgCDCStreamReader(params)+ with (+ patch(+ "posthog.temporal.data_imports.sources.postgres.cdc.stream_reader._connect_to_postgres",+ connect,+ ),+ patch("posthog.temporal.data_imports.sources.postgres.postgres.time.sleep"),+ ):+ with pytest.raises(psycopg.OperationalError):+ reader.connect()++ assert connect.call_count == 1