: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 CDC slot recreation on transient connection drops (#69097)
Tom Owersd3e8dfff7adc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.pyindex c9de5120cbea..f8d9ccacd212 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/adapter.py@@ -7,6 +7,8 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import TYPE_CHECKING, Any, Literal+import structlog+from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import cdc_error_infofrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.errors import (@@ -29,7 +31,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cremove_table_from_publication,slot_exists,)-from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import source_requires_ssl+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (+ _retry_on_connection_dropped,+ source_requires_ssl,+)if TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -37,6 +42,7 @@ if TYPE_CHECKING:from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCStreamReaderlogger = logging.getLogger(__name__)+_retry_logger = structlog.get_logger(__name__)def _split_qualified_table(qualified: str, default_schema: str) -> tuple[str, str]:@@ -135,22 +141,31 @@ class PostgresCDCAdapter:raise RuntimeError("Cannot recreate CDC replication slot: no slot name configured for this source")default_schema = self._resolve_schema(source)- with cdc_pg_connection(source) as conn:- drop_slot(conn, cdc_config.slot_name)- if cdc_config.publication_name and not publication_exists(conn, cdc_config.publication_name):- if cdc_config.management_mode != "posthog":- raise RuntimeError(- f"Publication '{cdc_config.publication_name}' does not exist on the source database. "- "Recreate it (see the CDC setup instructions), then resync the source."++ def _recreate() -> str:+ with cdc_pg_connection(source) as conn:+ drop_slot(conn, cdc_config.slot_name)+ if cdc_config.publication_name and not publication_exists(conn, cdc_config.publication_name):+ if cdc_config.management_mode != "posthog":+ raise RuntimeError(+ f"Publication '{cdc_config.publication_name}' does not exist on the source database. "+ "Recreate it (see the CDC setup instructions), then resync the source."+ )+ return create_slot_and_publication(+ conn,+ cdc_config.slot_name,+ cdc_config.publication_name,+ tables=[_split_qualified_table(t, default_schema) for t in tables],)- consistent_point = create_slot_and_publication(- conn,- cdc_config.slot_name,- cdc_config.publication_name,- tables=[_split_qualified_table(t, default_schema) for t in tables],- )- else:- consistent_point = create_slot(conn, cdc_config.slot_name)+ return create_slot(conn, cdc_config.slot_name)++ # Recovery reconnects and reruns DDL on a source that just dropped our streaming+ # connection (the slot invalidation that triggered recovery), so a transient drop+ # mid-recreate — the server terminating our backend on a deploy/failover, an idle cull —+ # is likely. drop_slot runs first on every attempt, so retrying is idempotent; absorb the+ # drop in-process instead of failing the whole recovery. Permanent errors (auth, a missing+ # customer-owned publication) don't match the predicate and re-raise immediately.+ consistent_point = _retry_on_connection_dropped(_recreate, _retry_logger)return {"cdc_consistent_point": consistent_point}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.pyindex 156f9d0995e4..c07b5ead6ccf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_adapter.py@@ -3,9 +3,12 @@ import uuidimport pytestfrom unittest.mock import MagicMock, patch+import psycopg.errors+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapter_ADAPTER = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter"+_POSTGRES = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres"def _source(**cdc_overrides):@@ -250,6 +253,33 @@ class TestRecreateSlot:with pytest.raises(RuntimeError, match="no slot name"):PostgresCDCAdapter().recreate_slot(source, tables=[])+ @patch(f"{_POSTGRES}.time.sleep")+ @patch(f"{_ADAPTER}.create_slot")+ @patch(f"{_ADAPTER}.publication_exists", return_value=True)+ @patch(f"{_ADAPTER}.drop_slot")+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)+ def test_retries_recreation_after_transient_connection_drop(+ self, _conn, mock_drop, _pub_exists, mock_create_slot, _sleep+ ) -> None:+ # The source terminates our backend mid-recreate (deploy/failover); recovery must reconnect+ # and retry rather than fail the whole run. drop-before-create keeps the retry idempotent.+ mock_create_slot.side_effect = [+ psycopg.errors.AdminShutdown("terminating connection due to administrator command"),+ "0/CC",+ ]+ source = _source(+ cdc_enabled=True,+ cdc_management_mode="posthog",+ cdc_slot_name="posthog_slot",+ cdc_publication_name="posthog_pub",+ )++ fields = PostgresCDCAdapter().recreate_slot(source, tables=["users"])++ assert fields == {"cdc_consistent_point": "0/CC"}+ assert mock_create_slot.call_count == 2+ assert mock_drop.call_count == 2+class TestAlterPublicationMembership:@patch(f"{_ADAPTER}.add_table_to_publication")