: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): run llm judge evals as sync activity (#62436)
Radu Raiceace0cfa42e28c
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex 417df7ae8b8c..4080bf8313cb 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -5,9 +5,11 @@ from typing import Any, NotRequired, Required, TypedDictfrom django.conf import settingsfrom django.db import models+from django.utils import timezoneimport structlogimport temporalio+import posthoganalyticsfrom pydantic import BaseModel, model_validatorfrom structlog.contextvars import bind_contextvarsfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicy@@ -25,7 +27,6 @@ from posthog.temporal.ai_observability.metrics import (increment_tokens,)from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.scoped import scoped_temporalfrom products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequestfrom products.ai_observability.backend.llm.config import get_eval_config@@ -528,14 +529,16 @@ def _build_errored_trace_result(allows_na: bool) -> LLMJudgeResult:@temporalio.activity.defn-@scoped_temporal()-async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:+def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:"""Execute LLM judge to evaluate the target event.Fetches API key configuration internally to avoid passing sensitive data between activities."""- from django.utils import timezone+ return _execute_llm_judge_activity(inputs)++def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:evaluation = inputs.evaluationevent_data = inputs.event_data@@ -644,7 +647,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeRprovider_key_id = model_configuration.get("provider_key_id")if provider_key_id:- provider_key = await database_sync_to_async(_get_provider_key_by_id)(provider_key_id)+ provider_key = _get_provider_key_by_id(provider_key_id)else:# Using PostHog key — enforce trial model allowlist and quotaif model not in TRIAL_MODEL_IDS:@@ -653,13 +656,13 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR{"error_type": "model_not_allowed", "model": model},non_retryable=True,)- await database_sync_to_async(_check_trial_quota)()+ _check_trial_quota()provider_key = Noneelse:# TODO(llma): Remove after migration completes - legacy evals without model_configurationprovider = "openai"model = DEFAULT_JUDGE_MODEL- provider_key = await database_sync_to_async(_get_legacy_provider_key)()+ provider_key = _get_legacy_provider_key()is_byok = provider_key is not Nonekey_id = str(provider_key.id) if provider_key else Nonediff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex c75b9c1a3f6a..7e43efef8d65 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -103,9 +103,8 @@ class TestRunEvaluationWorkflow:assert result["output_type"] == "boolean"assert result["output_config"] == {"allows_na": False}- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity(self, setup_data):+ def test_execute_llm_judge_activity(self, setup_data):"""Test LLM judge execution with realistic message array format"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -140,9 +139,7 @@ class TestRunEvaluationWorkflow: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)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))assert result["verdict"] is Trueassert result["reasoning"] == "The answer is correct"@@ -270,9 +267,8 @@ class TestRunEvaluationWorkflow:assert parsed.evaluation_id == "eval-123"assert parsed.event_data == event_data- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data):+ def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data):"""Test LLM judge execution with allows_na=True when applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -306,18 +302,15 @@ class TestRunEvaluationWorkflow: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)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))assert result["verdict"] is Trueassert result["applicable"] is Trueassert result["reasoning"] == "The answer is correct"assert result["allows_na"] is True- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data):+ def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data):"""Test LLM judge execution with allows_na=True when not applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -353,9 +346,7 @@ class TestRunEvaluationWorkflow: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)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))assert result["verdict"] is Noneassert result["applicable"] is False@@ -370,9 +361,8 @@ class TestRunEvaluationWorkflow: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):+ 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 ofproducing a verdict against an empty Output (which historically defaulted to true)."""evaluation_obj = setup_data["evaluation"]@@ -398,9 +388,7 @@ class TestRunEvaluationWorkflow:)with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:- result = await execute_llm_judge_activity(- ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))mock_client_class.assert_not_called()@@ -417,9 +405,8 @@ class TestRunEvaluationWorkflow:assert "model" not in resultassert "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):+ 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"]@@ -443,9 +430,7 @@ class TestRunEvaluationWorkflow:)with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:- result = await execute_llm_judge_activity(- ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))mock_client_class.assert_not_called()@@ -463,11 +448,8 @@ class TestRunEvaluationWorkflow: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- ):+ 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"]@@ -500,9 +482,7 @@ class TestRunEvaluationWorkflow: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)- )+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))mock_client.complete.assert_called_once()@@ -620,9 +600,8 @@ class TestRunEvaluationWorkflow:assert fields["status_reason"]["after"] == "trial_limit_reached"assert logs[0].is_system is True- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_successful_execution_does_not_disable_evaluation(self, setup_data):+ def test_successful_execution_does_not_disable_evaluation(self, setup_data):evaluation = setup_data["evaluation"]team = setup_data["team"]@@ -653,14 +632,13 @@ class TestRunEvaluationWorkflow:mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)mock_client.complete.return_value = mock_response- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation_dict, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation_dict, event_data=event_data))- await sync_to_async(evaluation.refresh_from_db)()+ evaluation.refresh_from_db()assert evaluation.enabled is True- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity_parse_error_raises_non_retryable(self, setup_data):+ def test_execute_llm_judge_activity_parse_error_raises_non_retryable(self, setup_data):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -690,7 +668,7 @@ class TestRunEvaluationWorkflow:)with pytest.raises(ApplicationError, match="Failed to parse structured output") as exc_info:- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))assert exc_info.value.non_retryable is Trueassert exc_info.value.details[0] == {"error_type": "parse_error"}@@ -703,9 +681,8 @@ class TestRunEvaluationWorkflow:pytest.param(TimeoutError("read timeout"), "TimeoutError", id="timeout_error"),],)- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity_unhandled_exception_uses_class_name(+ def test_execute_llm_judge_activity_unhandled_exception_uses_class_name(self, raised_exception: Exception, expected_label: str, setup_data):evaluation_obj = setup_data["evaluation"]@@ -731,13 +708,12 @@ class TestRunEvaluationWorkflow:mock_client.complete.side_effect = raised_exceptionwith pytest.raises(type(raised_exception)):- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))mock_increment_errors.assert_called_once_with(expected_label, provider="openai")- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data):+ def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data):team = setup_data["team"]evaluation = {@@ -758,7 +734,7 @@ class TestRunEvaluationWorkflow:event_data = create_mock_event_data(team.id)with pytest.raises(ApplicationError, match="not available on the trial plan") as exc_info:- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))assert exc_info.value.non_retryable is Trueassert exc_info.value.details[0]["error_type"] == "model_not_allowed"@@ -1336,9 +1312,8 @@ class TestJudgePromptAssembly:regressions in section ordering, tool catalog inclusion, and tool_call_idcorrelation that the unit tests for the helpers can't catch alone."""- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_prompt_contains_input_tools_and_output_sections_in_order(self, setup_data):+ def test_prompt_contains_input_tools_and_output_sections_in_order(self, setup_data):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]evaluation = {@@ -1384,7 +1359,7 @@ class TestJudgePromptAssembly:mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)mock_client.complete.return_value = mock_response- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))completion_request = mock_client.complete.call_args[0][0]user_prompt = completion_request.messages[0]["content"]@@ -1403,9 +1378,8 @@ class TestJudgePromptAssembly:assert "- send_email: Send an email." in user_promptassert "- lookup_user: Look up a user." in user_prompt- @pytest.mark.asyncio@pytest.mark.django_db(transaction=True)- async def test_prompt_omits_tools_section_when_catalog_absent(self, setup_data):+ def test_prompt_omits_tools_section_when_catalog_absent(self, setup_data):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]evaluation = {@@ -1433,7 +1407,7 @@ class TestJudgePromptAssembly:mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)mock_client.complete.return_value = mock_response- await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))+ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))user_prompt = mock_client.complete.call_args[0][0].messages[0]["content"]assert "Tools available:" not in user_prompt