: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(warehouse-sources): fix cdc table-mode and sync-type switches (#108581)
Daniel RC64bf30645c51
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 3622892c014f..c34287ab92a4 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -1109,7 +1109,12 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# 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):+ for stale_key in (+ "cdc_last_log_position",+ "cdc_deferred_runs",+ CDC_RESET_PENDING_KEY,+ CDC_SNAPSHOT_LANE_KEY,+ ):payload.pop(stale_key, None)instance.initial_sync_complete = Falsevalidated_data["initial_sync_complete"] = False@@ -1145,6 +1150,9 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# type that ever allowed 1min), clamp the inherited cadence to the floor so the switch# doesn't dead-end. The clamp flows through the sync_frequency handling below.resulting_sync_type = sync_type if "sync_type" in data else instance.sync_type+ # An explicit `"sync_type": null` is saved too, so only an omitted field keeps the current type.+ is_cdc = resulting_sync_type == ExternalDataSchema.SyncType.CDC+ leaving_cdc = instance.sync_type == ExternalDataSchema.SyncType.CDC and not is_cdcresulting_frequency = sync_frequencyif not resulting_frequency and instance.sync_frequency_interval is not None:resulting_frequency = sync_frequency_interval_to_sync_frequency(instance.sync_frequency_interval)@@ -1228,13 +1236,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# 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- ):+ if should_sync is True and not instance.should_sync and is_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."@@ -1244,11 +1246,14 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# force-projects a non-nullable `_ph_xmin` control column that no other sync type writes.# Reusing the existing Delta table fails the write — the column is missing on the way in, or# lingers on the way out — so force a full resync to rebuild the table from scratch.- if (- "sync_type" in data- and sync_type != instance.sync_type- and ExternalDataSchema.SyncType.XMIN in (sync_type, instance.sync_type)- ):+ crosses_xmin = sync_type != instance.sync_type and ExternalDataSchema.SyncType.XMIN in (+ sync_type,+ instance.sync_type,+ )+ # cdc_only wrote the consolidated table only at its initial snapshot, so a sync type that goes on+ # from that table would skip every change since then.+ leaves_cdc_only = leaving_cdc and instance.cdc_table_mode == "cdc_only"+ if "sync_type" in data and (crosses_xmin or leaves_cdc_only):if is_any_external_data_schema_paused(instance.team_id):raise ValidationError("Monthly sync limit reached. Please increase your billing limit before changing "@@ -1305,11 +1310,20 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersinstance.table.save(update_fields=["columns"])# CDC publication management: add/remove table when toggling should_sync- is_cdc = (sync_type == ExternalDataSchema.SyncType.CDC) or (- sync_type is None and instance.sync_type == ExternalDataSchema.SyncType.CDC- )- if is_cdc and source_type_supports_cdc(source.source_type):- self._handle_cdc_publication_change(instance, source, should_sync, sync_type, validated_data)+ # A reset handed to capture paused the schedule, and capture only finishes a reset for a CDC table,+ # so a table leaving CDC drops the pending reset and resumes its schedule itself.+ resume_paused_schedule = leaving_cdc and bool((instance.sync_type_config or {}).get(CDC_RESET_PENDING_KEY))+ if resume_paused_schedule:+ instance.sync_type_config.pop(CDC_RESET_PENDING_KEY, None)+ # Capture stops buffering the table, whoever manages the publication, so a later return to CDC+ # must empty the buffer before its new snapshot.+ if leaving_cdc:+ instance.sync_type_config.pop(CDC_SNAPSHOT_LANE_KEY, None)+ publication_removal: Callable[[], None] | None = None+ if (is_cdc or leaving_cdc) and source_type_supports_cdc(source.source_type):+ publication_removal = self._handle_cdc_publication_change(+ instance, source, should_sync, sync_type, leaving_cdc, validated_data+ )if trigger_refresh:instance.sync_type_config.update({"reset_pipeline": True})@@ -1318,6 +1332,8 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# Persist under a row lock, replaying only the sync_type_config keys this request changed# so a concurrent CDC extract activity's writes aren't reverted by the full-instance save.updated_instance = self._save_merging_sync_type_config(instance, validated_data, original_sync_type_config)+ if publication_removal is not None:+ self._run_temporal_side_effect(publication_removal)# A version repin invalidates any in-flight import: retried/resumed activities re-resolve# the version from the DB, so letting the run finish would mix two vendor API versions in@@ -1343,7 +1359,10 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersself._run_temporal_side_effect(cancel_running_import)if source.supports_scheduled_sync and (- should_sync is not None or was_sync_frequency_updated or was_sync_time_of_day_updated+ should_sync is not None+ or was_sync_frequency_updated+ or was_sync_time_of_day_updated+ or resume_paused_schedule):def update_schedule() -> None:@@ -1355,7 +1374,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersif schedule_exists:if should_sync is False:pause_external_data_schedule(str(updated_instance.id))- elif should_sync is True and not reset_pending:+ elif (should_sync is True or (resume_paused_schedule and should_sync_value)) and not reset_pending:unpause_external_data_schedule(str(updated_instance.id))elif should_sync_value:# No schedule yet but the schema should be syncing — create (or recover) it. The@@ -1382,7 +1401,7 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersself._maybe_create_webhook(updated_instance)# Sync CDC extraction schedule after any CDC schema change- if is_cdc:+ if is_cdc or leaving_cdc:def sync_cdc_schedule() -> None:try:@@ -1588,13 +1607,19 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializerssource: ExternalDataSource,should_sync: bool | None,sync_type: str | None,+ leaving_cdc: bool,validated_data: dict[str, Any],- ) -> None:- """Add/remove the table from the CDC capture set when a schema is toggled or set to CDC."""+ ) -> Callable[[], None] | None:+ """Add/remove the table from the CDC capture set when a schema is toggled, set to CDC, or moved off CDC.++ A removal comes back for the caller to run once the schema is saved. Run before the save, a+ failed save would leave a table that capture still reads out of the publication, and the+ changes made in the meantime would never reach it.+ """adapter = get_cdc_adapter(source)cdc_config = adapter.parse_cdc_config(source)if cdc_config.management_mode != "posthog" or not cdc_config.publication_name:- return+ return None_, db_schema, source_table_name = get_postgres_source_location(schema_name=instance.name,@@ -1605,9 +1630,8 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersnewly_set_to_cdc = (sync_type == ExternalDataSchema.SyncType.CDC and instance.sync_type != ExternalDataSchema.SyncType.CDC)-# Add table to capture set when enabling CDC or toggling sync on- if newly_set_to_cdc or (should_sync is True and not instance.should_sync):+ if not leaving_cdc and (newly_set_to_cdc or (should_sync is True and not instance.should_sync)):try:adapter.add_table(source, db_schema, source_table_name)except Exception as e:@@ -1638,10 +1662,12 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersinstance.initial_sync_complete = Falsevalidated_data["initial_sync_complete"] = False- # Remove table from capture set when toggling sync off- elif should_sync is False and instance.should_sync:- adapter.remove_table(source, db_schema, source_table_name)+ # Remove table from capture set when toggling sync off or moving it off CDC. Left in, capture+ # keeps decoding the table's changes only to drop them, and the source keeps streaming them.+ elif leaving_cdc or (should_sync is False and instance.should_sync):instance.sync_type_config.pop(CDC_SNAPSHOT_LANE_KEY, None)+ return lambda: adapter.remove_table(source, db_schema, source_table_name)+ return Noneclass ExternalDataSchemaListSerializer(serializers.ModelSerializer):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 6e2cef13e0fb..4c7ce55e27ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py@@ -25,7 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helperssync_engineering_analytics_views,sync_revenue_analytics_views,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_complete+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (+ own_linked_table,+ set_initial_sync_complete,+)from products.warehouse_sources.backend.temporal.data_imports.query_folder_state import QueryFolderPointerHistoryfrom products.warehouse_sources.backend.temporal.data_imports.schema_flags import is_schema_flag_enabledfrom products.warehouse_sources.backend.temporal.data_imports.util import (@@ -338,9 +341,12 @@ async def _publish_queryable_files(existing_queryable_folder = await _get_companion_queryable_folder()else:- existing_queryable_folder = await database_sync_to_async_pool(- lambda: schema.table.queryable_folder if schema.table else None- )()++ def _own_queryable_folder() -> str | None:+ table = own_linked_table(schema, job.pipeline)+ return table.queryable_folder if table is not None else None++ existing_queryable_folder = await database_sync_to_async_pool(_own_queryable_folder)()double_buffer = await database_sync_to_async_pool(is_schema_flag_enabled)(schema, DOUBLE_BUFFERED_QUERY_FOLDERS_FLAGdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.pyindex 76ef738d4de0..f63cbdb66a5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_load.py@@ -82,6 +82,7 @@ async def _run_post_load(run_scheduled = AsyncMock()with (patch(f"{_LOAD_MODULE}.prepare_s3_files_for_querying", prepare_s3),+ patch(f"{_LOAD_MODULE}.own_linked_table", lambda schema, _pipeline: schema.table),patch(f"{_LOAD_MODULE}.is_schema_flag_enabled", MagicMock(return_value=double_buffer_enabled)),patch(f"{_LOAD_MODULE}._stored_sync_type_config", MagicMock(return_value=stored_sync_type_config)),patch(f"{_LOAD_MODULE}.notify_revenue_analytics_that_sync_has_completed", AsyncMock()),diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.pyindex 071a4667b0e6..7c98815649a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py@@ -31,8 +31,10 @@ from products.warehouse_sources.backend.models.external_data_schema import (mark_initial_sync_complete,update_sync_type_config_keys,)+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.models.util import hogql_type_name_for_clickhouse_type+from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import companion_resource_namefrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.common.db_retry import (retry_on_operational_error,@@ -257,6 +259,23 @@ def _refresh_cumulative_row_count(table: DataWarehouseTable, logger: FilteringBologger.warning(f"Could not refresh cumulative row count for {context}, keeping previous value", exc_info=True)+def own_linked_table(schema: ExternalDataSchema, pipeline: ExternalDataSource) -> DataWarehouseTable | None:+ """The schema's linked table, unless the link is its `_cdc` companion.++ cdc_only links the schema to its companion table. Reusing that link after a switch to a mode that+ writes the consolidated table would publish the consolidated data under the companion's record,+ and the consolidated table would never get a record of its own. A pinned folder can give the+ schema's own table the companion's name, and then the link is right.+ """+ table = schema.table+ if table is None:+ return None+ names = resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name)+ table_name = build_table_name(pipeline, names.table_storage_name)+ companion_name = build_table_name(pipeline, companion_resource_name(schema.name))+ return None if table.name == companion_name != table_name else table++async def validate_schema_and_update_table(run_id: str,team_id: int,@@ -326,7 +345,7 @@ async def validate_schema_and_update_table(# held the Postgres transaction (and the select_for_update row lock below) open for# minutes, surfacing as "idle in transaction" connections that stalled vacuum and# exhausted the connection pool.- table_created: DataWarehouseTable | None = external_data_schema.table+ table_created: DataWarehouseTable | None = own_linked_table(external_data_schema, job.pipeline)if table_created is None:# The ServerException handler below can leave a created table unlinked, so look fordiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.pyindex 8316612cfd67..d404f0d036ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/test_pipeline_sync.py@@ -12,6 +12,8 @@ from asgiref.sync import async_to_syncfrom clickhouse_driver.errors import ServerExceptionfrom parameterized import parameterized+from posthog.models import Team+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -407,10 +409,18 @@ class TestValidateSchemaAndUpdateTable:assert not table.columnsassert table.created_via == DataWarehouseTableCreatedVia.SOURCE- def _linked_table(self, team, schema, job, *, queryable_folder: str) -> DataWarehouseTable:+ def _linked_table(+ self,+ team: Team,+ schema: ExternalDataSchema,+ job: ExternalDataJob,+ *,+ queryable_folder: str,+ storage_name: str | None = None,+ ) -> DataWarehouseTable:names = resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name)table = DataWarehouseTable.objects.create(- name=build_table_name(job.pipeline, names.table_storage_name),+ name=build_table_name(job.pipeline, storage_name or names.table_storage_name),format=DataWarehouseTableFormat.DeltaS3Wrapper,url_pattern="s3://bucket/orders_v1/*.parquet",team=team,@@ -448,6 +458,57 @@ class TestValidateSchemaAndUpdateTable:# A reported 0 must not zero a table that was just republished.assert table.row_count == 150+ def test_a_schema_linked_to_its_cdc_companion_gets_its_own_table(self, team: Team) -> None:+ schema, job = self._schema_and_job(team)+ companion = self._linked_table(+ team, schema, job, queryable_folder="orders_cdc__query_a", storage_name="orders_cdc"+ )++ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ async_to_sync(validate_schema_and_update_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ row_count=10,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="orders__query_a",+ )++ schema.refresh_from_db()+ companion.refresh_from_db()+ assert schema.table is not None+ assert (schema.table.name, schema.table.queryable_folder) == (+ build_table_name(job.pipeline, "orders"),+ "orders__query_a",+ )+ assert companion.queryable_folder == "orders_cdc__query_a"++ def test_a_schema_whose_own_table_has_the_companion_name_keeps_it(self, team: Team) -> None:+ schema, job = self._schema_and_job(team)+ schema.s3_folder_name = "orders_cdc"+ schema.save()+ own_table = self._linked_table(team, schema, job, queryable_folder="orders_cdc__query_a")++ with (+ patch.object(DataWarehouseTable, "get_columns", return_value={}),+ patch.object(DataWarehouseTable, "get_count", return_value=150),+ ):+ async_to_sync(validate_schema_and_update_table)(+ run_id=str(job.id),+ team_id=team.pk,+ schema_id=schema.id,+ row_count=10,+ table_format=DataWarehouseTableFormat.DeltaS3Wrapper,+ queryable_folder="orders_cdc__query_b",+ )++ schema.refresh_from_db()+ assert schema.table_id == own_table.id+ assert DataWarehouseTable.objects.filter(team=team, deleted=False).count() == 1+@pytest.mark.parametrize(("recorded_active", "expect_restart"),[diff --git a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.pyindex 18bd3c104d13..e430cfcde7dd 100644--- a/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py+++ b/products/warehouse_sources/backend/tests/api/test_cdc_table_mode_patch.py@@ -19,6 +19,7 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.api.test.test_user import create_user+from posthog.models import Team, Userfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -335,6 +336,144 @@ def test_toggling_sync_drops_the_snapshot_marker(team, user, client: HttpClient,assert "cdc_snapshot_lane" not in schema.sync_type_config[email protected]("should_sync_before", [True, False])[email protected]("new_sync_type", [ExternalDataSchema.SyncType.FULL_REFRESH, None])+def test_moving_a_table_off_cdc_drops_it_from_the_publication(+ team: Team, user: User, client: HttpClient, should_sync_before: bool, new_sync_type: str | None+) -> None:+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")+ ExternalDataSchema.objects.filter(id=schema.id).update(+ should_sync=should_sync_before,+ sync_type_config={key: value for key, value in schema.sync_type_config.items() if key != "primary_key_columns"},+ )+ client.force_login(user)+ with (+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]) as alter_publication,+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]) as sync_capture_schedule,+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),+ mock.patch(f"{_VIEW}.pause_external_data_schedule"),+ mock.patch(f"{_VIEW}.unpause_external_data_schedule"),+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": new_sync_type, "should_sync": True},+ content_type="application/json",+ )++ assert response.status_code == 200, response.content+ assert [call.kwargs["add"] for call in alter_publication.call_args_list] == [False]+ sync_capture_schedule.assert_called_once()+ schema.refresh_from_db()+ assert schema.sync_type == new_sync_type++[email protected]("management_mode", ["posthog", "self_managed"])+def test_a_table_moved_off_cdc_during_a_handed_over_reset_syncs_again(+ team: Team, user: User, client: HttpClient, management_mode: str+) -> None:+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")+ source.job_inputs = {**source.job_inputs, "cdc_management_mode": management_mode}+ source.save()+ ExternalDataSchema.objects.filter(id=schema.id).update(+ sync_type_config={+ **schema.sync_type_config,+ "cdc_reset_pending": {"trigger": True},+ "cdc_snapshot_lane": "buffer",+ }+ )+ client.force_login(user)+ with (+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),+ mock.patch(f"{_VIEW}.unpause_external_data_schedule") as unpause,+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "full_refresh"},+ content_type="application/json",+ )++ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert "cdc_reset_pending" not in schema.sync_type_config+ assert "cdc_snapshot_lane" not in schema.sync_type_config+ unpause.assert_called_once_with(str(schema.id))+++ ("table_mode", "over_billing_limit", "expected_status", "resynced"),+ [+ ("cdc_only", False, 200, True),+ ("cdc_only", True, 400, False),+ ("both", False, 200, False),+ ],+)+def test_moving_a_cdc_only_table_off_cdc_resyncs_it(+ team: Team,+ user: User,+ client: HttpClient,+ table_mode: str,+ over_billing_limit: bool,+ expected_status: int,+ resynced: bool,+) -> None:+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode=table_mode)+ client.force_login(user)+ with (+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]),+ mock.patch(_PATCH_TARGETS["external_data_workflow_exists"], return_value=True),+ mock.patch(_PATCH_TARGETS["sync_external_data_job_workflow"]),+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as trigger,+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=over_billing_limit),+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "full_refresh"},+ content_type="application/json",+ )++ assert response.status_code == expected_status, response.content+ schema.refresh_from_db()+ assert bool(schema.sync_type_config.get("reset_pipeline")) is resynced+ assert trigger.called is resynced+++def test_a_table_stays_in_the_publication_when_its_move_off_cdc_is_not_saved(+ team: Team, user: User, client: HttpClient+) -> None:+ _, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")+ client.force_login(user)+ client.raise_request_exception = False+ with (+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),+ mock.patch(_PATCH_TARGETS["alter_cdc_publication"]) as alter_publication,+ mock.patch(_PATCH_TARGETS["sync_cdc_extraction_schedule"]),+ mock.patch(+ f"{_VIEW}.ExternalDataSchemaSerializer._save_merging_sync_type_config",+ side_effect=RuntimeError("save failed"),+ ),+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={"sync_type": "full_refresh"},+ content_type="application/json",+ )++ assert response.status_code == 500+ alter_publication.assert_not_called()+ schema.refresh_from_db()+ assert schema.sync_type == ExternalDataSchema.SyncType.CDC++@pytest.mark.parametrize(("sync_frequency", "expected_status"), [("7day", 200), ("30day", 400)])def test_a_cdc_table_syncs_before_its_captured_changes_expire(team, user, client: HttpClient, sync_frequency, expected_statusdiff --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 2c2def68a799..767314fc09ec 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@@ -2981,24 +2981,38 @@ class TestUpdateExternalDataSchema:return stack@pytest.mark.parametrize(- "initial_sync_complete, prior_config",+ "initial_sync_complete, prior_config, management_mode",[- pytest.param(False, {}, id="never_synced"),- pytest.param(True, {}, id="loaded_by_full_refresh"),+ pytest.param(False, {}, "posthog", id="never_synced"),+ pytest.param(True, {}, "posthog", id="loaded_by_full_refresh"),pytest.param(True,- {"cdc_mode": "streaming", "cdc_last_log_position": "0/16B3748", "cdc_deferred_runs": [{"run": 1}]},+ {+ "cdc_mode": "streaming",+ "cdc_last_log_position": "0/16B3748",+ "cdc_deferred_runs": [{"run": 1}],+ "cdc_snapshot_lane": "buffer",+ },+ "posthog",id="left_over_from_earlier_cdc_period",),+ pytest.param(+ True,+ {"cdc_mode": "streaming", "cdc_snapshot_lane": "buffer"},+ "self_managed",+ id="left_over_on_a_self_managed_source",+ ),],)def test_switch_to_cdc_starts_a_fresh_snapshot(- self, team, user, client: HttpClient, temporal, initial_sync_complete, prior_config+ self, team, user, client: HttpClient, temporal, initial_sync_complete, prior_config, management_mode):client.force_login(user)- _, schema = self._managed_cdc_source_and_full_refresh_schema(+ source, schema = self._managed_cdc_source_and_full_refresh_schema(team, initial_sync_complete=initial_sync_complete, sync_type_config=prior_config)+ source.job_inputs = {**source.job_inputs, "cdc_management_mode": management_mode}+ source.save()with self._patch_cdc_switch():response = client.patch(@@ -3013,6 +3027,7 @@ class TestUpdateExternalDataSchema:assert schema.sync_type_config["cdc_mode"] == "snapshot"assert "cdc_last_log_position" not in schema.sync_type_configassert "cdc_deferred_runs" not in schema.sync_type_config+ assert "cdc_snapshot_lane" not in schema.sync_type_configassert schema.initial_sync_complete is False@pytest.mark.parametrize(