🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(shared): trace code eval dispatches (#14024)
Tobias Wochingerf1ac0082399f
diff --git a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.tsnew file mode 100644index 0000000000..ce31fb050d--- /dev/null+++ b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts@@ -0,0 +1,229 @@+import { SpanKind } from "@opentelemetry/api";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { AwsLambdaCodeEvalDispatcher } from "./awsLambdaCodeEvalDispatcher";+import type { DispatchInput } from "./codeEvalDispatcherTypes";++const mocks = vi.hoisted(() => {+ const span = {+ setAttribute: vi.fn(),+ setAttributes: vi.fn(),+ };++ return {+ span,+ instrumentAsync: vi.fn(async (_ctx, callback) => callback(span)),+ traceException: vi.fn(),+ };+});++vi.mock("../instrumentation", () => ({+ instrumentAsync: mocks.instrumentAsync,+ traceException: mocks.traceException,+}));++vi.mock("../logger", () => ({+ logger: {+ warn: vi.fn(),+ },+}));++const baseInput: DispatchInput = {+ scope: {+ organizationId: "org-1",+ projectId: "project-1",+ evaluatorId: "evaluator-1",+ },+ runtime: { language: "TYPESCRIPT" },+ execution: { jobExecutionId: "job-1" },+ code: { source: "function evaluate() {}" },+ payload: {+ observation: {+ input: null,+ output: null,+ metadata: null,+ },+ },+};++function expectSpanAttributes(attributes: Record<string, unknown>): void {+ expect(mocks.span.setAttributes).toHaveBeenCalledWith(+ expect.objectContaining(attributes),+ );+}++describe("AwsLambdaCodeEvalDispatcher observability", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("dispatches inside a dedicated trace with code evaluator context", async () => {+ const send = vi.fn().mockResolvedValue({+ StatusCode: 200,+ ExecutedVersion: "$LATEST",+ Payload: Buffer.from(+ JSON.stringify({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ }),+ ),+ $metadata: {+ requestId: "request-1",+ httpStatusCode: 200,+ attempts: 2,+ totalRetryDelay: 15,+ },+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await dispatcher.dispatch(baseInput);++ expect(mocks.instrumentAsync).toHaveBeenCalledWith(+ {+ name: "code-eval.dispatch.aws-lambda",+ spanKind: SpanKind.CLIENT,+ traceScope: "code-eval-dispatcher",+ startNewTrace: true,+ },+ expect.any(Function),+ );+ expectSpanAttributes({+ "eval.dispatcher.name": "aws-lambda",+ "eval.job_execution.id": "job-1",+ "eval.runner.language": "TYPESCRIPT",+ "eval.template.id": "evaluator-1",+ "langfuse.code_eval.lambda.function_name":+ "code-based-eval-executor-node",+ "langfuse.org.id": "org-1",+ "langfuse.project.id": "project-1",+ });+ expect(mocks.span.setAttribute).toHaveBeenCalledWith("eval.score.count", 1);+ expectSpanAttributes({+ "langfuse.code_eval.lambda.status_code": 200,+ "langfuse.code_eval.lambda.executed_version": "$LATEST",+ "aws.request_id": "request-1",+ "aws.http_status_code": 200,+ "aws.sdk.attempts": 2,+ "aws.sdk.total_retry_delay_ms": 15,+ });+ });++ it("records the original AWS SDK error before throwing the derived dispatcher error", async () => {+ const error = Object.assign(new Error("Rate exceeded"), {+ code: "TooManyRequests",+ $metadata: {+ requestId: "request-2",+ httpStatusCode: 429,+ attempts: 3,+ totalRetryDelay: 25,+ },+ });+ error.name = "TooManyRequestsException";+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn().mockRejectedValue(error) } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "LAMBDA_CONCURRENCY_LIMIT",+ retryable: true,+ });++ expect(mocks.traceException).toHaveBeenCalledWith(+ error,+ mocks.span,+ "code_eval.aws_lambda.original_error",+ );+ expectSpanAttributes({+ "langfuse.code_eval.error.code": "LAMBDA_CONCURRENCY_LIMIT",+ "langfuse.code_eval.error.retryable": true,+ });+ expectSpanAttributes({+ "langfuse.code_eval.aws_error.name": "TooManyRequestsException",+ "langfuse.code_eval.aws_error.code": "TooManyRequests",+ "aws.request_id": "request-2",+ "aws.http_status_code": 429,+ "aws.sdk.attempts": 3,+ "aws.sdk.total_retry_delay_ms": 25,+ });+ });++ it("records dispatch context and error code for preflight limit failures", async () => {+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn() } as any,+ });++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ code: { source: "a".repeat(256 * 1024 + 1) },+ }),+ ).rejects.toMatchObject({+ code: "SOURCE_TOO_LARGE",+ retryable: false,+ });++ expectSpanAttributes({+ "eval.dispatcher.name": "aws-lambda",+ "eval.job_execution.id": "job-1",+ "eval.runner.language": "TYPESCRIPT",+ "eval.template.id": "evaluator-1",+ "langfuse.org.id": "org-1",+ "langfuse.project.id": "project-1",+ });+ expectSpanAttributes({+ "langfuse.code_eval.error.code": "SOURCE_TOO_LARGE",+ "langfuse.code_eval.error.retryable": false,+ });+ });++ it("records the original Lambda FunctionError before throwing the derived user-facing error", async () => {+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: {+ send: vi.fn().mockResolvedValue({+ StatusCode: 200,+ FunctionError: "Handled",+ Payload: Buffer.from(+ JSON.stringify({+ errorMessage: "x is not defined",+ errorType: "ReferenceError",+ stackTrace: ["at evaluate (index.js:1:1)"],+ }),+ ),+ $metadata: {+ requestId: "request-3",+ httpStatusCode: 200,+ attempts: 1,+ totalRetryDelay: 0,+ },+ }),+ } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ message: "ReferenceError: x is not defined",+ retryable: false,+ });++ const tracedError = mocks.traceException.mock.calls[0][0];+ expect(tracedError).toMatchObject({+ name: "ReferenceError",+ message: "x is not defined",+ stack: "at evaluate (index.js:1:1)",+ });+ expect(mocks.traceException).toHaveBeenCalledWith(+ tracedError,+ mocks.span,+ "code_eval.aws_lambda.function_error",+ );+ expectSpanAttributes({+ "langfuse.code_eval.error.code": "USER_CODE_ERROR",+ "langfuse.code_eval.error.retryable": false,+ });+ expectSpanAttributes({+ "langfuse.code_eval.lambda.status_code": 200,+ "langfuse.code_eval.lambda.function_error": "Handled",+ "aws.request_id": "request-3",+ });+ });+});diff --git a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.ts b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.tsindex a14caa527a..27ba961d08 100644--- a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.ts+++ b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.ts@@ -3,7 +3,9 @@ import {LambdaClient,type InvokeCommandInput,} from "@aws-sdk/client-lambda";+import { SpanKind, type AttributeValue, type Span } from "@opentelemetry/api";import { z } from "zod";+import { instrumentAsync, traceException } from "../instrumentation";import { logger } from "../logger";import {assertDispatchInputWithinLimits,@@ -162,10 +164,40 @@ export class AwsLambdaCodeEvalDispatcher implements CodeEvalDispatcher {}async dispatch(input: DispatchInput): Promise<DispatchResult> {- const serializedPayload = assertDispatchInputWithinLimits(input);+ return instrumentAsync(+ {+ name: "code-eval.dispatch.aws-lambda",+ spanKind: SpanKind.CLIENT,+ traceScope: "code-eval-dispatcher",+ startNewTrace: true,+ },+ async (span) => this.dispatchWithTracing(input, span),+ );+ }++ private async dispatchWithTracing(+ input: DispatchInput,+ span: Span,+ ): Promise<DispatchResult> {const functionName = this.functionNameByLanguage[input.runtime.language];+ span.setAttributes({+ "eval.dispatcher.name": this.name,+ "eval.job_execution.id": input.execution.jobExecutionId,+ "eval.runner.language": input.runtime.language,+ "eval.template.id": input.scope.evaluatorId,+ "langfuse.code_eval.lambda.function_name": functionName,+ "langfuse.org.id": input.scope.organizationId,+ "langfuse.project.id": input.scope.projectId,+ });+try {+ const serializedPayload = assertDispatchInputWithinLimits(input);+ span.setAttribute(+ "langfuse.code_eval.payload.bytes",+ Buffer.byteLength(serializedPayload, "utf8"),+ );+const commandInput: InvokeCommandInput = {FunctionName: functionName,InvocationType: "RequestResponse",@@ -176,17 +208,30 @@ export class AwsLambdaCodeEvalDispatcher implements CodeEvalDispatcher {const response = await this.lambdaClient.send(new InvokeCommand(commandInput),);+ setSpanAttributes(span, {+ ...getAwsMetadataSpanAttributes(response.$metadata),+ "langfuse.code_eval.lambda.status_code": response.StatusCode,+ "langfuse.code_eval.lambda.executed_version": response.ExecutedVersion,+ "langfuse.code_eval.lambda.function_error": response.FunctionError,+ });// Lambda function errors come back as HTTP 200 with `FunctionError`// set; the SDK does NOT throw for these. SDK service exceptions// (throttling, auth, etc.) hit the outer catch instead.// https://docs.aws.amazon.com/lambda/latest/dg/invocation-errors.htmlif (response.FunctionError) {- throw classifyLambdaFunctionError({+ const dispatcherError = classifyLambdaFunctionError({functionName,functionError: response.FunctionError,payload: response.Payload,});+ traceLambdaFunctionError({+ span,+ functionName,+ functionError: response.FunctionError,+ payload: response.Payload,+ });+ throw dispatcherError;}if (!response.Payload) {@@ -199,21 +244,39 @@ export class AwsLambdaCodeEvalDispatcher implements CodeEvalDispatcher {);}- return parseLambdaResponsePayload({+ span.setAttribute(+ "langfuse.code_eval.lambda.response_payload.bytes",+ response.Payload.byteLength,+ );++ const result = parseLambdaResponsePayload({functionName,payload: response.Payload,});+ span.setAttribute("eval.score.count", result.scores.length);+ return result;} catch (error) {if (error instanceof CodeEvalDispatcherError) {+ setDispatcherErrorSpanAttributes(span, error);logDispatcherError({ functionName, error });throw error;}+ traceException(error, span, "code_eval.aws_lambda.original_error");+ const errorRecord = isRecord(error) ? error : null;+ setSpanAttributes(span, {+ ...getAwsMetadataSpanAttributes(errorRecord?.$metadata),+ "langfuse.code_eval.aws_error.name":+ error instanceof Error ? error.name : undefined,+ "langfuse.code_eval.aws_error.code":+ typeof errorRecord?.code === "string" ? errorRecord.code : undefined,+ });const awsError = classifyAwsLambdaError(error);const dispatcherError = new CodeEvalDispatcherError(`Failed to invoke code eval Lambda ${functionName}: ${error instanceof Error ? error.message : String(error)}`,{ ...awsError, cause: error },);+ setDispatcherErrorSpanAttributes(span, dispatcherError);logDispatcherError({ functionName, error: dispatcherError });throw dispatcherError;}@@ -237,6 +300,78 @@ function logDispatcherError(params: {);}+function setDispatcherErrorSpanAttributes(+ span: Span,+ error: CodeEvalDispatcherError,+): void {+ span.setAttributes({+ "langfuse.code_eval.error.code": error.code,+ "langfuse.code_eval.error.retryable": error.retryable,+ });+}++function getAwsMetadataSpanAttributes(+ metadata: unknown,+): Record<string, AttributeValue | undefined> {+ if (!isRecord(metadata)) return {};++ return {+ "aws.request_id":+ typeof metadata.requestId === "string" ? metadata.requestId : undefined,+ "aws.http_status_code":+ typeof metadata.httpStatusCode === "number"+ ? metadata.httpStatusCode+ : undefined,+ "aws.sdk.attempts":+ typeof metadata.attempts === "number" ? metadata.attempts : undefined,+ "aws.sdk.total_retry_delay_ms":+ typeof metadata.totalRetryDelay === "number"+ ? metadata.totalRetryDelay+ : undefined,+ };+}++function setSpanAttributes(+ span: Span,+ attributes: Record<string, AttributeValue | undefined>,+): void {+ const definedAttributes = Object.fromEntries(+ Object.entries(attributes).filter(([, value]) => value !== undefined),+ ) as Record<string, AttributeValue>;++ if (Object.keys(definedAttributes).length > 0) {+ span.setAttributes(definedAttributes);+ }+}++function traceLambdaFunctionError(params: {+ span: Span;+ functionName: string;+ functionError: string;+ payload: Uint8Array | undefined;+}): void {+ const errorPayload = parseLambdaErrorPayload(params.payload);+ const record = isRecord(errorPayload) ? errorPayload : null;++ const error = new Error(+ typeof record?.errorMessage === "string"+ ? record.errorMessage+ : `Code eval Lambda ${params.functionName} returned FunctionError=${params.functionError}`,+ );+ error.name =+ typeof record?.errorType === "string"+ ? record.errorType+ : "LambdaFunctionError";++ if (Array.isArray(record?.stackTrace)) {+ error.stack = record.stackTrace+ .filter((line) => typeof line === "string")+ .join("\n");+ }++ traceException(error, params.span, "code_eval.aws_lambda.function_error");+}+function classifyLambdaFunctionError(params: {functionName: string;functionError: string;