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.

fix(data-warehouse): notify users when CDC syncs halt on non-retriable errors (#71706)

Daniel RC7d3ce04c62bf
diff --git a/posthog/templates/email/external_data_failure_digest.html b/posthog/templates/email/external_data_failure_digest.html
index 3031548d2cd2..9320e37aef44 100644
--- a/posthog/templates/email/external_data_failure_digest.html
+++ b/posthog/templates/email/external_data_failure_digest.html
@@ -10,8 +10,8 @@
Some data warehouse syncs are failing in project <strong>{{ team.name }}</strong>.
{% if has_paused %}
Syncs marked <strong>paused</strong> hit an error we can't retry (for example invalid credentials or an
- unreachable host) &mdash; fix the source configuration, then re-enable syncing to resume. Other syncs will
- be retried automatically on their next scheduled run.
+ unreachable host) &mdash; each sync's error message says how to fix it and get syncing again. Other syncs
+ will be retried automatically on their next scheduled run.
{% else %}
They will be retried automatically on their next scheduled run, but the data in these tables may be out of
date until a sync succeeds.
diff --git a/products/data_warehouse/backend/facade/tasks.py b/products/data_warehouse/backend/facade/tasks.py
index 6f2a49f2a845..903908088d80 100644
--- a/products/data_warehouse/backend/facade/tasks.py
+++ b/products/data_warehouse/backend/facade/tasks.py
@@ -5,5 +5,6 @@ Re-export of the beat-scheduled task that core registers (posthog/tasks/schedule
"""
from products.data_warehouse.backend.tasks import send_external_data_failure_digest_catchup
+from products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digest
-__all__ = ["send_external_data_failure_digest_catchup"]
+__all__ = ["schedule_external_data_failure_digest", "send_external_data_failure_digest_catchup"]
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 b6f9cbda141e..bd3f180a01a0 100644
--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py
@@ -5,11 +5,7 @@ from django.db import transaction
from prometheus_client import Counter
from structlog.types import FilteringBoundLogger
-from products.data_warehouse.backend.tasks import (
- EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS,
- EXTERNAL_DATA_FAILURE_DIGEST_SCHEDULED_COUNTER,
- send_external_data_failure_digest_task,
-)
+from products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digest
from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema
from products.warehouse_sources.backend.facade.pipelines import (
LOCK_TAKEOVER_LATEST_ERROR,
@@ -81,12 +77,13 @@ def update_external_job_status(
schema = ExternalDataSchema.objects.select_for_update().get(id=model.schema_id, team_id=team_id)
- # 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"):
+ # The CDC halted states are absorbing: a loader finishing an in-flight batch after the
+ # source broke (or a non-retryable error paused extraction) must not repaint the schema
+ # healthy while syncing is stopped. Which markers halt a schema is the model's business
+ # (cdc_halted) — this generic layer only honors the state.
+ if schema.cdc_halted:
logger.info(
- "dwh_schema_status_update_skipped_cdc_broken",
+ "dwh_schema_status_update_skipped_cdc_halted",
job_id=job_id,
schema_id=str(schema.id),
requested_status=schema_status,
@@ -104,10 +101,7 @@ def update_external_job_status(
if status == ExternalDataJob.Status.FAILED:
try:
- send_external_data_failure_digest_task.apply_async(
- args=[team_id], countdown=EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS
- )
- EXTERNAL_DATA_FAILURE_DIGEST_SCHEDULED_COUNTER.labels(trigger="inline").inc()
+ schedule_external_data_failure_digest(team_id)
except Exception:
logger.exception("Failed to schedule external data failure digest")
diff --git a/products/data_warehouse/backend/logic/external_data_source/notifications.py b/products/data_warehouse/backend/logic/external_data_source/notifications.py
index 36d5de9f7cad..5c993cad575e 100644
--- a/products/data_warehouse/backend/logic/external_data_source/notifications.py
+++ b/products/data_warehouse/backend/logic/external_data_source/notifications.py
@@ -76,14 +76,17 @@ def notify_external_data_sync_failures(team_id: int) -> None:
.filter(team_id=team_id, status=ExternalDataSchema.Status.FAILED)
.filter(Q(last_error_notified_at__isnull=True) | Exists(newer_failed_job))
.select_related("source")
- # Paused (should_sync=False) schemas first — they need user action.
- .order_by("should_sync", "name")
+ .order_by("name")
)
if not failing_schemas:
return
+ # Halted schemas first — they need user action. sync_halted reads sync_type_config,
+ # so this sort happens in Python, not SQL.
+ failing_schemas.sort(key=lambda schema: not schema.sync_halted)
+
# The template regroups on source_id, which needs schemas consecutive per
- # source; sources with paused schemas come first.
+ # source; sources with halted schemas come first.
schemas_by_source: dict[str, list[ExternalDataSchema]] = {}
for schema in failing_schemas:
schemas_by_source.setdefault(str(schema.source_id), []).append(schema)
@@ -91,7 +94,7 @@ def notify_external_data_sync_failures(team_id: int) -> None:
schema
for group in sorted(
schemas_by_source.values(),
- key=lambda group: (group[0].should_sync, str(group[0].source.source_type).lower()),
+ key=lambda group: (not group[0].sync_halted, str(group[0].source.source_type).lower()),
)
for schema in group
]
@@ -113,7 +116,7 @@ def notify_external_data_sync_failures(team_id: int) -> None:
# The template truncates for display (truncatechars), and the rendered
# HTML is what crosses the Celery boundary — no need to cap here.
"error": schema.latest_error or "Unknown error",
- "paused": not schema.should_sync,
+ "paused": schema.sync_halted,
"url": f"{source_url}?schema={quote(schema.name)}",
}
)
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 7727c32872e4..a268d8f29627 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
@@ -174,8 +174,8 @@ class TestUpdateExternalJobStatus:
with (
patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
patch(
- "products.data_warehouse.backend.logic.external_data_source.jobs.send_external_data_failure_digest_task"
- ) as mock_notify_task,
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ) as mock_schedule_digest,
):
update_external_job_status(
job_id=str(job.id),
@@ -186,11 +186,9 @@ class TestUpdateExternalJobStatus:
)
if expect_notify:
- mock_notify_task.apply_async.assert_called_once()
- assert mock_notify_task.apply_async.call_args.kwargs["args"] == [team.pk]
- assert mock_notify_task.apply_async.call_args.kwargs["countdown"] > 0
+ mock_schedule_digest.assert_called_once_with(team.pk)
else:
- mock_notify_task.apply_async.assert_not_called()
+ mock_schedule_digest.assert_not_called()
def test_failure_notification_not_repeated_on_retried_terminal_transition(self):
team, _source, _schema, job = _create_org_team_source_schema_job()
@@ -198,8 +196,8 @@ class TestUpdateExternalJobStatus:
with (
patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
patch(
- "products.data_warehouse.backend.logic.external_data_source.jobs.send_external_data_failure_digest_task"
- ) as mock_notify_task,
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ) as mock_schedule_digest,
):
for _ in range(2):
update_external_job_status(
@@ -210,7 +208,7 @@ class TestUpdateExternalJobStatus:
latest_error="boom",
)
- mock_notify_task.apply_async.assert_called_once()
+ mock_schedule_digest.assert_called_once()
def test_failed_digest_scheduling_error_does_not_fail_status_update(self):
team, _source, _schema, job = _create_org_team_source_schema_job()
@@ -218,10 +216,10 @@ class TestUpdateExternalJobStatus:
with (
patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"),
patch(
- "products.data_warehouse.backend.logic.external_data_source.jobs.send_external_data_failure_digest_task"
- ) as mock_notify_task,
+ "products.data_warehouse.backend.logic.external_data_source.jobs.schedule_external_data_failure_digest"
+ ) as mock_schedule_digest,
):
- mock_notify_task.apply_async.side_effect = Exception("broker down")
+ mock_schedule_digest.side_effect = Exception("broker down")
updated = update_external_job_status(
job_id=str(job.id),
team_id=team.pk,
@@ -300,12 +298,19 @@ 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.
+ @pytest.mark.parametrize(
+ "halting_marker",
+ [
+ {"cdc_broken": {"reason": "slot_missing", "at": "2026-06-29T10:40:00+00:00"}},
+ {"cdc_extraction_paused": {"reason": "auth_failed", "at": "2026-06-29T10:40:00+00:00"}},
+ ],
+ )
+ def test_cdc_halted_schema_status_is_not_overwritten(self, halting_marker):
+ # A loader finishing an in-flight batch after `mark_cdc_broken` (or after a non-retryable
+ # error paused extraction) must not repaint the schema healthy while syncing is stopped —
+ # the job completes, the schema stays FAILED until the marker is cleared.
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.sync_type_config = halting_marker
schema.status = ExternalDataSchema.Status.FAILED
schema.latest_error = "The replication slot no longer exists on the source database."
schema.save()
diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py b/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py
index a0c09f224562..4a8a2438062c 100644
--- a/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py
+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.py
@@ -56,6 +56,17 @@ class TestNotifyExternalDataSyncFailures:
should_sync=False,
latest_error="Invalid API key",
)
+ # CDC breakage halts syncing without flipping should_sync — it must still read as
+ # "action required", not "will retry".
+ ExternalDataSchema.objects.create(
+ name="Accounts",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ should_sync=True,
+ latest_error="Replication slot dropped",
+ sync_type_config={"cdc_broken": {"reason": "auto_dropped_critical_lag"}},
+ )
with patch(SENDER_PATH) as mock_sender:
notify_external_data_sync_failures(team.pk)
@@ -64,12 +75,13 @@ class TestNotifyExternalDataSyncFailures:
team_id, items = mock_sender.call_args.args
assert team_id == team.pk
assert [(item["schema_name"], item["paused"]) for item in items] == [
+ ("Accounts", True),
("Invoice", True),
("Charge", False),
]
- assert items[0]["error"] == "Invalid API key"
+ assert items[0]["error"] == "Replication slot dropped"
assert items[0]["source_type"] == "Stripe"
- assert f"managed-{source.id}/syncs?schema=Invoice" in items[0]["url"]
+ assert f"managed-{source.id}/syncs?schema=Accounts" in items[0]["url"]
@pytest.mark.parametrize(
"name,label,expected_display",
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 25a8be80010a..7a89da241add 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -3809,7 +3809,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# 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"])
+ update_sync_type_config_keys(
+ schema_id, instance.team_id, removes=["cdc_broken", "cdc_extraction_paused"]
+ )
except ExternalDataSchema.DoesNotExist:
pass
@@ -4007,6 +4009,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
data={"message": f"Could not resume CDC: {e}"},
)
+ # Extraction is running again: clear the paused marker so the schema stops reading as
+ # halted (failure digest badge, loader status guard). Status stays FAILED until a run
+ # actually succeeds. After the unpause, so a failure here leaves the marker for retry.
+ for schema in cdc_schemas:
+ try:
+ update_sync_type_config_keys(schema.id, instance.team_id, removes=["cdc_extraction_paused"])
+ except ExternalDataSchema.DoesNotExist:
+ pass
+
return Response(status=status.HTTP_200_OK, data={"success": True})
@action(methods=["POST"], detail=True)
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index db91eef51123..fc3d83b8e57c 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -12,8 +12,8 @@ from products.data_warehouse.backend.logic.external_data_source.notifications im
logger = structlog.get_logger(__name__)
-# Digest tasks scheduled, by trigger: "inline" (a sync just failed, from jobs.py)
-# vs "catchup" (the daily sweep below). increase(...{trigger="catchup"}[1d]) is the
+# Digest tasks scheduled, by trigger: "inline" (a sync just failed, from jobs.py),
+# "cdc" (a CDC failure path), or "catchup" (the daily sweep below). increase(...{trigger="catchup"}[1d]) is the
# catch-up fan-out — how many teams the daily sweep re-notifies. The inline count is
# the burst denominator: comparing it to delivered emails shows how hard the 15-min
# countdown + campaign-key dedup are collapsing bursts.
@@ -42,6 +42,18 @@ EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS = 15 * 60
EXTERNAL_DATA_FAILURE_DIGEST_LOCK_TIMEOUT_SECONDS = 120
+def schedule_external_data_failure_digest(team_id: int, *, trigger: str = "inline") -> None:
+ """Schedule the per-team failure digest email after the burst-collapse delay.
+
+ Safe to call on every failure: the task dedupes via a per-team lock and a
+ per-digest-day campaign key.
+ """
+ send_external_data_failure_digest_task.apply_async(
+ args=[team_id], countdown=EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS
+ )
+ EXTERNAL_DATA_FAILURE_DIGEST_SCHEDULED_COUNTER.labels(trigger=trigger).inc()
+
+
@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.send_external_data_failure_digest_task")
@skip_team_scope_audit
def send_external_data_failure_digest_task(team_id: int) -> None:
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 482c81a33ec2..fc779e58edf5 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
@@ -11048,7 +11048,11 @@ class TestResumeCDC(APIBaseTest):
)
def test_resume_cdc_unpauses_when_slot_intact(self, mock_get_status, mock_unpause, mock_sync) -> None:
source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)
- self._cdc_schema(source)
+ schema = self._cdc_schema(source)
+ # The non-retryable failure that paused the schedule also stamped this marker; a resume
+ # that leaves it behind keeps the schema reading as halted (digest badge, status guard).
+ schema.sync_type_config["cdc_extraction_paused"] = {"reason": "auth_failed", "at": "2026-07-16T05:42:00+00:00"}
+ schema.save()
response = self._resume(source)
assert response.status_code == 200, response.content
@@ -11058,6 +11062,9 @@ class TestResumeCDC(APIBaseTest):
assert mock_sync.call_args.args[0].pk == source.pk
mock_unpause.assert_called_once_with(str(source.pk))
assert mock_get_status.call_args.args[0].pk == source.pk
+ schema.refresh_from_db()
+ assert "cdc_extraction_paused" not in schema.sync_type_config
+ assert schema.sync_halted is False
@patch("products.data_warehouse.backend.presentation.views.external_data_source.unpause_cdc_extraction_schedule")
@patch(
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 60521fb0657f..696b0f8bb571 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -150,6 +150,19 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
def is_xmin(self):
return self.sync_type == self.SyncType.XMIN
+ @property
+ def cdc_halted(self) -> bool:
+ """True while a CDC marker absorbs status updates: the source is marked broken, or the
+ extraction schedule was paused after a non-retryable error. Cleared by repair, resume,
+ disable, or a successful extraction run."""
+ config = self.sync_type_config or {}
+ return bool(config.get("cdc_broken")) or bool(config.get("cdc_extraction_paused"))
+
+ @property
+ def sync_halted(self) -> bool:
+ """True when syncing will not resume without user action."""
+ return not self.should_sync or self.cdc_halted
+
@property
def xmin_last_value(self) -> int | None:
if self.sync_type_config:
@@ -830,6 +843,37 @@ def update_sync_type_config_keys(
return config
+def complete_schema_run(schema: ExternalDataSchema, *, last_synced_at: datetime) -> bool:
+ """Mark a schema COMPLETED after a successful run, atomically with the broken-state check.
+
+ The sweeper can mark the source broken at any moment; checking ``cdc_broken`` outside the
+ row lock would let a stale instance repaint the schema healthy right after the sweeper wrote
+ FAILED, hiding the breakage from the UI and the failure digest (the loader-side twin of this
+ guard lives in jobs.update_external_job_status, which already checks under its own lock).
+ Clears a stale ``cdc_extraction_paused`` marker — a successful run proves extraction resumed.
+ Returns whether the repaint happened; the passed instance is refreshed either way.
+ """
+ with transaction.atomic():
+ fresh = ExternalDataSchema.objects.select_for_update().get(id=schema.id, team_id=schema.team_id)
+ config = fresh.sync_type_config or {}
+ repainted = not config.get("cdc_broken")
+ if repainted:
+ config.pop("cdc_extraction_paused", None)
+ fresh.sync_type_config = config
+ fresh.status = ExternalDataSchema.Status.COMPLETED
+ fresh.latest_error = None
+ fresh.last_synced_at = last_synced_at
+ fresh.save(
+ update_fields=["sync_type_config", "status", "latest_error", "last_synced_at", "updated_at"],
+ skip_activity_log=True,
+ )
+ schema.sync_type_config = fresh.sync_type_config
+ schema.status = fresh.status
+ schema.latest_error = fresh.latest_error
+ schema.last_synced_at = fresh.last_synced_at
+ return repainted
+
+
def mark_initial_sync_complete(schema_id: str | uuid.UUID, team_id: int) -> None:
"""Mark a schema's first successful sync complete. Shared by the V2 pipelines and the V3 loader.
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 962110bd339b..060c6782ecff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -34,6 +34,7 @@ from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
+ complete_schema_run,
update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -1212,11 +1213,8 @@ class CDCExtractActivity:
now = dt.datetime.now(tz=dt.UTC)
for schema in self.cdc_schemas:
- schema.status = ExternalDataSchema.Status.COMPLETED
- schema.latest_error = None
- schema.last_synced_at = now
- schema.save(update_fields=["status", "latest_error", "last_synced_at", "updated_at"])
- self._record_run_heartbeat(schema, now)
+ if not self._repaint_schema_healthy(schema, now):
+ continue
# Per-schema breadcrumb so the Syncs UI shows _why_ the latest run produced no rows.
self._schema_log(schema).info(
"cdc_extract_no_changes",
@@ -1393,7 +1391,9 @@ class CDCExtractActivity:
)
if marked_broken:
assert self.source is not None
- mark_cdc_broken(self.source, info.category.value, friendly)
+ # This run records its own FAILED job rows below; a second set from mark_cdc_broken
+ # would show every incident as two identical failed runs.
+ mark_cdc_broken(self.source, info.category.value, friendly, create_visibility_jobs=False)
elif not info.retryable and self.source is not None:
# A non-retryable error re-fails every scheduled run, so pause the schedule instead of
# looping it. No cdc_broken marker: the slot is intact, so it stays Repair-CDC-ineligible.
@@ -1403,23 +1403,50 @@ class CDCExtractActivity:
schema.status = ExternalDataSchema.Status.FAILED
schema.latest_error = friendly
schema.save(update_fields=["status", "latest_error", "updated_at"])
+ if not info.retryable:
+ # Persisted so the failure digest email can tell "paused, action required"
+ # apart from "will retry" — the schedule pause itself leaves no DB trace.
+ self._update_schema_sync_type_config(
+ schema,
+ updates={
+ "cdc_extraction_paused": {
+ "reason": info.category.value,
+ "at": dt.datetime.now(tz=dt.UTC).isoformat(),
+ }
+ },
+ )
# 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(
"cdc_extract_schema_failed", error=str(exc), category=info.category, retryable=info.retryable
)
+ terminal = not info.retryable or activity.info().attempt >= CDC_MAX_EXTRACTION_ATTEMPTS
# A failure before the first micro-flush creates no ExternalDataJob, so the Syncs tab stays
- # empty while the schema reads FAILED. Backfill a terminal FAILED row per schema so the run
- # is visible — but only once retries are exhausted or the error is non-retryable, otherwise
- # every transient retry would leave a stray failed row.
- if not self.created_jobs and (activity.info().attempt >= CDC_MAX_EXTRACTION_ATTEMPTS or not info.retryable):
+ # empty while the schema reads FAILED. Backfill a terminal FAILED row per job-less schema so
+ # the run is visible — but only once retries are exhausted or the error is non-retryable,
+ # otherwise every transient retry would leave a stray failed row.
+ if terminal:
try:
self._create_failure_visibility_jobs(friendly)
except Exception:
self.log.warning("cdc_failure_visibility_jobs_failed", exc_info=True)
+ # mark_cdc_broken schedules the digest itself; every other terminal failure schedules it
+ # here, mirroring what update_external_job_status does for non-CDC syncs.
+ if terminal and not marked_broken:
+ self._schedule_failure_digest()
self._emit_run_duration("failed")
return info
+ def _schedule_failure_digest(self) -> None:
+ try:
+ # Deferred: the tasks module pulls Celery wiring onto the import path.
+ from products.data_warehouse.backend.facade.tasks import schedule_external_data_failure_digest
+
+ schedule_external_data_failure_digest(self.inputs.team_id, trigger="cdc")
+ except Exception:
+ # Best-effort: the daily catch-up still delivers via the FAILED job rows.
+ self.log.warning("cdc_digest_schedule_failed", exc_info=True)
+
def _capture_non_retryable(self, info: CDCErrorInfo) -> None:
# Best-effort: analytics must never mask the NonRetryableException the caller is about to raise.
try:
@@ -1436,14 +1463,18 @@ class CDCExtractActivity:
self.log.warning("cdc_non_retryable_capture_failed", exc_info=True)
def _create_failure_visibility_jobs(self, friendly_error: str) -> None:
- """Create one terminal FAILED ExternalDataJob per CDC schema for a run that produced none.
+ """Create one terminal FAILED ExternalDataJob per job-less CDC schema for this run.
Mirrors the running-job creation in _get_or_create_tracker (workflow ids, V3, snapshot) so
the Syncs tab renders these the same way as a job that failed after it started writing.
+ Schemas whose job already exists this run (failed by _fail_created_jobs) are skipped.
"""
now = dt.datetime.now(tz=dt.UTC)
activity_info = activity.info()
+ schema_ids_with_jobs = {job.schema_id for job in self.created_jobs}
for schema in self.cdc_schemas:
+ if schema.id in schema_ids_with_jobs:
+ continue
ExternalDataJob.objects.create(
team_id=self.inputs.team_id,
pipeline_id=self.inputs.source_id,
@@ -1469,15 +1500,29 @@ class CDCExtractActivity:
updates={"cdc_last_run_at": run_at.isoformat(), "cdc_last_run_event_count": self.event_count},
)
+ def _repaint_schema_healthy(self, schema: ExternalDataSchema, now: dt.datetime) -> bool:
+ """Mark a schema COMPLETED after a successful run, respecting the absorbing broken state.
+
+ The marker check and the repaint run in one locked transaction (complete_schema_run) —
+ checking here on the in-memory copy would race the sweeper marking the source broken and
+ overwrite its FAILED with a stale COMPLETED. Returns whether the repaint happened.
+ """
+ try:
+ # The heartbeat records liveness (this run happened), independent of health.
+ self._record_run_heartbeat(schema, now)
+ if not complete_schema_run(schema, last_synced_at=now):
+ self._schema_log(schema).info("cdc_success_repaint_skipped_broken")
+ return False
+ except ExternalDataSchema.DoesNotExist:
+ return False
+ return True
+
def _finalize_success(self) -> None:
now = dt.datetime.now(tz=dt.UTC)
synced_tables = {tracker.table_name for tracker in self.write_trackers.values()}
for schema in self.cdc_schemas:
- schema.status = ExternalDataSchema.Status.COMPLETED
- schema.latest_error = None
- schema.last_synced_at = now
- schema.save(update_fields=["status", "latest_error", "last_synced_at", "updated_at"])
- self._record_run_heartbeat(schema, now)
+ if not self._repaint_schema_healthy(schema, now):
+ continue
# Breadcrumb for idle tables; _handle_no_changes only covers the whole-source-quiet case.
if schema.name not in synced_tables:
self._schema_log(schema).info("cdc_extract_no_changes")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
index a7d91c7cd204..63549d1fd48b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py
@@ -24,11 +24,15 @@ import posthoganalytics
from posthog.utils import get_machine_id
+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.workflow_activities.create_job_model import (
+ _build_schema_snapshot,
+)
logger = structlog.get_logger(__name__)
@@ -39,6 +43,7 @@ def mark_cdc_broken(
message: str,
*,
pause: bool = True,
+ create_visibility_jobs: bool = True,
**extra: typing.Any,
) -> None:
"""Move a CDC source into the broken state.
@@ -47,7 +52,9 @@ def mark_cdc_broken(
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.
+ ``create_visibility_jobs`` is turned off by callers inside a run (the extraction activity),
+ which already record their own FAILED job rows. ``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)
@@ -62,6 +69,15 @@ def mark_cdc_broken(
should_sync=True,
).exclude(deleted=True)
)
+ # The sweeper re-marks an unrepaired source on every sweep while the condition persists.
+ # Report once: only schemas newly entering this broken state produce failure-digest
+ # evidence, otherwise an ongoing condition would re-email the team daily and pile a
+ # synthetic FAILED run per sweep onto the Syncs tab.
+ newly_broken = [
+ schema
+ for schema in cdc_schemas
+ if ((schema.sync_type_config or {}).get("cdc_broken") or {}).get("reason") != reason
+ ]
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(
@@ -77,10 +93,53 @@ def mark_cdc_broken(
if pause:
_pause_schedule(source, log)
+ # Breakage often originates outside a run (the lag sweeper), so no FAILED job row exists.
+ # The failure digest email needs one: its schema query requires a failed job newer than the
+ # last notification, and the daily catch-up selects teams by recent failed jobs.
+ if newly_broken:
+ if create_visibility_jobs:
+ _create_failure_visibility_jobs(source, newly_broken, message, log)
+ _schedule_failure_digest(source, log)
+
_notify(source, message, log)
_capture(source, reason, paused=pause, log=log)
- log.warning("cdc_marked_broken", schemas=len(cdc_schemas), paused=pause)
+ log.warning("cdc_marked_broken", schemas=len(cdc_schemas), newly_broken=len(newly_broken), paused=pause)
+
+
+def _create_failure_visibility_jobs(
+ source: ExternalDataSource,
+ cdc_schemas: list[ExternalDataSchema],
+ message: str,
+ log: typing.Any,
+) -> None:
+ now = dt.datetime.now(tz=dt.UTC)
+ for schema in cdc_schemas:
+ try:
+ ExternalDataJob.objects.create(
+ team_id=source.team_id,
+ pipeline_id=source.id,
+ schema=schema,
+ status=ExternalDataJob.Status.FAILED,
+ rows_synced=0,
+ latest_error=message,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
+ finished_at=now,
+ schema_snapshot=_build_schema_snapshot(schema),
+ )
+ except Exception:
+ log.warning("cdc_broken_visibility_job_failed", schema_id=str(schema.id), exc_info=True)
+
+
+def _schedule_failure_digest(source: ExternalDataSource, log: typing.Any) -> None:
+ try:
+ # Deferred: the tasks module pulls Celery wiring onto the import path.
+ from products.data_warehouse.backend.facade.tasks import schedule_external_data_failure_digest
+
+ schedule_external_data_failure_digest(source.team_id, trigger="cdc")
+ except Exception:
+ # Best-effort: the daily catch-up still delivers via the visibility job rows.
+ log.warning("cdc_broken_digest_schedule_failed", exc_info=True)
def _pause_schedule(source: ExternalDataSource, log: typing.Any) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
index e67129abeb79..db9ac4b97450 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/repair.py
@@ -133,7 +133,7 @@ def _repair_locked(source: ExternalDataSource) -> int:
update_sync_type_config_keys(
schema.id,
source.team_id,
- removes=["cdc_broken"],
+ removes=["cdc_broken", "cdc_extraction_paused"],
extra_model_fields={"latest_error": None},
)
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
index 629218c4e9e4..a055439bf978 100644
--- 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
@@ -4,6 +4,7 @@ from contextlib import contextmanager
import pytest
from unittest.mock import patch
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
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
@@ -34,21 +35,22 @@ def _cdc_schema(team, source, *, name="users", should_sync=True, sync_type=Exter
@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.
+ # Patch the true boundaries mark_cdc_broken reaches (Temporal, Celery, 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.data_warehouse.backend.facade.tasks.schedule_external_data_failure_digest") as mock_digest,
patch("products.notifications.backend.facade.api.create_notification") as mock_notify,
patch("posthoganalytics.capture") as mock_capture,
):
- yield mock_pause, mock_notify, mock_capture
+ yield mock_pause, mock_digest, 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):
+ with _mocked_boundaries() as (mock_pause, mock_digest, mock_notify, mock_capture):
mark_cdc_broken(source, "auto_dropped_critical_lag", "lag too high", lag_mb=4096.0)
source.refresh_from_db()
@@ -64,18 +66,62 @@ def test_persists_broken_state_on_source_and_schemas(team):
# The locked merge must preserve unrelated sync_type_config keys.
assert schema.sync_type_config["cdc_mode"] == "streaming"
+ # Breakage usually happens outside a run (the sweeper), so mark_cdc_broken must leave the
+ # FAILED job row the failure digest email and daily catch-up key off — and schedule the digest.
+ job = ExternalDataJob.objects.get(schema=schema)
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert job.latest_error == "lag too high"
+ assert job.finished_at is not None
+ mock_digest.assert_called_once_with(team.pk, trigger="cdc")
+
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"
+ "second_reason,expects_new_evidence",
+ [
+ ("critical_lag_self_managed", False), # sweeper re-marking an ongoing condition
+ ("slot_missing", True), # a different breakage is new evidence
+ ],
+)
+def test_re_marking_reports_once_per_reason(team, second_reason, expects_new_evidence):
+ # The sweeper calls mark_cdc_broken on every sweep while the condition persists; only a
+ # schema newly entering a broken state may add digest evidence, or an unrepaired source
+ # would re-email the team daily and pile a synthetic failed run per sweep onto the Syncs tab.
+ source = _source(team)
+ schema = _cdc_schema(team, source)
+
+ with _mocked_boundaries() as (_pause, mock_digest, _notify, _capture):
+ mark_cdc_broken(source, "critical_lag_self_managed", "lag too high", pause=False)
+ mark_cdc_broken(source, second_reason, "still broken", pause=False)
+
+ expected_evidence_rounds = 2 if expects_new_evidence else 1
+ assert ExternalDataJob.objects.filter(schema=schema).count() == expected_evidence_rounds
+ assert mock_digest.call_count == expected_evidence_rounds
+
+
+def test_visibility_jobs_can_be_disabled_for_in_run_callers(team):
+ # The extraction activity records its own FAILED rows; a second set from mark_cdc_broken
+ # would render every incident as two identical failed runs.
+ source = _source(team)
+ schema = _cdc_schema(team, source)
+
+ with _mocked_boundaries() as (_pause, mock_digest, _notify, _capture):
+ mark_cdc_broken(source, "slot_missing", "slot gone", create_visibility_jobs=False)
+
+ assert not ExternalDataJob.objects.filter(schema=schema).exists()
+ mock_digest.assert_called_once()
+
+
@pytest.mark.parametrize("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):
+ with _mocked_boundaries() as (mock_pause, _digest, _notify, _capture):
mark_cdc_broken(source, "critical_lag_self_managed", "msg", pause=pause)
assert mock_pause.called is pause
@@ -96,3 +142,6 @@ def test_only_active_cdc_schemas_are_marked(team):
for untouched in (paused, incremental):
untouched.refresh_from_db()
assert "cdc_broken" not in untouched.sync_type_config
+ # Visibility job rows follow the same scoping — a user-paused schema must not resurface
+ # in the failure digest.
+ assert list(ExternalDataJob.objects.values_list("schema_id", flat=True)) == [active.id]
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 6c909d137812..2da74dd8a080 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
@@ -128,13 +128,35 @@ def _fake_update_schema_sync_type_config(schema, *, updates=None, removes=None,
setattr(schema, field, value)
+def _fake_complete_schema_run(schema, *, last_synced_at):
+ """Stand-in for complete_schema_run mirroring its contract on the in-memory mock schema:
+ a broken marker blocks the repaint, otherwise the paused marker clears and the schema
+ repaints COMPLETED. The real locked-transaction semantics are covered by
+ tests/test_models.py::TestCompleteSchemaRun."""
+ config = schema.sync_type_config or {}
+ if config.get("cdc_broken"):
+ return False
+ config.pop("cdc_extraction_paused", None)
+ schema.sync_type_config = config
+ schema.status = ExternalDataSchema.Status.COMPLETED
+ schema.latest_error = None
+ schema.last_synced_at = last_synced_at
+ return True
+
+
@pytest.fixture(autouse=True)
def _stub_sync_type_config_merge():
"""Route every activity sync_type_config write onto the in-memory mock schema (no DB)."""
- with patch.object(
- CDCExtractActivity,
- "_update_schema_sync_type_config",
- side_effect=_fake_update_schema_sync_type_config,
+ with (
+ patch.object(
+ CDCExtractActivity,
+ "_update_schema_sync_type_config",
+ side_effect=_fake_update_schema_sync_type_config,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.cdc.activities.complete_schema_run",
+ side_effect=_fake_complete_schema_run,
+ ),
):
yield
@@ -205,7 +227,7 @@ def _setup_mocks(
MockJob.Status.FAILED = "Failed"
mock_activity.heartbeat = MagicMock()
- mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1")
+ mock_activity.info.return_value = MagicMock(workflow_id="wf-1", workflow_run_id="run-1", attempt=1)
return mock_reader, mock_s3, mock_producer, mock_job
@@ -352,8 +374,11 @@ class TestBackpressureGuard:
with patch("psycopg.Connection.connect", side_effect=Exception("queue db down")):
assert act._previous_load_still_pending() is False
+ # close_old_connections is real Django connection housekeeping: without the patch this
+ # non-django_db test blows up whenever a django_db test ran earlier in the same process.
+ @patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.close_old_connections")
@patch("psycopg.Connection.connect")
- def test_run_skips_tick_without_touching_schemas_or_reader(self, mock_connect):
+ def test_run_skips_tick_without_touching_schemas_or_reader(self, mock_connect, _mock_close_conns):
act = self._activity()
with (
@@ -1081,7 +1106,7 @@ class TestCDCExtractActivity:
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")
+ 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)
cdc_extract_activity(inputs)
@@ -1841,11 +1866,18 @@ class TestErrorClassification:
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):
+ with (
+ patch("products.data_warehouse.backend.facade.tasks.schedule_external_data_failure_digest") as mock_digest,
+ pytest.raises(NonRetryableException),
+ ):
cdc_extract_activity(inputs)
assert schema.status == "Failed"
assert schema.latest_error == cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message
+ # The schedule pause leaves no DB trace of its own; this marker is what tells the failure
+ # digest email "paused, action required" instead of "will retry".
+ assert schema.sync_type_config["cdc_extraction_paused"]["reason"] == "auth_failed"
+ mock_digest.assert_called_once_with(1, trigger="cdc")
mock_posthoganalytics.capture.assert_called_once()
captured = mock_posthoganalytics.capture.call_args.kwargs
@@ -1929,6 +1961,9 @@ class TestErrorClassification:
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
+ # This run backfills its own FAILED rows; mark_cdc_broken adding a second set would
+ # show every incident as two identical failed runs.
+ assert mock_mark_broken.call_args.kwargs["create_visibility_jobs"] is False
mock_pause.assert_not_called()
@patch("products.warehouse_sources.backend.temporal.data_imports.cdc.activities.mark_cdc_broken")
@@ -2577,6 +2612,40 @@ class _ScriptedReader:
pass
+class TestSuccessRepaintGuards:
+ """A run finishing after the sweeper marked the source broken must not repaint the schema
+ healthy — that hides the breakage from the UI and from the failure digest email."""
+
+ def _activity_with(self, *schemas):
+ source = schemas[0].source
+ act = _make_extract_activity(source)
+ act.cdc_schemas = list(schemas)
+ return act
+
+ @pytest.mark.parametrize("finalize", ["success", "no_changes"])
+ def test_broken_schema_keeps_failed_state_and_paused_marker_clears(self, finalize):
+ source = _make_source()
+ broken = _make_schema("broken_table", source=source)
+ broken.status = "Failed"
+ broken.sync_type_config["cdc_broken"] = {"reason": "auto_dropped_critical_lag"}
+ recovered = _make_schema("recovered_table", source=source)
+ recovered.sync_type_config["cdc_extraction_paused"] = {"reason": "auth_failed"}
+ act = self._activity_with(broken, recovered)
+
+ if finalize == "success":
+ act._finalize_success()
+ else:
+ act.reader = MagicMock(last_commit_end_lsn=None)
+ act._handle_no_changes([])
+
+ assert broken.status == "Failed"
+ assert "cdc_broken" in broken.sync_type_config
+ assert recovered.status == ExternalDataSchema.Status.COMPLETED
+ # A successful run proves extraction resumed; the stale pause marker must not keep the
+ # digest email reporting "paused, action required".
+ assert "cdc_extraction_paused" not in recovered.sync_type_config
+
+
class TestCDCBoundedReadLoop:
"""The read loop peeks at most CDC_MAX_CHANGES_PER_READ changes per pass, advancing the slot
between passes so a large backlog drains over several passes (and, if needed, runs)."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
index d5869703dbda..27c1e39010f1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_metrics.py
@@ -140,6 +140,8 @@ def _extract_patches(source, schemas, events):
patch(f"{_ACTIVITIES}.ExternalDataSource") as MockSource,
patch.object(CDCExtractActivity, "_get_cdc_schemas", return_value=schemas),
patch.object(CDCExtractActivity, "_update_schema_sync_type_config"),
+ # The success repaint runs a locked DB transaction; these metric smoke tests are DB-less.
+ patch(f"{_ACTIVITIES}.complete_schema_run", return_value=True),
patch(f"{_ACTIVITIES}.get_cdc_adapter", return_value=adapter),
patch(f"{_ACTIVITIES}.S3BatchWriter", return_value=s3),
patch(f"{_ACTIVITIES}.PostgresProducer"),
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 2264bfeaa71e..aaa00f5d93cf 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
apply_incremental_lookback,
+ complete_schema_run,
mark_initial_sync_complete,
process_incremental_value,
update_sync_type_config_keys,
@@ -460,6 +461,85 @@ class TestMarkInitialSyncComplete(BaseTest):
assert schema.sync_type_config == expected_config
+class TestCompleteSchemaRun(BaseTest):
+ """The success repaint checks the broken marker under the row lock: the sweeper can mark the
+ source broken while a run is in flight, and an unlocked check on a stale instance would
+ overwrite the sweeper's FAILED with COMPLETED, hiding the breakage from the failure digest."""
+
+ def _schema(self, sync_type_config: dict) -> ExternalDataSchema:
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+ return ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source=source,
+ name="users",
+ sync_type="cdc",
+ sync_type_config=sync_type_config,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="boom",
+ )
+
+ @parameterized.expand(
+ [
+ (
+ # The sweeper marked the source broken after this run's instance was loaded;
+ # the stale instance must not repaint FAILED away.
+ "broken_marker_blocks_repaint",
+ {"cdc_mode": "streaming", "cdc_broken": {"reason": "slot_missing"}},
+ False,
+ ExternalDataSchema.Status.FAILED,
+ {"cdc_mode": "streaming", "cdc_broken": {"reason": "slot_missing"}},
+ ),
+ (
+ # A successful run proves extraction resumed: the pause marker is cleared in the
+ # same transaction as the repaint.
+ "paused_marker_cleared_on_repaint",
+ {"cdc_mode": "streaming", "cdc_extraction_paused": {"reason": "auth_failed"}},
+ True,
+ ExternalDataSchema.Status.COMPLETED,
+ {"cdc_mode": "streaming"},
+ ),
+ (
+ "healthy_schema_repaints",
+ {"cdc_mode": "streaming"},
+ True,
+ ExternalDataSchema.Status.COMPLETED,
+ {"cdc_mode": "streaming"},
+ ),
+ ]
+ )
+ def test_repaint_respects_markers(
+ self,
+ _name: str,
+ config: dict,
+ expected_repainted: bool,
+ expected_status: str,
+ expected_config: dict,
+ ) -> None:
+ schema = self._schema({"cdc_mode": "streaming"})
+ # The instance the activity holds predates the sweeper's marker write — a check against
+ # its in-memory config would see no marker and repaint every case below.
+ stale_instance = ExternalDataSchema.objects.get(id=schema.id)
+ ExternalDataSchema.objects.filter(id=schema.id).update(sync_type_config=config)
+
+ now = timezone.now()
+ repainted = complete_schema_run(stale_instance, last_synced_at=now)
+
+ assert repainted is expected_repainted
+ schema.refresh_from_db()
+ assert schema.status == expected_status
+ assert schema.sync_type_config == expected_config
+ assert schema.latest_error == ("boom" if not expected_repainted else None)
+ # The passed instance mirrors the persisted outcome either way.
+ assert stale_instance.status == expected_status
+ assert stale_instance.sync_type_config == expected_config
+
+
@pytest.mark.parametrize(
"clickhouse_type,expected",
[