: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
fix(alerts): run ai detector checks on the max-ai task queue (#105304)
posthog[bot]e0f15cc5bc2b
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 85ffec91c861..9ff3b016074c 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -31,6 +31,7 @@ from posthog.temporal.ai_observability import ()from posthog.temporal.alerts import (ACTIVITIES as ALERT_ACTIVITIES,+ AI_QUEUE_ACTIVITIES as ALERT_AI_QUEUE_ACTIVITIES,WORKFLOWS as ALERT_WORKFLOWS,)from posthog.temporal.backfill_group_type_created_at import (@@ -454,7 +455,7 @@ _task_queue_specs = [(settings.MAX_AI_TASK_QUEUE,AI_WORKFLOWS,- AI_ACTIVITIES,+ AI_ACTIVITIES + ALERT_AI_QUEUE_ACTIVITIES,),(settings.TEST_TASK_QUEUE,diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.pyindex 58e726989834..6a53c06e06a0 100644--- a/posthog/management/commands/test/test_start_temporal_worker.py+++ b/posthog/management/commands/test/test_start_temporal_worker.py@@ -6,6 +6,8 @@ from django.conf import settingsfrom posthog.management.commands.start_temporal_worker import (ACTIVITIES_DICT,+ AI_WORKFLOWS,+ ALERT_AI_QUEUE_ACTIVITIES,DATA_SYNC_WORKFLOWS,WA_DIGEST_ACTIVITIES,WA_DIGEST_WORKFLOWS,@@ -92,3 +94,15 @@ def test_wa_digests_are_registered_with_the_weekly_digest() -> None:workflows, activities = entries[0]assert set(WA_DIGEST_WORKFLOWS) <= set(workflows)assert set(WA_DIGEST_ACTIVITIES) <= set(activities)+++# CheckAlertWorkflow routes an AI detector's evaluation to the AI queue, because only that worker+# holds the model provider credentials. Routed there without the activity registered, every AI+# alert check would sit unpolled until it timed out. Queue settings collapse to a single dev queue+# under DEBUG, so match on the spec entry that carries the AI workflows rather than on a queue name.+def test_ai_queue_registers_the_alert_evaluate_activity() -> None:+ entries = [activities for _, workflows, activities in _task_queue_specs if AI_WORKFLOWS[0] in workflows]++ assert len(entries) == 1+ assert ALERT_AI_QUEUE_ACTIVITIES+ assert set(ALERT_AI_QUEUE_ACTIVITIES) <= set(entries[0])diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex c9d83b0bb80e..e589bda639c0 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -18,6 +18,7 @@ from posthog.slo.types import SloOperationfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restrictionfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.alerts.backend.facade.api import LLM_DETECTOR_UNAVAILABLE_ERROR_CODEfrom products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.facade.delivery_slo import alert_delivery_slofrom products.alerts.backend.facade.destinations import (@@ -319,6 +320,9 @@ def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempo"insight_url": insight_url,"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,},)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.htmlindex b6d2be29010a..bc1f2bd838b2 100644--- a/posthog/templates/email/alert_check_failed_to_evaluate.html+++ b/posthog/templates/email/alert_check_failed_to_evaluate.html@@ -1,9 +1,16 @@{% extends "email/base.html" %}{% block heading %}{{ alert_name }}{% endblock %} {% block section %}-<p>- PostHog could not evaluate this alert. This can happen when the insight or alert settings need attention, or- when PostHog has a temporary problem.-</p>+{% 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>+{% else %}+ <p>+ PostHog could not evaluate this alert. This can happen when the insight or alert settings need attention, or+ when PostHog has a temporary problem.+ </p>+{% endif %}<p><strong>Insight</strong><br />@@ -15,7 +22,7 @@<i>{{ alert_error }}</i></p><p>- Review the alert settings.+ {% if not provider_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 %}@@ -24,6 +31,8 @@If it fails again, contact support.</p><div class="mb mt text-center">- <a class="button" href="{% absolute_uri alert_url %}">Review alert</a>+ <a class="button" href="{% absolute_uri alert_url %}">+ {% if provider_unavailable %}View alert{% else %}Review alert{% endif %}+ </a></div>{% endblock %}diff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.pyindex b089a2635742..b33fe60d85ce 100644--- a/posthog/temporal/alerts/__init__.py+++ b/posthog/temporal/alerts/__init__.py@@ -21,6 +21,10 @@ WORKFLOWS = [CleanupAlertChecksWorkflow,]+# CheckAlertWorkflow routes an AI detector's evaluation to the AI task queue, because only+# that worker holds the model provider credentials.+AI_QUEUE_ACTIVITIES = [evaluate_alert]+ACTIVITIES = [retrieve_due_alerts,prepare_alert,diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex e629cd1045df..6f04a4562d28 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -41,7 +41,7 @@ from posthog.tasks.alerts.utils import (skip_because_of_weekend,)from posthog.temporal.alerts.investigation import claim_investigation_slot, decide_investigation-from posthog.temporal.alerts.metrics import record_due_insight_alert_metrics+from posthog.temporal.alerts.metrics import record_ai_detector_check_outcome, record_due_insight_alert_metricsfrom posthog.temporal.alerts.types import (AlertInfo,EvaluateAlertActivityInputs,@@ -62,6 +62,8 @@ from products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import validate_alert_config, validate_alert_insight_queryfrom products.alerts.backend.facade.api import (+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ LLM_DETECTOR_UNAVAILABLE_MESSAGE,MAX_CONCURRENT_MODEL_CALLS,LLMDetectorMisconfiguredError,LLMDetectorUnavailableError,@@ -315,6 +317,17 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResulreturn await _prepare()+def _failed_evaluation_error(inputs: RecordFailedEvaluationActivityInputs) -> dict:+ """The error payload for an evaluation that ran out of retries without writing a check.++ A provider the judge cannot reach is not the owner's configuration, and the raw transport+ error is not written for them, so that case gets its own code and its own wording.+ """+ if inputs.error_type == LLMDetectorUnavailableError.__name__:+ return {"code": LLM_DETECTOR_UNAVAILABLE_ERROR_CODE, "message": LLM_DETECTOR_UNAVAILABLE_MESSAGE}+ return {"message": inputs.error_message}++def _write_errored_alert_check(alert: AlertConfiguration, error: dict) -> tuple[AlertCheck, bool]:"""Write an errored AlertCheck for an already-locked alert and return it with the notify decision.@@ -352,6 +365,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRetry:alert_evaluation_result = check_alert_for_insight(alert, evaluation_id=evaluation_id)breaches = alert_evaluation_result.breaches+ if is_llm_detector_config(alert.detector_config):+ record_ai_detector_check_outcome("evaluated")except CH_TRANSIENT_ERRORS:raiseexcept LLMDetectorUnavailableError:@@ -359,8 +374,14 @@ 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 (AlertExtractionError, LLMDetectorMisconfiguredError) as err:+ except LLMDetectorMisconfiguredError as err:+ # Same fail-loud outcome as a bad query shape below, counted apart because a+ # withdrawn consent or rollout is the owner's to fix and never a provider failure.+ record_ai_detector_check_outcome("misconfigured")+ invalid_configuration = str(err)+ except AlertExtractionError as err:# The alert can't be evaluated as configured (wrong query shape / bad config) — a# deliberate fail-loud outcome, not a bug. Auto-disable and email the owner via the# existing path instead of capturing it as an exception, which would pollute error@@ -580,7 +601,7 @@ 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, {"message": inputs.error_message})+ alert_check, should_notify = _write_errored_alert_check(alert, _failed_evaluation_error(inputs))except AlertConfiguration.DoesNotExist:logger.warning("Alert gone before its failure could be recorded", alert_id=inputs.alert_id)return RecordFailedEvaluationResult()@@ -640,7 +661,8 @@ def dispatch_alert_error_in_app_notifications(alert: AlertConfiguration, alert_cerror_message = str(error.get("message") or "Unknown error").strip().rstrip(".")[:1000] or "Unknown error"alert_name = alert.name or "Alert"source_url = f"/project/{alert.team_id}/insights/{alert.insight.short_id}?alert_id={alert.id}"- if error.get("code") == "invalid_configuration":+ error_code = error.get("code")+ if error_code == "invalid_configuration":# The check turned the alert off, so a promise to try again would be false.title = f"{alert_name[:75]} was turned off"body = (@@ -655,12 +677,21 @@ def dispatch_alert_error_in_app_notifications(alert: AlertConfiguration, alert_celse "PostHog will try again at the next scheduled check.")title = f"{alert_name[:75]} could not be evaluated"- body = (- f"PostHog could not evaluate this alert: {error_message}. "- "This can happen when the insight or alert settings need attention, or when PostHog has a "- f"temporary problem. Review the alert settings. {next_check_message} If it fails again, "- "contact support."- )+ if error_code == LLM_DETECTOR_UNAVAILABLE_ERROR_CODE:+ # A provider PostHog could not reach is not something the alert's 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:+ body = (+ f"PostHog could not evaluate this alert: {error_message}. "+ "This can happen when the insight or alert settings need attention, or when PostHog has a "+ f"temporary problem. Review the alert settings. {next_check_message} If it fails again, "+ "contact support."+ )for user_id, _ in get_alert_error_notification_recipients(alert):try:diff --git a/posthog/temporal/alerts/metrics.py b/posthog/temporal/alerts/metrics.pyindex ccbfebc7a959..2de4dda04cc0 100644--- a/posthog/temporal/alerts/metrics.py+++ b/posthog/temporal/alerts/metrics.py@@ -1,12 +1,26 @@from datetime import datetime+from typing import Literal-from prometheus_client import Gauge+from prometheus_client import Counter, Gaugefrom posthog.metrics import pushed_metrics_registry+AiDetectorCheckOutcome = Literal["evaluated", "unavailable", "misconfigured"]-def record_due_insight_alert_metrics(due_count: int, oldest_due_at: datetime | None, polled_at: datetime) -> None:+# Nothing else separates an AI detector check that reached a verdict from one whose provider+# was out of reach: both land as an errored check, and only the worker logs say which.+_AI_DETECTOR_CHECK_COUNTER = Counter(+ "posthog_insight_alerts_ai_detector_checks_total",+ "AI detector insight alert evaluations, by outcome",+ labelnames=["outcome"],+)+++def record_ai_detector_check_outcome(outcome: AiDetectorCheckOutcome) -> None:+ _AI_DETECTOR_CHECK_COUNTER.labels(outcome=outcome).inc()++def record_due_insight_alert_metrics(due_count: int, oldest_due_at: datetime | None, polled_at: datetime) -> None:oldest_due_age_seconds: float = 0.0if oldest_due_at is not None:oldest_due_age_seconds = max((polled_at - oldest_due_at).total_seconds(), 0)diff --git a/posthog/temporal/alerts/types.py b/posthog/temporal/alerts/types.pyindex 9929edc98f7e..53bc4e22eee9 100644--- a/posthog/temporal/alerts/types.py+++ b/posthog/temporal/alerts/types.py@@ -79,6 +79,9 @@ class RecordFailedEvaluationActivityInputs:error_message: strevaluation_fingerprint: str | None = Noneteam_id: int | None = None+ # Class name of the failure, so the activity can pick a reason written for the alert's+ # owner. None on a workflow that started before this field existed.+ error_type: str | None = None@dataclasses.dataclass(frozen=True)diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.pyindex 736fb13a46e6..dd4ced955a4d 100644--- a/posthog/temporal/alerts/workflows.py+++ b/posthog/temporal/alerts/workflows.py@@ -151,6 +151,14 @@ class CheckAlertWorkflow(PostHogWorkflow):return# Phase 2 — evaluate: CH query + state machine + persist AlertCheck+ # An AI detector calls a model, and only the AI worker holds the provider+ # credentials, so that check evaluates on the AI queue.+ evaluate_task_queue = (+ settings.MAX_AI_TASK_QUEUE+ if prepare_result.uses_llm_detector+ and temporalio.workflow.patched("alerts-evaluate-ai-detector-on-ai-queue")+ else None+ )try:evaluation = await temporalio.workflow.execute_activity(evaluate_alert,@@ -159,6 +167,7 @@ class CheckAlertWorkflow(PostHogWorkflow):uses_llm_detector=prepare_result.uses_llm_detector,team_id=inputs.team_id,),+ task_queue=evaluate_task_queue,start_to_close_timeout=timeouts.evaluate_start_to_close,schedule_to_close_timeout=timeouts.activity_schedule_to_close,heartbeat_timeout=timeouts.heartbeat_timeout,@@ -254,11 +263,15 @@ class CheckAlertWorkflow(PostHogWorkflow):cause = unwrap_temporal_cause(evaluation_error)message = cause.message if cause is not None else str(evaluation_error)message = truncate_for_temporal_payload(message, MAX_ERROR_MESSAGE_CHARS)+ # Temporal rebuilds a remote failure as a bare ApplicationError with the original class+ # name on `type`, which is all the activity needs to pick the owner-facing reason.+ error_type = cause.type if cause is not None else type(evaluation_error).__name__recorded = await temporalio.workflow.execute_activity(record_failed_evaluation,RecordFailedEvaluationActivityInputs(alert_id=inputs.alert_id,error_message=message,+ error_type=error_type,evaluation_fingerprint=evaluation_fingerprint,team_id=inputs.team_id,),diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 0418c7fc26c4..27663716f17f 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -61,7 +61,12 @@ from posthog.temporal.alerts.types import (from products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE-from products.alerts.backend.facade.api import LLMDetectorMisconfiguredError, LLMDetectorUnavailableError+from products.alerts.backend.facade.api import (+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ LLM_DETECTOR_UNAVAILABLE_MESSAGE,+ LLMDetectorMisconfiguredError,+ LLMDetectorUnavailableError,+)from products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.product_analytics.backend.facade.models import Insight@@ -1024,6 +1029,38 @@ class TestNotifyAlert:assert "Insight has a breakdown." in notification.bodyassert "try again" not in notification.body+ async def test_unreachable_provider_notification_does_not_ask_for_a_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+ )+ alert_with_user.next_check_at = next_check_at+ check = await _create_alert_check(+ alert_with_user,+ state=AlertState.ERRORED,+ error={"message": LLM_DETECTOR_UNAVAILABLE_MESSAGE, "code": LLM_DETECTOR_UNAVAILABLE_ERROR_CODE},+ )++ with (+ patch(+ "posthog.tasks.alerts.utils.send_notifications_for_errors",+ return_value=[_email_delivery("[email protected]")],+ ),+ patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,+ ):+ env = ActivityEnvironment()+ await env.run(+ notify_alert,+ NotifyAlertActivityInputs(alert_id=str(alert_with_user.id), alert_check_id=str(check.id)),+ )++ 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 "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+@pytest.mark.parametrize("message", [None, "", " "])async def test_error_notification_uses_fallback_for_missing_reason(self, alert_with_user, message) -> None:check = await _create_alert_check(alert_with_user, state=AlertState.ERRORED, error={"message": message})@@ -1061,6 +1098,23 @@ class TestNotifyAlert:assert [(delivery.channel, delivery.target) for delivery in deliveries] == [("email", subscriber_email)]assert mock_send_alert_email.call_args.kwargs["template_context"]["next_check_at"] == next_check_at+ @pytest.mark.parametrize(+ "error,provider_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+ ) -> 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+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)recipients = await sync_to_async(get_alert_error_notification_recipients)(alert)diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.pyindex b42f304a610c..67cbeff322fd 100644--- a/posthog/temporal/tests/test_alerts_workflows.py+++ b/posthog/temporal/tests/test_alerts_workflows.py@@ -37,6 +37,9 @@ from posthog.temporal.alerts.types import (DEFAULT_MAX_DUE_ALERTS_PER_SCHEDULE_RUN,AlertInfo,CheckAlertWorkflowInputs,+ EvaluateAlertResult,+ PrepareAction,+ PrepareAlertResult,ScheduleDueAlertChecksWorkflowInputs,SkipReason,)@@ -44,7 +47,11 @@ from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlefrom posthog.temporal.common.slo_interceptor import SloInterceptorfrom posthog.temporal.tests.test_alerts_activities import _email_delivery-from products.alerts.backend.facade.api import LLMDetectorUnavailableError+from products.alerts.backend.facade.api import (+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ LLM_DETECTOR_UNAVAILABLE_MESSAGE,+ LLMDetectorUnavailableError,+)from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Thresholdfrom products.product_analytics.backend.facade.models import Insight@@ -56,6 +63,42 @@ CHECK_ALERT_ACTIVITIES: list[Callable[..., Any]] = []+ "uses_llm_detector,expected_task_queue",+ [(False, None), (True, settings.MAX_AI_TASK_QUEUE)],+)+async def test_check_alert_workflow_evaluates_ai_detectors_on_the_ai_task_queue(+ uses_llm_detector: bool, expected_task_queue: str | None+) -> None:+ # Only the AI worker holds the model provider credentials, so an AI detector's evaluation+ # has to leave the analytics-platform queue. Every other alert stays on it (task_queue=None).+ execute_activity = AsyncMock(+ side_effect=[+ PrepareAlertResult(action=PrepareAction.EVALUATE, uses_llm_detector=uses_llm_detector),+ EvaluateAlertResult(alert_check_id=None, should_notify=False, new_state=AlertState.NOT_FIRING),+ ]+ )++ with (+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.execute_activity", new=execute_activity),+ patch("posthog.temporal.alerts.workflows.temporalio.workflow.patched", return_value=True),+ ):+ await CheckAlertWorkflow().run(+ CheckAlertWorkflowInputs(+ alert_id=str(uuid.uuid4()),+ team_id=1,+ distinct_id="alerts-queue-test",+ calculation_interval=AlertCalculationInterval.DAILY.value,+ insight_id=1,+ )+ )++ evaluate_call = execute_activity.await_args_list[1]+ assert evaluate_call.args[0] is evaluate_alert+ assert evaluate_call.kwargs["task_queue"] == expected_task_queue++@pytest.mark.asyncioasync def test_schedule_due_alert_checks_passes_configured_limit_to_retrieval() -> None:execute_activity = AsyncMock(return_value=[])@@ -424,7 +467,7 @@ class _PermanentEvaluationError(Exception):@pytest.mark.parametrize(- "error,expected_attempts,expect_workflow_failure,expected_outcome,edit_on_final_attempt",+ "error,expected_attempts,expect_workflow_failure,expected_outcome,edit_on_final_attempt,expected_error_code",[pytest.param(ClickHouseClusterMemoryLimitExceeded(),@@ -432,6 +475,7 @@ class _PermanentEvaluationError(Exception):True,SloOutcome.FAILURE,False,+ None,id="transient_retried_to_exhaustion",),pytest.param(@@ -440,14 +484,25 @@ class _PermanentEvaluationError(Exception):False,SloOutcome.SUCCESS,False,+ None,id="non_transient_not_retried",),+ pytest.param(+ LLMDetectorUnavailableError("Could not resolve authentication method"),+ ALERT_EVALUATE_RETRY_POLICY.maximum_attempts,+ True,+ SloOutcome.FAILURE,+ False,+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ id="model_provider_out_of_reach",+ ),pytest.param(LLMDetectorUnavailableError("Model timed out"),ALERT_EVALUATE_RETRY_POLICY.maximum_attempts,True,SloOutcome.FAILURE,True,+ None,id="edited_during_final_model_attempt",),],@@ -463,6 +518,7 @@ async def test_check_alert_workflow_records_errored_check_when_evaluation_keeps_expect_workflow_failure: bool,expected_outcome: SloOutcome,edit_on_final_attempt: bool,+ expected_error_code: str | None,) -> None:# However evaluation fails, the workflow must leave an errored check, notify the owner, and push# next_check_at into the future so the one-minute sweep doesn't restart the chain forever.@@ -515,6 +571,15 @@ async def test_check_alert_workflow_records_errored_check_when_evaluation_keeps_else:assert check is not Noneassert check.state == AlertState.ERRORED+ 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+ # carries its own code and never the raw transport error.+ assert check.error == {+ "code": LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ "message": LLM_DETECTOR_UNAVAILABLE_MESSAGE,+ }mock_send_errors.assert_called_once()assert refreshed.next_check_at is not Noneassert refreshed.next_check_at > datetime.now(UTC)diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex 01422b25667d..90ee81119103 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -26,6 +26,8 @@ from products.access_control.backend.facade.user_access_control import UserAccesfrom products.alerts.backend.facade.contracts import DestinationTypefrom products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.judge.contract import (+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ LLM_DETECTOR_UNAVAILABLE_MESSAGE,MAX_CONCURRENT_MODEL_CALLS,MAX_PROMPT_POINTS,LLMDetectorError,@@ -187,6 +189,8 @@ def snooze_alert_from_slack(__all__ = [+ "LLM_DETECTOR_UNAVAILABLE_ERROR_CODE",+ "LLM_DETECTOR_UNAVAILABLE_MESSAGE","MAX_CONCURRENT_MODEL_CALLS","MAX_PROMPT_POINTS","LLMAlertRefusal",diff --git a/products/alerts/backend/judge/__init__.py b/products/alerts/backend/judge/__init__.pyindex 7e9a11fce42c..fef52949dbd3 100644--- a/products/alerts/backend/judge/__init__.py+++ b/products/alerts/backend/judge/__init__.py@@ -6,6 +6,8 @@ implementation is ``products.alerts.backend.judge.llm.LLMSeriesJudge``.from products.alerts.backend.judge.contract import (DEFAULT_CONFIDENCE_THRESHOLD,+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,+ LLM_DETECTOR_UNAVAILABLE_MESSAGE,MAX_CONCURRENT_MODEL_CALLS,MAX_PROMPT_POINTS,AnomalyKind,@@ -20,6 +22,8 @@ from products.alerts.backend.judge.contract import (__all__ = ["DEFAULT_CONFIDENCE_THRESHOLD",+ "LLM_DETECTOR_UNAVAILABLE_ERROR_CODE",+ "LLM_DETECTOR_UNAVAILABLE_MESSAGE","MAX_CONCURRENT_MODEL_CALLS","MAX_PROMPT_POINTS","AnomalyKind",diff --git a/products/alerts/backend/judge/contract.py b/products/alerts/backend/judge/contract.pyindex b01c25a8b628..650aa6d57222 100644--- a/products/alerts/backend/judge/contract.py+++ b/products/alerts/backend/judge/contract.py@@ -53,6 +53,16 @@ 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.+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."+)++@frozenclass SeriesContext:"""What the series means: everything the judge reads that the values array cannot carry."""diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex 4e12a26863e0..8bd23e65bab0 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -83,6 +83,7 @@ from products.alerts.backend.evaluation.validation import (from products.alerts.backend.facade.api import (INSIGHT_ALERT_DESTINATION_TYPES,INSIGHT_ALERT_EVENT_IDS,+ LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,MAX_PROMPT_POINTS,LLMAlertWrite,LLMDetectorError,@@ -573,7 +574,7 @@ class AlertCheckSerializer(serializers.ModelSerializer):# Only reasons written for the alert's owner pass through. Anything else may carry an# internal detail, so the history shows a generic message instead.code = instance.error.get("code")- if code in ("email_unavailable", "invalid_configuration"):+ if code in ("email_unavailable", "invalid_configuration", LLM_DETECTOR_UNAVAILABLE_ERROR_CODE):return {"code": code, "message": message}return {"message": "This alert encountered an error. Check the alert configuration and try again."}diff --git a/products/alerts/backend/test/test_email_notifications.py b/products/alerts/backend/test/test_email_notifications.pyindex 65a8c0ea9c11..3a5c1810973e 100644--- a/products/alerts/backend/test/test_email_notifications.py+++ b/products/alerts/backend/test/test_email_notifications.py@@ -78,6 +78,27 @@ 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:+ html = render_to_string(+ "email/alert_check_failed_to_evaluate.html",+ {+ "alert_error": "The AI detector could not reach its model provider.",+ "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,+ },+ )++ assert "could not run the AI detector" in html+ assert "there is nothing to change" in html+ assert "Review the alert settings" not in html+ assert "settings need attention" not in html+ assert "PostHog will try again" in html+ assert "View alert" in html++def test_alert_evaluation_failure_email_includes_the_reason_and_next_check_timing() -> None:html = render_to_string("email/alert_check_failed_to_evaluate.html",diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 244c8f5365b9..afd16967dc91 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -379,6 +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."),])def test_retrieve_check_includes_allowlisted_error_code(self, code: str, message: str) -> None: