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): report the real outcome when an AI detector check fails (#105409)

posthog[bot]cd310654eaac
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index e589bda639c0..5a040096b9a1 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -321,8 +321,8 @@ def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempo
"insight_name": alert.insight.name,
"next_check_at": alert.next_check_at,
# The template drops its "review the alert settings" advice for this code, because
- # a provider PostHog could not reach is not something the alert's owner can fix.
- "provider_unavailable": error.get("code") == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
+ # a check the AI detector could not complete is not something the owner can fix.
+ "detector_unavailable": error.get("code") == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
},
)
accepted_at = datetime.now(UTC).isoformat()
diff --git a/posthog/templates/email/alert_check_failed_to_evaluate.html b/posthog/templates/email/alert_check_failed_to_evaluate.html
index bc1f2bd838b2..2a2840d6dd7f 100644
--- a/posthog/templates/email/alert_check_failed_to_evaluate.html
+++ b/posthog/templates/email/alert_check_failed_to_evaluate.html
@@ -1,10 +1,7 @@
{% extends "email/base.html" %}
{% block heading %}{{ alert_name }}{% endblock %} {% block section %}
-{% if provider_unavailable %}
- <p>
- PostHog could not run the AI detector for this alert.
- The alert and insight settings are correct, so there is nothing to change.
- </p>
+{% if detector_unavailable %}
+ <p>PostHog could not run the AI detector for this alert, so this check did not run.</p>
{% else %}
<p>
PostHog could not evaluate this alert. This can happen when the insight or alert settings need attention, or
@@ -22,7 +19,7 @@
<i>{{ alert_error }}</i>
</p>
<p>
- {% if not provider_unavailable %}Review the alert settings.{% endif %}
+ {% if not detector_unavailable %}Review the alert settings.{% endif %}
{% if next_check_at %}
PostHog will try again on {{ next_check_at|date:"F j, Y, g:i A T" }}.
{% else %}
@@ -32,7 +29,7 @@
</p>
<div class="mb mt text-center">
<a class="button" href="{% absolute_uri alert_url %}">
- {% if provider_unavailable %}View alert{% else %}Review alert{% endif %}
+ {% if detector_unavailable %}View alert{% else %}Review alert{% endif %}
</a>
</div>
{% endblock %}
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 6f04a4562d28..d52afa0880a2 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -374,7 +374,6 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
# re-raise so the retry policy gets another attempt. Once the attempts run out the
# retry-exhausted path records an errored check, the same outcome as any other
# evaluation that never produced a value.
- record_ai_detector_check_outcome("unavailable")
raise
except LLMDetectorMisconfiguredError as err:
# Same fail-loud outcome as a bad query shape below, counted apart because a
@@ -487,7 +486,15 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
# Route and evaluate the same snapshot. A second read after choosing the executor
# could pick up an AI detector and run its model call on the shared pool.
alert = await _load_alert_for_evaluation(inputs)
- executor = _LLM_EVALUATE_EXECUTOR if is_llm_detector_config(alert.detector_config) else None
+ uses_llm_detector = is_llm_detector_config(alert.detector_config)
+ if uses_llm_detector != inputs.uses_llm_detector:
+ # The prepare phase picked the task queue from the detector type it read, and only
+ # the AI worker holds the model credentials. An edit since then means this worker may
+ # not be able to run the alert as it now stands, so leave it to the next scheduler
+ # tick, which prepares and routes it again.
+ logger.info("alerts.skip_detector_type_changed", alert_id=inputs.alert_id)
+ return EvaluateAlertResult(alert_check_id=None, should_notify=False, new_state=AlertState(alert.state))
+ executor = _LLM_EVALUATE_EXECUTOR if uses_llm_detector else None
return await database_sync_to_async(_evaluate, thread_sensitive=False, executor=executor)(alert)
@@ -601,11 +608,17 @@ async def record_failed_evaluation(inputs: RecordFailedEvaluationActivityInputs)
# machine keeps that from sending a duplicate notification.
if alert.next_check_at is not None and alert.next_check_at > datetime.now(UTC):
return RecordFailedEvaluationResult()
- alert_check, should_notify = _write_errored_alert_check(alert, _failed_evaluation_error(inputs))
+ error = _failed_evaluation_error(inputs)
+ alert_check, should_notify = _write_errored_alert_check(alert, error)
except AlertConfiguration.DoesNotExist:
logger.warning("Alert gone before its failure could be recorded", alert_id=inputs.alert_id)
return RecordFailedEvaluationResult()
+ # Counted here and not on the failing attempt, so one scheduled check stays one increment
+ # however many times Temporal retried it.
+ if error.get("code") == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE:
+ record_ai_detector_check_outcome("unavailable")
+
logger.warning(
"alerts.recorded_failed_evaluation",
alert_id=inputs.alert_id,
@@ -678,11 +691,10 @@ def dispatch_alert_error_in_app_notifications(alert: AlertConfiguration, alert_c
)
title = f"{alert_name[:75]} could not be evaluated"
if error_code == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE:
- # A provider PostHog could not reach is not something the alert's owner can fix,
+ # A check the AI detector could not complete is not something the owner can fix,
# so this case drops the advice to review the alert settings.
body = (
f"PostHog could not evaluate this alert: {error_message}. "
- "The alert and insight settings are correct, so there is nothing to change. "
f"{next_check_message} If it fails again, contact support."
)
else:
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 27663716f17f..ac351e4bbb92 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -486,11 +486,63 @@ class TestEvaluateAlert:
env = ActivityEnvironment()
await env.run(
evaluate_alert,
- EvaluateAlertActivityInputs(alert_id=str(alert.id), uses_llm_detector=not uses_llm_detector),
+ EvaluateAlertActivityInputs(alert_id=str(alert.id), uses_llm_detector=uses_llm_detector),
)
assert thread_names[0].startswith("insight-alert-llm-evaluate") is uses_llm_detector
+ @pytest.mark.parametrize("prepared_as_llm_detector", [False, True])
+ async def test_skips_when_the_detector_type_no_longer_matches_the_routed_queue(
+ self, alert, ateam, prepared_as_llm_detector: bool
+ ) -> None:
+ # Only the AI worker holds the model credentials, and prepare picked the queue from the
+ # detector type it read. An edit since then must leave the check to the next tick instead
+ # of running it on a worker that cannot serve it.
+ await sync_to_async(AlertConfiguration.objects.filter(team=ateam, id=alert.id).update)(
+ detector_config={"type": "llm" if prepared_as_llm_detector else "zscore"}
+ )
+
+ with patch("posthog.temporal.alerts.activities.check_alert_for_insight") as mock_evaluate:
+ env = ActivityEnvironment()
+ result = await env.run(
+ evaluate_alert,
+ EvaluateAlertActivityInputs(
+ alert_id=str(alert.id),
+ uses_llm_detector=not prepared_as_llm_detector,
+ team_id=ateam.id,
+ ),
+ )
+
+ mock_evaluate.assert_not_called()
+ assert result.alert_check_id is None
+ assert result.should_notify is False
+ assert not await sync_to_async(AlertCheck.objects.filter(alert_configuration_id=alert.id).exists)()
+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(id=alert.id)
+ assert refreshed.next_check_at == alert.next_check_at
+
+ async def test_an_unavailable_detector_is_not_counted_on_every_attempt(self, alert, ateam) -> None:
+ # Temporal retries this activity, so counting here would report one scheduled check as
+ # several failures. The retry-exhausted path owns the count instead.
+ await sync_to_async(AlertConfiguration.objects.filter(team=ateam, id=alert.id).update)(
+ detector_config={"type": "llm"}
+ )
+
+ with (
+ patch(
+ "posthog.temporal.alerts.activities.check_alert_for_insight",
+ side_effect=LLMDetectorUnavailableError("Model timed out"),
+ ),
+ patch("posthog.temporal.alerts.activities.record_ai_detector_check_outcome") as mock_outcome,
+ ):
+ env = ActivityEnvironment()
+ with pytest.raises(LLMDetectorUnavailableError):
+ await env.run(
+ evaluate_alert,
+ EvaluateAlertActivityInputs(alert_id=str(alert.id), uses_llm_detector=True, team_id=ateam.id),
+ )
+
+ mock_outcome.assert_not_called()
+
@pytest.mark.parametrize(
"changes,evaluation_error",
[
@@ -823,6 +875,51 @@ class TestRecordFailedEvaluation:
)
assert result_again.alert_check_id is not None
+ @pytest.mark.parametrize(
+ "error_type,expected_outcomes",
+ [
+ (LLMDetectorUnavailableError.__name__, ["unavailable"]),
+ ("ValueError", []),
+ (None, []),
+ ],
+ )
+ async def test_counts_one_unavailable_outcome_per_recorded_failure(
+ self, alert, error_type, expected_outcomes
+ ) -> None:
+ env = ActivityEnvironment()
+ with patch("posthog.temporal.alerts.activities.record_ai_detector_check_outcome") as mock_outcome:
+ result = await env.run(
+ record_failed_evaluation,
+ RecordFailedEvaluationActivityInputs(
+ alert_id=str(alert.id),
+ error_message="Model timed out",
+ error_type=error_type,
+ team_id=alert.team_id,
+ ),
+ )
+
+ assert result.alert_check_id is not None
+ assert [call.args[0] for call in mock_outcome.call_args_list] == expected_outcomes
+
+ async def test_does_not_count_an_unavailable_outcome_it_never_recorded(self, alert_with_user) -> None:
+ # A disable between prepare and evaluate writes no errored check, so it is not a failed
+ # detector check either and must not move the health counter.
+ await sync_to_async(AlertConfiguration.objects.filter(pk=alert_with_user.id).update)(enabled=False)
+
+ env = ActivityEnvironment()
+ with patch("posthog.temporal.alerts.activities.record_ai_detector_check_outcome") as mock_outcome:
+ result = await env.run(
+ record_failed_evaluation,
+ RecordFailedEvaluationActivityInputs(
+ alert_id=str(alert_with_user.id),
+ error_message="Alert disabled between prepare and evaluate",
+ error_type=LLMDetectorUnavailableError.__name__,
+ ),
+ )
+
+ assert result.alert_check_id is None
+ mock_outcome.assert_not_called()
+
async def test_skips_disabled_alert_without_recording_or_notifying(self, alert_with_user) -> None:
# Disabling an alert mid-check makes evaluate_alert raise into this activity. A normal
# disable must not become an errored check or a "could not evaluate" email to subscribers.
@@ -1029,7 +1126,9 @@ class TestNotifyAlert:
assert "Insight has a breakdown." in notification.body
assert "try again" not in notification.body
- async def test_unreachable_provider_notification_does_not_ask_for_a_settings_review(self, alert_with_user) -> None:
+ async def test_unavailable_detector_notification_names_no_cause_and_no_settings_review(
+ self, alert_with_user
+ ) -> None:
next_check_at = datetime(2026, 8, 12, 14, 30, tzinfo=UTC)
await sync_to_async(AlertConfiguration.objects.filter(pk=alert_with_user.pk).update)(
next_check_at=next_check_at
@@ -1055,8 +1154,9 @@ class TestNotifyAlert:
)
notification = mock_create_notification.call_args.args[0]
- assert "could not reach its model provider" in notification.body
- assert "there is nothing to change" in notification.body
+ assert "could not complete this check" in notification.body
+ assert "model provider" not in notification.body
+ assert "there is nothing to change" not in notification.body
assert "Review the alert settings" not in notification.body
assert "settings need attention" not in notification.body
assert "PostHog will try again on August 12, 2026 at 2:30 PM UTC" in notification.body
@@ -1099,21 +1199,21 @@ class TestNotifyAlert:
assert mock_send_alert_email.call_args.kwargs["template_context"]["next_check_at"] == next_check_at
@pytest.mark.parametrize(
- "error,provider_unavailable",
+ "error,detector_unavailable",
[
({"message": "boom"}, False),
({"message": "boom", "code": "invalid_configuration"}, False),
({"message": LLM_DETECTOR_UNAVAILABLE_MESSAGE, "code": LLM_DETECTOR_UNAVAILABLE_ERROR_CODE}, True),
],
)
- async def test_error_email_marks_an_unreachable_provider(
- self, alert_with_user, error, provider_unavailable
+ async def test_error_email_marks_an_unavailable_detector(
+ self, alert_with_user, error, detector_unavailable
) -> None:
with patch("posthog.tasks.alerts.utils.send_alert_email") as mock_send_alert_email:
await sync_to_async(send_notifications_for_errors)(alert_with_user, error, "notification-key")
template_context = mock_send_alert_email.call_args.kwargs["template_context"]
- assert template_context["provider_unavailable"] is provider_unavailable
+ assert template_context["detector_unavailable"] is detector_unavailable
async def test_error_notification_does_not_include_an_unsubscribed_creator(self, alert, auser) -> None:
await sync_to_async(AlertConfiguration.objects.filter(pk=alert.id).update)(created_by_id=auser.id)
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 67cbeff322fd..13dd37ccad27 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -494,7 +494,7 @@ class _PermanentEvaluationError(Exception):
SloOutcome.FAILURE,
False,
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
- id="model_provider_out_of_reach",
+ id="detector_could_not_complete_the_check",
),
pytest.param(
LLMDetectorUnavailableError("Model timed out"),
@@ -574,7 +574,7 @@ async def test_check_alert_workflow_records_errored_check_when_evaluation_keeps_
if expected_error_code is None:
assert check.error is not None and "code" not in check.error
else:
- # A provider the judge cannot reach is not the owner's configuration, so the check
+ # A check the judge could not complete is not the owner's configuration, so the check
# carries its own code and never the raw transport error.
assert check.error == {
"code": LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,
diff --git a/products/alerts/backend/judge/contract.py b/products/alerts/backend/judge/contract.py
index 650aa6d57222..66fbdbf4da4a 100644
--- a/products/alerts/backend/judge/contract.py
+++ b/products/alerts/backend/judge/contract.py
@@ -55,11 +55,12 @@ class LLMDetectorMisconfiguredError(LLMDetectorError):
# What the alert's owner reads on a check the judge could not reach a verdict for. The raw
# transport error can carry an internal detail, so the check history and the error email show
-# this instead, and the code is what lets it past the serializer's allowlist.
+# this instead, and the code is what lets it past the serializer's allowlist. The wording names
+# the outcome and not a cause: the same error also covers a rollout lookup that returned nothing,
+# a worker with no free model-call slot, and a model reply the judge could not read.
LLM_DETECTOR_UNAVAILABLE_ERROR_CODE = "llm_detector_unavailable"
LLM_DETECTOR_UNAVAILABLE_MESSAGE = (
- "The AI detector could not reach its model provider, so this check did not run. "
- "The alert is still on and the next check tries again."
+ "The AI detector could not complete this check. The alert is still on and the next check tries again."
)
diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.py
index 3a5c1810973e..afcaa678239f 100644
--- a/products/alerts/backend/test/test_email_notifications.py
+++ b/products/alerts/backend/test/test_email_notifications.py
@@ -78,21 +78,22 @@ def test_alert_firing_email_lists_every_breach_description() -> None:
assert "Signups dropped below 50" in html
-def test_alert_evaluation_failure_email_drops_the_settings_advice_for_an_unreachable_provider() -> None:
+def test_alert_evaluation_failure_email_claims_no_cause_for_an_unavailable_detector() -> None:
html = render_to_string(
"email/alert_check_failed_to_evaluate.html",
{
- "alert_error": "The AI detector could not reach its model provider.",
+ "alert_error": "The AI detector could not complete this check.",
"alert_url": "/project/1/insights/example?alert_id=1",
"alert_name": "Example alert",
"insight_url": "/project/1/insights/example",
"insight_name": "Example insight",
- "provider_unavailable": True,
+ "detector_unavailable": True,
},
)
assert "could not run the AI detector" in html
- assert "there is nothing to change" in html
+ assert "model provider" not in html
+ assert "there is nothing to change" not in html
assert "Review the alert settings" not in html
assert "settings need attention" not in html
assert "PostHog will try again" in html
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index afd16967dc91..83a126dfe58c 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -379,7 +379,7 @@ class TestAlert(TrendsInsightAPITest, QueryMatchingTest):
[
("email_unavailable", "Email delivery is unavailable."),
("invalid_configuration", "AI data processing consent was withdrawn for this project."),
- ("llm_detector_unavailable", "The AI detector could not reach its model provider."),
+ ("llm_detector_unavailable", "The AI detector could not complete this check."),
]
)
def test_retrieve_check_includes_allowlisted_error_code(self, code: str, message: str) -> None: