:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): don't fail evals on unparsable judge output (#103613)
Carlos Marchalb9de1c721222
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 6b34453ef95f..b29f68e0dc7b 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -1,12 +1,12 @@import jsonfrom dataclasses import dataclassfrom datetime import timedelta-from typing import Any+from typing import Annotated, Any, Literalimport structlogimport temporalioimport posthoganalytics-from pydantic import BaseModel, model_validator+from pydantic import BaseModel, BeforeValidatorfrom structlog.contextvars import bind_contextvarsfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError@@ -34,7 +34,7 @@ from posthog.temporal.ai_observability.model_resolution import model_specfrom posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.utils import close_db_connections-from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest, Usagefrom products.ai_observability.backend.llm.errors import (AuthenticationError,ContextWindowExceededError,@@ -85,24 +85,41 @@ class BooleanEvalResult(BaseModel):verdict: bool+_OUTCOME_ALIASES = {+ "n/a": "not_applicable",+ "na": "not_applicable",+ "notapplicable": "not_applicable",+}+++def _normalize_outcome(value: Any) -> Any:+ if not isinstance(value, str):+ return value+ cleaned = value.strip().strip(".").lower().replace("-", "_").replace(" ", "_")+ return _OUTCOME_ALIASES.get(cleaned, cleaned)++class BooleanWithNAEvalResult(BaseModel):- """Structured output for boolean with N/A evaluation results.+ """Structured output for boolean evaluation results that allow N/A.- When the evaluation criteria doesn't apply to the input/output,- applicable should be False and verdict should be None.+ One enum rather than an `applicable` flag beside a nullable `verdict`, because no provider's+ JSON Schema subset expresses "verdict is required when applicable is true", so the two-field+ shape let a model return a combination a validator here then rejected. Anthropic does not+ enforce the enum, which is what `_normalize_outcome` is for."""reasoning: str- applicable: bool- verdict: bool | None = None+ outcome: Annotated[Literal["pass", "fail", "not_applicable"], BeforeValidator(_normalize_outcome)]++ @property+ def applicable(self) -> bool:+ return self.outcome != "not_applicable"- @model_validator(mode="after")- def validate_verdict_consistency(self) -> "BooleanWithNAEvalResult":- if self.applicable and self.verdict is None:- raise ValueError("verdict is required when applicable is true")- if not self.applicable and self.verdict is not None:- raise ValueError("verdict must be null when applicable is false")- return self+ @property+ def verdict(self) -> bool | None:+ if self.outcome == "not_applicable":+ return None+ return self.outcome == "pass"@dataclass@@ -120,12 +137,11 @@ def get_output_type_config(allows_na: bool) -> OutputTypeConfig:response_format=BooleanWithNAEvalResult,instructions="""First, determine if this evaluation criteria is applicable to the given input/output. If the criteria doesn't apply to this case mark it as not applicable.-Note: If the criteria above instructs you to return "N/A", "not applicable", or similar, treat that as applicable=false with verdict=null.+Note: If the criteria above instructs you to return "N/A", "not applicable", or similar, return an outcome of "not_applicable".Return:-- applicable: true if the criteria applies to this input/output, false if it doesn't apply-- verdict: true if it passes, false if it fails, or null if not applicable-- reasoning: a brief explanation (1 sentence)""",+- reasoning: a brief explanation (1 sentence)+- outcome: "pass" if the generation meets the criteria, "fail" if it does not, "not_applicable" if the criteria doesn't apply to this input/output""",)return OutputTypeConfig(response_format=BooleanEvalResult,@@ -220,6 +236,35 @@ def _build_context_window_skip_result(return result+def _build_unparsable_response_skip_result(+ allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str, usage: Usage | None+) -> EvaluationActivityResult:+ """Per-item skip for a judge response that does not match the requested schema.++ This skip carries `model` and `provider`, unlike the others, because the model did run and+ the call was billed. `usage` is None when the failure reached us as an exception, which drops+ the counts the provider reported.+ """+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": None if allows_na else False,+ "reasoning": "Evaluation model returned an unreadable response; evaluation skipped.",+ "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,+ "is_byok": is_byok,+ "key_id": key_id,+ "allows_na": allows_na,+ "model": model,+ "provider": provider,+ "skipped": True,+ "skip_reason": "unparsable_response",+ }+ if allows_na:+ result["applicable"] = False+ return result++@temporalio.activity.defn@close_db_connections# capture_exceptions=False: the worker interceptor reports judge failures, and its capture carries@@ -420,12 +465,19 @@ def call_llm_judge(non_retryable=True,)except StructuredOutputParseError as e:+ # Skip rather than raise: non-conforming model output is not a PostHog defect, and raising+ # files a new error tracking issue on each deploy, because the fingerprint follows the stack.increment_errors("parse_error", provider=provider)- raise ApplicationError(- str(e),- {"error_type": "parse_error"},- non_retryable=True,- ) from e+ logger.warning(+ "LLM judge returned unparsable structured output",+ evaluation_id=evaluation["id"],+ provider=provider,+ model=model,+ error=str(e),+ )+ return _build_unparsable_response_skip_result(+ allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, usage=None+ )except ContextWindowExceededError:# Skip rather than raise: retrying can't fix an over-window prompt and just spams error tracking.@@ -459,8 +511,16 @@ def call_llm_judge(parsed_result = response.parsedif 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']}")+ increment_errors("empty_structured_response", provider=provider)+ logger.warning(+ "LLM judge returned empty structured response",+ evaluation_id=evaluation["id"],+ provider=provider,+ model=model,+ )+ return _build_unparsable_response_skip_result(+ allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, usage=response.usage+ )assert isinstance(parsed_result, BooleanEvalResult | BooleanWithNAEvalResult)diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex 377271e1d712..0e95de2a5cb2 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -277,7 +277,9 @@ def build_evaluation_event_properties(properties["$ai_evaluation_skipped"] = Trueproperties["$ai_evaluation_skip_reason"] = result.get("skip_reason")- if evaluation_type == "llm_judge" and not result.get("skipped"):+ # Keyed on a model rather than on the skip flag: a skip that reached the provider was billed,+ # and a skip that never called one carries no model, so it still gets no attribution.+ if evaluation_type == "llm_judge" and result.get("model"):properties["$ai_model"] = result.get("model", DEFAULT_JUDGE_MODEL)properties["$ai_provider"] = result.get("provider", "openai")properties["$ai_input_tokens"] = result.get("input_tokens", 0)diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 7b10a5f48fbb..52a46f8f11fb 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport posthoganalyticsfrom asgiref.sync import sync_to_asyncfrom parameterized import parameterized+from pydantic import ValidationError as PydanticValidationErrorfrom temporalio import activityfrom temporalio.api.enums.v1 import EventTypefrom temporalio.exceptions import ApplicationError, CancelledError@@ -610,10 +611,18 @@ class TestRunEvaluationWorkflow:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_emit_evaluation_event_activity_skipped_omits_cost_attribution(self, setup_data):- """Skipped evaluations never made an API call, so the emitted event must not attribute- a model, provider, or token usage. The skip is surfaced via dedicated properties so- consumers can still distinguish a skip from a regular result."""+ @pytest.mark.parametrize(+ "skip_reason, model, provider, input_tokens, output_tokens, expects_attribution",+ [+ # Nothing reached a provider, so attributing a model would invent a call that never ran.+ pytest.param("trace_errored", None, None, 0, 0, False, id="no_call_made"),+ # The model ran and billed before its answer turned out to be unreadable.+ pytest.param("unparsable_response", "gpt-5-mini", "openai", 11, 7, True, id="call_billed"),+ ],+ )+ async def test_emit_evaluation_event_activity_attributes_only_a_skip_that_called_a_model(+ self, setup_data, skip_reason, model, provider, input_tokens, output_tokens, expects_attribution+ ):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -628,16 +637,19 @@ class TestRunEvaluationWorkflow:result: EvaluationActivityResult = {"result_type": "boolean","verdict": False,- "reasoning": "Source trace errored before producing output; evaluation skipped.",- "input_tokens": 0,- "output_tokens": 0,- "total_tokens": 0,+ "reasoning": "Evaluation skipped.",+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ "total_tokens": input_tokens + output_tokens,"is_byok": False,"key_id": None,"allows_na": False,"skipped": True,- "skip_reason": "trace_errored",+ "skip_reason": skip_reason,}+ if model is not None and provider is not None:+ result["model"] = model+ result["provider"] = providerwith patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:with patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture:@@ -656,20 +668,26 @@ class TestRunEvaluationWorkflow:props = mock_capture.call_args[1]["properties"]assert props["$ai_evaluation_skipped"] is True- assert props["$ai_evaluation_skip_reason"] == "trace_errored"+ assert props["$ai_evaluation_skip_reason"] == skip_reasonassert props["$ai_evaluation_result_type"] == "boolean"assert props["$ai_evaluation_result"] is False- for cost_key in (- "$ai_model",- "$ai_provider",- "$ai_input_tokens",- "$ai_output_tokens",- "$ai_evaluation_model",- "$ai_evaluation_provider",- "$ai_evaluation_key_type",- "$ai_evaluation_key_id",- ):- assert cost_key not in props, f"{cost_key} must be omitted for skipped evaluations"+ if expects_attribution:+ assert props["$ai_model"] == model+ assert props["$ai_provider"] == provider+ assert props["$ai_input_tokens"] == input_tokens+ assert props["$ai_output_tokens"] == output_tokens+ else:+ for cost_key in (+ "$ai_model",+ "$ai_provider",+ "$ai_input_tokens",+ "$ai_output_tokens",+ "$ai_evaluation_model",+ "$ai_evaluation_provider",+ "$ai_evaluation_key_type",+ "$ai_evaluation_key_id",+ ):+ assert cost_key not in props, f"{cost_key} must be omitted when no model was called"@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@@ -1269,7 +1287,7 @@ class TestRunEvaluationWorkflow:mock_client = MagicMock()mock_client_class.return_value = mock_client- mock_parsed = BooleanWithNAEvalResult(verdict=True, applicable=True, reasoning="The answer is correct")+ mock_parsed = BooleanWithNAEvalResult(outcome="pass", reasoning="The answer is correct")mock_response = MagicMock()mock_response.parsed = mock_parsed@@ -1312,7 +1330,7 @@ class TestRunEvaluationWorkflow:mock_client_class.return_value = mock_clientmock_parsed = BooleanWithNAEvalResult(- verdict=None, applicable=False, reasoning="This is a greeting, not a math problem"+ outcome="not_applicable", reasoning="This is a greeting, not a math problem")mock_response = MagicMock()@@ -1640,14 +1658,23 @@ class TestRunEvaluationWorkflow:evaluation.refresh_from_db()assert evaluation.enabled is True- def test_execute_llm_judge_activity_parse_error_raises_non_retryable(self):+ @pytest.mark.parametrize(+ "output_config, expected_verdict, expected_applicable",+ [+ pytest.param({}, False, None, id="allows_na_false"),+ pytest.param({"allows_na": True}, None, False, id="allows_na_true"),+ ],+ )+ def test_execute_llm_judge_activity_parse_error_skips_item(+ self, output_config, expected_verdict, expected_applicable+ ):evaluation = {"id": "eval-123","name": "Test Evaluation","evaluation_type": "llm_judge","evaluation_config": {"prompt": "Is this response factually accurate?"},"output_type": "boolean",- "output_config": {},+ "output_config": output_config,"team_id": 1,}@@ -1673,12 +1700,58 @@ class TestRunEvaluationWorkflow:"Failed to parse structured output: I need to fetch your bundles...")- with pytest.raises(ApplicationError, match="Failed to parse structured output") as exc_info:- execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))mock_increment_errors.assert_called_once_with("parse_error", provider="openai")- assert exc_info.value.non_retryable is True- assert exc_info.value.details[0] == {"error_type": "parse_error"}+ assert result["skipped"] is True+ assert result["skip_reason"] == "unparsable_response"+ assert result["verdict"] is expected_verdict+ assert result.get("applicable") is expected_applicable+ # The exception drops the provider's counts, but the call still happened on a known model.+ assert result["provider"] == "openai"+ assert result["input_tokens"] == 0++ def test_execute_llm_judge_activity_empty_structured_response_skips_item(self):+ evaluation = {+ "id": "eval-123",+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this response factually accurate?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ }++ event_data = create_mock_event_data(+ 1,+ properties={+ "$ai_input": [{"role": "user", "content": "What is 2+2?"}],+ "$ai_output_choices": [{"role": "assistant", "content": "4"}],+ },+ )++ with (+ patch(+ "posthog.temporal.ai_observability.model_resolution.EvaluationConfig.objects.get_or_create"+ ) as mock_get_or_create,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_increment_errors,+ ):+ mock_get_or_create.return_value = (_mock_config_with_active_key("openai"), False)+ mock_client = MagicMock()+ mock_client_class.return_value = mock_client+ mock_response = MagicMock()+ mock_response.parsed = None+ mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)+ mock_client.complete.return_value = mock_response++ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))++ mock_increment_errors.assert_called_once_with("empty_structured_response", provider="openai")+ assert result["skipped"] is True+ assert result["skip_reason"] == "unparsable_response"+ assert result["provider"] == "openai"+ assert (result["input_tokens"], result["output_tokens"]) == (10, 5)@pytest.mark.parametrize("raised_exception, expected_label",@@ -2427,24 +2500,26 @@ class TestEvalResultModels:assert result.reasoning == "Test reasoning"assert result.verdict is True- def test_boolean_with_na_eval_result_applicable(self):- """Test BooleanWithNAEvalResult model when applicable"""- result = BooleanWithNAEvalResult(reasoning="Test reasoning", applicable=True, verdict=True)- assert result.reasoning == "Test reasoning"- assert result.applicable is True- assert result.verdict is True-- def test_boolean_with_na_eval_result_not_applicable(self):- """Test BooleanWithNAEvalResult model when not applicable"""- result = BooleanWithNAEvalResult(reasoning="Not applicable", applicable=False, verdict=None)- assert result.reasoning == "Not applicable"- assert result.applicable is False- assert result.verdict is None-- def test_boolean_with_na_eval_result_rejects_verdict_when_not_applicable(self):- """Test that verdict must be null when applicable is false"""- with pytest.raises(ValueError, match="verdict must be null when applicable is false"):- BooleanWithNAEvalResult(reasoning="Not applicable", applicable=False, verdict=True)+ @pytest.mark.parametrize(+ "outcome, expected_verdict, expected_applicable",+ [+ pytest.param("pass", True, True, id="pass"),+ pytest.param("fail", False, True, id="fail"),+ pytest.param("not_applicable", None, False, id="not_applicable"),+ pytest.param("Pass", True, True, id="capitalized"),+ pytest.param(" FAIL ", False, True, id="padded_uppercase"),+ pytest.param("Not Applicable", None, False, id="spaced"),+ pytest.param("N/A", None, False, id="n_slash_a"),+ ],+ )+ def test_boolean_with_na_eval_result_maps_outcome(self, outcome, expected_verdict, expected_applicable):+ result = BooleanWithNAEvalResult(reasoning="Test reasoning", outcome=outcome)+ assert result.verdict is expected_verdict+ assert result.applicable is expected_applicable++ def test_boolean_with_na_eval_result_rejects_unknown_outcome(self):+ with pytest.raises(PydanticValidationError):+ BooleanWithNAEvalResult(reasoning="Test reasoning", outcome="maybe")class TestRunHogEvalAllowsNA:diff --git a/products/ai_observability/backend/backfill_candidates.py b/products/ai_observability/backend/backfill_candidates.pyindex a03d768481c7..16de8fc967ff 100644--- a/products/ai_observability/backend/backfill_candidates.py+++ b/products/ai_observability/backend/backfill_candidates.py@@ -111,6 +111,8 @@ WHERE event = '$ai_generation'GROUP BY unit_id"""+# An unparsable judge response is the one skip a later run can resolve, so it does not count+# as evaluated. A trace that errored or a prompt over the context window skips again.# Reads the shared events table rather than ai_events: the verdict rows must stay visible past the# ai_events retention window, so a re-run of an old backfill still sees what it already covered._ALREADY_EVALUATED_SQL = """@@ -121,6 +123,8 @@ WHERE event = '$ai_evaluation'AND {target_type_filter}AND timestamp >= {window_start}AND timestamp < {verdict_end}+ AND (isNull(properties.$ai_evaluation_skip_reason)+ OR properties.$ai_evaluation_skip_reason != 'unparsable_response')"""diff --git a/products/ai_observability/backend/test/test_backfill_candidates.py b/products/ai_observability/backend/test/test_backfill_candidates.pyindex ae838e92d709..56b99fb9764f 100644--- a/products/ai_observability/backend/test/test_backfill_candidates.py+++ b/products/ai_observability/backend/test/test_backfill_candidates.py@@ -224,6 +224,33 @@ class TestBackfillCandidates(ClickhouseTestMixin, APIBaseTest):assert self._count(target=target, rerun_existing=False) == expectedassert self._count(target=target, rerun_existing=True) == expected + 1+ @parameterized.expand(+ [+ # A judge response nobody could read may parse on a later run, so the unit is still owed a verdict.+ ("unparsable_response", 4),+ # These two skip the same way every run, so re-offering them would never produce a verdict.+ ("context_window_exceeded", 3),+ ("trace_errored", 3),+ ]+ )+ def test_only_a_transient_skip_leaves_the_unit_a_candidate(self, skip_reason: str, expected: int) -> None:+ _create_event(+ team=self.team,+ event="$ai_evaluation",+ distinct_id="d",+ timestamp=BASE + timedelta(minutes=5),+ properties={+ "$ai_evaluation_id": str(self.evaluation.id),+ "$ai_target_id": _generation_uuid(1),+ "$ai_target_type": "generation_uuid",+ "$ai_evaluation_skipped": True,+ "$ai_evaluation_skip_reason": skip_reason,+ },+ )+ flush_persons_and_events()++ assert self._count(target="generation", rerun_existing=False) == expected+@parameterized.expand([# A generation is graded when it lands, so a verdict three days later belongs todiff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsxindex f614e648e94c..702ac702c1e5 100644--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx@@ -22,6 +22,7 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventTconst evaluationId = eventProperties.$ai_evaluation_idconst resultRun = {status: 'completed' as const,+ skipped: eventProperties.$ai_evaluation_skipped === true || eventProperties.$ai_evaluation_skipped === 'true',...normalizeEvaluationResultProperties({rawResult: eventProperties.$ai_evaluation_result,rawApplicable: eventProperties.$ai_evaluation_applicable,