🪢 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
fix(evals): prevent llm-as-a-judge queue stalls (#13037)
Hassieb Pakzad2e94ebfe4b3f
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex c65ac9a41f..e217ccd727 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -43,7 +43,11 @@ import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";import { ProxyAgent } from "undici";import { getInternalTracingHandler } from "./getInternalTracingHandler";import { decrypt } from "../../encryption";-import { decryptAndParseExtraHeaders } from "./utils";+import {+ decryptAndParseExtraHeaders,+ executeWithRuntimeTimeout,+ RUNTIME_TIMEOUT_ADAPTERS,+} from "./utils";import { logger } from "../logger";import { LLMCompletionError } from "./errors";@@ -453,6 +457,19 @@ export async function fetchLLMCompletion(metadata: traceSinkParams?.metadata,};+ const runtimeTimeoutEnabled = RUNTIME_TIMEOUT_ADAPTERS.has(+ modelParams.adapter,+ );+ const runtimeTimeoutController = runtimeTimeoutEnabled+ ? new AbortController()+ : undefined;+ const runConfigWithTimeout = runtimeTimeoutController+ ? {+ ...runConfig,+ signal: runtimeTimeoutController.signal,+ }+ : runConfig;+const thinkingTypes = getThinkingBlockTypes(modelParams.adapter);try {@@ -460,17 +477,24 @@ export async function fetchLLMCompletion(if (params.structuredOutputSchema) {// Thinking-capable adapters may produce reasoning blocks that corrupt JSON schema// parsing. Force function calling so the parser reads from tool_calls instead.+ const structuredOutputSchema = params.structuredOutputSchema;const structuredOutputConfig =thinkingTypes != null? { method: "functionCalling" as const }: undefined;- const structuredOutput = await (chatModel as ChatOpenAI)- .withStructuredOutput(- params.structuredOutputSchema,- structuredOutputConfig,- )- .invoke(finalMessages, runConfig);+ const structuredOutput = await executeWithRuntimeTimeout({+ enabled: runtimeTimeoutEnabled,+ timeoutMs,+ abortController: runtimeTimeoutController,+ operation: () =>+ (chatModel as ChatOpenAI)+ .withStructuredOutput(+ structuredOutputSchema,+ structuredOutputConfig,+ )+ .invoke(finalMessages, runConfigWithTimeout),+ });return structuredOutput;}@@ -481,9 +505,15 @@ export async function fetchLLMCompletion(function: tool,}));- const result = await chatModel- .bindTools(langchainTools)- .invoke(finalMessages, runConfig);+ const result = await executeWithRuntimeTimeout({+ enabled: runtimeTimeoutEnabled,+ timeoutMs,+ abortController: runtimeTimeoutController,+ operation: () =>+ chatModel+ .bindTools(langchainTools)+ .invoke(finalMessages, runConfigWithTimeout),+ });// For thinking adapters, strip reasoning blocks from content before parsing// so ToolCallResponseSchema can validate. Extract reasoning separately.@@ -512,20 +542,37 @@ export async function fetchLLMCompletion(}if (streaming)- return chatModel- .pipe(new BytesOutputParser())- .stream(finalMessages, runConfig);+ return await executeWithRuntimeTimeout({+ enabled: runtimeTimeoutEnabled,+ timeoutMs,+ abortController: runtimeTimeoutController,+ operation: () =>+ chatModel+ .pipe(new BytesOutputParser())+ .stream(finalMessages, runConfigWithTimeout),+ });// content with thinking blocks can't be handled by StringOutputParser// Invoke model directly and extract text + reasoning separately.if (thinkingTypes != null) {- const aiMessage = await chatModel.invoke(finalMessages, runConfig);+ const aiMessage = await executeWithRuntimeTimeout({+ enabled: runtimeTimeoutEnabled,+ timeoutMs,+ abortController: runtimeTimeoutController,+ operation: () => chatModel.invoke(finalMessages, runConfigWithTimeout),+ });return extractCompletionWithReasoning(aiMessage, thinkingTypes);}- const completion = await chatModel- .pipe(new StringOutputParser())- .invoke(finalMessages, runConfig);+ const completion = await executeWithRuntimeTimeout({+ enabled: runtimeTimeoutEnabled,+ timeoutMs,+ abortController: runtimeTimeoutController,+ operation: () =>+ chatModel+ .pipe(new StringOutputParser())+ .invoke(finalMessages, runConfigWithTimeout),+ });return completion;} catch (e) {diff --git a/packages/shared/src/server/llm/utils.ts b/packages/shared/src/server/llm/utils.tsindex 896c37d8db..ffb9e46e0c 100644--- a/packages/shared/src/server/llm/utils.ts+++ b/packages/shared/src/server/llm/utils.ts@@ -1,9 +1,49 @@import { z } from "zod";import { decrypt } from "../../encryption";+import { LLMAdapter } from "./types";const ExtraHeaderSchema = z.record(z.string(), z.string());+export const RUNTIME_TIMEOUT_ADAPTERS = new Set([+ LLMAdapter.VertexAI,+ LLMAdapter.GoogleAIStudio,+]);++export async function executeWithRuntimeTimeout<T>({+ enabled,+ timeoutMs,+ abortController,+ operation,+}: {+ enabled: boolean;+ timeoutMs: number;+ abortController?: AbortController;+ operation: () => Promise<T>;+}): Promise<T> {+ if (!enabled) {+ return operation();+ }++ const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);++ let timeoutId: ReturnType<typeof setTimeout> | undefined;++ try {+ return await Promise.race([+ operation(),+ new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => {+ abortController?.abort(timeoutError);+ reject(timeoutError);+ }, timeoutMs);+ }),+ ]);+ } finally {+ if (timeoutId) clearTimeout(timeoutId);+ }+}+export function decryptAndParseExtraHeaders(extraHeaders: string | null | undefined,) {diff --git a/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts b/worker/src/__tests__/fetchLLMCompletionTimeout.test.tsnew file mode 100644index 0000000000..53bf85ec99--- /dev/null+++ b/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts@@ -0,0 +1,163 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const invokeMock = vi.fn();+const streamMock = vi.fn();+const chatVertexAIConstructorMock = vi.fn().mockImplementation(() => ({+ invoke: invokeMock,+ pipe: vi.fn().mockReturnValue({+ stream: streamMock,+ }),+}));+const VERTEXAI_USE_DEFAULT_CREDENTIALS = "__VERTEXAI_DEFAULT_CREDENTIALS__";++process.env.CLICKHOUSE_URL ??= "http://localhost:8123";+process.env.CLICKHOUSE_USER ??= "default";+process.env.CLICKHOUSE_PASSWORD ??= "password";+process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";+process.env.ENCRYPTION_KEY ??=+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";++class MockLLMCompletionError extends Error {+ responseStatusCode: number;+ isRetryable: boolean;+ blockReason: null;++ constructor(params: {+ message: string;+ responseStatusCode?: number;+ isRetryable?: boolean;+ }) {+ super(params.message);+ this.name = "LLMCompletionError";+ this.responseStatusCode = params.responseStatusCode ?? 500;+ this.isRetryable = params.isRetryable ?? false;+ this.blockReason = null;+ }++ shouldBlockConfig() {+ return false;+ }++ getEvaluatorBlockReason() {+ return null;+ }+}++describe("fetchLLMCompletion runtime timeouts", () => {+ let originalTimeout: number;+ let originalCloudRegion: string | undefined;+ let env: typeof import("../../../packages/shared/src/env").env;+ let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;+ let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;++ beforeEach(async () => {+ vi.useFakeTimers();+ invokeMock.mockReset();+ streamMock.mockReset();+ chatVertexAIConstructorMock.mockClear();+ vi.resetModules();+ originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ vi.doMock("@langchain/google-vertexai", () => ({+ ChatVertexAI: chatVertexAIConstructorMock,+ }));+ vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({+ LLMCompletionError: MockLLMCompletionError,+ }));++ ({ env } = await import("../../../packages/shared/src/env"));+ ({ encrypt } = await import("../../../packages/shared/src/encryption"));+ ({ fetchLLMCompletion } =+ await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));++ originalTimeout = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;+ });++ afterEach(() => {+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = originalTimeout;+ if (originalCloudRegion === undefined) {+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ } else {+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ }+ vi.useRealTimers();+ });++ it("wraps non-streaming VertexAI timeouts as non-retryable LLMCompletionError", async () => {+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = 25;++ invokeMock.mockImplementation(() => new Promise(() => {}));++ const completionPromise = fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "What is 2+2? Answer only with the number.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "google-vertex-ai",+ adapter: "google-vertex-ai",+ model: "gemini-2.0-flash",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(VERTEXAI_USE_DEFAULT_CREDENTIALS),+ config: null,+ },+ });++ const completionRejection = expect(completionPromise).rejects.toMatchObject(+ {+ name: "LLMCompletionError",+ message: "Request timed out after 25ms",+ isRetryable: false,+ },+ );++ await vi.runOnlyPendingTimersAsync();+ await completionRejection;+ });++ it("wraps streaming VertexAI timeouts as non-retryable LLMCompletionError", async () => {+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = 25;++ streamMock.mockImplementation(() => new Promise(() => {}));++ const completionPromise = fetchLLMCompletion({+ streaming: true,+ messages: [+ {+ role: "user",+ content: "Stream the answer.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "google-vertex-ai",+ adapter: "google-vertex-ai",+ model: "gemini-2.0-flash",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(VERTEXAI_USE_DEFAULT_CREDENTIALS),+ config: null,+ },+ });++ const completionRejection = expect(completionPromise).rejects.toMatchObject(+ {+ name: "LLMCompletionError",+ message: "Request timed out after 25ms",+ isRetryable: false,+ },+ );++ await vi.runOnlyPendingTimersAsync();+ await completionRejection;+ });+});diff --git a/worker/src/features/utils/retry-handler.test.ts b/worker/src/features/utils/retry-handler.test.tsnew file mode 100644index 0000000000..13b0ec8d04--- /dev/null+++ b/worker/src/features/utils/retry-handler.test.ts@@ -0,0 +1,108 @@+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";++vi.mock("@langfuse/shared/src/server", () => ({+ convertQueueNameToMetricName: vi.fn().mockImplementation((name) => name),+ logger: {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ recordDistribution: vi.fn(),+}));++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ datasetRuns: {+ findFirstOrThrow: vi.fn(),+ },+ jobExecution: {+ findFirstOrThrow: vi.fn(),+ },+ },+}));++vi.mock("crypto", () => ({+ randomUUID: vi.fn().mockReturnValue("retry-job-id"),+}));++import { prisma } from "@langfuse/shared/src/db";+import { logger, recordDistribution } from "@langfuse/shared/src/server";+import { retryLLMRateLimitError } from "./retry-handler";++describe("retryLLMRateLimitError", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date(),+ });+ });++ it("returns queue_unavailable instead of throwing when queue.add fails", async () => {+ const add = vi.fn().mockRejectedValue(new Error("redis unavailable"));++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date(),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ delayFn: () => 30_000,+ },+ );++ expect(result).toEqual({+ outcome: "queue_unavailable",+ });+ expect(add).toHaveBeenCalledOnce();+ expect(logger.warn).toHaveBeenCalledWith(+ expect.stringContaining("Failed to enqueue retry job"),+ expect.any(Error),+ );+ expect(recordDistribution).toHaveBeenCalledTimes(2);+ });++ it("returns queue_unavailable instead of throwing when age lookup fails", async () => {+ (prisma.jobExecution.findFirstOrThrow as Mock).mockRejectedValue(+ new Error("database unavailable"),+ );++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date(),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add: vi.fn() },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ delayFn: () => 30_000,+ },+ );++ expect(result).toEqual({+ outcome: "queue_unavailable",+ });+ expect(logger.error).toHaveBeenCalledWith(+ expect.stringContaining("Failed to handle 429 retry"),+ expect.any(Error),+ );+ expect(recordDistribution).not.toHaveBeenCalled();+ });+});diff --git a/worker/src/features/utils/retry-handler.ts b/worker/src/features/utils/retry-handler.tsindex 17228e729f..b28023fb28 100644--- a/worker/src/features/utils/retry-handler.ts+++ b/worker/src/features/utils/retry-handler.ts@@ -28,14 +28,23 @@ interface RetryConfig {delayFn: (attempt: number) => number;}+export type RetryScheduleResult =+ | {+ outcome: "scheduled";+ delay: number;+ retryBaggage: RetryBaggage;+ }+ | {+ outcome: "skipped";+ reason: "too_old";+ }+ | {+ outcome: "queue_unavailable";+ };+/*** Handles rate limiting and retry logic for queue jobs* Automatically retries jobs that fail with 429/5xx errors unless they're older than 24h- *- * @param error - The error that occurred- * @param job - The job that failed- * @param config - Retry configuration- * @returns true if retry was handled and job was added to the queue, false if regular processing should continue*/export async function retryLLMRateLimitError(job: {@@ -46,7 +55,7 @@ export async function retryLLMRateLimitError(};},config: RetryConfig,-): Promise<void> {+): Promise<RetryScheduleResult> {try {const jobId = job.data.payload[config.idField];@@ -67,65 +76,98 @@ export async function retryLLMRateLimitError(`Job ${jobId} is rate limited for more than 24h. Stop retrying.`,);- return; // Don't retry+ return {+ outcome: "skipped",+ reason: "too_old",+ };}// Retry the job with delayconst delay = config.delayFn((job.data.retryBaggage?.attempt ?? 0) + 1);- const retryBaggage: RetryBaggage | undefined = job.data.retryBaggage+ const retryBaggage: RetryBaggage = job.data.retryBaggage? {originalJobTimestamp: new Date(job.data.retryBaggage.originalJobTimestamp,),attempt: job.data.retryBaggage.attempt + 1,}- : undefined;+ : {+ originalJobTimestamp: new Date(job.data.timestamp),+ attempt: 1,+ };- // Record retry attempt distribution per queue- if (retryBaggage) {- recordDistribution(- `${convertQueueNameToMetricName(config.queueName)}.retries`,- retryBaggage.attempt,- {- queue: config.queueName,- },+ if (!config.queue) {+ logger.warn(+ `Retry queue ${config.queueName} is not available for job ${jobId}. Falling back to normal error handling.`,);- // Record delay distribution per queue- recordDistribution(- `${convertQueueNameToMetricName(config.queueName)}.total_retry_delay_ms`,- new Date().getTime() -- new Date(retryBaggage.originalJobTimestamp).getTime(), // this is the total delay- {- queue: config.queueName,- unit: "milliseconds",- },- );+ return {+ outcome: "queue_unavailable",+ };}- logger.info(- `Job ${jobId} is rate limited. Retrying in ${delay}ms. Attempt: ${retryBaggage?.attempt}. Total delay: ${retryBaggage ? new Date().getTime() - new Date(retryBaggage?.originalJobTimestamp).getTime() : "unavailable"}ms.`,+ // Record retry attempt distribution per queue+ recordDistribution(+ `${convertQueueNameToMetricName(config.queueName)}.retries`,+ retryBaggage.attempt,+ {+ queue: config.queueName,+ },);- await config.queue?.add(- config.queueName,+ // Record delay distribution per queue+ recordDistribution(+ `${convertQueueNameToMetricName(config.queueName)}.total_retry_delay_ms`,+ new Date().getTime() -+ new Date(retryBaggage.originalJobTimestamp).getTime(), // this is the total delay{- name: config.jobName,- id: randomUUID(),- timestamp: new Date(),- payload: job.data.payload,- retryBaggage: retryBaggage,+ queue: config.queueName,+ unit: "milliseconds",},- { delay },);++ logger.info(+ `Job ${jobId} is rate limited. Retrying in ${delay}ms. Attempt: ${retryBaggage?.attempt}. Total delay: ${retryBaggage ? new Date().getTime() - new Date(retryBaggage?.originalJobTimestamp).getTime() : "unavailable"}ms.`,+ );++ try {+ await config.queue.add(+ config.queueName,+ {+ name: config.jobName,+ id: randomUUID(),+ timestamp: new Date(),+ payload: job.data.payload,+ retryBaggage: retryBaggage,+ },+ { delay },+ );+ } catch (addErr) {+ logger.warn(+ `Failed to enqueue retry job for ${jobId}. Falling back to normal error handling.`,+ addErr,+ );++ return {+ outcome: "queue_unavailable",+ };+ }++ return {+ outcome: "scheduled",+ delay,+ retryBaggage,+ };} catch (innerErr) {const jobId = job.data.payload[config.idField];logger.error(- `Failed to handle 429 retry for ${jobId}. Continuing regular processing.`,+ `Failed to handle 429 retry for ${jobId}. Falling back to caller error handling.`,innerErr,);- throw innerErr;+ return {+ outcome: "queue_unavailable",+ };}}diff --git a/worker/src/queues/__tests__/experimentQueueProcessor.test.ts b/worker/src/queues/__tests__/experimentQueueProcessor.test.tsnew file mode 100644index 0000000000..387f653b34--- /dev/null+++ b/worker/src/queues/__tests__/experimentQueueProcessor.test.ts@@ -0,0 +1,90 @@+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";+import { Job } from "bullmq";++vi.mock("@langfuse/shared/src/server", () => ({+ ExperimentCreateQueue: {+ getInstance: vi.fn().mockReturnValue({+ add: vi.fn(),+ }),+ },+ QueueJobs: {+ ExperimentCreateJob: "experiment-create-job",+ },+ QueueName: {+ ExperimentCreate: "experiment-create-queue",+ },+ isLLMCompletionError: vi.fn(),+ logger: {+ error: vi.fn(),+ },+ traceException: vi.fn(),+}));++vi.mock("../../features/utils", () => ({+ retryLLMRateLimitError: vi.fn(),+}));++vi.mock("../../features/experiments/experimentServiceClickhouse", () => ({+ createExperimentJobClickhouse: vi.fn(),+}));++vi.mock("../../errors/UnrecoverableError", async () => {+ const actual = await vi.importActual("../../errors/UnrecoverableError");+ return {+ ...actual,+ isUnrecoverableError: vi.fn(),+ };+});++import { isLLMCompletionError } from "@langfuse/shared/src/server";+import { createExperimentJobClickhouse } from "../../features/experiments/experimentServiceClickhouse";+import { retryLLMRateLimitError } from "../../features/utils";+import { experimentCreateQueueProcessor } from "../experimentQueue";+import { isUnrecoverableError } from "../../errors/UnrecoverableError";++describe("experimentCreateQueueProcessor", () => {+ const createMockJob = (): Job<any> =>+ ({+ data: {+ payload: {+ projectId: "project-id",+ runId: "run-id",+ },+ },+ }) as Job<any>;++ beforeEach(() => {+ vi.clearAllMocks();+ (isLLMCompletionError as Mock).mockReturnValue(false);+ (isUnrecoverableError as Mock).mockReturnValue(false);+ });++ it("rethrows retryable LLM errors when the retry queue is unavailable", async () => {+ const llmError = new Error("Rate limit exceeded");+ (llmError as Error & { isRetryable: boolean }).isRetryable = true;+ (createExperimentJobClickhouse as Mock).mockRejectedValue(llmError);+ (isLLMCompletionError as Mock).mockReturnValue(true);+ (retryLLMRateLimitError as Mock).mockResolvedValue({+ outcome: "queue_unavailable",+ });++ await expect(+ experimentCreateQueueProcessor(createMockJob()),+ ).rejects.toThrow("Rate limit exceeded");++ expect(retryLLMRateLimitError).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ payload: expect.objectContaining({+ projectId: "project-id",+ runId: "run-id",+ }),+ }),+ }),+ expect.objectContaining({+ table: "dataset_runs",+ idField: "runId",+ }),+ );+ });+});diff --git a/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.tsindex 9e7d652924..d8c29ae3ea 100644--- a/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts+++ b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts@@ -1,10 +1,38 @@-import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";+import {+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";import { Job } from "bullmq";-import { JobExecutionStatus } from "@prisma/client";-import { llmAsJudgeExecutionQueueProcessorBuilder } from "../evalQueue";-import { QueueName, type TQueueJobTypes } from "@langfuse/shared/src/server";import { UnrecoverableError } from "../../errors/UnrecoverableError";+const QueueName = {+ LLMAsJudgeExecution: "llm-as-a-judge-execution-queue",+ EvaluationExecutionSecondaryQueue: "evaluation-execution-secondary-queue",+} as const;++const QueueJobs = {+ LLMAsJudgeExecution: "llm-as-a-judge-execution-job",+ EvaluationExecution: "evaluation-execution-job",+} as const;++const JobExecutionStatus = {+ DELAYED: "DELAYED",+ ERROR: "ERROR",+} as const;++vi.mock("@langfuse/shared", () => ({+ removeEmptyEnvVariables: <T>(value: T) => value,+ JobExecutionStatus: {+ DELAYED: "DELAYED",+ ERROR: "ERROR",+ },+}));+// Mock prismavi.mock("@langfuse/shared/src/db", () => ({prisma: {@@ -20,10 +48,20 @@ vi.mock("../../features/evaluation/observationEval", () => ({}));// Mock logger and span-vi.mock("@langfuse/shared/src/server", async () => {- const actual = await vi.importActual("@langfuse/shared/src/server");+vi.mock("@langfuse/shared/src/server", () => {+ const getQueueInstance = vi.fn().mockReturnValue({+ add: vi.fn(),+ });+return {- ...actual,+ QueueName: {+ LLMAsJudgeExecution: "llm-as-a-judge-execution-queue",+ EvaluationExecutionSecondaryQueue: "evaluation-execution-secondary-queue",+ },+ QueueJobs: {+ LLMAsJudgeExecution: "llm-as-a-judge-execution-job",+ EvaluationExecution: "evaluation-execution-job",+ },logger: {debug: vi.fn(),info: vi.fn(),@@ -34,10 +72,14 @@ vi.mock("@langfuse/shared/src/server", async () => {getCurrentSpan: vi.fn().mockReturnValue({setAttribute: vi.fn(),}),+ EvalExecutionQueue: {+ getInstance: vi.fn(),+ },+ SecondaryEvalExecutionQueue: {+ getInstance: vi.fn(),+ },LLMAsJudgeExecutionQueue: {- getInstance: vi.fn().mockReturnValue({- add: vi.fn(),- }),+ getInstance: getQueueInstance,},isLLMCompletionError: vi.fn(),};@@ -73,12 +115,18 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {const jobExecutionId = "job-exec-456";const observationS3Path = "evals/test/observation.json";const queueName = `${QueueName.LLMAsJudgeExecution}-1`;- const llmAsJudgeExecutionQueueProcessor =- llmAsJudgeExecutionQueueProcessorBuilder(queueName);-- const createMockJob = (- overrides: Partial<TQueueJobTypes[QueueName.LLMAsJudgeExecution]> = {},- ): Job<TQueueJobTypes[QueueName.LLMAsJudgeExecution]> => {+ let llmAsJudgeExecutionQueueProcessor: (+ job: Job<{+ payload: {+ projectId: string;+ jobExecutionId: string;+ observationS3Path: string;+ };+ retryBaggage?: { attempt: number };+ }>,+ ) => Promise<unknown>;++ const createMockJob = (overrides: Record<string, unknown> = {}): Job<any> => {return {data: {id: "queue-job-123",@@ -92,9 +140,16 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {retryBaggage: { attempt: 0 },...overrides,},- } as unknown as Job<TQueueJobTypes[QueueName.LLMAsJudgeExecution]>;+ } as Job<any>;};+ beforeAll(async () => {+ const { llmAsJudgeExecutionQueueProcessorBuilder } =+ await import("../evalQueue");+ llmAsJudgeExecutionQueueProcessor =+ llmAsJudgeExecutionQueueProcessorBuilder(queueName);+ });+beforeEach(() => {vi.clearAllMocks();(isLLMCompletionError as Mock).mockReturnValue(false);@@ -146,6 +201,9 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {// Mark as retryable(rateLimitError as unknown as { isRetryable: boolean }).isRetryable =true;+ (retryLLMRateLimitError as Mock).mockResolvedValue({+ outcome: "scheduled",+ });const job = createMockJob();await llmAsJudgeExecutionQueueProcessor(job);@@ -180,6 +238,9 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {true;(processObservationEval as Mock).mockRejectedValue(rateLimitError);(isLLMCompletionError as Mock).mockReturnValue(true);+ (retryLLMRateLimitError as Mock).mockResolvedValue({+ outcome: "scheduled",+ });const job = createMockJob();@@ -188,6 +249,61 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {llmAsJudgeExecutionQueueProcessor(job),).resolves.not.toThrow();});++ it("should set ERROR when retryable LLM errors are not re-enqueued", async () => {+ const rateLimitError = new Error("Rate limit exceeded");+ (processObservationEval as Mock).mockRejectedValue(rateLimitError);+ (isLLMCompletionError as Mock).mockReturnValue(true);+ (rateLimitError as unknown as { isRetryable: boolean }).isRetryable =+ true;+ (retryLLMRateLimitError as Mock).mockResolvedValue({+ outcome: "skipped",+ reason: "too_old",+ });++ const job = createMockJob();+ await llmAsJudgeExecutionQueueProcessor(job);++ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: {+ id: jobExecutionId,+ projectId,+ },+ data: expect.objectContaining({+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "Rate limit exceeded",+ executionTraceId: "test-trace-id",+ }),+ });+ });++ it("should set ERROR when the retry queue is unavailable", async () => {+ const rateLimitError = new Error("Rate limit exceeded");+ (processObservationEval as Mock).mockRejectedValue(rateLimitError);+ (isLLMCompletionError as Mock).mockReturnValue(true);+ (rateLimitError as unknown as { isRetryable: boolean }).isRetryable =+ true;+ (retryLLMRateLimitError as Mock).mockResolvedValue({+ outcome: "queue_unavailable",+ });++ const job = createMockJob();+ await llmAsJudgeExecutionQueueProcessor(job);++ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: {+ id: jobExecutionId,+ projectId,+ },+ data: expect.objectContaining({+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "Rate limit exceeded",+ executionTraceId: "test-trace-id",+ }),+ });+ });});describe("LLM completion errors (non-retryable)", () => {@@ -356,7 +472,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {const job = createMockJob({retryBaggage: { attempt: 3 },});- await llmAsJudgeExecutionQueueProcessor(job);+ await llmAsJudgeExecutionQueueProcessor(job as Job<any>);expect(mockSpan.setAttribute).toHaveBeenCalledWith("messaging.bullmq.job.input.retryBaggage.attempt",@@ -373,7 +489,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {const job = createMockJob();delete (job.data as { retryBaggage?: unknown }).retryBaggage;- await llmAsJudgeExecutionQueueProcessor(job);+ await llmAsJudgeExecutionQueueProcessor(job as Job<any>);expect(mockSpan.setAttribute).toHaveBeenCalledWith("messaging.bullmq.job.input.retryBaggage.attempt",diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.tsindex 2386b0ff8c..2fd638727b 100644--- a/worker/src/queues/evalQueue.ts+++ b/worker/src/queues/evalQueue.ts@@ -211,7 +211,7 @@ export const evalJobExecutorQueueProcessorBuilder = (? SecondaryEvalExecutionQueue.getInstance({ shardName: queueName }): EvalExecutionQueue.getInstance({ shardName: queueName });- await retryLLMRateLimitError(job, {+ const retryResult = await retryLLMRateLimitError(job, {table: "job_executions",idField: "jobExecutionId",queue,@@ -220,20 +220,22 @@ export const evalJobExecutorQueueProcessorBuilder = (delayFn: delayInMs,});- // Use the deterministic execution trace ID to update the job execution- await prisma.jobExecution.update({- where: {- id: job.data.payload.jobExecutionId,- projectId: job.data.payload.projectId,- },- data: {- status: JobExecutionStatus.DELAYED,- executionTraceId,- },- });+ if (retryResult.outcome === "scheduled") {+ // Use the deterministic execution trace ID to update the job execution+ await prisma.jobExecution.update({+ where: {+ id: job.data.payload.jobExecutionId,+ projectId: job.data.payload.projectId,+ },+ data: {+ status: JobExecutionStatus.DELAYED,+ executionTraceId,+ },+ });- // Return early as we have already scheduled a delayed retry- return;+ // Return early as we have already scheduled a delayed retry+ return;+ }}// At this point there will be only 4xx LLMCompletionErrors that are not retryable and application errors@@ -305,7 +307,7 @@ export const llmAsJudgeExecutionQueueProcessorBuilder =const queue = LLMAsJudgeExecutionQueue.getInstance({shardName: queueName,});- await retryLLMRateLimitError(job, {+ const retryResult = await retryLLMRateLimitError(job, {table: "job_executions",idField: "jobExecutionId",queue,@@ -314,18 +316,20 @@ export const llmAsJudgeExecutionQueueProcessorBuilder =delayFn: delayInMs,});- await prisma.jobExecution.update({- where: {- id: job.data.payload.jobExecutionId,- projectId: job.data.payload.projectId,- },- data: {- status: JobExecutionStatus.DELAYED,- executionTraceId,- },- });+ if (retryResult.outcome === "scheduled") {+ await prisma.jobExecution.update({+ where: {+ id: job.data.payload.jobExecutionId,+ projectId: job.data.payload.projectId,+ },+ data: {+ status: JobExecutionStatus.DELAYED,+ executionTraceId,+ },+ });- return;+ return;+ }}await prisma.jobExecution.update({diff --git a/worker/src/queues/experimentQueue.ts b/worker/src/queues/experimentQueue.tsindex c70d712ece..0301253f9e 100644--- a/worker/src/queues/experimentQueue.ts+++ b/worker/src/queues/experimentQueue.ts@@ -23,7 +23,7 @@ export const experimentCreateQueueProcessor = async (return true;} catch (e) {if (isLLMCompletionError(e) && e.isRetryable) {- await retryLLMRateLimitError(job, {+ const retryResult = await retryLLMRateLimitError(job, {table: "dataset_runs",idField: "runId",queue: ExperimentCreateQueue.getInstance(),@@ -32,7 +32,8 @@ export const experimentCreateQueueProcessor = async (delayFn: delayInMs,});- return;+ if (retryResult.outcome === "scheduled") return;+ if (retryResult.outcome === "queue_unavailable") throw e;}if (isLLMCompletionError(e) || isUnrecoverableError(e)) return;