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): mark CDC sources broken instead of looping (#65905)

Daniel RC4c3f6fdeb7ab
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index a3c0715fd03a..c65497bbbcd7 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -40,6 +40,7 @@ _LAZY = {
"is_cdc_enabled_for_team": "logic.data_load.service",
"is_custom_source_ai_builder_enabled_for_team": "logic.data_load.service",
"is_xmin_enabled_for_team": "logic.data_load.service",
+ "pause_cdc_extraction_schedule": "logic.data_load.service",
"pause_external_data_schedule": "logic.data_load.service",
"sync_cdc_extraction_schedule": "logic.data_load.service",
"sync_discover_schemas_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.py
index 0dfb864cc21c..04c0d3b0c927 100644
--- a/products/data_warehouse/backend/logic/data_load/service.py
+++ b/products/data_warehouse/backend/logic/data_load/service.py
@@ -552,6 +552,23 @@ def delete_cdc_extraction_schedule(source_id: str) -> None:
pass
+def pause_cdc_extraction_schedule(source_id: str) -> None:
+ """Pause the CDC extraction schedule for a source so it stops firing.
+
+ Used when CDC is marked broken (e.g. the safety net dropped the slot): leaving the
+ schedule running would retry forever against a slot that no longer exists. A missing
+ schedule is treated as a no-op.
+ """
+ schedule_id = _get_cdc_extraction_schedule_id(source_id)
+ temporal = sync_connect()
+ try:
+ pause_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/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 9bd28b5f2888..55e7e2d54170 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -96,16 +96,19 @@ from products.data_warehouse.backend.presentation.views.external_data_schema imp
)
from products.data_warehouse.backend.presentation.views.public_source_configs import build_source_configs
from products.revenue_analytics.backend.joins import ensure_person_join, remove_person_join
+from products.warehouse_sources.backend.facade.api import (
+ mysql_columns_to_dwh_columns,
+ postgres_columns_to_dwh_columns,
+ validate_source_prefix,
+)
from products.warehouse_sources.backend.facade.models import (
DataWarehouseTable,
ExternalDataJob,
ExternalDataSchema,
ExternalDataSource,
PendingSourceCredential,
- mysql_columns_to_dwh_columns,
- postgres_columns_to_dwh_columns,
sync_old_schemas_with_new_schemas,
- validate_source_prefix,
+ update_sync_type_config_keys,
)
from products.warehouse_sources.backend.facade.source_management import (
DEFAULT_LAG_CRITICAL_THRESHOLD_MB,
@@ -3281,6 +3284,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
capture_exception(e, {"source_id": str(instance.id)})
with transaction.atomic():
+ # Clear any broken marker (recovery contract): leaving a stale cdc_broken in
+ # sync_type_config would make CDC look broken the moment it's re-enabled.
+ # Must be inside the atomic block so a failed schema-state reset rolls this back too.
+ for schema_id in cdc_schema_ids:
+ try:
+ update_sync_type_config_keys(schema_id, instance.team_id, removes=["cdc_broken"])
+ except ExternalDataSchema.DoesNotExist:
+ pass
+
# Force CDC schemas to pick a new strategy by clearing sync_type and pausing.
ExternalDataSchema.objects.filter(
source=instance,
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 f76f5a84942b..f68e791e043f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -47,8 +47,10 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import
deduplicate_table,
enrich_delete_rows,
)
+from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_broken
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import (
MAX_FRIENDLY_MESSAGE_LENGTH,
+ CDCErrorCategory,
CDCErrorInfo,
CDCSchemaMergeError,
classify_cdc_error,
@@ -1221,10 +1223,19 @@ class CDCExtractActivity:
info = classify_cdc_error(exc, self.adapter)
friendly = info.friendly_message[:MAX_FRIENDLY_MESSAGE_LENGTH]
self._fail_created_jobs(friendly)
+ # A missing slot/publication won't recover on retry: mark the source broken — that persists
+ # the per-schema FAILED state + the cdc_broken marker the UI/health check read and pauses the
+ # schedule, so it stops firing hourly against a resource that is gone (the same zombie the lag
+ # safety net produces). Any other failure just fails this run's schemas.
+ marked_broken = info.category in (CDCErrorCategory.SLOT_MISSING, CDCErrorCategory.PUBLICATION_MISSING)
+ if marked_broken:
+ assert self.source is not None
+ mark_cdc_broken(self.source, info.category.value, friendly)
for schema in self.cdc_schemas:
- schema.status = ExternalDataSchema.Status.FAILED
- schema.latest_error = friendly
- schema.save(update_fields=["status", "latest_error", "updated_at"])
+ if not marked_broken:
+ schema.status = ExternalDataSchema.Status.FAILED
+ schema.latest_error = friendly
+ schema.save(update_fields=["status", "latest_error", "updated_at"])
# User-facing column gets the friendly copy; the raw error still routes to structured
# logs / the Syncs log viewer for debugging.
self._schema_log(schema).error(
@@ -1455,19 +1466,38 @@ def cleanup_orphan_slots_activity() -> None:
adapter.drop_resources(conn, cdc_config.slot_name, cdc_config.publication_name)
slots_dropped += 1
- source.status = ExternalDataSource.Status.ERROR
- source.save(update_fields=["status", "updated_at"])
metrics.get_auto_drop_metric(source.team_id, str(source.id)).add(1)
+ # The slot is gone — move the source to an explicit broken state and pause the
+ # schedule so it stops retrying against a slot that no longer exists.
+ mark_cdc_broken(
+ source,
+ "auto_dropped_critical_lag",
+ f"Change data capture was automatically stopped because replication lag "
+ f"exceeded {critical_threshold_mb} MB and the safety net dropped the "
+ f"replication slot. Use Repair CDC to recreate it and re-sync.",
+ lag_mb=round(lag_mb, 1),
+ )
except Exception:
source_log.exception("failed_to_auto_drop_slot")
metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
elif cdc_config.management_mode == "self_managed":
+ # Customer owns the slot: surface the broken state but keep the schedule running
+ # and never drop — the lag may recover once they reduce load on the source.
try:
- source.status = ExternalDataSource.Status.ERROR
- source.save(update_fields=["status", "updated_at"])
+ mark_cdc_broken(
+ source,
+ "critical_lag_self_managed",
+ f"Change data capture replication lag exceeded {critical_threshold_mb} MB. "
+ f"This slot is self-managed, so PostHog did not drop it — reduce load or WAL "
+ f"retention on the source database, or it may invalidate the slot and "
+ f"require a full re-sync.",
+ pause=False,
+ lag_mb=round(lag_mb, 1),
+ )
except Exception:
- source_log.exception("failed_to_update_source_status")
+ source_log.exception("failed_to_mark_self_managed_broken")
+ metrics.get_sweeper_source_errors_metric().add(1)
sources_errored += 1
elif lag_mb >= cdc_config.lag_warning_threshold_mb:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
new file mode 100644
index 000000000000..a7d91c7cd204
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -0,0 +1,135 @@
+"""Mark a CDC source as broken.
+
+When change data capture can no longer make progress on its own — the safety net dropped
+the slot after critical lag, or an extraction hit a missing slot/publication — the source
+must move to an explicit, user-visible "broken" state instead of silently retrying forever.
+
+This persists the broken state across three surfaces that the UI and health check already read:
+
+- ``source.status = ERROR`` — the source-level "something is wrong" signal.
+- per-CDC-schema ``sync_type_config["cdc_broken"]`` plus ``status=FAILED`` / friendly ``latest_error``.
+- the Temporal extraction schedule is paused so it stops firing against a resource that is gone.
+
+Clearing ``cdc_broken`` and unpausing the schedule (done by ``repair_cdc`` / ``disable_cdc``)
+restores operation — see the recovery contract in those API actions.
+"""
+
+from __future__ import annotations
+
+import typing
+import datetime as dt
+
+import structlog
+import posthoganalytics
+
+from posthog.utils import get_machine_id
+
+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
+
+logger = structlog.get_logger(__name__)
+
+
+def mark_cdc_broken(
+ source: ExternalDataSource,
+ reason: str,
+ message: str,
+ *,
+ pause: bool = True,
+ **extra: typing.Any,
+) -> None:
+ """Move a CDC source into the broken state.
+
+ ``reason`` is a stable machine code (e.g. ``"auto_dropped_critical_lag"``); ``message`` is the
+ friendly, credential-safe copy shown to the user. ``pause`` controls whether the extraction
+ schedule is paused — left on for PostHog-managed breakage (the slot is gone, retrying is futile)
+ and turned off for self-managed critical lag, whose customer-owned slot may still recover.
+ ``extra`` keys (e.g. ``lag_mb``) are merged into the persisted ``cdc_broken`` marker.
+ """
+ log = logger.bind(source_id=str(source.id), team_id=source.team_id, reason=reason)
+
+ source.status = ExternalDataSource.Status.ERROR
+ source.save(update_fields=["status", "updated_at"])
+
+ broken_marker = {"reason": reason, "at": dt.datetime.now(tz=dt.UTC).isoformat(), **extra}
+ cdc_schemas = list(
+ ExternalDataSchema.objects.filter(
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ ).exclude(deleted=True)
+ )
+ for schema in cdc_schemas:
+ # Locked merge so a concurrent API PATCH of sync_type_config can't clobber the marker.
+ update_sync_type_config_keys(
+ schema.id,
+ source.team_id,
+ updates={"cdc_broken": broken_marker},
+ extra_model_fields={
+ "status": ExternalDataSchema.Status.FAILED,
+ "latest_error": message,
+ },
+ )
+
+ if pause:
+ _pause_schedule(source, log)
+
+ _notify(source, message, log)
+ _capture(source, reason, paused=pause, log=log)
+
+ log.warning("cdc_marked_broken", schemas=len(cdc_schemas), paused=pause)
+
+
+def _pause_schedule(source: ExternalDataSource, log: typing.Any) -> None:
+ try:
+ # Deferred: data_load.service participates in the CDC schedule<->workflow import cycle.
+ from products.data_warehouse.backend.facade.api import pause_cdc_extraction_schedule
+
+ pause_cdc_extraction_schedule(str(source.id))
+ except Exception:
+ # Best-effort: a failed pause must not block persisting the broken state.
+ log.warning("cdc_broken_pause_schedule_failed", exc_info=True)
+
+
+def _notify(source: ExternalDataSource, message: str, log: typing.Any) -> None:
+ try:
+ from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationType,
+ Priority,
+ TargetType,
+ create_notification,
+ )
+
+ create_notification(
+ NotificationData(
+ team_id=source.team_id,
+ notification_type=NotificationType.PIPELINE_FAILURE,
+ priority=Priority.NORMAL,
+ title="Change data capture needs attention",
+ body=message,
+ target_type=TargetType.TEAM,
+ target_id=str(source.team_id),
+ )
+ )
+ except Exception:
+ log.warning("cdc_broken_notification_failed", exc_info=True)
+
+
+def _capture(source: ExternalDataSource, reason: str, *, paused: bool, log: typing.Any) -> None:
+ try:
+ posthoganalytics.capture(
+ distinct_id=get_machine_id(),
+ event="cdc marked broken",
+ properties={
+ "team_id": source.team_id,
+ "source_id": str(source.id),
+ "reason": reason,
+ "paused": paused,
+ },
+ )
+ except Exception:
+ log.warning("cdc_broken_capture_failed", exc_info=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py
new file mode 100644
index 000000000000..629218c4e9e4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_broken.py
@@ -0,0 +1,98 @@
+import uuid
+from contextlib import contextmanager
+
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.cdc.broken import mark_cdc_broken
+
+pytestmark = pytest.mark.django_db
+
+
+def _source(team):
+ return ExternalDataSource.objects.create(
+ team_id=team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+
+
+def _cdc_schema(team, source, *, name="users", should_sync=True, sync_type=ExternalDataSchema.SyncType.CDC):
+ return ExternalDataSchema.objects.create(
+ team_id=team.pk,
+ source=source,
+ name=name,
+ sync_type=sync_type,
+ should_sync=should_sync,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
+
+
+@contextmanager
+def _mocked_boundaries():
+ # Patch the true boundaries mark_cdc_broken reaches (Temporal, Kafka, analytics) at their source
+ # modules, since broken.py imports the schedule/notification helpers lazily.
+ with (
+ patch("products.data_warehouse.backend.logic.data_load.service.pause_cdc_extraction_schedule") as mock_pause,
+ patch("products.notifications.backend.facade.api.create_notification") as mock_notify,
+ patch("posthoganalytics.capture") as mock_capture,
+ ):
+ yield mock_pause, mock_notify, mock_capture
+
+
+def test_persists_broken_state_on_source_and_schemas(team):
+ source = _source(team)
+ schema = _cdc_schema(team, source)
+
+ with _mocked_boundaries() as (mock_pause, mock_notify, mock_capture):
+ mark_cdc_broken(source, "auto_dropped_critical_lag", "lag too high", lag_mb=4096.0)
+
+ source.refresh_from_db()
+ assert source.status == ExternalDataSource.Status.ERROR
+
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ assert schema.latest_error == "lag too high"
+ broken = schema.sync_type_config["cdc_broken"]
+ assert broken["reason"] == "auto_dropped_critical_lag"
+ assert broken["lag_mb"] == 4096.0
+ assert "at" in broken
+ # The locked merge must preserve unrelated sync_type_config keys.
+ assert schema.sync_type_config["cdc_mode"] == "streaming"
+
+ mock_pause.assert_called_once_with(str(source.id))
+ mock_notify.assert_called_once()
+ mock_capture.assert_called_once()
+ assert mock_capture.call_args.kwargs["event"] == "cdc marked broken"
+
+
[email protected]("pause", [True, False])
+def test_pause_flag_controls_schedule_pause(team, pause):
+ source = _source(team)
+ _cdc_schema(team, source)
+
+ with _mocked_boundaries() as (mock_pause, _notify, _capture):
+ mark_cdc_broken(source, "critical_lag_self_managed", "msg", pause=pause)
+
+ assert mock_pause.called is pause
+
+
+def test_only_active_cdc_schemas_are_marked(team):
+ source = _source(team)
+ active = _cdc_schema(team, source, name="active")
+ paused = _cdc_schema(team, source, name="paused", should_sync=False)
+ incremental = _cdc_schema(team, source, name="incr", sync_type=ExternalDataSchema.SyncType.INCREMENTAL)
+
+ with _mocked_boundaries():
+ mark_cdc_broken(source, "auto_dropped_critical_lag", "msg")
+
+ active.refresh_from_db()
+ assert "cdc_broken" in active.sync_type_config
+
+ for untouched in (paused, incremental):
+ untouched.refresh_from_db()
+ assert "cdc_broken" not in untouched.sync_type_config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
index 71bc2836410c..86d18c3b605e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_cleanup_orphan_slots.py
@@ -4,6 +4,7 @@ from contextlib import contextmanager
import pytest
from unittest.mock import MagicMock, patch
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.cdc.activities import cleanup_orphan_slots_activity
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
@@ -23,6 +24,17 @@ def _create_source(team, *, deleted=False, job_inputs=None):
)
+def _create_cdc_schema(team, source, name="users"):
+ return ExternalDataSchema.objects.create(
+ team_id=team.pk,
+ source=source,
+ name=name,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ should_sync=True,
+ sync_type_config={"cdc_mode": "streaming"},
+ )
+
+
def _cdc_job_inputs(*, enabled=True, management="posthog", auto_drop_slot=True, slot="posthog_slot", pub="posthog_pub"):
return {
"cdc_enabled": enabled,
@@ -59,9 +71,13 @@ def _run(adapter):
return_value=adapter,
),
patch("products.data_warehouse.backend.logic.data_load.service.delete_cdc_extraction_schedule") as mock_delete,
+ # mark_cdc_broken (critical-lag paths) reaches Temporal / Kafka / analytics — stub the boundaries.
+ patch("products.data_warehouse.backend.logic.data_load.service.pause_cdc_extraction_schedule") as mock_pause,
+ patch("products.notifications.backend.facade.api.create_notification"),
+ patch("posthoganalytics.capture"),
):
cleanup_orphan_slots_activity()
- return mock_activity, mock_delete
+ return mock_activity, mock_delete, mock_pause
def test_encrypted_cdc_source_is_selected(team):
@@ -97,7 +113,7 @@ def test_deleted_posthog_managed_drops_resources_and_schedule(team):
_create_source(team, deleted=True, job_inputs=_cdc_job_inputs(management="posthog"))
adapter = _mock_adapter()
- _, mock_delete = _run(adapter)
+ _, mock_delete, _ = _run(adapter)
mock_delete.assert_called_once()
adapter.drop_resources.assert_called_once()
@@ -108,21 +124,26 @@ def test_deleted_self_managed_drops_schedule_but_not_slot(team):
_create_source(team, deleted=True, job_inputs=_cdc_job_inputs(management="self_managed"))
adapter = _mock_adapter()
- _, mock_delete = _run(adapter)
+ _, mock_delete, _ = _run(adapter)
mock_delete.assert_called_once()
adapter.drop_resources.assert_not_called()
-def test_critical_lag_posthog_auto_drop_drops_and_marks_error(team):
+def test_critical_lag_posthog_auto_drop_marks_broken_and_pauses(team):
source = _create_source(team, job_inputs=_cdc_job_inputs(auto_drop_slot=True))
+ schema = _create_cdc_schema(team, source)
adapter = _mock_adapter(lag_bytes=5000 * 1024 * 1024) # 5000 MB > 2048 MB critical default
- _run(adapter)
+ _, _, mock_pause = _run(adapter)
adapter.drop_resources.assert_called_once()
source.refresh_from_db()
assert source.status == ExternalDataSource.Status.ERROR
+ schema.refresh_from_db()
+ assert schema.status == ExternalDataSchema.Status.FAILED
+ assert schema.sync_type_config["cdc_broken"]["reason"] == "auto_dropped_critical_lag"
+ mock_pause.assert_called_once_with(str(source.id))
def test_critical_lag_auto_drop_disabled_does_not_drop(team):
@@ -136,10 +157,17 @@ def test_critical_lag_auto_drop_disabled_does_not_drop(team):
adapter.drop_resources.assert_not_called()
-def test_critical_lag_self_managed_never_drops(team):
- _create_source(team, job_inputs=_cdc_job_inputs(management="self_managed"))
+def test_critical_lag_self_managed_marks_broken_without_drop_or_pause(team):
+ source = _create_source(team, job_inputs=_cdc_job_inputs(management="self_managed"))
+ schema = _create_cdc_schema(team, source)
adapter = _mock_adapter(lag_bytes=5000 * 1024 * 1024)
- _run(adapter)
+ _, _, mock_pause = _run(adapter)
+ # Customer owns the slot: surface the broken state but never drop or pause — it may recover.
adapter.drop_resources.assert_not_called()
+ mock_pause.assert_not_called()
+ source.refresh_from_db()
+ assert source.status == ExternalDataSource.Status.ERROR
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_broken"]["reason"] == "critical_lag_self_managed"
diff --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.py
index 89a70ed0f4a5..62b23e52c980 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
@@ -1790,6 +1790,80 @@ class TestErrorClassification:
assert captured["properties"]["source_id"] == str(source.id)
mock_reader.close.assert_called_once()
+ @parameterized.expand(
+ [
+ (
+ "slot_missing",
+ psycopg.errors.UndefinedObject,
+ 'replication slot "posthog_slot" does not exist',
+ "slot_missing",
+ ),
+ (
+ "publication_missing",
+ psycopg.errors.UndefinedObject,
+ 'publication "posthog_pub" does not exist',
+ "publication_missing",
+ ),
+ ("auth_failed", psycopg.errors.InvalidPassword, 'password authentication failed for user "test"', None),
+ ]
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_machine_id",
+ return_value="machine-1",
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.posthoganalytics")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
+ @patch.object(CDCExtractActivity, "_get_cdc_schemas")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ def test_missing_slot_or_publication_marks_cdc_broken(
+ self,
+ _name,
+ exc_cls,
+ exc_message,
+ expected_reason,
+ mock_close_conns,
+ MockSourceModel,
+ mock_get_schemas,
+ mock_get_adapter,
+ mock_activity,
+ mock_posthoganalytics,
+ mock_get_machine_id,
+ mock_mark_broken,
+ ):
+ # A missing slot/publication is non-retryable and must trip mark_cdc_broken (pause + persist
+ # the broken marker) so the schedule stops firing against a resource that no longer exists.
+ # A transient auth failure, equally non-retryable, must NOT — it could recover.
+ source = _make_source()
+ MockSourceModel.objects.get.return_value = source
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ mock_get_schemas.return_value = [schema]
+
+ mock_reader = MagicMock()
+ mock_reader.read_changes.side_effect = exc_cls(exc_message)
+ mock_reader.truncated_tables = []
+ mock_adapter = MagicMock()
+ mock_adapter.create_reader.return_value = mock_reader
+ mock_adapter.is_slot_invalidation_error.return_value = False
+ mock_adapter.classify_error = PostgresCDCAdapter().classify_error
+ mock_get_adapter.return_value = mock_adapter
+
+ mock_activity.heartbeat = MagicMock()
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
+
+ inputs = CDCExtractInput(team_id=1, source_id=source.id)
+ with pytest.raises(NonRetryableException):
+ cdc_extract_activity(inputs)
+
+ if expected_reason is None:
+ mock_mark_broken.assert_not_called()
+ else:
+ mock_mark_broken.assert_called_once()
+ assert mock_mark_broken.call_args.args[0] is source
+ assert mock_mark_broken.call_args.args[1] == expected_reason
+
@patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_machine_id",
return_value="machine-1",
@@ -2081,32 +2155,35 @@ class TestCleanupOrphanSlotsRetentionCap:
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
def test_retention_cap_lowers_critical_threshold(
- self, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
+ self, mock_mark_broken, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
):
# Configured critical is 10240 MB, but the engine caps retention at 1000 MB:
# at 900 MB of lag (>= 80% of the cap) the sweeper must already act.
- source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=1000)
+ _source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=1000)
cleanup_orphan_slots_activity()
+ # Dropping + marking broken is the "act" — the broken-state details are covered in test_broken.
mock_adapter.drop_resources.assert_called_once()
- assert source.status is MockSourceModel.Status.ERROR
- source.save.assert_called()
+ mock_mark_broken.assert_called_once()
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.HeartbeaterSync")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.activity")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.get_cdc_adapter")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.ExternalDataSource")
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
def test_unlimited_retention_keeps_configured_threshold(
- self, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
+ self, mock_mark_broken, mock_close_conns, MockSourceModel, mock_get_adapter, mock_activity, mock_heartbeater
):
source, mock_adapter = self._setup(mock_get_adapter, MockSourceModel, lag_mb=900, cap_mb=None)
cleanup_orphan_slots_activity()
mock_adapter.drop_resources.assert_not_called()
+ mock_mark_broken.assert_not_called()
class TestExtractionHeartbeat:
diff --git a/tach.toml b/tach.toml
index ad04245e7fe7..19f825ccb777 100644
--- a/tach.toml
+++ b/tach.toml
@@ -248,6 +248,7 @@ depends_on = [
"products.data_modeling",
"products.data_tools",
"products.data_warehouse",
+ "products.notifications",
"products.posthog_ai",
"products.warehouse_sources_queue",
"products.workflows",