: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): stop cdc tables from re-snapshotting on every sync (#107600)
Tom Owers6b8bc3d65c96
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex 4b7758c48774..210ec41667ba 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -17,6 +17,7 @@ _LAZY = {"draft_manifest_sync": "sources.custom.ai_builder","fetch_docs_text": "sources.custom.ai_builder","CDCSourceAdapter": "cdc.adapters",+ "add_table_failure_message": "cdc.adapters","get_cdc_adapter": "cdc.adapters","source_type_supports_cdc": "cdc.adapters","CDCRepairError": "cdc.repair",diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex e27883705aba..b8f9b8360692 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -65,6 +65,7 @@ from products.warehouse_sources.backend.facade.source_management import (RowFilterValidationError,SourceRegistry,WebhookSource,+ add_table_failure_message,filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,get_cdc_adapter,hand_reset_to_capture_if_sync_running,@@ -1082,6 +1083,16 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers_apply_primary_key_columns(data, payload, instance, "CDC")if instance.sync_type != ExternalDataSchema.SyncType.CDC:_refuse_reserved_cdc_column(instance)+ # A table joining CDC starts from a fresh snapshot, even when an earlier sync+ # method or an earlier CDC period already loaded it. The snapshot moves to+ # streaming only when initial_sync_complete goes from False to True, so a table+ # left at True repeats the full snapshot on every scheduled run. A capture+ # position from an earlier CDC period belongs to a dropped slot.+ payload["cdc_mode"] = "snapshot"+ for stale_key in ("cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY):+ payload.pop(stale_key, None)+ instance.initial_sync_complete = False+ validated_data["initial_sync_complete"] = Falsevalidated_data["sync_type_config"] = payloadelif sync_type == ExternalDataSchema.SyncType.XMIN:@@ -1567,7 +1578,12 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# Add table to capture set when enabling CDC or toggling sync onif newly_set_to_cdc or (should_sync is True and not instance.should_sync):- adapter.add_table(source, db_schema, source_table_name)+ try:+ adapter.add_table(source, db_schema, source_table_name)+ except Exception as e:+ raise ValidationError(+ add_table_failure_message(adapter, e, source, db_schema, source_table_name)+ ) from e# Capture skipped the table while it was out of the set, so its buffer has a gap. Without# the marker, capture empties the buffer before the new snapshot instead of replaying it.instance.sync_type_config.pop(CDC_SNAPSHOT_LANE_KEY, None)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex b00062c254ce..a2808648b2a2 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -62,6 +62,7 @@ from products.warehouse_sources.backend.facade.source_management import (SourceRegistry,SourceSchema,WebhookSource,+ add_table_failure_message,build_default_schemas,draft_manifest_sync,fetch_docs_text,@@ -1645,11 +1646,25 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):# guarantees non-None schema/table when it resolves above. `cast` narrows for mypy# without a runtime check. The adapter no-ops for self-managed / no-publication.if is_cdc_schema and should_sync and cdc_enabled and cdc_adapter is not None:- cdc_adapter.add_table(- new_source_model,- cast(str, metadata_source_schema),- cast(str, metadata_source_table_name),- )+ try:+ cdc_adapter.add_table(+ new_source_model,+ cast(str, metadata_source_schema),+ cast(str, metadata_source_table_name),+ )+ except Exception as e:+ message = add_table_failure_message(+ cdc_adapter,+ e,+ new_source_model,+ cast(str, metadata_source_schema),+ cast(str, metadata_source_table_name),+ )+ # A hard delete leaves no source row for the orphan-slot sweeper to find, so+ # drop the slot and publication created above before deleting the source.+ cdc_adapter.cleanup_resources(new_source_model)+ new_source_model.delete()+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": message})if direct_engine_adapter is not None and is_direct_query and should_sync:# Apply the picker's column subset on the very first DataWarehouseTable build,diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.pyindex 083e359ddca4..92fb3f027658 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/adapters.py@@ -18,6 +18,8 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar+from posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import CDCConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapterfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -143,8 +145,11 @@ class CDCSourceAdapter(Protocol[CDCConfigT_co]):...def add_table(self, source: ExternalDataSource, schema: str, table: str) -> None:- """Best-effort include a table in the change-capture set (PG: ALTER PUBLICATION ADD TABLE).- No-op when PostHog doesn't own the capture definition (e.g. self-managed)."""+ """Include a table in the change-capture set (PG: ALTER PUBLICATION ADD TABLE).+ No-op when PostHog doesn't own the capture definition (e.g. self-managed).++ Raises when the table can't be added. A CDC table outside the capture set never receives+ a change, so every sync of it repeats the full snapshot. Callers refuse the switch instead."""...def remove_table(self, source: ExternalDataSource, schema: str, table: str) -> None:@@ -207,3 +212,23 @@ def source_type_supports_cdc(source_type: ExternalDataSourceType | str | None) -except ValueError:return Falsereturn resolved in _cdc_adapters()+++def add_table_failure_message(+ adapter: CDCSourceAdapter[CDCConfig],+ exc: BaseException,+ source: ExternalDataSource,+ schema: str,+ table: str,+) -> str:+ """User-facing message for an ``add_table`` failure. Captures only the failures that+ point at a PostHog bug, because the customer fixes ownership, grants and reachability."""+ if fixable := adapter.customer_fixable_error_message(exc):+ return fixable+ if adapter.is_connection_error(exc):+ return f"Couldn't connect to your database to add {schema}.{table} to change data capture: {exc}"+ capture_exception(exc, {"source_id": str(source.id), "team_id": source.team_id})+ return (+ f"Couldn't add {schema}.{table} to change data capture: {exc} "+ "Try again, or switch this table to Incremental sync instead."+ )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 474d6d2811c2..3baef0e07467 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@@ -384,35 +384,38 @@ class PostgresCDCAdapter:}def add_table(self, source: ExternalDataSource, schema: str, table: str) -> None:- """Best-effort ALTER PUBLICATION ADD TABLE. No-op for self-managed / no publication."""+ """ALTER PUBLICATION ADD TABLE. No-op for self-managed / no publication. Raises on failure."""self._alter_publication_membership(source, schema, table, add=True)def remove_table(self, source: ExternalDataSource, schema: str, table: str) -> None:"""Best-effort ALTER PUBLICATION DROP TABLE. No-op for self-managed / no publication."""- self._alter_publication_membership(source, schema, table, add=False)-- def _alter_publication_membership(self, source: ExternalDataSource, schema: str, table: str, add: bool) -> None:- cdc_config = self.parse_cdc_config(source)- # PostHog only manages the publication in posthog-managed mode.- if cdc_config.management_mode != "posthog" or not cdc_config.publication_name:- returntry:- with cdc_pg_connection(source) as conn:- if add:- add_table_to_publication(conn, cdc_config.publication_name, schema, table)- else:- remove_table_from_publication(conn, cdc_config.publication_name, schema, table)+ self._alter_publication_membership(source, schema, table, add=False)except Exception:logger.exception(- "Failed to %s table %s.%s %s CDC publication '%s' (best-effort), source_id=%s",- "add" if add else "remove",+ "Failed to remove table %s.%s from CDC publication (best-effort), source_id=%s",schema,table,- "to" if add else "from",- cdc_config.publication_name,source.id,)+ def _alter_publication_membership(self, source: ExternalDataSource, schema: str, table: str, add: bool) -> None:+ publication_name = self._managed_publication_name(source)+ if publication_name is None:+ return+ with cdc_pg_connection(source) as conn:+ if add:+ add_table_to_publication(conn, publication_name, schema, table)+ else:+ remove_table_from_publication(conn, publication_name, schema, table)++ def _managed_publication_name(self, source: ExternalDataSource) -> str | None:+ cdc_config = self.parse_cdc_config(source)+ # PostHog only manages the publication in posthog-managed mode.+ if cdc_config.management_mode != "posthog" or not cdc_config.publication_name:+ return None+ return cdc_config.publication_name+def _resolve_schema(self, source: ExternalDataSource) -> str:raw = (source.job_inputs or {}).get("schema")return raw.strip() if isinstance(raw, str) and raw.strip() else "public"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 d182e598a15d..d8815d2aa539 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@@ -380,6 +380,20 @@ class TestAlterPublicationMembership:PostgresCDCAdapter().add_table(source, "public", "orders")mock_add.assert_not_called()+ @patch(f"{_ADAPTER}.add_table_to_publication", side_effect=psycopg.errors.InsufficientPrivilege("must be owner"))+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)+ def test_add_table_raises_when_the_publication_rejects_the_table(self, _conn, _mock_add) -> None:+ source = _source(cdc_enabled=True, cdc_management_mode="posthog", cdc_publication_name="pub")+ with pytest.raises(psycopg.errors.InsufficientPrivilege):+ PostgresCDCAdapter().add_table(source, "public", "orders")++ @patch(f"{_ADAPTER}.remove_table_from_publication", side_effect=psycopg.OperationalError("connection refused"))+ @patch(f"{_ADAPTER}.cdc_pg_connection", new_callable=_fake_conn)+ def test_remove_table_stays_best_effort(self, _conn, mock_remove) -> None:+ source = _source(cdc_enabled=True, cdc_management_mode="posthog", cdc_publication_name="pub")+ PostgresCDCAdapter().remove_table(source, "public", "orders")+ mock_remove.assert_called_once()+class TestGetStatus:@patch(f"{_ADAPTER}.get_publication_tables", return_value=["public.orders", "public.users"])diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex 374a54c2841f..2c2def68a799 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py@@ -2927,6 +2927,143 @@ class TestUpdateExternalDataSchema:mock_add_table.assert_called_once()assert mock_add_table.call_args.args == (source, "analytics", "events")+ @staticmethod+ def _managed_cdc_source_and_full_refresh_schema(team, **schema_fields: Any):+ source = ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ status=ExternalDataSource.Status.RUNNING,+ source_type=ExternalDataSourceType.POSTGRES,+ job_inputs={+ "schema": "",+ "cdc_enabled": True,+ "cdc_management_mode": "posthog",+ "cdc_slot_name": "test_slot",+ "cdc_publication_name": "test_pub",+ },+ )+ 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",+ },+ **schema_fields.pop("sync_type_config", {}),+ }+ schema = ExternalDataSchema.objects.create(+ team=team,+ source=source,+ name="analytics.events",+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ sync_type_config=sync_type_config,+ **{"should_sync": False, **schema_fields},+ )+ return source, schema++ @staticmethod+ def _patch_cdc_switch(add_table_side_effect: BaseException | None = None) -> contextlib.ExitStack:+ stack = contextlib.ExitStack()+ views = "products.warehouse_sources.backend.presentation.views.external_data_schema"+ stack.enter_context(mock.patch(f"{views}.is_cdc_enabled_for_team", return_value=True))+ stack.enter_context(mock.patch(f"{views}.external_data_workflow_exists", return_value=False))+ stack.enter_context(mock.patch(f"{views}.sync_external_data_job_workflow"))+ stack.enter_context(mock.patch(f"{views}.sync_cdc_extraction_schedule"))+ stack.enter_context(+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table",+ side_effect=add_table_side_effect,+ )+ )+ return stack++ @pytest.mark.parametrize(+ "initial_sync_complete, prior_config",+ [+ pytest.param(False, {}, id="never_synced"),+ pytest.param(True, {}, id="loaded_by_full_refresh"),+ pytest.param(+ True,+ {"cdc_mode": "streaming", "cdc_last_log_position": "0/16B3748", "cdc_deferred_runs": [{"run": 1}]},+ id="left_over_from_earlier_cdc_period",+ ),+ ],+ )+ def test_switch_to_cdc_starts_a_fresh_snapshot(+ self, team, user, client: HttpClient, temporal, initial_sync_complete, prior_config+ ):+ client.force_login(user)+ _, schema = self._managed_cdc_source_and_full_refresh_schema(+ team, initial_sync_complete=initial_sync_complete, sync_type_config=prior_config+ )++ with self._patch_cdc_switch():+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "cdc", "should_sync": True},+ content_type="application/json",+ )++ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert schema.sync_type == ExternalDataSchema.SyncType.CDC+ assert schema.sync_type_config["cdc_mode"] == "snapshot"+ assert "cdc_last_log_position" not in schema.sync_type_config+ assert "cdc_deferred_runs" not in schema.sync_type_config+ assert schema.initial_sync_complete is False++ @pytest.mark.parametrize(+ "add_table_error, expected_message, captured",+ [+ pytest.param(+ psycopg.errors.InsufficientPrivilege("must be owner of table events"),+ "PostgreSQL only lets a table's owner publish it",+ False,+ id="table_not_owned",+ ),+ pytest.param(+ psycopg.OperationalError("connection refused"),+ "Couldn't connect to your database to add analytics.events to change data capture",+ False,+ id="database_unreachable",+ ),+ pytest.param(+ RuntimeError("unexpected"),+ "Couldn't add analytics.events to change data capture",+ True,+ id="unexpected_error",+ ),+ ],+ )+ def test_switch_to_cdc_refused_when_table_cannot_join_publication(+ self, team, user, client: HttpClient, temporal, add_table_error, expected_message, captured+ ):+ client.force_login(user)+ _, schema = self._managed_cdc_source_and_full_refresh_schema(team, initial_sync_complete=True)++ with (+ self._patch_cdc_switch(add_table_side_effect=add_table_error),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.adapters.capture_exception"+ ) as mock_capture,+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "cdc", "should_sync": True},+ content_type="application/json",+ )++ assert response.status_code == 400, response.content+ assert expected_message in response.json()["detail"]+ assert mock_capture.called is captured+ schema.refresh_from_db()+ assert schema.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH+ assert schema.should_sync is False+ assert schema.initial_sync_complete is True+def test_delete_data_hides_direct_postgres_table(self, team, user, client: HttpClient, temporal):client.force_login(user)source = ExternalDataSource.objects.create(diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 2a78878c5d3d..7e13b9866d7d 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -4413,27 +4413,8 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(public_schema.sync_type_config["schema_metadata"]["source_schema"], "public")self.assertEqual(analytics_schema.sync_type_config["schema_metadata"]["source_schema"], "analytics")- @patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",- return_value=True,- )- @patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table"- )- @patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources"- )- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")- def test_create_postgres_cdc_with_blank_schema_uses_physical_schema_metadata(- self,- mock_get_source,- mock_cdc_pg_connection,- mock_get_primary_key_columns,- mock_setup_cdc_resources,- mock_add_table,- _mock_is_cdc_enabled_for_team,+ def _post_postgres_cdc_source_with_one_table(+ self, mock_get_source, mock_cdc_pg_connection, mock_get_primary_key_columns, mock_setup_cdc_resources):_configure_source_mock_versioning(mock_get_source)source_mock = mock_get_source.return_value@@ -4480,7 +4461,7 @@ class TestExternalDataSource(APIBaseTest):mock_setup_cdc_resources.side_effect = setup_cdc_slot- response = self.client.post(+ return self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/",data={"source_type": "Postgres",@@ -4500,6 +4481,32 @@ class TestExternalDataSource(APIBaseTest):},)+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",+ return_value=True,+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table"+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources"+ )+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")+ def test_create_postgres_cdc_with_blank_schema_uses_physical_schema_metadata(+ self,+ mock_get_source,+ mock_cdc_pg_connection,+ mock_get_primary_key_columns,+ mock_setup_cdc_resources,+ mock_add_table,+ _mock_is_cdc_enabled_for_team,+ ):+ response = self._post_postgres_cdc_source_with_one_table(+ mock_get_source, mock_cdc_pg_connection, mock_get_primary_key_columns, mock_setup_cdc_resources+ )+assert response.status_code == status.HTTP_201_CREATED, response.contentschema = ExternalDataSchema.objects.get(team_id=self.team.pk, name="analytics.events")assert schema.sync_type_config["primary_key_columns"] == ["id"]@@ -4513,6 +4520,43 @@ class TestExternalDataSource(APIBaseTest):mock_add_table.assert_called_once()assert mock_add_table.call_args.args[1:] == ("analytics", "events")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",+ return_value=True,+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources"+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table",+ side_effect=psycopg.errors.InsufficientPrivilege("must be owner of table events"),+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources"+ )+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")+ def test_create_postgres_cdc_refused_when_a_table_cannot_join_the_publication(+ self,+ mock_get_source,+ mock_cdc_pg_connection,+ mock_get_primary_key_columns,+ mock_setup_cdc_resources,+ _mock_add_table,+ mock_cleanup_resources,+ _mock_is_cdc_enabled_for_team,+ ):+ response = self._post_postgres_cdc_source_with_one_table(+ mock_get_source, mock_cdc_pg_connection, mock_get_primary_key_columns, mock_setup_cdc_resources+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "PostgreSQL only lets a table's owner publish it" in response.json()["message"]+ mock_cleanup_resources.assert_called_once()+ assert not ExternalDataSource.objects.filter(team_id=self.team.pk).exists()+ assert not ExternalDataSchema.objects.filter(team_id=self.team.pk, name="analytics.events").exists()+@patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,