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): email users when external data syncs fail (#62874)

Marcus Hof6ee2e4cf3661
diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
index 33fe1c2213fd..4326525d95b7 100644
--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
@@ -379,7 +379,7 @@ export function UpdateEmailPreferences(): JSX.Element {
<SimpleSwitch
setting="plugin_disabled"
label="Data pipeline errors"
- description="Get notified when data pipeline components (destinations, batch exports) encounter errors for all projects"
+ description="Get notified when data pipeline components (destinations, batch exports, data warehouse sources) encounter errors for all projects"
dataAttr="pipeline_errors_enabled"
/>
{user?.notification_settings?.plugin_disabled !== false && (
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index fa12d23b0167..5614e7590b94 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -12,6 +12,7 @@ import structlog
import posthoganalytics
from celery import shared_task
from posthoganalytics import new_context, tag
+from prometheus_client import Counter, Histogram
from posthog.caching.login_device_cache import check_and_cache_login_device
from posthog.cloud_utils import is_cloud
@@ -608,6 +609,120 @@ def send_batch_export_run_failure(
message.send()
+# The digest "day" rolls over at this hour UTC (not midnight) so the daily block
+# resets — and the catch-up email lands — during waking hours for US and EU.
+# The catch-up cron in scheduled.py is anchored to this constant.
+EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC = 10
+
+# Send-funnel counter: every call lands on exactly one outcome label, so the
+# delivered-vs-suppressed breakdown (and the "delivered" rate that feeds the
+# noise dashboard + alert) is recoverable from a single metric. Intentionally
+# unlabelled by team — per-team volume is read from MessagingRecord instead, to
+# keep Prometheus cardinality bounded.
+EXTERNAL_DATA_FAILURE_DIGEST_COUNTER = Counter(
+ "external_data_failure_digest_total",
+ "External data failure digest email send attempts, by funnel outcome.",
+ labelnames=["outcome"],
+)
+
+# Heaviness of delivered emails — the true failing-schema count (capped rows +
+# omitted), so a digest listing 200 failures is distinguishable from one listing 2.
+EXTERNAL_DATA_FAILURE_DIGEST_SCHEMAS_HISTOGRAM = Histogram(
+ "external_data_failure_digest_schemas",
+ "Failing schemas represented in a delivered failure digest email.",
+ buckets=(1, 2, 3, 5, 10, 20, 30, 50, 100, 250, float("inf")),
+)
+
+EXTERNAL_DATA_FAILURE_DIGEST_OMITTED_COUNTER = Counter(
+ "external_data_failure_digest_omitted_schemas_total",
+ "Failing schemas dropped from delivered digest emails beyond the per-email cap.",
+)
+
+
+def send_external_data_failure_digest(team_id: int, schemas: list[dict[str, Any]], omitted_count: int = 0) -> bool:
+ """Email a per-team digest of failing external data source syncs.
+
+ Runs inside the digest Celery task (products/data_warehouse/backend/tasks.py),
+ so the send is synchronous. The MessagingRecord campaign key embeds the digest
+ day, capping delivery at one email per team per digest day — repeat calls the
+ same day are no-ops.
+
+ Returns whether the email was actually delivered, so the caller can stamp the
+ included schemas as notified.
+ """
+ if not is_email_available(with_absolute_urls=True):
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="email_unavailable").inc()
+ return False
+
+ # Shift the clock back so the date in the key changes at the boundary hour
+ # (UTC-anchored — date.today() would follow the OS timezone instead).
+ digest_day = (timezone.now() - datetime.timedelta(hours=EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC)).date()
+ campaign_key = f"external_data_failure_digest_{team_id}_{digest_day.strftime('%Y-%m-%d')}"
+
+ # Every job in a burst schedules its own delayed digest task; the first to send
+ # wins and the rest bail here, before the expensive recipient queries and render.
+ if MessagingRecord.objects.filter(campaign_key=campaign_key, sent_at__isnull=False).exists():
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="deduped").inc()
+ return False
+
+ try:
+ team = Team.objects.get(id=team_id)
+ except Team.DoesNotExist:
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="team_missing").inc()
+ logger.warning("Team %d not found for external data failure digest", team_id)
+ return False
+
+ # Rollout gate (absent flag = off). Gated teams are never stamped, so when the
+ # flag opens up the catch-up delivers their currently-failing schemas naturally.
+ if not settings.TEST and not posthoganalytics.feature_enabled(
+ key="external-data-failure-digest-email",
+ distinct_id=str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ ):
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="flag_disabled").inc()
+ return False
+
+ memberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)
+ if not memberships_to_email:
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="no_recipients").inc()
+ return False
+
+ paused_count = sum(1 for schema in schemas if schema["paused"])
+ subject = (
+ f"[Alert] Data warehouse syncs paused in project '{team.name}'"
+ if paused_count == len(schemas) and omitted_count == 0
+ else f"[Alert] Data warehouse syncs failing in project '{team.name}'"
+ )
+
+ message = EmailMessage(
+ campaign_key=campaign_key,
+ subject=subject,
+ template_name="external_data_failure_digest",
+ template_context={
+ "team": team,
+ "schemas": schemas,
+ "has_paused": paused_count > 0,
+ "omitted_count": omitted_count,
+ "sources_url": f"{settings.SITE_URL}/project/{team.id}/data-management/sources",
+ },
+ )
+ for membership in memberships_to_email:
+ message.add_user_recipient(membership.user)
+ # _send_email swallows provider failures without retrying, so only
+ # MessagingRecord.sent_at proves delivery — stamping on enqueue would
+ # permanently silence paused schemas whenever a send failed.
+ message.send(send_async=False)
+ delivered = MessagingRecord.objects.filter(campaign_key=campaign_key, sent_at__isnull=False).exists()
+ if delivered:
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="delivered").inc()
+ EXTERNAL_DATA_FAILURE_DIGEST_SCHEMAS_HISTOGRAM.observe(len(schemas) + omitted_count)
+ if omitted_count:
+ EXTERNAL_DATA_FAILURE_DIGEST_OMITTED_COUNTER.inc(omitted_count)
+ else:
+ EXTERNAL_DATA_FAILURE_DIGEST_COUNTER.labels(outcome="send_failed").inc()
+ return delivered
+
+
@shared_task(ignore_result=True)
@skip_team_scope_audit
def send_matview_failure_digest() -> None:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 03c0f0568b12..2308bb67aeab 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -13,6 +13,7 @@ from posthog.clickhouse.client.execute_async import QueryStatusManager
from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports
from posthog.tasks.auth_token_cache_verification import verify_and_fix_auth_token_cache_task
from posthog.tasks.email import (
+ EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC,
send_error_tracking_weekly_digest,
send_hog_functions_daily_digest,
send_matview_failure_digest,
@@ -70,6 +71,7 @@ from posthog.utils import get_crontab, get_instance_region
from products.conversations.backend.tasks import flush_pending_email_replies, wake_snoozed_tickets
from products.data_modeling.backend.tasks.cleanup_test_saved_queries import cleanup_expired_test_saved_queries
+from products.data_warehouse.backend.tasks import send_external_data_failure_digest_catchup
from products.endpoints.backend.tasks import deactivate_stale_materializations
from products.feature_flags.backend.tasks import (
cleanup_stale_flag_definitions_expiry_tracking_task,
@@ -381,6 +383,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="send matview failure digest",
)
+ # Just after the digest day rolls over (EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC),
+ # when the date-keyed campaign block resets.
+ sender.add_periodic_task(
+ crontab(hour=str(EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC), minute="15"),
+ send_external_data_failure_digest_catchup.s(),
+ name="send external data failure digest catch-up",
+ )
+
# Every 30 minutes, send decide request counts to the main posthog instance
sender.add_periodic_task(
crontab(minute="*/30"),
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index d58fbe7a2dd0..6461d6e5b94d 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -15,6 +15,7 @@ from posthog.api.email_verification import email_verification_token_generator
from posthog.models import Organization, Team, User
from posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQL
from posthog.models.instance_setting import set_instance_setting
+from posthog.models.messaging import MessagingRecord
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_invite import OrganizationInvite
from posthog.tasks.email import (
@@ -27,6 +28,7 @@ from posthog.tasks.email import (
send_discussions_mentioned,
send_email_change_emails,
send_email_verification,
+ send_external_data_failure_digest,
send_fatal_plugin_error,
send_hog_function_disabled,
send_hog_functions_daily_digest,
@@ -555,6 +557,190 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
send_batch_export_run_failure(batch_export_run.id, failure_rate=1.0)
assert len(mocked_email_messages) == 0
+ def test_send_external_data_failure_digest(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ with freeze_time("2024-05-15 10:00:00"):
+ sent = send_external_data_failure_digest(
+ self.team.pk,
+ [
+ {
+ "schema_name": "Invoice",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "Invalid API key",
+ "paused": True,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Invoice",
+ },
+ {
+ "schema_name": "Charge",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "transient error",
+ "paused": False,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
+ },
+ ],
+ )
+
+ assert sent is True
+ assert len(mocked_email_messages) == 1
+ assert mocked_email_messages[0].send.call_count == 1
+ assert mocked_email_messages[0].html_body
+ assert (
+ MockEmailMessage.call_args.kwargs["campaign_key"]
+ == f"external_data_failure_digest_{self.team.pk}_2024-05-15"
+ )
+ assert "failing" in MockEmailMessage.call_args.kwargs["subject"]
+
+ def test_send_external_data_failure_digest_day_rolls_over_at_boundary_hour(
+ self, MockEmailMessage: MagicMock
+ ) -> None:
+ mock_email_messages(MockEmailMessage)
+
+ with freeze_time("2024-05-15 09:59:00"):
+ send_external_data_failure_digest(
+ self.team.pk,
+ [
+ {
+ "schema_name": "Charge",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "boom",
+ "paused": False,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
+ }
+ ],
+ )
+
+ assert (
+ MockEmailMessage.call_args.kwargs["campaign_key"]
+ == f"external_data_failure_digest_{self.team.pk}_2024-05-14"
+ )
+
+ @parameterized.expand([(True, 1), (False, 0)])
+ def test_send_external_data_failure_digest_respects_rollout_flag(
+ self, MockEmailMessage: MagicMock, flag_enabled: bool, expected_emails: int
+ ) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ items = [
+ {
+ "schema_name": "Charge",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "boom",
+ "paused": False,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
+ }
+ ]
+ with (
+ self.settings(TEST=False),
+ patch("posthog.tasks.email.posthoganalytics.feature_enabled", return_value=flag_enabled) as mock_flag,
+ ):
+ sent = send_external_data_failure_digest(self.team.pk, items)
+
+ assert sent is flag_enabled
+ assert len(mocked_email_messages) == expected_emails
+ assert mock_flag.call_args.kwargs["key"] == "external-data-failure-digest-email"
+ assert mock_flag.call_args.kwargs["groups"]["project"] == str(self.team.pk)
+
+ def test_send_external_data_failure_digest_skips_when_already_sent_today(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ with freeze_time("2024-05-15 10:00:00"):
+ record, _ = MessagingRecord.objects.get_or_create(
+ raw_email="[email protected]",
+ campaign_key=f"external_data_failure_digest_{self.team.pk}_2024-05-15",
+ )
+ record.sent_at = timezone.now()
+ record.save()
+
+ sent = send_external_data_failure_digest(
+ self.team.pk,
+ [
+ {
+ "schema_name": "Charge",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "boom",
+ "paused": False,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
+ }
+ ],
+ )
+
+ assert sent is False
+ assert len(mocked_email_messages) == 0
+
+ def test_send_external_data_failure_digest_all_paused_subject(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+
+ send_external_data_failure_digest(
+ self.team.pk,
+ [
+ {
+ "schema_name": "Invoice",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "Invalid API key",
+ "paused": True,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Invoice",
+ }
+ ],
+ )
+
+ assert len(mocked_email_messages) == 1
+ assert "paused" in MockEmailMessage.call_args.kwargs["subject"]
+
+ def test_send_external_data_failure_digest_with_settings(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+ user2 = self._create_user("[email protected]")
+ self.user.partial_notification_settings = {"plugin_disabled": False}
+ self.user.save()
+
+ items = [
+ {
+ "schema_name": "Charge",
+ "source_type": "Stripe",
+ "source_id": "abc",
+ "source_prefix": "",
+ "source_url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs",
+ "error": "boom",
+ "paused": False,
+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Charge",
+ }
+ ]
+ with freeze_time("2024-05-15 10:00:00"):
+ send_external_data_failure_digest(self.team.pk, items)
+
+ assert mocked_email_messages[0].to == [
+ {"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}
+ ]
+
+ self.user.partial_notification_settings = {"plugin_disabled": True}
+ self.user.save()
+
+ with freeze_time("2024-05-15 18:00:00"):
+ send_external_data_failure_digest(self.team.pk, items)
+ assert len(mocked_email_messages) == 1
+
+ with freeze_time("2024-05-16 10:00:00"):
+ send_external_data_failure_digest(self.team.pk, items)
+ assert len(mocked_email_messages[1].to) == 2
+
def test_should_send_pipeline_error_notification(self, MockEmailMessage: MagicMock) -> None:
# Default threshold is 1% (0.01) - notify when failure rate exceeds that
assert should_send_pipeline_error_notification(self.user, failure_rate=0.1) is True
diff --git a/posthog/templates/email/external_data_failure_digest.html b/posthog/templates/email/external_data_failure_digest.html
new file mode 100644
index 000000000000..3031548d2cd2
--- /dev/null
+++ b/posthog/templates/email/external_data_failure_digest.html
@@ -0,0 +1,77 @@
+{% extends "email/base.html" %}
+{% load posthog_assets %}
+
+{% block preheader %}Data warehouse sync failures in {{ team.name }}{% endblock %}
+
+{% block heading %}Data warehouse sync failures{% endblock %}
+
+{% block section %}
+<p style="color: #374151;">
+ 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.
+ {% 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.
+ {% endif %}
+</p>
+
+{% regroup schemas by source_id as source_groups %}
+{% for group in source_groups %}
+<div style="background-color: #ffffff; border: 1px solid #e5e7eb; border-left: 4px solid {% if group.list.0.paused %}#dc3545{% else %}#fd7e14{% endif %}; border-radius: 8px; padding: 16px 20px; margin-bottom: 12px;">
+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse;">
+ <tr>
+ <td align="left" style="text-align: left;">
+ <a href="{{ group.list.0.source_url }}" target="_blank" style="text-decoration: none; color: #111827; font-weight: 700; font-size: 1em;">{{ group.list.0.source_type }}</a>
+ {% if group.list.0.source_prefix %}<span style="color: #9ca3af; font-size: 0.85em;">&nbsp;{{ group.list.0.source_prefix }}</span>{% endif %}
+ </td>
+ <td align="right" style="text-align: right; color: #9ca3af; font-size: 0.8em; white-space: nowrap;">
+ {{ group.list|length }} sync{{ group.list|length|pluralize }} failing
+ </td>
+ </tr>
+ </table>
+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse: collapse; margin-top: 10px;">
+ {% for schema in group.list %}
+ <tr>
+ <td align="left" style="padding: 9px 8px 9px 0; border-top: 1px solid #f3f4f6; vertical-align: top; text-align: left; white-space: nowrap;">
+ <a href="{{ schema.url }}" target="_blank" style="text-decoration: none; color: #111827; font-weight: 600; font-size: 0.9em;">{{ schema.schema_name|truncatechars:32 }}</a>
+ </td>
+ <td align="left" style="padding: 9px 8px; border-top: 1px solid #f3f4f6; vertical-align: top; text-align: left; color: #6b7280; font-size: 0.85em; word-break: break-word;">
+ {{ schema.error|truncatechars:90 }}
+ </td>
+ <td align="right" style="padding: 9px 0 9px 8px; border-top: 1px solid #f3f4f6; vertical-align: top; text-align: right; white-space: nowrap;">
+ {% if schema.paused %}
+ <span style="background-color: #fee2e2; color: #b91c1c; border-radius: 9999px; padding: 2px 10px; font-size: 0.75em; font-weight: 600;">Paused &mdash; action required</span>
+ {% else %}
+ <span style="background-color: #f3f4f6; color: #6b7280; border-radius: 9999px; padding: 2px 10px; font-size: 0.75em;">Will retry</span>
+ {% endif %}
+ </td>
+ </tr>
+ {% endfor %}
+ </table>
+</div>
+{% endfor %}
+
+{% if omitted_count %}
+<p style="font-size: 0.9em; color: #374151; margin-top: 8px;">
+ &hellip;and <strong>{{ omitted_count }}</strong> more failing syncs &mdash;
+ <a href="{{ sources_url }}" target="_blank" style="color: #111827; font-weight: 600;">view them all in PostHog</a>.
+</p>
+{% endif %}
+
+<p style="font-size: 0.85em; color: #6b7280; margin-top: 16px;">
+ Click a source to open it in PostHog, or a sync name to see its history and full error details.
+</p>
+
+{% endblock %}
+
+{% block footer %}
+Need help?
+<a href="https://posthog.com/questions?{{ utm_tags }}" target="_blank"><b>Visit support</b></a>
+or
+<a href="https://posthog.com/docs/cdp/sources?{{ utm_tags }}" target="_blank"><b>read our documentation</b></a>.<br /><br />
+
+<a href="{% absolute_uri '/settings/user-notifications' %}">Manage these notifications in PostHog</a>
+{% endblock %}
diff --git a/products/data_warehouse/backend/external_data_source/jobs.py b/products/data_warehouse/backend/external_data_source/jobs.py
index 775e2c9a378b..384a00cf307d 100644
--- a/products/data_warehouse/backend/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/external_data_source/jobs.py
@@ -4,6 +4,11 @@ from structlog.types import FilteringBoundLogger
from posthog.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES, emit_data_import_app_metrics
+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.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -49,4 +54,13 @@ def update_external_job_status(
logger.debug("Emitting app metrics")
emit_data_import_app_metrics(model)
+ 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()
+ except Exception:
+ logger.exception("Failed to schedule external data failure digest")
+
return model
diff --git a/products/data_warehouse/backend/external_data_source/notifications.py b/products/data_warehouse/backend/external_data_source/notifications.py
new file mode 100644
index 000000000000..6cf4b2e6dd91
--- /dev/null
+++ b/products/data_warehouse/backend/external_data_source/notifications.py
@@ -0,0 +1,117 @@
+import datetime as dt
+from urllib.parse import quote
+
+from django.conf import settings
+from django.db.models import Exists, OuterRef, Q
+from django.utils import timezone
+
+import structlog
+
+from posthog.tasks.email import send_external_data_failure_digest
+
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+logger = structlog.get_logger(__name__)
+
+# A broken source can fail hundreds of schemas at once; cap the email table and
+# point at the sources page for the rest. Omitted schemas are still stamped as
+# notified — the email communicates them in aggregate via the "+N more" line.
+MAX_SCHEMAS_PER_DIGEST_EMAIL = 30
+
+
+def get_team_ids_with_recent_sync_failures(lookback: dt.timedelta = dt.timedelta(hours=26)) -> list[int]:
+ """Teams with still-failing schemas that have an un-communicated recent failure.
+
+ Powers the daily catch-up digest: failures that the one-email-per-day block
+ swallowed get flushed the next day — including schemas that were paused and
+ will never produce another failed run to re-trigger the inline path. A failure
+ counts only if it is newer than the schema's `last_error_notified_at` stamp,
+ so failures already covered by an earlier digest don't trigger a duplicate.
+
+ The lookback exceeds the 24h digest day on purpose: a failure just after the
+ 10:00 UTC rollover, blocked because that digest day's email already went out,
+ is 24h15m+ old by the next catch-up run — a 24h lookback would drop it forever
+ for paused schemas. The stamp check above keeps the wider window duplicate-free.
+ """
+ cutoff = dt.datetime.now(dt.UTC) - lookback
+ # Drive from the schema side: the jobs table grows with every sync run and has
+ # no index on (status, finished_at), so starting there would seq-scan it daily.
+ # Schemas are one row each, and their jobs are reachable via the schema_id FK index.
+ unnotified_failed_job = ExternalDataJob.objects.filter(
+ schema_id=OuterRef("id"),
+ status=ExternalDataJob.Status.FAILED,
+ finished_at__gte=cutoff,
+ ).filter(Q(schema__last_error_notified_at__isnull=True) | Q(finished_at__gt=OuterRef("last_error_notified_at")))
+ return list(
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(status=ExternalDataSchema.Status.FAILED)
+ .filter(Exists(unnotified_failed_job))
+ .values_list("team_id", flat=True)
+ .distinct()
+ )
+
+
+def notify_external_data_sync_failures(team_id: int) -> None:
+ """Email the team a digest of every currently-failing external data schema.
+
+ Runs inside the digest Celery task; exceptions are swallowed so a notification
+ problem never crash-loops the task. Throttling to one email per team per digest
+ day happens in the email layer via the MessagingRecord campaign key, so
+ scheduling this for every failed job is safe.
+ """
+ try:
+ failing_schemas = list(
+ ExternalDataSchema.objects.exclude(deleted=True)
+ .filter(team_id=team_id, status=ExternalDataSchema.Status.FAILED)
+ .select_related("source")
+ # Paused (should_sync=False) schemas first — they need user action.
+ .order_by("should_sync", "name")
+ )
+ if not failing_schemas:
+ return
+
+ # The template regroups on source_id, which needs schemas consecutive per
+ # source; sources with paused 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)
+ ordered_schemas = [
+ schema
+ for group in sorted(
+ schemas_by_source.values(),
+ key=lambda group: (group[0].should_sync, str(group[0].source.source_type).lower()),
+ )
+ for schema in group
+ ]
+
+ items = []
+ for schema in ordered_schemas[:MAX_SCHEMAS_PER_DIGEST_EMAIL]:
+ source_url = (
+ f"{settings.SITE_URL}/project/{team_id}/data-management/sources/managed-{schema.source_id}/syncs"
+ )
+ items.append(
+ {
+ "schema_name": schema.name,
+ "source_id": str(schema.source_id),
+ "source_type": schema.source.source_type,
+ "source_prefix": (schema.source.prefix or "").rstrip("_"),
+ "source_url": source_url,
+ # 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,
+ "url": f"{source_url}?schema={quote(schema.name)}",
+ }
+ )
+
+ omitted_count = max(0, len(failing_schemas) - MAX_SCHEMAS_PER_DIGEST_EMAIL)
+ sent = send_external_data_failure_digest(team_id, items, omitted_count=omitted_count)
+ if sent:
+ # Mark every listed schema as communicated, so the daily catch-up only
+ # re-triggers for failures that happened after this email went out.
+ ExternalDataSchema.objects.filter(team_id=team_id, id__in=[schema.id for schema in failing_schemas]).update(
+ last_error_notified_at=timezone.now()
+ )
+ except Exception:
+ logger.exception("Failed to send external data sync failure digest", team_id=team_id)
diff --git a/products/data_warehouse/backend/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/external_data_source/test/test_jobs.py
index d19d3a038139..a13db4f00209 100644
--- a/products/data_warehouse/backend/external_data_source/test/test_jobs.py
+++ b/products/data_warehouse/backend/external_data_source/test/test_jobs.py
@@ -158,3 +158,78 @@ class TestUpdateExternalJobStatus:
assert updated.finished_at is not None
assert updated.latest_error == "boom"
mock_emit.assert_called_once()
+
+ @pytest.mark.parametrize(
+ "status,expect_notify",
+ [
+ (ExternalDataJob.Status.FAILED, True),
+ (ExternalDataJob.Status.COMPLETED, False),
+ (ExternalDataJob.Status.BILLING_LIMIT_REACHED, False),
+ (ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW, False),
+ (ExternalDataJob.Status.RUNNING, False),
+ ],
+ )
+ def test_failure_notification_only_fires_on_failed_status(self, status, expect_notify):
+ team, _source, _schema, job = _create_org_team_source_schema_job()
+
+ with (
+ patch("products.data_warehouse.backend.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.external_data_source.jobs.send_external_data_failure_digest_task"
+ ) as mock_notify_task,
+ ):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=status,
+ logger=MagicMock(),
+ latest_error="boom" if status == ExternalDataJob.Status.FAILED else None,
+ )
+
+ 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
+ else:
+ mock_notify_task.apply_async.assert_not_called()
+
+ def test_failure_notification_not_repeated_on_retried_terminal_transition(self):
+ team, _source, _schema, job = _create_org_team_source_schema_job()
+
+ with (
+ patch("products.data_warehouse.backend.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.external_data_source.jobs.send_external_data_failure_digest_task"
+ ) as mock_notify_task,
+ ):
+ for _ in range(2):
+ update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.FAILED,
+ logger=MagicMock(),
+ latest_error="boom",
+ )
+
+ mock_notify_task.apply_async.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()
+
+ with (
+ patch("products.data_warehouse.backend.external_data_source.jobs.emit_data_import_app_metrics"),
+ patch(
+ "products.data_warehouse.backend.external_data_source.jobs.send_external_data_failure_digest_task"
+ ) as mock_notify_task,
+ ):
+ mock_notify_task.apply_async.side_effect = Exception("broker down")
+ updated = update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=ExternalDataJob.Status.FAILED,
+ logger=MagicMock(),
+ latest_error="boom",
+ )
+
+ assert updated.status == ExternalDataJob.Status.FAILED
+ assert updated.finished_at is not None
diff --git a/products/data_warehouse/backend/external_data_source/test/test_notifications.py b/products/data_warehouse/backend/external_data_source/test/test_notifications.py
new file mode 100644
index 000000000000..fc243ca822e0
--- /dev/null
+++ b/products/data_warehouse/backend/external_data_source/test/test_notifications.py
@@ -0,0 +1,279 @@
+import uuid
+import datetime as dt
+
+import pytest
+from unittest.mock import patch
+
+from posthog.models import Organization, Team
+
+from products.data_warehouse.backend.external_data_source.notifications import (
+ MAX_SCHEMAS_PER_DIGEST_EMAIL,
+ get_team_ids_with_recent_sync_failures,
+ notify_external_data_sync_failures,
+)
+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
+
+pytestmark = [
+ pytest.mark.django_db,
+]
+
+SENDER_PATH = "products.data_warehouse.backend.external_data_source.notifications.send_external_data_failure_digest"
+
+
+def _create_team_and_source() -> tuple[Team, ExternalDataSource]:
+ org = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=org, name="Test Team")
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ status="running",
+ source_type="Stripe",
+ )
+ return team, source
+
+
+class TestNotifyExternalDataSyncFailures:
+ def test_sends_digest_with_failing_schemas_classified(self):
+ team, source = _create_team_and_source()
+ ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ should_sync=True,
+ latest_error="transient error",
+ )
+ ExternalDataSchema.objects.create(
+ name="Invoice",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ should_sync=False,
+ latest_error="Invalid API key",
+ )
+
+ with patch(SENDER_PATH) as mock_sender:
+ notify_external_data_sync_failures(team.pk)
+
+ mock_sender.assert_called_once()
+ team_id, items = mock_sender.call_args.args
+ assert team_id == team.pk
+ assert [(item["schema_name"], item["paused"]) for item in items] == [
+ ("Invoice", True),
+ ("Charge", False),
+ ]
+ assert items[0]["error"] == "Invalid API key"
+ assert items[0]["source_type"] == "Stripe"
+ assert f"managed-{source.id}/syncs?schema=Invoice" in items[0]["url"]
+
+ @pytest.mark.parametrize(
+ "status,should_sync,deleted",
+ [
+ (ExternalDataSchema.Status.COMPLETED, True, False),
+ (ExternalDataSchema.Status.RUNNING, True, False),
+ (ExternalDataSchema.Status.BILLING_LIMIT_REACHED, True, False),
+ (ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW, True, False),
+ (ExternalDataSchema.Status.FAILED, True, True),
+ ],
+ )
+ def test_does_not_send_for_non_failing_or_deleted_schemas(self, status, should_sync, deleted):
+ team, source = _create_team_and_source()
+ ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=status,
+ should_sync=should_sync,
+ deleted=deleted,
+ latest_error="some error",
+ )
+
+ with patch(SENDER_PATH) as mock_sender:
+ notify_external_data_sync_failures(team.pk)
+
+ mock_sender.assert_not_called()
+
+ def test_missing_error_defaults_to_unknown(self):
+ team, source = _create_team_and_source()
+ ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error=None,
+ )
+
+ with patch(SENDER_PATH) as mock_sender:
+ notify_external_data_sync_failures(team.pk)
+
+ (_, items) = mock_sender.call_args.args
+ assert items[0]["error"] == "Unknown error"
+
+ def test_swallows_sender_exceptions(self):
+ team, source = _create_team_and_source()
+ ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="boom",
+ )
+
+ with patch(SENDER_PATH, side_effect=Exception("smtp down")):
+ notify_external_data_sync_failures(team.pk)
+
+ def test_caps_listed_schemas_and_reports_omitted_count(self):
+ team, source = _create_team_and_source()
+ total = MAX_SCHEMAS_PER_DIGEST_EMAIL + 5
+ schemas = ExternalDataSchema.objects.bulk_create(
+ ExternalDataSchema(
+ name=f"table_{i:03d}",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="boom",
+ )
+ for i in range(total)
+ )
+
+ with patch(SENDER_PATH, return_value=True) as mock_sender:
+ notify_external_data_sync_failures(team.pk)
+
+ (_, items) = mock_sender.call_args.args
+ assert len(items) == MAX_SCHEMAS_PER_DIGEST_EMAIL
+ assert mock_sender.call_args.kwargs["omitted_count"] == 5
+ assert (
+ ExternalDataSchema.objects.filter(
+ id__in=[schema.id for schema in schemas], last_error_notified_at__isnull=False
+ ).count()
+ == total
+ )
+
+ def test_stamps_schemas_after_successful_send(self):
+ team, source = _create_team_and_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="boom",
+ )
+
+ with patch(SENDER_PATH, return_value=True):
+ notify_external_data_sync_failures(team.pk)
+
+ schema.refresh_from_db()
+ assert schema.last_error_notified_at is not None
+
+ def test_does_not_stamp_when_email_not_sent(self):
+ team, source = _create_team_and_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=ExternalDataSchema.Status.FAILED,
+ latest_error="boom",
+ )
+
+ with patch(SENDER_PATH, return_value=False):
+ notify_external_data_sync_failures(team.pk)
+
+ schema.refresh_from_db()
+ assert schema.last_error_notified_at is None
+
+
+class TestGetTeamIdsWithRecentSyncFailures:
+ def _create_schema_with_job(
+ self,
+ *,
+ schema_status: str,
+ job_finished_at: dt.datetime,
+ schema_deleted: bool = False,
+ last_error_notified_at: dt.datetime | None = None,
+ ) -> Team:
+ team, source = _create_team_and_source()
+ schema = ExternalDataSchema.objects.create(
+ name="Charge",
+ team=team,
+ source=source,
+ status=schema_status,
+ deleted=schema_deleted,
+ latest_error="boom",
+ last_error_notified_at=last_error_notified_at,
+ )
+ job = ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status=ExternalDataJob.Status.FAILED,
+ )
+ ExternalDataJob.objects.filter(id=job.id).update(finished_at=job_finished_at)
+ return team
+
+ def test_includes_team_with_recent_failure_on_failing_schema(self):
+ team = self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.FAILED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2),
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == [team.pk]
+
+ @pytest.mark.parametrize(
+ "schema_status,job_age,schema_deleted",
+ [
+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=30), False),
+ (ExternalDataSchema.Status.COMPLETED, dt.timedelta(hours=2), False),
+ (ExternalDataSchema.Status.FAILED, dt.timedelta(hours=2), True),
+ ],
+ )
+ def test_excludes_non_actionable_teams(self, schema_status, job_age, schema_deleted):
+ self._create_schema_with_job(
+ schema_status=schema_status,
+ job_finished_at=dt.datetime.now(dt.UTC) - job_age,
+ schema_deleted=schema_deleted,
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == []
+
+ def test_excludes_failures_already_communicated(self):
+ self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.FAILED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2),
+ last_error_notified_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=1),
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == []
+
+ def test_includes_failures_newer_than_the_stamp(self):
+ team = self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.FAILED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=1),
+ last_error_notified_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2),
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == [team.pk]
+
+ def test_includes_failure_blocked_just_after_digest_rollover(self):
+ team = self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.FAILED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=24, minutes=10),
+ last_error_notified_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=24, minutes=14),
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == [team.pk]
+
+ def test_only_returns_qualifying_teams(self):
+ qualifying = self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.FAILED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2),
+ )
+ self._create_schema_with_job(
+ schema_status=ExternalDataSchema.Status.COMPLETED,
+ job_finished_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2),
+ )
+
+ assert get_team_ids_with_recent_sync_failures() == [qualifying.pk]
diff --git a/products/data_warehouse/backend/external_data_source/test/test_tasks.py b/products/data_warehouse/backend/external_data_source/test/test_tasks.py
new file mode 100644
index 000000000000..391615cce8f5
--- /dev/null
+++ b/products/data_warehouse/backend/external_data_source/test/test_tasks.py
@@ -0,0 +1,39 @@
+from unittest.mock import patch
+
+from posthog.redis import get_client
+
+from products.data_warehouse.backend.tasks import (
+ send_external_data_failure_digest_catchup,
+ send_external_data_failure_digest_task,
+)
+
+
+class TestExternalDataFailureDigestTasks:
+ def test_digest_task_builds_digest(self):
+ with patch("products.data_warehouse.backend.tasks.notify_external_data_sync_failures") as mock_notify:
+ send_external_data_failure_digest_task(123)
+
+ mock_notify.assert_called_once_with(123)
+
+ def test_digest_task_skips_when_another_send_is_in_flight(self):
+ lock = get_client().lock("external_data_failure_digest:123", timeout=10)
+ assert lock.acquire(blocking=False)
+ try:
+ with patch("products.data_warehouse.backend.tasks.notify_external_data_sync_failures") as mock_notify:
+ send_external_data_failure_digest_task(123)
+ finally:
+ lock.release()
+
+ mock_notify.assert_not_called()
+
+ def test_catchup_fans_out_per_team(self):
+ with (
+ patch(
+ "products.data_warehouse.backend.tasks.get_team_ids_with_recent_sync_failures",
+ return_value=[1, 2],
+ ),
+ patch("products.data_warehouse.backend.tasks.send_external_data_failure_digest_task") as mock_task,
+ ):
+ send_external_data_failure_digest_catchup()
+
+ assert [c.args for c in mock_task.delay.call_args_list] == [(1,), (2,)]
diff --git a/products/data_warehouse/backend/tasks.py b/products/data_warehouse/backend/tasks.py
new file mode 100644
index 000000000000..b9c74d4634cd
--- /dev/null
+++ b/products/data_warehouse/backend/tasks.py
@@ -0,0 +1,83 @@
+import structlog
+from celery import shared_task
+from prometheus_client import Counter
+
+from posthog.redis import get_client, redis
+from posthog.scoping_audit import skip_team_scope_audit
+
+from products.data_warehouse.backend.external_data_source.notifications import (
+ get_team_ids_with_recent_sync_failures,
+ notify_external_data_sync_failures,
+)
+
+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
+# 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.
+EXTERNAL_DATA_FAILURE_DIGEST_SCHEDULED_COUNTER = Counter(
+ "external_data_failure_digest_scheduled_total",
+ "External data failure digest tasks scheduled, by trigger source.",
+ labelnames=["trigger"],
+)
+
+# Task executions, by outcome: "processed" took the per-team lock and ran the send
+# funnel; "lock_contended" lost the race to a concurrent send and skipped. A high
+# lock_contended share is the per-team serialization working, not a problem.
+EXTERNAL_DATA_FAILURE_DIGEST_TASK_COUNTER = Counter(
+ "external_data_failure_digest_task_total",
+ "External data failure digest task executions, by outcome.",
+ labelnames=["outcome"],
+)
+
+# Schemas of one source tend to fail within seconds of each other (e.g. a dead
+# credential failing every schema on the next run). The digest waits this long so
+# the whole burst lands in one email instead of racing the first failure's send.
+EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS = 15 * 60
+
+# Generous bound on one digest build + synchronous send; the lock auto-expires
+# after this if a worker dies mid-flight.
+EXTERNAL_DATA_FAILURE_DIGEST_LOCK_TIMEOUT_SECONDS = 120
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit
+def send_external_data_failure_digest_task(team_id: int) -> None:
+ # Serialize per team: a racing task could mistake an in-flight winner's delivery
+ # for its own and stamp schemas the delivered email never contained, permanently
+ # silencing a paused schema. The loser skips instead — anything the winner didn't
+ # cover stays un-stamped for a later task or the catch-up.
+ try:
+ with get_client().lock(
+ f"external_data_failure_digest:{team_id}",
+ timeout=EXTERNAL_DATA_FAILURE_DIGEST_LOCK_TIMEOUT_SECONDS,
+ blocking=False,
+ ):
+ notify_external_data_sync_failures(team_id)
+ EXTERNAL_DATA_FAILURE_DIGEST_TASK_COUNTER.labels(outcome="processed").inc()
+ except redis.exceptions.LockError:
+ EXTERNAL_DATA_FAILURE_DIGEST_TASK_COUNTER.labels(outcome="lock_contended").inc()
+ logger.info("External data failure digest already in flight for team, skipping", team_id=team_id)
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit
+def send_external_data_failure_digest_catchup() -> None:
+ """Flush sync failures the one-email-per-day block swallowed.
+
+ Runs daily just after the digest day rolls over (10:15 UTC, see
+ EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC) and the date-keyed campaign
+ block resets. Any team whose schemas failed in the last 24 hours and are
+ still failing gets a fresh digest — this guarantees every error is
+ eventually communicated, including schemas paused by a non-retryable error
+ that will never fail again to re-trigger the inline notification path.
+ """
+ team_ids = get_team_ids_with_recent_sync_failures()
+ for team_id in team_ids:
+ send_external_data_failure_digest_task.delay(team_id)
+
+ if team_ids:
+ EXTERNAL_DATA_FAILURE_DIGEST_SCHEDULED_COUNTER.labels(trigger="catchup").inc(len(team_ids))
+ logger.info("Dispatched external data failure digest catch-up for %d teams", len(team_ids))
diff --git a/products/warehouse_sources/backend/migrations/0011_externaldataschema_last_error_notified_at.py b/products/warehouse_sources/backend/migrations/0011_externaldataschema_last_error_notified_at.py
new file mode 100644
index 000000000000..8b9d6f98ebf8
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0011_externaldataschema_last_error_notified_at.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.14 on 2026-06-12 09:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0010_alter_externaldatasource_source_type_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="externaldataschema",
+ name="last_error_notified_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When this schema's failure was last included in a failure digest email.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 7a018bf28008..f5587e610111 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0010_alter_externaldatasource_source_type_and_more
+0011_externaldataschema_last_error_notified_at
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 7d18a4f33f1c..0aac676fa43b 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -51,6 +51,11 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
latest_error = models.TextField(
null=True, blank=True, help_text="The latest error that occurred when syncing this schema."
)
+ last_error_notified_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="When this schema's failure was last included in a failure digest email.",
+ )
status = models.CharField(max_length=400, null=True, blank=True)
last_synced_at = models.DateTimeField(null=True, blank=True)
sync_type = models.CharField(max_length=128, choices=SyncType, null=True, blank=True)