Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(alerts): show how to fix unavailable email delivery (#87971)

Matt Pua2046e6457302
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 5769e098fc36..345d006effc1 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -492,7 +492,13 @@ def add_alert_check(
return alert_check, should_notify(outcome)
-def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> AlertCheck:
+def disable_invalid_alert(
+ alert: AlertConfiguration,
+ reason: str,
+ *,
+ notify_subscribers: bool = True,
+ error_code: str | None = None,
+) -> AlertCheck:
"""Auto-disable a misconfigured alert and email its subscribers.
Used for configuration problems that make the alert unevaluable as set up — a deliberate,
@@ -505,15 +511,18 @@ def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> AlertCheck:
alert.save(update_fields=[*state_fields, "last_checked_at"])
targets_to_notify = alert.get_subscribed_users_emails()
+ error = {"message": reason}
+ if error_code:
+ error["code"] = error_code
alert_check = AlertCheck.objects.create(
alert_configuration=alert,
calculated_value=None,
condition=alert.condition,
targets_notified={},
state=AlertState.ERRORED,
- error={"message": reason},
+ error=error,
)
- if targets_to_notify:
+ if targets_to_notify and notify_subscribers:
deliveries = send_notifications_for_disabled(alert, reason, targets_to_notify)
record_alert_delivery(alert, alert_check, deliveries)
return alert_check
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index c1a3bbd5ee73..69a4c1bfe3d4 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -14,6 +14,7 @@ from posthog.schema import AlertState
from posthog.hogql.errors import TableAccessDeniedError
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.email import is_email_available
from posthog.errors import CH_TRANSIENT_ERRORS
from posthog.exceptions_capture import capture_exception
from posthog.query_creator_access import creator_access_revoked, report_creator_access_revoked
@@ -48,6 +49,7 @@ from posthog.temporal.alerts.types import (
)
from posthog.temporal.common.heartbeat import Heartbeater
+from products.alerts.backend.destinations import count_active_alert_destinations
from products.alerts.backend.evaluation import check_alert_for_insight
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.validation import validate_alert_config
@@ -108,6 +110,17 @@ async def retrieve_due_alerts() -> list[AlertInfo]:
return await get_alerts()
+def _has_active_destinations(alert: AlertConfiguration) -> bool:
+ return (
+ count_active_alert_destinations(
+ team_id=alert.team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids={"$insight_alert_firing"},
+ )
+ > 0
+ )
+
+
@temporalio.activity.defn
async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResult:
"""Load the alert, validate its config, and decide whether to evaluate."""
@@ -134,6 +147,12 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
)
return PrepareAlertResult(action=PrepareAction.SKIP, reason=SkipReason.INSIGHT_DELETED)
+ wants_email = bool(alert.get_subscribed_users_emails())
+ if wants_email and not is_email_available() and not _has_active_destinations(alert):
+ reason = "Email delivery is unavailable on this instance. Configure email before re-enabling this alert."
+ disable_invalid_alert(alert, reason, notify_subscribers=False, error_code="email_unavailable")
+ return PrepareAlertResult(action=PrepareAction.AUTO_DISABLE, reason=reason)
+
# Plan downgrade protection: entitlement-gated intervals must stop evaluating when the
# org loses the feature (e.g. billing downgrade), since API validation only runs on writes.
entitlement_error = AlertConfiguration.interval_entitlement_error(
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index a896569046e7..634f221f4cc8 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -327,6 +327,24 @@ class TestPrepareAlert:
assert check.error is not None
assert result.reason in check.error["message"]
+ async def test_auto_disable_email_alert_when_email_is_unavailable(self, alert_with_user) -> None:
+ with patch("posthog.temporal.alerts.activities.is_email_available", return_value=False):
+ env = ActivityEnvironment()
+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(alert_with_user.id)))
+
+ assert result.action == PrepareAction.AUTO_DISABLE
+ assert (
+ result.reason
+ == "Email delivery is unavailable on this instance. Configure email before re-enabling this alert."
+ )
+
+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_user.pk)
+ assert refreshed.enabled is False
+ assert refreshed.state == AlertState.ERRORED
+
+ check = await sync_to_async(AlertCheck.objects.get)(alert_configuration=refreshed)
+ assert check.error == {"message": result.reason, "code": "email_unavailable"}
+
async def test_evaluate_for_valid_alert(self, alert) -> None:
env = ActivityEnvironment()
result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(alert.id)))
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 2588819da2e8..6eef8a8b5bf8 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -184,19 +184,20 @@ async def _run_check_alert_workflow(alert_id: str, slo: SloConfig, team_id: int,
interceptors=[SloInterceptor()],
workflow_runner=UnsandboxedWorkflowRunner(),
):
- await env.client.execute_workflow(
- CheckAlertWorkflow.run,
- CheckAlertWorkflowInputs(
- alert_id=alert_id,
- team_id=team_id,
- distinct_id=alert_id,
- calculation_interval=AlertCalculationInterval.DAILY.value,
- insight_id=insight_id,
- slo=slo,
- ),
- id=f"check-alert-{uuid.uuid4()}",
- task_queue=settings.TEMPORAL_TASK_QUEUE,
- )
+ with patch("posthog.temporal.alerts.activities.is_email_available", return_value=True):
+ await env.client.execute_workflow(
+ CheckAlertWorkflow.run,
+ CheckAlertWorkflowInputs(
+ alert_id=alert_id,
+ team_id=team_id,
+ distinct_id=alert_id,
+ calculation_interval=AlertCalculationInterval.DAILY.value,
+ insight_id=insight_id,
+ slo=slo,
+ ),
+ id=f"check-alert-{uuid.uuid4()}",
+ task_queue=settings.TEMPORAL_TASK_QUEUE,
+ )
def _completed_slo_props(mock_slo_analytics: MagicMock, operation: SloOperation = SloOperation.ALERT_CHECK) -> dict:
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 3fa493ee01e9..23b66dab7b53 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -33,6 +33,7 @@ from posthog.api.fields import OptionalBooleanField
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
+from posthog.email import is_email_available
from posthog.event_usage import get_request_analytics_properties
from posthog.exceptions_capture import capture_exception
from posthog.helpers.trigram_search import (
@@ -251,6 +252,7 @@ class AlertDeliverySerializer(serializers.Serializer):
class AlertCheckSerializer(serializers.ModelSerializer):
targets_notified = serializers.SerializerMethodField()
+ error = serializers.SerializerMethodField(allow_null=True)
investigation_notebook_short_id = serializers.SerializerMethodField(
help_text="Short ID of the Notebook produced by the investigation agent, when the agent ran for this check."
)
@@ -268,6 +270,7 @@ class AlertCheckSerializer(serializers.ModelSerializer):
"created_at",
"calculated_value",
"state",
+ "error",
"targets_notified",
"anomaly_scores",
"triggered_points",
@@ -287,6 +290,16 @@ class AlertCheckSerializer(serializers.ModelSerializer):
def get_targets_notified(self, instance: AlertCheck) -> bool:
return instance.targets_notified != {}
+ def get_error(self, instance: AlertCheck) -> dict[str, str] | None:
+ if not isinstance(instance.error, dict):
+ return None
+ message = instance.error.get("message")
+ if not isinstance(message, str):
+ return None
+ if instance.error.get("code") == "email_unavailable":
+ return {"code": "email_unavailable", "message": message}
+ return {"message": "This alert encountered an error. Check the alert configuration and try again."}
+
def get_investigation_notebook_short_id(self, instance: AlertCheck) -> str | None:
notebook = instance.investigation_notebook
return notebook.short_id if notebook is not None else None
@@ -1257,6 +1270,7 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
failed_delivery_channels: list[str] = []
successful_email_count = 0
successful_destination_count = 0
+ email_delivery_unavailable = bool(email_targets) and not is_email_available()
if email_targets:
try:
send_test_alert_email(alert, recipients=email_targets, idempotency_key=str(uuid.uuid4()))
@@ -1280,8 +1294,13 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
failed_delivery_channels.append("destination")
if successful_email_count == 0 and successful_destination_count == 0:
+ detail = (
+ "Email delivery is unavailable for this instance. Configure email settings before trying again."
+ if email_delivery_unavailable
+ else "Unable to start the test delivery. Check the configured channels and try again."
+ )
return Response(
- {"detail": "Unable to start the test delivery. Check the configured channels and try again."},
+ {"detail": detail},
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
posthoganalytics.capture(
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index 74c89a116660..1c71908f42b9 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -382,6 +382,57 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert len(body["checks"]) == expected_count
assert body["checks_total"] == total_checks
+ def test_retrieve_check_includes_allowlisted_error_code(self) -> None:
+ creation_request = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "error code test",
+ }
+ alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()
+ alert_obj = AlertConfiguration.objects.get(id=alert["id"])
+ AlertCheck.objects.create(
+ alert_configuration=alert_obj,
+ calculated_value=None,
+ state=AlertState.ERRORED,
+ error={"code": "email_unavailable", "message": "Email delivery is unavailable."},
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["checks"][0]["error"] == {
+ "code": "email_unavailable",
+ "message": "Email delivery is unavailable.",
+ }
+
+ def test_retrieve_check_hides_internal_error_message(self) -> None:
+ creation_request = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "internal error test",
+ }
+ alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()
+ alert_obj = AlertConfiguration.objects.get(id=alert["id"])
+ AlertCheck.objects.create(
+ alert_configuration=alert_obj,
+ calculated_value=None,
+ state=AlertState.ERRORED,
+ error={"message": "ClickHouse failed to connect to internal.example.com"},
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["checks"][0]["error"] == {
+ "message": "This alert encountered an error. Check the alert configuration and try again."
+ }
+
@parameterized.expand(
[
("returns_newest_slice_first", 3, 0, [7.0, 6.0, 5.0]),
@@ -1739,6 +1790,24 @@ class TestAlertTestDelivery(APIBaseTest):
mock_email_message.return_value.send.assert_called_once_with()
mock_trigger.assert_not_called()
+ @mock.patch("products.alerts.backend.presentation.views.alert.is_email_available", return_value=False)
+ @mock.patch(
+ "products.alerts.backend.presentation.views.alert.send_test_alert_email",
+ side_effect=RuntimeError("email unavailable"),
+ )
+ def test_returns_email_unavailable_when_email_delivery_is_not_configured(
+ self, _mock_email, _mock_available
+ ) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert["id"])
+ AlertSubscription.objects.create(alert_configuration=alert, user=self.user)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}/test-delivery/")
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE, response.content
+ assert response.json() == {
+ "detail": "Email delivery is unavailable for this instance. Configure email settings before trying again."
+ }
+
@mock.patch(
"products.alerts.backend.presentation.views.alert.send_test_alert_email",
side_effect=RuntimeError("email failed"),
diff --git a/products/alerts/frontend/components/AlertDefinition.tsx b/products/alerts/frontend/components/AlertDefinition.tsx
index 3f1901e8185e..66ec6c639a47 100644
--- a/products/alerts/frontend/components/AlertDefinition.tsx
+++ b/products/alerts/frontend/components/AlertDefinition.tsx
@@ -1,7 +1,7 @@
import { ReactNode } from 'react'
import { IconCalendar, IconClock } from '@posthog/icons'
-import { LemonTag, Link } from '@posthog/lemon-ui'
+import { LemonBanner, LemonTag, Link } from '@posthog/lemon-ui'
import { AlertState } from '~/queries/schema/schema-general'
@@ -39,6 +39,34 @@ export function AlertStateIndicator({ alert }: { alert: AlertType }): JSX.Elemen
}
}
+export function AlertErrorBanner({ alert }: { alert: AlertType }): JSX.Element | null {
+ if (alert.state !== AlertState.ERRORED) {
+ return null
+ }
+
+ const error = alert.checks?.find((check) => check.error?.message)?.error
+ if (!error?.message) {
+ return null
+ }
+
+ if (error.code !== 'email_unavailable') {
+ return (
+ <LemonBanner type="error" data-attr="alert-error-banner">
+ <strong>{alert.enabled ? 'Alert error.' : 'Alert disabled.'}</strong> {error.message}
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <LemonBanner type="error" data-attr="alert-error-banner">
+ <strong>Alert disabled.</strong> {error.message} To resume it,{' '}
+ <Link to="https://posthog.com/docs/self-host/configure/email" target="_blank" targetBlankIcon>
+ configure email settings
+ </Link>
+ </LemonBanner>
+ )
+}
+
interface AlertNextEvaluationStatusProps {
children: ReactNode
loading?: boolean
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 0ab5a018b34f..ae7512ba5a81 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -179,12 +179,19 @@ export interface AlertDeliveryApi {
display_label: string
}
+/**
+ * @nullable
+ */
+export type AlertCheckApiError = { [key: string]: string } | null
+
export interface AlertCheckApi {
readonly id: string
readonly created_at: string
/** @nullable */
readonly calculated_value: number | null
readonly state: AlertCheckStateEnumApi
+ /** @nullable */
+ readonly error: AlertCheckApiError
readonly targets_notified: boolean
readonly anomaly_scores: unknown
readonly triggered_points: unknown
diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.ts
index a1a422ba9055..f9133e4f4b50 100644
--- a/products/alerts/frontend/logic/alertNotificationLogic.ts
+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts
@@ -516,10 +516,6 @@ export const alertNotificationLogic = kea<alertNotificationLogicType>([
}
lemonToast.success(`Test delivery started for ${deliveryTargets.join(' and ')}.`)
},
- sendTestDeliveryFailure: ({ errorObject }) => {
- const detail = errorObject?.detail
- lemonToast.error(typeof detail === 'string' ? detail : 'Unable to send the test. Try again.')
- },
})),
afterMount(({ actions, props }) => {
diff --git a/products/alerts/frontend/types.ts b/products/alerts/frontend/types.ts
index 6241f92f7cad..a51e9d7fe640 100644
--- a/products/alerts/frontend/types.ts
+++ b/products/alerts/frontend/types.ts
@@ -138,6 +138,7 @@ export interface AlertCheck {
created_at: string
calculated_value: number | null
state: AlertState
+ error?: { code?: string; message?: string } | null
targets_notified: boolean
anomaly_scores?: (number | null)[] | null
triggered_points?: number[] | null
diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsx
index dd7563fff046..89a622cae63e 100644
--- a/products/alerts/frontend/views/EditAlertModal.tsx
+++ b/products/alerts/frontend/views/EditAlertModal.tsx
@@ -19,7 +19,11 @@ import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'
import { FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'
import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/AlertAdvancedOptionsSection'
-import { AlertStateIndicator, AlertTimezoneNotice } from 'products/alerts/frontend/components/AlertDefinition'
+import {
+ AlertErrorBanner,
+ AlertStateIndicator,
+ AlertTimezoneNotice,
+} from 'products/alerts/frontend/components/AlertDefinition'
import { AlertDefinitionSection } from 'products/alerts/frontend/components/AlertDefinitionSection'
import {
AlertEditor,
@@ -509,6 +513,7 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {
</div>
) : undefined
}
+ statusNode={alert ? <AlertErrorBanner alert={alert} /> : undefined}
tabs={tabs}
/>
)
diff --git a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
index 76aac902ca81..30e689a717bf 100644
--- a/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
+++ b/products/alerts/frontend/views/InsightAlertNotificationSection.tsx
@@ -1,6 +1,10 @@
+import { useValues } from 'kea'
+
import { IconBell } from '@posthog/icons'
+import { LemonBanner, Link } from '@posthog/lemon-ui'
import { MemberSelectMultiple } from 'lib/components/MemberSelectMultiple'
+import { preflightLogic } from 'lib/logic/preflightLogic'
import { InsightShortId } from '~/types'
@@ -27,6 +31,11 @@ export function InsightAlertNotificationSection({
showSectionTitle = true,
onSetAlertFormValue,
}: InsightAlertNotificationSectionProps): JSX.Element {
+ const { preflight, preflightLoading } = useValues(preflightLogic)
+ const hasEmailRecipients = alertForm.subscribed_users?.some((user) => Boolean(user.email)) ?? false
+ const showEmailUnavailableWarning =
+ !preflightLoading && preflight?.email_service_available === false && hasEmailRecipients
+
let destinations: JSX.Element
if (inlineNotificationsEnabled) {
destinations = <InlineAlertNotifications alertId={alertId} />
@@ -42,6 +51,14 @@ export function InsightAlertNotificationSection({
const content = (
<>
+ {showEmailUnavailableWarning ? (
+ <LemonBanner type="warning" data-attr="alert-email-unavailable-banner" className="mb-4">
+ Email delivery is unavailable for this instance. This alert will not send email notifications.{' '}
+ <Link to="https://posthog.com/docs/self-host/configure/email" target="_blank" targetBlankIcon>
+ Configure email settings
+ </Link>
+ </LemonBanner>
+ ) : null}
<div className="flex gap-4 items-center">
<div>E-mail</div>
<div className="flex-auto" data-prevent-wizard-submit>
diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsx
index 3c9bda050852..79d1f1ff4f43 100644
--- a/products/alerts/frontend/views/InsightAlerts.tsx
+++ b/products/alerts/frontend/views/InsightAlerts.tsx
@@ -119,7 +119,7 @@ export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {
title: 'Status',
dataIndex: 'state',
render: function renderStateIndicator(_, alert: AlertType) {
- return alert.enabled ? <AlertStateIndicator alert={alert} /> : null
+ return <AlertStateIndicator alert={alert} />
},
},
{
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dc27f84b24a0..f6f1e7ea8a95 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9341,12 +9341,19 @@ export namespace Schemas {
display_label: string;
}
+ /**
+ * @nullable
+ */
+ export type AlertCheckError = {[key: string]: string} | null;
+
export interface AlertCheck {
readonly id: string;
readonly created_at: string;
/** @nullable */
readonly calculated_value: number | null;
readonly state: AlertCheckStateEnum;
+ /** @nullable */
+ readonly error: AlertCheckError;
readonly targets_notified: boolean;
readonly anomaly_scores: unknown;
readonly triggered_points: unknown;