πͺ’ 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(worker): bound LLM queue retries (#14511)
Hassieb Pakzadf40bf6b215c1
diff --git a/worker/src/env.ts b/worker/src/env.tsindex 68fce0a654..c30ffc6130 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -142,6 +142,16 @@ const EnvSchema = z.object({.number().positive().default(5),+ LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_ATTEMPTS: z.coerce+ .number()+ .int()+ .min(0)+ .default(4),+ LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_AGE_SECONDS: z.coerce+ .number()+ .int()+ .positive()+ .default(120 * 60),LANGFUSE_CODE_EVAL_EXECUTION_WORKER_CONCURRENCY: z.coerce.number().positive()diff --git a/worker/src/features/utils/retry-handler.test.ts b/worker/src/features/utils/retry-handler.test.tsindex 13b0ec8d04..e389813c10 100644--- a/worker/src/features/utils/retry-handler.test.ts+++ b/worker/src/features/utils/retry-handler.test.ts@@ -1,4 +1,17 @@-import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";++const mockEnv = vi.hoisted(() => ({+ LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_ATTEMPTS: 4,+ LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_AGE_SECONDS: 120 * 60,+}));vi.mock("@langfuse/shared/src/server", () => ({convertQueueNameToMetricName: vi.fn().mockImplementation((name) => name),@@ -25,18 +38,32 @@ vi.mock("crypto", () => ({randomUUID: vi.fn().mockReturnValue("retry-job-id"),}));+vi.mock("../../env", () => ({+ env: mockEnv,+}));+import { prisma } from "@langfuse/shared/src/db";import { logger, recordDistribution } from "@langfuse/shared/src/server";import { retryLLMRateLimitError } from "./retry-handler";describe("retryLLMRateLimitError", () => {beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-01-01T02:00:00.000Z"));vi.clearAllMocks();+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ mockEnv.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_ATTEMPTS = 4;+ mockEnv.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_AGE_SECONDS = 120 * 60;(prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({- createdAt: new Date(),+ createdAt: new Date("2026-01-01T01:00:00.000Z"),});});+ afterEach(() => {+ (Math.random as unknown as Mock).mockRestore?.();+ vi.useRealTimers();+ });+it("returns queue_unavailable instead of throwing when queue.add fails", async () => {const add = vi.fn().mockRejectedValue(new Error("redis unavailable"));@@ -56,7 +83,6 @@ describe("retryLLMRateLimitError", () => {queue: { add },queueName: "llm-as-a-judge-execution-queue-1",jobName: "llm-as-a-judge-execution-job",- delayFn: () => 30_000,},);@@ -92,7 +118,6 @@ describe("retryLLMRateLimitError", () => {queue: { add: vi.fn() },queueName: "llm-as-a-judge-execution-queue-1",jobName: "llm-as-a-judge-execution-job",- delayFn: () => 30_000,},);@@ -105,4 +130,309 @@ describe("retryLLMRateLimitError", () => {);expect(recordDistribution).not.toHaveBeenCalled();});++ it("returns max_attempts without queueing when retry budget is exhausted", async () => {+ const add = vi.fn();++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T01:00:00.000Z"),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ },+ retryBaggage: {+ originalJobTimestamp: new Date("2026-01-01T01:00:00.000Z"),+ attempt: 4,+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ },+ );++ expect(result).toEqual({+ outcome: "skipped",+ reason: "max_attempts",+ });+ expect(add).not.toHaveBeenCalled();+ });++ it("returns too_old without queueing when retry age budget is exhausted", async () => {+ const add = vi.fn();+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2025-12-31T23:59:59.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2025-12-31T23:59:59.000Z"),+ 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",+ },+ );++ expect(result).toEqual({+ outcome: "skipped",+ reason: "too_old",+ });+ expect(add).not.toHaveBeenCalled();+ });++ it("anchors retry age to the first LLM attempt after an initial queue delay", async () => {+ const add = vi.fn().mockResolvedValue(undefined);+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2025-12-31T23:00:00.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T02:00:00.000Z"),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ delay: 3 * 60 * 60 * 1000,+ },+ retryBaggage: {+ originalJobTimestamp: new Date("2025-12-31T23:00:00.000Z"),+ attempt: 0,+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ },+ );++ expect(result).toMatchObject({+ outcome: "scheduled",+ delaySeconds: 5 * 60,+ retryBaggage: {+ attempt: 1,+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ },+ });+ expect(add).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue-1",+ expect.objectContaining({+ payload: expect.objectContaining({+ delay: 3 * 60 * 60 * 1000,+ }),+ retryBaggage: expect.objectContaining({+ attempt: 1,+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ }),+ }),+ { delay: 5 * 60 * 1000 },+ );+ });++ it("caps scheduled delay at the remaining retry age budget", async () => {+ const add = vi.fn().mockResolvedValue(undefined);+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2026-01-01T00:01:00.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T00:01:00.000Z"),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ },+ retryBaggage: {+ originalJobTimestamp: new Date("2026-01-01T00:01:00.000Z"),+ attempt: 3,+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ },+ );++ expect(result).toMatchObject({+ outcome: "scheduled",+ delaySeconds: 60,+ retryBaggage: {+ attempt: 4,+ originalJobTimestamp: new Date("2026-01-01T00:01:00.000Z"),+ },+ });+ expect(add).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue-1",+ expect.objectContaining({+ retryBaggage: expect.objectContaining({+ attempt: 4,+ }),+ }),+ { delay: 60 * 1000 },+ );+ });++ it("derives the default retry schedule from retry count and age window", async () => {+ const add = vi.fn().mockResolvedValue(undefined);+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2026-01-01T02:00:00.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T02:00:00.000Z"),+ payload: {+ projectId: "project-id",+ jobExecutionId: "job-execution-id",+ },+ retryBaggage: {+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ attempt: 1,+ },+ },+ },+ {+ table: "job_executions",+ idField: "jobExecutionId",+ queue: { add },+ queueName: "llm-as-a-judge-execution-queue-1",+ jobName: "llm-as-a-judge-execution-job",+ },+ );++ expect(result).toMatchObject({+ outcome: "scheduled",+ delaySeconds: 2600,+ retryBaggage: {+ attempt: 2,+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ },+ });+ expect(add).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue-1",+ expect.objectContaining({+ retryBaggage: expect.objectContaining({+ attempt: 2,+ }),+ }),+ { delay: 2600 * 1000 },+ );+ });++ it("applies jitter to the scheduled delay", async () => {+ const add = vi.fn().mockResolvedValue(undefined);+ (Math.random as unknown as Mock).mockReturnValue(0);+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2026-01-01T02:00:00.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T02:00:00.000Z"),+ 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",+ },+ );++ expect(result).toMatchObject({+ outcome: "scheduled",+ delaySeconds: 4 * 60,+ retryBaggage: {+ attempt: 1,+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ },+ });+ expect(add).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue-1",+ expect.objectContaining({+ retryBaggage: expect.objectContaining({+ attempt: 1,+ }),+ }),+ { delay: 4 * 60 * 1000 },+ );+ });++ it("derives retry delays from custom retry count and age window", async () => {+ const add = vi.fn().mockResolvedValue(undefined);+ mockEnv.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_ATTEMPTS = 4;+ mockEnv.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_AGE_SECONDS = 2 * 60;+ (prisma.jobExecution.findFirstOrThrow as Mock).mockResolvedValue({+ createdAt: new Date("2026-01-01T02:00:00.000Z"),+ });++ const result = await retryLLMRateLimitError(+ {+ data: {+ timestamp: new Date("2026-01-01T02:00:00.000Z"),+ 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",+ },+ );++ expect(result).toMatchObject({+ outcome: "scheduled",+ delaySeconds: 30,+ retryBaggage: {+ attempt: 1,+ originalJobTimestamp: new Date("2026-01-01T02:00:00.000Z"),+ },+ });+ expect(add).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue-1",+ expect.objectContaining({+ retryBaggage: expect.objectContaining({+ attempt: 1,+ }),+ }),+ { delay: 30 * 1000 },+ );+ });});diff --git a/worker/src/features/utils/retry-handler.ts b/worker/src/features/utils/retry-handler.tsindex b28023fb28..97e74a996d 100644--- a/worker/src/features/utils/retry-handler.ts+++ b/worker/src/features/utils/retry-handler.ts@@ -6,8 +6,67 @@ import {} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";import { prisma } from "@langfuse/shared/src/db";+import { env } from "../../env";-const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;+const LLM_QUEUE_RETRY_FIRST_DELAY_SECONDS = 5 * 60;+const LLM_QUEUE_RETRY_JITTER_FACTOR = 0.2;++const getLLMQueueRetryTargetOffsetSeconds = ({+ attempt,+ maxRetryAttempts,+ maxAgeSeconds,+}: {+ attempt: number;+ maxRetryAttempts: number;+ maxAgeSeconds: number;+}) => {+ if (attempt < 1 || attempt > maxRetryAttempts) return 0;++ const firstRetryDelaySeconds = Math.min(+ LLM_QUEUE_RETRY_FIRST_DELAY_SECONDS,+ maxAgeSeconds / maxRetryAttempts,+ );++ if (maxRetryAttempts === 1) return firstRetryDelaySeconds;++ // With the default 4 retries over 120m this is roughly 5m, 43m, 82m, 120m.+ const retryProgress = (attempt - 1) / (maxRetryAttempts - 1);++ return Math.round(+ firstRetryDelaySeconds ++ (maxAgeSeconds - firstRetryDelaySeconds) * retryProgress,+ );+};++const getLLMQueueRetryDelaySeconds = ({+ attempt,+ elapsedSeconds,+ maxRetryAttempts,+ maxAgeSeconds,+}: {+ attempt: number;+ elapsedSeconds: number;+ maxRetryAttempts: number;+ maxAgeSeconds: number;+}) => {+ const targetOffsetSeconds = getLLMQueueRetryTargetOffsetSeconds({+ attempt,+ maxRetryAttempts,+ maxAgeSeconds,+ });+ const delaySeconds = Math.max(0, targetOffsetSeconds - elapsedSeconds);+ const jitterMultiplier =+ 1 -+ LLM_QUEUE_RETRY_JITTER_FACTOR ++ Math.random() * LLM_QUEUE_RETRY_JITTER_FACTOR * 2;+ const jitteredDelaySeconds = Math.round(delaySeconds * jitterMultiplier);+ const remainingAgeSeconds = Math.max(0, maxAgeSeconds - elapsedSeconds);++ return Math.min(jitteredDelaySeconds, remainingAgeSeconds);+};++const getInitialQueueDelayMs = (delay: unknown) =>+ typeof delay === "number" && Number.isFinite(delay) ? Math.max(0, delay) : 0;/*** Configuration for retry handling with rate limiting and age checks@@ -23,28 +82,26 @@ interface RetryConfig {queueName: string;/** Job name for the retry job */jobName: string;- /** Function to generate retry delay in milliseconds */-- delayFn: (attempt: number) => number;}export type RetryScheduleResult =| {outcome: "scheduled";- delay: number;+ delaySeconds: number;retryBaggage: RetryBaggage;}| {outcome: "skipped";- reason: "too_old";+ reason: "too_old" | "max_attempts";}| {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+ * Handles rate limiting and retry logic for queue jobs.+ * Automatically retries jobs that fail with 429/5xx errors unless they exceed+ * the configured retry budget or age limit.*/export async function retryLLMRateLimitError(job: {@@ -58,8 +115,9 @@ export async function retryLLMRateLimitError(): Promise<RetryScheduleResult> {try {const jobId = job.data.payload[config.idField];+ const maxRetryAttempts = env.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_ATTEMPTS;+ const maxAgeSeconds = env.LANGFUSE_LLM_AS_JUDGE_QUEUE_RETRY_MAX_AGE_SECONDS;- // Check if the job is older than 24hconst record =config.table === "dataset_runs"? await prisma.datasetRuns.findFirstOrThrow({@@ -71,10 +129,19 @@ export async function retryLLMRateLimitError(where: { id: jobId, projectId: job.data.payload.projectId },});- if (record.createdAt < new Date(Date.now() - ONE_DAY_IN_MS)) {- logger.info(- `Job ${jobId} is rate limited for more than 24h. Stop retrying.`,- );+ // The retry budget starts when the LLM call is first attempted, not when a+ // delayed evaluation job row was created.+ const retryWindowStartTimeMs =+ record.createdAt.getTime() ++ getInitialQueueDelayMs(job.data.payload.delay);++ const elapsedSeconds = Math.max(+ 0,+ (Date.now() - retryWindowStartTimeMs) / 1000,+ );++ if (elapsedSeconds >= maxAgeSeconds) {+ logger.info(`Job ${jobId} exceeded retry age limit. Stop retrying.`);return {outcome: "skipped",@@ -82,20 +149,38 @@ export async function retryLLMRateLimitError(};}- // Retry the job with delay- const delay = config.delayFn((job.data.retryBaggage?.attempt ?? 0) + 1);-- const retryBaggage: RetryBaggage = job.data.retryBaggage- ? {- originalJobTimestamp: new Date(- job.data.retryBaggage.originalJobTimestamp,- ),- attempt: job.data.retryBaggage.attempt + 1,- }- : {- originalJobTimestamp: new Date(job.data.timestamp),- attempt: 1,- };+ const currentAttempt = (job.data.retryBaggage?.attempt ?? 0) + 1;++ if (currentAttempt > maxRetryAttempts) {+ logger.info(`Job ${jobId} exceeded retry attempt limit. Stop retrying.`);++ return {+ outcome: "skipped",+ reason: "max_attempts",+ };+ }++ const delaySeconds = getLLMQueueRetryDelaySeconds({+ attempt: currentAttempt,+ elapsedSeconds,+ maxRetryAttempts,+ maxAgeSeconds,+ });+ const delayMs = Math.round(delaySeconds * 1000);++ const retryWindowStart = new Date(retryWindowStartTimeMs);+ const retryBaggage: RetryBaggage =+ job.data.retryBaggage && job.data.retryBaggage.attempt > 0+ ? {+ originalJobTimestamp: new Date(+ job.data.retryBaggage.originalJobTimestamp,+ ),+ attempt: currentAttempt,+ }+ : {+ originalJobTimestamp: retryWindowStart,+ attempt: currentAttempt,+ };if (!config.queue) {logger.warn(@@ -128,7 +213,7 @@ export async function retryLLMRateLimitError();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.`,+ `Job ${jobId} is rate limited. Retrying in ${delaySeconds}s. Attempt: ${retryBaggage?.attempt}. Total delay: ${retryBaggage ? new Date().getTime() - new Date(retryBaggage?.originalJobTimestamp).getTime() : "unavailable"}ms.`,);try {@@ -141,7 +226,7 @@ export async function retryLLMRateLimitError(payload: job.data.payload,retryBaggage: retryBaggage,},- { delay },+ { delay: delayMs },);} catch (addErr) {logger.warn(@@ -156,7 +241,7 @@ export async function retryLLMRateLimitError(return {outcome: "scheduled",- delay,+ delaySeconds,retryBaggage,};} catch (innerErr) {diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.tsindex 616160a594..5f3f124e20 100644--- a/worker/src/queues/evalQueue.ts+++ b/worker/src/queues/evalQueue.ts@@ -15,7 +15,6 @@ import {} from "@langfuse/shared/src/server";import { createEvalJobs, evaluate } from "../features/evaluation/evalService";import { processObservationEval } from "../features/evaluation/observationEval";-import { delayInMs } from "./utils/delays";import { createW3CTraceId, retryLLMRateLimitError } from "../features/utils";import { isUnrecoverableError } from "../errors/UnrecoverableError";import { retryObservationNotFound } from "../features/evaluation/retryObservationNotFound";@@ -188,15 +187,16 @@ export const evalJobExecutorQueueProcessorBuilder = (// β Yes β No// βΌ βΌ// ββββββββββββββββββββ βββββββββββββββββββββββββ- // β Is job < 24h old?β β Is it retryable? β- // βββββββ¬βββββββ¬ββββββ β (shouldRetryJob) β- // Yes β β No βββββββ¬ββββββββββββββ¬ββββ+ // β Is job inside itsβ β Is it retryable? β+ // β retry budget? β β (shouldRetryJob) β+ // βββββββ¬βββββββ¬ββββββ βββββββ¬ββββββββββββββ¬ββββ+ // Yes β β No Yesβ βNo// βΌ βΌ Yesβ βNo// βββββββββββ ββββββββββ βΌ βΌ// βSet: β βSet: β βββββββββββ ββββββββββββ// βDELAYED β βERROR β βBullMQ β βSet: β- // βRetry in β βStop β βretry β βERROR β- // β1-25 min β β β βw/ exp. β βDone β+ // βRetry by β βStop β βretry β βERROR β+ // β120 min β β β βw/ exp. β βDone β// βββββββββββ ββββββββββ βbackoff β ββββββββββββ// βββββββββββ@@ -217,7 +217,6 @@ export const evalJobExecutorQueueProcessorBuilder = (queue,queueName,jobName: QueueJobs.EvaluationExecution,- delayFn: delayInMs,});if (retryResult.outcome === "scheduled") {@@ -316,7 +315,6 @@ export const llmAsJudgeExecutionQueueProcessorBuilder =queue,queueName,jobName: QueueJobs.LLMAsJudgeExecution,- delayFn: delayInMs,});if (retryResult.outcome === "scheduled") {diff --git a/worker/src/queues/experimentQueue.ts b/worker/src/queues/experimentQueue.tsindex 0301253f9e..b98965e441 100644--- a/worker/src/queues/experimentQueue.ts+++ b/worker/src/queues/experimentQueue.ts@@ -9,7 +9,6 @@ import {traceException,} from "@langfuse/shared/src/server";import { retryLLMRateLimitError } from "../features/utils";-import { delayInMs } from "./utils/delays";import { createExperimentJobClickhouse } from "../features/experiments/experimentServiceClickhouse";import { isUnrecoverableError } from "../errors/UnrecoverableError";@@ -29,7 +28,6 @@ export const experimentCreateQueueProcessor = async (queue: ExperimentCreateQueue.getInstance(),queueName: QueueName.ExperimentCreate,jobName: QueueJobs.ExperimentCreateJob,- delayFn: delayInMs,});if (retryResult.outcome === "scheduled") return;diff --git a/worker/src/queues/utils/delays.ts b/worker/src/queues/utils/delays.tsdeleted file mode 100644index 052ba54467..0000000000--- a/worker/src/queues/utils/delays.ts+++ /dev/null@@ -1,13 +0,0 @@-export const delayInMs = (attempt: number) => {- const range = {- minMinutes: 1,- maxMinutes: 10 + attempt * 5, // add a delay the more attempts we have- };-- const delay = Math.floor(- Math.random() * (range.maxMinutes - range.minMinutes + 1) +- range.minMinutes,- );-- return delay * 60 * 1000;-};