:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): produce internal events for sync alerts (#114376)
Tom Owers96ce887ab810
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex 506638123038..75cefc6a6047 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -47,6 +47,9 @@ _LAZY = {"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",+ "SyncAlertEvent": "logic.external_data_source.alerts",+ "SyncAlertKind": "logic.external_data_source.alerts",+ "emit_sync_alert": "logic.external_data_source.alerts","create_and_register_webhook": "logic.external_data_source.webhooks","delete_webhook_and_hog_function": "logic.external_data_source.webhooks","get_or_create_webhook_hog_function": "logic.external_data_source.webhooks",diff --git a/products/data_warehouse/backend/logic/external_data_source/alerts.py b/products/data_warehouse/backend/logic/external_data_source/alerts.pynew file mode 100644index 000000000000..aeba6c396ec5--- /dev/null+++ b/products/data_warehouse/backend/logic/external_data_source/alerts.py@@ -0,0 +1,190 @@+from enum import StrEnum+from typing import Any+from urllib.parse import quote++from django.conf import settings+from django.core.cache import cache++import structlog+from prometheus_client import Counter++from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event+from posthog.exceptions_capture import capture_exception++from products.cdp.backend.facade.models import HogFunction+from products.warehouse_sources.backend.facade.api import get_sync_alert_context+from products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSchemaStatus++logger = structlog.get_logger(__name__)++SYNC_ALERT_EVENTS = Counter(+ "dwh_sync_alert_events_total",+ "Sync alert internal events, by event name and outcome",+ labelnames=["event", "outcome"],+)++MAX_ERROR_LENGTH = 1000++# A destination created less than this long ago can miss a completed sync. The check runs on every+# completed run of every schema, so it must not query Postgres each time.+SUBSCRIBER_CACHE_SECONDS = 60+++class SyncAlertEvent(StrEnum):+ """Internal events a destination can subscribe to. Saved destinations filter on these names."""++ FAILED = "$data_warehouse_sync_failed"+ RECOVERED = "$data_warehouse_sync_recovered"+ COMPLETED = "$data_warehouse_sync_completed"+ BILLING_LIMIT_REACHED = "$data_warehouse_billing_limit_reached"+++class SyncAlertKind(StrEnum):+ JOB_FAILED = "job_failed"+ SCHEMA_PAUSED = "schema_paused"+ CDC_BROKEN = "cdc_broken"+ BILLING_LIMIT_REACHED = "reached"+ BILLING_LIMIT_TOO_LOW = "too_low"+++BILLING_KIND_BY_STATUS: dict[str, SyncAlertKind] = {+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED: SyncAlertKind.BILLING_LIMIT_REACHED,+ ExternalDataSchemaStatus.BILLING_LIMIT_TOO_LOW: SyncAlertKind.BILLING_LIMIT_TOO_LOW,+}++# Events that fire on every run. The others fire on a state change, so their volume is low enough+# to produce without a subscriber check.+EVENTS_PRODUCED_ONLY_FOR_SUBSCRIBERS = frozenset({SyncAlertEvent.COMPLETED})+++def events_for_terminal_run(+ *,+ status: ExternalDataJobStatus,+ previous_schema_status: str | None,+ previous_failed_runs: int,+ counts_as_source_failure: bool,+) -> list[SyncAlertEvent]:+ """The alert events for the first terminal write of a run.++ Failed, recovered and billing events fire on a state change of the schema, so a schema that+ fails each retry sends one alert, not one for each run. `previous_failed_runs` is the failure+ streak before this run moved it. A failure that says nothing about the source does not start+ a streak, so it sends no failed alert and its next completed run sends no recovered alert.+ """+ if status == ExternalDataJobStatus.FAILED:+ return [SyncAlertEvent.FAILED] if counts_as_source_failure and previous_failed_runs == 0 else []++ if status == ExternalDataJobStatus.COMPLETED:+ recovered = previous_failed_runs > 0 or previous_schema_status in BILLING_KIND_BY_STATUS+ return [SyncAlertEvent.RECOVERED, SyncAlertEvent.COMPLETED] if recovered else [SyncAlertEvent.COMPLETED]++ if status in BILLING_KIND_BY_STATUS and previous_schema_status != status:+ return [SyncAlertEvent.BILLING_LIMIT_REACHED]++ return []+++def emit_terminal_run_alerts(+ *,+ team_id: int,+ schema_id: str,+ job_id: str,+ status: ExternalDataJobStatus,+ previous_schema_status: str | None,+ previous_failed_runs: int,+ counts_as_source_failure: bool,+) -> None:+ for event in events_for_terminal_run(+ status=status,+ previous_schema_status=previous_schema_status,+ previous_failed_runs=previous_failed_runs,+ counts_as_source_failure=counts_as_source_failure,+ ):+ kind = SyncAlertKind.JOB_FAILED if event == SyncAlertEvent.FAILED else BILLING_KIND_BY_STATUS.get(status)+ emit_sync_alert(team_id=team_id, schema_id=schema_id, event=event, kind=kind, job_id=job_id)+++def emit_sync_alert(+ *,+ team_id: int,+ schema_id: str,+ event: SyncAlertEvent,+ kind: SyncAlertKind | None = None,+ job_id: str | None = None,+) -> None:+ """Produce one sync alert event. Never raises, because an alert must not fail the sync that sent it."""+ try:+ if event in EVENTS_PRODUCED_ONLY_FOR_SUBSCRIBERS and not _has_subscriber(team_id, event):+ SYNC_ALERT_EVENTS.labels(event=event.value, outcome="no_subscriber").inc()+ return++ properties = _build_properties(team_id=team_id, schema_id=schema_id, event=event, kind=kind, job_id=job_id)+ if properties is None:+ SYNC_ALERT_EVENTS.labels(event=event.value, outcome="schema_missing").inc()+ return++ produce_internal_event(+ team_id=team_id,+ event=InternalEventEvent(event=event.value, distinct_id=f"team_{team_id}", properties=properties),+ )+ SYNC_ALERT_EVENTS.labels(event=event.value, outcome="produced").inc()+ except Exception as error:+ SYNC_ALERT_EVENTS.labels(event=event.value, outcome="error").inc()+ logger.exception("dwh_sync_alert_emit_failed", team_id=team_id, schema_id=schema_id, event_name=event.value)+ capture_exception(error)+++def _has_subscriber(team_id: int, event: SyncAlertEvent) -> bool:+ cache_key = f"dwh_sync_alert_subscriber:{team_id}:{event.value}"+ cached = cache.get(cache_key)+ if cached is not None:+ return bool(cached)++ has_subscriber = HogFunction.objects.filter(+ team_id=team_id,+ type="internal_destination",+ enabled=True,+ deleted=False,+ filters__events__contains=[{"id": event.value}],+ ).exists()+ cache.set(cache_key, has_subscriber, SUBSCRIBER_CACHE_SECONDS)+ return has_subscriber+++def _build_properties(+ *,+ team_id: int,+ schema_id: str,+ event: SyncAlertEvent,+ kind: SyncAlertKind | None,+ job_id: str | None,+) -> dict[str, Any] | None:+ include_error = event == SyncAlertEvent.FAILED+ context = get_sync_alert_context(team_id, schema_id, job_id, include_error=include_error)+ if context is None:+ return None++ source_url = f"{settings.SITE_URL}/project/{team_id}/data-management/sources/managed-{context.source_id}/syncs"++ # Only a failed event carries the error. A billing-limited run keeps the error of the last real+ # failure on the schema, which is not the reason for a billing event. `latest_error` is the copy+ # the Syncs tab shows. The internal error can hold driver text and connection details.+ error = (context.latest_error or "Unknown error")[:MAX_ERROR_LENGTH] if include_error else None++ return {+ "source_id": str(context.source_id),+ "source_type": context.source_type,+ "source_prefix": (context.source_prefix or "").rstrip("_"),+ "schema_id": str(context.schema_id),+ "schema_name": context.schema_label or context.schema_name,+ "job_id": str(context.job_id) if context.job_id else None,+ "status": context.status,+ "kind": kind.value if kind else None,+ "error": error,+ "rows_synced": context.rows_synced,+ "paused": context.sync_halted,+ "failed_runs_in_a_row": context.failed_runs_in_a_row,+ "source_url": source_url,+ "schema_url": f"{source_url}?schema={quote(context.schema_name)}",+ "finished_at": context.finished_at.isoformat() if context.finished_at else None,+ }diff --git a/products/data_warehouse/backend/logic/external_data_source/jobs.py b/products/data_warehouse/backend/logic/external_data_source/jobs.pyindex 1532099b68f7..49fec32f65f2 100644--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py@@ -9,6 +9,7 @@ from structlog.types import FilteringBoundLoggerfrom posthog.exceptions_capture import capture_exception+from products.data_warehouse.backend.logic.external_data_source.alerts import emit_terminal_run_alertsfrom products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digestfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchemafrom products.warehouse_sources.backend.facade.pipelines import (@@ -72,6 +73,9 @@ def update_external_job_status(gap of its next runs (see `retry_limits`)."""is_first_terminal_transition = False+ schema_status_written = False+ previous_schema_status: str | None = None+ previous_failed_runs = 0with transaction.atomic():model = ExternalDataJob.objects.select_for_update().get(id=job_id, team_id=team_id)@@ -166,6 +170,9 @@ def update_external_job_status(if streak_moved:schema.save(update_fields=["sync_type_config", "updated_at"])else:+ schema_status_written = True+ previous_schema_status = schema.status+ previous_failed_runs = schema.failed_runs_in_a_rowschema.status = schema_statusif not billing_limited_run:schema.latest_error = error_to_persist@@ -202,6 +209,19 @@ def update_external_job_status(except Exception:logger.exception("Failed to schedule external data failure digest")+ # A CDC-halted schema kept its status, so this run changed nothing a destination should hear+ # about. The CDC code sends its own alert when it halts a schema.+ if schema_status_written:+ emit_terminal_run_alerts(+ team_id=team_id,+ schema_id=str(model.schema_id),+ job_id=job_id,+ status=status,+ previous_schema_status=previous_schema_status,+ previous_failed_runs=previous_failed_runs,+ counts_as_source_failure=counts_as_source_failure,+ )+return modeldiff --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.pyindex 36880fb8f865..5c28c1d02c37 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@@ -4,10 +4,13 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import MagicMock, patch+from django.core.cache import cache+from temporalio.exceptions import CancelledErrorfrom posthog.models import Organization, Team+from products.cdp.backend.facade.models import HogFunctionfrom products.data_warehouse.backend.logic.external_data_source.jobs import update_external_job_statusfrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.pipelines import LOCK_TAKEOVER_LATEST_ERROR@@ -522,6 +525,254 @@ class TestUpdateExternalJobStatus:assert schema.sync_type_config == {"failure_streak": {"runs": 7, "last_failed_at": last_failed_at}}+FAILED_EVENT = "$data_warehouse_sync_failed"+RECOVERED_EVENT = "$data_warehouse_sync_recovered"+COMPLETED_EVENT = "$data_warehouse_sync_completed"+BILLING_EVENT = "$data_warehouse_billing_limit_reached"+STREAK_OF_TWO = {"failure_streak": {"runs": 2, "last_failed_at": "2026-01-01T00:00:00+00:00"}}+++class TestSyncAlertEvents:+ @pytest.fixture(autouse=True)+ def _clear_subscriber_cache(self):+ cache.clear()++ @staticmethod+ def _finalize(team, job, status, **kwargs) -> list[dict]:+ 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.schedule_external_data_failure_digest"+ ),+ patch(+ "products.data_warehouse.backend.logic.external_data_source.alerts.produce_internal_event"+ ) as mock_produce,+ ):+ update_external_job_status(+ job_id=str(job.id),+ team_id=team.pk,+ status=status,+ logger=MagicMock(),+ latest_error=kwargs.pop("latest_error", "boom") if status == ExternalDataJobStatus.FAILED else None,+ **kwargs,+ )+ assert all(call.kwargs["team_id"] == team.pk for call in mock_produce.call_args_list)+ return [+ {"event": call.kwargs["event"].event, **call.kwargs["event"].properties}+ for call in mock_produce.call_args_list+ ]++ @staticmethod+ def _subscribe(team, event_name: str) -> None:+ HogFunction.objects.create(+ team=team,+ type="internal_destination",+ enabled=True,+ hog="return event",+ filters={"source": "internal-events", "events": [{"id": event_name, "type": "events"}]},+ )++ @pytest.mark.parametrize(+ "schema_status,sync_type_config,status,counts_as_source_failure,subscribed_to_completed,expected",+ [+ pytest.param(None, {}, ExternalDataJobStatus.FAILED, True, False, [FAILED_EVENT], id="first-failure"),+ pytest.param(+ ExternalDataSchemaStatus.FAILED,+ STREAK_OF_TWO,+ ExternalDataJobStatus.FAILED,+ True,+ False,+ [],+ id="repeat-failure-is-silent",+ ),+ pytest.param(None, {}, ExternalDataJobStatus.FAILED, False, False, [], id="non-source-failure-is-silent"),+ pytest.param(+ None,+ {"cdc_broken": {"reason": "slot_missing"}},+ ExternalDataJobStatus.FAILED,+ True,+ False,+ [],+ id="cdc-halted-schema-is-silent",+ ),+ pytest.param(+ ExternalDataSchemaStatus.FAILED,+ STREAK_OF_TWO,+ ExternalDataJobStatus.COMPLETED,+ True,+ False,+ [RECOVERED_EVENT],+ id="recovered-after-failures",+ ),+ pytest.param(+ ExternalDataSchemaStatus.FAILED,+ STREAK_OF_TWO,+ ExternalDataJobStatus.COMPLETED,+ True,+ True,+ [RECOVERED_EVENT, COMPLETED_EVENT],+ id="recovered-and-completed-with-subscriber",+ ),+ pytest.param(+ ExternalDataSchemaStatus.FAILED,+ {},+ ExternalDataJobStatus.COMPLETED,+ True,+ False,+ [],+ id="completed-after-non-source-failure-is-not-a-recovery",+ ),+ pytest.param(+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,+ {},+ ExternalDataJobStatus.COMPLETED,+ True,+ False,+ [RECOVERED_EVENT],+ id="recovered-after-billing-limit",+ ),+ pytest.param(+ ExternalDataSchemaStatus.COMPLETED,+ {},+ ExternalDataJobStatus.COMPLETED,+ True,+ False,+ [],+ id="completed-without-subscriber-is-not-produced",+ ),+ pytest.param(+ ExternalDataSchemaStatus.COMPLETED,+ {},+ ExternalDataJobStatus.COMPLETED,+ True,+ True,+ [COMPLETED_EVENT],+ id="completed-with-subscriber",+ ),+ pytest.param(+ ExternalDataSchemaStatus.COMPLETED,+ {},+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ True,+ False,+ [BILLING_EVENT],+ id="billing-limit-reached",+ ),+ pytest.param(+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,+ {},+ ExternalDataJobStatus.BILLING_LIMIT_REACHED,+ True,+ False,+ [],+ id="repeat-billing-limit-is-silent",+ ),+ pytest.param(+ ExternalDataSchemaStatus.BILLING_LIMIT_REACHED,+ {},+ ExternalDataJobStatus.BILLING_LIMIT_TOO_LOW,+ True,+ False,+ [BILLING_EVENT],+ id="billing-limit-kind-changed",+ ),+ ],+ )+ def test_terminal_run_produces_alert_events(+ self, schema_status, sync_type_config, status, counts_as_source_failure, subscribed_to_completed, expected+ ):+ team, _source, schema, job = _create_org_team_source_schema_job()+ schema.status = schema_status+ schema.sync_type_config = sync_type_config+ schema.save()+ if subscribed_to_completed:+ self._subscribe(team, COMPLETED_EVENT)++ produced = self._finalize(team, job, status, counts_as_source_failure=counts_as_source_failure)++ assert [event["event"] for event in produced] == expected++ def test_a_repeated_terminal_write_for_the_same_job_produces_no_second_event(self):+ team, _source, _schema, job = _create_org_team_source_schema_job()++ first = self._finalize(team, job, ExternalDataJobStatus.FAILED)+ second = self._finalize(team, job, ExternalDataJobStatus.FAILED)++ assert [event["event"] for event in first] == [FAILED_EVENT]+ assert second == []++ def test_failed_event_properties(self):+ team, source, schema, job = _create_org_team_source_schema_job()+ source.prefix = "billing_"+ source.save()+ schema.label = "Charges"+ schema.save()++ with patch("django.conf.settings.SITE_URL", "https://app.example.com"):+ produced = self._finalize(team, job, ExternalDataJobStatus.FAILED)++ job.refresh_from_db()+ assert job.finished_at is not None+ source_url = f"https://app.example.com/project/{team.pk}/data-management/sources/managed-{source.id}/syncs"+ assert produced == [+ {+ "event": FAILED_EVENT,+ "source_id": str(source.id),+ "source_type": "Stripe",+ "source_prefix": "billing",+ "schema_id": str(schema.id),+ "schema_name": "Charges",+ "job_id": str(job.id),+ "status": ExternalDataSchemaStatus.FAILED,+ "kind": "job_failed",+ "error": "boom",+ "rows_synced": 100,+ "paused": False,+ "failed_runs_in_a_row": 1,+ "source_url": source_url,+ "schema_url": f"{source_url}?schema=Charge",+ "finished_at": job.finished_at.isoformat(),+ }+ ]++ def test_failed_event_error_masks_the_stored_credentials_of_the_source(self):+ team, source, _schema, job = _create_org_team_source_schema_job()+ source.job_inputs = {"stripe_secret_key": "sk_live_stored_credential"}+ source.save()++ produced = self._finalize(+ team,+ job,+ ExternalDataJobStatus.FAILED,+ latest_error="401 for key sk_live_stored_credential at https://api.example.com?api_key=other_secret_value",+ )++ assert produced[0]["error"] == "401 for key *** at https://api.example.com?api_key=***"++ def test_a_produce_error_does_not_fail_the_status_update(self):+ team, _source, _schema, job = _create_org_team_source_schema_job()++ 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.schedule_external_data_failure_digest"+ ),+ patch(+ "products.data_warehouse.backend.logic.external_data_source.alerts.produce_internal_event",+ side_effect=RuntimeError("kafka down"),+ ),+ ):+ updated = update_external_job_status(+ job_id=str(job.id),+ team_id=team.pk,+ status=ExternalDataJobStatus.FAILED,+ logger=MagicMock(),+ latest_error="boom",+ )++ assert updated.status == ExternalDataJobStatus.FAILED++class TestFinalizeQueueSweep:@pytest.mark.parametrize("status",diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex e518fad318ac..a16f64a3fc9e 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -91,6 +91,7 @@ __all__ = ["list_tables_for_source","list_jobs_for_source","list_column_statistics",+ "get_sync_alert_context",# framework-free helper transforms"clickhouse_columns_to_dwh_columns","motherduck_columns_to_dwh_columns",@@ -612,3 +613,18 @@ def list_column_statistics(team_id: int) -> list[contracts.ColumnStatistics]:)for table_id, column_name, null_fraction, min_value, max_value in qs]+++def get_sync_alert_context(+ team_id: int, schema_id: str, job_id: str | None = None, *, include_error: bool = False+) -> contracts.SyncAlertContext | None:+ """The facts a sync alert event reports, or None when the schema no longer exists.++ `include_error` adds the schema's error with the source's stored credentials masked. It is+ opt-in because the masking decrypts the source's inputs, which most alerts have no use for.+ """+ from products.warehouse_sources.backend.sync_alert_context import ( # noqa: PLC0415 -- the redaction helpers sit under presentation, which the facade must not import at module level+ build_sync_alert_context,+ )++ return build_sync_alert_context(team_id, schema_id, job_id, include_error=include_error)diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex 5a2325438512..3e9c83a2ed16 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -225,6 +225,28 @@ class ExternalDataJob:source_prefix: str | None+@dataclass(frozen=True)+class SyncAlertContext:+ """What a sync alert event reports about one schema and, when given, one run.++ `latest_error` is already redacted, so it holds no stored credential of the source.+ """++ source_id: UUID+ source_type: str+ source_prefix: str | None+ schema_id: UUID+ schema_name: str+ schema_label: str | None+ status: str | None+ latest_error: str | None+ sync_halted: bool+ failed_runs_in_a_row: int+ job_id: UUID | None+ rows_synced: int | None+ finished_at: datetime | None++# --- Column annotation ---diff --git a/products/warehouse_sources/backend/sync_alert_context.py b/products/warehouse_sources/backend/sync_alert_context.pynew file mode 100644index 000000000000..3ba49d9653a1--- /dev/null+++ b/products/warehouse_sources/backend/sync_alert_context.py@@ -0,0 +1,40 @@+from products.warehouse_sources.backend.facade import contracts+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+++def build_sync_alert_context(+ team_id: int, schema_id: str, job_id: str | None, *, include_error: bool+) -> contracts.SyncAlertContext | None:+ schema = ExternalDataSchema.objects.select_related("source").filter(id=schema_id, team_id=team_id).first()+ if schema is None:+ return None++ job = ExternalDataJob.objects.filter(id=job_id, team_id=team_id).first() if job_id else None+ source = schema.source++ latest_error = None+ if include_error and schema.latest_error:+ # Deferred: the redaction helpers live under presentation, which imports the facades.+ from products.warehouse_sources.backend.presentation.views.external_data_source.helpers import ( # noqa: PLC0415+ get_error_redaction_values,+ redact_error_message,+ )++ latest_error = redact_error_message(schema.latest_error, get_error_redaction_values(source))++ return contracts.SyncAlertContext(+ source_id=source.id,+ source_type=source.source_type,+ source_prefix=source.prefix,+ schema_id=schema.id,+ schema_name=schema.name,+ schema_label=schema.label,+ status=schema.status,+ latest_error=latest_error,+ sync_halted=schema.sync_halted,+ failed_runs_in_a_row=schema.failed_runs_in_a_row,+ job_id=job.id if job else None,+ rows_synced=job.rows_synced if job else None,+ finished_at=job.finished_at if job else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.pyindex e40607cbbf0f..33ddd5592cf0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py@@ -1288,10 +1288,13 @@ class CDCExtractActivity:# Outside an activity nothing retries, so every failure there is terminal.retries_left = activity.in_activity() and activity.info().attempt < CDC_MAX_EXTRACTION_ATTEMPTSterminal = not info.retryable or not retries_left+ newly_failed_schema_ids: list[str] = []for schema in self.cdc_schemas:# Only a terminal failure paints the schema. A later successful attempt never repaints it,# because its status belongs to the scheduled sync that consumes the buffer.if terminal and not marked_broken:+ if schema.status != ExternalDataSchema.Status.FAILED:+ newly_failed_schema_ids.append(str(schema.id))schema.status = ExternalDataSchema.Status.FAILEDschema.latest_error = friendlyschema.save(update_fields=["status", "latest_error", "updated_at"])@@ -1325,6 +1328,10 @@ class CDCExtractActivity:# here, mirroring what update_external_job_status does for non-CDC syncs.if terminal and not marked_broken:self._schedule_failure_digest()+ # A paused schedule runs no more, so each schema it stops sends the alert once.+ paused = not info.retryable+ alert_schema_ids = [str(schema.id) for schema in self.cdc_schemas] if paused else newly_failed_schema_ids+ self._emit_sync_alerts(alert_schema_ids, paused=paused)# An unclassified failure stays retryable and never pauses the schedule, so a deterministic# one re-fails every scheduled run indefinitely. Only _capture_non_retryable emits analytics,# so these never reach error triage — capture the terminal case so the taxonomy can be taught@@ -1334,6 +1341,24 @@ class CDCExtractActivity:self._emit_run_duration("failed")return info+ def _emit_sync_alerts(self, schema_ids: list[str], *, paused: bool) -> None:+ # An unclassified failure fails every scheduled run again. Only the schemas this run moved+ # to Failed send an alert, so a failure that persists sends one alert, not one for each run.+ # Deferred: the data_warehouse facade imports this pipeline back.+ from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415+ SyncAlertEvent,+ SyncAlertKind,+ emit_sync_alert,+ )++ for schema_id in schema_ids:+ emit_sync_alert(+ team_id=self.inputs.team_id,+ schema_id=schema_id,+ event=SyncAlertEvent.FAILED,+ kind=SyncAlertKind.SCHEMA_PAUSED if paused else SyncAlertKind.JOB_FAILED,+ )+def _schedule_failure_digest(self) -> None:try:# Deferred: the tasks module pulls Celery wiring onto the import path.diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.pyindex 53c3beead768..e07a0d01a180 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/broken.py@@ -119,6 +119,7 @@ def mark_cdc_broken(if create_visibility_jobs:_create_failure_visibility_jobs(source, newly_broken, message, log)_schedule_failure_digest(source, log)+ _emit_sync_alerts(source, newly_broken)_notify(source, message, log)_capture(source, reason, paused=pause, log=log)@@ -253,6 +254,19 @@ def _schedule_failure_digest(source: ExternalDataSource, log: typing.Any) -> Nonlog.warning("cdc_broken_digest_schedule_failed", exc_info=True)+def _emit_sync_alerts(source: ExternalDataSource, schemas: list[ExternalDataSchema]) -> None:+ # Deferred: the data_warehouse facade imports this pipeline back.+ from products.data_warehouse.backend.facade.api import SyncAlertEvent, SyncAlertKind, emit_sync_alert++ for schema in schemas:+ emit_sync_alert(+ team_id=source.team_id,+ schema_id=str(schema.id),+ event=SyncAlertEvent.FAILED,+ kind=SyncAlertKind.CDC_BROKEN,+ )++def _pause_schedules(source: ExternalDataSource, cdc_schemas: list[ExternalDataSchema], log: typing.Any) -> None:# 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_external_data_schedulediff --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.pyindex 705099df0b4a..1589a64a6885 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@@ -98,13 +98,23 @@ def test_re_marking_reports_once_per_reason(team, second_reason, expects_new_evisource = _source(team)schema = _cdc_schema(team, source)- with _mocked_boundaries() as (_pause, mock_digest, _notify, _capture, _table_pause):+ with (+ _mocked_boundaries() as (_pause, mock_digest, _notify, _capture, _table_pause),+ patch(+ "products.data_warehouse.backend.logic.external_data_source.alerts.produce_internal_event"+ ) as mock_produce,+ ):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 1assert ExternalDataJob.objects.filter(schema=schema).count() == expected_evidence_roundsassert mock_digest.call_count == expected_evidence_rounds+ alerts = [+ (produced.kwargs["event"].event, produced.kwargs["event"].properties["kind"])+ for produced in mock_produce.call_args_list+ ]+ assert alerts == [("$data_warehouse_sync_failed", "cdc_broken")] * expected_evidence_roundsdef test_visibility_jobs_can_be_disabled_for_in_run_callers(team):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.pyindex cacaabd5063d..c4baefca1adc 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@@ -612,12 +612,17 @@ class TestErrorClassification:inputs = CDCExtractInput(team_id=1, source_id=source.id)with (patch("products.data_warehouse.backend.facade.tasks.schedule_external_data_failure_digest") as mock_digest,+ patch(+ "products.data_warehouse.backend.logic.external_data_source.alerts.emit_sync_alert"+ ) as mock_emit_sync_alert,pytest.raises(NonRetryableException),):cdc_extract_activity(inputs)assert schema.status == "Failed"assert schema.latest_error == cdc_error_info(CDCErrorCategory.AUTH_FAILED).friendly_message+ mock_emit_sync_alert.assert_called_once()+ assert mock_emit_sync_alert.call_args.kwargs["kind"].value == "schema_paused"# 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"diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex ee5d900cdbfa..51d91113b918 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -31,8 +31,11 @@ from posthog.usage_ingestion.client import UsageRecord, areport_usagefrom posthog.utils import get_machine_idfrom products.data_warehouse.backend.facade.api import (+ SyncAlertEvent,+ SyncAlertKind,a_unpause_external_data_schedule,create_warehouse_templates_for_source,+ emit_sync_alert,update_external_job_status,)from products.managed_warehouse.backend.facade.temporal import (@@ -667,6 +670,18 @@ async def _update_job_status(inputs: UpdateExternalDataJobStatusInputs, logger:counts_as_source_failure=counts_as_source_failure,)+ if has_non_retryable_error:+ # A non-retryable failure does not count toward the failure streak, so the status write+ # above sends no failed alert for it. The schema stops syncing until a person turns it back+ # on, which is the failure a destination most needs to hear about.+ await database_sync_to_async_pool(emit_sync_alert)(+ team_id=inputs.team_id,+ schema_id=inputs.schema_id,+ event=SyncAlertEvent.FAILED,+ kind=SyncAlertKind.SCHEMA_PAUSED,+ job_id=job_id,+ )+if inputs.internal_error and source is not None:# This activity runs once the workflow has given up, so every error reaching here has# already exhausted its retries — including the ones no source classified. Those used todiff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.pyindex 3448299bcaa3..8000bbf6c6ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_external_data_job_activities.py@@ -332,10 +332,17 @@ def test_read_only_transaction_disables_the_schema_only_when_the_source_raised_imock.patch("products.warehouse_sources.backend.temporal.data_imports.external_data_job.update_external_job_status") as mock_update_job_status,+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.external_data_job.emit_sync_alert"+ ) as mock_emit_sync_alert,):asyncio.run(env.run(update_external_data_job_model, inputs))assert mock_update_should_sync.called is expect_disabled+ paused_alerts = [+ (call.kwargs["event"].value, call.kwargs["kind"].value) for call in mock_emit_sync_alert.call_args_list+ ]+ assert paused_alerts == ([("$data_warehouse_sync_failed", "schema_paused")] if expect_disabled else [])customer_message = mock_update_job_status.call_args.kwargs["latest_error"] or ""assert ("tries to write to your database" in customer_message) is expect_disabled