Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(evals): surface invalid code eval results (#13887)

Tobias Wochinger64d0d50432e0
diff --git a/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts b/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
index 3f0f2d3ffe..a34609f084 100644
--- a/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
+++ b/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
@@ -143,6 +143,7 @@ export const CodeEvalDispatcherErrorCodes = CodeEvalDispatcherErrorCode.enum;
export class CodeEvalDispatcherError extends Error {
public readonly code: CodeEvalDispatcherErrorCode;
public readonly retryable: boolean;
+ public readonly returnedResult?: unknown;
constructor(
message: string,
@@ -150,12 +151,14 @@ export class CodeEvalDispatcherError extends Error {
code: CodeEvalDispatcherErrorCode;
retryable?: boolean;
cause?: unknown;
+ returnedResult?: unknown;
},
) {
super(message, { cause: options.cause });
this.name = "CodeEvalDispatcherError";
this.code = options.code;
this.retryable = options.retryable ?? false;
+ this.returnedResult = options.returnedResult;
}
}
@@ -205,7 +208,10 @@ export function parseDispatchResult(result: unknown): DispatchResult {
if (!parsed.success) {
throw new CodeEvalDispatcherError(
`Invalid code eval result: ${parsed.error.message}`,
- { code: CodeEvalDispatcherErrorCodes.INVALID_RESULT },
+ {
+ code: CodeEvalDispatcherErrorCodes.INVALID_RESULT,
+ returnedResult: result,
+ },
);
}
diff --git a/packages/shared/src/server/evals/codeEvalExecution.ts b/packages/shared/src/server/evals/codeEvalExecution.ts
index d6a0e1f2ec..0529d1657d 100644
--- a/packages/shared/src/server/evals/codeEvalExecution.ts
+++ b/packages/shared/src/server/evals/codeEvalExecution.ts
@@ -72,6 +72,7 @@ export type CodeEvalUserVisibleError = {
code: CodeEvalUserVisibleErrorCode;
message: string;
retryable: boolean;
+ returnedResult?: unknown;
};
export class CodeEvalExecutionError extends Error {
@@ -129,6 +130,7 @@ function buildCodeEvalPayload(params: {
function getCodeEvalErrorDetails(error: unknown): {
name: string;
message: string;
+ returnedResult?: unknown;
code: CodeEvalUserVisibleErrorCode;
retryable: boolean;
} {
@@ -136,6 +138,7 @@ function getCodeEvalErrorDetails(error: unknown): {
return {
name: error.name,
message: error.message,
+ returnedResult: error.returnedResult,
code: error.code,
retryable: error.retryable,
};
@@ -175,6 +178,9 @@ export function getCodeEvalUserVisibleError(
code: details.code,
message: message ?? details.message,
retryable: details.retryable,
+ ...(details.returnedResult !== undefined
+ ? { returnedResult: details.returnedResult }
+ : {}),
};
}
@@ -240,6 +246,9 @@ export async function runCodeBasedEvaluationDispatch(params: {
code: visibleError.code,
message: visibleError.message,
retryable: errorDetails.retryable,
+ ...(visibleError.returnedResult !== undefined
+ ? { returnedResult: visibleError.returnedResult }
+ : {}),
};
const errorCodeForTrace = errorDetails.code;
diff --git a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts
index f4e6f9f4bf..6fe10e787f 100644
--- a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts
+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts
@@ -23,6 +23,7 @@ import { EvalTargetObject } from "@langfuse/shared";
vi.hoisted(() => {
process.env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED = "true";
+ process.env.LANGFUSE_CODE_EVAL_DISPATCHER = "insecure-local";
});
const orgIds: string[] = [];
@@ -345,6 +346,53 @@ maybe("evals.testRunCodeEval", () => {
});
});
+ it("returns invalid evaluator results for test-run debugging", async () => {
+ const { project, caller } = await prepare();
+ const observationId = randomUUID();
+ const traceId = randomUUID();
+ const startTime = new Date();
+ const template = await createCodeTemplate(
+ project.id,
+ `function evaluate() {
+ return { score: 1 };
+ }`,
+ );
+
+ await createEventsCh([
+ createEvent({
+ project_id: project.id,
+ trace_id: traceId,
+ span_id: observationId,
+ id: observationId,
+ start_time: startTime.getTime() * 1000,
+ }),
+ ]);
+
+ const response = await caller.evals.testRunCodeEval({
+ projectId: project.id,
+ evalTemplateId: template.id,
+ target: EvalTargetObject.EVENT,
+ scoreName: "unsaved-score",
+ observationId,
+ traceId,
+ startTime,
+ mapping: [],
+ });
+
+ expect(response).toEqual({
+ success: false,
+ error: {
+ code: "INVALID_RESULT",
+ message: expect.stringContaining(
+ "The evaluator returned an invalid result.",
+ ),
+ returnedResult: { score: 1 },
+ },
+ executionTraceId: expect.stringMatching(/^[0-9a-f]{32}$/),
+ executionTraceFromTimestamp: expect.any(Date),
+ });
+ });
+
it("passes experiment context to test runs", async () => {
const { project, caller } = await prepare();
const observationId = randomUUID();
diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.ts
index a49cf71d70..0ae975ef9d 100644
--- a/web/src/features/evals/server/codeEvalTestRun.ts
+++ b/web/src/features/evals/server/codeEvalTestRun.ts
@@ -9,7 +9,7 @@ import {
processEventBatch,
resolveConfiguredCodeEvalDispatcher,
runCodeBasedEvaluationDispatch,
- type CodeEvalUserVisibleErrorCode,
+ type CodeEvalUserVisibleError,
type DispatchResult,
type InternalTraceWriteInput,
} from "@langfuse/shared/src/server";
@@ -33,6 +33,8 @@ import {
isExperimentTarget,
} from "@/src/features/evals/utils/typeHelpers";
+type CodeEvalTestRunError = Omit<CodeEvalUserVisibleError, "retryable">;
+
export type CodeEvalTestRunResult =
| {
success: true;
@@ -42,10 +44,7 @@ export type CodeEvalTestRunResult =
}
| {
success: false;
- error: {
- code: CodeEvalUserVisibleErrorCode;
- message: string;
- };
+ error: CodeEvalTestRunError;
executionTraceId: string;
executionTraceFromTimestamp: Date;
};
@@ -181,15 +180,19 @@ async function runCodeEvalTestForObservation(params: {
return {
success: false,
- error: {
- code: dispatchOutcome.error.code,
- message: dispatchOutcome.error.message,
- },
+ error: toCodeEvalTestRunError(dispatchOutcome.error),
executionTraceId: dispatchOutcome.executionTraceId,
executionTraceFromTimestamp: dispatchOutcome.executionTraceFromTimestamp,
};
}
+function toCodeEvalTestRunError({
+ retryable: _retryable,
+ ...error
+}: CodeEvalUserVisibleError): CodeEvalTestRunError {
+ return error;
+}
+
async function getObservationForEvalByFilter(params: {
projectId: string;
target: EvalTargetObject;
diff --git a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
index 3db8656504..3922ab63c9 100644
--- a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
+++ b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
@@ -357,6 +357,36 @@ describe("AwsLambdaCodeEvalDispatcher", () => {
} satisfies Partial<CodeEvalDispatcherError>);
});
+ it("includes a small invalid Lambda result as structured error data", async () => {
+ const send = vi.fn().mockResolvedValue({
+ Payload: Buffer.from(JSON.stringify({ score: 1 })),
+ });
+ const dispatcher = new AwsLambdaCodeEvalDispatcher({
+ lambdaClient: { send } as any,
+ });
+
+ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({
+ code: "INVALID_RESULT",
+ retryable: false,
+ returnedResult: { score: 1 },
+ } satisfies Partial<CodeEvalDispatcherError>);
+ });
+
+ it("does not include a returned result for invalid JSON Lambda responses", async () => {
+ const send = vi.fn().mockResolvedValue({
+ Payload: Buffer.from("not-json"),
+ });
+ const dispatcher = new AwsLambdaCodeEvalDispatcher({
+ lambdaClient: { send } as any,
+ });
+
+ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({
+ code: "INVALID_RESULT",
+ retryable: false,
+ returnedResult: undefined,
+ } satisfies Partial<CodeEvalDispatcherError>);
+ });
+
it("rejects Lambda responses that exceed the wire byte-size limit", async () => {
// Build a response payload larger than the 256 KiB result cap. The
// guard inspects `response.Payload.byteLength` before any JSON parsing,
diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
index 39c8edf6eb..d2799431d8 100644
--- a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
@@ -6,6 +6,7 @@ import {
import {
CodeEvalDispatcherError,
CodeEvalDispatcherErrorCodes,
+ parseDispatchResult,
} from "../../../../../packages/shared/src/server/evals/codeEvalDispatcherTypes";
import { CodeEvalExecutionError } from "../../../../../packages/shared/src/server/evals/codeEvalExecution";
import { UnrecoverableError } from "../../../errors/UnrecoverableError";
@@ -482,6 +483,60 @@ describe("executeCodeBasedEvaluation", () => {
);
});
+ it("preserves a small invalid returned result in the structured trace error", async () => {
+ mocks.dispatcher.dispatch.mockImplementation(() =>
+ parseDispatchResult({ score: 1 }),
+ );
+
+ const promise = executeCodeBasedEvaluation({
+ projectId: "project-1",
+ organizationId: "org-1",
+ job: {
+ id: "job-1",
+ jobConfigurationId: "config-1",
+ jobInputTraceId: "trace-1",
+ jobInputObservationId: "obs-1",
+ jobInputDatasetItemId: null,
+ } as any,
+ config: { id: "config-1", scoreName: "default-score" } as any,
+ template: {
+ id: "template-1",
+ name: "Code evaluator",
+ type: EvalTemplateType.CODE,
+ version: 1,
+ sourceCode: "function evaluate() {}",
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ prompt: null,
+ outputDefinition: null,
+ } as any,
+ extractedVariables: [{ var: "input", value: "prompt" }],
+ executionMetadata: { job_execution_id: "job-1" },
+ });
+
+ await expect(promise).rejects.toThrow(UnrecoverableError);
+ await expect(promise).rejects.toThrow(
+ "The evaluator returned an invalid result.",
+ );
+
+ const trace = mocks.writeInternalTrace.mock.calls[0]?.[0];
+ const output = JSON.parse(trace.eventInputs[0].output);
+
+ expect(mocks.writeInternalTrace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ eventInputs: [
+ expect.objectContaining({
+ statusMessage: expect.not.stringContaining("returnedResult"),
+ metadata: expect.objectContaining({
+ error_message: expect.not.stringContaining("returnedResult"),
+ error_code: "INVALID_RESULT",
+ }),
+ }),
+ ],
+ }),
+ );
+ expect(output.error.returnedResult).toEqual({ score: 1 });
+ });
+
it("writes an actionable user-visible timeout error", async () => {
const rawTimeoutMessage =
"Function.TimedOut: Task timed out after 2 seconds";
diff --git a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
index c85dfb9536..f417c6dc08 100644
--- a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
+++ b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
@@ -251,4 +251,20 @@ describe("LocalCodeEvalDispatcher", () => {
retryable: false,
} satisfies Partial<CodeEvalDispatcherError>);
});
+
+ it("includes a small invalid returned result as structured error data", async () => {
+ const dispatcher = new LocalCodeEvalDispatcher();
+
+ await expect(
+ dispatcher.dispatch({
+ ...baseInput,
+ runtime: { language: "TYPESCRIPT" },
+ code: { source: `function evaluate() { return { score: 1 }; }` },
+ }),
+ ).rejects.toMatchObject({
+ code: "INVALID_RESULT",
+ retryable: false,
+ returnedResult: { score: 1 },
+ } satisfies Partial<CodeEvalDispatcherError>);
+ });
});