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.

feat(llma): disable evals on terminal user errors (#66186)

Radu Raiceafdc33975049a
diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.py
new file mode 100644
index 000000000000..0715fbff1acd
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_errors.py
@@ -0,0 +1,244 @@
+"""Shared taxonomy for evaluation execution errors.
+
+The split between user-actionable and PostHog-owned errors is load-bearing:
+user errors disable the evaluation without failing the Temporal activity, while
+PostHog-owned errors still raise so Temporal/Grafana stays useful.
+"""
+
+from dataclasses import dataclass
+from typing import Literal
+
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+
+from products.ai_observability.backend.models.evaluations import EvaluationStatusReason
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+
+EvaluationErrorOwner = Literal["user", "posthog"]
+MAX_STATUS_REASON_DETAIL_LENGTH = 2000
+
+
+@dataclass(frozen=True)
+class EvaluationErrorSpec:
+ error_type: str
+ owner: EvaluationErrorOwner
+ safe_message: str
+ status_reason: str | None = None
+ disables_evaluation: bool = False
+ provider_key_state: str | None = None
+ send_trial_usage_email: bool = False
+
+
+USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
+ "trial_limit_reached": EvaluationErrorSpec(
+ error_type="trial_limit_reached",
+ owner="user",
+ safe_message="Trial evaluation limit reached. Add a provider API key to continue.",
+ status_reason=EvaluationStatusReason.TRIAL_LIMIT_REACHED,
+ disables_evaluation=True,
+ send_trial_usage_email=True,
+ ),
+ "model_not_allowed": EvaluationErrorSpec(
+ error_type="model_not_allowed",
+ owner="user",
+ safe_message="The selected model is not available on the trial plan.",
+ status_reason=EvaluationStatusReason.MODEL_NOT_ALLOWED,
+ disables_evaluation=True,
+ ),
+ "no_default_model": EvaluationErrorSpec(
+ error_type="no_default_model",
+ owner="user",
+ safe_message="This provider has no default model. Set a model on the evaluation.",
+ status_reason=EvaluationStatusReason.NO_DEFAULT_MODEL,
+ disables_evaluation=True,
+ ),
+ "key_invalid": EvaluationErrorSpec(
+ error_type="key_invalid",
+ owner="user",
+ safe_message="The provider API key is disabled. Re-validate or replace the key.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_INVALID,
+ disables_evaluation=True,
+ ),
+ "key_not_found": EvaluationErrorSpec(
+ error_type="key_not_found",
+ owner="user",
+ safe_message="The provider API key was deleted. Attach a provider API key before re-enabling.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_DELETED,
+ disables_evaluation=True,
+ ),
+ "auth_error": EvaluationErrorSpec(
+ error_type="auth_error",
+ owner="user",
+ safe_message="The provider API key is invalid or has been deleted.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_INVALID,
+ disables_evaluation=True,
+ provider_key_state=LLMProviderKey.State.INVALID,
+ ),
+ "permission_error": EvaluationErrorSpec(
+ error_type="permission_error",
+ owner="user",
+ safe_message="The provider API key does not have access to this model.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_PERMISSION_DENIED,
+ disables_evaluation=True,
+ provider_key_state=LLMProviderKey.State.ERROR,
+ ),
+ "quota_error": EvaluationErrorSpec(
+ error_type="quota_error",
+ owner="user",
+ safe_message="The provider API key has exceeded its quota.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_QUOTA_EXCEEDED,
+ disables_evaluation=True,
+ provider_key_state=LLMProviderKey.State.ERROR,
+ ),
+ "rate_limit": EvaluationErrorSpec(
+ error_type="rate_limit",
+ owner="user",
+ safe_message="The provider API key is being rate limited.",
+ status_reason=EvaluationStatusReason.PROVIDER_KEY_RATE_LIMITED,
+ disables_evaluation=True,
+ provider_key_state=LLMProviderKey.State.ERROR,
+ ),
+ "model_not_found": EvaluationErrorSpec(
+ error_type="model_not_found",
+ owner="user",
+ safe_message="The selected model was not found. Choose an available model before re-enabling.",
+ status_reason=EvaluationStatusReason.MODEL_NOT_FOUND,
+ disables_evaluation=True,
+ ),
+ "hog_error": EvaluationErrorSpec(
+ error_type="hog_error",
+ owner="user",
+ safe_message="The Hog evaluation code failed. Fix the code before re-enabling this evaluation.",
+ status_reason=EvaluationStatusReason.HOG_ERROR,
+ disables_evaluation=True,
+ ),
+}
+
+
+POSTHOG_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
+ "parse_error": EvaluationErrorSpec(
+ error_type="parse_error",
+ owner="posthog",
+ safe_message="The judge response could not be parsed.",
+ ),
+ "provider_unavailable": EvaluationErrorSpec(
+ error_type="provider_unavailable",
+ owner="posthog",
+ safe_message="The model provider request failed.",
+ ),
+ "emit_evaluation_event_failed": EvaluationErrorSpec(
+ error_type="emit_evaluation_event_failed",
+ owner="posthog",
+ safe_message="The evaluation result event could not be emitted.",
+ ),
+}
+
+
+EVALUATION_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
+ **USER_ERROR_SPECS,
+ **POSTHOG_ERROR_SPECS,
+}
+
+
+def get_evaluation_error_spec(error_type: str | None, *, is_byok: bool = False) -> EvaluationErrorSpec | None:
+ if error_type == "model_not_found" and not is_byok:
+ return None
+ if error_type is None:
+ return None
+ return EVALUATION_ERROR_SPECS.get(error_type)
+
+
+def require_user_error_spec(error_type: str, *, is_byok: bool = False) -> EvaluationErrorSpec:
+ spec = get_evaluation_error_spec(error_type, is_byok=is_byok)
+ if spec is None or spec.owner != "user":
+ raise ValueError(f"Expected user-actionable evaluation error spec for {error_type}")
+ return spec
+
+
+def application_error_details(error: ApplicationError) -> dict[str, str | int | float | bool | None]:
+ if not error.details:
+ return {}
+ details = error.details[0]
+ if isinstance(details, dict):
+ return details
+ return {}
+
+
+def terminal_user_error_result(
+ *,
+ spec: EvaluationErrorSpec,
+ message: str | None,
+ allows_na: bool,
+ provider: str | None = None,
+ model: str | None = None,
+ key_id: str | None = None,
+ is_byok: bool = False,
+) -> EvaluationActivityResult:
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
+ "verdict": None,
+ "reasoning": spec.safe_message if not message else message,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "total_tokens": 0,
+ "is_byok": is_byok,
+ "key_id": key_id,
+ "allows_na": allows_na,
+ "skipped": True,
+ "skip_reason": spec.error_type,
+ "terminal_user_error": True,
+ "status_reason": spec.status_reason,
+ }
+ if provider:
+ result["provider"] = provider
+ if model:
+ result["model"] = model
+ if spec.provider_key_state:
+ result["provider_key_state"] = spec.provider_key_state
+ if allows_na:
+ result["applicable"] = False
+ return result
+
+
+def terminal_user_error_result_from_application_error(
+ error: ApplicationError,
+ *,
+ allows_na: bool,
+ provider: str | None = None,
+ model: str | None = None,
+ key_id: str | None = None,
+ is_byok: bool = False,
+) -> EvaluationActivityResult | None:
+ details = application_error_details(error)
+ error_type = details.get("error_type")
+ detail_key_id = details.get("key_id")
+ resolved_is_byok = is_byok or bool(detail_key_id)
+ spec = get_evaluation_error_spec(str(error_type) if error_type else None, is_byok=resolved_is_byok)
+ if spec is None or spec.owner != "user":
+ return None
+
+ detail_provider = details.get("provider")
+ detail_model = details.get("model")
+ return terminal_user_error_result(
+ spec=spec,
+ message=error.message,
+ allows_na=allows_na,
+ provider=str(detail_provider) if detail_provider else provider,
+ model=str(detail_model) if detail_model else model,
+ key_id=str(detail_key_id) if detail_key_id else key_id,
+ is_byok=resolved_is_byok,
+ )
+
+
+def status_reason_detail_for_terminal_user_error(spec: EvaluationErrorSpec, message: str | None) -> str | None:
+ if spec.error_type != "hog_error" or not message:
+ return None
+
+ if len(message) <= MAX_STATUS_REASON_DETAIL_LENGTH:
+ return message
+ return f"{message[: MAX_STATUS_REASON_DETAIL_LENGTH - 3]}..."
+
+
+def is_terminal_user_error_result(result: EvaluationActivityResult) -> bool:
+ return result.get("terminal_user_error") is True
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
index aed17ac0548a..5e3953afc8df 100644
--- a/posthog/temporal/ai_observability/evaluation_hog.py
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -7,6 +7,10 @@ import temporalio
from temporalio.exceptions import ApplicationError
from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.evaluation_errors import (
+ require_user_error_spec,
+ status_reason_detail_for_terminal_user_error,
+)
from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
@@ -122,13 +126,17 @@ async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict
# non-boolean result). That's an expected outcome of running customer-authored code,
# not a system fault — record it as a skipped evaluation the user can see, rather than
# raising (which would flood error tracking with one event per matching generation).
+ spec = require_user_error_spec("hog_error")
+ error_detail = status_reason_detail_for_terminal_user_error(spec, result["error"]) or spec.safe_message
errored_result: EvaluationActivityResult = {
"result_type": "boolean",
"verdict": None if allows_na else False,
- "reasoning": result["error"],
+ "reasoning": error_detail,
"allows_na": allows_na,
"skipped": True,
"skip_reason": "hog_error",
+ "terminal_user_error": True,
+ "status_reason": spec.status_reason,
}
if allows_na:
errored_result["applicable"] = False
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 7952b5588af6..9f5a32a516e3 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -11,6 +11,11 @@ from structlog.contextvars import bind_contextvars
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
+from posthog.temporal.ai_observability.evaluation_errors import (
+ require_user_error_spec,
+ terminal_user_error_result,
+ terminal_user_error_result_from_application_error,
+)
from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io, extract_event_tools
from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions
@@ -19,6 +24,7 @@ from posthog.temporal.ai_observability.metrics import (
increment_key_type,
increment_provider_model,
increment_tokens,
+ increment_user_errors,
)
from posthog.temporal.ai_observability.model_resolution import model_spec
@@ -209,7 +215,15 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
return _build_errored_trace_result(allows_na)
team_id = evaluation["team_id"]
- resolved = model_spec(evaluation.get("model_configuration")).resolve(team_id)
+ try:
+ resolved = model_spec(evaluation.get("model_configuration")).resolve(team_id)
+ except ApplicationError as e:
+ terminal_result = terminal_user_error_result_from_application_error(e, allows_na=allows_na)
+ if terminal_result is not None:
+ increment_user_errors(terminal_result["skip_reason"], provider=terminal_result.get("provider"))
+ return terminal_result
+ raise
+
provider = resolved.provider
model = resolved.model
provider_key = resolved.provider_key
@@ -252,45 +266,77 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
)
)
except AuthenticationError:
- increment_errors("auth_error", provider=provider)
if is_byok:
- raise ApplicationError(
- "API key is invalid or has been deleted.",
- {"error_type": "auth_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
+ increment_user_errors("auth_error", provider=provider)
+ return terminal_user_error_result(
+ spec=require_user_error_spec("auth_error", is_byok=True),
+ message="API key is invalid or has been deleted.",
+ allows_na=allows_na,
+ provider=provider,
+ model=model,
+ key_id=key_id,
+ is_byok=True,
)
+ increment_errors("auth_error", provider=provider)
raise
except ModelPermissionError:
- increment_errors("permission_error", provider=provider)
if is_byok:
- raise ApplicationError(
- "API key doesn't have access to this model.",
- {"error_type": "permission_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
+ increment_user_errors("permission_error", provider=provider)
+ return terminal_user_error_result(
+ spec=require_user_error_spec("permission_error", is_byok=True),
+ message="API key doesn't have access to this model.",
+ allows_na=allows_na,
+ provider=provider,
+ model=model,
+ key_id=key_id,
+ is_byok=True,
)
+ increment_errors("permission_error", provider=provider)
raise
except QuotaExceededError:
- increment_errors("quota_error", provider=provider)
if is_byok:
- raise ApplicationError(
- "API key has exceeded its quota.",
- {"error_type": "quota_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
+ increment_user_errors("quota_error", provider=provider)
+ return terminal_user_error_result(
+ spec=require_user_error_spec("quota_error", is_byok=True),
+ message="API key has exceeded its quota.",
+ allows_na=allows_na,
+ provider=provider,
+ model=model,
+ key_id=key_id,
+ is_byok=True,
)
+ increment_errors("quota_error", provider=provider)
raise
except RateLimitError:
- increment_errors("rate_limit", provider=provider)
if is_byok:
- raise ApplicationError(
- "API key is being rate limited.",
- {"error_type": "rate_limit", "key_id": key_id, "provider": provider},
- non_retryable=True,
+ increment_user_errors("rate_limit", provider=provider)
+ return terminal_user_error_result(
+ spec=require_user_error_spec("rate_limit", is_byok=True),
+ message="API key is being rate limited.",
+ allows_na=allows_na,
+ provider=provider,
+ model=model,
+ key_id=key_id,
+ is_byok=True,
)
+ increment_errors("rate_limit", provider=provider)
raise
except ModelNotFoundError:
+ if is_byok:
+ increment_user_errors("model_not_found", provider=provider)
+ return terminal_user_error_result(
+ spec=require_user_error_spec("model_not_found", is_byok=True),
+ message=f"Model '{model}' not found.",
+ allows_na=allows_na,
+ provider=provider,
+ model=model,
+ key_id=key_id,
+ is_byok=True,
+ )
increment_errors("model_not_found", provider=provider)
raise ApplicationError(
f"Model '{model}' not found.",
+ {"error_type": "model_not_found", "provider": provider, "model": model},
non_retryable=True,
)
except StructuredOutputParseError as e:
@@ -312,12 +358,12 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
increment_errors(type(e).__name__, provider=provider)
raise
- result = response.parsed
- if result is None:
+ parsed_result = response.parsed
+ if parsed_result is None:
logger.exception("LLM judge returned empty structured response", evaluation_id=evaluation["id"])
raise ValueError(f"LLM judge returned empty structured response for evaluation {evaluation['id']}")
- assert isinstance(result, BooleanEvalResult | BooleanWithNAEvalResult)
+ assert isinstance(parsed_result, BooleanEvalResult | BooleanWithNAEvalResult)
usage = response.usage
@@ -332,8 +378,8 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
result_dict: EvaluationActivityResult = {
"result_type": "boolean",
- "verdict": result.verdict,
- "reasoning": result.reasoning,
+ "verdict": parsed_result.verdict,
+ "reasoning": parsed_result.reasoning,
"input_tokens": usage.input_tokens if usage else 0,
"output_tokens": usage.output_tokens if usage else 0,
"total_tokens": usage.total_tokens if usage else 0,
@@ -344,11 +390,11 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
"provider": provider,
}
- if allows_na and isinstance(result, BooleanWithNAEvalResult):
- result_dict["applicable"] = result.applicable
- elif isinstance(result, BooleanEvalResult):
+ if allows_na and isinstance(parsed_result, BooleanWithNAEvalResult):
+ result_dict["applicable"] = parsed_result.applicable
+ elif isinstance(parsed_result, BooleanEvalResult):
pass
else:
- raise ValueError(f"Unexpected result type: {type(result)}")
+ raise ValueError(f"Unexpected result type: {type(parsed_result)}")
return result_dict
diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.py
index 88acd60bc4ed..46b37c6c6aa7 100644
--- a/posthog/temporal/ai_observability/evaluation_types.py
+++ b/posthog/temporal/ai_observability/evaluation_types.py
@@ -34,6 +34,9 @@ class EvaluationActivityResult(TypedDict, total=False):
applicable: NotRequired[bool]
skipped: NotRequired[bool]
skip_reason: NotRequired[str]
+ terminal_user_error: NotRequired[bool]
+ status_reason: NotRequired[str | None]
+ provider_key_state: NotRequired[str]
sentiment_label: NotRequired[str]
sentiment_score: NotRequired[float]
sentiment_scores: NotRequired[dict[str, float]]
diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
index d4ad62ce40ad..d57b4c48410f 100644
--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py
+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime
from typing import Any
from django.conf import settings
-from django.db import models
+from django.db import models, transaction
import structlog
import temporalio
@@ -18,7 +18,7 @@ from posthog.temporal.ai_observability.evaluation_types import EvaluationActivit
from posthog.temporal.ai_observability.metrics import increment_emit_event_outcome
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
-from products.ai_observability.backend.models.evaluations import Evaluation
+from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatus
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
logger = structlog.get_logger(__name__)
@@ -126,16 +126,30 @@ async def increment_trial_eval_count_activity(team_id: int) -> int | None:
@temporalio.activity.defn
-async def disable_evaluation_activity(evaluation_id: str, team_id: int, status_reason: str = "") -> None:
- """Transition an evaluation into the ERROR state when the workflow hits a terminal skippable error."""
+async def disable_evaluation_activity(
+ evaluation_id: str, team_id: int, status_reason: str = "", status_reason_detail: str | None = None
+) -> bool:
+ """Transition an evaluation into the ERROR state when the workflow hits a terminal skippable error.
- def _disable() -> None:
+ Returns True only for the first workflow that disables the evaluation. Later in-flight
+ workflows can hit the same terminal error after the first transition, but shouldn't send
+ duplicate disabled notifications or write duplicate activity log rows.
+ """
+
+ def _disable() -> bool:
reason = status_reason or "trial_limit_reached"
- evaluation = Evaluation.objects.filter(id=evaluation_id, team_id=team_id).first()
- if evaluation is not None:
- evaluation.set_status("error", reason)
+ with transaction.atomic():
+ evaluation = Evaluation.objects.select_for_update().filter(id=evaluation_id, team_id=team_id).first()
+ if evaluation is None:
+ return False
+
+ if evaluation.status == EvaluationStatus.ERROR and not evaluation.enabled:
+ return False
+
+ evaluation.set_status("error", reason, status_reason_detail)
+ return True
- await database_sync_to_async(_disable)()
+ return await database_sync_to_async(_disable)()
@dataclass
@@ -228,11 +242,19 @@ class SendEvaluationDisabledEmailInputs:
evaluation_name: str
status_reason: str
human_readable_reason: str
+ disabled_at: datetime | None = None
_STATUS_REASON_SUBJECTS = {
"model_not_allowed": "Your AI observability evaluation was disabled because its model isn't supported on the trial plan",
+ "no_default_model": "Your AI observability evaluation was disabled because no default model is configured",
"provider_key_deleted": "Your AI observability evaluation was disabled because its provider API key was removed",
+ "provider_key_invalid": "Your AI observability evaluation was disabled because its provider API key is invalid",
+ "provider_key_permission_denied": "Your AI observability evaluation was disabled because its provider API key lacks model access",
+ "provider_key_quota_exceeded": "Your AI observability evaluation was disabled because its provider API key quota was exceeded",
+ "provider_key_rate_limited": "Your AI observability evaluation was disabled because its provider API key is being rate limited",
+ "model_not_found": "Your AI observability evaluation was disabled because its model was not found",
+ "hog_error": "Your AI observability evaluation was disabled because its Hog code failed",
}
@@ -260,6 +282,8 @@ async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabled
settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"
evaluation_url = f"/project/{team.pk}/ai-evals/evaluations/{inputs.evaluation_id}"
campaign_key = f"llm_analytics_eval_disabled_{inputs.evaluation_id}_{inputs.status_reason}"
+ if inputs.disabled_at is not None:
+ campaign_key = f"{campaign_key}_{int(inputs.disabled_at.timestamp() * 1_000_000)}"
subject = _STATUS_REASON_SUBJECTS.get(
inputs.status_reason, f'Your evaluation "{inputs.evaluation_name}" has been disabled'
)
diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.py
index 29b0bf46151d..1d1c26092fed 100644
--- a/posthog/temporal/ai_observability/metrics.py
+++ b/posthog/temporal/ai_observability/metrics.py
@@ -92,6 +92,18 @@ def increment_errors(error_type: str, *, provider: str | None = None) -> None:
counter.add(1)
+def increment_user_errors(error_type: str, *, provider: str | None = None) -> None:
+ """Track terminal user-actionable eval errors separately from system failures."""
+ if not activity.in_activity() and not workflow.in_workflow():
+ return
+ attrs: dict[str, str | int | float | bool] = {"error_type": error_type}
+ if provider is not None:
+ attrs["provider"] = provider
+ meter = get_metric_meter(attrs)
+ counter = meter.create_counter("llma_eval_user_errors", "Terminal user-actionable evaluation errors")
+ counter.add(1)
+
+
def increment_eval_signal_outcome(outcome: str) -> None:
"""Track eval signal activity outcomes (skipped_config_disabled, skipped_org_not_approved, skipped_low_significance, emitted, summarization_failed)."""
meter = get_metric_meter({"outcome": outcome})
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index a4e99aa814e0..04bc53307c92 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -1,6 +1,6 @@
import json
from datetime import timedelta
-from typing import NotRequired, Required, TypedDict
+from typing import Any, NotRequired, Required, TypedDict
from django.conf import settings
@@ -8,6 +8,13 @@ import temporalio
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import ApplicationError
+from posthog.temporal.ai_observability.evaluation_errors import (
+ application_error_details,
+ get_evaluation_error_spec,
+ is_terminal_user_error_result,
+ status_reason_detail_for_terminal_user_error,
+ terminal_user_error_result_from_application_error,
+)
from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io, extract_event_tools
from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_activity, run_hog_eval
from posthog.temporal.ai_observability.evaluation_llm_judge import (
@@ -137,65 +144,20 @@ class RunEvaluationWorkflow(PostHogWorkflow):
)
except temporalio.exceptions.ActivityError as e:
if isinstance(e.cause, ApplicationError) and e.cause.details:
- details = e.cause.details[0]
+ details = application_error_details(e.cause)
error_type = details.get("error_type")
+ legacy_terminal_result = terminal_user_error_result_from_application_error(
+ e.cause,
+ allows_na=(evaluation.get("output_config") or {}).get("allows_na", False),
+ )
+ if legacy_terminal_result is not None:
+ return await self._handle_terminal_user_error_result(
+ evaluation=evaluation,
+ evaluation_type=evaluation_type,
+ result=legacy_terminal_result,
+ )
- if error_type in (
- "trial_limit_reached",
- "key_invalid",
- "parse_error",
- "model_not_allowed",
- "no_default_model",
- ):
- if error_type in ("trial_limit_reached", "model_not_allowed", "no_default_model"):
- await temporalio.workflow.execute_activity(
- disable_evaluation_activity,
- args=[evaluation["id"], evaluation["team_id"], error_type],
- schedule_to_close_timeout=timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
- if error_type == "trial_limit_reached":
- if temporalio.workflow.patched("trial-usage-email"):
- try:
- await temporalio.workflow.execute_activity(
- send_trial_usage_email_activity,
- SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=100),
- activity_id=f"send-trial-usage-email-100pct-{evaluation['team_id']}",
- schedule_to_close_timeout=timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
- except Exception:
- temporalio.workflow.logger.exception(
- "Failed to send trial exhausted email",
- team_id=evaluation["team_id"],
- )
- elif error_type == "model_not_allowed":
- if temporalio.workflow.patched("eval-disabled-email"):
- model = details.get("model", "the selected model")
- try:
- await temporalio.workflow.execute_activity(
- send_evaluation_disabled_email_activity,
- SendEvaluationDisabledEmailInputs(
- team_id=evaluation["team_id"],
- evaluation_id=evaluation["id"],
- evaluation_name=evaluation.get("name", "Unknown evaluation"),
- status_reason="model_not_allowed",
- human_readable_reason=(
- f"The model '{model}' isn't available on the trial plan."
- ),
- ),
- activity_id=(
- f"send-eval-disabled-email-{evaluation['id']}-model_not_allowed"
- ),
- schedule_to_close_timeout=timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
- except Exception:
- temporalio.workflow.logger.exception(
- "Failed to send evaluation disabled email",
- evaluation_id=evaluation["id"],
- team_id=evaluation["team_id"],
- )
+ if error_type in ("parse_error",):
skip_result: WorkflowResult = {
"verdict": None,
"skipped": True,
@@ -249,6 +211,13 @@ class RunEvaluationWorkflow(PostHogWorkflow):
non_retryable=True,
)
+ if is_terminal_user_error_result(result):
+ return await self._handle_terminal_user_error_result(
+ evaluation=evaluation,
+ evaluation_type=evaluation_type,
+ result=result,
+ )
+
try:
await temporalio.workflow.execute_activity(
emit_evaluation_event_activity,
@@ -341,3 +310,103 @@ class RunEvaluationWorkflow(PostHogWorkflow):
if skip_reason is not None:
workflow_result["skip_reason"] = skip_reason
return workflow_result
+
+ async def _handle_terminal_user_error_result(
+ self,
+ *,
+ evaluation: dict[str, Any],
+ evaluation_type: str,
+ result: EvaluationActivityResult,
+ ) -> WorkflowResult:
+ skip_reason = result.get("skip_reason", "terminal_user_error")
+ spec = get_evaluation_error_spec(
+ str(skip_reason) if skip_reason else None,
+ is_byok=bool(result.get("is_byok", False)),
+ )
+ status_reason = result.get("status_reason")
+ disabled_evaluation = False
+ if status_reason:
+ reasoning = result.get("reasoning")
+ status_reason_detail = (
+ status_reason_detail_for_terminal_user_error(
+ spec,
+ reasoning if isinstance(reasoning, str) else None,
+ )
+ if spec
+ else None
+ )
+ disabled_evaluation = await temporalio.workflow.execute_activity(
+ disable_evaluation_activity,
+ args=[evaluation["id"], evaluation["team_id"], status_reason, status_reason_detail],
+ schedule_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ key_id = result.get("key_id")
+ provider_key_state = result.get("provider_key_state")
+ if key_id and provider_key_state:
+ await temporalio.workflow.execute_activity(
+ update_key_state_activity,
+ args=[str(key_id), provider_key_state, result["reasoning"]],
+ schedule_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ if spec and spec.send_trial_usage_email and temporalio.workflow.patched("trial-usage-email"):
+ try:
+ await temporalio.workflow.execute_activity(
+ send_trial_usage_email_activity,
+ SendTrialUsageEmailInputs(team_id=evaluation["team_id"], threshold_pct=100),
+ activity_id=f"send-trial-usage-email-100pct-{evaluation['team_id']}",
+ schedule_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except Exception:
+ temporalio.workflow.logger.exception(
+ "Failed to send trial exhausted email",
+ team_id=evaluation["team_id"],
+ )
+
+ dedupe_disabled_email = temporalio.workflow.patched("eval-disabled-email-on-disable-transition")
+ should_send_disabled_email = (
+ spec is not None
+ and spec.disables_evaluation
+ and bool(status_reason)
+ and (disabled_evaluation or not dedupe_disabled_email)
+ and not spec.send_trial_usage_email
+ and temporalio.workflow.patched("eval-disabled-email")
+ )
+ if should_send_disabled_email:
+ assert spec is not None
+ email_status_reason = str(status_reason)
+ try:
+ await temporalio.workflow.execute_activity(
+ send_evaluation_disabled_email_activity,
+ SendEvaluationDisabledEmailInputs(
+ team_id=evaluation["team_id"],
+ evaluation_id=evaluation["id"],
+ evaluation_name=evaluation.get("name", "Unknown evaluation"),
+ status_reason=email_status_reason,
+ human_readable_reason=spec.safe_message,
+ disabled_at=temporalio.workflow.now(),
+ ),
+ activity_id=f"send-eval-disabled-email-{evaluation['id']}-{email_status_reason}",
+ schedule_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except Exception:
+ temporalio.workflow.logger.exception(
+ "Failed to send evaluation disabled email",
+ evaluation_id=evaluation["id"],
+ team_id=evaluation["team_id"],
+ )
+
+ workflow_result: WorkflowResult = {
+ "verdict": None,
+ "skipped": True,
+ "skip_reason": skip_reason,
+ "message": result["reasoning"],
+ "evaluation_id": evaluation["id"],
+ "evaluation_type": evaluation_type,
+ }
+ return workflow_result
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 4b5742709a98..c12e3d9fe0ce 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -1,6 +1,6 @@
import json
import uuid
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -8,17 +8,34 @@ from unittest.mock import MagicMock, patch
from asgiref.sync import sync_to_async
from parameterized import parameterized
+from temporalio import activity
from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.models import Organization, Team
from posthog.temporal.ai_observability.sentiment.extraction import truncate_to_head_tail
from posthog.temporal.ai_observability.sentiment.schema import SentimentResult
-from products.ai_observability.backend.llm.errors import StructuredOutputParseError
+from products.ai_observability.backend.llm.errors import (
+ AuthenticationError,
+ ModelNotFoundError,
+ ModelPermissionError,
+ QuotaExceededError,
+ RateLimitError,
+ StructuredOutputParseError,
+)
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.model_configuration import LLMModelConfiguration
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+from .evaluation_errors import (
+ MAX_STATUS_REASON_DETAIL_LENGTH,
+ require_user_error_spec,
+ status_reason_detail_for_terminal_user_error,
+ terminal_user_error_result_from_application_error,
+)
from .run_evaluation import (
BooleanEvalResult,
BooleanWithNAEvalResult,
@@ -29,6 +46,7 @@ from .run_evaluation import (
RunEvaluationWorkflow,
SendEvaluationDisabledEmailInputs,
SendTrialUsageEmailInputs,
+ WorkflowResult,
disable_evaluation_activity,
emit_evaluation_event_activity,
execute_hog_eval_activity,
@@ -43,6 +61,42 @@ from .run_evaluation import (
)
+def test_status_reason_detail_for_terminal_user_error_only_keeps_truncated_hog_errors():
+ hog_spec = require_user_error_spec("hog_error")
+ permission_spec = require_user_error_spec("permission_error")
+ long_message = "x" * (MAX_STATUS_REASON_DETAIL_LENGTH + 10)
+
+ assert status_reason_detail_for_terminal_user_error(permission_spec, "provider denied") is None
+ assert status_reason_detail_for_terminal_user_error(hog_spec, long_message) == (
+ f"{long_message[: MAX_STATUS_REASON_DETAIL_LENGTH - 3]}..."
+ )
+
+
+def test_terminal_user_error_result_from_application_error_uses_key_details_for_byok_model_not_found():
+ result = terminal_user_error_result_from_application_error(
+ ApplicationError(
+ "Model 'missing-model' not found.",
+ {
+ "error_type": "model_not_found",
+ "key_id": "key-123",
+ "provider": "openai",
+ "model": "missing-model",
+ },
+ non_retryable=True,
+ ),
+ allows_na=False,
+ )
+
+ assert result is not None
+ assert result["terminal_user_error"] is True
+ assert result["skip_reason"] == "model_not_found"
+ assert result["status_reason"] == "model_not_found"
+ assert result["is_byok"] is True
+ assert result["key_id"] == "key-123"
+ assert result["provider"] == "openai"
+ assert result["model"] == "missing-model"
+
+
def create_mock_event_data(team_id: int, **overrides: Any) -> dict[str, Any]:
"""Helper to create mock event data for tests"""
defaults = {
@@ -338,6 +392,175 @@ class TestRunEvaluationWorkflow:
assert parsed.evaluation_id == "eval-123"
assert parsed.event_data == event_data
+ @pytest.mark.asyncio
+ async def test_terminal_user_error_disables_emails_without_emitting_evaluation_event(self):
+ calls: list[str] = []
+
+ @activity.defn(name="fetch_evaluation_activity")
+ async def mock_fetch_evaluation(inputs: RunEvaluationInputs) -> dict[str, Any]:
+ calls.append("fetch")
+ return {
+ "id": inputs.evaluation_id,
+ "name": "Hog eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": 1,
+ }
+
+ @activity.defn(name="execute_hog_eval_activity")
+ async def mock_execute_hog_eval(
+ evaluation: dict[str, Any], event_data: dict[str, Any]
+ ) -> EvaluationActivityResult:
+ calls.append("execute_hog")
+ return {
+ "result_type": "boolean",
+ "verdict": False,
+ "reasoning": "Must return boolean, got int: 42",
+ "allows_na": False,
+ "skipped": True,
+ "skip_reason": "hog_error",
+ "terminal_user_error": True,
+ "status_reason": "hog_error",
+ }
+
+ @activity.defn(name="disable_evaluation_activity")
+ async def mock_disable_evaluation(
+ evaluation_id: str, team_id: int, reason: str, reason_detail: str | None = None
+ ) -> bool:
+ calls.append(f"disable:{evaluation_id}:{team_id}:{reason}:{reason_detail}")
+ return True
+
+ @activity.defn(name="send_evaluation_disabled_email_activity")
+ async def mock_send_evaluation_disabled_email(inputs: SendEvaluationDisabledEmailInputs) -> None:
+ calls.append(f"email:{inputs.evaluation_id}:{inputs.status_reason}:{inputs.human_readable_reason}")
+
+ @activity.defn(name="emit_evaluation_event_activity")
+ async def mock_emit_evaluation_event(inputs: EmitEvaluationEventInputs) -> None:
+ calls.append("emit")
+ raise AssertionError("terminal user errors must not emit $ai_evaluation")
+
+ task_queue = str(uuid.uuid4())
+ evaluation_id = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RunEvaluationWorkflow],
+ activities=[
+ mock_fetch_evaluation,
+ mock_execute_hog_eval,
+ mock_disable_evaluation,
+ mock_send_evaluation_disabled_email,
+ mock_emit_evaluation_event,
+ ],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result: WorkflowResult = await env.client.execute_workflow(
+ RunEvaluationWorkflow.run,
+ RunEvaluationInputs(
+ evaluation_id=evaluation_id,
+ event_data=create_mock_event_data(team_id=1),
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ assert calls == [
+ "fetch",
+ "execute_hog",
+ f"disable:{evaluation_id}:1:hog_error:Must return boolean, got int: 42",
+ (
+ f"email:{evaluation_id}:hog_error:"
+ "The Hog evaluation code failed. Fix the code before re-enabling this evaluation."
+ ),
+ ]
+ assert result["evaluation_id"] == evaluation_id
+ assert result["evaluation_type"] == "hog"
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "hog_error"
+ assert result["message"] == "Must return boolean, got int: 42"
+
+ @pytest.mark.asyncio
+ async def test_terminal_user_error_does_not_email_when_evaluation_was_already_disabled(self):
+ calls: list[str] = []
+
+ @activity.defn(name="fetch_evaluation_activity")
+ async def mock_fetch_evaluation(inputs: RunEvaluationInputs) -> dict[str, Any]:
+ calls.append("fetch")
+ return {
+ "id": inputs.evaluation_id,
+ "name": "Hog eval",
+ "evaluation_type": "hog",
+ "evaluation_config": {},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": 1,
+ }
+
+ @activity.defn(name="execute_hog_eval_activity")
+ async def mock_execute_hog_eval(
+ evaluation: dict[str, Any], event_data: dict[str, Any]
+ ) -> EvaluationActivityResult:
+ calls.append("execute_hog")
+ return {
+ "result_type": "boolean",
+ "verdict": False,
+ "reasoning": "Must return boolean, got int: 42",
+ "allows_na": False,
+ "skipped": True,
+ "skip_reason": "hog_error",
+ "terminal_user_error": True,
+ "status_reason": "hog_error",
+ }
+
+ @activity.defn(name="disable_evaluation_activity")
+ async def mock_disable_evaluation(
+ evaluation_id: str, team_id: int, reason: str, reason_detail: str | None = None
+ ) -> bool:
+ calls.append(f"disable:{evaluation_id}:{team_id}:{reason}:{reason_detail}")
+ return False
+
+ @activity.defn(name="send_evaluation_disabled_email_activity")
+ async def mock_send_evaluation_disabled_email(inputs: SendEvaluationDisabledEmailInputs) -> None:
+ calls.append("email")
+ raise AssertionError("already-disabled terminal errors must not send another email")
+
+ task_queue = str(uuid.uuid4())
+ evaluation_id = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[RunEvaluationWorkflow],
+ activities=[
+ mock_fetch_evaluation,
+ mock_execute_hog_eval,
+ mock_disable_evaluation,
+ mock_send_evaluation_disabled_email,
+ ],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result: WorkflowResult = await env.client.execute_workflow(
+ RunEvaluationWorkflow.run,
+ RunEvaluationInputs(
+ evaluation_id=evaluation_id,
+ event_data=create_mock_event_data(team_id=1),
+ ),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ assert calls == [
+ "fetch",
+ "execute_hog",
+ f"disable:{evaluation_id}:1:hog_error:Must return boolean, got int: 42",
+ ]
+ assert result["evaluation_id"] == evaluation_id
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "hog_error"
+
@pytest.mark.django_db(transaction=True)
def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data):
"""Test LLM judge execution with allows_na=True when applicable"""
@@ -664,12 +887,16 @@ class TestRunEvaluationWorkflow:
assert evaluation.enabled
- await disable_evaluation_activity(str(evaluation.id), team.id, "trial_limit_reached")
+ disabled = await disable_evaluation_activity(
+ str(evaluation.id), team.id, "hog_error", "Must return boolean, got int: 42"
+ )
await sync_to_async(evaluation.refresh_from_db)()
+ assert disabled is True
assert not evaluation.enabled
assert evaluation.status == "error"
- assert evaluation.status_reason == "trial_limit_reached"
+ assert evaluation.status_reason == "hog_error"
+ assert evaluation.status_reason_detail == "Must return boolean, got int: 42"
logs = await sync_to_async(
lambda: list(ActivityLog.objects.filter(scope="Evaluation", item_id=str(evaluation.id), activity="updated"))
@@ -680,9 +907,22 @@ class TestRunEvaluationWorkflow:
fields = {c["field"]: c for c in detail["changes"]}
assert fields["status"]["before"] == "active"
assert fields["status"]["after"] == "error"
- assert fields["status_reason"]["after"] == "trial_limit_reached"
+ assert fields["status_reason"]["after"] == "hog_error"
+ assert fields["status_reason_detail"]["after"] == "Must return boolean, got int: 42"
assert logs[0].is_system is True
+ disabled_again = await disable_evaluation_activity(
+ str(evaluation.id), team.id, "hog_error", "Must return boolean, got int: 42"
+ )
+
+ logs_after_retry = await sync_to_async(
+ lambda: ActivityLog.objects.filter(
+ scope="Evaluation", item_id=str(evaluation.id), activity="updated"
+ ).count()
+ )()
+ assert disabled_again is False
+ assert logs_after_retry == 1
+
@pytest.mark.django_db(transaction=True)
def test_successful_execution_does_not_disable_evaluation(self, setup_data):
evaluation = setup_data["evaluation"]
@@ -816,11 +1056,122 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id)
- with pytest.raises(ApplicationError, match="not available on the trial plan") as exc_info:
- execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_user_errors") as mock_user_errors,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_errors,
+ ):
+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
- assert exc_info.value.non_retryable is True
- assert exc_info.value.details[0]["error_type"] == "model_not_allowed"
+ mock_client_class.assert_not_called()
+ mock_user_errors.assert_called_once_with("model_not_allowed", provider=None)
+ mock_errors.assert_not_called()
+ assert result["terminal_user_error"] is True
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "model_not_allowed"
+ assert result["status_reason"] == "model_not_allowed"
+ assert result["verdict"] is None
+
+ @pytest.mark.parametrize(
+ "raised_exception, skip_reason, status_reason, provider_key_state",
+ [
+ pytest.param(
+ AuthenticationError(),
+ "auth_error",
+ "provider_key_invalid",
+ LLMProviderKey.State.INVALID,
+ id="auth_error",
+ ),
+ pytest.param(
+ ModelPermissionError("gpt-5.4"),
+ "permission_error",
+ "provider_key_permission_denied",
+ LLMProviderKey.State.ERROR,
+ id="permission_error",
+ ),
+ pytest.param(
+ QuotaExceededError(),
+ "quota_error",
+ "provider_key_quota_exceeded",
+ LLMProviderKey.State.ERROR,
+ id="quota_error",
+ ),
+ pytest.param(
+ RateLimitError(),
+ "rate_limit",
+ "provider_key_rate_limited",
+ LLMProviderKey.State.ERROR,
+ id="rate_limit",
+ ),
+ pytest.param(
+ ModelNotFoundError("gpt-5.4"),
+ "model_not_found",
+ "model_not_found",
+ None,
+ id="model_not_found",
+ ),
+ ],
+ )
+ @pytest.mark.django_db(transaction=True)
+ def test_execute_llm_judge_activity_byok_provider_user_errors_return_terminal_result(
+ self,
+ raised_exception: Exception,
+ skip_reason: str,
+ status_reason: str,
+ provider_key_state: str | None,
+ setup_data,
+ ):
+ team = setup_data["team"]
+ provider_key = LLMProviderKey.objects.create(
+ team=team,
+ provider="openai",
+ name="OpenAI",
+ state=LLMProviderKey.State.OK,
+ encrypted_config={"api_key": "sk-test"},
+ )
+
+ evaluation = {
+ "id": str(setup_data["evaluation"].id),
+ "name": "Test Evaluation",
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Is this accurate?"},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": team.id,
+ "model_configuration": {
+ "provider": "openai",
+ "model": "gpt-5.4",
+ "provider_key_id": str(provider_key.id),
+ },
+ }
+ event_data = create_mock_event_data(team.id)
+
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_user_errors") as mock_user_errors,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_errors,
+ ):
+ mock_client = MagicMock()
+ mock_client_class.return_value = mock_client
+ mock_client.complete.side_effect = raised_exception
+
+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+
+ mock_client.complete.assert_called_once()
+ mock_user_errors.assert_called_once_with(skip_reason, provider="openai")
+ mock_errors.assert_not_called()
+ assert result["terminal_user_error"] is True
+ assert result["skipped"] is True
+ assert result["skip_reason"] == skip_reason
+ assert result["status_reason"] == status_reason
+ assert result["is_byok"] is True
+ assert result["key_id"] == str(provider_key.id)
+ assert result["provider"] == "openai"
+ assert result["model"] == "gpt-5.4"
+ if provider_key_state is None:
+ assert "provider_key_state" not in result
+ else:
+ assert result["provider_key_state"] == provider_key_state
class TestExecuteHogEvalActivity:
@@ -902,6 +1253,8 @@ class TestExecuteHogEvalActivity:
assert result["skipped"] is True
assert result["skip_reason"] == "hog_error"
+ assert result["terminal_user_error"] is True
+ assert result["status_reason"] == "hog_error"
assert "Must return boolean" in result["reasoning"]
@pytest.mark.asyncio
@@ -1029,6 +1382,8 @@ class TestExecuteHogEvalActivity:
assert result["skipped"] is True
assert result["skip_reason"] == "hog_error"
+ assert result["terminal_user_error"] is True
+ assert result["status_reason"] == "hog_error"
assert "Global variable not found" in result["reasoning"]
@pytest.mark.asyncio
@@ -1332,6 +1687,8 @@ class TestExecuteHogEvalActivityAllowsNA:
assert result["skipped"] is True
assert result["skip_reason"] == "hog_error"
+ assert result["terminal_user_error"] is True
+ assert result["status_reason"] == "hog_error"
assert result["verdict"] is False
assert "Must return boolean" in result["reasoning"]
@@ -1528,6 +1885,7 @@ class TestSendEvaluationDisabledEmailActivity:
evaluation_name="My Eval",
status_reason="model_not_allowed",
human_readable_reason="The model 'gpt-9' isn't available on the trial plan.",
+ disabled_at=datetime(2026, 6, 25, 12, 0, 0, tzinfo=UTC),
)
)
@@ -1538,6 +1896,8 @@ class TestSendEvaluationDisabledEmailActivity:
assert "isn't available on the trial plan" in call_kwargs["template_context"]["disabled_reason"]
# Campaign key must include the reason so a later different-reason error triggers a fresh email.
assert "model_not_allowed" in call_kwargs["campaign_key"]
+ # It also includes the disable timestamp so a later same-reason disable sends a fresh email.
+ assert "1782388800000000" in call_kwargs["campaign_key"]
mock_message.send.assert_called_once()
@pytest.mark.asyncio
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index bbd1c5430389..1395d197e764 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -36,7 +36,7 @@ from ..models.evaluation_configs import (
validate_evaluation_configs,
)
from ..models.evaluation_reports import EvaluationReport
-from ..models.evaluations import Evaluation
+from ..models.evaluations import Evaluation, EvaluationStatusReason
from ..models.model_configuration import LLMModelConfiguration
from ..models.provider_keys import LLMProvider, LLMProviderKey
from .metrics import llma_track_latency
@@ -44,6 +44,15 @@ from .metrics import llma_track_latency
logger = structlog.get_logger(__name__)
+PROVIDER_KEY_ERROR_STATUS_REASONS = {
+ EvaluationStatusReason.PROVIDER_KEY_DELETED,
+ EvaluationStatusReason.PROVIDER_KEY_INVALID,
+ EvaluationStatusReason.PROVIDER_KEY_PERMISSION_DENIED,
+ EvaluationStatusReason.PROVIDER_KEY_QUOTA_EXCEEDED,
+ EvaluationStatusReason.PROVIDER_KEY_RATE_LIMITED,
+}
+
+
@extend_schema_field(
{
"oneOf": [
@@ -156,6 +165,14 @@ class EvaluationConditionSerializer(serializers.Serializer):
class EvaluationSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
model_configuration = ModelConfigurationSerializer(required=False, allow_null=True)
+ status_reason_detail = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Additional detail for the current system-disabled status. This is only populated when the detail is "
+ "safe to show in the evaluation UI."
+ ),
+ )
evaluation_config = _EvaluationConfigField(
required=False,
help_text=(
@@ -186,6 +203,7 @@ class EvaluationSerializer(serializers.ModelSerializer):
"enabled",
"status",
"status_reason",
+ "status_reason_detail",
"evaluation_type",
"evaluation_config",
"output_type",
@@ -198,8 +216,16 @@ class EvaluationSerializer(serializers.ModelSerializer):
"deleted",
]
# status / status_reason are server-managed (coerced from enabled on user writes, set directly by
- # system transitions). Clients toggle `enabled`; the model's save() keeps the trio consistent.
- read_only_fields = ["id", "status", "status_reason", "created_at", "updated_at", "created_by"]
+ # system transitions). Clients toggle `enabled`; the model's save() keeps the status fields consistent.
+ read_only_fields = [
+ "id",
+ "status",
+ "status_reason",
+ "status_reason_detail",
+ "created_at",
+ "updated_at",
+ "created_by",
+ ]
extra_kwargs = {
"name": {"help_text": "Name of the evaluation."},
"description": {"help_text": "Optional description of what this evaluation checks."},
@@ -297,7 +323,9 @@ class EvaluationSerializer(serializers.ModelSerializer):
)
def _validate_re_enable(self, data: dict) -> None:
- has_byok = self._has_byok_key(data)
+ provider_key = self._effective_provider_key(data)
+ has_byok = provider_key is not None
+ has_usable_byok = provider_key is not None and provider_key.state == LLMProviderKey.State.OK
status_reason = getattr(self.instance, "status_reason", None)
evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)
# Non-model evals never call an LLM provider, consume trial quota, or need a BYOK key.
@@ -306,18 +334,23 @@ class EvaluationSerializer(serializers.ModelSerializer):
if not evaluation_uses_model_configuration(evaluation_type):
return
+ if has_byok and not has_usable_byok:
+ raise serializers.ValidationError(
+ {"enabled": "Attach a working provider API key before re-enabling this evaluation."}
+ )
+
# Trial limit: can only re-enable if they've attached a BYOK key (which bypasses trial quota).
if status_reason == "trial_limit_reached" or not status_reason:
team = self.context["get_team"]()
config = EvaluationConfig.objects.filter(team=team).first()
- if config and config.trial_limit_reached and not has_byok:
+ if config and config.trial_limit_reached and not has_usable_byok:
raise serializers.ValidationError(
{"enabled": "Trial evaluation limit reached. Add a provider API key to re-enable this evaluation."}
)
# Model-not-allowed: the eval's current model must now be on the trial allowlist, or they
# must have attached a BYOK key (BYOK bypasses the allowlist entirely).
- if status_reason == "model_not_allowed" and not has_byok:
+ if status_reason == "model_not_allowed" and not has_usable_byok:
from products.ai_observability.backend.llm import TRIAL_MODEL_IDS
model_config_data = data.get("model_configuration")
@@ -337,35 +370,45 @@ class EvaluationSerializer(serializers.ModelSerializer):
}
)
- # Provider key deleted: the eval must now point at a real provider key.
- if status_reason == "provider_key_deleted" and not has_byok:
+ # Provider key failures: the eval must now point at a usable provider key.
+ if status_reason in PROVIDER_KEY_ERROR_STATUS_REASONS:
+ if not has_usable_byok:
+ raise serializers.ValidationError(
+ {"enabled": "Attach a working provider API key before re-enabling this evaluation."}
+ )
+
+ if status_reason == "model_not_found" and not self._has_model_configuration_after_update(data):
raise serializers.ValidationError(
- {
- "enabled": "The provider API key for this evaluation was deleted. Attach a provider API key before re-enabling."
- }
+ {"enabled": "Choose an available model before re-enabling this evaluation."}
)
# No default model: the team's active key is for a provider we have no default model for, and
# the eval left its model unset. Require an explicit model so it can't immediately re-disable.
if status_reason == "no_default_model":
- has_model_configuration = bool(data.get("model_configuration")) or bool(
- self.instance and self.instance.model_configuration_id
- )
- if not has_model_configuration:
+ if not self._has_model_configuration_after_update(data):
raise serializers.ValidationError(
{
"enabled": "This evaluation's provider has no default model. Set a model on the evaluation before re-enabling."
}
)
- def _has_byok_key(self, data: dict) -> bool:
- """Check if the evaluation will have a BYOK key after this update."""
+ def _has_model_configuration_after_update(self, data: dict) -> bool:
+ return bool(data.get("model_configuration")) or bool(self.instance and self.instance.model_configuration_id)
+
+ def _effective_provider_key(self, data: dict) -> LLMProviderKey | None:
+ """Return the provider key the evaluation will use after this update."""
model_config_data = data.get("model_configuration")
if model_config_data is not None:
- return bool(model_config_data.get("provider_key_id"))
+ provider_key_id = model_config_data.get("provider_key_id")
+ if not provider_key_id:
+ return None
+ return LLMProviderKey.objects.filter(
+ id=provider_key_id,
+ team=self.context["get_team"](),
+ ).first()
if self.instance and self.instance.model_configuration:
- return self.instance.model_configuration.provider_key_id is not None
- return False
+ return self.instance.model_configuration.provider_key
+ return None
def _create_or_update_model_configuration(
self, model_config_data: dict[str, Any] | None, team_id: int
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 631f3abb3f21..37427b045a5f 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -856,6 +856,43 @@ class TestEnableBlockingWhenTrialExhausted(APIBaseTest):
eval_obj.refresh_from_db()
self.assertTrue(eval_obj.enabled)
+ def test_rejects_enabling_trial_eval_with_unusable_byok_key_when_limit_reached(self):
+ EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openai",
+ name="Key",
+ state=LLMProviderKey.State.INVALID,
+ encrypted_config={"api_key": "sk-test"},
+ created_by=self.user,
+ )
+ mc = LLMModelConfiguration.objects.create(
+ team=self.team,
+ provider="openai",
+ model="gpt-5-mini",
+ provider_key=key,
+ )
+ eval_obj = Evaluation.objects.create(
+ team=self.team,
+ name="Invalid BYOK Eval",
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "test"},
+ output_type="boolean",
+ model_configuration=mc,
+ enabled=False,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"enabled": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("working provider API key", str(response.data))
+ eval_obj.refresh_from_db()
+ self.assertFalse(eval_obj.enabled)
+
class TestReEnableValidatesRootCauseResolved(APIBaseTest):
"""When an eval is in the error state, flipping enabled=True must fail unless the condition
@@ -911,8 +948,39 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):
self.assertEqual(eval_obj.status, "active")
self.assertIsNone(eval_obj.status_reason)
- def test_rejects_re_enable_when_provider_key_still_missing(self):
- eval_obj = self._create_errored_eval(status_reason="provider_key_deleted")
+ def test_rejects_re_enable_when_model_not_allowed_with_unusable_byok_key(self):
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openai",
+ name="Key",
+ state=LLMProviderKey.State.INVALID,
+ encrypted_config={"api_key": "sk-test"},
+ created_by=self.user,
+ )
+ eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9", provider_key=key)
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"enabled": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("working provider API key", str(response.data))
+ eval_obj.refresh_from_db()
+ self.assertFalse(eval_obj.enabled)
+
+ @parameterized.expand(
+ [
+ ("provider_key_deleted",),
+ ("provider_key_invalid",),
+ ("provider_key_permission_denied",),
+ ("provider_key_quota_exceeded",),
+ ("provider_key_rate_limited",),
+ ]
+ )
+ def test_rejects_re_enable_when_provider_key_still_missing(self, status_reason):
+ eval_obj = self._create_errored_eval(status_reason=status_reason)
response = self.client.patch(
f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
@@ -922,6 +990,69 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("provider API key", str(response.data))
+ @parameterized.expand(
+ [
+ ("provider_key_invalid", LLMProviderKey.State.INVALID),
+ ("provider_key_permission_denied", LLMProviderKey.State.ERROR),
+ ("provider_key_quota_exceeded", LLMProviderKey.State.ERROR),
+ ("provider_key_rate_limited", LLMProviderKey.State.ERROR),
+ ]
+ )
+ def test_rejects_re_enable_when_provider_key_is_still_not_usable(self, status_reason, key_state):
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openai",
+ name="Key",
+ state=key_state,
+ encrypted_config={"api_key": "sk-test"},
+ created_by=self.user,
+ )
+ eval_obj = self._create_errored_eval(status_reason=status_reason, provider_key=key)
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"enabled": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("working provider API key", str(response.data))
+
+ def test_allows_re_enable_when_model_not_found_with_existing_model_config(self):
+ eval_obj = self._create_errored_eval(status_reason="model_not_found")
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {"enabled": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ eval_obj.refresh_from_db()
+ self.assertTrue(eval_obj.enabled)
+ self.assertIsNone(eval_obj.status_reason)
+
+ def test_allows_re_enable_when_model_not_found_with_new_model(self):
+ eval_obj = self._create_errored_eval(status_reason="model_not_found", model="missing-model")
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {
+ "enabled": True,
+ "model_configuration": {
+ "provider": "openai",
+ "model": "gpt-5-mini",
+ "provider_key_id": None,
+ },
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ eval_obj.refresh_from_db()
+ self.assertTrue(eval_obj.enabled)
+ self.assertIsNone(eval_obj.status_reason)
+
def test_allows_re_enable_when_provider_key_attached(self):
key = LLMProviderKey.objects.create(
team=self.team,
diff --git a/products/ai_observability/backend/migrations/0009_alter_evaluation_status_reason.py b/products/ai_observability/backend/migrations/0009_alter_evaluation_status_reason.py
new file mode 100644
index 000000000000..1c96e211413d
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0009_alter_evaluation_status_reason.py
@@ -0,0 +1,42 @@
+# Generated by Django 5.2.14 on 2026-06-25 17:48
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("ai_observability", "0008_alter_evaluation_status_reason")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="status_reason",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("trial_limit_reached", "Trial evaluation limit reached"),
+ ("model_not_allowed", "Model not available on the trial plan"),
+ ("provider_key_deleted", "Provider API key was deleted"),
+ (
+ "no_default_model",
+ "No default model available for the selected provider",
+ ),
+ ("provider_key_invalid", "Provider API key is invalid"),
+ (
+ "provider_key_permission_denied",
+ "Provider API key lacks model access",
+ ),
+ ("provider_key_quota_exceeded", "Provider API key quota exceeded"),
+ ("provider_key_rate_limited", "Provider API key is rate limited"),
+ ("model_not_found", "Model not found"),
+ ("hog_error", "Hog evaluation code failed"),
+ ],
+ max_length=50,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="evaluation",
+ name="status_reason_detail",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index f2d21a21035a..85a6d471fc03 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0008_alter_evaluation_status_reason
+0009_alter_evaluation_status_reason
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index 21433f5af298..b3148a3ce44d 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -34,6 +34,12 @@ class EvaluationStatusReason(models.TextChoices):
MODEL_NOT_ALLOWED = "model_not_allowed", "Model not available on the trial plan"
PROVIDER_KEY_DELETED = "provider_key_deleted", "Provider API key was deleted"
NO_DEFAULT_MODEL = "no_default_model", "No default model available for the selected provider"
+ PROVIDER_KEY_INVALID = "provider_key_invalid", "Provider API key is invalid"
+ PROVIDER_KEY_PERMISSION_DENIED = "provider_key_permission_denied", "Provider API key lacks model access"
+ PROVIDER_KEY_QUOTA_EXCEEDED = "provider_key_quota_exceeded", "Provider API key quota exceeded"
+ PROVIDER_KEY_RATE_LIMITED = "provider_key_rate_limited", "Provider API key is rate limited"
+ MODEL_NOT_FOUND = "model_not_found", "Model not found"
+ HOG_ERROR = "hog_error", "Hog evaluation code failed"
class Evaluation(ModelActivityMixin, UUIDTModel):
@@ -56,6 +62,7 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
enabled = models.BooleanField(default=False)
status = models.CharField(max_length=20, choices=EvaluationStatus, default=EvaluationStatus.PAUSED)
status_reason = models.CharField(max_length=50, choices=EvaluationStatusReason, null=True, blank=True)
+ status_reason_detail = models.TextField(null=True, blank=True)
evaluation_type = models.CharField(max_length=50, choices=EvaluationType)
evaluation_config = models.JSONField(default=dict)
@@ -114,8 +121,8 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
`status` directly take effect even when `enabled` is stale in memory.
Post-reconciliation invariants are always enforced:
- - ACTIVE → enabled=True, status_reason=None
- - PAUSED → enabled=False, status_reason=None
+ - ACTIVE → enabled=True, status_reason/detail=None
+ - PAUSED → enabled=False, status_reason/detail=None
- ERROR → enabled=False, status_reason required (raises otherwise)
"""
# UUIDTModel assigns pk in __init__, so we can't use `self.pk is None` to detect new rows.
@@ -136,24 +143,30 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
if self.status == EvaluationStatus.ACTIVE:
self.enabled = True
self.status_reason = None
+ self.status_reason_detail = None
elif self.status == EvaluationStatus.PAUSED:
self.enabled = False
self.status_reason = None
+ self.status_reason_detail = None
elif self.status == EvaluationStatus.ERROR:
self.enabled = False
if not self.status_reason:
raise ValidationError({"status_reason": "status_reason is required when status is ERROR"})
def set_status(
- self, status: "EvaluationStatus | str", reason: "EvaluationStatusReason | str | None" = None
+ self,
+ status: "EvaluationStatus | str",
+ reason: "EvaluationStatusReason | str | None" = None,
+ reason_detail: str | None = None,
) -> None:
"""Transition helper. Prefer this (or .save()) over .update() so invariants stay enforced.
- Callers using QuerySet.update() bypass save() — they must write all three fields together.
+ Callers using QuerySet.update() bypass save() — they must write the status fields together.
"""
self.status = EvaluationStatus(status)
self.status_reason = EvaluationStatusReason(reason) if reason else None
- self.save(update_fields=["status", "status_reason", "enabled", "updated_at"])
+ self.status_reason_detail = reason_detail
+ self.save(update_fields=["status", "status_reason", "status_reason_detail", "enabled", "updated_at"])
def save(self, *args, **kwargs):
from posthog.cdp.filters import compile_filters_bytecode
diff --git a/products/ai_observability/backend/models/test/test_evaluations.py b/products/ai_observability/backend/models/test/test_evaluations.py
index 083184c7c77b..628d1ab04e33 100644
--- a/products/ai_observability/backend/models/test/test_evaluations.py
+++ b/products/ai_observability/backend/models/test/test_evaluations.py
@@ -376,18 +376,25 @@ class TestEvaluationStatusCoercion(BaseTest):
evaluation = self._create(enabled=True)
evaluation.status = EvaluationStatus.ERROR
evaluation.status_reason = EvaluationStatusReason.TRIAL_LIMIT_REACHED
+ evaluation.status_reason_detail = "The trial limit was reached."
evaluation.save()
evaluation.status = EvaluationStatus.PAUSED
evaluation.save()
self.assertIsNone(evaluation.status_reason)
+ self.assertIsNone(evaluation.status_reason_detail)
def test_set_status_helper_transitions_all_three_fields(self):
evaluation = self._create(enabled=True)
- evaluation.set_status(EvaluationStatus.ERROR, EvaluationStatusReason.PROVIDER_KEY_DELETED)
+ evaluation.set_status(
+ EvaluationStatus.ERROR,
+ EvaluationStatusReason.HOG_ERROR,
+ "Must return boolean, got int: 42",
+ )
evaluation.refresh_from_db()
self.assertEqual(evaluation.status, EvaluationStatus.ERROR)
- self.assertEqual(evaluation.status_reason, EvaluationStatusReason.PROVIDER_KEY_DELETED)
+ self.assertEqual(evaluation.status_reason, EvaluationStatusReason.HOG_ERROR)
+ self.assertEqual(evaluation.status_reason_detail, "Must return boolean, got int: 42")
self.assertFalse(evaluation.enabled)
def test_refresh_from_db_resets_change_tracking_baseline(self):
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 3240381d5eb8..dbd3e31537c3 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -48,7 +48,7 @@ import {
evaluationTypeUsesModelConfiguration,
} from './evaluationCapabilities'
import { LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'
-import { statusReasonLabel } from './statusDisplay'
+import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'
import { EvaluationType } from './types'
export function AIObservabilityEvaluation(): JSX.Element {
@@ -321,10 +321,17 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="space-y-1">
<p className="font-semibold">This evaluation was automatically disabled</p>
<p>
- {statusReasonLabel(evaluation.status_reason)}. Update the configuration below (e.g. choose a
- supported model or add a provider API key in settings), then re-enable the evaluation to
- resume running.
+ {statusReasonLabel(evaluation.status_reason)}.{' '}
+ {statusReasonRecoveryLabel(evaluation.status_reason)}
</p>
+ {evaluation.status_reason_detail && (
+ <div className="space-y-1">
+ <p className="font-semibold">Error details</p>
+ <pre className="m-0 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded border bg-bg-light p-2 font-mono text-xs">
+ {evaluation.status_reason_detail}
+ </pre>
+ </div>
+ )}
</div>
</LemonBanner>
)}
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 2a81341600fc..7a1787ebfdf7 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -70,6 +70,7 @@ const mockEvaluation: EvaluationConfig = {
enabled: true,
status: 'active',
status_reason: null,
+ status_reason_detail: null,
evaluation_type: 'llm_judge',
evaluation_config: { prompt: 'Is this response helpful?' },
output_type: 'boolean',
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 7f71d5cb339a..9f29a58756a2 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -470,6 +470,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
enabled: true,
status: 'active' as const,
status_reason: null,
+ status_reason_detail: null,
output_type: 'boolean' as const,
output_config: {},
conditions: [
@@ -564,6 +565,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
enabled: true,
status: 'active',
status_reason: null,
+ status_reason_detail: null,
evaluation_type: 'llm_judge',
evaluation_config: {
prompt: '',
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index be10caf590c4..296174be8897 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -59,6 +59,7 @@ const evaluationWithKey = (id: string, providerKeyId: string | null): LLMJudgeEv
enabled: true,
status: 'active',
status_reason: null,
+ status_reason_detail: null,
evaluation_type: 'llm_judge',
evaluation_config: { prompt: 'Prompt' },
output_type: 'boolean',
@@ -173,7 +174,14 @@ describe('llmEvaluationsLogic', () => {
logic.actions.toggleEvaluationEnabledSuccess('eval-errored')
await expectLogic(logic).toMatchValues({
- evaluations: [expect.objectContaining({ enabled: true, status: 'active', status_reason: null })],
+ evaluations: [
+ expect.objectContaining({
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ }),
+ ],
})
})
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index 1c3ac0981218..3895a08305c4 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -93,6 +93,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
// Keep status in sync so the list-column pill updates optimistically.
status: !e.enabled ? 'active' : 'paused',
status_reason: null,
+ status_reason_detail: null,
}
: e
),
diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
index 08909693e451..550223fa350a 100644
--- a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
+++ b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
@@ -1,17 +1,75 @@
-import { statusReasonLabel } from './statusDisplay'
+import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'
-describe('statusReasonLabel', () => {
- it.each([
- ['trial_limit_reached' as const, 'Trial evaluation limit reached'],
- ['model_not_allowed' as const, 'Model not available on the trial plan'],
- ['provider_key_deleted' as const, 'Provider API key was deleted'],
- ['no_default_model' as const, 'No default model available for the selected provider'],
- ])('maps %s to user-facing copy', (reason, expected) => {
- expect(statusReasonLabel(reason)).toBe(expected)
+describe('statusDisplay', () => {
+ describe('statusReasonLabel', () => {
+ it.each([
+ ['trial_limit_reached' as const, 'Trial evaluation limit reached'],
+ ['model_not_allowed' as const, 'Model not available on the trial plan'],
+ ['provider_key_deleted' as const, 'Provider API key was deleted'],
+ ['no_default_model' as const, 'No default model available for the selected provider'],
+ ['provider_key_invalid' as const, 'Provider API key is invalid'],
+ ['provider_key_permission_denied' as const, 'Provider API key lacks model access'],
+ ['provider_key_quota_exceeded' as const, 'Provider API key quota exceeded'],
+ ['provider_key_rate_limited' as const, 'Provider API key is rate limited'],
+ ['model_not_found' as const, 'Model not found'],
+ ['hog_error' as const, 'Hog evaluation code failed'],
+ ])('maps %s to user-facing copy', (reason, expected) => {
+ expect(statusReasonLabel(reason)).toBe(expected)
+ })
+
+ it('returns a generic fallback when reason is null or undefined', () => {
+ expect(statusReasonLabel(null)).toBe('Disabled by the system')
+ expect(statusReasonLabel(undefined)).toBe('Disabled by the system')
+ })
})
- it('returns a generic fallback when reason is null or undefined', () => {
- expect(statusReasonLabel(null)).toBe('Disabled by the system')
- expect(statusReasonLabel(undefined)).toBe('Disabled by the system')
+ describe('statusReasonRecoveryLabel', () => {
+ it.each([
+ [
+ 'trial_limit_reached' as const,
+ 'Add a provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'model_not_allowed' as const,
+ 'Choose a supported model or add a provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'provider_key_deleted' as const,
+ 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'provider_key_invalid' as const,
+ 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'provider_key_permission_denied' as const,
+ 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'provider_key_quota_exceeded' as const,
+ 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'provider_key_rate_limited' as const,
+ 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',
+ ],
+ [
+ 'no_default_model' as const,
+ 'Choose an available model, then re-enable the evaluation to resume running.',
+ ],
+ ['model_not_found' as const, 'Choose an available model, then re-enable the evaluation to resume running.'],
+ ['hog_error' as const, 'Fix the Hog code, then re-enable the evaluation to resume running.'],
+ ])('maps %s to recovery copy', (reason, expected) => {
+ expect(statusReasonRecoveryLabel(reason)).toBe(expected)
+ })
+
+ it('returns a generic fallback when reason is null or undefined', () => {
+ expect(statusReasonRecoveryLabel(null)).toBe(
+ 'Fix the configuration, then re-enable the evaluation to resume running.'
+ )
+ expect(statusReasonRecoveryLabel(undefined)).toBe(
+ 'Fix the configuration, then re-enable the evaluation to resume running.'
+ )
+ })
})
})
diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.ts b/products/ai_observability/frontend/evaluations/statusDisplay.ts
index 6dc8609959b0..86de3c897130 100644
--- a/products/ai_observability/frontend/evaluations/statusDisplay.ts
+++ b/products/ai_observability/frontend/evaluations/statusDisplay.ts
@@ -5,11 +5,44 @@ const REASON_LABELS: Record<EvaluationStatusReason, string> = {
model_not_allowed: 'Model not available on the trial plan',
provider_key_deleted: 'Provider API key was deleted',
no_default_model: 'No default model available for the selected provider',
+ provider_key_invalid: 'Provider API key is invalid',
+ provider_key_permission_denied: 'Provider API key lacks model access',
+ provider_key_quota_exceeded: 'Provider API key quota exceeded',
+ provider_key_rate_limited: 'Provider API key is rate limited',
+ model_not_found: 'Model not found',
+ hog_error: 'Hog evaluation code failed',
}
+const PROVIDER_KEY_REASONS = new Set<EvaluationStatusReason>([
+ 'provider_key_deleted',
+ 'provider_key_invalid',
+ 'provider_key_permission_denied',
+ 'provider_key_quota_exceeded',
+ 'provider_key_rate_limited',
+])
+
export function statusReasonLabel(reason: EvaluationStatusReason | null | undefined): string {
if (!reason) {
return 'Disabled by the system'
}
return REASON_LABELS[reason] ?? 'Disabled by the system'
}
+
+export function statusReasonRecoveryLabel(reason: EvaluationStatusReason | null | undefined): string {
+ if (reason === 'trial_limit_reached') {
+ return 'Add a provider API key in settings, then re-enable the evaluation to resume running.'
+ }
+ if (reason === 'model_not_allowed') {
+ return 'Choose a supported model or add a provider API key in settings, then re-enable the evaluation to resume running.'
+ }
+ if (reason === 'no_default_model' || reason === 'model_not_found') {
+ return 'Choose an available model, then re-enable the evaluation to resume running.'
+ }
+ if (reason === 'hog_error') {
+ return 'Fix the Hog code, then re-enable the evaluation to resume running.'
+ }
+ if (reason && PROVIDER_KEY_REASONS.has(reason)) {
+ return 'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.'
+ }
+ return 'Fix the configuration, then re-enable the evaluation to resume running.'
+}
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 429a92955fe1..b5cd5f870693 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -10,6 +10,12 @@ export type EvaluationStatusReason =
| 'model_not_allowed'
| 'provider_key_deleted'
| 'no_default_model'
+ | 'provider_key_invalid'
+ | 'provider_key_permission_denied'
+ | 'provider_key_quota_exceeded'
+ | 'provider_key_rate_limited'
+ | 'model_not_found'
+ | 'hog_error'
export interface ModelConfiguration {
provider: LLMProvider
@@ -42,6 +48,7 @@ export interface BaseEvaluationConfig {
enabled: boolean
status: EvaluationStatus
status_reason: EvaluationStatusReason | null
+ status_reason_detail: string | null
output_type: EvaluationOutputType
output_config: EvaluationOutputConfig
conditions: EvaluationConditionSet[]
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 5d3d1ddd6fba..3a1736a848b4 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -330,6 +330,12 @@ export const EvaluationStatusEnumApi = {
* * `model_not_allowed` - Model not available on the trial plan
* * `provider_key_deleted` - Provider API key was deleted
* * `no_default_model` - No default model available for the selected provider
+ * * `provider_key_invalid` - Provider API key is invalid
+ * * `provider_key_permission_denied` - Provider API key lacks model access
+ * * `provider_key_quota_exceeded` - Provider API key quota exceeded
+ * * `provider_key_rate_limited` - Provider API key is rate limited
+ * * `model_not_found` - Model not found
+ * * `hog_error` - Hog evaluation code failed
*/
export type StatusReasonEnumApi = (typeof StatusReasonEnumApi)[keyof typeof StatusReasonEnumApi]
@@ -338,6 +344,12 @@ export const StatusReasonEnumApi = {
ModelNotAllowed: 'model_not_allowed',
ProviderKeyDeleted: 'provider_key_deleted',
NoDefaultModel: 'no_default_model',
+ ProviderKeyInvalid: 'provider_key_invalid',
+ ProviderKeyPermissionDenied: 'provider_key_permission_denied',
+ ProviderKeyQuotaExceeded: 'provider_key_quota_exceeded',
+ ProviderKeyRateLimited: 'provider_key_rate_limited',
+ ModelNotFound: 'model_not_found',
+ HogError: 'hog_error',
} as const
/**
@@ -466,6 +478,11 @@ export interface EvaluationApi {
enabled?: boolean
readonly status: EvaluationStatusEnumApi
readonly status_reason: StatusReasonEnumApi | null
+ /**
+ * Additional detail for the current system-disabled status. This is only populated when the detail is safe to show in the evaluation UI.
+ * @nullable
+ */
+ readonly status_reason_detail: string | null
/** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
@@ -544,6 +561,11 @@ export interface PatchedEvaluationApi {
enabled?: boolean
readonly status?: EvaluationStatusEnumApi
readonly status_reason?: StatusReasonEnumApi | null
+ /**
+ * Additional detail for the current system-disabled status. This is only populated when the detail is safe to show in the evaluation UI.
+ * @nullable
+ */
+ readonly status_reason_detail?: string | null
/** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 621d2fa98358..947389b4b6a5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20456,6 +20456,12 @@ export namespace Schemas {
* * `model_not_allowed` - Model not available on the trial plan
* * `provider_key_deleted` - Provider API key was deleted
* * `no_default_model` - No default model available for the selected provider
+ * * `provider_key_invalid` - Provider API key is invalid
+ * * `provider_key_permission_denied` - Provider API key lacks model access
+ * * `provider_key_quota_exceeded` - Provider API key quota exceeded
+ * * `provider_key_rate_limited` - Provider API key is rate limited
+ * * `model_not_found` - Model not found
+ * * `hog_error` - Hog evaluation code failed
*/
export type StatusReasonEnum = typeof StatusReasonEnum[keyof typeof StatusReasonEnum];
@@ -20465,6 +20471,12 @@ export namespace Schemas {
ModelNotAllowed: 'model_not_allowed',
ProviderKeyDeleted: 'provider_key_deleted',
NoDefaultModel: 'no_default_model',
+ ProviderKeyInvalid: 'provider_key_invalid',
+ ProviderKeyPermissionDenied: 'provider_key_permission_denied',
+ ProviderKeyQuotaExceeded: 'provider_key_quota_exceeded',
+ ProviderKeyRateLimited: 'provider_key_rate_limited',
+ ModelNotFound: 'model_not_found',
+ HogError: 'hog_error',
} as const;
/**
@@ -20565,6 +20577,11 @@ export namespace Schemas {
enabled?: boolean;
readonly status: EvaluationStatusEnum;
readonly status_reason: StatusReasonEnum | null;
+ /**
+ * Additional detail for the current system-disabled status. This is only populated when the detail is safe to show in the evaluation UI.
+ * @nullable
+ */
+ readonly status_reason_detail: string | null;
/** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
@@ -36937,6 +36954,11 @@ export namespace Schemas {
enabled?: boolean;
readonly status?: EvaluationStatusEnum;
readonly status_reason?: StatusReasonEnum | null;
+ /**
+ * Additional detail for the current system-disabled status. This is only populated when the detail is safe to show in the evaluation UI.
+ * @nullable
+ */
+ readonly status_reason_detail?: string | null;
/** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge