Skip to content

: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.

feat(data-warehouse): add repair CDC action for lost replication slots (#69049)

Daniel RC4578021e4f23
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 14e35b7d82fe..ae568086bf3d 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -47,6 +47,7 @@ _LAZY = {
"sync_external_data_job_workflow": "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",
"unpause_external_data_schedule": "logic.data_load.service",
"create_warehouse_templates_for_source": "logic.data_load.source_templates",
"update_external_job_status": "logic.external_data_source.jobs",
diff --git a/products/data_warehouse/backend/logic/data_load/service.py b/products/data_warehouse/backend/logic/data_load/service.py
index a9766d8b96ab..22152164b93f 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -569,6 +569,22 @@ def pause_cdc_extraction_schedule(source_id: str) -> None:
raise
+def unpause_cdc_extraction_schedule(source_id: str) -> None:
+ """Unpause the CDC extraction schedule for a source so it resumes firing.
+
+ Recovery counterpart of `pause_cdc_extraction_schedule`, used by CDC repair once the
+ change-stream resource exists again. A missing schedule is treated as a no-op.
+ """
+ schedule_id = _get_cdc_extraction_schedule_id(source_id)
+ temporal = sync_connect()
+ try:
+ unpause_schedule(temporal, schedule_id=schedule_id)
+ except temporalio.service.RPCError as e:
+ if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:
+ return
+ raise
+
+
@async_to_sync
async def bulk_sync_cdc_extraction_schedules(
source_intervals: list[tuple[ExternalDataSource, timedelta]],
diff --git a/products/data_warehouse/backend/logic/external_data_source/jobs.py b/products/data_warehouse/backend/logic/external_data_source/jobs.py
index 611133b93d3e..b6f9cbda141e 100644
--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py
@@ -80,9 +80,21 @@ def update_external_job_status(
raise ValueError(f"External data job {job_id} is not attached to a schema")
schema = ExternalDataSchema.objects.select_for_update().get(id=model.schema_id, team_id=team_id)
- schema.status = schema_status
- schema.latest_error = latest_error
- schema.save(update_fields=["status", "latest_error", "updated_at"])
+
+ # The CDC broken state is absorbing: a loader finishing an in-flight batch after
+ # `mark_cdc_broken` must not repaint the schema healthy while the slot is gone.
+ # The marker is cleared by repair_cdc / disable_cdc, after which updates resume.
+ if (schema.sync_type_config or {}).get("cdc_broken"):
+ logger.info(
+ "dwh_schema_status_update_skipped_cdc_broken",
+ job_id=job_id,
+ schema_id=str(schema.id),
+ requested_status=schema_status,
+ )
+ else:
+ schema.status = schema_status
+ schema.latest_error = latest_error
+ schema.save(update_fields=["status", "latest_error", "updated_at"])
model.refresh_from_db()
diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
index 19169082f110..7727c32872e4 100644
--- a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
@@ -300,6 +300,30 @@ class TestUpdateExternalJobStatus:
assert schema.status == ExternalDataSchema.Status.COMPLETED
assert schema.latest_error is None
+ def test_cdc_broken_schema_status_is_not_overwritten(self):
+ # A loader finishing an in-flight batch after `mark_cdc_broken` must not repaint
+ # the schema healthy while the slot is gone — the job completes, the schema stays
+ # FAILED with the broken-state message until repair/disable clears the marker.
+ team, _source, schema, job = _create_org_team_source_schema_job()
+ schema.sync_type_config = {"cdc_broken": {"reason": "slot_missing", "at": "2026-06-29T10:40:00+00:00"}}
+ schema.status = ExternalDataSchema.Status.FAILED
+ schema.latest_error = "The replication slot no longer exists on the source database."
+ schema.save()
+
+ with patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"):
+ updated = update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.COMPLETED,
+ logger=MagicMock(),
+ latest_error=None,
+ )
+
+ assert updated.status == ExternalDataJob.Status.COMPLETED
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ assert schema.latest_error == "The replication slot no longer exists on the source database."
+
def test_rejected_transition_does_not_overwrite_schema_status(self):
team, _source, schema, job = _create_org_team_source_schema_job()
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index f6380cbdc604..7bc46cc05999 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -122,6 +122,8 @@ from products.warehouse_sources.backend.facade.source_management import (
PREVIEW_DEFAULT_ROWS,
PREVIEW_MAX_ROWS,
AnySource,
+ CDCRepairError,
+ CDCRepairInProgress,
CDCSourceAdapter,
ClickHouseSource,
Config,
@@ -146,6 +148,7 @@ from products.warehouse_sources.backend.facade.source_management import (
get_cdc_adapter,
get_primary_key_columns,
manifest_request_hosts,
+ repair_cdc_source,
source_requires_ssl,
source_type_supports_cdc,
sql_schema_metadata,
@@ -1555,6 +1558,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"check_cdc_prerequisites_for_source",
"enable_cdc",
"disable_cdc",
+ "repair_cdc",
"update_cdc_settings",
# Live outbound HTTP to a caller-supplied manifest (including POSTs) — a
# side-effecting action, so it needs write scope, not read.
@@ -3576,6 +3580,74 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
return Response(status=status.HTTP_200_OK, data={"success": True})
+ @extend_schema(
+ request=None,
+ responses={
+ 200: OpenApiResponse(
+ response={
+ "type": "object",
+ "properties": {
+ "success": {"type": "boolean"},
+ "schemas_reset": {"type": "integer"},
+ },
+ },
+ description="CDC repaired; schemas_reset CDC schemas will fully re-sync.",
+ ),
+ 400: OpenApiResponse(
+ description="CDC not enabled, no active CDC schemas, source looks healthy, or engine-side recreation failed."
+ ),
+ 409: OpenApiResponse(description="A repair is already running for this source."),
+ },
+ )
+ @action(methods=["POST"], detail=True)
+ def repair_cdc(self, request: Request, *arg: Any, **kwargs: Any):
+ """Repair CDC on a source whose replication resources were lost.
+
+ Only proceeds on evidence of breakage (a persisted broken marker, or a live probe
+ showing the slot/publication missing) — repairing a healthy source would drop its
+ slot and force a full re-sync. Cancels running CDC jobs, recreates the engine-side
+ slot/publication against the stored CDC config, resets every active CDC schema to
+ snapshot mode for a full re-sync (changes since the old slot died are
+ unrecoverable), clears the broken markers, and resumes the paused schedules.
+ Idempotent: safe to retry after a partial failure. Concurrent repairs of the same
+ source are rejected with a 409.
+ """
+ instance: ExternalDataSource = self.get_object()
+
+ adapter, err = self._get_cdc_adapter_or_400(instance)
+ if err is not None:
+ return err
+ assert adapter is not None # narrowed by _get_cdc_adapter_or_400
+
+ cdc_config = adapter.parse_cdc_config(instance)
+ if not cdc_config.enabled:
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": "CDC is not enabled on this source."},
+ )
+
+ try:
+ schemas_reset = repair_cdc_source(instance)
+ except CDCRepairInProgress as e:
+ return Response(status=status.HTTP_409_CONFLICT, data={"message": str(e)})
+ except CDCRepairError as e:
+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})
+ except (OperationalError, BaseSSHTunnelForwarderError, SSLRequiredError) as e:
+ # Expected user/upstream connection failure — surface as a 400 without capturing,
+ # mirroring the enable_cdc handler.
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": f"Could not connect to source to repair CDC: {e}"},
+ )
+ except Exception as e:
+ capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": f"Could not repair CDC: {e}"},
+ )
+
+ return Response(status=status.HTTP_200_OK, data={"success": True, "schemas_reset": schemas_reset})
+
@action(methods=["POST"], detail=True)
def update_cdc_settings(self, request: Request, *arg: Any, **kwargs: Any):
"""Update CDC tuning fields without enabling/disabling.
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 4d4f4dc603b5..e6371f1c1fe4 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -9760,6 +9760,299 @@ class TestDisableCDC(APIBaseTest):
assert called_with.pk == source.pk
+BROKEN_MARKER = {"reason": "slot_missing", "at": "2026-06-29T10:40:00+00:00"}
+
+
+class TestRepairCDC(APIBaseTest):
+ def _repair(self, source: ExternalDataSource):
+ return self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/repair_cdc/",
+ )
+
+ def test_repair_cdc_rejects_when_cdc_not_enabled(self) -> None:
+ source = _make_postgres_source(self.team.pk, self.user)
+ response = self._repair(source)
+ assert response.status_code == 400
+ assert "CDC is not enabled" in response.json()["message"]
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot"
+ )
+ def test_repair_cdc_rejects_when_no_active_cdc_schemas(self, mock_recreate) -> None:
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ ExternalDataSchema.objects.create(
+ name="incremental_table",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ should_sync=True,
+ )
+ response = self._repair(source)
+ assert response.status_code == 400
+ assert "no active CDC schemas" in response.json()["message"]
+ mock_recreate.assert_not_called()
+
+ @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")
+ @patch("products.data_warehouse.backend.logic.data_load.service.trigger_external_data_workflow")
+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_external_data_schedule")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",
+ return_value={"cdc_consistent_point": "0/AABBCC"},
+ )
+ def test_repair_cdc_resets_schemas_and_resumes_schedules(
+ self, mock_recreate, mock_unpause_schema, mock_trigger, mock_unpause_extraction, mock_sync_extraction
+ ) -> None:
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ source.status = ExternalDataSource.Status.ERROR
+ source.save()
+
+ broken_schema = ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="The replication slot no longer exists on the source database.",
+ initial_sync_complete=True,
+ sync_type_config={
+ "cdc_mode": "streaming",
+ "cdc_last_log_position": "0/123",
+ "cdc_deferred_runs": [{"run": "stale"}],
+ "cdc_broken": BROKEN_MARKER,
+ },
+ )
+ streaming_schema = ExternalDataSchema.objects.create(
+ name="users",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ initial_sync_complete=True,
+ sync_type_config={"cdc_mode": "streaming", "cdc_broken": BROKEN_MARKER},
+ )
+ disabled_cdc_schema = ExternalDataSchema.objects.create(
+ name="ignored",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=False,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
+ non_cdc_schema = ExternalDataSchema.objects.create(
+ name="incremental_table",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ should_sync=True,
+ )
+
+ response = self._repair(source)
+ assert response.status_code == 200, response.content
+ body = response.json()
+ assert body["success"] is True
+ assert body["schemas_reset"] == 2
+
+ # Slot recreated against the qualified capture set of active CDC schemas only.
+ mock_recreate.assert_called_once()
+ assert sorted(mock_recreate.call_args.kwargs["tables"]) == ["public.orders", "public.users"]
+
+ for schema in (broken_schema, streaming_schema):
+ schema.refresh_from_db()
+ config = schema.sync_type_config
+ assert config["cdc_mode"] == "snapshot"
+ assert config["reset_pipeline"] is True
+ assert "cdc_broken" not in config
+ assert "cdc_last_log_position" not in config
+ assert "cdc_deferred_runs" not in config
+ assert schema.initial_sync_complete is False
+ assert schema.latest_error is None
+
+ disabled_cdc_schema.refresh_from_db()
+ assert disabled_cdc_schema.sync_type_config == {"cdc_mode": "streaming"}
+ non_cdc_schema.refresh_from_db()
+ assert non_cdc_schema.sync_type_config == {}
+
+ source.refresh_from_db()
+ assert source.job_inputs["cdc_consistent_point"] == "0/AABBCC"
+ assert source.status == ExternalDataSource.Status.RUNNING
+
+ unpaused_ids = {call.args[0] for call in mock_unpause_schema.call_args_list}
+ assert unpaused_ids == {str(broken_schema.id), str(streaming_schema.id)}
+ triggered_ids = {str(call.args[0].id) for call in mock_trigger.call_args_list}
+ assert triggered_ids == {str(broken_schema.id), str(streaming_schema.id)}
+ mock_sync_extraction.assert_called_once()
+ mock_unpause_extraction.assert_called_once_with(str(source.pk))
+
+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_cdc_extraction_schedule")
+ @patch("products.data_warehouse.backend.logic.data_load.service.trigger_external_data_workflow")
+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_external_data_schedule")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",
+ side_effect=psycopg.OperationalError("connection refused"),
+ )
+ def test_repair_cdc_failure_keeps_broken_state(
+ self, _mock_recreate, mock_unpause_schema, mock_trigger, mock_unpause_extraction
+ ) -> None:
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ schema = ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ status=ExternalDataSchema.Status.FAILED,
+ sync_type_config={"cdc_mode": "streaming", "cdc_broken": BROKEN_MARKER},
+ )
+
+ response = self._repair(source)
+ assert response.status_code == 400
+ assert "Could not connect to source to repair CDC" in response.json()["message"]
+
+ # Broken state must survive a failed repair so a retry starts from the same place.
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_broken"] == BROKEN_MARKER
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ mock_unpause_schema.assert_not_called()
+ mock_trigger.assert_not_called()
+ mock_unpause_extraction.assert_not_called()
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot"
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status"
+ )
+ def test_repair_cdc_rejects_healthy_source(self, mock_status, mock_recreate) -> None:
+ # No broken markers and a live probe showing slot + publication present: repair must
+ # refuse — otherwise a stray API call drops a healthy slot and forces a full re-sync.
+ mock_status.return_value = {"slot_exists": True, "publication_exists": True, "lag_bytes": 0}
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
+
+ response = self._repair(source)
+ assert response.status_code == 400
+ assert "CDC looks healthy" in response.json()["message"]
+ mock_recreate.assert_not_called()
+
+ @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")
+ @patch("products.data_warehouse.backend.logic.data_load.service.trigger_external_data_workflow")
+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_external_data_schedule")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",
+ return_value={"cdc_consistent_point": "0/AABBCC"},
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status",
+ return_value={"slot_exists": False, "publication_exists": True, "lag_bytes": None},
+ )
+ def test_repair_cdc_allows_missing_slot_without_marker(
+ self, mock_status, mock_recreate, _unpause, _trigger, _unpause_ext, _sync_ext
+ ) -> None:
+ # A slot dropped on the source database before any extraction run noticed leaves no
+ # cdc_broken marker — the live probe is the evidence that lets repair proceed.
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
+
+ response = self._repair(source)
+ assert response.status_code == 200, response.content
+ mock_recreate.assert_called_once()
+
+ @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")
+ @patch("products.data_warehouse.backend.logic.data_load.service.trigger_external_data_workflow")
+ @patch("products.data_warehouse.backend.logic.data_load.service.unpause_external_data_schedule")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.recreate_slot",
+ 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
+ ) -> 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.
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ cdc_schema = ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming", "cdc_broken": BROKEN_MARKER},
+ )
+ non_cdc_schema = ExternalDataSchema.objects.create(
+ name="incremental_table",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.INCREMENTAL,
+ should_sync=True,
+ )
+ ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline_id=source.pk,
+ schema_id=cdc_schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ workflow_id="cdc-workflow-1",
+ rows_synced=0,
+ )
+ ExternalDataJob.objects.create(
+ team_id=self.team.pk,
+ pipeline_id=source.pk,
+ schema_id=non_cdc_schema.id,
+ status=ExternalDataJob.Status.RUNNING,
+ workflow_id="incremental-workflow-1",
+ rows_synced=0,
+ )
+
+ 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")
+
+ def test_repair_cdc_conflicts_while_another_repair_holds_the_lock(self) -> None:
+ from posthog.redis import get_client
+
+ from products.warehouse_sources.backend.temporal.data_imports.cdc.repair import _repair_lock_key
+
+ source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
+ ExternalDataSchema.objects.create(
+ name="orders",
+ team_id=self.team.pk,
+ source_id=source.pk,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming", "cdc_broken": BROKEN_MARKER},
+ )
+
+ redis = get_client()
+ lock_key = _repair_lock_key(str(source.pk))
+ assert redis.set(lock_key, "1", nx=True, ex=60)
+ try:
+ response = self._repair(source)
+ finally:
+ redis.delete(lock_key)
+
+ assert response.status_code == 409
+ assert "already running" in response.json()["message"]
+
+
class TestUpdateCDCSettings(APIBaseTest):
def test_update_cdc_settings_rejects_source_type_without_cdc_support(self) -> None:
# Stripe has no CDC adapter — the viewset must surface that as a 400, not crash.
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
index 0793f81d30ef..3f3afd100df2 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/CDCSection.tsx
@@ -13,7 +13,7 @@ import {
LemonTag,
} from '@posthog/lemon-ui'
-import api from 'lib/api'
+import api, { ApiConfig } from 'lib/api'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
@@ -27,6 +27,8 @@ import { humanizeBytes } from 'lib/utils/numbers'
import { AccessControlLevel, AccessControlResourceType, ExternalDataSource } from '~/types'
+import { externalDataSourcesRepairCdcCreate } from 'products/warehouse_sources/frontend/generated/api'
+
import { CDC_SOURCE_TYPES } from '../../../shared/cdc'
import { sourceSettingsLogic } from './sourceSettingsLogic'
@@ -226,6 +228,38 @@ function EnabledControls({ source }: { source: ExternalDataSource }): JSX.Elemen
})
}
+ const onRepair = (): void => {
+ confirmThen({
+ title: 'Repair CDC',
+ description: (
+ <div className="space-y-2">
+ <p className="m-0">
+ PostHog will recreate the replication resources on your database and fully re-sync every CDC
+ schema from a fresh snapshot.
+ </p>
+ <p className="m-0 text-sm">
+ Changes made since the slot was lost cannot be recovered — tables will match the current source
+ state once the re-sync completes.
+ </p>
+ </div>
+ ),
+ primaryText: 'Repair and re-sync',
+ onConfirm: async () => {
+ setBusy(true)
+ try {
+ await externalDataSourcesRepairCdcCreate(String(ApiConfig.getCurrentTeamId()), source.id)
+ lemonToast.success('CDC repaired — schemas are re-syncing')
+ loadSource()
+ loadCdcStatus()
+ } catch (e: any) {
+ lemonToast.error(e?.message ?? "Couldn't repair CDC")
+ } finally {
+ setBusy(false)
+ }
+ },
+ })
+ }
+
const onDisable = (): void => {
confirmThen({
title: 'Disable CDC',
@@ -328,9 +362,24 @@ function EnabledControls({ source }: { source: ExternalDataSource }): JSX.Elemen
) : null}
{status && (status.slot_exists === false || status.publication_exists === false) && (
<LemonBanner type="error" className="mt-2">
- {status.slot_exists === false
- ? 'The replication slot is missing on your database — CDC syncs will fail until it is recreated. Disable and re-enable CDC to recreate it.'
- : 'The publication is missing on your database — recreate it (self-managed) or disable and re-enable CDC (PostHog-managed).'}
+ <div className="space-y-2">
+ <p className="m-0">
+ {status.slot_exists === false
+ ? 'The replication slot is missing on your database — CDC syncs will fail until it is recreated. Repairing recreates it and re-syncs every CDC schema from a fresh snapshot.'
+ : 'The publication is missing on your database — recreate it (self-managed) or repair CDC (PostHog-managed).'}
+ </p>
+ {(status.slot_exists === false || cdc.management_mode === 'posthog') && (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.ExternalDataSource}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={source.user_access_level}
+ >
+ <LemonButton type="secondary" size="small" onClick={onRepair} loading={busy}>
+ Repair CDC
+ </LemonButton>
+ </AccessControlAction>
+ )}
+ </div>
</LemonBanner>
)}
{status?.publication_exists && (
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 7069c8bcd6d9..e1f1556e7685 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -19,6 +19,9 @@ _LAZY = {
"CDCSourceAdapter": "cdc.adapters",
"get_cdc_adapter": "cdc.adapters",
"source_type_supports_cdc": "cdc.adapters",
+ "CDCRepairError": "cdc.repair",
+ "CDCRepairInProgress": "cdc.repair",
+ "repair_cdc_source": "cdc.repair",
"ClickHouseSource": "sources.clickhouse.source",
"AnySource": "sources.common.base",
"ExternalWebhookInfo": "sources.common.base",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index bbc39e5e1eb9..38a30c8156dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -56,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import
CDCSchemaMergeError,
classify_cdc_error,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_name
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
@@ -906,21 +907,8 @@ class CDCExtractActivity:
)
def _qualified_table_name(self, schema: ExternalDataSchema) -> str:
- """Resolve a CDC schema row to its source-qualified `schema.table` name.
-
- Prefers stored schema_metadata, then a dotted display name, then the source's
- default schema — so a row stored bare (`orders`) still resolves to its real
- source location (`public.orders`).
- """
default_schema = (self.source.job_inputs or {}).get("schema") if self.source else None
- metadata = schema.sync_type_config.get("schema_metadata") or {}
- src_schema = metadata.get("source_schema")
- src_table = metadata.get("source_table_name")
- if isinstance(src_schema, str) and isinstance(src_table, str):
- return f"{src_schema}.{src_table}"
- if "." in schema.name:
- return schema.name
- return f"{default_schema or 'public'}.{schema.name}"
+ return cdc_qualified_table_name(schema, default_schema)
def _build_event_name_map(self) -> dict[str, str]:
"""Map each schema's source-qualified `schema.table` name to its stored `name`.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
index eaaf543898e8..b82ed7f77a6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
@@ -89,12 +89,12 @@ _CATEGORY_DEFAULTS: dict[CDCErrorCategory, tuple[str, bool]] = {
),
CDCErrorCategory.SLOT_MISSING: (
"The replication slot no longer exists on the source database, so changes can no longer be "
- "read. Disable and re-enable change data capture to recreate it and re-sync.",
+ "read. Use Repair CDC to recreate it and re-sync.",
False,
),
CDCErrorCategory.PUBLICATION_MISSING: (
"The publication used for change data capture no longer exists on the source database. "
- "Recreate it, or disable and re-enable change data capture, then re-sync.",
+ "Recreate it (self-managed), or use Repair CDC (PostHog-managed) to recreate it and re-sync.",
False,
),
CDCErrorCategory.SLOT_IN_USE: (
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py
new file mode 100644
index 000000000000..96a296c12c73
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/naming.py
@@ -0,0 +1,23 @@
+"""Shared CDC naming helpers, dependency-free so both steady-state extraction and
+recovery paths can use them without importing each other."""
+
+from __future__ import annotations
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
+def cdc_qualified_table_name(schema: ExternalDataSchema, default_schema: str | None) -> str:
+ """Resolve a CDC schema row to its source-qualified `schema.table` name.
+
+ Prefers stored schema_metadata, then a dotted display name, then the source's
+ default schema — so a row stored bare (`orders`) still resolves to its real
+ source location (`public.orders`).
+ """
+ metadata = schema.sync_type_config.get("schema_metadata") or {}
+ src_schema = metadata.get("source_schema")
+ src_table = metadata.get("source_table_name")
+ if isinstance(src_schema, str) and isinstance(src_table, str):
+ return f"{src_schema}.{src_table}"
+ if "." in schema.name:
+ return schema.name
+ return f"{default_schema or 'public'}.{schema.name}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
new file mode 100644
index 000000000000..e67129abeb79
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -0,0 +1,227 @@
+"""Repair a broken CDC source.
+
+Recovery counterpart of ``broken.mark_cdc_broken``: once the change-stream resource can be
+recreated (the safety net dropped the slot, or someone dropped it on the source database),
+repair recreates the engine-side resources against the stored CDC config, resets every
+active CDC schema to snapshot mode so it re-syncs from current table state, clears the
+``cdc_broken`` markers, and resumes the paused schedules.
+
+WAL between the old slot's last confirmed position and the new slot's consistent point is
+gone — the re-snapshot covers current rows, but intermediate changes in that gap (including
+their ``_cdc`` history rows) cannot be recovered.
+
+Safeguards, in order:
+
+- a per-source Redis lock rejects concurrent repairs (``CDCRepairInProgress``);
+- repair only proceeds on evidence of breakage — a persisted ``cdc_broken`` marker or a
+ live probe showing the slot/publication missing — so a stray API call against a healthy
+ source can't drop its slot and force a full re-sync of every CDC schema;
+- running CDC jobs are cancelled first (a job holding the slot fails
+ ``pg_drop_replication_slot``, and a wedged run would block the SKIP-overlap schedules);
+- the ``cdc_broken`` markers are cleared only *after* the new slot exists and the schedules
+ are resumed, so a failure at any earlier step leaves the broken evidence in place and a
+ retry passes the gate and re-runs idempotently.
+"""
+
+from __future__ import annotations
+
+import typing
+
+import structlog
+
+from posthog.redis import get_client
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.adapters import CDCSourceAdapter, get_cdc_adapter
+from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_name
+
+logger = structlog.get_logger(__name__)
+
+REPAIR_LOCK_TTL_SECONDS = 300
+
+
+class CDCRepairError(Exception):
+ """Repair cannot proceed; the message is user-facing and credential-safe."""
+
+
+class CDCRepairInProgress(CDCRepairError):
+ """Another repair currently holds this source's repair lock."""
+
+
+def _repair_lock_key(source_id: str) -> str:
+ return f"cdc_repair_lock:{source_id}"
+
+
+def repair_cdc_source(source: ExternalDataSource) -> int:
+ """Repair CDC on a source whose change-stream resources were lost.
+
+ Returns the number of CDC schemas reset for re-sync. Raises ``CDCRepairError`` when
+ there is nothing to repair (no active CDC schemas, source looks healthy) or
+ ``CDCRepairInProgress`` when another repair holds the lock; lets engine/RPC errors
+ propagate for the caller to surface — the flow is safe to re-run after any failure.
+ """
+ redis = get_client()
+ lock_key = _repair_lock_key(str(source.id))
+ if not redis.set(lock_key, "1", nx=True, ex=REPAIR_LOCK_TTL_SECONDS):
+ raise CDCRepairInProgress("A repair is already running for this source. Try again in a few minutes.")
+ try:
+ return _repair_locked(source)
+ finally:
+ # Best-effort: the TTL reaps the lock if this delete is lost.
+ try:
+ redis.delete(lock_key)
+ except Exception:
+ logger.warning("cdc_repair_lock_release_failed", source_id=str(source.id), exc_info=True)
+
+
+def _repair_locked(source: ExternalDataSource) -> int:
+ log = logger.bind(source_id=str(source.id), team_id=source.team_id)
+
+ adapter = get_cdc_adapter(source)
+ # Re-asserted here (not just in the viewset) so any future facade caller inherits the
+ # guard — repairing a CDC-disabled source would provision resources nothing consumes.
+ if not adapter.parse_cdc_config(source).enabled:
+ raise CDCRepairError("CDC is not enabled on this source.")
+
+ cdc_schemas = list(
+ ExternalDataSchema.objects.filter(
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ ).exclude(deleted=True)
+ )
+ if not cdc_schemas:
+ raise CDCRepairError("There are no active CDC schemas on this source to repair.")
+
+ _require_broken_evidence(source, adapter, cdc_schemas)
+ _cancel_running_cdc_jobs(source, cdc_schemas, log)
+
+ # 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
+ # and no schema keeps streaming across the gap unnoticed. Deferred runs are dropped —
+ # 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 in cdc_schemas:
+ update_sync_type_config_keys(
+ schema.id,
+ source.team_id,
+ updates={"cdc_mode": "snapshot", "reset_pipeline": True},
+ removes=["cdc_last_log_position", "cdc_deferred_runs"],
+ extra_model_fields={"initial_sync_complete": False},
+ )
+
+ default_schema = (source.job_inputs or {}).get("schema")
+ resource_fields = adapter.recreate_slot(
+ source, tables=[cdc_qualified_table_name(schema, default_schema) for schema in cdc_schemas]
+ )
+
+ source.job_inputs = {**(source.job_inputs or {}), **resource_fields}
+ source.status = ExternalDataSource.Status.RUNNING
+ source.save(update_fields=["job_inputs", "status", "updated_at"])
+
+ _resume_schedules(source, cdc_schemas)
+
+ # 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
+ # failure inside this loop leaves some markers, which also re-opens the gate.
+ for schema in cdc_schemas:
+ update_sync_type_config_keys(
+ schema.id,
+ source.team_id,
+ removes=["cdc_broken"],
+ extra_model_fields={"latest_error": None},
+ )
+
+ _trigger_resnapshots(cdc_schemas, log)
+
+ log.info("cdc_repair_complete", schemas_reset=len(cdc_schemas))
+ return len(cdc_schemas)
+
+
+def _require_broken_evidence(
+ source: ExternalDataSource, adapter: CDCSourceAdapter, cdc_schemas: list[ExternalDataSchema]
+) -> None:
+ """Refuse to repair a source that looks healthy.
+
+ Repair drops and recreates the slot and forces a full re-sync of every CDC schema, so
+ it must not be reachable as a no-questions-asked API mutation. Evidence is either a
+ persisted ``cdc_broken`` marker or a live probe showing the slot/publication missing
+ (covers a slot dropped on the source database before any extraction run noticed).
+ """
+ if any((schema.sync_type_config or {}).get("cdc_broken") for schema in cdc_schemas):
+ return
+
+ live_status = adapter.get_status(source)
+ if live_status.get("slot_exists") is False or live_status.get("publication_exists") is False:
+ return
+
+ raise CDCRepairError(
+ "CDC looks healthy on this source — the replication slot and publication both exist. "
+ "Repair is only available when one of them is missing, because it forces a full re-sync "
+ "of every CDC schema."
+ )
+
+
+def _cancel_running_cdc_jobs(
+ source: ExternalDataSource, cdc_schemas: list[ExternalDataSchema], log: typing.Any
+) -> None:
+ """Cancel running CDC jobs' workflows before touching the slot.
+
+ A run still holding the slot makes ``pg_drop_replication_slot`` fail, and a wedged
+ Running workflow would block the resumed SKIP-overlap schedules from firing.
+ Best-effort per job: cancellation of an already-dead workflow must not block repair.
+ """
+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
+ from products.data_warehouse.backend.facade.api import cancel_external_data_workflow
+
+ running_jobs = ExternalDataJob.objects.filter(
+ pipeline_id=source.pk,
+ team_id=source.team_id,
+ status=ExternalDataJob.Status.RUNNING,
+ schema_id__in=[schema.id for schema in cdc_schemas],
+ ).exclude(workflow_id__isnull=True)
+ for job in running_jobs:
+ if not job.workflow_id:
+ continue
+ try:
+ cancel_external_data_workflow(job.workflow_id)
+ except Exception:
+ log.warning("cdc_repair_cancel_workflow_failed", workflow_id=job.workflow_id, exc_info=True)
+
+
+def _resume_schedules(source: ExternalDataSource, cdc_schemas: list[ExternalDataSchema]) -> None:
+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
+ from products.data_warehouse.backend.facade.api import (
+ sync_cdc_extraction_schedule,
+ unpause_cdc_extraction_schedule,
+ unpause_external_data_schedule,
+ )
+
+ for schema in cdc_schemas:
+ unpause_external_data_schedule(str(schema.id))
+
+ # Recreate the extraction schedule if it's gone (e.g. deleted out-of-band) — unpausing
+ # a missing schedule is a no-op and would leave CDC repaired but never extracting.
+ sync_cdc_extraction_schedule(source)
+ unpause_cdc_extraction_schedule(str(source.id))
+
+
+def _trigger_resnapshots(cdc_schemas: list[ExternalDataSchema], log: typing.Any) -> None:
+ """Kick each schema's re-snapshot now instead of waiting out a full sync interval.
+
+ Best-effort: the schedules are already unpaused, so a failed trigger only delays the
+ re-sync until the next interval — it must not fail a repair that has already succeeded.
+ """
+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
+ from products.data_warehouse.backend.facade.api import trigger_external_data_workflow
+
+ for schema in cdc_schemas:
+ try:
+ trigger_external_data_workflow(schema)
+ except Exception:
+ log.warning("cdc_repair_trigger_failed", schema_id=str(schema.id), exc_info=True)
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 018fa0a32fab..ae3c55ab32cc 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -5582,6 +5582,11 @@ export type ExternalDataSourcesBulkUpdateSchemasPartialUpdateParams = {
search?: string
}
+export type ExternalDataSourcesRepairCdcCreate200 = {
+ success?: boolean
+ schemas_reset?: number
+}
+
export type ExternalDataSourcesCheckCdcPrerequisitesCreate200 = {
valid?: boolean
errors?: string[]
diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.ts
index c995353ba696..3f16b052b55b 100644
--- a/products/warehouse_sources/frontend/generated/api.ts
+++ b/products/warehouse_sources/frontend/generated/api.ts
@@ -22,6 +22,7 @@ import type {
ExternalDataSourcesConnectLinkRetrieveParams,
ExternalDataSourcesConnectionsListParams,
ExternalDataSourcesListParams,
+ ExternalDataSourcesRepairCdcCreate200,
ExternalDataSourcesStoredCredentialsListParams,
ExternalDataSourcesWizardRetrieveParams,
PaginatedExternalDataSchemaListApi,
@@ -669,6 +670,33 @@ export const externalDataSourcesReloadCreate = async (
})
}
+export const getExternalDataSourcesRepairCdcCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/external_data_sources/${id}/repair_cdc/`
+}
+
+/**
+ * Repair CDC on a source whose replication resources were lost.
+ *
+ * Only proceeds on evidence of breakage (a persisted broken marker, or a live probe
+ * showing the slot/publication missing) — repairing a healthy source would drop its
+ * slot and force a full re-sync. Cancels running CDC jobs, recreates the engine-side
+ * slot/publication against the stored CDC config, resets every active CDC schema to
+ * snapshot mode for a full re-sync (changes since the old slot died are
+ * unrecoverable), clears the broken markers, and resumes the paused schedules.
+ * Idempotent: safe to retry after a partial failure. Concurrent repairs of the same
+ * source are rejected with a 409.
+ */
+export const externalDataSourcesRepairCdcCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ExternalDataSourcesRepairCdcCreate200> => {
+ return apiMutator<ExternalDataSourcesRepairCdcCreate200>(getExternalDataSourcesRepairCdcCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getExternalDataSourcesRevenueAnalyticsConfigPartialUpdateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/external_data_sources/${id}/revenue_analytics_config/`
}
diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yaml
index b3d0eb7a848a..63a848c65a40 100644
--- a/products/warehouse_sources/mcp/tools.yaml
+++ b/products/warehouse_sources/mcp/tools.yaml
@@ -436,6 +436,24 @@ tools:
- prefix
- description
- job_inputs
+ external-data-sources-repair-cdc-create:
+ operation: external_data_sources_repair_cdc_create
+ enabled: true
+ scopes:
+ - external_data_source:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Repair CDC on a source
+ description: >
+ Repair change data capture on a source whose replication slot or publication was lost — use when
+ 'external-data-sources-cdc-status-retrieve' shows slot_exists=false or publication_exists=false, or the
+ source reports a CDC error about a missing slot. Recreates the replication resources from the stored CDC
+ config, resets every active CDC schema to a fresh snapshot (a full re-sync — changes made while the slot was
+ gone cannot be recovered), and resumes the paused sync schedules. Refuses with a 400 if CDC looks healthy
+ (both slot and publication exist) so it cannot accidentally force a re-sync, and with a 409 if a repair is
+ already running. Safe to retry after a failure. Returns {success, schemas_reset}.
external-data-sources-retrieve:
operation: external_data_sources_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a07b83b8ec05..a3a5843aa398 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3583,6 +3583,20 @@
"readOnlyHint": false
}
},
+ "external-data-sources-repair-cdc-create": {
+ "description": "Repair change data capture on a source whose replication slot or publication was lost — use when 'external-data-sources-cdc-status-retrieve' shows slot_exists=false or publication_exists=false, or the source reports a CDC error about a missing slot. Recreates the replication resources from the stored CDC config, resets every active CDC schema to a fresh snapshot (a full re-sync — changes made while the slot was gone cannot be recovered), and resumes the paused sync schedules. Refuses with a 400 if CDC looks healthy (both slot and publication exist) so it cannot accidentally force a re-sync, and with a 409 if a repair is already running. Safe to retry after a failure. Returns {success, schemas_reset}.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Repair CDC on a source",
+ "title": "Repair CDC on a source",
+ "required_scopes": ["external_data_source:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"external-data-sources-retrieve": {
"description": "Get a single data warehouse source by ID. Returns full details including source type, connection status, prefix, all table schemas with their sync statuses, latest error, and last sync timestamp.",
"category": "Warehouse sources",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d2a81e7a9e10..0dc548fde15a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3823,6 +3823,20 @@
"readOnlyHint": false
}
},
+ "external-data-sources-repair-cdc-create": {
+ "description": "Repair change data capture on a source whose replication slot or publication was lost — use when 'external-data-sources-cdc-status-retrieve' shows slot_exists=false or publication_exists=false, or the source reports a CDC error about a missing slot. Recreates the replication resources from the stored CDC config, resets every active CDC schema to a fresh snapshot (a full re-sync — changes made while the slot was gone cannot be recovered), and resumes the paused sync schedules. Refuses with a 400 if CDC looks healthy (both slot and publication exist) so it cannot accidentally force a re-sync, and with a 409 if a repair is already running. Safe to retry after a failure. Returns {success, schemas_reset}.",
+ "category": "Warehouse sources",
+ "feature": "warehouse_sources",
+ "summary": "Repair CDC on a source",
+ "title": "Repair CDC on a source",
+ "required_scopes": ["external_data_source:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"external-data-sources-retrieve": {
"description": "Get a single data warehouse source by ID. Returns full details including source type, connection status, prefix, all table schemas with their sync statuses, latest error, and last sync timestamp.",
"category": "Warehouse sources",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d8460e40ae1b..82db6a070fe5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59215,6 +59215,11 @@ export namespace Schemas {
search?: string;
};
+ export type EnvironmentsExternalDataSourcesRepairCdcCreate200 = {
+ success?: boolean;
+ schemas_reset?: number;
+ };
+
export type EnvironmentsExternalDataSourcesCheckCdcPrerequisitesCreate200 = {
valid?: boolean;
errors?: string[];
@@ -66017,6 +66022,11 @@ export namespace Schemas {
search?: string;
};
+ export type ExternalDataSourcesRepairCdcCreate200 = {
+ success?: boolean;
+ schemas_reset?: number;
+ };
+
export type ExternalDataSourcesCheckCdcPrerequisitesCreate200 = {
valid?: boolean;
errors?: string[];
diff --git a/services/mcp/src/generated/warehouse_sources/api.ts b/services/mcp/src/generated/warehouse_sources/api.ts
index b7d218363a5e..331dd9f1ac74 100644
--- a/services/mcp/src/generated/warehouse_sources/api.ts
+++ b/services/mcp/src/generated/warehouse_sources/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 25 enabled ops
+ * PostHog API - MCP 26 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1537,6 +1537,27 @@ export const ExternalDataSourcesReloadCreateBody = /* @__PURE__ */ zod
})
.describe('Mixin for serializers to add user access control fields')
+/**
+ * Repair CDC on a source whose replication resources were lost.
+ *
+ * Only proceeds on evidence of breakage (a persisted broken marker, or a live probe
+ * showing the slot/publication missing) — repairing a healthy source would drop its
+ * slot and force a full re-sync. Cancels running CDC jobs, recreates the engine-side
+ * slot/publication against the stored CDC config, resets every active CDC schema to
+ * snapshot mode for a full re-sync (changes since the old slot died are
+ * unrecoverable), clears the broken markers, and resumes the paused schedules.
+ * Idempotent: safe to retry after a partial failure. Concurrent repairs of the same
+ * source are rejected with a 409.
+ */
+export const ExternalDataSourcesRepairCdcCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this external data source.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
/**
* Create, Read, Update and Delete External data Sources.
*/
diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.ts
index f5beda35c309..bd98f0a474f4 100644
--- a/services/mcp/src/tools/generated/warehouse_sources.ts
+++ b/services/mcp/src/tools/generated/warehouse_sources.ts
@@ -31,6 +31,7 @@ import {
ExternalDataSourcesRefreshSchemasCreateParams,
ExternalDataSourcesReloadCreateBody,
ExternalDataSourcesReloadCreateParams,
+ ExternalDataSourcesRepairCdcCreateParams,
ExternalDataSourcesRetrieveParams,
ExternalDataSourcesSetupCreateBody,
ExternalDataSourcesStoredCredentialsListQueryParams,
@@ -763,6 +764,21 @@ const externalDataSourcesReload = (): ToolBase<typeof ExternalDataSourcesReloadS
},
})
+const ExternalDataSourcesRepairCdcCreateSchema = ExternalDataSourcesRepairCdcCreateParams.omit({ project_id: true })
+
+const externalDataSourcesRepairCdcCreate = (): ToolBase<typeof ExternalDataSourcesRepairCdcCreateSchema, unknown> => ({
+ name: 'external-data-sources-repair-cdc-create',
+ schema: ExternalDataSourcesRepairCdcCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof ExternalDataSourcesRepairCdcCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/repair_cdc/`,
+ })
+ return result
+ },
+})
+
const ExternalDataSourcesRetrieveSchema = ExternalDataSourcesRetrieveParams.omit({ project_id: true })
const externalDataSourcesRetrieve = (): ToolBase<
@@ -892,6 +908,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'external-data-sources-partial-update': externalDataSourcesPartialUpdate,
'external-data-sources-refresh-schemas': externalDataSourcesRefreshSchemas,
'external-data-sources-reload': externalDataSourcesReload,
+ 'external-data-sources-repair-cdc-create': externalDataSourcesRepairCdcCreate,
'external-data-sources-retrieve': externalDataSourcesRetrieve,
'external-data-sources-update-webhook-inputs-create': externalDataSourcesUpdateWebhookInputsCreate,
'external-data-sources-webhook-info-retrieve': externalDataSourcesWebhookInfoRetrieve,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-repair-cdc-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-repair-cdc-create.json
new file mode 100644
index 000000000000..f4b140f0d7cd
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/external-data-sources-repair-cdc-create.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this external data source.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}