: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): answer manual eval run errors with DRF codes (#87758)
Bernat Torresfed791562090
diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.pyindex 95eea3a81cec..95605275241c 100644--- a/products/ai_observability/backend/api/evaluation_runs.py+++ b/products/ai_observability/backend/api/evaluation_runs.py@@ -8,6 +8,7 @@ import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schemafrom rest_framework import serializers, viewsets+from rest_framework.exceptions import APIException, NotFound, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -73,8 +74,7 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):to asynchronously execute the evaluation."""serializer = EvaluationRunRequestSerializer(data=request.data)- if not serializer.is_valid():- return Response({"error": serializer.errors}, status=400)+ serializer.is_valid(raise_exception=True)evaluation_id = str(serializer.validated_data["evaluation_id"])target_event_id = str(serializer.validated_data["target_event_id"])@@ -86,7 +86,7 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):try:evaluation = Evaluation.objects.get(id=evaluation_id, team_id=self.team_id, deleted=False)except Evaluation.DoesNotExist:- return Response({"error": f"Evaluation {evaluation_id} not found"}, status=404)+ raise NotFound(f"Evaluation {evaluation_id} not found")self.check_object_permissions(request, evaluation)@@ -95,14 +95,10 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# verdict with $ai_target_type "generation_uuid" under that evaluation's name — which then# counts towards its pass rate while being invisible on the trace or session it belongs to.if evaluation.target != EvaluationTarget.GENERATION.value:- return Response(- {- "error": (- f"This evaluation runs on the whole {evaluation.target}, so it can't be re-run against a "- "single generation."- )- },- status=400,+ raise ValidationError(+ f"This evaluation runs on the whole {evaluation.target}, so it can't be re-run against a "+ "single generation.",+ code="evaluation_target_mismatch",)# Fetch event data from ClickHouse using available keys@@ -126,14 +122,11 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):try:event_data = self._fetch_event_for_evaluation(where_clauses, params)except AIEventsExpiredError:- return Response(- {- "error": f"Event {target_event_id} is past the ai_events retention window and can no longer be evaluated"- },- status=404,+ raise NotFound(+ f"Event {target_event_id} is past the ai_events retention window and can no longer be evaluated")except AIEventsNotFoundError:- return Response({"error": f"Event {target_event_id} not found"}, status=404)+ raise NotFound(f"Event {target_event_id} not found")# Build workflow inputsinputs = RunEvaluationInputs(@@ -204,7 +197,9 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):target_event_id=target_event_id,error=str(e),)- return Response({"error": "Failed to start evaluation"}, status=500)+ # The frontend prefixes this with the action name, so "Failed to start evaluation" here+ # would read back as "Run evaluation failed: Failed to start evaluation".+ raise APIException("The evaluation service is unavailable. Try again in a moment.") from edef _fetch_event_for_evaluation(self, where_clauses: list[str], params: dict[str, object]) -> dict:"""Fetch the target event with its heavy AI columns from ai_events.diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.pyindex aae2ed30da23..7d0ff3752f62 100644--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py@@ -235,7 +235,10 @@ class TestEvaluationRunViewSet(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST- assert target in response.json()["error"]+ body = response.json()+ assert target in body["detail"]+ # Callers match on this code, so a rename is a breaking change and should fail here.+ assert body["code"] == "evaluation_target_mismatch"def test_create_evaluation_run_missing_params(self):"""Test creating evaluation run with missing parameters"""@@ -247,6 +250,9 @@ class TestEvaluationRunViewSet(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST+ body = response.json()+ assert body["attr"] == "target_event_id"+ assert body["type"] == "validation_error"def test_create_evaluation_run_different_team(self):"""Test creating evaluation run for evaluation from different team"""diff --git a/products/ai_observability/frontend/llmEvaluationExecutionLogic.test.ts b/products/ai_observability/frontend/llmEvaluationExecutionLogic.test.tsnew file mode 100644index 000000000000..018c06cfe648--- /dev/null+++ b/products/ai_observability/frontend/llmEvaluationExecutionLogic.test.ts@@ -0,0 +1,78 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { llmEvaluationExecutionLogic } from './llmEvaluationExecutionLogic'++// A guard keyed on the status alone lets all three pass silently, because the shared handler has+// no `detail` or `statusText` to render for them.+const NOTHING_FOR_THE_SHARED_HANDLER: [string, () => Response][] = [+ [+ 'a proxy answering in HTML',+ () => new Response('<html>Bad Request</html>', { status: 400, headers: { 'content-type': 'text/html' } }),+ ],+ ['a gateway answering with an empty body', () => new Response(null, { status: 502 })],+ [+ 'a body that could not be read',+ () => new Response('<!doctype html>', { status: 200, headers: { 'content-type': 'application/json' } }),+ ],+]++describe('llmEvaluationExecutionLogic', () => {+ let logic: ReturnType<typeof llmEvaluationExecutionLogic.build>+ let runResponse: [number, Record<string, unknown>] | Response++ beforeEach(() => {+ useMocks({+ post: {+ '/api/environments/:team_id/evaluation_runs/': () => runResponse,+ },+ })+ initKeaTests()+ logic = llmEvaluationExecutionLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ // A local toast here as well would show the user the same sentence twice.+ it('leaves a refused run to the shared handler', async () => {+ runResponse = [+ 400,+ {+ type: 'validation_error',+ code: 'evaluation_target_mismatch',+ detail: "This evaluation runs on the whole trace, so it can't be re-run against a single generation.",+ attr: null,+ },+ ]+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as any)++ await expectLogic(logic, () => {+ logic.actions.runEvaluation('eval-1', 'event-1', '2026-08-06T00:00:00Z', '$ai_generation')+ }).toDispatchActions(['runEvaluationFailure'])++ expect(toast.mock.calls).toEqual([+ [+ "Run evaluation failed: This evaluation runs on the whole trace, so it can't be re-run against a single generation.",+ ],+ ])+ })++ it.each(NOTHING_FOR_THE_SHARED_HANDLER)('answers %s', async (_label, buildResponse) => {+ runResponse = buildResponse()+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '' as any)++ await expectLogic(logic, () => {+ logic.actions.runEvaluation('eval-1', 'event-1', '2026-08-06T00:00:00Z', '$ai_generation')+ }).toDispatchActions(['runEvaluationFailure'])++ expect(toast.mock.calls).toEqual([['Failed to start evaluation']])+ })+})diff --git a/products/ai_observability/frontend/llmEvaluationExecutionLogic.ts b/products/ai_observability/frontend/llmEvaluationExecutionLogic.tsindex 219b6897736d..fe2c0cc10dfa 100644--- a/products/ai_observability/frontend/llmEvaluationExecutionLogic.ts+++ b/products/ai_observability/frontend/llmEvaluationExecutionLogic.ts@@ -1,7 +1,7 @@import { MakeLogicType, actions, connect, kea, path, reducers } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'@@ -131,7 +131,12 @@ export const llmEvaluationExecutionLogic = kea<llmEvaluationExecutionLogicType>(lemonToast.success('Evaluation started successfully')return response} catch (error) {- lemonToast.error('Failed to start evaluation')+ // `initKea`'s loader handler renders `detail` or `statusText`, so toasting+ // here as well would repeat it. A reply carrying neither leaves that+ // handler silent, which is the case this covers.+ if (!(error instanceof ApiError) || !(error.detail || error.statusText)) {+ lemonToast.error('Failed to start evaluation')+ }throw error}},