: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): add destination health and auto-pause (#112179)
Tom Owerscfb2ec921430
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 02149d8389d1..fd04ba599e31 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2957,25 +2957,25 @@ snapshots:data-warehouse-sourcedestinationsbanner--flag-off--light:hash: v1.k794b7964.48c6b225dec1945c20d154de4f18c40be7b0c4f34c4b337878243bf984816e16.-vKIJKAdSQSKB0z_IMuQYV4bY1tzFQwajwGoiiB2TGgdata-warehouse-warehousedestinationstable--default--dark:- hash: v1.k794b7964.017bbc5ee3725d33a34aeead66418a2bce7ddbc407fbb28d05e25cc563103465.8DKub_NldGVl5fyy8aotD9-9UKyd-n_Tm8MJAOJwCsM+ hash: v1.k794b7964.c922f81194d27174299c5367fad3a6d1f5e7f0c9e537cf3d2220a74d7e83d634.95VxYo0ilxD1TllbW4UBcIy_x2Edb1yHzElsS-Qr3m0data-warehouse-warehousedestinationstable--default--light:- hash: v1.k794b7964.5b778200ea1e4ccdd8554c7485b44e9554fc6e1b903cb53d01b1b58a8ee2db08.UU8_Pa4obTCmLTwR00QqQf24aya1d2aLleGE4gvuYvQ+ hash: v1.k794b7964.3adf6b5db58907ab34b4d9aab3a5abcf6966d2a8a599a9ab7a0191de44e3df36.ooOgg06iZR2P-XqGFv1C5Rprz_kdBMUgfmLLmIfaO-Qdata-warehouse-warehousedestinationstable--deleting--dark:- hash: v1.k794b7964.017bbc5ee3725d33a34aeead66418a2bce7ddbc407fbb28d05e25cc563103465.Fc5axCHhIpX7JD8liItgEVHgXX75pUHQnHArANwtOWQ+ hash: v1.k794b7964.c922f81194d27174299c5367fad3a6d1f5e7f0c9e537cf3d2220a74d7e83d634.f10lCm11CyCMqfvwpNGI1QawuqcDvexLAo7ev8Nid7Qdata-warehouse-warehousedestinationstable--deleting--light:- hash: v1.k794b7964.5b778200ea1e4ccdd8554c7485b44e9554fc6e1b903cb53d01b1b58a8ee2db08.z7zNtVL3PEbQ2oi6VJghXfTmA1Q_2PKrA8JJIaMmgHU+ hash: v1.k794b7964.3adf6b5db58907ab34b4d9aab3a5abcf6966d2a8a599a9ab7a0191de44e3df36.8yCe-L96YBjF8bIf3ZlF10naEep4oEiRx9IqTkURazwdata-warehouse-warehousedestinationstable--empty--dark:- hash: v1.k794b7964.9f1bf33e217cec7392aabfd90b22f1b90d23c376fe23fd3da26da296bd2a3bed.vr1sLFpw_5xjzCc0k0Y0O4rgmSzSJt1fymgjYnzfs1M+ hash: v1.k794b7964.d14fb7d10388b60ba43ad5e4effd46eca566ae23edf1d9a78b0aacf7cf8c7c12.xrsdHkKIXSYppkyp3eY1bUOl6yYEYNsXDw4hbMwwn2gdata-warehouse-warehousedestinationstable--empty--light:- hash: v1.k794b7964.fbf426283f3c515b35f5b1a1d83bbd80527692b393d1b415e83070e2fb525077.kx3a5CnOGxV-4p6vGDHRT1z1wGNOdijZQKO-vQKmovo+ hash: v1.k794b7964.9633e71ccd923a4b645cbd7e5f7828d9ba636752bf03a9b87cad9a9531e1c7e9.78o_-iB0lHqPOFXtdMzVbYqoixqpHMWFnC7wfOnVVrQdata-warehouse-warehousedestinationstable--linked--dark:- hash: v1.k794b7964.0cc9ddc5088e4b5c7f93e29834dcd9941ce455bc77fbbeba45c18febc02fd350.ffwG1Nl3GTV6onbBl7ekXJVw0zh7mKWIiYKjAATVTwQ+ hash: v1.k794b7964.69a102482f6c2c29be926283b1a67b69d1a7d0aa8bbb51ba8bcdaf1544e34bff.-wehe2SZ5lG-TcxYzPLtWIOGJ0qMBPneEQnlMHKkxMEdata-warehouse-warehousedestinationstable--linked--light:- hash: v1.k794b7964.59f3210d57cb7af2d6008e3e72f7bad5a25b4a9e4dcad90637121ee69236e686.441rO62-RtZnwj2nrXJt8UsD7LvAL57d_opCKdlKitE+ hash: v1.k794b7964.fb93aa881e2185250b6e2bfcfa652a0236798c482b70e6cf060dd624a9708a7c.nE7rPnA0GJ5QqpUWS0pU2Y2SGNUdg1Q4WQJgkFZnIAgdata-warehouse-warehousedestinationstable--loading--dark:- hash: v1.k794b7964.6822b2603856380f898ef83e31d6bb3a179ef78e97dce603804d61e536e33543.jdFqJsjhfMQIUySpfQ_Dvwca7kdb_1jRS9j5U5OmIDY+ hash: v1.k794b7964.a9321f81db4ce8e44b1e992594bf2d6a3c5fee1c1e0a0c9f26e98b85e4988fc3.NhlBc-vyfRFqQ4ygYG8U6g-3Pdwz7ZVCP4D82o51ka0data-warehouse-warehousedestinationstable--loading--light:- hash: v1.k794b7964.b5aaffa7f7e755ef371931ba26506118e66221071eacbcb8d96df4a8d1fda234.KvSLPPOYhqF6fjKn-ZV23joNGS5B-4jwxfaff2cyP7I+ hash: v1.k794b7964.06d456b3d18f191bf9c300a4f58d2b9bbf3f623da857f48343422c049835e1b7.ZhxFgamp7HbAKfSlUm6RyLWPUBu7LbtlTqSUf1U3tGkendpoints-usagetrendschart--breakdown--dark:hash: v1.k794b7964.725cd338f4c7922dc0defc35db0438ca80cd1fcec083b52cae4a3fce1be90235.fSfMnv_kEKzqwV0o4HdZA5W2pAUvXeiW-1fDQjjEu_wendpoints-usagetrendschart--breakdown--light:diff --git a/posthog/email.py b/posthog/email.pyindex fa0fc10f08d9..86de9fecdf18 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -1,3 +1,4 @@+import reimport htmlimport uuidimport smtplib@@ -66,12 +67,13 @@ def is_smtp_email_service_available() -> bool:def single_line(value: str) -> str:- """Flatten CR/LF to spaces so a user-set value is safe in an email Subject.+ """Flatten CR/LF to a single space so a user-set value is safe in an email Subject.A CR or LF in a Subject makes Django raise BadHeaderError, which the send path swallows, so- the whole notification would be dropped.+ the whole notification would be dropped. A run of CR/LF (e.g. "\r\n") collapses to one space+ rather than one per character, so it reads like a single line break once flattened."""- return value.replace("\r", " ").replace("\n", " ")+ return re.sub(r"[\r\n]+", " ", value)def is_email_available(with_absolute_urls: bool = False) -> bool:diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 54df85da6086..9e7388a1c89d 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -219,3 +219,9 @@ DATA_WAREHOUSE_V3_COALESCE_MAX_ROWS = get_from_env("DATA_WAREHOUSE_V3_COALESCE_MDATA_WAREHOUSE_V3_COALESCE_MAX_BYTES = get_from_env("DATA_WAREHOUSE_V3_COALESCE_MAX_BYTES", 64 * 1024 * 1024, type_cast=int)++# Consecutive configuration errors (bad credentials, unknown database, unreachable host) after which+# PostHog pauses a destination instead of letting every scheduled run fail against it.+DATA_WAREHOUSE_DESTINATION_PAUSE_AFTER_CONFIGURATION_FAILURES = get_from_env(+ "DATA_WAREHOUSE_DESTINATION_PAUSE_AFTER_CONFIGURATION_FAILURES", 3, type_cast=int+)diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 7199c56f5ab1..03ade43623e6 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -1266,6 +1266,72 @@ def send_external_data_failure_digest(team_id: int, schemas: list[dict[str, Any]return delivered+def _filter_members_by_external_data_source_access(+ memberships: list[OrganizationMembership], team: Team+) -> list[OrganizationMembership]:+ """Drop members who cannot view destinations, which `ExternalDataDestinationViewSet` gates on `external_data_source`.++ Falls back to the unfiltered list when the check fails: not being able to check must not silently stop the email.+ """+ if not memberships:+ return memberships+ try:+ if not UserAccessControl(memberships[0].user, team).access_controls_supported:+ return memberships+ return [+ membership+ for membership in memberships+ if UserAccessControl(membership.user, team).check_access_level_for_resource(+ "external_data_source", "viewer"+ )+ ]+ except Exception:+ logger.exception("Destination access check failed, sending to all subscribed members", team_id=team.id)+ return memberships+++@shared_task(**EMAIL_TASK_KWARGS)+@with_team_scope()+def send_warehouse_destination_paused(+ team_id: int, destination_id: str, destination_name: str, latest_error: str, paused_at: str+) -> None:+ """Tell a project that PostHog paused a data warehouse destination after repeated configuration errors.++ The destination stays paused until someone edits it, so one email per pause is enough. The+ caller passes the details so this module does not read the warehouse product's models.+ """+ if not is_email_available(with_absolute_urls=True):+ return+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return++ memberships_to_email = get_members_to_notify_for_pipeline_error(+ team, failure_rate=1.0, pipeline_id=f"warehouse_destination:{destination_id}"+ )+ memberships_to_email = _filter_members_by_external_data_source_access(memberships_to_email, team)+ if not memberships_to_email:+ return++ message = EmailMessage(+ campaign_key=f"warehouse_destination_paused_{destination_id}_{paused_at}",+ subject=(+ f"[Alert] Data warehouse destination '{single_line(destination_name)}' paused in project "+ f"'{single_line(team.name)}'"+ ),+ template_name="warehouse_destination_paused",+ template_context={+ "team": team,+ "destination_name": destination_name,+ "latest_error": latest_error,+ "destinations_url": f"{settings.SITE_URL}/project/{team.id}/data-management/warehouse-destinations",+ },+ )+ for membership in memberships_to_email:+ message.add_user_recipient(membership.user)+ message.send()++MAX_VIEWS_PER_DIGEST_EMAIL = 30MAX_ERROR_CHARS = 255diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex c83f151e0bfb..aaac0f4b5448 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -75,6 +75,7 @@'posthog.tasks.email.send_two_factor_auth_disabled_email','posthog.tasks.email.send_two_factor_auth_enabled_email','posthog.tasks.email.send_two_factor_reset_email',+ 'posthog.tasks.email.send_warehouse_destination_paused','posthog.tasks.email.send_wizard_pr_ready_email','posthog.tasks.email.send_workflow_email_sending_paused','posthog.tasks.email.send_workflow_email_sending_warning',diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex db1022bca71b..da013539ec82 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -50,6 +50,7 @@ from posthog.tasks.email import (send_project_secret_api_key_exposed,send_provisioning_welcome,send_team_matview_failure_digest,+ send_warehouse_destination_paused,send_wizard_pr_ready_email,send_workflow_email_sending_paused,send_workflow_email_sending_warning,@@ -1054,6 +1055,76 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):{"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}]+ def test_send_warehouse_destination_paused_names_the_error_and_respects_the_opt_out(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ user2 = self._create_user("[email protected]")+ destination_id = "0190a2b4-0000-0000-0000-000000000001"+ self.user.partial_notification_settings = {+ "plugin_disabled": True,+ "pipeline_notifications_disabled": {f"warehouse_destination:{destination_id}": True},+ }+ self.user.save()++ send_warehouse_destination_paused(+ self.team.id, destination_id, "analytics postgres", "The host name does not exist.", "2026-01-01T00:00:00"+ )++ assert len(mocked_email_messages) == 1+ message = mocked_email_messages[0]+ assert message.to == [+ {"recipient": "[email protected]", "raw_email": "[email protected]", "distinct_id": str(user2.distinct_id)}+ ]+ assert "analytics postgres" in message.subject+ assert "The host name does not exist." in message.html_body+ assert f"/project/{self.team.id}/data-management/warehouse-destinations" in message.html_body++ def test_send_warehouse_destination_paused_normalizes_subject_names(self, MockEmailMessage: MagicMock) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self.team.name = "project\nname"+ self.team.save(update_fields=["name"])++ send_warehouse_destination_paused(+ self.team.id,+ "0190a2b4-0000-0000-0000-000000000001",+ "destination\r\nname",+ "The host name does not exist.",+ "2026-01-01T00:00:00",+ )++ assert mocked_email_messages[0].subject == (+ "[Alert] Data warehouse destination 'destination name' paused in project 'project name'"+ )++ def test_send_warehouse_destination_paused_skips_members_without_destination_access(+ self, MockEmailMessage: MagicMock+ ) -> None:+ mocked_email_messages = mock_email_messages(MockEmailMessage)+ self._create_user("[email protected]")++ class FakeUserAccessControl:+ def __init__(self, user: User, team: object) -> None:+ self.user = user++ access_controls_supported = True++ def check_access_level_for_resource(self, resource: str, level: str) -> bool:+ assert (resource, level) == ("external_data_source", "viewer")+ return self.user.email != "[email protected]"++ with patch("posthog.tasks.email.UserAccessControl", FakeUserAccessControl):+ send_warehouse_destination_paused(+ self.team.id,+ "0190a2b4-0000-0000-0000-000000000001",+ "analytics postgres",+ "The host name does not exist.",+ "2026-01-01T00:00:00",+ )++ assert len(mocked_email_messages) == 1+ assert [r["recipient"] for r in mocked_email_messages[0].to] == [self.user.email]+def test_send_hog_function_disabled_per_pipeline_opt_out(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)hog_function = HogFunction.objects.create(diff --git a/posthog/templates/email/warehouse_destination_paused.html b/posthog/templates/email/warehouse_destination_paused.htmlnew file mode 100644index 000000000000..5106480d4847--- /dev/null+++ b/posthog/templates/email/warehouse_destination_paused.html@@ -0,0 +1,31 @@+{% extends "email/base.html" %}+{% block heading %}A data warehouse destination is paused{% endblock %}+{% block section %}+ <!-- prettier-ignore -->+ <p>+ PostHog paused the destination <b>{{ destination_name }}</b> in project <b>{{ team.name }}</b>. The last few syncs could not connect to it because of its settings.+ </p>+ <p>The last error was:</p>+ <p><i>{{ latest_error }}</i></p>+ <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>+ </div>+ <div class="mt">+ <p>+ If the button above doesn't work, paste this link into your browser:+ <br />+ <a href="{{ destinations_url }}">{{ destinations_url }}</a>+ </p>+ </div>+{% 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?{{ 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/batch_exports/backend/facade/destinations/s3.py b/products/batch_exports/backend/facade/destinations/s3.pyindex 3127fc81a486..6afd1479a482 100644--- a/products/batch_exports/backend/facade/destinations/s3.py+++ b/products/batch_exports/backend/facade/destinations/s3.py@@ -13,6 +13,7 @@ from products.batch_exports.backend.temporal.destinations.s3_batch_export importConcurrentS3Consumer,IntermittentUploadPartTimeoutError,PolicyStatement,+ S3IntegrationNotFoundError,_get_s3_integration as get_s3_integration,get_credentials_using_user_aws_role,s3_client,@@ -22,6 +23,7 @@ __all__ = ["ConcurrentS3Consumer","IntermittentUploadPartTimeoutError","PolicyStatement",+ "S3IntegrationNotFoundError","S3_SUPPORTED_COMPRESSIONS","get_credentials_using_user_aws_role","get_s3_integration",diff --git a/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.stories.tsx b/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.stories.tsxindex 6ef980f40ab3..bfacfd0e6369 100644--- a/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.stories.tsx+++ b/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.stories.tsx@@ -11,6 +11,9 @@ const WAREHOUSE: ExternalDataDestinationApi = {config: {},integration: null,is_posthog_warehouse: true,+ status: 'healthy',+ latest_error: null,+ latest_error_at: null,created_at: '2026-08-20T10:00:00Z',updated_at: '2026-08-25T10:00:00Z',created_by: null,@@ -23,11 +26,30 @@ const POSTGRES: ExternalDataDestinationApi = {config: { database: 'analytics', schema: 'customer_sync' },integration: 1,is_posthog_warehouse: false,+ status: 'healthy',+ latest_error: null,+ latest_error_at: null,created_at: '2026-08-24T10:00:00Z',updated_at: '2026-08-26T14:00:00Z',created_by: null,} as ExternalDataDestinationApi+const PAUSED_POSTGRES: ExternalDataDestinationApi = {+ id: '01a03e9c-1b81-0000-4c2a-8f1d3e6b7a90',+ type: 'Postgres',+ name: 'Reporting Postgres',+ config: { database: 'reporting', schema: 'public' },+ integration: 2,+ is_posthog_warehouse: false,+ status: 'paused',+ latest_error:+ 'The database refused the user name or password. Update the credentials on the destination, then run the sync again.',+ latest_error_at: '2026-08-31T09:00:00Z',+ created_at: '2026-08-22T10:00:00Z',+ updated_at: '2026-08-31T09:00:00Z',+ created_by: null,+} as ExternalDataDestinationApi+const meta: Meta<typeof WarehouseDestinationsTable> = {title: 'Data Warehouse/WarehouseDestinationsTable',component: WarehouseDestinationsTable,@@ -45,7 +67,7 @@ const Template: StoryFn<typeof WarehouseDestinationsTable> = (props: WarehouseDeexport const Default = Template.bind({})Default.args = {- destinations: [POSTGRES, WAREHOUSE],+ destinations: [POSTGRES, PAUSED_POSTGRES, WAREHOUSE],loading: false,onEdit: () => {},onDelete: () => {},diff --git a/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.tsx b/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.tsxindex fb7b70c68cc2..842ca5545b26 100644--- a/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.tsx+++ b/products/data_warehouse/frontend/scenes/WarehouseDestinationsScene/WarehouseDestinationsTable.tsx@@ -1,12 +1,15 @@import type { ReactNode } from 'react'import { IconPencil, IconTrash } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTableColumn, LemonTag, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonTable, LemonTableColumn, LemonTag, LemonTagType, Link } from '@posthog/lemon-ui'import { More } from 'lib/lemon-ui/LemonButton/More'import { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'-import { ExternalDataDestinationApi } from 'products/warehouse_sources/frontend/generated/api.schemas'+import {+ ExternalDataDestinationApi,+ ExternalDataDestinationStatusEnumApi,+} from 'products/warehouse_sources/frontend/generated/api.schemas'import { DestinationIcon, destinationTypeLabel } from '../../shared/components/DestinationIcon'import { destinationTarget } from '../../shared/components/destinationTarget'@@ -14,6 +17,12 @@ import { SyncedSources } from './SyncedSources'const MANAGED_REASON = 'The PostHog warehouse is managed for you'+const STATUS_TAGS: Record<ExternalDataDestinationStatusEnumApi, { label: string; type: LemonTagType }> = {+ healthy: { label: 'Healthy', type: 'success' },+ failing: { label: 'Failing', type: 'warning' },+ paused: { label: 'Paused', type: 'danger' },+}+export interface WarehouseDestinationsTableProps {destinations: ExternalDataDestinationApi[]loading: boolean@@ -73,6 +82,25 @@ export function WarehouseDestinationsTable({</LemonTag>),},+ {+ title: 'Status',+ key: 'status',+ render: (_, destination) => {+ // The PostHog warehouse is written by the sync itself, so it has no delivery health of its own.+ if (destination.is_posthog_warehouse) {+ return null+ }+ const tag = STATUS_TAGS[destination.status]+ return (+ <div className="flex flex-col items-start gap-1 max-w-80">+ <LemonTag type={tag.type}>{tag.label}</LemonTag>+ {destination.status !== 'healthy' && destination.latest_error ? (+ <span className="text-muted text-xs">{destination.latest_error}</span>+ ) : null}+ </div>+ )+ },+ },{title: 'Synced by',key: 'synced_sources',diff --git a/products/warehouse_sources/backend/destination_health.py b/products/warehouse_sources/backend/destination_health.pynew file mode 100644index 000000000000..59d2f9d50c5b--- /dev/null+++ b/products/warehouse_sources/backend/destination_health.py@@ -0,0 +1,169 @@+"""Whether deliveries to a destination work, and pausing one that keeps failing on its own settings.++A destination with bad settings (wrong password, unknown database, unreachable host) fails every+run that delivers to it. After `DATA_WAREHOUSE_DESTINATION_PAUSE_AFTER_CONFIGURATION_FAILURES`+such failures in a row, PostHog turns off every link to it and tells the project once. The schemas+themselves stay on, so a table that also syncs to the PostHog warehouse or another destination+keeps syncing there.++Every write here is best effort. A health record that cannot be saved must never fail a delivery.+"""++from __future__ import annotations++from django.conf import settings+from django.db import transaction+from django.utils import timezone++import structlog++from posthog.exceptions_capture import capture_exception++from products.warehouse_sources.backend.models.external_data_destination import (+ ExternalDataDestination,+ ExternalDataSchemaDestination,+ ExternalDataSourceDestination,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.errors import (+ DestinationConfigurationError,+)++logger = structlog.get_logger(__name__)++# Shown for a failure that is not a configuration error. The raw error can name hosts or carry+# driver output, so it stays in the logs and the user sees this instead.+TRANSIENT_DELIVERY_ERROR = "PostHog could not deliver data to this destination. The next sync will try again."+++def record_delivery_failure(destination: ExternalDataDestination, error: BaseException) -> None:+ """Save the error on the destination, and pause it if its settings failed too many times in a row."""+ try:+ _record_failure(destination, error)+ except Exception as e:+ capture_exception(e)+ logger.warning("destination_health_failure_not_recorded", destination_id=str(destination.id), error=str(e))+++def record_delivery_success(destination: ExternalDataDestination) -> None:+ """Mark a failing destination healthy again. A paused one stays paused until a user turns it back on.++ Reads the instance the delivery already loaded, so a destination that is already healthy costs+ no query.+ """+ if (+ destination.status == ExternalDataDestination.Status.HEALTHY+ and not destination.consecutive_configuration_failures+ ):+ return+ try:+ updated = (+ ExternalDataDestination.objects.for_team(destination.team_id, canonical=True)+ .filter(id=destination.id)+ .exclude(status=ExternalDataDestination.Status.PAUSED)+ .update(+ status=ExternalDataDestination.Status.HEALTHY,+ consecutive_configuration_failures=0,+ updated_at=timezone.now(),+ )+ )+ if updated:+ destination.status = ExternalDataDestination.Status.HEALTHY+ destination.consecutive_configuration_failures = 0+ except Exception as e:+ capture_exception(e)+ logger.warning("destination_health_success_not_recorded", destination_id=str(destination.id), error=str(e))+++def resume_destination(destination: ExternalDataDestination) -> None:+ """Turn a destination back on after a user edits it or selects it again.++ Turns its links back on only when PostHog paused it. Nothing else turns a link off, so every+ link that is off on a paused destination is one the pause turned off.+ """+ with transaction.atomic():+ locked = (+ ExternalDataDestination.objects.for_team(destination.team_id, canonical=True)+ .select_for_update()+ .filter(id=destination.id, deleted=False)+ .first()+ )+ if locked is None:+ return+ if locked.status == ExternalDataDestination.Status.PAUSED:+ _set_links_enabled(locked, enabled=True)+ locked.status = ExternalDataDestination.Status.HEALTHY+ locked.consecutive_configuration_failures = 0+ locked.save(update_fields=["status", "consecutive_configuration_failures", "updated_at"])++ destination.status = locked.status+ destination.consecutive_configuration_failures = 0+++def _record_failure(destination: ExternalDataDestination, error: BaseException) -> None:+ is_configuration_error = isinstance(error, DestinationConfigurationError)+ message = error.detail if isinstance(error, DestinationConfigurationError) else TRANSIENT_DELIVERY_ERROR+ now = timezone.now()+ paused = False++ with transaction.atomic():+ locked = (+ ExternalDataDestination.objects.for_team(destination.team_id, canonical=True)+ .select_for_update()+ .filter(id=destination.id, deleted=False)+ .first()+ )+ if locked is None:+ return++ locked.latest_error = message+ locked.latest_error_at = now+ # A run that started before the pause can still reach a paused destination. Its failure+ # updates the error but must not send a second notification.+ if locked.status != ExternalDataDestination.Status.PAUSED:+ if is_configuration_error:+ locked.consecutive_configuration_failures += 1+ if (+ is_configuration_error+ and locked.consecutive_configuration_failures+ >= settings.DATA_WAREHOUSE_DESTINATION_PAUSE_AFTER_CONFIGURATION_FAILURES+ ):+ _set_links_enabled(locked, enabled=False)+ locked.status = ExternalDataDestination.Status.PAUSED+ paused = True+ else:+ locked.status = ExternalDataDestination.Status.FAILING+ locked.save(+ update_fields=[+ "latest_error",+ "latest_error_at",+ "status",+ "consecutive_configuration_failures",+ "updated_at",+ ]+ )++ if paused:+ from posthog.tasks.email import send_warehouse_destination_paused++ logger.warning(+ "destination_paused_after_configuration_errors",+ destination_id=str(locked.id),+ destination_type=locked.type,+ failures=locked.consecutive_configuration_failures,+ )+ team_id, destination_id, name = locked.team_id, str(locked.id), locked.name+ transaction.on_commit(+ lambda: send_warehouse_destination_paused.delay(team_id, destination_id, name, message, now.isoformat())+ )++ destination.status = locked.status+ destination.latest_error = locked.latest_error+ destination.latest_error_at = locked.latest_error_at+ destination.consecutive_configuration_failures = locked.consecutive_configuration_failures+++def _set_links_enabled(destination: ExternalDataDestination, *, enabled: bool) -> None:+ for link_model in (ExternalDataSourceDestination, ExternalDataSchemaDestination):+ link_model.objects.for_team(destination.team_id, canonical=True).filter(+ destination_id=destination.id, enabled=not enabled+ ).update(enabled=enabled, updated_at=timezone.now())diff --git a/products/warehouse_sources/backend/facade/destination_health.py b/products/warehouse_sources/backend/facade/destination_health.pynew file mode 100644index 000000000000..87886cea0ef4--- /dev/null+++ b/products/warehouse_sources/backend/facade/destination_health.py@@ -0,0 +1,16 @@+"""Destination health transitions used by warehouse presentation endpoints."""++from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from products.warehouse_sources.backend.facade.models import ExternalDataDestination+++def resume_destination(destination: "ExternalDataDestination") -> None:+ # Deferred to keep the email task graph off Django's model import path.+ from products.warehouse_sources.backend.destination_health import resume_destination as _resume_destination++ _resume_destination(destination)+++__all__ = ["resume_destination"]diff --git a/products/warehouse_sources/backend/migrations/0185_externaldatadestination_health.py b/products/warehouse_sources/backend/migrations/0185_externaldatadestination_health.pynew file mode 100644index 000000000000..fd71827c004d--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0185_externaldatadestination_health.py@@ -0,0 +1,44 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0184_repin_langfuse_api_version_v3"),+ ]++ operations = [+ migrations.AddField(+ model_name="externaldatadestination",+ name="status",+ field=models.CharField(+ choices=[("healthy", "Healthy"), ("failing", "Failing"), ("paused", "Paused")],+ db_default="healthy",+ default="healthy",+ help_text="Whether the last delivery to this destination worked, failed, or PostHog paused it.",+ max_length=32,+ ),+ ),+ migrations.AddField(+ model_name="externaldatadestination",+ name="latest_error",+ field=models.TextField(+ blank=True,+ help_text="The last delivery error, in words safe to show the user. Never holds credentials.",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="externaldatadestination",+ name="latest_error_at",+ field=models.DateTimeField(blank=True, help_text="When the last delivery error occurred.", null=True),+ ),+ migrations.AddField(+ model_name="externaldatadestination",+ name="consecutive_configuration_failures",+ field=models.IntegerField(+ db_default=0,+ default=0,+ help_text="Configuration errors since the last successful delivery. At the threshold, PostHog pauses the destination.",+ ),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 39a8ff3efba1..edb24947558d 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0184_repin_langfuse_api_version_v3+0185_externaldatadestination_healthdiff --git a/products/warehouse_sources/backend/models/external_data_destination.py b/products/warehouse_sources/backend/models/external_data_destination.pyindex 3129ccce6766..166df07776d6 100644--- a/products/warehouse_sources/backend/models/external_data_destination.py+++ b/products/warehouse_sources/backend/models/external_data_destination.py@@ -28,6 +28,12 @@ class ExternalDataDestination(TeamScopedRootMixin, UpdatedMetaFields, DeletedMetAZURE_BLOB = "AzureBlob", "Azure Blob"S3 = "S3", "S3"+ class Status(models.TextChoices):+ HEALTHY = "healthy", "Healthy"+ FAILING = "failing", "Failing"+ # PostHog turned off every link to this destination after repeated configuration errors.+ PAUSED = "paused", "Paused"+# `db_constraint=False`: a real FK constraint to the hot `posthog_team` table would# take a lock on it while being created. Team scoping is enforced at the app level# via `TeamScopedRootMixin`. See products/README.md "Adding or moving backend models@@ -53,8 +59,26 @@ class ExternalDataDestination(TeamScopedRootMixin, UpdatedMetaFields, DeletedMet"posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+")created_at = models.DateTimeField(auto_now_add=True)+ status = models.CharField(+ max_length=32,+ choices=Status,+ default=Status.HEALTHY,+ db_default=Status.HEALTHY,+ help_text="Whether the last delivery to this destination worked, failed, or PostHog paused it.",+ )+ latest_error = models.TextField(+ null=True,+ blank=True,+ help_text="The last delivery error, in words safe to show the user. Never holds credentials.",+ )+ latest_error_at = models.DateTimeField(null=True, blank=True, help_text="When the last delivery error occurred.")+ consecutive_configuration_failures = models.IntegerField(+ default=0,+ db_default=0,+ help_text="Configuration errors since the last successful delivery. At the threshold, PostHog pauses the destination.",+ )- __repr__ = sane_repr("id", "team_id", "type", "name")+ __repr__ = sane_repr("id", "team_id", "type", "name", "status")class Meta:db_table = "posthog_externaldatadestination"diff --git a/products/warehouse_sources/backend/presentation/views/destination_links.py b/products/warehouse_sources/backend/presentation/views/destination_links.pyindex 1d6e16816a0c..691a8f34e3ac 100644--- a/products/warehouse_sources/backend/presentation/views/destination_links.py+++ b/products/warehouse_sources/backend/presentation/views/destination_links.py@@ -4,15 +4,19 @@ Kept out of the source and schema viewsets so the destination set is edited throshared, tested path rather than two near-copies."""+from collections.abc import Callablefrom typing import Anyfrom django.db import transaction+from django.db.models import Qfrom rest_framework import serializersfrom rest_framework.exceptions import ValidationError+from products.warehouse_sources.backend.facade.destination_health import resume_destinationfrom products.warehouse_sources.backend.facade.models import (ExternalDataDestination,+ ExternalDataSchema,ExternalDataSchemaDestination,ExternalDataSource,ExternalDataSourceDestination,@@ -79,7 +83,62 @@ def _resolve_destinations(team_id: int, destination_ids: list) -> list[ExternalDreturn destinations-def set_source_destinations(*, team_id: int, source_id: Any, destination_ids: list | None) -> list[str]:+def _resume_paused(+ destinations: list[ExternalDataDestination], authorize: Callable[[list[ExternalDataSchema]], None]+) -> None:+ # Lock and reload the destinations because one can be paused after `_resolve_destinations`+ # reads it but before its new links are created.+ team_id = destinations[0].team_id+ selected_ids = [destination.id for destination in destinations]+ locked_destinations = list(+ ExternalDataDestination.objects.for_team(team_id, canonical=True)+ .select_for_update()+ .filter(id__in=selected_ids, deleted=False)+ )+ missing = {str(destination_id) for destination_id in selected_ids} - {+ str(destination.id) for destination in locked_destinations+ }+ if missing:+ raise ValidationError({"destination_ids": f"Unknown destinations: {', '.join(sorted(missing))}"})++ # Selecting a paused destination again is how a user turns it back on after fixing it.+ paused = [+ destination+ for destination in locked_destinations+ if destination.status == ExternalDataDestination.Status.PAUSED+ ]+ if not paused:+ return++ source_ids = (+ ExternalDataSourceDestination.objects.for_team(paused[0].team_id)+ .filter(destination__in=paused)+ .values_list("source_id", flat=True)+ )+ schema_ids = (+ ExternalDataSchemaDestination.objects.for_team(paused[0].team_id)+ .filter(destination__in=paused)+ .values_list("schema_id", flat=True)+ )+ schemas = list(+ ExternalDataSchema.objects.exclude(deleted=True)+ .filter(team_id=paused[0].team_id)+ .filter(Q(source_id__in=source_ids) | Q(id__in=schema_ids))+ .select_related("table", "source")+ .distinct()+ )+ authorize(schemas)+ for destination in paused:+ resume_destination(destination)+++def set_source_destinations(+ *,+ team_id: int,+ source_id: Any,+ destination_ids: list | None,+ authorize_resume: Callable[[list[ExternalDataSchema]], None],+) -> list[str]:"""Replace a source's destination set. Returns the ids now attached."""if not destination_ids:raise ValidationError({"destination_ids": EMPTY_SET_MESSAGE})@@ -96,10 +155,17 @@ def set_source_destinations(*, team_id: int, source_id: Any, destination_ids: liExternalDataSourceDestination.objects.for_team(team_id).create(team_id=team_id, source_id=source_id, destination=destination)+ _resume_paused(destinations, authorize_resume)return [str(d.id) for d in destinations]-def set_schema_destinations(*, team_id: int, schema_id: Any, destination_ids: list | None) -> list[str] | None:+def set_schema_destinations(+ *,+ team_id: int,+ schema_id: Any,+ destination_ids: list | None,+ authorize_resume: Callable[[list[ExternalDataSchema]], None],+) -> list[str] | None:"""Replace a table's destination override, or clear it so the table follows its source.Null clears the override. An empty list is rejected rather than treated as "sync nowhere":@@ -125,4 +191,5 @@ def set_schema_destinations(*, team_id: int, schema_id: Any, destination_ids: liExternalDataSchemaDestination.objects.for_team(team_id).create(team_id=team_id, schema_id=schema_id, destination=destination)+ _resume_paused(destinations, authorize_resume)return [str(d.id) for d in destinations]diff --git a/products/warehouse_sources/backend/presentation/views/external_data_destination.py b/products/warehouse_sources/backend/presentation/views/external_data_destination.pyindex 90306af80723..966f7a4d9353 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_destination.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_destination.py@@ -17,6 +17,7 @@ from posthog.permissions import is_service_authfrom products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resourcefrom products.data_warehouse.backend.facade.api import is_any_external_data_schema_paused+from products.warehouse_sources.backend.facade.destination_health import resume_destinationfrom products.warehouse_sources.backend.facade.models import (ExternalDataDestination,ExternalDataSchema,@@ -132,6 +133,23 @@ class ExternalDataDestinationSerializer(serializers.ModelSerializer):is_posthog_warehouse = serializers.BooleanField(read_only=True, help_text="Whether this is the managed PostHog warehouse destination.")+ status = serializers.ChoiceField(+ choices=ExternalDataDestination.Status.choices,+ read_only=True,+ help_text=(+ "Whether delivery to this destination works. `healthy`: the last delivery worked. `failing`: the "+ "last delivery failed. `paused`: PostHog stopped syncing to it after repeated configuration errors. "+ "Edit the destination to turn it back on."+ ),+ )+ latest_error = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="The last delivery error, safe to show to the user. Null if no delivery has failed.",+ )+ latest_error_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the last delivery error occurred."+ )synced_sources = serializers.SerializerMethodField(help_text=("Sources whose tables sync to this destination, so you can see what a change or a "@@ -191,8 +209,21 @@ class ExternalDataDestinationSerializer(serializers.ModelSerializer):"created_by","updated_at","synced_sources",+ "status",+ "latest_error",+ "latest_error_at",+ ]+ read_only_fields = [+ "id",+ "is_posthog_warehouse",+ "created_at",+ "created_by",+ "updated_at",+ "synced_sources",+ "status",+ "latest_error",+ "latest_error_at",]- read_only_fields = ["id", "is_posthog_warehouse", "created_at", "created_by", "updated_at", "synced_sources"]def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:destination_type = attrs.get("type", getattr(self.instance, "type", None))@@ -385,8 +416,8 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSif is_service_auth(self.request):return- source_ids = {link.source_id for link in instance.source_links.filter(enabled=True)}- direct_schema_ids = {link.schema_id for link in instance.schema_links.filter(enabled=True)}+ source_ids = {link.source_id for link in instance.source_links.all()}+ direct_schema_ids = {link.schema_id for link in instance.schema_links.all()}schemas = list(ExternalDataSchema.objects.exclude(deleted=True).filter(team_id=self.team_id)@@ -499,6 +530,10 @@ class ExternalDataDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewS# always construct this viewset's serializer with the existing instance to update.self._assert_can_mutate(cast(ExternalDataDestination, serializer.instance))super().perform_update(serializer)+ # An edit is how a user says they fixed the destination, so the next sync tries it again.+ destination = cast(ExternalDataDestination, serializer.instance)+ # Reload under the destination lock: a delivery can pause it after this request reads it.+ resume_destination(destination)def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Soft-delete, and detach it from everything that syncs to it.diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.pyindex 1f8d2a4898ae..7628e21b2769 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py@@ -1,5 +1,5 @@import datetime as dt-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom typing import Any, Optional, castfrom django.db import transaction@@ -1957,6 +1957,15 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if obj.source.is_system_managed:raise PermissionDenied("This schema is managed by PostHog and cannot be changed through this API.")+ def _assert_can_resume_destinations(self, schemas: Iterable[ExternalDataSchema]) -> None:+ if is_service_auth(self.request):+ return+ uac = self.user_access_control+ for schema in schemas:+ level = uac.get_user_access_level(schema.table or schema.source)+ if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):+ raise PermissionDenied("You do not have editor access to every table wired to this destination.")+@extend_schema(exclude=True)def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:# Schemas are created by source schema discovery, never via the API. ModelViewSet would@@ -2068,6 +2077,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):team_id=self.team_id,schema_id=schema.id,destination_ids=serializer.validated_data["destination_ids"],+ authorize_resume=self._assert_can_resume_destinations,)return Response(status=status.HTTP_200_OK,diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.pyindex 1c9c9b236902..ae9c352d46d1 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py@@ -309,6 +309,7 @@ class ExternalDataSourceConnectionOptionsMixin(base.ExternalDataSourceViewSetBasteam_id=self.team_id,source_id=source.id,destination_ids=serializer.validated_data["destination_ids"],+ authorize_resume=self._assert_can_write_schemas,)return Response(status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).datadiff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pyindex c343d489e108..31fe79f4857a 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -1774,6 +1774,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):team_id=self.team_id,source_id=new_source_model.pk,destination_ids=selected_destination_ids,+ authorize_resume=self._assert_can_write_schemas,)except Exception as e:# The source is already created and its tables are configured. Losing that over adiff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.pyindex 084f4704d06e..b03e6bd6d268 100644--- a/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/enablement.py@@ -25,6 +25,15 @@ if TYPE_CHECKING:WAREHOUSE_MULTI_DESTINATION_FLAG = "warehouse-multi-destination"+NO_ACTIVE_DESTINATIONS_MESSAGE = (+ "Every destination this table syncs to is paused, so this sync did not run. "+ "Fix the destination, then edit it to turn it back on."+)+++class NoActiveDestinationsError(Exception):+ """Every link of the schema is off, so the run has nowhere to deliver."""+def is_multi_destination_enabled(team_id: int, source_type: str) -> bool:"""Whether this team's syncs of this source type deliver to configured destinations.@@ -70,8 +79,13 @@ def destination_ids_for_run(schema: ExternalDataSchema) -> list[str]:This list is the run's whole destination set. Anything that needs the external subset asks`external_destination_ids_for` for it rather than reading "non-empty" as "has externaldestinations": the warehouse is delivered through delta, not through a destination writer.+ Raises `NoActiveDestinationsError` when the schema has links but every one of them is off."""- return sorted(str(destination.id) for destination in resolve_destinations(schema))+ destinations = resolve_destinations(schema)+ if not destinations:+ raise NoActiveDestinationsError(NO_ACTIVE_DESTINATIONS_MESSAGE)++ return sorted(str(destination.id) for destination in destinations)def external_destination_ids_for(team_id: int, destination_ids: Sequence[str]) -> list[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.pyindex 6e96dc1adb04..c485d87983de 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/delivery.py@@ -20,6 +20,7 @@ from collections.abc import Iterableimport structlogfrom asgiref.sync import async_to_sync+from products.warehouse_sources.backend.destination_health import record_delivery_failure, record_delivery_successfrom products.warehouse_sources.backend.models.external_data_destination import ExternalDataDestinationfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -291,10 +292,12 @@ def deliver_batch_to_destinations(error=str(e),msg=f"Failed writing to {destination.name} ({run_ctx.table_name}): {e}",)+ record_delivery_failure(destination, e)if isinstance(e, DestinationConfigurationError):raiseraise DestinationDeliveryError(destination.name, e) from e+ record_delivery_success(destination)rows_written = outcome.rows_written if outcome else 0duration_seconds = round(time.monotonic() - started_at, 3)logger.info(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 1beea8a75626..393fd60d666b 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@@ -3,11 +3,16 @@ import uuidfrom posthog.test.base import BaseTestfrom unittest import mock+from django.db import OperationalError+import structlog.testingfrom parameterized import parameterized+from products.warehouse_sources.backend.destination_health import TRANSIENT_DELIVERY_ERRORfrom products.warehouse_sources.backend.models.external_data_destination import (ExternalDataDestination,+ ExternalDataSchemaDestination,+ ExternalDataSourceDestination,get_or_create_warehouse_destination,)from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -377,3 +382,133 @@ class TestWarehousePresence(DeliveryTestCase):a = self._destination("warehouse a")assert delivery.warehouse_is_a_destination(self._signal([str(a.id)])) is False+++class TestDestinationHealth(DeliveryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.source = ExternalDataSource.objects.create(+ team=self.team, source_id="src", connection_id="conn", status="Running", source_type="Stripe"+ )+ self.schema = ExternalDataSchema.objects.create(team=self.team, source=self.source, name="charges")+ # destination_health imports this lazily (inside _record_failure) to avoid a circular+ # import with posthog.tasks.email, so the patch target is the task's home module, not+ # destination_health itself.+ email_patch = mock.patch("posthog.tasks.email.send_warehouse_destination_paused")+ self.paused_email = email_patch.start()+ self.addCleanup(email_patch.stop)++ def _deliver(self, destination: ExternalDataDestination) -> Exception | None:+ try:+ with self.captureOnCommitCallbacks(execute=True):+ delivery.deliver_batch_to_destinations(self._signal([str(destination.id)]))+ except delivery.DestinationDeliveryError as e:+ return e+ return None++ def _set_health(self, destination: ExternalDataDestination, status: str, failures: int) -> None:+ ExternalDataDestination.objects.for_team(self.team.pk).filter(id=destination.id).update(+ status=status, consecutive_configuration_failures=failures+ )+ destination.refresh_from_db()++ @parameterized.expand(+ [+ ("configuration_error", "configuration_error_for", "The host name does not exist.", 2),+ ("transient_error", "fail_for", TRANSIENT_DELIVERY_ERROR, 1),+ ]+ )+ def test_a_failed_delivery_records_the_error_on_the_destination(+ self, _name: str, failure_attribute: str, expected_error: str, expected_failures: int+ ) -> None:+ destination = self._destination("customer redshift")+ self._set_health(destination, ExternalDataDestination.Status.HEALTHY, 1)+ setattr(RecordingWriter, failure_attribute, {"customer redshift"})++ assert self._deliver(destination) is not None++ destination.refresh_from_db()+ assert destination.status == ExternalDataDestination.Status.FAILING+ assert destination.latest_error == expected_error+ assert destination.latest_error_at is not None+ assert destination.consecutive_configuration_failures == expected_failures+ self.paused_email.delay.assert_not_called()++ @parameterized.expand(+ [+ ("failing_is_reset", ExternalDataDestination.Status.FAILING, 2, ExternalDataDestination.Status.HEALTHY, 0),+ ("paused_stays_paused", ExternalDataDestination.Status.PAUSED, 3, ExternalDataDestination.Status.PAUSED, 3),+ ]+ )+ def test_a_successful_delivery_resets_a_failing_destination(+ self, _name: str, status: str, failures: int, expected_status: str, expected_failures: int+ ) -> None:+ destination = self._destination("customer redshift")+ self._set_health(destination, status, failures)++ assert self._deliver(destination) is None++ destination.refresh_from_db()+ assert destination.status == expected_status+ assert destination.consecutive_configuration_failures == expected_failures++ def test_repeated_configuration_errors_pause_only_the_links_to_that_destination(self) -> None:+ broken = self._destination("customer redshift")+ working = self._destination("customer snowflake", ExternalDataDestination.Type.SNOWFLAKE)+ links = ExternalDataSourceDestination.objects.for_team(self.team.pk)+ broken_source_link = links.create(team_id=self.team.pk, source=self.source, destination=broken)+ working_source_link = links.create(team_id=self.team.pk, source=self.source, destination=working)+ broken_schema_link = ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, schema=self.schema, destination=broken+ )+ RecordingWriter.configuration_error_for = {"customer redshift"}++ statuses = []+ with self.settings(DATA_WAREHOUSE_DESTINATION_PAUSE_AFTER_CONFIGURATION_FAILURES=2):+ # The third delivery is a run that started before the pause, so it still reaches the destination.+ for _ in range(3):+ self._deliver(broken)+ broken.refresh_from_db()+ statuses.append(broken.status)++ assert statuses == [+ ExternalDataDestination.Status.FAILING,+ ExternalDataDestination.Status.PAUSED,+ ExternalDataDestination.Status.PAUSED,+ ]+ for link in (broken_source_link, working_source_link, broken_schema_link):+ link.refresh_from_db()+ assert (broken_source_link.enabled, broken_schema_link.enabled, working_source_link.enabled) == (+ False,+ False,+ True,+ )+ self.schema.refresh_from_db()+ assert self.schema.should_sync is True+ self.paused_email.delay.assert_called_once_with(+ self.team.pk, str(broken.id), "customer redshift", "The host name does not exist.", mock.ANY+ )++ @parameterized.expand(+ [+ ("failure", "configuration_error_for", DestinationConfigurationError),+ ("success", None, None),+ ]+ )+ def test_a_health_write_that_fails_does_not_change_the_delivery_outcome(+ self, _name: str, failure_attribute: str | None, expected_error: type[Exception] | None+ ) -> None:+ destination = self._destination("customer redshift")+ destination.status = ExternalDataDestination.Status.FAILING+ if failure_attribute:+ setattr(RecordingWriter, failure_attribute, {"customer redshift"})+ signal = self._signal([str(destination.id)])++ with mock.patch.object(+ ExternalDataDestination.objects, "for_team", side_effect=OperationalError("database unavailable")+ ):+ if expected_error:+ with self.assertRaises(expected_error):+ delivery.deliver_batch_to_destinations(signal, destinations=[destination])+ else:+ assert delivery.deliver_batch_to_destinations(signal, destinations=[destination]) == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.pyindex 09853622d68f..bd214fa3878a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py@@ -58,6 +58,7 @@ from products.batch_exports.backend.facade.destinations.s3 import (ConcurrentS3Consumer,IntermittentUploadPartTimeoutError,PolicyStatement,+ S3IntegrationNotFoundError,get_credentials_using_user_aws_role,get_s3_integration,s3_client,@@ -310,7 +311,10 @@ class S3DestinationWriter:if self._ctx.integration_id is None:raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL)- integration = await get_s3_integration(self._ctx.integration_id, self._ctx.team_id)+ try:+ integration = await get_s3_integration(self._ctx.integration_id, self._ctx.team_id)+ except S3IntegrationNotFoundError as error:+ raise DestinationConfigurationError(self._ctx.destination_name, MISSING_INTEGRATION_DETAIL) from errorendpoint_url: str | None = Nonerefresh_credentials: RefreshCredentials | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex cf0a6b7e3698..684098d58fe1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (+ NoActiveDestinationsError,destination_ids_for_run,is_multi_destination_enabled,)@@ -46,7 +47,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (get_v3_pipeline_lock_holder,)-from products.warehouse_sources.backend.temporal.data_imports.util import retry_internal_db_operation+from products.warehouse_sources.backend.temporal.data_imports.util import (+ NonRetryableException,+ retry_internal_db_operation,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.check_billing_limits import (billing_limit_reached,)@@ -362,7 +366,13 @@ def create_external_data_job_model_activity(destination_ids: list[str] = []if is_multi_destination_enabled(inputs.team_id, source.source_type):- destination_ids = destination_ids_for_run(schema)+ try:+ destination_ids = destination_ids_for_run(schema)+ except NoActiveDestinationsError as e:+ # Fails before the job exists and before anything is extracted, so a paused+ # destination costs the source no reads.+ logger.info("Every destination of this table is paused, not running the sync")+ raise NonRetryableException() from e# A refresh run skips the repartition activity, the only thing that ends a repartition hold on# the import. A refresh while the import is held never wipes the table or restarts the clock,# so the refresh waits until the repartition resolves.@@ -479,6 +489,9 @@ def create_external_data_job_model_activity(import_handoffs_are_free=settings.DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED,failed_runs_in_a_row=failed_runs_in_a_row,)+ except NonRetryableException:+ # Already classified and logged where it was raised.+ raiseexcept V3PipelineLockLostError:# The takeover race the guard handles, not a defect — skip the generic handler's# stack trace log, same reasoning as SourceOrSchemaDeletedError above.diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex c73bc0ea15ee..17d8cdd947cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -15,10 +15,18 @@ from posthog.temporal.common.posthog_client import is_expected_activity_failurefrom products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotationfrom products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatisticsfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.external_data_destination import (+ ExternalDataDestination,+ ExternalDataSourceDestination,+)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (+ NO_ACTIVE_DESTINATIONS_MESSAGE,+)+from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableExceptionfrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (CreateExternalDataJobModelActivityInputs,SourceOrSchemaDeletedError,@@ -340,6 +348,34 @@ class TestCreateJobActivityStatusOrdering:assert outputs.failed_runs_in_a_row == 4+ @patch(f"{MODULE}.close_old_connections")+ @patch(f"{MODULE}.activity")+ @patch(f"{MODULE}._verify_v3_lock_still_held")+ @patch(f"{MODULE}.is_multi_destination_enabled", return_value=True)+ def test_a_table_whose_every_destination_is_paused_fails_before_the_job_exists(+ self, _mock_flag: MagicMock, _mock_lock: MagicMock, mock_activity: MagicMock, _mock_close: MagicMock+ ) -> None:+ mock_activity.info.return_value.workflow_id = "wf-1"+ mock_activity.info.return_value.workflow_run_id = "run-1"+ team = _team()+ schema = _schema(team, None)+ destination = ExternalDataDestination.objects.for_team(team.id).create(+ team_id=team.id, type=ExternalDataDestination.Type.REDSHIFT, name="paused"+ )+ ExternalDataSourceDestination.objects.for_team(team.id).create(+ team_id=team.id, source=schema.source, destination=destination, enabled=False+ )++ with pytest.raises(NonRetryableException) as exc_info:+ create_external_data_job_model_activity(+ CreateExternalDataJobModelActivityInputs(+ team_id=team.id, schema_id=schema.id, source_id=schema.source_id, billable=True, is_v3=True+ )+ )++ assert str(exc_info.value.cause) == NO_ACTIVE_DESTINATIONS_MESSAGE+ assert not ExternalDataJob.objects.filter(schema_id=schema.id).exists()+@pytest.mark.django_dbclass TestCreateJobActivityScheduledFullRefresh:diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py b/products/warehouse_sources/backend/tests/api/test_external_data_destination.pyindex 87db6a367e6e..20c2a520419f 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_destination.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_destination.py@@ -82,6 +82,8 @@ class TestExternalDataDestinationAPI(DestinationAPITestBase):assert [d["id"] for d in listing["results"]] == [str(destination.id)]assert listing["results"][0]["is_posthog_warehouse"] is False+ assert listing["results"][0]["status"] == ExternalDataDestination.Status.HEALTHY+ assert listing["results"][0]["latest_error"] is Nonedef test_a_destination_needs_an_integration(self) -> None:response = self.client.post(self.base, {"type": ExternalDataDestination.Type.POSTGRES, "name": "no creds"})@@ -695,6 +697,79 @@ class TestDestinationLinkEndpoints(DestinationAPITestBase):assert self.client.get(self.source_url).json()["destination_ids"] == [str(other.id)]+ @parameterized.expand(+ [+ ("edit_paused", "edit", ExternalDataDestination.Status.PAUSED),+ ("edit_failing", "edit", ExternalDataDestination.Status.FAILING),+ ("select_on_source", "source", ExternalDataDestination.Status.PAUSED),+ ("select_on_table", "schema", ExternalDataDestination.Status.PAUSED),+ ]+ )+ def test_a_user_turns_a_paused_destination_back_on(self, _name: str, action: str, status_before: str) -> None:+ other_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="other",+ connection_id="conn",+ status="Running",+ source_type=ExternalDataSourceType.STRIPE,+ )+ paused = status_before == ExternalDataDestination.Status.PAUSED+ source_link = ExternalDataSourceDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, source=other_source, destination=self.destination, enabled=not paused+ )+ schema_link = ExternalDataSchemaDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, schema=self.schema, destination=self.destination, enabled=not paused+ )+ ExternalDataDestination.objects.for_team(self.team.pk).filter(id=self.destination.id).update(+ status=status_before, consecutive_configuration_failures=3, latest_error="The host name does not exist."+ )++ if action == "edit":+ response = self.client.patch(f"{self.base}/{self.destination.id}", {"name": "fixed"})+ else:+ url = self.source_url if action == "source" else self.schema_url+ response = self.client.patch(url, {"destination_ids": [str(self.destination.id)]})++ assert response.status_code == status.HTTP_200_OK, response.json()+ if action == "edit":+ assert response.json()["status"] == ExternalDataDestination.Status.HEALTHY+ self.destination.refresh_from_db()+ assert self.destination.status == ExternalDataDestination.Status.HEALTHY+ assert self.destination.consecutive_configuration_failures == 0+ assert self.destination.latest_error == "The host name does not exist."+ source_link.refresh_from_db()+ assert source_link.enabled is True+ if action != "schema":+ schema_link.refresh_from_db()+ assert schema_link.enabled is True++ def test_selecting_a_destination_recovers_a_pause_that_races_with_selection(self) -> None:+ from products.warehouse_sources.backend.presentation.views.destination_links import _resolve_destinations++ def pause_after_resolving(*args, **kwargs):+ destinations = _resolve_destinations(*args, **kwargs)+ ExternalDataDestination.objects.for_team(self.team.pk).filter(id=self.destination.id).update(+ status=ExternalDataDestination.Status.PAUSED,+ consecutive_configuration_failures=3,+ )+ return destinations++ with patch(+ "products.warehouse_sources.backend.presentation.views.destination_links._resolve_destinations",+ side_effect=pause_after_resolving,+ ):+ response = self.client.patch(self.source_url, {"destination_ids": [str(self.destination.id)]})++ assert response.status_code == status.HTTP_200_OK, response.json()+ self.destination.refresh_from_db()+ assert self.destination.status == ExternalDataDestination.Status.HEALTHY+ assert self.destination.consecutive_configuration_failures == 0+ assert (+ ExternalDataSourceDestination.objects.for_team(self.team.pk)+ .get(source=self.source, destination=self.destination)+ .enabled+ )+def test_an_unknown_destination_is_rejected(self) -> None:response = self.client.patch(self.source_url, {"destination_ids": ["00000000-0000-0000-0000-000000000000"]})@@ -759,3 +834,67 @@ class TestDestinationLinkEndpoints(DestinationAPITestBase):body = self.client.get(self.schema_url).json()assert body["inherits_from_source"] is Falseassert body["destination_ids"] == [str(other.id)]+++class TestDestinationResumeAccessControl(DestinationAPITestBase):+ def setUp(self) -> None:+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ self.editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = self.organization.memberships.get(user=self.editor)+ AccessControl.objects.create(+ team=self.team,+ resource="external_data_source",+ resource_id=None,+ access_level="editor",+ organization_member=membership,+ )+ self.hidden_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="hidden",+ connection_id="hidden-conn",+ status="Running",+ source_type=ExternalDataSourceType.STRIPE,+ )+ ExternalDataSchema.objects.create(team=self.team, source=self.hidden_source, name="hidden_table")+ AccessControl.objects.create(+ team=self.team,+ resource="external_data_source",+ resource_id=str(self.hidden_source.id),+ access_level="none",+ organization_member=membership,+ )+ self.destination = self._create_destination()+ self.hidden_link = ExternalDataSourceDestination.objects.for_team(self.team.pk).create(+ team_id=self.team.pk, source=self.hidden_source, destination=self.destination, enabled=False+ )+ ExternalDataDestination.objects.for_team(self.team.pk).filter(id=self.destination.id).update(+ status=ExternalDataDestination.Status.PAUSED+ )+ self.client.force_login(self.editor)++ @parameterized.expand([("edit",), ("select_on_source",), ("select_on_table",)])+ def test_resuming_requires_editor_access_to_every_wired_table(self, action: str) -> None:+ if action == "edit":+ response = self.client.patch(f"{self.base}/{self.destination.id}", {"name": "fixed"})+ elif action == "select_on_source":+ response = self.client.patch(+ f"/api/projects/{self.team.pk}/external_data_sources/{self.source.id}/destinations",+ {"destination_ids": [str(self.destination.id)]},+ )+ else:+ response = self.client.patch(+ f"/api/projects/{self.team.pk}/external_data_schemas/{self.schema.id}/destinations",+ {"destination_ids": [str(self.destination.id)]},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ self.destination.refresh_from_db()+ self.hidden_link.refresh_from_db()+ assert self.destination.status == ExternalDataDestination.Status.PAUSED+ assert self.hidden_link.enabled is Falsediff --git a/products/warehouse_sources/backend/tests/test_external_data_destination.py b/products/warehouse_sources/backend/tests/test_external_data_destination.pyindex 5ac25e125ffe..2a17d8598c19 100644--- a/products/warehouse_sources/backend/tests/test_external_data_destination.py+++ b/products/warehouse_sources/backend/tests/test_external_data_destination.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.models.external_data_destination importfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.destinations.enablement import (+ NoActiveDestinationsError,destination_ids_for_run,external_destination_ids_for,)@@ -79,6 +80,9 @@ class TestResolveDestinations(BaseTest):)assert resolve_destinations(self.schema) == []+ # An empty id list means "the PostHog warehouse only", which this table never picked.+ with self.assertRaises(NoActiveDestinationsError):+ destination_ids_for_run(self.schema)def test_deleted_destinations_are_excluded(self) -> None:live = self._destination("live")diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex eda7958ebfb0..70ede733e98a 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -45,6 +45,20 @@ export interface SyncedSourceApi {via_table_override: boolean}+/**+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused+ */+export type ExternalDataDestinationStatusEnumApi =+ (typeof ExternalDataDestinationStatusEnumApi)[keyof typeof ExternalDataDestinationStatusEnumApi]++export const ExternalDataDestinationStatusEnumApi = {+ Healthy: 'healthy',+ Failing: 'failing',+ Paused: 'paused',+} as const+export interface ExternalDataDestinationApi {readonly id: string/** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.@@ -79,6 +93,22 @@ export interface ExternalDataDestinationApi {readonly updated_at: string | null/** Sources whose tables sync to this destination, so you can see what a change or a deletion would affect. Includes sources that reach it through a single table's override, and — for the PostHog warehouse — sources that write there by default because nothing else was configured. */readonly synced_sources: readonly SyncedSourceApi[]+ /** Whether delivery to this destination works. `healthy`: the last delivery worked. `failing`: the last delivery failed. `paused`: PostHog stopped syncing to it after repeated configuration errors. Edit the destination to turn it back on.+ *+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused */+ readonly status: ExternalDataDestinationStatusEnumApi+ /**+ * The last delivery error, safe to show to the user. Null if no delivery has failed.+ * @nullable+ */+ readonly latest_error: string | null+ /**+ * When the last delivery error occurred.+ * @nullable+ */+ readonly latest_error_at: string | null}export interface PaginatedExternalDataDestinationListApi {@@ -124,6 +154,22 @@ export interface PatchedExternalDataDestinationApi {readonly updated_at?: string | null/** Sources whose tables sync to this destination, so you can see what a change or a deletion would affect. Includes sources that reach it through a single table's override, and — for the PostHog warehouse — sources that write there by default because nothing else was configured. */readonly synced_sources?: readonly SyncedSourceApi[]+ /** Whether delivery to this destination works. `healthy`: the last delivery worked. `failing`: the last delivery failed. `paused`: PostHog stopped syncing to it after repeated configuration errors. Edit the destination to turn it back on.+ *+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused */+ readonly status?: ExternalDataDestinationStatusEnumApi+ /**+ * The last delivery error, safe to show to the user. Null if no delivery has failed.+ * @nullable+ */+ readonly latest_error?: string | null+ /**+ * When the last delivery error occurred.+ * @nullable+ */+ readonly latest_error_at?: string | null}export interface AddSourcesRequestApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d6345e0a8dc7..08ba851a0a12 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46531,6 +46531,20 @@ export namespace Schemas {S3: 'S3',} as const;+ /**+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused+ */+ export type ExternalDataDestinationStatusEnum = typeof ExternalDataDestinationStatusEnum[keyof typeof ExternalDataDestinationStatusEnum];+++ export const ExternalDataDestinationStatusEnum = {+ Healthy: 'healthy',+ Failing: 'failing',+ Paused: 'paused',+ } as const;+export interface ExternalDataDestination {readonly id: string;/** Where synced rows are written. The PostHog warehouse is managed for you, so you cannot create one here.@@ -46565,6 +46579,22 @@ export namespace Schemas {readonly updated_at: string | null;/** Sources whose tables sync to this destination, so you can see what a change or a deletion would affect. Includes sources that reach it through a single table's override, and — for the PostHog warehouse — sources that write there by default because nothing else was configured. */readonly synced_sources: readonly SyncedSource[];+ /** Whether delivery to this destination works. `healthy`: the last delivery worked. `failing`: the last delivery failed. `paused`: PostHog stopped syncing to it after repeated configuration errors. Edit the destination to turn it back on.+ *+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused */+ readonly status: ExternalDataDestinationStatusEnum;+ /**+ * The last delivery error, safe to show to the user. Null if no delivery has failed.+ * @nullable+ */+ readonly latest_error: string | null;+ /**+ * When the last delivery error occurred.+ * @nullable+ */+ readonly latest_error_at: string | null;}/**@@ -78814,6 +78844,22 @@ export namespace Schemas {readonly updated_at?: string | null;/** Sources whose tables sync to this destination, so you can see what a change or a deletion would affect. Includes sources that reach it through a single table's override, and — for the PostHog warehouse — sources that write there by default because nothing else was configured. */readonly synced_sources?: readonly SyncedSource[];+ /** Whether delivery to this destination works. `healthy`: the last delivery worked. `failing`: the last delivery failed. `paused`: PostHog stopped syncing to it after repeated configuration errors. Edit the destination to turn it back on.+ *+ * * `healthy` - Healthy+ * * `failing` - Failing+ * * `paused` - Paused */+ readonly status?: ExternalDataDestinationStatusEnum;+ /**+ * The last delivery error, safe to show to the user. Null if no delivery has failed.+ * @nullable+ */+ readonly latest_error?: string | null;+ /**+ * When the last delivery error occurred.+ * @nullable+ */+ readonly latest_error_at?: string | null;}/**