Skip to content

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

fix: use exponential reschedule to handle obs not found in dataset-run-item-queue (#10374)

Steffen Schmitzc1bcf3d3dc54
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index cce671081c..a5d299496e 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -375,6 +375,7 @@ export type TQueueJobTypes = {
id: string;
payload: DatasetRunItemUpsertEventType;
name: QueueJobs.DatasetRunItemUpsert;
+ retryBaggage?: RetryBaggage;
};
[QueueName.EvaluationExecution]: {
timestamp: Date;
diff --git a/worker/src/__tests__/observation-retry.test.ts b/worker/src/__tests__/observation-retry.test.ts
new file mode 100644
index 0000000000..6d8ce000eb
--- /dev/null
+++ b/worker/src/__tests__/observation-retry.test.ts
@@ -0,0 +1,278 @@
+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
+import {
+ observationRetryDelayInMs,
+ retryObservationNotFound,
+} from "../features/evaluation/retryObservationNotFound";
+import {
+ DatasetRunItemUpsertQueue,
+ RetryBaggage,
+} from "@langfuse/shared/src/server";
+import { ObservationNotFoundError } from "../errors/ObservationNotFoundError";
+
+// Mock the queue
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ DatasetRunItemUpsertQueue: {
+ getInstance: vi.fn(),
+ },
+ };
+});
+
+describe("Observation Retry Logic", () => {
+ describe("observationRetryDelayInMs", () => {
+ test("returns correct exponential backoff delays", () => {
+ expect(observationRetryDelayInMs(1)).toBe(30 * 1000); // 30s
+ expect(observationRetryDelayInMs(2)).toBe(60 * 1000); // 1m
+ expect(observationRetryDelayInMs(3)).toBe(120 * 1000); // 2m
+ expect(observationRetryDelayInMs(4)).toBe(240 * 1000); // 4m
+ });
+
+ test("continues exponential growth beyond attempt 4", () => {
+ expect(observationRetryDelayInMs(5)).toBe(480 * 1000); // 8m
+ });
+ });
+
+ describe("retryObservationNotFound", () => {
+ let mockQueueAdd: ReturnType<typeof vi.fn>;
+ let mockQueue: { add: typeof mockQueueAdd };
+
+ beforeEach(() => {
+ mockQueueAdd = vi.fn().mockResolvedValue(undefined);
+ mockQueue = { add: mockQueueAdd };
+ vi.mocked(DatasetRunItemUpsertQueue.getInstance).mockReturnValue(
+ mockQueue as any,
+ );
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("schedules retry on first failure", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ },
+ };
+
+ const shouldRetry = await retryObservationNotFound(error, job);
+
+ expect(shouldRetry).toBe(true);
+ expect(mockQueueAdd).toHaveBeenCalledTimes(1);
+
+ const addCall = mockQueueAdd.mock.calls[0];
+ expect(addCall[0]).toBe("dataset-run-item-upsert");
+ expect(addCall[1].payload.projectId).toBe("project-1");
+ expect(addCall[1].payload.observationId).toBe("obs-123");
+ expect(addCall[1].retryBaggage.attempt).toBe(1);
+ expect(addCall[2].delay).toBe(30 * 1000); // 30s delay
+ });
+
+ test("increases attempt count on subsequent failures", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ retryBaggage: {
+ originalJobTimestamp: new Date(),
+ attempt: 2,
+ } as RetryBaggage,
+ },
+ };
+
+ const shouldRetry = await retryObservationNotFound(error, job);
+
+ expect(shouldRetry).toBe(true);
+ expect(mockQueueAdd).toHaveBeenCalledTimes(1);
+
+ const addCall = mockQueueAdd.mock.calls[0];
+ expect(addCall[1].retryBaggage.attempt).toBe(3);
+ expect(addCall[2].delay).toBe(120 * 1000); // 2m delay (attempt 3)
+ });
+
+ test("returns false when max attempts reached", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ retryBaggage: {
+ originalJobTimestamp: new Date(),
+ attempt: 4,
+ } as RetryBaggage,
+ },
+ };
+
+ const shouldRetry = await retryObservationNotFound(error, job);
+
+ expect(shouldRetry).toBe(false);
+ expect(mockQueueAdd).not.toHaveBeenCalled();
+ });
+
+ test("returns false when job is older than 10 minutes", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const oldTimestamp = new Date(Date.now() - 11 * 60 * 1000); // 11 minutes ago
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ retryBaggage: {
+ originalJobTimestamp: oldTimestamp,
+ attempt: 1,
+ } as RetryBaggage,
+ },
+ };
+
+ const shouldRetry = await retryObservationNotFound(error, job);
+
+ expect(shouldRetry).toBe(false);
+ expect(mockQueueAdd).not.toHaveBeenCalled();
+ });
+
+ test("preserves original timestamp across retries", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ // Use a recent timestamp to avoid max age check
+ const originalTimestamp = new Date(Date.now() - 2 * 60 * 1000); // 2 minutes ago
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ retryBaggage: {
+ originalJobTimestamp: originalTimestamp,
+ attempt: 2,
+ } as RetryBaggage,
+ },
+ };
+
+ await retryObservationNotFound(error, job);
+
+ const addCall = mockQueueAdd.mock.calls[0];
+ expect(addCall[1].retryBaggage.originalJobTimestamp).toEqual(
+ originalTimestamp,
+ );
+ });
+
+ test("includes all job data in retry payload", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ },
+ };
+
+ await retryObservationNotFound(error, job);
+
+ const addCall = mockQueueAdd.mock.calls[0];
+ const payload = addCall[1].payload;
+ expect(payload.projectId).toBe("project-1");
+ expect(payload.datasetItemId).toBe("item-1");
+ expect(payload.traceId).toBe("trace-1");
+ expect(payload.observationId).toBe("obs-123");
+ });
+
+ test("handles job without observationId", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: undefined,
+ },
+ };
+
+ const shouldRetry = await retryObservationNotFound(error, job);
+
+ expect(shouldRetry).toBe(true);
+ const addCall = mockQueueAdd.mock.calls[0];
+ expect(addCall[1].payload.observationId).toBeUndefined();
+ });
+
+ test("applies correct delay for each attempt", async () => {
+ const error = new ObservationNotFoundError({
+ message: "Test error",
+ observationId: "obs-123",
+ });
+
+ const attempts = [
+ { attempt: 0, expectedDelay: 30 * 1000 }, // Attempt 1: 30s
+ { attempt: 1, expectedDelay: 60 * 1000 }, // Attempt 2: 1m
+ { attempt: 2, expectedDelay: 120 * 1000 }, // Attempt 3: 2m
+ { attempt: 3, expectedDelay: 240 * 1000 }, // Attempt 4: 4m
+ ];
+
+ for (const { attempt, expectedDelay } of attempts) {
+ vi.clearAllMocks();
+
+ const job = {
+ data: {
+ projectId: "project-1",
+ datasetItemId: "item-1",
+ traceId: "trace-1",
+ observationId: "obs-123",
+ retryBaggage:
+ attempt > 0
+ ? ({
+ originalJobTimestamp: new Date(),
+ attempt,
+ } as RetryBaggage)
+ : undefined,
+ },
+ };
+
+ await retryObservationNotFound(error, job);
+
+ const addCall = mockQueueAdd.mock.calls[0];
+ expect(addCall[2].delay).toBe(expectedDelay);
+ }
+ });
+ });
+});
diff --git a/worker/src/errors/ObservationNotFoundError.ts b/worker/src/errors/ObservationNotFoundError.ts
new file mode 100644
index 0000000000..4d992fe010
--- /dev/null
+++ b/worker/src/errors/ObservationNotFoundError.ts
@@ -0,0 +1,22 @@
+const ObservationNotFoundErrorName = "ObservationNotFoundError";
+
+export class ObservationNotFoundError extends Error {
+ observationId: string;
+
+ constructor(params: { message: string; observationId: string }) {
+ super(params.message);
+
+ this.name = ObservationNotFoundErrorName;
+ this.observationId = params.observationId;
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this);
+ }
+ }
+}
+
+export function isObservationNotFoundError(
+ e: any,
+): e is ObservationNotFoundError {
+ return e instanceof Error && e.name === ObservationNotFoundErrorName;
+}
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 0fbe09d297..64c4c64304 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -56,6 +56,7 @@ import { compileHandlebarString, createW3CTraceId } from "../utils";
import { env } from "../../env";
import { JSONPath } from "jsonpath-plus";
import { UnrecoverableError } from "../../errors/UnrecoverableError";
+import { ObservationNotFoundError } from "../../errors/ObservationNotFoundError";
let s3StorageServiceClient: StorageService;
@@ -475,11 +476,12 @@ export const createEvalJobs = async ({
);
if (!observationExists) {
logger.warn(
- `Observation ${observationId} not found, retrying dataset eval later`,
- );
- throw new Error(
- "Observation not found. Rejecting job to use retry-attempts.",
+ `Observation ${observationId} not found, will retry with exponential backoff`,
);
+ throw new ObservationNotFoundError({
+ message: "Observation not found, retrying later",
+ observationId,
+ });
}
}
diff --git a/worker/src/features/evaluation/retryObservationNotFound.ts b/worker/src/features/evaluation/retryObservationNotFound.ts
new file mode 100644
index 0000000000..2ce6d6ff45
--- /dev/null
+++ b/worker/src/features/evaluation/retryObservationNotFound.ts
@@ -0,0 +1,143 @@
+import {
+ convertQueueNameToMetricName,
+ logger,
+ recordDistribution,
+ RetryBaggage,
+ QueueName,
+ QueueJobs,
+ DatasetRunItemUpsertQueue,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+import type { ObservationNotFoundError } from "../../errors/ObservationNotFoundError";
+
+const MAX_RETRY_ATTEMPTS = 5; // Initial attempt + 4 retries
+const MAX_AGE_MS = 10 * 60 * 1000; // 10 minutes
+
+/**
+ * Exponential backoff delay function for observation-not-found retries
+ * Returns: 30s, 1m (60s), 2m (120s), 4m (240s)
+ */
+export const observationRetryDelayInMs = (attempt: number): number => {
+ // Exponential backoff with 30s base: 30s * 2^(attempt-1)
+ const baseDelayMs = 30 * 1000;
+ return baseDelayMs * Math.pow(2, attempt - 1);
+};
+
+/**
+ * Handles observation-not-found errors with exponential backoff retry logic
+ * @returns true if retry was scheduled, false if max attempts reached (should log warning and complete)
+ */
+export async function retryObservationNotFound(
+ error: ObservationNotFoundError,
+ job: {
+ data: {
+ projectId: string;
+ datasetItemId: string;
+ traceId: string;
+ observationId?: string;
+ retryBaggage?: RetryBaggage;
+ };
+ },
+): Promise<boolean> {
+ try {
+ const currentAttempt = (job.data.retryBaggage?.attempt ?? 0) + 1;
+ const originalTimestamp =
+ job.data.retryBaggage?.originalJobTimestamp ?? new Date();
+
+ // Check if job is older than max age
+ const ageMs = Date.now() - new Date(originalTimestamp).getTime();
+ if (ageMs > MAX_AGE_MS) {
+ logger.warn(
+ `Observation ${error.observationId} not found after ${MAX_AGE_MS / 1000}s. Giving up.`,
+ {
+ projectId: job.data.projectId,
+ datasetItemId: job.data.datasetItemId,
+ observationId: error.observationId,
+ traceId: job.data.traceId,
+ ageMs,
+ attempts: currentAttempt,
+ },
+ );
+ return false; // Max age reached, don't retry
+ }
+
+ // Check if max attempts reached
+ if (currentAttempt >= MAX_RETRY_ATTEMPTS) {
+ logger.warn(
+ `Observation ${error.observationId} not found after ${MAX_RETRY_ATTEMPTS} attempts. Giving up.`,
+ {
+ projectId: job.data.projectId,
+ datasetItemId: job.data.datasetItemId,
+ observationId: error.observationId,
+ traceId: job.data.traceId,
+ ageMs,
+ attempts: currentAttempt,
+ },
+ );
+ return false; // Max attempts reached, don't retry
+ }
+
+ // Calculate delay for next attempt
+ const delay = observationRetryDelayInMs(currentAttempt);
+
+ const retryBaggage: RetryBaggage = {
+ originalJobTimestamp: new Date(originalTimestamp),
+ attempt: currentAttempt,
+ };
+
+ // Record retry attempt distribution
+ recordDistribution(
+ `${convertQueueNameToMetricName(QueueName.DatasetRunItemUpsert)}.retries`,
+ retryBaggage.attempt,
+ {
+ queue: QueueName.DatasetRunItemUpsert,
+ reason: "observation_not_found",
+ },
+ );
+
+ logger.info(
+ `Observation ${error.observationId} not found. Retrying in ${delay}ms. Attempt ${currentAttempt}/${MAX_RETRY_ATTEMPTS}.`,
+ {
+ projectId: job.data.projectId,
+ datasetItemId: job.data.datasetItemId,
+ observationId: error.observationId,
+ traceId: job.data.traceId,
+ delayMs: delay,
+ totalDelayMs: ageMs,
+ attempt: currentAttempt,
+ },
+ );
+
+ // Re-queue the job with delay
+ const queue = DatasetRunItemUpsertQueue.getInstance();
+ await queue?.add(
+ QueueJobs.DatasetRunItemUpsert,
+ {
+ name: QueueJobs.DatasetRunItemUpsert,
+ id: randomUUID(),
+ timestamp: new Date(),
+ payload: {
+ projectId: job.data.projectId,
+ datasetItemId: job.data.datasetItemId,
+ traceId: job.data.traceId,
+ observationId: job.data.observationId,
+ },
+ retryBaggage,
+ },
+ { delay },
+ );
+
+ return true; // Retry scheduled
+ } catch (innerErr) {
+ logger.error(
+ `Failed to handle observation-not-found retry for observation ${error.observationId}. Job will fail.`,
+ {
+ error: innerErr,
+ projectId: job.data.projectId,
+ datasetItemId: job.data.datasetItemId,
+ observationId: error.observationId,
+ },
+ );
+ throw innerErr;
+ }
+}
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 08ef298ec8..0062a9f423 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -15,6 +15,8 @@ import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
import { delayInMs } from "./utils/delays";
import { createW3CTraceId, retryLLMRateLimitError } from "../features/utils";
import { isUnrecoverableError } from "../errors/UnrecoverableError";
+import { retryObservationNotFound } from "../features/evaluation/retryObservationNotFound";
+import { isObservationNotFoundError } from "../errors/ObservationNotFoundError";
export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
@@ -49,6 +51,37 @@ export const evalJobDatasetCreatorQueueProcessor = async (
});
return true;
} catch (e) {
+ // Handle observation-not-found errors with manual retry
+ if (isObservationNotFoundError(e)) {
+ const shouldRetry = await retryObservationNotFound(e, {
+ data: {
+ projectId: job.data.payload.projectId,
+ datasetItemId: job.data.payload.datasetItemId,
+ traceId: job.data.payload.traceId,
+ observationId: job.data.payload.observationId,
+ retryBaggage: job.data.retryBaggage,
+ },
+ });
+
+ if (shouldRetry) {
+ // Retry was scheduled, complete this job successfully
+ return true;
+ } else {
+ // Max attempts reached, log warning and complete successfully
+ logger.warn(
+ `Observation not found after max retries. Completing job without creating eval.`,
+ {
+ projectId: job.data.payload.projectId,
+ datasetItemId: job.data.payload.datasetItemId,
+ observationId: job.data.payload.observationId,
+ traceId: job.data.payload.traceId,
+ },
+ );
+ return true;
+ }
+ }
+
+ // All other errors should be logged and propagated for BullMQ retry
logger.error(
`Failed job Evaluation for dataset item: ${job.data.payload.datasetItemId}`,
e,