: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(data-warehouse): gate CDC source setup and per-table PK (#60274)
Daniel RC0e72979a54e2
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex 8c970525f65b..9929360f6890 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -419,6 +419,18 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):cdc_table_mode = data.get("cdc_table_mode")if cdc_table_mode in ("consolidated", "cdc_only", "both"):payload["cdc_table_mode"] = cdc_table_mode++ # CDC needs a PK for UPDATE/DELETE merges. Accept the caller's PK or reuse what+ # discovery already stored; refuse the switch when neither is set.+ new_pk = data.get("primary_key_columns")+ if new_pk:+ payload["primary_key_columns"] = new_pk+ elif not payload.get("primary_key_columns"):+ raise ValidationError(+ f"CDC requires a primary key on table '{instance.name}'. "+ "Provide primary_key_columns or refresh schema discovery to pick one up."+ )+validated_data["sync_type_config"] = payloadelse:# For CDC schemas where sync_type isn't being changed, still allow cdc_table_mode updates@@ -464,6 +476,20 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):if source.supports_scheduled_sync and should_sync is True and sync_type is None and instance.sync_type is None:raise ValidationError("Sync type must be set up first before enabling schema")+ # Catches a CDC schema being flipped on later when sync_type isn't changing — the+ # sync_type branch above doesn't run, so PK presence isn't enforced there.+ effective_sync_type = sync_type or instance.sync_type+ if (+ should_sync is True+ and not instance.should_sync+ and effective_sync_type == ExternalDataSchema.SyncType.CDC+ and not instance.primary_key_columns+ ):+ raise ValidationError(+ f"CDC requires a primary key on table '{instance.name}'. "+ "Add a primary key on the source table and retry."+ )+# When re-enabling a webhook schema, force a full refresh to avoid missing dataif (should_sync is Truediff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 4027b0ef2d32..f48af1819417 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -1088,12 +1088,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiaccess_method=access_method,)- # CDC: create slot + publication for PostHog-managed sources- cdc_enabled = payload.get("cdc_enabled", False) and is_cdc_enabled_for_team(self.team)- if cdc_enabled and source_type_model == ExternalDataSourceType.POSTGRES:- cdc_result = self._setup_cdc_slot(source, source_config, new_source_model, payload)- if cdc_result is not None:- return cdc_result+ # CDC is Postgres-only today — fold the source-type check in here so every downstream+ # `if cdc_enabled` block is safe without repeating it.+ cdc_enabled = (+ payload.get("cdc_enabled", False)+ and source_type_model == ExternalDataSourceType.POSTGRES+ and is_cdc_enabled_for_team(self.team)+ )source_schemas = source.get_schemas(source_config, self.team_id)if is_direct_postgres:@@ -1125,11 +1126,35 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidata={"message": "Schemas given do not exist in source"},)+ # Refuse per-schema `sync_type=cdc` when source-level CDC is off — `_setup_cdc_slot`+ # would be skipped, leaving the source with no replication slot/publication.+ if not cdc_enabled:+ cdc_schemas_in_payload = sorted(+ {+ schema["name"]+ for schema in payload_schemas+ if schema.get("sync_type") == "cdc"+ and schema.get("should_sync", False)+ and isinstance(schema.get("name"), str)+ }+ )+ if cdc_schemas_in_payload:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ "CDC must be enabled on the source before selecting it as a sync type. "+ f"The following schemas requested CDC: {', '.join(cdc_schemas_in_payload)}."+ )+ },+ )+active_schemas: list[ExternalDataSchema] = []# Pre-fetch PK column names for CDC tablespk_columns_by_table: dict[str, list[str]] = {}- if cdc_enabled and source_type_model == ExternalDataSourceType.POSTGRES:+ if cdc_enabled:cdc_table_names_by_schema: dict[str, set[str]] = {}cdc_schema_name_by_location: dict[tuple[str, str], str] = {}for schema in payload_schemas:@@ -1160,6 +1185,37 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif schema_name is not None:pk_columns_by_table[schema_name] = primary_key_columns+ # CDC needs a PK for UPDATE/DELETE merges. Refuse here so `_setup_cdc_slot` doesn't+ # create replication state on the source for a config we're about to reject.+ tables_missing_pk = sorted(+ {+ schema["name"]+ for schema in payload_schemas+ if schema.get("sync_type") == "cdc"+ and schema.get("should_sync", False)+ and isinstance(schema.get("name"), str)+ and not pk_columns_by_table.get(schema["name"])+ }+ )+ if tables_missing_pk:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ "CDC requires a primary key on each table. "+ f"The following tables have no primary key: {', '.join(tables_missing_pk)}."+ )+ },+ )++ # Slot + publication setup runs after PK validation so we don't leave replication state+ # on the source for a config we're about to refuse.+ if cdc_enabled:+ cdc_result = self._setup_cdc_slot(source, source_config, new_source_model, payload)+ if cdc_result is not None:+ return cdc_result+# Create all ExternalDataSchema objects and enable syncing for active schemasfor schema in payload_schemas:sync_type = schema.get("sync_type")diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.pyindex 6dd09593eca7..2b3570bfb639 100644--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py@@ -1,5 +1,6 @@import uuidfrom datetime import timedelta+from typing import Anyimport pytestfrom posthog.test.base import APIBaseTest@@ -320,6 +321,117 @@ class TestExternalDataSchema(APIBaseTest):assert schema.sync_type_config.get("reset_pipeline") is Noneassert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH+ @parameterized.expand(+ [+ # Stored PK from earlier discovery — reuse it; no caller override needed.+ (+ "reuses_stored_primary_key",+ {"primary_key_columns": ["id"], "schema_metadata": {}},+ None,+ status.HTTP_200_OK,+ ExternalDataSchema.SyncType.CDC,+ ["id"],+ ),+ # Caller explicitly provides PK — takes precedence over (and persists alongside)+ # whatever was stored.+ (+ "caller_override_wins",+ {"primary_key_columns": ["old"], "schema_metadata": {}},+ ["new_pk"],+ status.HTTP_200_OK,+ ExternalDataSchema.SyncType.CDC,+ ["new_pk"],+ ),+ # No stored PK, no override → refuse the switch.+ (+ "rejects_when_no_primary_key_available",+ {"schema_metadata": {}},+ None,+ status.HTTP_400_BAD_REQUEST,+ ExternalDataSchema.SyncType.FULL_REFRESH,+ None,+ ),+ ]+ )+ def test_update_schema_to_cdc(+ self,+ _name: str,+ initial_sync_type_config: dict,+ payload_pk: list[str] | None,+ expected_status: int,+ expected_sync_type: str,+ expected_pk_columns: list[str] | None,+ ):+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs={"host": "h", "port": 5432, "database": "d", "user": "u", "password": "p", "schema": "public"},+ )+ schema = ExternalDataSchema.objects.create(+ name="quotes",+ team=self.team,+ source=source,+ should_sync=False,+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type_config=initial_sync_type_config,+ )++ request_body: dict[str, Any] = {"sync_type": "cdc"}+ if payload_pk is not None:+ request_body["primary_key_columns"] = payload_pk++ with (+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.is_cdc_enabled_for_team",+ return_value=True,+ ),+ mock.patch("products.data_warehouse.backend.api.external_data_schema.trigger_external_data_workflow"),+ mock.patch(+ "products.data_warehouse.backend.api.external_data_schema.external_data_workflow_exists",+ return_value=False,+ ),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data=request_body,+ )++ assert response.status_code == expected_status, response.content+ if expected_status == status.HTTP_400_BAD_REQUEST:+ assert "primary key" in str(response.json()).lower()+ schema.refresh_from_db()+ assert schema.sync_type == expected_sync_type+ if expected_pk_columns is not None:+ assert schema.sync_type_config["primary_key_columns"] == expected_pk_columns+ assert schema.sync_type_config["cdc_mode"] == "snapshot"++ def test_update_schema_enable_should_sync_rejects_cdc_without_primary_key(self):+ # Schemas already in CDC mode with an empty primary_key_columns (created before the+ # API gate landed) must not be re-enabled until a PK is added on the source side.+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs={"host": "h", "port": 5432, "database": "d", "user": "u", "password": "p", "schema": "public"},+ )+ schema = ExternalDataSchema.objects.create(+ name="tracking_link",+ team=self.team,+ source=source,+ should_sync=False,+ sync_type=ExternalDataSchema.SyncType.CDC,+ sync_type_config={"cdc_mode": "snapshot", "primary_key_columns": []},+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}",+ data={"should_sync": True},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "primary key" in str(response.json()).lower()+ schema.refresh_from_db()+ assert schema.should_sync is False+@parameterized.expand([ExternalDataSchema.SyncType.APPEND, ExternalDataSchema.SyncType.INCREMENTAL],)@@ -1093,12 +1205,13 @@ class TestUpdateExternalDataSchema:should_sync=False,sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,sync_type_config={+ "primary_key_columns": ["id"],"schema_metadata": {"columns": [{"name": "id", "data_type": "integer", "is_nullable": False}],"foreign_keys": [],"source_schema": "analytics","source_table_name": "events",- }+ },},)diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex f15716cbf44b..3a7da33ea90b 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -2305,6 +2305,156 @@ class TestExternalDataSource(APIBaseTest):mock_add_table_to_cdc_publication.assert_called_once()assert mock_add_table_to_cdc_publication.call_args.args[1:] == ("test_pub", "analytics", "events")+ @patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)+ @patch(+ "products.data_warehouse.backend.api.external_data_source.ExternalDataSourceViewSet._add_table_to_cdc_publication"+ )+ @patch("products.data_warehouse.backend.api.external_data_source.ExternalDataSourceViewSet._setup_cdc_slot")+ @patch("posthog.temporal.data_imports.sources.postgres.postgres.get_primary_key_columns")+ @patch("posthog.temporal.data_imports.sources.postgres.cdc.slot_manager.cdc_pg_connection")+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")+ def test_create_postgres_cdc_rejects_table_without_primary_key(+ self,+ mock_get_source,+ mock_cdc_pg_connection,+ mock_get_primary_key_columns,+ mock_setup_cdc_slot,+ mock_add_table_to_cdc_publication,+ _mock_is_cdc_enabled_for_team,+ ):+ # CDC (logical replication) cannot identify rows on UPDATE/DELETE without a primary key.+ # Frontend gates on `supports_cdc`, but the backend must enforce too — direct API/MCP+ # callers, or a UI that lost track of `supports_cdc`, would otherwise create a schema+ # that enters streaming mode and breaks downstream.+ source_mock = mock_get_source.return_value+ source_mock.validate_config.return_value = (True, [])+ parsed_config = Mock()+ parsed_config.schema = "public"+ parsed_config.to_dict.return_value = {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ }+ source_mock.parse_config.return_value = parsed_config+ source_mock.validate_credentials.return_value = (True, None)+ source_mock.get_schemas.return_value = [+ SourceSchema(+ name="tracking_link",+ supports_incremental=False,+ supports_append=False,+ supports_cdc=False,+ columns=[("id", "uuid", False)],+ foreign_keys=[],+ source_schema="public",+ source_table_name="tracking_link",+ )+ ]++ mock_cdc_pg_connection.return_value.__enter__.return_value = object()+ mock_cdc_pg_connection.return_value.__exit__.return_value = None+ # Source DB reports no PK for the table.+ mock_get_primary_key_columns.return_value = {}++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Postgres",+ "created_via": "web",+ "payload": {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ "cdc_enabled": True,+ "schemas": [+ {"name": "tracking_link", "should_sync": True, "sync_type": "cdc"},+ ],+ },+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "primary key" in response.json()["message"].lower()+ assert "tracking_link" in response.json()["message"]+ # No source row left behind on validation failure.+ assert ExternalDataSource.objects.filter(team_id=self.team.pk).count() == 0+ # CDC slot setup must not run when validation rejects — otherwise we'd leave a+ # replication slot + publication on the source for a config we're about to refuse.+ mock_setup_cdc_slot.assert_not_called()+ mock_add_table_to_cdc_publication.assert_not_called()++ @patch("products.data_warehouse.backend.api.external_data_source.is_cdc_enabled_for_team", return_value=True)+ @patch("products.data_warehouse.backend.api.external_data_source.ExternalDataSourceViewSet._setup_cdc_slot")+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")+ def test_create_rejects_cdc_schemas_when_source_cdc_disabled(+ self,+ mock_get_source,+ mock_setup_cdc_slot,+ _mock_is_cdc_enabled_for_team,+ ):+ # If the user never toggled CDC on at the source-setup step, `payload.cdc_enabled` is+ # False and `_setup_cdc_slot` never runs — so no replication slot/publication exists+ # on the source. Accepting per-schema `sync_type=cdc` in that state would persist+ # broken configs (no slot, empty PKs, snapshot→streaming flip leaving everything+ # Failed). Backend must reject up front.+ source_mock = mock_get_source.return_value+ source_mock.validate_config.return_value = (True, [])+ parsed_config = Mock()+ parsed_config.schema = "public"+ parsed_config.to_dict.return_value = {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ }+ source_mock.parse_config.return_value = parsed_config+ source_mock.validate_credentials.return_value = (True, None)+ source_mock.get_schemas.return_value = [+ SourceSchema(+ name="borrower",+ supports_incremental=True,+ supports_append=True,+ supports_cdc=True,+ columns=[("id", "uuid", False)],+ foreign_keys=[],+ source_schema="public",+ source_table_name="borrower",+ )+ ]++ response = self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Postgres",+ "created_via": "web",+ "payload": {+ "host": "localhost",+ "port": 5432,+ "database": "app",+ "user": "user",+ "password": "pass",+ "schema": "public",+ # Note: no cdc_enabled flag here — source-level CDC is off.+ "schemas": [+ {"name": "borrower", "should_sync": True, "sync_type": "cdc"},+ ],+ },+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "cdc must be enabled" in response.json()["message"].lower()+ assert "borrower" in response.json()["message"]+ assert ExternalDataSource.objects.filter(team_id=self.team.pk).count() == 0+ mock_setup_cdc_slot.assert_not_called()+@parameterized.expand([# Frontend sends null when the user leaves the PK selector empty — backend fallsdiff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex d1c92e08959e..395eebcb1858 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -1349,6 +1349,15 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([getDatabaseSchemaPayload(values.source))+ // Backend `cdc_available` only reflects the team flag — clear it when the+ // user didn't toggle CDC on for this source in step 1.+ const sourceCdcEnabled = !!values.source.payload?.cdc_enabled+ if (!sourceCdcEnabled) {+ for (const schema of schemas) {+ schema.cdc_available = false+ }+ }+let showToast = falsefor (const schema of schemas) {@@ -1368,7 +1377,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([showToast = trueschema.should_sync = schema.should_sync_default ?? true- const cdcEnabled = values.source.payload?.cdc_enabled+ const cdcEnabled = sourceCdcEnabledif (cdcEnabled && schema.cdc_available) {schema.sync_type = 'cdc'} else if (schema.supports_webhooks) {