: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): leave a cdc reset to capture while a sync can hand over (#106621)
Daniel RCf6a5653ef414
diff --git a/docs/internal/cdc-buffered-ingress-runbook.md b/docs/internal/cdc-buffered-ingress-runbook.mdindex 66421c973d4a..ba28a5d6dca9 100644--- a/docs/internal/cdc-buffered-ingress-runbook.md+++ b/docs/internal/cdc-buffered-ingress-runbook.md@@ -60,6 +60,10 @@ The new snapshot reads the table after the reset, so nothing skipped is lost.The key stays until the schedule is unpaused, so a failed unpause is retried too.A reset from slot-invalidation recovery marks the key `awaiting_slot` until the replacement slot exists, so no later run can unpause the table before capture has a point to resume from, and the table stays out of capture until then.Recovery clears the flag once the slot is back, and so does any read that succeeds, so a failure right after the recreation cannot leave the table waiting for good.+A resync, a table-mode switch, re-enabling a table's sync, and Repair CDC use the same key: when a sync of the table can still hand over, they pause its schedule and leave the reset to capture, which also starts the new snapshot.+They then start a capture run right away, and recreate the capture schedule if it is gone, so the reset does not wait for the next tick. A source that is marked broken, or whose capture is paused after a non-retryable error, is left alone: Repair CDC or resuming capture restarts it.+Each write that stages a reset gives the key a new `generation`, so capture drops only the reset it finished, even when a request stages the same reset again while that snapshot starts.+The admin resync refuses instead, because it starts its own non-billable run, so it asks the operator to retry once the sync stops.Turning a table's sync off, or adding it back to capture, drops its marker, because capture skipped the table in between and its buffer has a gap.Capture handles a TRUNCATE only after every change of its transaction has been read, so no pre-TRUNCATE change can land in the buffer after the purge.Without the marker, the hand-over purges the whole buffer, as legacy always did.diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex 74e34d46095a..b13e40304f5c 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -39,6 +39,7 @@ _LAZY = {"sync_cdc_extraction_schedule": "logic.data_load.service","sync_discover_schemas_schedule": "logic.data_load.service","sync_external_data_job_workflow": "logic.data_load.service",+ "trigger_cdc_extraction_schedule": "logic.data_load.service","trigger_external_data_source_workflow": "logic.data_load.service","trigger_external_data_workflow": "logic.data_load.service","unpause_cdc_extraction_schedule": "logic.data_load.service",diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.pyindex a7fbdf8ebd16..5b2a673adade 100644--- a/products/data_warehouse/backend/logic/data_load/service.py+++ b/products/data_warehouse/backend/logic/data_load/service.py@@ -596,6 +596,23 @@ def sync_cdc_extraction_schedule(source: ExternalDataSource, create: bool = Falsraise+def trigger_cdc_extraction_schedule(source_id: str) -> bool:+ """Start a CDC extraction run for a source now. Returns False when the schedule is gone.++ Recreating it is the caller's job, because building a schedule reads the source row and this+ boundary takes ids: `sync_cdc_extraction_schedule(source, create=True)` fires its first run.+ """+ schedule_id = _get_cdc_extraction_schedule_id(source_id)+ temporal = sync_connect()+ try:+ trigger_schedule(temporal, schedule_id=schedule_id)+ except temporalio.service.RPCError as e:+ if e.status != temporalio.service.RPCStatusCode.NOT_FOUND:+ raise+ return False+ return True++def delete_cdc_extraction_schedule(source_id: str) -> None:"""Delete the CDC extraction schedule for a source."""schedule_id = _get_cdc_extraction_schedule_id(source_id)diff --git a/products/data_warehouse/backend/logic/data_load/test/test_service.py b/products/data_warehouse/backend/logic/data_load/test/test_service.pyindex 3a472bd3429e..c36b72fcd155 100644--- a/products/data_warehouse/backend/logic/data_load/test/test_service.py+++ b/products/data_warehouse/backend/logic/data_load/test/test_service.py@@ -38,6 +38,7 @@ from products.data_warehouse.backend.logic.data_load.service import (is_cdc_extraction_schedule_paused,pause_external_data_schedule,sync_cdc_extraction_schedule,+ trigger_cdc_extraction_schedule,unpause_external_data_schedule,)from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource@@ -577,3 +578,29 @@ def test_a_unpause_reraises_other_rpc_errors():pytest.raises(RPCError),):async_to_sync(a_unpause_external_data_schedule)("some-schedule-id")+++ "trigger_error, started",+ [(None, True), (_not_found(), False)],+)+def test_triggering_capture_reports_a_schedule_that_is_gone(trigger_error: RPCError | None, started: bool) -> None:+ # The caller recreates the schedule, because building one reads the source row.+ source_id = str(uuid.uuid4())++ with (+ patch(f"{SERVICE}.sync_connect", return_value=MagicMock()),+ patch(f"{SERVICE}.trigger_schedule", side_effect=trigger_error) as trigger,+ ):+ assert trigger_cdc_extraction_schedule(source_id) is started++ assert trigger.call_args.kwargs["schedule_id"] == _get_cdc_extraction_schedule_id(source_id)+++def test_triggering_capture_raises_any_other_temporal_error() -> None:+ with (+ patch(f"{SERVICE}.sync_connect", return_value=MagicMock()),+ patch(f"{SERVICE}.trigger_schedule", side_effect=RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b"")),+ pytest.raises(RPCError),+ ):+ trigger_cdc_extraction_schedule(str(uuid.uuid4()))diff --git a/products/warehouse_sources/backend/ad_hoc_sync.py b/products/warehouse_sources/backend/ad_hoc_sync.pyindex a99cfbf7226f..a4dc9cf63999 100644--- a/products/warehouse_sources/backend/ad_hoc_sync.py+++ b/products/warehouse_sources/backend/ad_hoc_sync.py@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.models.external_data_schema import ()from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (BUFFER_LANE,+ cancel_sync_that_could_hand_over,resnapshot_stays_in_buffer,)@@ -52,6 +53,10 @@ class WorkflowStartError(Exception):"""The workflow failed to start. Any pause taken by this call has been rolled back."""+class SyncStillRunningError(Exception):+ """A CDC table's running sync could still hand over, so nothing was staged. Its cancel was requested."""++@async_to_syncasync def start_external_data_workflow(client: Client, workflow_id: str, inputs: ExternalDataWorkflowInputs) -> None:await client.start_workflow(@@ -92,6 +97,11 @@ def trigger_ad_hoc_sync(schedule plus an ad-hoc workflow, so without it the scheduled run can race this one. A schedulethe caller already paused by hand is left alone, so this does not undo their action."""+ # A sync that hands over after a CDC reset leaves the reset pending on a streaming table, whose next+ # run wipes it. This call starts its own run, so it cannot leave the reset to capture.+ if reset_pipeline and schema.is_cdc and cancel_sync_that_could_hand_over(schema):+ raise SyncStillRunningError("A sync of this table is still stopping. Retry in a minute.")+was_paused = is_schedule_paused(client, str(schema.id))paused_now = Falseif not was_paused:diff --git a/products/warehouse_sources/backend/admin/external_data_schema_admin.py b/products/warehouse_sources/backend/admin/external_data_schema_admin.pyindex a518b55f889e..31a123b39601 100644--- a/products/warehouse_sources/backend/admin/external_data_schema_admin.py+++ b/products/warehouse_sources/backend/admin/external_data_schema_admin.py@@ -19,6 +19,7 @@ from products.data_warehouse.backend.facade.api import ()from products.warehouse_sources.backend.ad_hoc_sync import (SchedulePauseError,+ SyncStillRunningError,WorkflowStartError,is_schedule_paused as _is_schedule_paused,start_external_data_workflow as _start_external_data_workflow,@@ -401,6 +402,9 @@ class ExternalDataSchemaAdmin(admin.ModelAdmin):except WorkflowStartError as e:messages.error(request, f"Failed to trigger sync: {e}")return redirect(_change_url(schema_id))+ except SyncStillRunningError as e:+ messages.error(request, str(e))+ return redirect(_change_url(schema_id))workflow_id = trigger.workflow_idadmin_paused_now = trigger.schedule_paused_nowdiff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.pyindex fc4495c6e93f..4136bcbc35fa 100644--- a/products/warehouse_sources/backend/facade/source_management.py+++ b/products/warehouse_sources/backend/facade/source_management.py@@ -26,6 +26,8 @@ _LAZY = {"purge_buffer_prefix": "cdc.buffer","CDC_SEQ_COLUMN": "cdc.batcher","BUFFER_LANE": "cdc.snapshot_lane",+ "CDC_RESET_PENDING_KEY": "cdc.snapshot_lane",+ "hand_reset_to_capture_if_sync_running": "cdc.snapshot_lane","resnapshot_stays_in_buffer": "cdc.snapshot_lane","ClickHouseConnectionError": "sources.clickhouse.clickhouse","ClickHouseSource": "sources.clickhouse.source",diff --git a/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py b/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.pyindex ffcb43584a7b..4be04dd39493 100644--- a/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py+++ b/products/warehouse_sources/backend/management/commands/resync_schemas_non_billable.py@@ -8,7 +8,12 @@ from temporalio.client import Clientfrom posthog.temporal.common.client import sync_connect-from products.warehouse_sources.backend.ad_hoc_sync import SchedulePauseError, WorkflowStartError, trigger_ad_hoc_sync+from products.warehouse_sources.backend.ad_hoc_sync import (+ SchedulePauseError,+ SyncStillRunningError,+ WorkflowStartError,+ trigger_ad_hoc_sync,+)from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemalogger = structlog.get_logger(__name__)@@ -160,6 +165,9 @@ class Command(BaseCommand):except WorkflowStartError:logger.exception("Failed to trigger sync", schema_id=str(schema.id), team_id=schema.team_id)return False+ except SyncStillRunningError:+ logger.warning("Sync still stopping, skipping", schema_id=str(schema.id), team_id=schema.team_id)+ return Falseself.stdout.write(f" triggered {schema.id} workflow_id={trigger.workflow_id}")logger.info(diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 82ffb6ee6e78..b29a9faa4ae8 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -59,6 +59,7 @@ from products.warehouse_sources.backend.facade.models import (from products.warehouse_sources.backend.facade.pipelines import finish_row_trackingfrom products.warehouse_sources.backend.facade.source_management import (BUFFER_LANE,+ CDC_RESET_PENDING_KEY,CDC_SEQ_COLUMN,AnySource,RowFilterValidationError,@@ -66,6 +67,7 @@ from products.warehouse_sources.backend.facade.source_management import (WebhookSource,filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,get_cdc_adapter,+ hand_reset_to_capture_if_sync_running,purge_buffer_prefix,resnapshot_stays_in_buffer,source_type_supports_cdc,@@ -161,27 +163,19 @@ def _concrete_field_names(validated_data: dict[str, Any]) -> list[str]:def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:"""Cancel any running workflow and reset schema state so the next run does a full snapshot.+ While the cancelled sync could still hand over, the reset is left to capture instead.+Must save before triggering: the workflow reloads the schema and bails via`CDCHandledExternally` if it sees `cdc_mode='streaming'`."""- latest_running_job = (- ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id).order_by("-created_at").first()- )- if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":- try:- cancel_external_data_workflow(latest_running_job.workflow_id)- except temporalio.service.RPCError as e:- logger.exception(- "Could not cancel running workflow before re-snapshot",- schema_id=str(instance.id),- exc_info=e,- )+ if hand_reset_to_capture_if_sync_running(instance, logger):+ return# Merge under a row lock so the reset can't clobber a concurrent CDC extract activity's# sync_type_config writes (and the status/initial_sync_complete save below skips the JSON# column, leaving no second window for the merged config to be overwritten).updates: dict[str, Any] = {"reset_pipeline": True, "cdc_mode": "snapshot"}- removes = ["cdc_last_log_position", "cdc_deferred_runs"]+ removes = ["cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY]if resnapshot_stays_in_buffer(instance, logger):updates[CDC_SNAPSHOT_LANE_KEY] = BUFFER_LANEinstance.sync_type_config = update_sync_type_config_keys(@@ -1313,24 +1307,30 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializersdef update_schedule() -> None:should_sync_value = should_sync if should_sync is not None else updated_instance.should_sync+ # A reset left to capture keeps the schedule paused, and capture unpauses it once the reset is done.+ reset_pending = bool((updated_instance.sync_type_config or {}).get(CDC_RESET_PENDING_KEY))schedule_exists = external_data_workflow_exists(str(updated_instance.id))if schedule_exists:if should_sync is False:pause_external_data_schedule(str(updated_instance.id))- elif should_sync is True:+ elif should_sync is True 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# schedule is built from the current frequency, so a cadence-only edit on an# enabled-but-unscheduled schema still takes effect.- sync_external_data_job_workflow(updated_instance, create=True, should_sync=should_sync_value)+ sync_external_data_job_workflow(+ updated_instance, create=True, should_sync=should_sync_value and not reset_pending+ )# Re-issue an existing schedule when the cadence changed. A disabled schema with no# schedule has nothing to update — updating a missing schedule raises "workflow not# found" — so its new cadence is just saved and applies if/when it is enabled.if (was_sync_frequency_updated or was_sync_time_of_day_updated) and schedule_exists:- sync_external_data_job_workflow(updated_instance, create=False, should_sync=should_sync_value)+ sync_external_data_job_workflow(+ updated_instance, create=False, should_sync=should_sync_value and not reset_pending+ )self._run_temporal_side_effect(update_schedule)@@ -1577,13 +1577,18 @@ class ExternalDataSchemaSerializer(UserAccessControlSerializerMixin, serializers# during that window are permanently lost regardless of how short it was.# reset_pipeline wipes the warehouse table first — otherwise the snapshot# merges current rows over the stale pre-disable ones and never drops deletes.- if should_sync is True and not newly_set_to_cdc:+ if (+ should_sync is True+ and not newly_set_to_cdc+ and not hand_reset_to_capture_if_sync_running(instance, logger)+ ):# Mutate in memory only — the locked terminal save in `update()` (which calls this)# persists both fields, merging cdc_mode onto the freshly-read config so a concurrent# CDC extract activity's writes survive. A separate save here would clobber them. It# writes only the columns validated_data names, hence the flag going in there too.instance.sync_type_config["cdc_mode"] = "snapshot"instance.sync_type_config["reset_pipeline"] = True+ instance.sync_type_config.pop(CDC_RESET_PENDING_KEY, None)instance.initial_sync_complete = Falsevalidated_data["initial_sync_complete"] = False@@ -1927,22 +1932,27 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},)- latest_running_job = (- ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id)- .order_by("-created_at")- .first()- )-- if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":- cancel_external_data_workflow(latest_running_job.workflow_id)-cdc_resync = instance.is_cdc+ if cdc_resync:+ # A sync that hands over after the reset would leave the reset pending on a streaming+ # table, whose next run wipes it. Capture finishes the reset once that sync stops.+ if hand_reset_to_capture_if_sync_running(instance, logger):+ return Response(status=status.HTTP_200_OK)+ else:+ latest_running_job = (+ ExternalDataJob.objects.filter(schema_id=instance.pk, team_id=instance.team_id)+ .order_by("-created_at")+ .first()+ )+ if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":+ cancel_external_data_workflow(latest_running_job.workflow_id)+updates: dict[str, Any] = {"reset_pipeline": True}removes: list[str] = []if cdc_resync:# Reset CDC state so the next run does a full re-snapshotupdates["cdc_mode"] = "snapshot"- removes = ["cdc_last_log_position", "cdc_deferred_runs"]+ removes = ["cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY]# Without the marker, the next capture run would empty the buffer, deleting changes a# capture run already in progress wrote after the snapshot started reading.if resnapshot_stays_in_buffer(instance, logger):diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex 83f30d50a0a4..9166b153a98d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -26,6 +26,7 @@ import structlogimport pyarrow.compute as pcimport posthoganalyticsfrom temporalio import activity+from temporalio.service import RPCError, RPCStatusCodefrom posthog.settings import WAREHOUSE_SOURCES_DATABASE_URLfrom posthog.temporal.common.activity_context import current_workflow_id, current_workflow_run_id@@ -83,8 +84,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import)from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (BUFFER_LANE,+ CDC_RESET_PENDING_KEY,cancel_running_sync,is_buffered_snapshot_enabled,+ next_reset_generation,snapshot_in_buffer,)from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import (@@ -117,9 +120,24 @@ SLOT_INVALIDATION_RECOVERY_MESSAGE = ("once the re-sync completes.")-# Marks a table whose reset waits for its running sync to stop. The slot moves past the TRUNCATE-# meanwhile, so this key is what makes a later capture run finish the reset.-CDC_RESET_PENDING_KEY = "cdc_reset_pending"++def _merge_pending_reset(+ config: dict[str, typing.Any], *, clear_deferred_runs: bool, awaiting_slot: bool+) -> dict[str, typing.Any]:+ """Merge a reset into the table's pending one. Read under the row lock, so a request's fields survive.++ `clear_deferred_runs` accumulates: a reset that owes the drop keeps owing it until one happens.+ `awaiting_slot` is this reset's own answer, because only the reset that is waiting for a slot+ holds the table back, and slot recovery clears the wait.+ """+ current = config.get(CDC_RESET_PENDING_KEY)+ fields = dict(current) if isinstance(current, dict) else {}+ fields["clear_deferred_runs"] = clear_deferred_runs or bool(fields.get("clear_deferred_runs"))+ fields["awaiting_slot"] = awaiting_slot+ fields["generation"] = next_reset_generation(fields)+ config[CDC_RESET_PENDING_KEY] = fields+ return fields+# The sweeper's auto-drop must fire below the engine's own retention cap, otherwise the# engine invalidates the slot first and we lose the chance to act cleanly.@@ -1531,10 +1549,8 @@ class CDCExtractActivity:# A sync that hands over after the reset flips the table to streaming with reset_pipeline still# set, so its next run wipes the table. A cancel only asks the workflow to stop, and the loader# still applies its queued batches, so the reset waits until neither can happen. A failed pause- # or cancel fails the run while the slot still holds the TRUNCATE.- pending = self._pending_reset(schema)- if pending is not None and pending.get("clear_deferred_runs"):- clear_deferred_runs = True+ # or cancel fails the run while the slot still holds the TRUNCATE. A reset already pending+ # is merged into, under the row lock, so its own fields survive this one.self._pause_schema_schedule(schema)stopping = cancel_running_sync(schema)# The queue alone, because deferred runs flush only after a hand-over, which the pause prevents.@@ -1555,14 +1571,14 @@ class CDCExtractActivity:# fails the run while the slot still holds the TRUNCATE, and the next run repeats the reset.purge_buffer_prefix(schema.team_id, str(schema.id), self._schema_log(schema), strict=self._source_buffered)removes = ["cdc_last_log_position"]- if clear_deferred_runs:- removes.append("cdc_deferred_runs")+ updates: dict[str, typing.Any] = {"cdc_mode": "snapshot", "reset_pipeline": True}+# Pending until the schedule is unpaused, so a failed unpause repeats on the next run.- updates: dict[str, typing.Any] = {- "cdc_mode": "snapshot",- "reset_pipeline": True,- CDC_RESET_PENDING_KEY: {"clear_deferred_runs": clear_deferred_runs, "awaiting_slot": awaiting_slot},- }+ def _merge_pending(config: dict[str, typing.Any]) -> None:+ merged = _merge_pending_reset(config, clear_deferred_runs=clear_deferred_runs, awaiting_slot=awaiting_slot)+ if merged["clear_deferred_runs"]:+ config.pop("cdc_deferred_runs", None)+# Later runs write the table's changes to the emptied buffer as an unbroken run, so the next# snapshot stays in the buffer with them.if schema.name in self._buffered_table_names and (@@ -1580,10 +1596,11 @@ class CDCExtractActivity:schema,updates=updates,removes=removes,+ mutate=_merge_pending,extra_model_fields={"initial_sync_complete": False},)self._tables_awaiting_reset.discard(schema.name)- if clear_deferred_runs:+ if schema.sync_type_config[CDC_RESET_PENDING_KEY]["clear_deferred_runs"]:self._emit_deferred_runs_depth()return True@@ -1599,12 +1616,11 @@ class CDCExtractActivity:if self.batcher is not None:self.batcher.discard(schema.name)self._tables_awaiting_reset.add(schema.name)- self._update_schema_sync_type_config(- schema,- updates={- CDC_RESET_PENDING_KEY: {"clear_deferred_runs": clear_deferred_runs, "awaiting_slot": awaiting_slot}- },- )++ def _merge_pending(config: dict[str, typing.Any]) -> None:+ _merge_pending_reset(config, clear_deferred_runs=clear_deferred_runs, awaiting_slot=awaiting_slot)++ self._update_schema_sync_type_config(schema, mutate=_merge_pending)self._schema_log(schema).info("cdc_reset_waits_for_running_sync", stopping_workflow_id=stopping_workflow_id)def _release_reset_awaiting_slot(self, schema: ExternalDataSchema) -> None:@@ -1616,9 +1632,14 @@ class CDCExtractActivity:pending = self._pending_reset(schema)if pending is None or not pending.get("awaiting_slot"):return- self._update_schema_sync_type_config(- schema, updates={CDC_RESET_PENDING_KEY: {**pending, "awaiting_slot": False}}- )++ def _clear_wait(config: dict[str, typing.Any]) -> None:+ # Read under the row lock, so fields a request added since — its `trigger` — survive.+ current = config.get(CDC_RESET_PENDING_KEY)+ if isinstance(current, dict):+ config[CDC_RESET_PENDING_KEY] = {**current, "awaiting_slot": False}++ self._update_schema_sync_type_config(schema, mutate=_clear_wait)def _pause_schema_schedule(self, schema: ExternalDataSchema) -> None:# Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.@@ -1629,15 +1650,69 @@ class CDCExtractActivity:def _unpause_schema_schedule(self, schema: ExternalDataSchema) -> None:"""Let a reset table's schedule start its snapshot. A failure leaves the reset pending for the next run."""schema_log = self._schema_log(schema)+ pending = (schema.sync_type_config or {}).get(CDC_RESET_PENDING_KEY)try:- from products.data_warehouse.backend.facade.api import unpause_external_data_schedule+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.+ from products.data_warehouse.backend.facade.api import unpause_external_data_schedule # noqa: PLC0415unpause_external_data_schedule(str(schema.id))schema_log.info("unpaused_schema_schedule_for_resnapshot", schema_id=str(schema.id))except Exception:schema_log.warning("failed_to_unpause_schema_schedule", schema_id=str(schema.id), exc_info=True)return- self._update_schema_sync_type_config(schema, removes=[CDC_RESET_PENDING_KEY])+ # A reset handed over by a request starts its snapshot now, as the request would have. The+ # key is dropped only once that snapshot is under way, so a failed start is retried too.+ if isinstance(pending, dict) and pending.get("trigger") and not self._trigger_resnapshot(schema):+ return++ def _drop_finished_reset(config: dict[str, typing.Any]) -> None:+ # Only the reset this run finished, told apart by its generation. A request that staged+ # another one while the snapshot was starting keeps it, and a later run does that reset too.+ current = config.get(CDC_RESET_PENDING_KEY)+ if isinstance(current, dict) and isinstance(pending, dict):+ finished = current.get("generation") == pending.get("generation")+ else:+ finished = current == pending+ if finished:+ config.pop(CDC_RESET_PENDING_KEY, None)++ self._update_schema_sync_type_config(schema, mutate=_drop_finished_reset)++ def _trigger_resnapshot(self, schema: ExternalDataSchema) -> bool:+ """Start the snapshot for a reset a request handed over, recovering a missing schedule first.++ Unpausing a schedule that is gone succeeds silently, so without the recovery the table would+ keep a reset nothing runs. The request recovers the same way when it triggers the sync itself.++ Returns whether the snapshot started. The reset stays pending otherwise, and a later run+ repeats it rather than leaving the table with a snapshot nobody asked for again.+ """+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.+ from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415+ sync_external_data_job_workflow,+ trigger_external_data_workflow,+ )++ schema_log = self._schema_log(schema)+ try:+ trigger_external_data_workflow(schema)+ return True+ except RPCError as e:+ # Recovery builds the schedule from the table's own cadence, so one without it has+ # nothing to build from, and a table whose sync is off must not get one that fires a run.+ if e.status != RPCStatusCode.NOT_FOUND or not schema.should_sync or schema.sync_frequency_interval is None:+ schema_log.warning("failed_to_trigger_resnapshot", schema_id=str(schema.id), exc_info=True)+ return False+ except Exception:+ schema_log.warning("failed_to_trigger_resnapshot", schema_id=str(schema.id), exc_info=True)+ return False+ try:+ # Creating the schedule fires its first run, which is the snapshot this reset owes.+ sync_external_data_job_workflow(schema, create=True, should_sync=True)+ except Exception:+ schema_log.warning("failed_to_recover_schema_schedule", schema_id=str(schema.id), exc_info=True)+ return False+ return Truedef _pause_cdc_extraction_schedule(self) -> None:"""Pause the source's CDC extraction schedule after a non-retryable failure (best-effort)."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.pyindex 0de055c7094b..7948db39e52d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py@@ -42,6 +42,10 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import CDCSourceAdapter, get_cdc_adapterfrom products.warehouse_sources.backend.temporal.data_imports.cdc.buffer import purge_buffer_prefixfrom products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_name+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (+ CDC_RESET_PENDING_KEY,+ hand_reset_to_capture_if_sync_running,+)logger = structlog.get_logger(__name__)@@ -113,6 +117,16 @@ def _repair_locked(source: ExternalDataSource) -> int:)all_cdc_schema_ids = [schema.id for schema in all_cdc_schemas]_cancel_running_cdc_jobs(source, all_cdc_schemas, log)+ # A sync that hands over after its table's reset leaves the reset pending on a streaming table,+ # whose next run wipes it. Capture finishes those resets once the syncs stop, after this repair.+ # They wait for the slot as well, because the one they would snapshot against is gone until+ # `recreate_slot` below, and a capture run firing meanwhile must not start that snapshot.+ handed_over = {+ schema.id+ for schema in all_cdc_schemas+ if hand_reset_to_capture_if_sync_running(schema, log, awaiting_slot=True)+ }+ reset_now = [schema for schema in cdc_schemas if schema.id not in handed_over]# Reset schemas before touching the slot (same ordering as the extraction activity's# slot-invalidation recovery): if recreation fails below, a re-run repeats idempotently@@ -120,11 +134,13 @@ def _repair_locked(source: ExternalDataSource) -> int:# they reference WAL from the dead slot and the re-snapshot supersedes them. The# `cdc_broken` markers deliberately survive this step: they are the retry gate.for schema_id in all_cdc_schema_ids:+ if schema_id in handed_over:+ continueupdate_sync_type_config_keys(schema_id,source.team_id,updates={"cdc_mode": "snapshot", "reset_pipeline": True},- removes=["cdc_last_log_position", "cdc_deferred_runs"],+ removes=["cdc_last_log_position", "cdc_deferred_runs", CDC_RESET_PENDING_KEY],extra_model_fields={"initial_sync_complete": False},)@@ -152,7 +168,7 @@ def _repair_locked(source: ExternalDataSource) -> int:source.status = ExternalDataSource.Status.RUNNINGsource.save(update_fields=["job_inputs", "status", "updated_at"])- _resume_schedules(source, cdc_schemas)+ _resume_schedules(source, reset_now)# Only now that the new slot exists and the schedules are resumed: clear the broken# evidence. A failure before this point leaves the markers for the retry gate; a@@ -165,7 +181,7 @@ def _repair_locked(source: ExternalDataSource) -> int:extra_model_fields={"latest_error": None},)- _trigger_resnapshots(cdc_schemas, log)+ _trigger_resnapshots(reset_now, log)log.info("cdc_repair_complete", schemas_reset=len(cdc_schemas))return len(cdc_schemas)diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.pyindex 8f89ffb8801c..3532b7e81625 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/snapshot_lane.py@@ -13,14 +13,18 @@ imports, so the schema API can call it.from __future__ import annotations-from typing import TYPE_CHECKING+from functools import partial+from typing import TYPE_CHECKING, Anyimport posthoganalyticsfrom structlog.types import FilteringBoundLoggerfrom temporalio.service import RPCError, RPCStatusCodefrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob-from products.warehouse_sources.backend.models.external_data_schema import CDC_SNAPSHOT_LANE_KEY+from products.warehouse_sources.backend.models.external_data_schema import (+ CDC_SNAPSHOT_LANE_KEY,+ update_sync_type_config_keys,+)from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import CDC_EXTRACTION_WORKFLOW_ID_PREFIXfrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import parse_ingest_mode@@ -31,6 +35,9 @@ if TYPE_CHECKING:# older worker ignores the marker, so it would defer that table's changes or purge its buffer.BUFFERED_SNAPSHOT_FLAG = "dwh-cdc-buffered-snapshot"BUFFER_LANE = "buffer"+# Marks a table whose reset waits for a sync that can still hand over. The slot or the request moves+# on meanwhile, so this key is what makes a later capture run finish the reset.+CDC_RESET_PENDING_KEY = "cdc_reset_pending"def team_flag_enabled(flag: str, team_id: int, logger: FilteringBoundLogger) -> bool:@@ -118,3 +125,95 @@ def cancel_running_sync(schema: ExternalDataSchema) -> str | None:raisereturn Nonereturn job.workflow_id+++def cancel_sync_that_could_hand_over(schema: ExternalDataSchema) -> bool:+ """Cancel the table's running sync. Returns True while it could still hand over.++ It can until its workflow has closed and none of its batches are left in the load queue.+ """+ # Deferred: source_manager pulls in the pipeline, which this module stays free of.+ from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import ( # noqa: PLC0415+ has_queued_batches,+ )++ return cancel_running_sync(schema) is not None or has_queued_batches(schema)+++def hand_reset_to_capture_if_sync_running(+ schema: ExternalDataSchema, logger: FilteringBoundLogger, *, awaiting_slot: bool = False+) -> bool:+ """Leave a CDC table's reset to capture while a sync of it could still hand over. Returns whether it did.++ When no sync can, returns False, and the caller resets the table now. Otherwise the schedule is+ paused and the reset marked pending, and capture finishes it once the sync stops. A failed check+ hands the reset over too, because capture retries it.++ `awaiting_slot` holds the staged reset back until a capture run has read the slot. Repair CDC+ hands its resets over before it recreates the slot, and a capture run that fires in between+ would otherwise start the snapshot against the dead one.+ """+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.+ from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415+ pause_external_data_schedule,+ sync_cdc_extraction_schedule,+ trigger_cdc_extraction_schedule,+ )++ try:+ if not cancel_sync_that_could_hand_over(schema):+ return False+ except Exception:+ logger.warning("cdc_reset_sync_check_failed", schema_id=str(schema.id), exc_info=True)+ try:+ pause_external_data_schedule(str(schema.id))+ except Exception:+ # Capture pauses the schedule again before it resets the table.+ logger.warning("cdc_reset_schedule_pause_failed", schema_id=str(schema.id), exc_info=True)++ persisted = update_sync_type_config_keys(+ schema.id, schema.team_id, mutate=partial(stage_handed_over_reset, awaiting_slot=awaiting_slot)+ )+ # Only this key in memory, so a caller that saves the schema afterwards keeps its own edits.+ schema.sync_type_config = {+ **(schema.sync_type_config or {}),+ CDC_RESET_PENDING_KEY: persisted[CDC_RESET_PENDING_KEY],+ }+ # Capture finishes the reset, so start a run now instead of waiting for its schedule: the last+ # run may have looked for resets just before this write, and the schedule may be gone. A halted+ # source is left alone, because Repair CDC or a resumed capture restarts capture itself.+ if not schema.cdc_halted:+ try:+ if not trigger_cdc_extraction_schedule(str(schema.source_id)):+ # The schedule is gone, and creating it fires its first run.+ sync_cdc_extraction_schedule(schema.source, create=True)+ except Exception:+ # The capture schedule's next tick still finishes the reset.+ logger.warning("cdc_reset_capture_trigger_failed", schema_id=str(schema.id), exc_info=True)+ logger.info("cdc_reset_handed_to_capture", schema_id=str(schema.id))+ return True+++def stage_handed_over_reset(config: dict[str, Any], *, awaiting_slot: bool = False) -> None:+ """Stage a request's reset for capture. Read under the row lock.++ Merged, not replaced: a reset already waiting on a slot must keep waiting, or the snapshot this+ hands over would start before capture has a point to resume from.+ """+ current = config.get(CDC_RESET_PENDING_KEY)+ fields = dict(current) if isinstance(current, dict) else {}+ fields["clear_deferred_runs"] = True+ fields["trigger"] = True+ if awaiting_slot:+ fields["awaiting_slot"] = True+ fields["generation"] = next_reset_generation(fields)+ config[CDC_RESET_PENDING_KEY] = fields+++def next_reset_generation(fields: dict[str, Any]) -> int:+ """The generation for a reset staged over `fields`.++ Every write that stages a reset takes a new one, so capture drops only the reset it finished,+ even when a request stages an identical reset while that one's snapshot starts.+ """+ return int(fields.get("generation") or 0) + 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.pyindex 5f95f498afd1..972143879e14 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py@@ -32,7 +32,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities imp)from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import CDC_SEQ_COLUMN, CDC_SEQ_PROVENANCEfrom products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCErrorCategory, cdc_error_info-from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import cancel_running_sync+from products.warehouse_sources.backend.temporal.data_imports.cdc.snapshot_lane import (+ cancel_running_sync,+ stage_handed_over_reset,+)from products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager import has_queued_batchesfrom products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEventfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (@@ -4003,18 +4006,19 @@ class TestBufferedIngressCapture:@parameterized.expand([- ("sync_still_stopping", "users-snapshot", True),- ("sync_stopped", None, False),+ ("sync_still_stopping", "users-snapshot", {"clear_deferred_runs": False}, True),+ ("sync_stopped", None, {"clear_deferred_runs": False}, False),+ ("sync_stopped_after_a_request_reset", None, {"clear_deferred_runs": True, "trigger": True}, False),])@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")def test_a_pending_reset_finishes_before_the_read_once_the_sync_stopped(- self, _name, stopping_workflow_id, waits, MockBufferWriter, mock_purge+ self, _name, stopping_workflow_id, pending, waits, MockBufferWriter, mock_purge):source = _make_source()schema = _make_schema("users", cdc_mode="streaming", source=source)- schema.sync_type_config["cdc_reset_pending"] = {"clear_deferred_runs": False}+ schema.sync_type_config["cdc_reset_pending"] = pendingevents = [_make_event(op="I", position="0/100", columns={"id": 1})]with (@@ -4023,16 +4027,96 @@ class TestBufferedIngressCapture:return_value=stopping_workflow_id,),patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule") as unpause,+ patch("products.data_warehouse.backend.facade.api.trigger_external_data_workflow") as trigger,):reader, _s3, _producer = self._run(MockBufferWriter, events, [schema], source)assert mock_purge.called is not waitsassert unpause.called is not waits+ assert trigger.called is (not waits and bool(pending.get("trigger")))assert schema.sync_type_config.get("reset_pipeline") is (None if waits else True)assert ("cdc_reset_pending" in schema.sync_type_config) is waitsassert MockBufferWriter.return_value.write_batch.called is not waitsreader.confirm_position.assert_called_once_with("0/100")+ @parameterized.expand(+ [+ ("schedule_recreated", None, False),+ ("recovery_failed", RuntimeError("temporal down"), True),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_a_handed_over_reset_recreates_a_schedule_that_is_gone(+ self, _name, create_error, stays_pending, MockBufferWriter, _mock_purge+ ):+ # Unpausing a schedule that is gone succeeds silently, so the trigger is the first call to+ # see it missing. Left there, the table would carry a reset with nothing to run it, while+ # the request that handed the reset over would have recreated the schedule itself.+ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ schema.sync_type_config["cdc_reset_pending"] = {"clear_deferred_runs": True, "trigger": True}+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",+ return_value=None,+ ),+ patch("products.data_warehouse.backend.facade.api.unpause_external_data_schedule"),+ patch(+ "products.data_warehouse.backend.facade.api.trigger_external_data_workflow",+ side_effect=RPCError("schedule not found", RPCStatusCode.NOT_FOUND, b""),+ ),+ patch(+ "products.data_warehouse.backend.facade.api.sync_external_data_job_workflow",+ side_effect=create_error,+ ) as create_schedule,+ ):+ self._run(MockBufferWriter, events, [schema], source)++ create_schedule.assert_called_once_with(schema, create=True, should_sync=True)+ # A snapshot that never started keeps the key, so a later run repeats the reset and its start.+ assert ("cdc_reset_pending" in schema.sync_type_config) is stays_pending++ @parameterized.expand(+ [+ ("a_different_reset", {"clear_deferred_runs": False}),+ ("the_same_reset_again", {"clear_deferred_runs": True, "trigger": True}),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")+ def test_a_reset_staged_while_the_snapshot_was_starting_is_left_pending(+ self, _name, pending, MockBufferWriter, _mock_purge+ ):+ # The unpause lets a sync start, so a request can hand its own reset over before this run+ # has dropped the key. Dropping it wholesale would lose that reset with nothing to redo it.+ source = _make_source()+ schema = _make_schema("users", cdc_mode="streaming", source=source)+ schema.sync_type_config["cdc_reset_pending"] = pending+ events = [_make_event(op="I", position="0/100", columns={"id": 1})]+ staged: dict = {}++ def hand_another_reset_over(_schedule_id):+ stage_handed_over_reset(schema.sync_type_config)+ staged.update(schema.sync_type_config["cdc_reset_pending"])++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.cancel_running_sync",+ return_value=None,+ ),+ patch(+ "products.data_warehouse.backend.facade.api.unpause_external_data_schedule",+ side_effect=hand_another_reset_over,+ ),+ patch("products.data_warehouse.backend.facade.api.trigger_external_data_workflow"),+ ):+ self._run(MockBufferWriter, events, [schema], source)++ assert schema.sync_type_config["cdc_reset_pending"] == staged+@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.purge_buffer_prefix")@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.CDCBufferWriter")def test_a_reset_waiting_on_a_slot_holds_the_table_out_until_the_slot_reads(self, MockBufferWriter, mock_purge):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 2e071ad7dbfd..046babc76911 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@@ -14,6 +14,8 @@ from unittest import mockfrom django.test.client import Client as HttpClient+from temporalio.service import RPCError, RPCStatusCode+from posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.api.test.test_user import create_user@@ -41,8 +43,15 @@ _PATCH_TARGETS = {"sync_cdc_extraction_schedule": ("products.warehouse_sources.backend.presentation.views.external_data_schema.sync_cdc_extraction_schedule"),- "cancel_external_data_workflow": (- "products.warehouse_sources.backend.presentation.views.external_data_schema.cancel_external_data_workflow"+ "cancel_external_data_workflow": "products.data_warehouse.backend.facade.api.cancel_external_data_workflow",+ # The hand-over reaches the facade directly, so the view's own name is a different object.+ "facade_sync_cdc_extraction_schedule": "products.data_warehouse.backend.facade.api.sync_cdc_extraction_schedule",+ "pause_external_data_schedule": "products.data_warehouse.backend.facade.api.pause_external_data_schedule",+ "trigger_cdc_extraction_schedule": "products.data_warehouse.backend.facade.api.trigger_cdc_extraction_schedule",+ # The load queue lives in the warehouse-sources database, which these tests do not create. Left+ # real, the probe raises and a reset is handed to capture instead of being applied here.+ "has_queued_batches": (+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.has_queued_batches"),"trigger_external_data_workflow": ("products.warehouse_sources.backend.presentation.views.external_data_schema.trigger_external_data_workflow"@@ -157,7 +166,11 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(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["cancel_external_data_workflow"]) as mock_cancel,+ mock.patch(+ _PATCH_TARGETS["cancel_external_data_workflow"],+ side_effect=RPCError("workflow not found", RPCStatusCode.NOT_FOUND, b""),+ ) as mock_cancel,+ mock.patch(_PATCH_TARGETS["has_queued_batches"], return_value=False),mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),):@@ -182,6 +195,125 @@ def test_patch_cdc_table_mode_adding_target_triggers_resnapshot(mock_trigger.assert_called_once()[email protected]("action", ["resync", "cdc_table_mode_switch", "re_enable"])+def test_a_reset_is_left_to_capture_while_the_tables_sync_can_still_hand_over(team, user, client: HttpClient, action):+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated", ingest_mode="buffered")+ if action == "re_enable":+ ExternalDataSchema.objects.filter(id=schema.id).update(should_sync=False)+ running_job = ExternalDataJob.objects.create(+ team=team,+ pipeline=source,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ workflow_id="running-workflow-id",+ )+ client.force_login(user)++ with (+ mock.patch(_PATCH_TARGETS["is_cdc_enabled_for_team"], return_value=True),+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),+ 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["cancel_external_data_workflow"]) as mock_cancel,+ mock.patch(_PATCH_TARGETS["pause_external_data_schedule"]) as mock_pause,+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]) as mock_trigger,+ mock.patch(_PATCH_TARGETS["trigger_cdc_extraction_schedule"]) as mock_trigger_capture,+ mock.patch(f"{_VIEW}.pause_external_data_schedule"),+ mock.patch(f"{_VIEW}.unpause_external_data_schedule") as mock_view_unpause,+ ):+ url = f"/api/environments/{team.pk}/external_data_schemas/{schema.id}"+ if action == "resync":+ response = client.post(f"{url}/resync")+ else:+ payload = {"cdc_table_mode": "both"} if action == "cdc_table_mode_switch" else {"should_sync": True}+ response = client.patch(url, data=payload, content_type="application/json")++ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert schema.sync_type_config["cdc_reset_pending"] == {+ "clear_deferred_runs": True,+ "trigger": True,+ "generation": 1,+ }+ assert "reset_pipeline" not in schema.sync_type_config+ assert schema.sync_type_config["cdc_mode"] == "streaming"+ assert schema.initial_sync_complete is True+ mock_cancel.assert_called_once_with(running_job.workflow_id)+ mock_pause.assert_called_once_with(str(schema.id))+ mock_view_unpause.assert_not_called()+ mock_trigger.assert_not_called()+ mock_trigger_capture.assert_called_once_with(str(source.id))+++def test_a_hand_over_keeps_a_reset_that_is_still_waiting_on_a_slot(team, user, client: HttpClient):+ # Replacing the key instead of merging into it would drop `awaiting_slot`, and the next capture+ # run would start the snapshot before slot recovery has a point for it to resume from.+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")+ ExternalDataSchema.objects.filter(id=schema.id).update(+ sync_type_config={+ **schema.sync_type_config,+ "cdc_reset_pending": {"clear_deferred_runs": False, "awaiting_slot": True},+ }+ )+ ExternalDataJob.objects.create(+ team=team,+ pipeline=source,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ workflow_id="running-workflow-id",+ )+ client.force_login(user)++ with (+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]),+ mock.patch(_PATCH_TARGETS["pause_external_data_schedule"]),+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),+ mock.patch(_PATCH_TARGETS["trigger_cdc_extraction_schedule"]),+ ):+ response = client.post(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}/resync")++ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert schema.sync_type_config["cdc_reset_pending"] == {+ "clear_deferred_runs": True,+ "trigger": True,+ "awaiting_slot": True,+ "generation": 1,+ }+++def test_a_hand_over_recreates_a_capture_schedule_that_is_gone(team, user, client: HttpClient):+ # Triggering a schedule that is gone starts no run, so the pending reset would wait for a tick+ # that never comes. Creating the schedule fires its first run, which finishes the reset.+ source, schema = _make_cdc_source_and_schema(team, cdc_table_mode="consolidated")+ ExternalDataJob.objects.create(+ team=team,+ pipeline=source,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ workflow_id="running-workflow-id",+ )+ client.force_login(user)++ with (+ mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),+ mock.patch(_PATCH_TARGETS["cancel_external_data_workflow"]),+ mock.patch(_PATCH_TARGETS["pause_external_data_schedule"]),+ mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),+ mock.patch(_PATCH_TARGETS["trigger_cdc_extraction_schedule"], return_value=False),+ mock.patch(_PATCH_TARGETS["facade_sync_cdc_extraction_schedule"]) as mock_create_capture,+ ):+ response = client.post(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}/resync")++ assert response.status_code == 200, response.content+ schema.refresh_from_db()+ assert schema.sync_type_config["cdc_reset_pending"]["trigger"] is True+ mock_create_capture.assert_called_once_with(source, create=True)++@pytest.mark.parametrize(("should_sync_before", "should_sync_after"), [(True, False), (False, True)])def test_toggling_sync_drops_the_snapshot_marker(team, user, client: HttpClient, should_sync_before, should_sync_after):# Capture skips a table while its sync is off, so its buffer has a gap. A marker left behind would@@ -220,6 +352,7 @@ def test_resync_of_a_streaming_table_keeps_its_buffer_on_a_buffered_source(team,client.force_login(user)with (mock.patch(_PATCH_TARGETS["is_any_external_data_schema_paused"], return_value=False),+ mock.patch(_PATCH_TARGETS["has_queued_batches"], return_value=False),mock.patch(_PATCH_TARGETS["trigger_external_data_workflow"]),mock.patch(_PATCH_TARGETS["is_buffered_snapshot_enabled"], return_value=True),):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 31794d715089..374a54c2841f 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@@ -3220,6 +3220,12 @@ class TestUpdateExternalDataSchema:mock.patch("products.warehouse_sources.backend.presentation.views.external_data_schema.sync_cdc_extraction_schedule"),+ # The load queue lives in the warehouse-sources database, which this test does not+ # create. Left real, the probe raises and the reset is handed to capture instead.+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.has_queued_batches",+ return_value=False,+ ),):response = client.patch(f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",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 2f2682a75d7a..44ad78525512 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@@ -11661,6 +11661,17 @@ BROKEN_MARKER = {"reason": "slot_missing", "at": "2026-06-29T10:40:00+00:00"}class TestRepairCDC(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # The load queue lives in the warehouse-sources database, which these tests do not create.+ # Left real, the probe raises and repair hands every reset to capture instead of doing it.+ queue_probe = patch(+ "products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager.has_queued_batches",+ return_value=False,+ )+ queue_probe.start()+ self.addCleanup(queue_probe.stop)+def _repair(self, source: ExternalDataSource):return self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/repair_cdc/",@@ -11938,6 +11949,7 @@ class TestRepairCDC(APIBaseTest):assert "cdc_broken" not in schema.sync_type_configassert mock_recreate.call_count == 2+ @patch("products.data_warehouse.backend.logic.data_load.service.pause_external_data_schedule")@patch("products.data_warehouse.backend.logic.data_load.service.cancel_external_data_workflow")@patch("products.data_warehouse.backend.logic.data_load.service.sync_cdc_extraction_schedule")@patch("products.data_warehouse.backend.logic.data_load.service.unpause_cdc_extraction_schedule")@@ -11948,7 +11960,14 @@ class TestRepairCDC(APIBaseTest):return_value={"cdc_consistent_point": "0/AABBCC"},)def test_repair_cdc_cancels_running_cdc_jobs(- self, _mock_recreate, _unpause, _trigger, _unpause_ext, _sync_ext, mock_cancel+ self,+ _mock_recreate,+ mock_unpause_schedule,+ mock_trigger,+ mock_unpause_extraction,+ _sync_extraction,+ mock_cancel,+ mock_pause_schedule,) -> None:# A run still holding the slot fails pg_drop_replication_slot, and a wedged Running# workflow would block the resumed SKIP-overlap schedules — repair must cancel them.@@ -11988,7 +12007,21 @@ class TestRepairCDC(APIBaseTest):response = self._repair(source)assert response.status_code == 200, response.content# Only the CDC schema's run is cancelled — unrelated incremental syncs keep running.- mock_cancel.assert_called_once_with("cdc-workflow-1")+ assert {c.args[0] for c in mock_cancel.call_args_list} == {"cdc-workflow-1"}+ cdc_schema.refresh_from_db()+ # `awaiting_slot`: the slot this table would snapshot against is gone until repair+ # recreates it, so a capture run firing meanwhile must hold the reset instead of starting.+ assert cdc_schema.sync_type_config["cdc_reset_pending"] == {+ "clear_deferred_runs": True,+ "trigger": True,+ "awaiting_slot": True,+ "generation": 1,+ }+ assert "reset_pipeline" not in cdc_schema.sync_type_config+ mock_pause_schedule.assert_called_once_with(str(cdc_schema.id))+ mock_unpause_schedule.assert_not_called()+ mock_trigger.assert_not_called()+ mock_unpause_extraction.assert_called_once_with(str(source.id))def test_repair_cdc_conflicts_while_another_repair_holds_the_lock(self) -> None:from posthog.redis import get_clientdiff --git a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.pyindex f176fb0049f7..af0e49565f73 100644--- a/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py+++ b/products/warehouse_sources/backend/tests/test_ad_hoc_sync.py@@ -4,7 +4,11 @@ from unittest.mock import MagicMock, patchfrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team-from products.warehouse_sources.backend.ad_hoc_sync import WorkflowStartError, trigger_ad_hoc_sync+from products.warehouse_sources.backend.ad_hoc_sync import (+ SyncStillRunningError,+ WorkflowStartError,+ trigger_ad_hoc_sync,+)from products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,update_sync_type_config_keys,@@ -16,6 +20,17 @@ pytestmark = [pytest.mark.django_db]MODULE = "products.warehouse_sources.backend.ad_hoc_sync"+def no_sync_to_wait_for():+ """No sync of the table can hand over, so a reset is staged here rather than left to capture.++ The real check reads the load queue, which lives in the warehouse-sources database these tests+ do not create — it would raise, and a failed check hands the reset over.+ """+ with patch(f"{MODULE}.cancel_sync_that_could_hand_over", return_value=False) as stub:+ yield stub++@pytest.fixturedef schema():team = create_team(organization=create_organization("test org"))@@ -64,7 +79,7 @@ def test_a_schedule_already_paused_is_left_paused(schema):assert "admin_unpause_schedule_after_run" not in schema.sync_type_config-def test_failed_start_restores_staged_reset_state(schema):+def test_failed_start_restores_staged_reset_state(schema, no_sync_to_wait_for):schema.sync_type_config = {"cdc_mode": "streaming", "cdc_last_log_position": "0/ABC"}schema.sync_type = ExternalDataSchema.SyncType.CDCschema.initial_sync_complete = True@@ -87,7 +102,9 @@ def test_failed_start_restores_staged_reset_state(schema):@pytest.mark.parametrize("ingest_mode", [None, "buffered"])-def test_a_reset_of_a_streaming_cdc_table_keeps_its_buffer_and_concurrent_keys(schema, ingest_mode):+def test_a_reset_of_a_streaming_cdc_table_keeps_its_buffer_and_concurrent_keys(+ schema, ingest_mode, no_sync_to_wait_for+):schema.source.job_inputs = {"cdc_ingest_mode": ingest_mode} if ingest_mode else {}schema.source.save()schema.sync_type = ExternalDataSchema.SyncType.CDC@@ -112,3 +129,22 @@ def test_a_reset_of_a_streaming_cdc_table_keeps_its_buffer_and_concurrent_keys(s# Unmarked, the next capture run empties the buffer and can delete changes the snapshot never saw.assert (schema.sync_type_config.get("cdc_snapshot_lane") == "buffer") is (ingest_mode == "buffered")assert schema.sync_type_config["cdc_last_run_at"] == "2026-09-24T00:00:00+00:00"+++def test_a_cdc_reset_is_refused_while_the_tables_sync_can_still_hand_over(schema):+ schema.sync_type = ExternalDataSchema.SyncType.CDC+ schema.sync_type_config = {"cdc_mode": "streaming"}+ schema.save()++ with (+ patch(f"{MODULE}.cancel_sync_that_could_hand_over", return_value=True),+ patch(f"{MODULE}.pause_external_data_schedule") as pause,+ patch(f"{MODULE}.start_external_data_workflow") as start,+ pytest.raises(SyncStillRunningError),+ ):+ trigger_ad_hoc_sync(MagicMock(), schema, billable=False, reset_pipeline=True, workflow_id_prefix="test")++ pause.assert_not_called()+ start.assert_not_called()+ schema.refresh_from_db()+ assert schema.sync_type_config == {"cdc_mode": "streaming"}diff --git a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.pyindex 0e5556676f48..684cac904c4e 100644--- a/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py+++ b/products/warehouse_sources/backend/tests/test_external_data_schema_admin.py@@ -67,6 +67,9 @@ class TestExternalDataSchemaAdmin(BaseTest):with (patch(f"{_ADMIN_MODULE}.sync_connect"),patch(f"{_SHARED_MODULE}.is_schedule_paused", return_value=True),+ # No sync of the table can hand over, so the reset is staged here. The real check reads+ # the load queue, which lives in a database this test does not create.+ patch(f"{_SHARED_MODULE}.cancel_sync_that_could_hand_over", return_value=False),patch(f"{_SHARED_MODULE}.start_external_data_workflow") as mock_start,):response = self.admin.trigger_sync_view(self._request("post", {"reset_pipeline": "on"}), schema.id)