Skip to content

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

fix(aio): skip llm judge runs on unmapped provider 4xx (#109847)

posthog[bot]40c9cbf84178
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index d4238b31f6a0..0d14df029fc8 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -27,6 +27,7 @@ from posthog.temporal.ai_observability.evaluation_errors import (
require_user_error_spec,
terminal_user_error_result,
terminal_user_error_result_from_application_error,
+ truncate_error_detail,
)
from posthog.temporal.ai_observability.evaluation_event_io import (
extract_event_io,
@@ -58,6 +59,7 @@ from products.ai_observability.backend.llm.errors import (
RateLimitError,
StructuredOutputParseError,
UnsupportedModelError,
+ provider_error_detail,
)
from products.ai_observability.backend.llm.system_one import (
SystemOneClient,
@@ -89,6 +91,11 @@ LLM_JUDGE_RETRY_POLICY = RetryPolicy(
)
+# A retry can fix these client errors, so they stay on the retry policy like a 5xx.
+# 499 is a cancellation, which Gemini already maps to the transport lane.
+_RETRYABLE_CLIENT_ERROR_STATUSES = frozenset({408, 409, 429, 499})
+
+
class TransientJudgeError(NonReportableError):
"""A transient transport failure that reached the judge, wrapped to keep it out of error tracking.
@@ -375,6 +382,55 @@ def _build_unparsable_response_skip_result(
return result
+def _rejected_request_status(error: Exception) -> int | None:
+ """The 4xx status of a provider rejection that no retry can fix, or None.
+
+ The OpenAI and Anthropic SDKs put the status on `status_code`. google-genai puts it on `code`.
+ """
+ status = getattr(error, "status_code", None)
+ if not isinstance(status, int):
+ status = getattr(error, "code", None)
+ if not isinstance(status, int) or isinstance(status, bool):
+ return None
+ if 400 <= status < 500 and status not in _RETRYABLE_CLIENT_ERROR_STATUSES:
+ return status
+ return None
+
+
+def _build_rejected_request_skip_result(
+ allows_na: bool,
+ *,
+ is_byok: bool,
+ key_id: str | None,
+ status: int,
+ error: Exception,
+ output_type: str = "boolean",
+) -> EvaluationActivityResult:
+ """Per-item skip for a provider rejection that has no specific mapping.
+
+ The provider's message goes into the reasoning, because nothing else tells the user why the
+ provider rejected the request.
+ """
+ reasoning = (
+ f"The model provider rejected the evaluation request with status {status}, so this run was skipped. "
+ "Check the model and provider settings if this keeps happening."
+ )
+ detail = truncate_error_detail(provider_error_detail(error) or str(error))
+ if detail:
+ reasoning = f"{reasoning} Provider message: {detail}"
+ result: EvaluationActivityResult = {
+ **build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=reasoning,
+ skip_reason="request_rejected",
+ ),
+ "is_byok": is_byok,
+ "key_id": key_id,
+ }
+ return result
+
+
@temporalio.activity.defn
@close_db_connections
# capture_exceptions=False: the worker interceptor reports judge failures, and its capture carries
@@ -841,6 +897,28 @@ def call_llm_judge(
raise
except Exception as e:
+ rejected_status = _rejected_request_status(e)
+ # On a PostHog key a rejection is our bug, so it falls through to error tracking below.
+ if rejected_status is not None and is_byok:
+ # A single bad input and a bad configuration look the same here, so skip this run and
+ # leave the evaluation and its key alone.
+ increment_user_errors("request_rejected", provider=provider)
+ logger.warning(
+ "LLM provider rejected the judge request",
+ evaluation_id=evaluation["id"],
+ provider=provider,
+ model=model,
+ status=rejected_status,
+ error_class=type(e).__name__,
+ )
+ return _build_rejected_request_skip_result(
+ allows_na,
+ is_byok=is_byok,
+ key_id=key_id,
+ status=rejected_status,
+ error=e,
+ output_type=output_type,
+ )
logger.exception(
"Unhandled error from LLM client",
evaluation_id=evaluation["id"],
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 7dbfa52285fb..568690cd559b 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -11,8 +11,10 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.test import override_settings
import httpx
+import openai
import posthoganalytics
from asgiref.sync import async_to_sync, sync_to_async
+from google.genai import errors as genai_errors
from parameterized import parameterized
from pydantic import ValidationError as PydanticValidationError
from temporalio import activity
@@ -675,6 +677,88 @@ def test_system_one_rate_limit_retries_without_disabling_the_evaluation() -> Non
assert terminal_user_error_result_from_application_error(error.value, allows_na=False) is None
+def _openai_status_error(status: int, message: str) -> openai.APIStatusError:
+ response = httpx.Response(status, request=httpx.Request("POST", "https://llm.example.com/v1/chat/completions"))
+ return openai.APIStatusError(f"Error code: {status}", response=response, body={"error": {"message": message}})
+
+
+ "provider, raised_exception, expected_status, expected_detail",
+ [
+ pytest.param(
+ "openai_compatible",
+ _openai_status_error(400, "Example field is not supported."),
+ 400,
+ "Example field is not supported.",
+ id="openai_sdk_400",
+ ),
+ pytest.param(
+ "openai",
+ _openai_status_error(412, "Example precondition failed."),
+ 412,
+ "Example precondition failed.",
+ id="openai_sdk_412",
+ ),
+ pytest.param(
+ "gemini",
+ genai_errors.ClientError(400, {"error": {"code": 400, "message": "Example argument is invalid."}}),
+ 400,
+ "Example argument is invalid.",
+ id="genai_400",
+ ),
+ pytest.param(
+ "openai_compatible",
+ _openai_status_error(400, "x" * (MAX_STATUS_REASON_DETAIL_LENGTH * 2)),
+ 400,
+ "x" * (MAX_STATUS_REASON_DETAIL_LENGTH - 3) + "...",
+ id="long_message_is_truncated",
+ ),
+ ],
+)
+def test_unmapped_provider_rejection_skips_the_run_with_the_provider_message(
+ provider: str, raised_exception: Exception, expected_status: int, expected_detail: str
+) -> None:
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as client,
+ ):
+ spec.return_value.resolve.return_value = MagicMock(
+ provider=provider, model="example-judge-v1", provider_key=MagicMock(id="example-key"), is_byok=True
+ )
+ client.return_value.complete.side_effect = raised_exception
+ result = call_llm_judge(
+ evaluation={"id": "test-evaluation", "team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ )
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "request_rejected"
+ assert f"status {expected_status}" in result["reasoning"]
+ assert result["reasoning"].endswith(f"Provider message: {expected_detail}")
+ assert result["key_id"] == "example-key"
+ assert "terminal_user_error" not in result
+ assert "provider_key_state" not in result
+
+
+def test_unmapped_provider_rejection_on_a_posthog_key_still_raises() -> None:
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as client,
+ ):
+ spec.return_value.resolve.return_value = MagicMock(
+ provider="openai", model="example-judge-v1", provider_key=None, is_byok=False
+ )
+ client.return_value.complete.side_effect = _openai_status_error(400, "Example field is not supported.")
+ with pytest.raises(openai.APIStatusError):
+ call_llm_judge(
+ evaluation={"id": "test-evaluation", "team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ )
+
+
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")
@@ -2541,6 +2625,12 @@ class TestRunEvaluationWorkflow:
pytest.param(ProviderConnectionError("connection reset"), TransientJudgeError, id="connection_error"),
pytest.param(CancelledError("Cancelled"), CancelledError, id="cancellation"),
pytest.param(RuntimeError("boom"), RuntimeError, id="unhandled_error"),
+ pytest.param(
+ _openai_status_error(503, "Example upstream outage."), openai.APIStatusError, id="provider_5xx"
+ ),
+ pytest.param(
+ _openai_status_error(408, "Example request timeout."), openai.APIStatusError, id="provider_timeout"
+ ),
],
)
@pytest.mark.django_db(transaction=True)