: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): name the destination in sync failure emails (#115552)
Tom Owers97f4b65c6b96
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 03ade43623e6..625f21796638 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -1324,7 +1324,7 @@ def send_warehouse_destination_paused("team": team,"destination_name": destination_name,"latest_error": latest_error,- "destinations_url": f"{settings.SITE_URL}/project/{team.id}/data-management/warehouse-destinations",+ "destinations_url": f"{settings.SITE_URL}/project/{team.id}/data-management/warehouse-destinations?destination={destination_id}",},)for membership in memberships_to_email:diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex da013539ec82..36a521379954 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -768,6 +768,37 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):)assert "failing" in MockEmailMessage.call_args.kwargs["subject"]+ @parameterized.expand([(True,), (False,)])+ def test_send_external_data_failure_digest_shows_the_failed_destination(+ self, MockEmailMessage: MagicMock, names_destination: bool+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ destination_url = "https://app.posthog.com/project/1/data-management/warehouse-destinations?destination=abc"++ with time_machine.travel("2024-05-15 10:00:00", tick=False):+ 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": "Analytics PG: connection reset",+ "destination_name": "Analytics PG" if names_destination else None,+ "destination_url": destination_url if names_destination else None,+ "paused": False,+ "url": "https://app.posthog.com/project/1/data-management/sources/managed-abc/syncs?schema=Invoice",+ }+ ],+ )++ html_body = mocked_email_messages[0].html_body+ assert ("Delivery to Analytics PG failed" in html_body) is names_destination+ assert (destination_url in html_body) is names_destination+ assert "Analytics PG: connection reset" in html_body+def test_send_external_data_failure_digest_day_rolls_over_at_boundary_hour(self, MockEmailMessage: MagicMock) -> None:@@ -1078,7 +1109,11 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):]assert "analytics postgres" in message.subjectassert "The host name does not exist." in message.html_body- assert f"/project/{self.team.id}/data-management/warehouse-destinations" in message.html_body+ assert (+ f"/project/{self.team.id}/data-management/warehouse-destinations?destination={destination_id}"+ in message.html_body+ )+ assert "Open destination" in message.html_bodydef test_send_warehouse_destination_paused_normalizes_subject_names(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)diff --git a/posthog/templates/email/external_data_failure_digest.html b/posthog/templates/email/external_data_failure_digest.htmlindex e1c92ccbd8e3..07c6028adc7b 100644--- a/posthog/templates/email/external_data_failure_digest.html+++ b/posthog/templates/email/external_data_failure_digest.html@@ -73,7 +73,16 @@text-align: left;color: #6b7280;font-size: 0.85em;- word-break: break-word">{{ schema.error|truncatechars:90 }}</td>+ word-break: break-word">+ {% if schema.destination_name %}+ <a href="{{ schema.destination_url }}"+ target="_blank"+ style="color: #111827;+ font-weight: 600">Delivery to {{ schema.destination_name }} failed</a>+ <br />+ {% endif %}+ {{ schema.error|truncatechars:90 }}+ </td><td align="right"style="padding: 9px 0 9px 8px;border-top: 1px solid #f3f4f6;diff --git a/posthog/templates/email/warehouse_destination_paused.html b/posthog/templates/email/warehouse_destination_paused.htmlindex 5106480d4847..db612dd341be 100644--- a/posthog/templates/email/warehouse_destination_paused.html+++ b/posthog/templates/email/warehouse_destination_paused.html@@ -10,7 +10,7 @@<p>Tables that also sync to other destinations keep syncing there. Tables that sync only to this destination stop until you turn it back on.</p><p>To turn it back on, fix the problem, then open the destination and save it.</p><div class="mb mt text-center">- <a class="button" href="{{ destinations_url }}">Go to destinations</a>+ <a class="button" href="{{ destinations_url }}">Open destination</a></div><div class="mt"><p>diff --git a/products/data_warehouse/backend/logic/external_data_source/notifications.py b/products/data_warehouse/backend/logic/external_data_source/notifications.pyindex 81809a3def50..1be8f3e3a738 100644--- a/products/data_warehouse/backend/logic/external_data_source/notifications.py+++ b/products/data_warehouse/backend/logic/external_data_source/notifications.py@@ -9,7 +9,12 @@ import structlogfrom posthog.tasks.email import send_external_data_failure_digest-from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema+from products.warehouse_sources.backend.facade.models import (+ ExternalDataDestination,+ ExternalDataJob,+ ExternalDataSchema,+)+from products.warehouse_sources.backend.facade.pipelines import destination_named_in_failurefrom products.warehouse_sources.backend.facade.types import ExternalDataJobStatus, ExternalDataSchemaStatuslogger = structlog.get_logger(__name__)@@ -135,11 +140,26 @@ def notify_external_data_sync_failures(for schema in group]+ listed_schemas = ordered_schemas[:MAX_SCHEMAS_PER_DIGEST_EMAIL]+ destinations_by_name: dict[str, str] = {}+ if any(schema.latest_error for schema in listed_schemas):+ destinations = (+ ExternalDataDestination.objects.for_team(team_id)+ .exclude(deleted=True)+ .order_by("created_at")+ .values_list("name", "id")+ )+ for name, destination_pk in destinations:+ destinations_by_name.setdefault(name, str(destination_pk))+items = []- for schema in ordered_schemas[:MAX_SCHEMAS_PER_DIGEST_EMAIL]:+ for schema in listed_schemas:source_url = (f"{settings.SITE_URL}/project/{team_id}/data-management/sources/managed-{schema.source_id}/syncs")+ error = schema.latest_error or "Unknown error"+ destination_name = destination_named_in_failure(error, destinations_by_name)+ destination_id = destinations_by_name.get(destination_name) if destination_name is not None else Noneitems.append({# Prefer the human-readable label (e.g. a Slack channel name) over the@@ -151,7 +171,13 @@ def notify_external_data_sync_failures("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",+ "error": error,+ "destination_name": destination_name,+ "destination_url": (+ f"{settings.SITE_URL}/project/{team_id}/data-management/warehouse-destinations?destination={destination_id}"+ if destination_id is not None+ else None+ ),"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_notifications.py b/products/data_warehouse/backend/logic/external_data_source/test/test_notifications.pyindex 8f339812980a..cf42bed816e0 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@@ -12,7 +12,12 @@ from products.data_warehouse.backend.logic.external_data_source.notifications imget_team_ids_with_recent_sync_failures,notify_external_data_sync_failures,)-from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.models import (+ ExternalDataDestination,+ ExternalDataJob,+ ExternalDataSchema,+ ExternalDataSource,+)pytestmark = [pytest.mark.django_db,@@ -113,6 +118,42 @@ class TestNotifyExternalDataSyncFailures:# ...but the deep link always keeps using the raw identifier.assert f"?schema={quote(name)}" in items[0]["url"]+ @pytest.mark.parametrize(+ "error,destination_deleted,expect_destination",+ [+ ("Analytics PG: Destination configuration error. Bad host", False, True),+ ("Charge failed: Analytics PG: connection reset", False, True),+ ("Analytics PG: Destination configuration error. Bad host", True, False),+ ("Other PG: connection reset", False, False),+ ("Invalid API key", False, False),+ ],+ )+ def test_names_the_destination_that_failed(self, error, destination_deleted, expect_destination):+ team, source = _create_team_and_source()+ destination = ExternalDataDestination.objects.for_team(team.pk).create(+ team=team,+ type=ExternalDataDestination.Type.POSTGRES,+ name="Analytics PG",+ deleted=destination_deleted,+ )+ ExternalDataSchema.objects.create(+ name="Charge", team=team, source=source, status=ExternalDataSchema.Status.FAILED, latest_error=error+ )++ with patch(SENDER_PATH) as mock_sender:+ notify_external_data_sync_failures(team.pk)++ (_, items) = mock_sender.call_args.args+ assert items[0]["error"] == error+ if expect_destination:+ assert items[0]["destination_name"] == "Analytics PG"+ assert items[0]["destination_url"].endswith(+ f"/project/{team.pk}/data-management/warehouse-destinations?destination={destination.id}"+ )+ else:+ assert items[0]["destination_name"] is None+ assert items[0]["destination_url"] is None+@pytest.mark.parametrize("status,should_sync,deleted",[diff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.pyindex c439baab5c06..2673f3ba89de 100644--- a/products/warehouse_sources/backend/facade/pipelines.py+++ b/products/warehouse_sources/backend/facade/pipelines.py@@ -20,6 +20,7 @@ _LAZY = {"emit_data_import_app_metrics": "metrics","BatchQueue": "products.warehouse_sources_queue.backend.core.jobs_db","mark_job_failed_if_not_terminal": "pipelines.pipeline_v3.postgres_queue.consumer",+ "destination_named_in_failure": "pipelines.pipeline_v3.destinations_load.errors","release_v3_pipeline_lock": "pipelines.pipeline_v3.sync_lock","CDCExtractionInput": "cdc.workflows","SyncNewSchemasActivityInputs": "workflow_activities.sync_new_schemas",diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.pyindex 5f55db73aef3..05b531685b05 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/errors.py@@ -6,6 +6,8 @@ so the load consumer can match on the marker without importing any writer.from __future__ import annotations+from collections.abc import Iterable+# The load consumer matches this substring to fail a run on its first attempt. Changing it# silently turns every configuration error back into a retried, reported failure.DESTINATION_CONFIGURATION_ERROR_MARKER = "Destination configuration error"@@ -48,3 +50,12 @@ def is_configuration_failure_of(reason: str, destination_name: str) -> bool:"""prefix = f"{destination_name}: {DESTINATION_CONFIGURATION_ERROR_MARKER}"return reason.startswith(prefix) or f": {prefix}" in reason+++def destination_named_in_failure(reason: str, destination_names: Iterable[str]) -> str | None:+ """Return the longest destination name that matches a failure prefix."""+ return max(+ (name for name in destination_names if name and (reason.startswith(f"{name}: ") or f": {name}: " in reason)),+ key=len,+ default=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.pyindex 393fd60d666b..8e202ad8a4b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_delivery.py@@ -1,7 +1,7 @@import uuidfrom posthog.test.base import BaseTest-from unittest import mock+from unittest import TestCase, mockfrom django.db import OperationalError@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (DESTINATION_CONFIGURATION_ERROR_MARKER,DestinationConfigurationError,+ destination_named_in_failure,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage@@ -512,3 +513,19 @@ class TestDestinationHealth(DeliveryTestCase):delivery.deliver_batch_to_destinations(signal, destinations=[destination])else:assert delivery.deliver_batch_to_destinations(signal, destinations=[destination]) == 1+++class TestDestinationNamedInFailure(TestCase):+ @parameterized.expand(+ [+ ("prefix", "Prod: boom", ["Prod"], "Prod"),+ ("after_separator", "Charge: Prod: boom", ["Prod"], "Prod"),+ ("longest_wins", "My Prod: boom", ["Prod", "My Prod"], "My Prod"),+ ("substring_of_other_name", "My Prod: boom", ["Prod"], None),+ ("no_separator", "Prod went away", ["Prod"], None),+ ("no_destinations", "Prod: boom", [], None),+ ("empty_name_ignored", "Charge: : boom", [""], None),+ ]+ )+ def test_matches(self, _name, reason, names, expected):+ assert destination_named_in_failure(reason, names) == expected