: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(llma): skip judge evaluation when source trace errored (#56883)
Richard Solomou5de07ec8da67
diff --git a/posthog/temporal/llm_analytics/run_evaluation.py b/posthog/temporal/llm_analytics/run_evaluation.pyindex ed94ce58546d..a7944eb39668 100644--- a/posthog/temporal/llm_analytics/run_evaluation.py+++ b/posthog/temporal/llm_analytics/run_evaluation.py@@ -431,6 +431,48 @@ class ExecuteLLMJudgeInputs:}+def _is_errored_trace(properties: dict[str, Any]) -> bool:+ """Return True when the captured trace recorded an error.++ `$ai_is_error` may be ingested as a Python bool or a JSON-encoded string depending on the+ SDK and capture path, so we normalise both forms here.+ """+ raw = properties.get("$ai_is_error")+ if isinstance(raw, bool):+ return raw+ if isinstance(raw, str):+ return raw.strip().lower() == "true"+ return False+++def _build_errored_trace_result(allows_na: bool) -> dict[str, Any]:+ """Result returned when the source trace errored — skips the LLM call entirely.++ Keep the keys here in sync with the success-path result built around the bottom of+ `execute_llm_judge_activity`; `emit_evaluation_event_activity` and the workflow downstream+ both branch on the same shape. `model` and `provider` are deliberately omitted so the+ `.get(..., DEFAULT_JUDGE_MODEL)` defaults don't silently attribute phantom calls to a model+ that was never invoked — the emit activity instead detects the `skipped` flag and drops+ cost / model attribution entirely.+ """+ reasoning = "Source trace errored before producing output; evaluation skipped."+ result: dict[str, Any] = {+ "verdict": None if allows_na else False,+ "reasoning": reasoning,+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "is_byok": False,+ "key_id": None,+ "allows_na": allows_na,+ "skipped": True,+ "skip_reason": "trace_errored",+ }+ if allows_na:+ result["applicable"] = False+ return result++@temporalio.activity.defnasync def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> dict[str, Any]:"""Execute LLM judge to evaluate the target event.@@ -463,6 +505,20 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> dict[str,output_config = evaluation.get("output_config", {})allows_na = output_config.get("allows_na", False)+ # Parse properties early so we can short-circuit on traces that errored before producing+ # any output. Without this guard, the judge runs against an empty Output and tends to+ # return spurious verdicts (often `true`) instead of recognising that there is nothing to+ # evaluate.+ event_type = event_data["event"]+ properties = event_data["properties"]+ if isinstance(properties, str):+ properties = json.loads(properties)++ if _is_errored_trace(properties):+ # Visibility for skipped evaluations comes from the workflow-level SKIPPED status emitted+ # by the metrics interceptor; there is no error to record here.+ return _build_errored_trace_result(allows_na)+# Fetch provider key configuration (BYOK or trial)team_id = evaluation["team_id"]model_configuration = evaluation.get("model_configuration")@@ -553,12 +609,6 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> dict[str,is_byok = provider_key is not Nonekey_id = str(provider_key.id) if provider_key else None- # Build context from event- event_type = event_data["event"]- properties = event_data["properties"]- if isinstance(properties, str):- properties = json.loads(properties)-# Extract input/output based on event typeinput_raw, output_raw = extract_event_io(event_type, properties)@@ -875,8 +925,14 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> N"$session_id": source_props.get("$session_id"),}- # LLM-specific properties: cost attribution and model info (not applicable for hog evals)- if evaluation_type != "hog":+ if result.get("skipped"):+ properties["$ai_evaluation_skipped"] = True+ properties["$ai_evaluation_skip_reason"] = result.get("skip_reason")++ # LLM-specific properties: cost attribution and model info (not applicable for hog evals,+ # and skipped evaluations never made an API call so attributing them to a model would+ # pollute cost dashboards with phantom calls).+ if evaluation_type != "hog" and not result.get("skipped"):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)@@ -1086,8 +1142,10 @@ class RunEvaluationWorkflow(PostHogWorkflow):)raise- # Increment trial eval counter if using PostHog key (LLM judge only — no cost for hog evals)- if not result.get("is_byok"):+ # Increment trial eval counter if using PostHog key (LLM judge only — no cost for hog evals).+ # Skipped evaluations (e.g. errored source trace) never made an API call, so they do not+ # consume trial quota.+ if not result.get("is_byok") and not result.get("skipped"):threshold_pct = await temporalio.workflow.execute_activity(increment_trial_eval_count_activity,evaluation["team_id"],@@ -1130,16 +1188,20 @@ class RunEvaluationWorkflow(PostHogWorkflow):increment_errors("emit_evaluation_event_failed")raise- # Activity 5: Emit internal telemetry (fire-and-forget)- await temporalio.workflow.execute_activity(- emit_internal_telemetry_activity,- EmitInternalTelemetryInputs(- evaluation=evaluation,- team_id=evaluation["team_id"],- result=result,- ),- schedule_to_close_timeout=timedelta(seconds=30),- )+ # Activity 5: Emit internal telemetry (fire-and-forget). Internal telemetry tracks model,+ # provider, and token usage on the PostHog org for cost attribution; skipped evaluations+ # never made an API call, so emitting a phantom record with `verdict=False` and zero+ # tokens would pollute that data.+ if not result.get("skipped"):+ await temporalio.workflow.execute_activity(+ emit_internal_telemetry_activity,+ EmitInternalTelemetryInputs(+ evaluation=evaluation,+ team_id=evaluation["team_id"],+ result=result,+ ),+ schedule_to_close_timeout=timedelta(seconds=30),+ )# Emit signal when eval judge verdict is true (fire-and-forget).# v2: dedicated workflow on VIDEO_EXPORT_TASK_QUEUE (signals worker).@@ -1198,10 +1260,17 @@ class RunEvaluationWorkflow(PostHogWorkflow):team_id=evaluation["team_id"],)- return {+ workflow_result: dict[str, Any] = {"verdict": result["verdict"],"reasoning": result["reasoning"],"evaluation_id": evaluation["id"],"evaluation_type": evaluation_type,"is_byok": result.get("is_byok", False),+ "skipped": result.get("skipped", False),}+ # Match the shape of the existing workflow-level skip path (around the `error_type` branch+ # above) so consumers can group skipped workflows by reason without special-casing the+ # source of the skip.+ if result.get("skipped"):+ workflow_result["skip_reason"] = result.get("skip_reason")+ return workflow_resultdiff --git a/posthog/temporal/llm_analytics/test_run_evaluation.py b/posthog/temporal/llm_analytics/test_run_evaluation.pyindex 17bb2b6161d1..388cdf7e8c17 100644--- a/posthog/temporal/llm_analytics/test_run_evaluation.py+++ b/posthog/temporal/llm_analytics/test_run_evaluation.py@@ -196,6 +196,67 @@ class TestRunEvaluationWorkflow:assert props["$ai_output_tokens"] == 18assert props["$ai_evaluation_type"] == "online"+ @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."""+ evaluation_obj = setup_data["evaluation"]+ team = setup_data["team"]++ evaluation = {+ "id": str(evaluation_obj.id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ }++ event_data = create_mock_event_data(team.id, properties={})++ result = {+ "verdict": False,+ "reasoning": "Source trace errored before producing output; evaluation skipped.",+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "is_byok": False,+ "key_id": None,+ "allows_na": False,+ "skipped": True,+ "skip_reason": "trace_errored",+ }++ with patch("posthog.temporal.llm_analytics.run_evaluation.Team.objects.get") as mock_team_get:+ with patch("posthog.temporal.llm_analytics.run_evaluation.capture_internal") as mock_capture:+ mock_team_get.return_value = team+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())++ await emit_evaluation_event_activity(+ EmitEvaluationEventInputs(+ evaluation=evaluation,+ event_data=event_data,+ result=result,+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ )+ )++ 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_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"+def test_parse_inputs(self):"""Test that parse_inputs correctly parses workflow inputs"""event_data = create_mock_event_data(team_id=1)@@ -298,6 +359,153 @@ class TestRunEvaluationWorkflow:assert result["reasoning"] == "This is a greeting, not a math problem"assert result["allows_na"] is True+ @pytest.mark.parametrize(+ "ai_is_error_value",+ [+ pytest.param(True, id="bool_true"),+ pytest.param("true", id="string_true"),+ pytest.param("True", id="string_True_capitalized"),+ ],+ )+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_execute_llm_judge_activity_skips_errored_traces(self, ai_is_error_value: bool | str, setup_data):+ """Errored traces have no meaningful output — the judge must short-circuit instead of+ producing a verdict against an empty Output (which historically defaulted to true)."""+ evaluation_obj = setup_data["evaluation"]+ team = setup_data["team"]++ evaluation = {+ "id": str(evaluation_obj.id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this response relevant?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": team.id,+ }++ event_data = create_mock_event_data(+ team.id,+ properties={+ "$ai_input": [{"role": "user", "content": "What is 2+2?"}],+ "$ai_output_choices": [],+ "$ai_is_error": ai_is_error_value,+ },+ )++ with patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class:+ result = await execute_llm_judge_activity(+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)+ )++ mock_client_class.assert_not_called()++ assert result["verdict"] is False+ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_errored"+ assert result["allows_na"] is False+ assert result["input_tokens"] == 0+ assert result["output_tokens"] == 0+ assert result["total_tokens"] == 0+ assert "errored" in result["reasoning"].lower()+ # `model` / `provider` must be omitted so they don't get attributed to a phantom call+ # via `.get(..., DEFAULT_JUDGE_MODEL)` defaults in downstream consumers.+ assert "model" not in result+ assert "provider" not in result++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_execute_llm_judge_activity_skips_errored_trace_with_allows_na(self, setup_data):+ """When N/A is allowed, errored traces should be marked inapplicable rather than verdict=false."""+ evaluation_obj = setup_data["evaluation"]+ team = setup_data["team"]++ evaluation = {+ "id": str(evaluation_obj.id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this response relevant?"},+ "output_type": "boolean",+ "output_config": {"allows_na": True},+ "team_id": team.id,+ }++ event_data = create_mock_event_data(+ team.id,+ properties={+ "$ai_input": [{"role": "user", "content": "Hi"}],+ "$ai_is_error": True,+ },+ )++ with patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class:+ result = await execute_llm_judge_activity(+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)+ )++ mock_client_class.assert_not_called()++ assert result["verdict"] is None+ assert result["applicable"] is False+ assert result["allows_na"] is True+ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_errored"++ @pytest.mark.parametrize(+ "error_props",+ [+ pytest.param({}, id="missing"),+ pytest.param({"$ai_is_error": False}, id="explicit_false"),+ pytest.param({"$ai_is_error": "false"}, id="string_false"),+ ],+ )+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_execute_llm_judge_activity_does_not_skip_when_not_errored(+ self, error_props: dict[str, Any], setup_data+ ):+ """Sanity check: traces without `$ai_is_error=true` still flow through to the LLM judge."""+ evaluation_obj = setup_data["evaluation"]+ team = setup_data["team"]++ evaluation = {+ "id": str(evaluation_obj.id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this response relevant?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": team.id,+ }++ event_data = create_mock_event_data(+ team.id,+ properties={+ "$ai_input": [{"role": "user", "content": "What is 2+2?"}],+ "$ai_output_choices": [{"role": "assistant", "content": "4"}],+ **error_props,+ },+ )++ with patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class:+ mock_client = MagicMock()+ mock_client_class.return_value = mock_client++ mock_response = MagicMock()+ mock_response.parsed = BooleanEvalResult(verdict=True, reasoning="Correct")+ mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)+ mock_client.complete.return_value = mock_response++ result = await execute_llm_judge_activity(+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)+ )++ mock_client.complete.assert_called_once()++ assert result["verdict"] is True+ assert result.get("skipped") is not True+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_emit_evaluation_event_activity_allows_na_applicable(self, setup_data):