Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(llm-as-a-judge): add tracing for executions (#9654)

Hassieb Pakzad89e634285413
diff --git a/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.down.sql b/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.down.sql
new file mode 100644
index 0000000000..644c8b9080
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.down.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ON CLUSTER default DROP COLUMN IF EXISTS execution_trace_id;
diff --git a/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.up.sql b/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.up.sql
new file mode 100644
index 0000000000..aedc54abed
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0030_add_eval_execution_trace_id_to_scores.up.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ON CLUSTER default ADD COLUMN IF NOT EXISTS execution_trace_id Nullable(String);
diff --git a/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.down.sql b/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.down.sql
new file mode 100644
index 0000000000..ec8e08c7ae
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.down.sql
@@ -0,0 +1 @@
+ALTER TABLE scores DROP COLUMN IF EXISTS execution_trace_id;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.up.sql b/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.up.sql
new file mode 100644
index 0000000000..96115a56e6
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0030_add_eval_execution_trace_id_to_scores.up.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ADD COLUMN IF NOT EXISTS execution_trace_id Nullable(String);
diff --git a/packages/shared/package.json b/packages/shared/package.json
index e75cd24679..d134f25515 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -89,7 +89,7 @@
"jsonpath-plus": "10.3.0",
"kysely": "^0.27.4",
"langchain": "^0.3.30",
- "langfuse-langchain": "3.38.4",
+ "langfuse-langchain": "3.38.6",
"lodash": "^4.17.21",
"lossless-json": "^4.1.1",
"next-auth": "^4.24.11",
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 64ebd5a798..cef871c5ac 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -100,6 +100,7 @@ export const JobExecutionStatus = {
ERROR: "ERROR",
PENDING: "PENDING",
CANCELLED: "CANCELLED",
+ DELAYED: "DELAYED",
} as const;
export type JobExecutionStatus =
(typeof JobExecutionStatus)[keyof typeof JobExecutionStatus];
@@ -487,6 +488,7 @@ export type JobExecution = {
job_input_observation_id: string | null;
job_input_dataset_item_id: string | null;
job_output_score_id: string | null;
+ execution_trace_id: string | null;
};
export type LegacyPrismaObservation = {
id: string;
diff --git a/packages/shared/prisma/migrations/20251014161635_job_executions_add_execution_trace_id/migration.sql b/packages/shared/prisma/migrations/20251014161635_job_executions_add_execution_trace_id/migration.sql
new file mode 100644
index 0000000000..dfc4a8711c
--- /dev/null
+++ b/packages/shared/prisma/migrations/20251014161635_job_executions_add_execution_trace_id/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "job_executions" ADD COLUMN "execution_trace_id" TEXT;
+
+-- AlterEnum
+ALTER TYPE "JobExecutionStatus" ADD VALUE 'DELAYED';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index cb54f5459e..2851c7d7bc 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -901,6 +901,7 @@ enum JobExecutionStatus {
ERROR
PENDING
CANCELLED
+ DELAYED
}
model JobExecution {
@@ -932,6 +933,8 @@ model JobExecution {
jobOutputScoreId String? @map("job_output_score_id")
+ executionTraceId String? @map("execution_trace_id")
+
@@index([projectId, jobConfigurationId, jobInputTraceId])
@@index([projectId, status])
@@index([projectId, id])
diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.ts
index d5d5435e73..4aa147cfa8 100644
--- a/packages/shared/src/domain/scores.ts
+++ b/packages/shared/src/domain/scores.ts
@@ -29,6 +29,7 @@ export const ScoreSchema = z.object({
configId: z.string().nullable(),
stringValue: z.string().nullable(),
queueId: z.string().nullable(),
+ executionTraceId: z.string().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
dataType: z.enum(ScoreDataType),
diff --git a/packages/shared/src/errors/index.ts b/packages/shared/src/errors/index.ts
index 56d5ec6618..84c457f48a 100644
--- a/packages/shared/src/errors/index.ts
+++ b/packages/shared/src/errors/index.ts
@@ -8,4 +8,3 @@ export { ApiError } from "./ApiError";
export { InternalServerError } from "./InternalServerError";
export { LangfuseConflictError } from "./ConflictError";
export { ServiceUnavailableError } from "./ServiceUnavailableError";
-export { QUEUE_ERROR_MESSAGES } from "./utils/constants";
diff --git a/packages/shared/src/errors/utils/constants.ts b/packages/shared/src/errors/utils/constants.ts
deleted file mode 100644
index e0553c025e..0000000000
--- a/packages/shared/src/errors/utils/constants.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-export const QUEUE_ERROR_MESSAGES = {
- API_KEY_ERROR: "API key for provider",
- NO_DEFAULT_MODEL_ERROR: "No default model or custom model found for project",
- MAPPED_DATA_ERROR:
- "Please ensure the mapped data exists and consider extending the job delay.",
- INVALID_JSON_ERROR: "is not valid JSON",
- TOO_LOW_MAX_TOKENS_ERROR: "Error: Unterminated string in JSON at position",
- OUTPUT_TOKENS_TOO_LONG_ERROR:
- "Could not parse response content as the length limit was reached",
- TIMEOUT_ERROR: "Request timed out",
-};
diff --git a/packages/shared/src/features/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.ts
index 5811835ecb..bb1623f99f 100644
--- a/packages/shared/src/features/scores/interfaces/api/shared.ts
+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts
@@ -50,6 +50,7 @@ export const ScoreFoundationSchema = z.object({
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
queueId: z.string().nullish(),
+ executionTraceId: z.string().nullish(),
});
/**
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index b2982c2834..d7a2899043 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -15,6 +15,7 @@ export * from "./auth/invalidateApiKeys";
export * from "./auth/customSsoProvider";
export * from "./auth/gitHubEnterpriseProvider";
export * from "./llm/fetchLLMCompletion";
+export * from "./llm/errors";
export * from "./llm/utils";
export * from "./llm/types";
export * from "./llm/compileChatMessages";
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index dee8b4cd41..6dcd931840 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -480,6 +480,7 @@ const createAllIngestionSchemas = ({
source: z
.enum(["API", "EVAL", "ANNOTATION"])
.default("API" as ScoreSourceType),
+ executionTraceId: z.string().nullish(),
queueId: z.string().nullish(),
});
diff --git a/packages/shared/src/server/llm/errors.ts b/packages/shared/src/server/llm/errors.ts
new file mode 100644
index 0000000000..4486c69225
--- /dev/null
+++ b/packages/shared/src/server/llm/errors.ts
@@ -0,0 +1,24 @@
+const LLMCompletionErrorName = "LLMCompletionError";
+
+export class LLMCompletionError extends Error {
+ responseStatusCode: number;
+ isRetryable: boolean;
+
+ constructor(params: {
+ message: string;
+ responseStatusCode?: number;
+ isRetryable?: boolean;
+ }) {
+ super(params.message);
+
+ this.name = LLMCompletionErrorName;
+ this.responseStatusCode = params.responseStatusCode ?? 500;
+ this.isRetryable = params.isRetryable ?? false; // Default to false - be explicit about retryability
+
+ Error.captureStackTrace(this);
+ }
+}
+
+export function isLLMCompletionError(e: any): e is LLMCompletionError {
+ return e instanceof Error && e.name === LLMCompletionErrorName;
+}
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index db5145aa60..ff6be03736 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -45,6 +45,8 @@ import { HttpsProxyAgent } from "https-proxy-agent";
import { getInternalTracingHandler } from "./getInternalTracingHandler";
import { decrypt } from "../../encryption";
import { decryptAndParseExtraHeaders } from "./utils";
+import { logger } from "../logger";
+import { LLMCompletionError } from "./errors";
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
@@ -78,7 +80,6 @@ type LLMCompletionParams = {
callbacks?: BaseCallbackHandler[];
maxRetries?: number;
traceSinkParams?: TraceSinkParams;
- throwOnError?: boolean; // default is true
shouldUseLangfuseAPIKey?: boolean;
};
@@ -92,20 +93,14 @@ export async function fetchLLMCompletion(
params: LLMCompletionParams & {
streaming: true;
},
-): Promise<{
- completion: IterableReadableStream<Uint8Array>;
- processTracedEvents: ProcessTracedEvents;
-}>;
+): Promise<IterableReadableStream<Uint8Array>>;
export async function fetchLLMCompletion(
// eslint-disable-next-line no-unused-vars
params: LLMCompletionParams & {
streaming: false;
},
-): Promise<{
- completion: string;
- processTracedEvents: ProcessTracedEvents;
-}>;
+): Promise<string>;
export async function fetchLLMCompletion(
// eslint-disable-next-line no-unused-vars
@@ -113,32 +108,24 @@ export async function fetchLLMCompletion(
streaming: false;
structuredOutputSchema: ZodSchema;
},
-): Promise<{
- completion: Record<string, unknown>;
- processTracedEvents: ProcessTracedEvents;
-}>;
+): Promise<Record<string, unknown>>;
export async function fetchLLMCompletion(
// eslint-disable-next-line no-unused-vars
params: LLMCompletionParams & {
- tools: LLMToolDefinition[];
streaming: false;
+ tools: LLMToolDefinition[];
},
-): Promise<{
- completion: ToolCallResponse;
- processTracedEvents: ProcessTracedEvents;
-}>;
+): Promise<ToolCallResponse>;
export async function fetchLLMCompletion(
params: FetchLLMCompletionParams,
-): Promise<{
- completion:
- | string
- | IterableReadableStream<Uint8Array>
- | Record<string, unknown>
- | ToolCallResponse;
- processTracedEvents: ProcessTracedEvents;
-}> {
+): Promise<
+ | string
+ | IterableReadableStream<Uint8Array>
+ | Record<string, unknown>
+ | ToolCallResponse
+> {
const {
messages,
tools,
@@ -148,7 +135,6 @@ export async function fetchLLMCompletion(
llmConnection,
maxRetries,
traceSinkParams,
- throwOnError = true,
shouldUseLangfuseAPIKey = false,
} = params;
@@ -160,10 +146,23 @@ export async function fetchLLMCompletion(
let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();
if (traceSinkParams) {
- const internalTracingHandler = getInternalTracingHandler(traceSinkParams);
- processTracedEvents = internalTracingHandler.processTracedEvents;
-
- finalCallbacks.push(internalTracingHandler.handler);
+ // Safeguard: All internal traces must use LangfuseInternalTraceEnvironment enum values
+ // This prevents infinite eval loops (user trace β†’ eval β†’ eval trace β†’ another eval)
+ // See corresponding check in worker/src/features/evaluation/evalService.ts createEvalJobs()
+ if (!traceSinkParams.environment?.startsWith("langfuse")) {
+ logger.warn(
+ "Skipping trace creation: internal traces must use LangfuseInternalTraceEnvironment enum",
+ {
+ environment: traceSinkParams.environment,
+ traceId: traceSinkParams.traceId,
+ },
+ );
+ } else {
+ const internalTracingHandler = getInternalTracingHandler(traceSinkParams);
+ processTracedEvents = internalTracingHandler.processTracedEvents;
+
+ finalCallbacks.push(internalTracingHandler.handler);
+ }
}
finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;
@@ -360,13 +359,13 @@ export async function fetchLLMCompletion(
};
try {
+ // Important: await all generations in the try block as otherwise `processTracedEvents` will run too early in finally block
if (params.structuredOutputSchema) {
- return {
- completion: await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
- .withStructuredOutput(params.structuredOutputSchema)
- .invoke(finalMessages, runConfig),
- processTracedEvents,
- };
+ const structuredOutput = await (chatModel as ChatOpenAI) // Typecast necessary due to https://github.com/langchain-ai/langchainjs/issues/6795
+ .withStructuredOutput(params.structuredOutputSchema)
+ .invoke(finalMessages, runConfig);
+
+ return structuredOutput;
}
if (tools && tools.length > 0) {
@@ -382,32 +381,68 @@ export async function fetchLLMCompletion(
const parsed = ToolCallResponseSchema.safeParse(result);
if (!parsed.success) throw Error("Failed to parse LLM tool call result");
- return {
- completion: parsed.data,
- processTracedEvents,
- };
+ return parsed.data;
}
- if (streaming) {
- return {
- completion: await chatModel
- .pipe(new BytesOutputParser())
- .stream(finalMessages, runConfig),
- processTracedEvents,
- };
+ if (streaming)
+ return chatModel
+ .pipe(new BytesOutputParser())
+ .stream(finalMessages, runConfig);
+
+ const completion = await chatModel
+ .pipe(new StringOutputParser())
+ .invoke(finalMessages, runConfig);
+
+ return completion;
+ } catch (e) {
+ const responseStatusCode =
+ (e as any)?.response?.status ?? (e as any)?.status ?? 500;
+ const message = e instanceof Error ? e.message : String(e);
+
+ // Check for non-retryable error patterns in message
+ const nonRetryablePatterns = [
+ "Request timed out",
+ "is not valid JSON",
+ "Unterminated string in JSON at position",
+ "TypeError",
+ ];
+
+ const hasNonRetryablePattern = nonRetryablePatterns.some((pattern) =>
+ message.includes(pattern),
+ );
+
+ // Determine retryability:
+ // - 429 (rate limit): retryable with custom delay
+ // - 5xx (server errors): retryable with custom delay
+ // - 4xx (client errors): not retryable
+ // - Non-retryable patterns: not retryable
+ let isRetryable = false;
+
+ if (
+ e instanceof Error &&
+ (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
+ ) {
+ // Explicit 429 handling
+ isRetryable = true;
+ } else if (responseStatusCode >= 500) {
+ // 5xx errors are retryable (server issues)
+ isRetryable = true;
+ } else if (responseStatusCode === 429) {
+ // Rate limit is retryable
+ isRetryable = true;
}
- return {
- completion: await chatModel
- .pipe(new StringOutputParser())
- .invoke(finalMessages, runConfig),
- processTracedEvents,
- };
- } catch (error) {
- if (throwOnError) {
- throw error;
+ // Override if error message indicates non-retryable issue
+ if (hasNonRetryablePattern) {
+ isRetryable = false;
}
- return { completion: "", processTracedEvents };
+ throw new LLMCompletionError({
+ message,
+ responseStatusCode,
+ isRetryable,
+ });
+ } finally {
+ await processTracedEvents();
}
}
diff --git a/packages/shared/src/server/llm/getInternalTracingHandler.ts b/packages/shared/src/server/llm/getInternalTracingHandler.ts
index ed0b3500ad..cf7e9ecb09 100644
--- a/packages/shared/src/server/llm/getInternalTracingHandler.ts
+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts
@@ -20,19 +20,47 @@ export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {
const events = await handler.langfuse._exportLocalEvents(
traceSinkParams.targetProjectId,
);
- // to add the prompt name and version to only generation-type observations
- const processedEvents = events.map((event: any) => {
- if (event.type === "generation-create" && prompt) {
- return {
- ...event,
- body: {
- ...event.body,
- ...{ promptName: prompt.name, promptVersion: prompt.version },
- },
- };
+
+ // Filter out unnecessary Langchain spans
+ const blockedSpanIds = new Set();
+ const blockedSpanNames = [
+ "RunnableLambda",
+ "StructuredOutputParser",
+ "StrOutputParser",
+ "JsonOutputParser",
+ ];
+
+ for (const event of events) {
+ const eventName = "name" in event.body ? event.body.name : "";
+
+ if (!eventName) continue;
+
+ if (blockedSpanNames.includes(eventName) && "id" in event.body) {
+ blockedSpanIds.add(event.body.id);
}
- return event;
- });
+ }
+
+ const processedEvents = events
+ .filter((event) => {
+ if ("id" in event.body) {
+ return !blockedSpanIds.has(event.body.id);
+ }
+
+ return true;
+ })
+ .map((event: any) => {
+ // to add the prompt name and version to only generation-type observations
+ if (event.type === "generation-create" && prompt) {
+ return {
+ ...event,
+ body: {
+ ...event.body,
+ ...{ promptName: prompt.name, promptVersion: prompt.version },
+ },
+ };
+ }
+ return event;
+ });
await processEventBatch(
JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call
diff --git a/packages/shared/src/server/llm/testModelCall.ts b/packages/shared/src/server/llm/testModelCall.ts
index 68e5b5b144..0058aebb44 100644
--- a/packages/shared/src/server/llm/testModelCall.ts
+++ b/packages/shared/src/server/llm/testModelCall.ts
@@ -21,27 +21,25 @@ export const testModelCall = async ({
prompt?: string;
modelConfig?: ModelConfig | null;
}) => {
- (
- await fetchLLMCompletion({
- streaming: false,
- llmConnection: apiKey,
- messages: [
- {
- role: ChatMessageRole.User,
- content: prompt ?? "mock content",
- type: ChatMessageType.User,
- },
- ],
- modelParams: {
- provider: provider,
- model: model,
- adapter: apiKey.adapter,
- ...modelConfig,
+ await fetchLLMCompletion({
+ streaming: false,
+ llmConnection: apiKey,
+ messages: [
+ {
+ role: ChatMessageRole.User,
+ content: prompt ?? "mock content",
+ type: ChatMessageType.User,
},
- structuredOutputSchema: zodV3.object({
- score: zodV3.string(),
- reasoning: zodV3.string(),
- }),
- })
- ).completion;
+ ],
+ modelParams: {
+ provider: provider,
+ model: model,
+ adapter: apiKey.adapter,
+ ...modelConfig,
+ },
+ structuredOutputSchema: zodV3.object({
+ score: zodV3.string(),
+ reasoning: zodV3.string(),
+ }),
+ });
};
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index fac9d1ab63..faffb93d59 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -495,6 +495,7 @@ export type LLMApiKey =
export enum LangfuseInternalTraceEnvironment {
PromptExperiments = "langfuse-prompt-experiment",
+ LLMJudge = "langfuse-llm-as-a-judge",
}
export type TraceSinkParams = {
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 0ff416191e..fcfa773a81 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -49,6 +49,7 @@ export const TraceQueueEventSchema = z.object({
projectId: z.string(),
traceId: z.string(),
exactTimestamp: z.date().optional(),
+ traceEnvironment: z.string().optional(), // Optional to maintain backward compatibility with existing jobs in queue during deployment. 'optional()' can be removed after queue was exhausted
});
export const TracesQueueEventSchema = z.object({
projectId: z.string(),
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 8cd1d2b8d2..d12155737c 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -187,6 +187,7 @@ export const scoreRecordBaseSchema = z.object({
data_type: z.enum(["NUMERIC", "CATEGORICAL", "BOOLEAN"]).nullish(),
string_value: z.string().nullish(),
queue_id: z.string().nullish(),
+ execution_trace_id: z.string().nullish(),
is_deleted: z.number(),
});
@@ -571,6 +572,7 @@ export const convertPostgresScoreToInsert = (
data_type: score.data_type,
string_value: score.string_value,
queue_id: score.queue_id,
+ execution_trace_id: null, // Postgres scores do not have eval execution traces
created_at: score.created_at?.getTime(),
updated_at: score.updated_at?.getTime(),
event_ts: score.timestamp?.getTime(),
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 9e3e924dfd..1fd3058f91 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -320,6 +320,7 @@ export const getTraceScoresForDatasetRuns = async (
s.data_type as data_type,
s.string_value as string_value,
s.queue_id as queue_id,
+ s.execution_trace_id as execution_trace_id,
s.created_at as created_at,
s.updated_at as updated_at,
s.event_ts as event_ts,
@@ -830,6 +831,7 @@ export async function getScoresUiTable<
author_user_name: string | null;
config_id: string | null;
queue_id: string | null;
+ execution_trace_id: string | null;
created_at: string;
updated_at: string;
// has_metadata is 0 or 1 from ClickHouse, later converted to a boolean
@@ -856,6 +858,7 @@ export async function getScoresUiTable<
traceTags: row.trace_tags,
configId: row.config_id,
queueId: row.queue_id,
+ executionTraceId: row.execution_trace_id,
createdAt: parseClickhouseUTCDateTimeFormat(row.created_at),
updatedAt: parseClickhouseUTCDateTimeFormat(row.updated_at),
stringValue: row.string_value,
@@ -928,6 +931,7 @@ const getScoresUiGeneric = async <T>(props: {
s.source,
s.config_id,
s.queue_id,
+ s.execution_trace_id,
t.user_id,
t.name as trace_name,
t.tags as trace_tags
diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.ts
index cbb626860f..23dfb2a24f 100644
--- a/packages/shared/src/server/repositories/scores_converters.ts
+++ b/packages/shared/src/server/repositories/scores_converters.ts
@@ -33,6 +33,7 @@ export const convertToScore = (row: ScoreRecordReadType): ScoreDomain => {
dataType: row.data_type as ScoreDataType,
stringValue: row.string_value ?? null,
queueId: row.queue_id ?? null,
+ executionTraceId: row.execution_trace_id ?? null,
createdAt: new Date(row.created_at),
updatedAt: new Date(row.updated_at),
};
diff --git a/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts b/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
index 85955e854a..137e12b982 100644
--- a/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
+++ b/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
@@ -1,10 +1,6 @@
import z from "zod/v4";
import { prisma } from "../../../db";
-import {
- ForbiddenError,
- LangfuseNotFoundError,
- QUEUE_ERROR_MESSAGES,
-} from "../../../errors";
+import { ForbiddenError, LangfuseNotFoundError } from "../../../errors";
import { LLMApiKeySchema, ZodModelConfig } from "../../llm/types";
import { testModelCall } from "../../llm/testModelCall";
@@ -178,7 +174,7 @@ export class DefaultEvalModelService {
if (!selectedModel) {
return {
valid: false,
- error: `${QUEUE_ERROR_MESSAGES.NO_DEFAULT_MODEL_ERROR} ${projectId}.`,
+ error: `No default model or custom model configured for project ${projectId}`,
};
}
@@ -195,7 +191,7 @@ export class DefaultEvalModelService {
if (!parsedKey.success) {
return {
valid: false,
- error: `${QUEUE_ERROR_MESSAGES.API_KEY_ERROR} "${selectedModel.provider}" not found in project ${projectId}.`,
+ error: `API key for provider "${selectedModel.provider}" not found in project ${projectId}`,
};
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 41605eeed9..fa7c2124e9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -237,8 +237,8 @@ importers:
specifier: ^0.3.30
langfuse-langchain:
- specifier: 3.38.4
+ specifier: 3.38.6
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -9633,8 +9633,12 @@ packages:
resolution: {integrity: sha512-onTAqcEGhoXuBgqDFXe2t+bt9Vi+5YChRgdz3voM49JKoHwtVZQiUdqTfjSivGR75eSbYoiaIL8IRoio+jaqwg==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-7HJqouMrVOP9MFdu33M4G4uBFyQAIh/DqGYALfs41xqm7t99eZxKcTvt4rYZy67iQAhd58TG3q8+9haGzuLbOA==}
+ resolution: {integrity: sha512-EcZXa+DK9FJdi1I30+u19eKjuBJ04du6j2Nybk19KKCuraLczg/ppkTQcGvc4QOk//OAi3qUHrajUuV74RXsBQ==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-XY7M1R/G7bzihm1cCT1CXKlTLfjHfTiWCPOVm/Ko039Cr3Nz945+HOynqUngjhQUdqH0gAwDsFUZookosARJSw==}
engines: {node: '>=18'}
peerDependencies:
langchain: '>=0.0.157 <0.4.0'
@@ -9643,6 +9647,10 @@ packages:
resolution: {integrity: sha512-2UqMeHLl3DGNX1Nh/cO4jGhk7TzDJ6gjQLlyS9rwFCKVO81xot6b58yeTsTB5YrWupWsOxQtMNoQYIQGOUlH9Q==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-mtwfsNGIYvObRh+NYNGlJQJDiBN+Wr3Hnr++wN25mxuOpSTdXX+JQqVCyAqGL5GD2TAXRZ7COsN42Vmp9krYmg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-+Ez9EoiByeoTu/2BXmEaZ06iPNXM6thWJp02KfBO/raSMyCJ4jw7AkWWa+zBCTm0+Tw1Fj9FOxdqSskyN5nAwg==}
engines: {node: '>=16.0.0'}
@@ -24713,16 +24721,24 @@ snapshots:
dependencies:
mustache: 4.2.0
+ dependencies:
+ mustache: 4.2.0
+
dependencies:
- langfuse: 3.38.4
- langfuse-core: 3.38.4
+ langfuse: 3.38.6
+ langfuse-core: 3.38.6
dependencies:
langfuse-core: 3.38.4
+ dependencies:
+ langfuse-core: 3.38.6
+
dependencies:
chevrotain: 11.0.3
diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsx
index c8c27108b2..7e372ab022 100644
--- a/web/src/components/grouped-score-badge.tsx
+++ b/web/src/components/grouped-score-badge.tsx
@@ -5,8 +5,14 @@ import {
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
import { type LastUserScore, type APIScoreV2 } from "@langfuse/shared";
-import { BracesIcon, MessageCircleMoreIcon } from "lucide-react";
+import {
+ BracesIcon,
+ MessageCircleMoreIcon,
+ ExternalLinkIcon,
+} from "lucide-react";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
+import Link from "next/link";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
const partitionScores = <T extends APIScoreV2 | LastUserScore>(
scores: Record<string, T[]>,
@@ -46,6 +52,8 @@ const ScoreGroupBadge = <T extends APIScoreV2 | LastUserScore>({
compact?: boolean;
badgeClassName?: string;
}) => {
+ const projectId = useProjectIdFromURL();
+
return (
<Badge
variant="tertiary"
@@ -72,6 +80,18 @@ const ScoreGroupBadge = <T extends APIScoreV2 | LastUserScore>({
</HoverCardTrigger>
<HoverCardContent className="max-h-[50dvh] overflow-y-auto whitespace-normal break-normal text-xs">
<p className="whitespace-pre-wrap">{s.comment}</p>
+ {"executionTraceId" in s &&
+ s.executionTraceId &&
+ projectId && (
+ <Link
+ href={`/project/${projectId}/traces/${encodeURIComponent(s.executionTraceId)}`}
+ className="mt-2 flex items-center gap-1 text-blue-600 hover:underline"
+ target="_blank"
+ >
+ <ExternalLinkIcon className="h-3 w-3" />
+ View execution trace
+ </Link>
+ )}
</HoverCardContent>
</HoverCard>
)}
diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsx
index f045f17be0..a0b4ba3ec9 100644
--- a/web/src/components/layouts/status-badge.tsx
+++ b/web/src/components/layouts/status-badge.tsx
@@ -4,6 +4,7 @@ import { type ReactNode } from "react";
const statusCategories = {
active: ["production", "live", "active", "public"],
pending: ["pending", "waiting", "queued"],
+ delayed: ["delayed"],
inactive: ["disabled", "inactive"],
completed: ["completed", "done", "finished"],
error: ["error", "failed"],
@@ -38,6 +39,10 @@ export const StatusBadge = ({
badgeColor = "bg-light-yellow text-dark-yellow";
dotColor = "animate-ping bg-dark-yellow";
dotPingColor = "bg-dark-yellow";
+ } else if (statusCategories.delayed.includes(type.toLowerCase())) {
+ badgeColor = "bg-light-blue text-dark-blue";
+ dotColor = "animate-ping bg-dark-blue";
+ dotPingColor = "bg-dark-blue";
} else if (statusCategories.error.includes(type.toLowerCase())) {
badgeColor = "bg-light-red text-dark-red";
showDot = false;
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 7935519d1c..dbd1c48ef9 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -71,6 +71,7 @@ export type ScoresTableRow = {
jobConfigurationId?: string;
traceTags?: string[];
environment?: string;
+ executionTraceId?: string;
};
function createFilterState(
@@ -326,6 +327,24 @@ export default function ScoresTable({
) : undefined;
},
},
+ {
+ accessorKey: "executionTraceId",
+ id: "executionTraceId",
+ header: "Execution Trace",
+ enableSorting: false,
+ enableHiding: true,
+ defaultHidden: true,
+ size: 100,
+ cell: ({ row }) => {
+ const value = row.getValue("executionTraceId");
+ return typeof value === "string" ? (
+ <TableLink
+ path={`/project/${projectId}/traces/${encodeURIComponent(value)}`}
+ value={value}
+ />
+ ) : undefined;
+ },
+ },
{
accessorKey: "observationId",
id: "observationId",
@@ -616,6 +635,7 @@ export default function ScoresTable({
jobConfigurationId: score.jobConfigurationId ?? undefined,
traceTags: score.traceTags ?? undefined,
environment: score.environment ?? undefined,
+ executionTraceId: score.executionTraceId ?? undefined,
};
};
diff --git a/web/src/features/evals/components/eval-form-descriptions.tsx b/web/src/features/evals/components/eval-form-descriptions.tsx
index 5882854be9..62f037d4ab 100644
--- a/web/src/features/evals/components/eval-form-descriptions.tsx
+++ b/web/src/features/evals/components/eval-form-descriptions.tsx
@@ -24,7 +24,7 @@ export function TimeScopeDescription(props: {
}
return (
- <div>
+ <span>
This configuration will target{" "}
{props.timeScope?.includes("NEW") && props.timeScope?.includes("EXISTING")
? "all future and existing"
@@ -34,6 +34,6 @@ export function TimeScopeDescription(props: {
{props.target === "trace" ? "traces" : "dataset run items"} that match
these filters. Please note that it might take a while for your data to be
evaluated.
- </div>
+ </span>
);
}
diff --git a/web/src/features/evals/components/eval-log.tsx b/web/src/features/evals/components/eval-log.tsx
index 74fffac8b8..39cc860bde 100644
--- a/web/src/features/evals/components/eval-log.tsx
+++ b/web/src/features/evals/components/eval-log.tsx
@@ -24,6 +24,7 @@ export type JobExecutionRow = {
startTime?: string;
endTime?: string;
traceId?: string;
+ executionTraceId?: string;
templateId: string;
evaluatorId: string;
error?: string;
@@ -122,7 +123,21 @@ export default function EvalLogTable({
}),
columnHelper.accessor("traceId", {
id: "traceId",
- header: "Trace",
+ header: "Target Trace",
+ cell: (row) => {
+ const traceId = row.getValue();
+ return traceId ? (
+ <TableLink
+ path={`/project/${projectId}/traces/${encodeURIComponent(traceId)}`}
+ value={traceId}
+ />
+ ) : undefined;
+ },
+ }),
+ columnHelper.accessor("executionTraceId", {
+ id: "executionTraceId",
+ header: "Execution Trace",
+ enableHiding: true,
cell: (row) => {
const traceId = row.getValue();
return traceId ? (
@@ -186,6 +201,7 @@ export default function EvalLogTable({
startTime: jobConfig.startTime?.toLocaleString() ?? undefined,
endTime: jobConfig.endTime?.toLocaleString() ?? undefined,
traceId: jobConfig.jobInputTraceId ?? undefined,
+ executionTraceId: jobConfig.executionTraceId ?? undefined,
templateId: jobConfig.jobTemplateId ?? "",
evaluatorId: jobConfig.jobConfigurationId,
error: jobConfig.error ?? undefined,
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 98e058f1fc..ff54ca89de 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -1261,6 +1261,7 @@ export const evalRouter = createTRPCRouter({
| "jobInputTraceId"
| "jobTemplateId"
| "jobConfigurationId"
+ | "executionTraceId"
| "error"
>
>
@@ -1274,6 +1275,7 @@ export const evalRouter = createTRPCRouter({
je.job_input_trace_id as "jobInputTraceId",
je.job_template_id as "jobTemplateId",
je.job_configuration_id as "jobConfigurationId",
+ je.execution_trace_id as "executionTraceId",
je.error
`,
input.projectId,
diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.ts
index ef96ae6ff4..c0ec3537c5 100644
--- a/web/src/features/natural-language-filters/server/router.ts
+++ b/web/src/features/natural-language-filters/server/router.ts
@@ -130,14 +130,12 @@ export const naturalLanguageFilterRouter = createTRPCRouter({
shouldUseLangfuseAPIKey: true,
});
- await llmCompletion.processTracedEvents();
-
logger.info(
- `LLM completion received: ${JSON.stringify(llmCompletion.completion, null, 2)}`,
+ `LLM completion received: ${JSON.stringify(llmCompletion, null, 2)}`,
);
const parsedFilters = parseFiltersFromCompletion(
- llmCompletion.completion as string,
+ llmCompletion as string,
);
return {
diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.ts
index dbfc4fa813..645a4b54b8 100644
--- a/web/src/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/features/playground/server/chatCompletionHandler.ts
@@ -59,7 +59,7 @@ export default async function chatCompletionHandler(req: NextRequest) {
streaming: false,
structuredOutputSchema,
});
- return NextResponse.json(result.completion);
+ return NextResponse.json(result);
}
// If messages contain tool results, we include tools in the request
@@ -100,18 +100,18 @@ export default async function chatCompletionHandler(req: NextRequest) {
streaming: false,
tools: tools ?? [],
});
- return NextResponse.json(result.completion);
+ return NextResponse.json(result);
}
if (streaming) {
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
...fetchLLMCompletionParams,
streaming,
});
return new StreamingTextResponse(completion);
} else {
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
...fetchLLMCompletionParams,
streaming,
});
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index f352a7eb75..62c2656720 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -72,6 +72,7 @@ type AllScoresReturnType = Omit<ScoreDomain, "metadata"> & {
authorUserImage: string | null;
authorUserName: string | null;
hasMetadata: boolean;
+ executionTraceId: string | null;
};
export const scoresRouter = createTRPCRouter({
@@ -361,6 +362,7 @@ export const scoresRouter = createTRPCRouter({
authorUserId: ctx.session.user.id,
source: ScoreSource.ANNOTATION,
queueId: input.queueId ?? null,
+ executionTraceId: null,
createdAt: new Date(),
updatedAt: new Date(),
timestamp: new Date(),
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index ed1f033629..aaf0b117f3 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -1,7 +1,6 @@
import {
ApiError,
LLMAdapter,
- LangfuseNotFoundError,
ObservationType,
variableMappingList,
} from "@langfuse/shared";
@@ -17,23 +16,17 @@ import {
upsertTrace,
createDatasetRunItemsCh,
createDatasetRunItem,
+ createOrgProjectAndApiKey,
+ LLMCompletionError,
+ LangfuseInternalTraceEnvironment,
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
import Decimal from "decimal.js";
import { sql } from "kysely";
import { afterEach } from "node:test";
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
- vi,
-} from "vitest";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
import { compileHandlebarString } from "../features/utils/utilities";
import { OpenAIServer } from "./network";
-import { pruneDatabase } from "./utils";
import {
createEvalJobs,
evaluate,
@@ -54,6 +47,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
// Import the mocked function
import { fetchLLMCompletion } from "@langfuse/shared/src/server";
+import { UnrecoverableError } from "../errors/UnrecoverableError";
let OPENAI_API_KEY = process.env.OPENAI_API_KEY;
// Check for both OPENAI_API_KEY and LANGFUSE_LLM_CONNECTION_OPENAI_KEY
@@ -71,8 +65,7 @@ const openAIServer = new OpenAIServer({
const jobTimestamp = new Date();
beforeAll(openAIServer.setup);
-beforeEach(async () => {
- await pruneDatabase();
+beforeAll(async () => {
openAIServer.respondWithDefault();
});
afterEach(openAIServer.reset);
@@ -92,11 +85,12 @@ describe("eval service tests", () => {
describe("create eval jobs", () => {
test("creates new 'trace' eval job", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -105,7 +99,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -117,26 +111,31 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].status.toString()).toBe("PENDING");
expect(jobs[0].start_time).not.toBeNull();
}, 10_000);
test("creates new 'dataset' eval job", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const observationId = randomUUID();
const datasetId = randomUUID();
@@ -144,7 +143,7 @@ describe("eval service tests", () => {
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -153,7 +152,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: observationId,
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
type: "GENERATION",
start_time: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
@@ -164,7 +163,7 @@ describe("eval service tests", () => {
.insertInto("datasets")
.values({
id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-dataset",
})
.execute();
@@ -173,7 +172,7 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
source_trace_id: traceId,
source_observation_id: observationId,
@@ -183,7 +182,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -195,22 +194,26 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
datasetItemId: datasetItemId,
observationId: observationId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].job_input_observation_id).toBe(observationId);
expect(jobs[0].job_input_dataset_item_id).toBe(datasetItemId);
@@ -219,13 +222,14 @@ describe("eval service tests", () => {
}, 10_000);
test("handle dataset upsert with cached traces", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const datasetId = randomUUID();
const datasetItemId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -235,7 +239,7 @@ describe("eval service tests", () => {
.insertInto("datasets")
.values({
id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-dataset",
})
.execute();
@@ -244,7 +248,7 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
source_trace_id: traceId,
})
@@ -253,7 +257,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -268,7 +272,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -287,17 +291,22 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
datasetItemId: datasetItemId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
// If this does not throw, we're good.
expect(true).toBe(true);
});
test("creates new eval job for a dataset on upsert of the trace", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const datasetId = randomUUID();
const datasetItemId = randomUUID();
@@ -307,7 +316,7 @@ describe("eval service tests", () => {
.insertInto("datasets")
.values({
id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-dataset",
})
.execute();
@@ -316,7 +325,7 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
})
.execute();
@@ -327,14 +336,14 @@ describe("eval service tests", () => {
id: datasetRunId,
name: randomUUID(),
dataset_id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
})
.execute();
// Create a clickhouse run item
await createDatasetRunItemsCh([
createDatasetRunItem({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
dataset_run_id: datasetRunId,
dataset_item_id: datasetItemId,
@@ -345,7 +354,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -357,18 +366,22 @@ describe("eval service tests", () => {
});
const payloadDataset = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
datasetItemId: datasetItemId,
};
// This should exit early without an error as there is no trace yet.
- await createEvalJobs({ event: payloadDataset, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payloadDataset,
+ jobTimestamp,
+ });
const jobsAfterDataset = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
// No jobs should have been created.
@@ -377,29 +390,31 @@ describe("eval service tests", () => {
// Now upsert the trace and validate that the job was created.
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
});
const payloadTrace = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payloadTrace, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payloadTrace,
+ jobTimestamp,
+ });
const jobsAfterTrace = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobsAfterTrace.length).toBe(1);
- expect(jobsAfterTrace[0].project_id).toBe(
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- );
+ expect(jobsAfterTrace[0].project_id).toBe(projectId);
expect(jobsAfterTrace[0].job_input_trace_id).toBe(traceId);
expect(jobsAfterTrace[0].job_input_dataset_item_id).toBe(datasetItemId);
expect(jobsAfterTrace[0].status.toString()).toBe("PENDING");
@@ -407,6 +422,7 @@ describe("eval service tests", () => {
}, 10_000);
test("creates a new eval job for a dataset only if trace _and_ dataset are available", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const datasetId = randomUUID();
const datasetItemId = randomUUID();
@@ -415,7 +431,7 @@ describe("eval service tests", () => {
.insertInto("datasets")
.values({
id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-dataset",
})
.execute();
@@ -423,7 +439,7 @@ describe("eval service tests", () => {
// Create the trace and send the trace event. No job should be created
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -432,7 +448,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -444,17 +460,21 @@ describe("eval service tests", () => {
});
const payloadTrace = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId,
};
// This should exit early without an error as there is no trace yet.
- await createEvalJobs({ event: payloadTrace, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payloadTrace,
+ jobTimestamp,
+ });
const jobsAfterDataset = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
// No jobs should have been created.
@@ -465,30 +485,32 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
source_trace_id: traceId,
})
.execute();
const payloadDataset = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId,
datasetItemId,
};
- await createEvalJobs({ event: payloadDataset, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payloadDataset,
+ jobTimestamp,
+ });
const jobsAfterTrace = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobsAfterTrace.length).toBe(1);
- expect(jobsAfterTrace[0].project_id).toBe(
- "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
- );
+ expect(jobsAfterTrace[0].project_id).toBe(projectId);
expect(jobsAfterTrace[0].job_input_trace_id).toBe(traceId);
expect(jobsAfterTrace[0].job_input_dataset_item_id).toBe(datasetItemId);
expect(jobsAfterTrace[0].status.toString()).toBe("PENDING");
@@ -496,12 +518,13 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create job for inactive config", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -514,27 +537,32 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(0);
}, 10_000);
test("does not create eval job for existing job execution", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -544,7 +572,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -556,7 +584,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -568,21 +596,29 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
- await createEvalJobs({ event: payload, jobTimestamp }); // calling it twice to check it is only generated once
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ }); // calling it twice to check it is only generated once
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].status.toString()).toBe("PENDING");
expect(jobs[0].start_time).not.toBeNull();
@@ -590,12 +626,13 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create job for inactive config", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -608,29 +645,34 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(0);
}, 10_000);
test("does not create eval job for 0 sample rate", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await kyselyPrisma.$kysely
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -642,7 +684,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -654,27 +696,32 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(0);
}, 10_000);
test("cancels a job if the second event deselects", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
@@ -685,7 +732,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -699,7 +746,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -716,7 +763,7 @@ describe("eval service tests", () => {
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -736,11 +783,15 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
};
- await createEvalJobs({ event: payload, jobTimestamp });
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
// Wait for .5s
await new Promise((resolve) => setTimeout(resolve, 500));
@@ -748,7 +799,7 @@ describe("eval service tests", () => {
// update the trace to deselect the trace
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "b",
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
@@ -756,6 +807,7 @@ describe("eval service tests", () => {
});
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: payload,
jobTimestamp,
}); // calling it twice to check it is only generated once
@@ -763,11 +815,11 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].status.toString()).toBe("CANCELLED");
expect(jobs[0].start_time).not.toBeNull();
@@ -775,10 +827,11 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create eval job for existing traces if time scope is EXISTING but handler enforces NEW only", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const trace = createTrace({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
id: traceId,
});
@@ -787,7 +840,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -803,7 +856,7 @@ describe("eval service tests", () => {
const jobConfiguration2 = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -816,12 +869,13 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
configId: jobConfiguration.id,
};
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: payload,
jobTimestamp,
enforcedJobTimeScope: "NEW", // the config must contain NEW
@@ -830,7 +884,7 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.where("job_configuration_id", "in", [
jobConfiguration.id,
jobConfiguration2.id,
@@ -842,11 +896,12 @@ describe("eval service tests", () => {
}, 10_000);
test("does create eval for trace which is way in the past if timestamp is provided", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const timestamp = new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 1);
const trace = createTrace({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
id: traceId,
timestamp: timestamp.getTime(),
});
@@ -856,7 +911,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -869,13 +924,14 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
configId: jobConfiguration.id,
timestamp: timestamp,
};
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: payload,
jobTimestamp,
enforcedJobTimeScope: "NEW", // the config must contain NEW
@@ -884,7 +940,7 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.where("job_configuration_id", "in", [jobConfiguration.id])
.where("job_input_trace_id", "=", traceId)
.execute();
@@ -893,17 +949,18 @@ describe("eval service tests", () => {
}, 10_000);
test("does create eval for observation which is way in the past if timestamp is provided", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const timestamp = new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 1);
const trace = createTrace({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
id: traceId,
timestamp: timestamp.getTime(),
});
const observation = createObservation({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
id: randomUUID(),
start_time: timestamp.getTime(),
});
@@ -914,7 +971,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -927,7 +984,7 @@ describe("eval service tests", () => {
});
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
configId: jobConfiguration.id,
timestamp: timestamp,
@@ -935,6 +992,7 @@ describe("eval service tests", () => {
};
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: payload,
jobTimestamp,
enforcedJobTimeScope: "EXISTING", // the config must contain NEW
@@ -943,7 +1001,7 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.where("job_configuration_id", "in", [jobConfiguration.id])
.execute();
@@ -951,12 +1009,13 @@ describe("eval service tests", () => {
}, 10_000);
test("create eval for trace with timestamp in the near future", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: JSON.parse("[]"),
jobType: "EVAL",
delay: 0,
@@ -969,7 +1028,7 @@ describe("eval service tests", () => {
});
const trace = createTrace({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
id: traceId,
timestamp: new Date(Date.now() + 1000 * 60 * 60 * 24).getTime(),
});
@@ -977,8 +1036,9 @@ describe("eval service tests", () => {
await createTracesCh([trace]);
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId: traceId,
},
jobTimestamp,
@@ -987,13 +1047,14 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
}, 10_000);
test("creates dataset eval job with cached dataset item filtering - positive match", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const datasetId1 = randomUUID();
const datasetId2 = randomUUID();
@@ -1003,7 +1064,7 @@ describe("eval service tests", () => {
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -1015,17 +1076,17 @@ describe("eval service tests", () => {
.values([
{
id: datasetId1,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "dataset-alpha",
},
{
id: datasetId2,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "dataset-beta",
},
{
id: datasetId3,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "dataset-gamma",
},
])
@@ -1036,7 +1097,7 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId2,
source_trace_id: traceId,
})
@@ -1047,7 +1108,7 @@ describe("eval service tests", () => {
.insertInto("dataset_runs")
.values({
id: datasetRunId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: randomUUID(),
dataset_id: datasetId2,
})
@@ -1056,7 +1117,7 @@ describe("eval service tests", () => {
// Create a clickhouse run item that references dataset 2 and the new trace.
await createDatasetRunItemsCh([
createDatasetRunItem({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId2,
dataset_item_id: datasetItemId,
trace_id: traceId,
@@ -1068,7 +1129,7 @@ describe("eval service tests", () => {
data: [
{
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "stringOptions",
@@ -1086,7 +1147,7 @@ describe("eval service tests", () => {
},
{
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "stringOptions",
@@ -1104,7 +1165,7 @@ describe("eval service tests", () => {
},
{
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "stringOptions",
@@ -1124,8 +1185,9 @@ describe("eval service tests", () => {
});
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId,
},
jobTimestamp,
@@ -1134,12 +1196,12 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
// Should create exactly one job for the matching dataset (dataset-beta)
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].job_input_dataset_item_id).toBe(datasetItemId);
expect(jobs[0].status.toString()).toBe("PENDING");
@@ -1155,6 +1217,7 @@ describe("eval service tests", () => {
}, 10_000);
test("creates no dataset eval jobs with cached dataset item filtering - negative match", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const datasetId1 = randomUUID();
const datasetId2 = randomUUID();
@@ -1162,7 +1225,7 @@ describe("eval service tests", () => {
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
timestamp: convertDateToClickhouseDateTime(new Date()),
created_at: convertDateToClickhouseDateTime(new Date()),
updated_at: convertDateToClickhouseDateTime(new Date()),
@@ -1174,12 +1237,12 @@ describe("eval service tests", () => {
.values([
{
id: datasetId1,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "dataset-alpha",
},
{
id: datasetId2,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "dataset-beta",
},
])
@@ -1190,7 +1253,7 @@ describe("eval service tests", () => {
.insertInto("dataset_items")
.values({
id: datasetItemId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId1,
source_trace_id: traceId,
})
@@ -1210,7 +1273,7 @@ describe("eval service tests", () => {
data: [
{
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "stringOptions",
@@ -1228,7 +1291,7 @@ describe("eval service tests", () => {
},
{
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "stringOptions",
@@ -1248,8 +1311,9 @@ describe("eval service tests", () => {
});
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
traceId,
},
jobTimestamp,
@@ -1258,7 +1322,7 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
// Should create no jobs since dataset-delta doesn't match any filter
@@ -1268,12 +1332,13 @@ describe("eval service tests", () => {
describe("execute evals", () => {
test("evals a valid 'trace' event", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
openAIServer.respondWithDefault();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -1287,7 +1352,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1304,7 +1369,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1329,7 +1394,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'PENDING'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1341,7 +1406,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -1351,7 +1416,7 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
@@ -1361,11 +1426,11 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].status.toString()).toBe("COMPLETED");
expect(jobs[0].start_time).not.toBeNull();
@@ -1373,6 +1438,7 @@ describe("eval service tests", () => {
}, 50_000);
test("fails to eval without llm api key", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const templateId = randomUUID();
@@ -1380,7 +1446,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1397,7 +1463,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1422,7 +1488,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'PENDING'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1431,38 +1497,39 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
await expect(evaluate({ event: payload })).rejects.toThrowError(
- new LangfuseNotFoundError(
- `API key for provider "openai" not found in project 7a88fb47-b4e2-43b8-a06c-a5ce950dc53a.`,
+ new UnrecoverableError(
+ `Invalid model configuration for job ${jobExecutionId}: API key for provider "openai" not found in project ${projectId}`,
),
);
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
// the job will be failed when the exception is caught in the worker consumer
expect(jobs[0].status.toString()).toBe("PENDING");
}, 10_000);
test("fails to eval on openai error", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
openAIServer.respondWithError(401, "Not authorized");
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -1476,7 +1543,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1493,7 +1560,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1518,7 +1585,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'PENDING'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1530,7 +1597,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -1540,34 +1607,36 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
await expect(evaluate({ event: payload })).rejects.toThrowError(
- new ApiError(
- "Failed to call LLM: Error: 401 status code (no body)\n" +
+ new LLMCompletionError({
+ message:
+ "401 status code (no body)\n" +
"\n" +
"Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/MODEL_AUTHENTICATION/\n",
- 401,
- ),
+ responseStatusCode: 401,
+ }),
);
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
// the job will be failed when the exception is caught in the worker consumer
expect(jobs[0].status.toString()).toBe("PENDING");
}, 10_000);
test("evals should cancel if job is cancelled", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const templateId = randomUUID();
@@ -1575,7 +1644,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1592,7 +1661,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1616,7 +1685,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'CANCELLED'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1625,7 +1694,7 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
@@ -1635,13 +1704,14 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(0);
}, 10_000);
test("evals a valid 'trace' event and inserts score to ingestion pipeline", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
openAIServer.respondWithDefault();
const traceId = randomUUID();
@@ -1650,7 +1720,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1667,7 +1737,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1692,7 +1762,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'PENDING'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1704,7 +1774,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -1714,7 +1784,7 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
@@ -1724,11 +1794,11 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
expect(jobs[0].status.toString()).toBe("COMPLETED");
expect(jobs[0].start_time).not.toBeNull();
@@ -1736,6 +1806,7 @@ describe("eval service tests", () => {
}, 20_000);
test("handles LLM timeout gracefully", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
// Set up the mock to simulate timeout for this test only
const mockFetchLLMCompletion = vi.mocked(fetchLLMCompletion);
mockFetchLLMCompletion.mockRejectedValueOnce(
@@ -1746,7 +1817,7 @@ describe("eval service tests", () => {
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -1760,7 +1831,7 @@ describe("eval service tests", () => {
.insertInto("eval_templates")
.values({
id: templateId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-template",
version: 1,
prompt: "Please evaluate toxicity {{input}} {{output}}",
@@ -1777,7 +1848,7 @@ describe("eval service tests", () => {
const jobConfiguration = await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
filter: [
{
type: "string",
@@ -1802,7 +1873,7 @@ describe("eval service tests", () => {
.insertInto("job_executions")
.values({
id: jobExecutionId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
job_configuration_id: jobConfiguration.id,
status: sql`'PENDING'::"JobExecutionStatus"`,
start_time: new Date(),
@@ -1814,7 +1885,7 @@ describe("eval service tests", () => {
.insertInto("llm_api_keys")
.values({
id: randomUUID(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
secret_key: encrypt(String(OPENAI_API_KEY)),
provider: "openai",
adapter: LLMAdapter.OpenAI,
@@ -1824,7 +1895,7 @@ describe("eval service tests", () => {
.execute();
const payload = {
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
jobExecutionId: jobExecutionId,
delay: 1000,
};
@@ -1837,11 +1908,11 @@ describe("eval service tests", () => {
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.selectAll()
- .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("project_id", "=", projectId)
.execute();
expect(jobs.length).toBe(1);
- expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].project_id).toBe(projectId);
expect(jobs[0].job_input_trace_id).toBe(traceId);
// Job should still be PENDING because the error will be handled by the queue processor
expect(jobs[0].status.toString()).toBe("PENDING");
@@ -1853,6 +1924,7 @@ describe("eval service tests", () => {
describe("test variable extraction", () => {
test("extracts variables from a dataset item", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const datasetId = randomUUID();
const datasetItemId = randomUUID();
const traceId = randomUUID();
@@ -1861,7 +1933,7 @@ describe("eval service tests", () => {
.insertInto("datasets")
.values({
id: datasetId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "test-dataset",
})
.execute();
@@ -1872,7 +1944,7 @@ describe("eval service tests", () => {
id: datasetItemId,
input: { input: "This is a great prompt" },
expected_output: { expected_output: "This is a great response" },
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
dataset_id: datasetId,
})
.execute();
@@ -1891,7 +1963,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
datasetItemId: datasetItemId,
@@ -1911,11 +1983,12 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a trace", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
environment: "production",
input: JSON.stringify({ input: "This is a great prompt" }),
@@ -1939,7 +2012,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
@@ -1960,11 +2033,12 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a observation", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -1976,7 +2050,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "great-llm-name",
type: "GENERATION",
environment: "production",
@@ -2003,7 +2077,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
@@ -2024,6 +2098,7 @@ describe("eval service tests", () => {
}, 10_000);
test("fails if observation is not present", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
const variableMapping = variableMappingList.parse([
@@ -2043,24 +2118,25 @@ describe("eval service tests", () => {
await expect(
extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
}),
).rejects.toThrowError(
- new LangfuseNotFoundError(
+ new UnrecoverableError(
`Observation great-llm-name for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
),
);
}, 10_000);
test("does not fail if observation data is null", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -2073,7 +2149,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "great-llm-name",
type: "GENERATION",
start_time: convertDateToClickhouseDateTime(new Date()),
@@ -2097,7 +2173,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
@@ -2118,11 +2194,12 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a youngest observation", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -2134,7 +2211,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "great-llm-name",
type: "GENERATION",
input: JSON.stringify({ huhu: "This is a great prompt" }),
@@ -2149,7 +2226,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: "great-llm-name",
type: "GENERATION",
input: JSON.stringify({ huhu: "This is a great prompt again" }),
@@ -2177,7 +2254,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
@@ -2204,11 +2281,12 @@ describe("eval service tests", () => {
)(
"extracts variables from a %s observation",
async (observationType) => {
+ const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
await upsertTrace({
id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
user_id: "a",
input: JSON.stringify({ input: "This is a great prompt" }),
output: JSON.stringify({ output: "This is a great response" }),
@@ -2220,7 +2298,7 @@ describe("eval service tests", () => {
await upsertObservation({
id: randomUUID(),
trace_id: traceId,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
name: `great-${observationType.toLowerCase()}-name`,
type: observationType,
environment: "production",
@@ -2247,7 +2325,7 @@ describe("eval service tests", () => {
]);
const result = await extractVariablesFromTracingData({
- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ projectId,
variables: ["input", "output"],
traceId: traceId,
variableMapping: variableMapping,
@@ -2300,4 +2378,478 @@ describe("eval service tests", () => {
expect(!requiresDatabaseLookup(mixedFilters)).toBe(false);
});
+
+ describe("eval execution tracing", () => {
+ test("creates trace for eval execution and stores trace ID in score", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+ const jobExecutionId = randomUUID();
+ const templateId = randomUUID();
+
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ await kyselyPrisma.$kysely
+ .insertInto("llm_api_keys")
+ .values({
+ id: randomUUID(),
+ project_id: projectId,
+ secret_key: encrypt(String(OPENAI_API_KEY)),
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ custom_models: [],
+ display_secret_key: "123456",
+ })
+ .execute();
+
+ await prisma.evalTemplate.create({
+ data: {
+ id: templateId,
+ name: "test-evaluator",
+ projectId,
+ model: "gpt-3.5-turbo",
+ provider: "openai",
+ prompt: "Please evaluate: {{input}}",
+ version: 1,
+ vars: ["input"],
+ outputSchema: {
+ score: "score",
+ reasoning: "reasoning",
+ },
+ },
+ });
+
+ const configId = randomUUID();
+ await prisma.jobConfiguration.create({
+ data: {
+ id: configId,
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "test-score",
+ variableMapping: JSON.parse(
+ '[{"langfuseObject":"trace","selectedColumnId":"input","templateVariable":"input"}]',
+ ),
+ status: "ACTIVE",
+ evalTemplateId: templateId,
+ },
+ });
+
+ await prisma.jobExecution.create({
+ data: {
+ id: jobExecutionId,
+ projectId,
+ jobConfigurationId: configId,
+ jobInputTraceId: traceId,
+ jobTemplateId: templateId,
+ status: "PENDING",
+ startTime: new Date(),
+ },
+ });
+
+ // Mock fetchLLMCompletion to capture the traceSinkParams
+ let capturedTraceSinkParams: any = null;
+
+ vi.mocked(fetchLLMCompletion).mockImplementationOnce(
+ async (params: any) => {
+ capturedTraceSinkParams = params.traceSinkParams;
+ return { score: 0.8, reasoning: "Good response" };
+ },
+ );
+
+ await evaluate({
+ event: {
+ projectId,
+ jobExecutionId,
+ },
+ });
+
+ // Verify traceSinkParams were passed to fetchLLMCompletion
+ expect(capturedTraceSinkParams).toBeDefined();
+ expect(capturedTraceSinkParams.targetProjectId).toBe(projectId);
+ expect(capturedTraceSinkParams.traceId).toMatch(/^[a-f0-9]{32}$/);
+ expect(capturedTraceSinkParams.traceName).toBe(
+ "Execute evaluator: test-evaluator",
+ );
+ expect(capturedTraceSinkParams.environment).toBe(
+ LangfuseInternalTraceEnvironment.LLMJudge,
+ );
+ expect(capturedTraceSinkParams.metadata).toMatchObject({
+ job_execution_id: jobExecutionId,
+ job_configuration_id: configId,
+ target_trace_id: traceId,
+ score_id: capturedTraceSinkParams.metadata.score_id,
+ });
+ expect(capturedTraceSinkParams.metadata.score_id).toBeDefined();
+ }, 15_000);
+ });
+
+ describe("internal trace environment filtering", () => {
+ test("does not create eval jobs for trace-upsert with LLMJudge environment", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ // Create trace with LLMJudge environment
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ environment: LangfuseInternalTraceEnvironment.LLMJudge,
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ traceEnvironment: LangfuseInternalTraceEnvironment.LLMJudge,
+ };
+
+ // Attempt to create eval jobs
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify no eval jobs were created
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(0);
+ }, 10_000);
+
+ test("does not create eval jobs for trace-upsert with PromptExperiments environment", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ // Create trace with PromptExperiments environment
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ traceEnvironment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ };
+
+ // Attempt to create eval jobs
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify no eval jobs were created
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(0);
+ }, 10_000);
+
+ test("creates eval jobs for dataset-run-item-upsert with PromptExperiments environment", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+ const datasetId = randomUUID();
+ const datasetItemId = randomUUID();
+ const datasetRunId = randomUUID();
+
+ // Create dataset infrastructure
+ await kyselyPrisma.$kysely
+ .insertInto("datasets")
+ .values({
+ id: datasetId,
+ project_id: projectId,
+ name: "test-dataset",
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_items")
+ .values({
+ id: datasetItemId,
+ project_id: projectId,
+ dataset_id: datasetId,
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_runs")
+ .values({
+ id: datasetRunId,
+ name: randomUUID(),
+ dataset_id: datasetId,
+ project_id: projectId,
+ })
+ .execute();
+
+ // Create clickhouse run item
+ await createDatasetRunItemsCh([
+ createDatasetRunItem({
+ project_id: projectId,
+ dataset_id: datasetId,
+ dataset_run_id: datasetRunId,
+ dataset_item_id: datasetItemId,
+ trace_id: traceId,
+ }),
+ ]);
+
+ // Create trace with PromptExperiments environment
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active dataset eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "dataset",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ datasetItemId,
+ traceEnvironment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ };
+
+ // Attempt to create eval jobs via dataset-run-item-upsert
+ await createEvalJobs({
+ sourceEventType: "dataset-run-item-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify eval jobs WERE created (experiments need this)
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ expect(jobs[0].job_input_dataset_item_id).toBe(datasetItemId);
+ }, 10_000);
+
+ test("creates eval jobs for trace-upsert with production environment", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ // Create trace with production environment
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ environment: "production",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ traceEnvironment: "production",
+ };
+
+ // Attempt to create eval jobs
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify eval jobs WERE created (normal traces should be evaluated)
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ }, 10_000);
+
+ test("creates eval jobs for trace-upsert with undefined environment", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ // Create trace with undefined environment
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ // traceEnvironment intentionally omitted
+ };
+
+ // Attempt to create eval jobs
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify eval jobs WERE created (traces without environment should be evaluated)
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ }, 10_000);
+
+ test("does not create eval jobs for trace-upsert with 'langfuse' environment without hyphen", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ // Create trace with "langfuse" environment (no hyphen)
+ await upsertTrace({
+ id: traceId,
+ project_id: projectId,
+ environment: "langfuse",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ // Create an active eval configuration
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId,
+ traceEnvironment: "langfuse",
+ };
+
+ // Attempt to create eval jobs
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ // Verify eval jobs WERE created (only "langfuse-" prefix is blocked)
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", projectId)
+ .execute();
+
+ expect(jobs.length).toBe(0);
+ }, 10_000);
+ });
});
diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.ts
index 6ab10cbd49..a08b024b8e 100644
--- a/worker/src/__tests__/experimentsService.test.ts
+++ b/worker/src/__tests__/experimentsService.test.ts
@@ -6,11 +6,10 @@ import { LLMAdapter } from "@langfuse/shared";
import { encrypt } from "@langfuse/shared/encryption";
import { createExperimentJobClickhouse } from "../features/experiments/experimentServiceClickhouse";
import { logger } from "@langfuse/shared/src/server";
-import { callLLM } from "../features/utils/utilities";
+import { fetchLLMCompletion } from "@langfuse/shared/src/server";
// Mock LLM completion call
vi.mock("../features/utils/utilities", () => ({
- callLLM: vi.fn().mockResolvedValue({ id: "test-id" }),
compileHandlebarString: vi.fn().mockImplementation((str, context) => {
// Simple mock that replaces handlebars variables with their values
return str.replace(/\{\{(\w+)\}\}/g, (_, key) => context[key] || "");
@@ -22,6 +21,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
return {
...actual,
+ fetchLLMCompletion: vi.fn().mockResolvedValue({ id: "test-id" }),
logger: {
info: vi.fn(),
error: vi.fn(),
diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.ts
index d3cde8a00b..ef8a9771be 100644
--- a/worker/src/__tests__/llmConnections.test.ts
+++ b/worker/src/__tests__/llmConnections.test.ts
@@ -65,7 +65,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -93,7 +93,7 @@ describe("LLM Connection Tests", () => {
test("structured output - eval schema", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -128,7 +128,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -174,7 +174,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -204,7 +204,7 @@ describe("LLM Connection Tests", () => {
test("structured output - eval schema", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -241,7 +241,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -301,7 +301,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -330,7 +330,7 @@ describe("LLM Connection Tests", () => {
test("structured output - eval schema", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -366,7 +366,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -442,7 +442,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -472,7 +472,7 @@ describe("LLM Connection Tests", () => {
test.skip("structured output - eval schema", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -505,7 +505,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVars();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -552,7 +552,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -581,7 +581,7 @@ describe("LLM Connection Tests", () => {
test("structured output - eval schema", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -617,7 +617,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -664,7 +664,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -694,7 +694,7 @@ describe("LLM Connection Tests", () => {
test("structured output - eval schema", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
@@ -731,7 +731,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const { completion } = await fetchLLMCompletion({
+ const completion = await fetchLLMCompletion({
streaming: false,
messages: [
{
diff --git a/worker/src/errors/UnrecoverableError.ts b/worker/src/errors/UnrecoverableError.ts
new file mode 100644
index 0000000000..66bb9af82e
--- /dev/null
+++ b/worker/src/errors/UnrecoverableError.ts
@@ -0,0 +1,15 @@
+const UnrecoverableErrorName = "UnrecoverableError";
+
+export class UnrecoverableError extends Error {
+ constructor(message: string) {
+ super(message);
+
+ this.name = UnrecoverableErrorName;
+
+ Error.captureStackTrace(this);
+ }
+}
+
+export function isUnrecoverableError(e: any): e is UnrecoverableError {
+ return e instanceof Error && e.name === UnrecoverableErrorName;
+}
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 1028b02e84..d5afd72bbb 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -2,7 +2,7 @@ import { randomUUID } from "crypto";
import { sql } from "kysely";
import { z } from "zod/v4";
import { z as zodV3 } from "zod/v3";
-import { JobConfigState } from "@prisma/client";
+import { JobConfigState, JobExecutionStatus } from "@prisma/client";
import {
QueueJobs,
QueueName,
@@ -16,7 +16,6 @@ import {
EvalExecutionQueue,
checkTraceExistsAndGetTimestamp,
checkObservationExists,
- DatasetRunItemUpsertEventType,
TraceQueueEventType,
StorageService,
StorageServiceFactory,
@@ -30,6 +29,8 @@ import {
getCurrentSpan,
getDatasetItemIdsByTraceIdCh,
mapDatasetRunItemFilterColumn,
+ fetchLLMCompletion,
+ LangfuseInternalTraceEnvironment,
} from "@langfuse/shared/src/server";
import {
mapTraceFilterColumn,
@@ -37,10 +38,8 @@ import {
} from "./traceFilterUtils";
import {
ChatMessageRole,
- LangfuseNotFoundError,
Prisma,
singleFilter,
- InvalidRequestError,
variableMappingList,
evalDatasetFormFilterCols,
availableDatasetEvalVariables,
@@ -51,13 +50,12 @@ import {
TraceDomain,
Observation,
DatasetItem,
- QUEUE_ERROR_MESSAGES,
} from "@langfuse/shared";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
-import { backOff } from "exponential-backoff";
-import { callLLM, compileHandlebarString } from "../utils";
+import { compileHandlebarString, createW3CTraceId } from "../utils";
import { env } from "../../env";
import { JSONPath } from "jsonpath-plus";
+import { UnrecoverableError } from "../../errors/UnrecoverableError";
let s3StorageServiceClient: StorageService;
@@ -150,18 +148,30 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
*
* ─────────────────────────────────────────────────────────────────────────────────────────── β”‚
*/
+type CreateEvalJobsParams = {
+ jobTimestamp: Date;
+ enforcedJobTimeScope?: JobTimeScope;
+} & (
+ | {
+ sourceEventType: "trace-upsert";
+ event: TraceQueueEventType;
+ }
+ | {
+ sourceEventType: "dataset-run-item-upsert";
+ event: TraceQueueEventType;
+ }
+ | {
+ sourceEventType: "ui-create-eval";
+ event: CreateEvalQueueEventType;
+ }
+);
+
export const createEvalJobs = async ({
event,
+ sourceEventType,
jobTimestamp,
enforcedJobTimeScope,
-}: {
- event:
- | TraceQueueEventType
- | DatasetRunItemUpsertEventType
- | CreateEvalQueueEventType;
- jobTimestamp: Date;
- enforcedJobTimeScope?: JobTimeScope;
-}) => {
+}: CreateEvalJobsParams) => {
const span = getCurrentSpan();
if (span) {
span.setAttribute("messaging.bullmq.job.input.projectId", event.projectId);
@@ -209,6 +219,34 @@ export const createEvalJobs = async ({
`Creating eval jobs for trace ${event.traceId} on project ${event.projectId}`,
);
+ // Early exit: Skip eval job creation for internal Langfuse traces from trace-upsert queue
+ //
+ // CONTEXT: Prevent infinite eval loops
+ // Without this safeguard: user trace β†’ eval β†’ eval trace β†’ another eval β†’ infinite loop
+ //
+ // IMPLEMENTATION:
+ // - Block ALL traces with environment starting with "langfuse-" when coming from trace-upsert queue
+ // - This excludes traces from prompt experiments that come via dataset-run-item-upsert queue
+ // - Internal traces (e.g., eval executions) use LangfuseInternalTraceEnvironment enum values
+ //
+ // DUAL SAFEGUARD:
+ // - This check prevents eval job CREATION for internal traces
+ // - fetchLLMCompletion.ts enforces that internal traces MUST use "langfuse-" prefix
+ //
+ // See: packages/shared/src/server/llm/fetchLLMCompletion.ts (enforcement)
+ // See: packages/shared/src/server/llm/types.ts (LangfuseInternalTraceEnvironment enum)
+ if (
+ sourceEventType === "trace-upsert" &&
+ event.traceEnvironment?.startsWith("langfuse")
+ ) {
+ logger.debug("Skipping eval job creation for internal Langfuse trace", {
+ traceId: event.traceId,
+ environment: event.traceEnvironment,
+ });
+
+ return;
+ }
+
// Optimization: Fetch trace data once if we have multiple configs
let cachedTrace: TraceDomain | undefined | null = null;
recordIncrement("langfuse.evaluation-execution.config_count", configs.length);
@@ -542,12 +580,17 @@ export const createEvalJobs = async ({
logger.debug(
`Cancelling eval job for config ${config.id} and trace ${event.traceId}`,
);
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'CANCELLED'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .where("id", "=", existingJob[0].id)
- .execute();
+
+ await prisma.jobExecution.update({
+ where: {
+ id: existingJob[0].id,
+ projectId: event.projectId,
+ },
+ data: {
+ status: JobExecutionStatus.CANCELLED,
+ endTime: new Date(),
+ },
+ });
}
}
}
@@ -563,12 +606,12 @@ export const evaluate = async ({
`Evaluating job ${event.jobExecutionId} for project ${event.projectId}`,
);
// first, fetch all the context required for the evaluation
- const job = await kyselyPrisma.$kysely
- .selectFrom("job_executions")
- .selectAll()
- .where("id", "=", event.jobExecutionId)
- .where("project_id", "=", event.projectId)
- .executeTakeFirst();
+ const job = await prisma.jobExecution.findFirst({
+ where: {
+ id: event.jobExecutionId,
+ projectId: event.projectId,
+ },
+ });
if (!job) {
logger.info(
@@ -577,37 +620,38 @@ export const evaluate = async ({
return;
}
- if (job.status === "CANCELLED" || !job?.job_input_trace_id) {
+ if (job.status === "CANCELLED" || !job?.jobInputTraceId) {
logger.debug(`Job ${job.id} for project ${event.projectId} was cancelled.`);
- await kyselyPrisma.$kysely
- .deleteFrom("job_executions")
- .where("id", "=", job.id)
- .where("project_id", "=", event.projectId)
- .execute();
+ await prisma.jobExecution.delete({
+ where: {
+ id: job.id,
+ projectId: event.projectId,
+ },
+ });
return;
}
- const config = await kyselyPrisma.$kysely
- .selectFrom("job_configurations")
- .selectAll()
- .where("id", "=", job.job_configuration_id)
- .where("project_id", "=", event.projectId)
- .executeTakeFirstOrThrow();
+ const config = await prisma.jobConfiguration.findFirst({
+ where: {
+ id: job.jobConfigurationId,
+ projectId: event.projectId,
+ },
+ });
- if (!config || !config.eval_template_id) {
+ if (!config || !config.evalTemplateId) {
logger.error(
- `Eval template not found for config ${config.eval_template_id}`,
+ `Evaluation template not found for config: ${config?.evalTemplateId}`,
);
- throw new InvalidRequestError(
- `Eval template not found for config ${config.eval_template_id}`,
+ throw new UnrecoverableError(
+ `Evaluation template not found for config: ${config?.evalTemplateId}`,
);
}
const template = await prisma.evalTemplate.findFirstOrThrow({
where: {
- id: config.eval_template_id,
+ id: config.evalTemplateId,
OR: [{ projectId: event.projectId }, { projectId: null }],
},
});
@@ -618,16 +662,16 @@ export const evaluate = async ({
// selectedcolumnid is not safe to use, needs validation in extractVariablesFromTrace()
const parsedVariableMapping = variableMappingList.parse(
- config.variable_mapping,
+ config.variableMapping,
);
// extract the variables which need to be inserted into the prompt
const mappingResult = await extractVariablesFromTracingData({
projectId: event.projectId,
variables: template.vars,
- traceId: job.job_input_trace_id,
- traceTimestamp: job.job_input_trace_timestamp ?? undefined,
- datasetItemId: job.job_input_dataset_item_id ?? undefined,
+ traceId: job.jobInputTraceId,
+ traceTimestamp: job.jobInputTraceTimestamp ?? undefined,
+ datasetItemId: job.jobInputDatasetItemId ?? undefined,
variableMapping: parsedVariableMapping,
});
@@ -666,7 +710,9 @@ export const evaluate = async ({
.parse(template.outputSchema);
if (!parsedOutputSchema) {
- throw new InvalidRequestError("Output schema not found");
+ throw new UnrecoverableError(
+ "Output schema not found in evaluation template",
+ );
}
const evalScoreSchema = zodV3.object({
@@ -685,7 +731,9 @@ export const evaluate = async ({
logger.warn(
`Evaluating job ${event.jobExecutionId} will fail. ${modelConfig.error}`,
);
- throw new LangfuseNotFoundError(modelConfig.error);
+ throw new UnrecoverableError(
+ `Invalid model configuration for job ${event.jobExecutionId}: ${modelConfig.error}`,
+ );
}
const messages = [
@@ -696,25 +744,50 @@ export const evaluate = async ({
} as const,
];
- const llmOutput = await backOff(
- async () =>
- await callLLM({
- llmApiKey: modelConfig.config.apiKey,
- messages,
- modelParams: modelConfig.config.modelParams ?? {},
- provider: modelConfig.config.provider,
- model: modelConfig.config.model,
- structuredOutputSchema: evalScoreSchema,
- }),
- {
- numOfAttempts: 1, // turn off retries as Langchain is doing that for us already.
- },
+ // persist the score and update the job status
+ const scoreId = randomUUID();
+
+ // Use deterministic trace ID from job execution ID. Retries will be in same trace.
+ const executionTraceId = createW3CTraceId(event.jobExecutionId);
+
+ const executionMetadata = Object.fromEntries(
+ Object.entries({
+ job_execution_id: event.jobExecutionId,
+ job_configuration_id: job.jobConfigurationId,
+ target_trace_id: job.jobInputTraceId,
+ target_observation_id: job.jobInputObservationId,
+ target_dataset_item_id: job.jobInputDatasetItemId,
+ }).filter(([, v]) => v != null),
);
+ const llmOutput = await fetchLLMCompletion({
+ streaming: false,
+ llmConnection: modelConfig.config.apiKey,
+ messages,
+ modelParams: {
+ provider: modelConfig.config.provider,
+ model: modelConfig.config.model,
+ adapter: modelConfig.config.apiKey.adapter,
+ ...modelConfig.config.modelParams,
+ },
+ structuredOutputSchema: evalScoreSchema,
+ maxRetries: 1,
+ traceSinkParams: {
+ targetProjectId: event.projectId,
+ traceId: executionTraceId,
+ traceName: `Execute evaluator: ${template.name}`,
+ environment: LangfuseInternalTraceEnvironment.LLMJudge,
+ metadata: {
+ ...executionMetadata,
+ score_id: scoreId,
+ },
+ },
+ });
+
const parsedLLMOutput = evalScoreSchema.safeParse(llmOutput);
if (!parsedLLMOutput.success) {
- throw Error(
- `Invalid LLM response format. Model: ${modelConfig.config.model}, Response: ${llmOutput}`,
+ throw new UnrecoverableError(
+ `Invalid LLM response format from model ${modelConfig.config.model}. Response: ${llmOutput}`,
);
}
@@ -722,18 +795,17 @@ export const evaluate = async ({
`Evaluating job ${event.jobExecutionId} Parsed LLM output ${JSON.stringify(parsedLLMOutput)}`,
);
- // persist the score and update the job status
- const scoreId = randomUUID();
-
const baseScore = {
id: scoreId,
- traceId: job.job_input_trace_id,
- observationId: job.job_input_observation_id,
- name: config.score_name,
+ traceId: job.jobInputTraceId,
+ observationId: job.jobInputObservationId,
+ name: config.scoreName,
value: parsedLLMOutput.data.score,
comment: parsedLLMOutput.data.reasoning,
source: ScoreSource.EVAL,
environment: environment ?? "default",
+ executionTraceId: executionTraceId,
+ metadata: executionMetadata,
};
// Write score to S3 and ingest into queue for Clickhouse processing
@@ -780,20 +852,26 @@ export const evaluate = async ({
} catch (e) {
logger.error(`Failed to add score into IngestionQueue: ${e}`, e);
traceException(e);
+
throw new Error(`Failed to write score ${scoreId} into IngestionQueue`);
}
logger.debug(
- `Evaluating job ${event.jobExecutionId} persisted score ${scoreId} for trace ${job.job_input_trace_id}`,
+ `Evaluating job ${event.jobExecutionId} persisted score ${scoreId} for trace ${job.jobInputTraceId}`,
);
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'COMPLETED'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .set("job_output_score_id", scoreId)
- .where("id", "=", event.jobExecutionId)
- .execute();
+ await prisma.jobExecution.update({
+ where: {
+ id: event.jobExecutionId,
+ projectId: event.projectId,
+ },
+ data: {
+ status: JobExecutionStatus.COMPLETED,
+ endTime: new Date(),
+ jobOutputScoreId: scoreId,
+ executionTraceId,
+ },
+ });
logger.debug(
`Eval job ${job.id} for project ${event.projectId} completed with score ${parsedLLMOutput.data.score}`,
@@ -876,7 +954,7 @@ export async function extractVariablesFromTracingData({
`Dataset item ${datasetItemId} for project ${projectId} not found. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
);
// this should only happen for deleted data.
- throw new LangfuseNotFoundError(
+ throw Error(
`Dataset item ${datasetItemId} for project ${projectId} not found. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
);
}
@@ -921,7 +999,7 @@ export async function extractVariablesFromTracingData({
`Trace ${traceId} for project ${projectId} not found. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
);
// this should only happen for deleted data or replication lags across clickhouse nodes.
- throw new LangfuseNotFoundError(
+ throw Error(
`Trace ${traceId} for project ${projectId} not found. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
);
}
@@ -976,11 +1054,11 @@ export async function extractVariablesFromTracingData({
// user facing errors
if (!observation) {
logger.warn(
- `Observation ${mapping.objectName} for trace ${traceId} not found. ${QUEUE_ERROR_MESSAGES.MAPPED_DATA_ERROR}`,
+ `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
);
// this should only happen for deleted data or data replication lags across clickhouse nodes.
- throw new LangfuseNotFoundError(
- `Observation ${mapping.objectName} for trace ${traceId} not found. ${QUEUE_ERROR_MESSAGES.MAPPED_DATA_ERROR}`,
+ throw new UnrecoverableError(
+ `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
);
}
diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.ts
index 3c1d42f6bc..e71cd6da23 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -5,6 +5,7 @@ import {
DatasetRunItemUpsertQueue,
eventTypes,
ExperimentCreateEventSchema,
+ fetchLLMCompletion,
IngestionEventType,
LangfuseInternalTraceEnvironment,
logger,
@@ -17,16 +18,14 @@ import {
import { v4 } from "uuid";
import z from "zod/v4";
import {
- generateUnifiedTraceId,
parseDatasetItemInput,
replaceVariablesInPrompt,
validateAndSetupExperiment,
validateDatasetItem,
type PromptExperimentConfig,
} from "./utils";
-import { backOff } from "exponential-backoff";
-import { callLLM } from "../utils";
import { randomUUID } from "crypto";
+import { createW3CTraceId } from "../utils";
async function getExistingRunItemDatasetItemIds(
projectId: string,
@@ -65,7 +64,7 @@ async function processItem(
config: PromptExperimentConfig,
): Promise<{ success: boolean }> {
// Use unified trace ID to avoid creating duplicate traces between PostgreSQL and ClickHouse
- const newTraceId = generateUnifiedTraceId(config.runId, datasetItem.id);
+ const newTraceId = createW3CTraceId(`${config.runId}-${datasetItem.id}`);
const runItemId = v4();
const timestamp = new Date().toISOString();
@@ -181,20 +180,20 @@ async function processLLMCall(
prompt: config.prompt,
};
- await backOff(
- async () =>
- await callLLM({
- llmApiKey: config.validatedApiKey,
- modelParams: config.model_params,
- messages,
- traceSinkParams,
- throwOnError: false,
- ...config,
- }),
- {
- numOfAttempts: 1, // Turn off retries as Langchain handles this
+ await fetchLLMCompletion({
+ streaming: false,
+ llmConnection: config.validatedApiKey,
+ maxRetries: 1,
+ messages,
+ modelParams: {
+ provider: config.provider,
+ model: config.model,
+ adapter: config.validatedApiKey.adapter,
+ ...config.model_params,
},
- );
+ structuredOutputSchema: config.structuredOutputSchema,
+ traceSinkParams,
+ }).catch(); // catch errors and do not retry
return { success: true };
}
diff --git a/worker/src/features/experiments/utils.ts b/worker/src/features/experiments/utils.ts
index 39ce148285..45d7b6fd89 100644
--- a/worker/src/features/experiments/utils.ts
+++ b/worker/src/features/experiments/utils.ts
@@ -6,13 +6,10 @@ import {
datasetItemMatchesVariable,
extractPlaceholderNames,
extractVariables,
- InvalidRequestError,
- LangfuseNotFoundError,
MessagePlaceholderValues,
Prisma,
PromptContent,
PromptType,
- QUEUE_ERROR_MESSAGES,
stringifyValue,
} from "@langfuse/shared";
import { compileHandlebarString } from "../utils/utilities";
@@ -28,20 +25,7 @@ import {
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import z from "zod/v4";
-import { createHash } from "crypto";
-
-/**
- * Generate deterministic trace ID based on dataset run and item IDs
- * This ensures both PostgreSQL and ClickHouse use the same trace ID
- */
-export function generateUnifiedTraceId(
- runId: string,
- datasetItemId: string,
-): string {
- const input = `${runId}-${datasetItemId}`;
- const hash = createHash("sha256").update(input).digest("hex");
- return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-8${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
-}
+import { UnrecoverableError } from "../../errors/UnrecoverableError";
const isValidPrismaJsonObject = (
input: Prisma.JsonValue,
@@ -206,7 +190,8 @@ export async function validateAndSetupExperiment(
const datasetRun = await fetchDatasetRun(runId, projectId);
if (!datasetRun) {
- throw new LangfuseNotFoundError(`Dataset run ${runId} not found`);
+ // throw regular error here to allow retries for race conditions with dataset run creation
+ throw Error(`Dataset run ${runId} not found`);
}
// Validate experiment metadata
@@ -214,8 +199,8 @@ export async function validateAndSetupExperiment(
datasetRun.metadata,
);
if (!validatedRunMetadata.success) {
- throw new LangfuseNotFoundError(
- "Langfuse in-app experiments can only be run with prompt and model configurations in metadata.",
+ throw new UnrecoverableError(
+ "Langfuse in-app experiments require prompt and model configurations in dataset run metadata",
);
}
@@ -225,13 +210,11 @@ export async function validateAndSetupExperiment(
// Fetch and validate prompt
const prompt = await fetchPrompt(prompt_id, projectId);
if (!prompt) {
- throw new LangfuseNotFoundError(`Prompt ${prompt_id} not found`);
+ throw new UnrecoverableError(`Prompt ${prompt_id} not found`);
}
const validatedPrompt = PromptContentSchema.safeParse(prompt.prompt);
if (!validatedPrompt.success) {
- throw new InvalidRequestError(
- `Prompt ${prompt_id} not found in expected format`,
- );
+ throw new UnrecoverableError(`Prompt ${prompt_id} has invalid format`);
}
// Fetch and validate API key
@@ -239,16 +222,12 @@ export async function validateAndSetupExperiment(
where: { projectId, provider },
});
if (!apiKey) {
- throw new LangfuseNotFoundError(
- `${QUEUE_ERROR_MESSAGES.API_KEY_ERROR} ${provider} not found.`,
- );
+ throw new UnrecoverableError(`API key for provider ${provider} not found`);
}
const validatedApiKey = LLMApiKeySchema.safeParse(apiKey);
if (!validatedApiKey.success) {
- throw new LangfuseNotFoundError(
- `${QUEUE_ERROR_MESSAGES.API_KEY_ERROR} ${provider} not found.`,
- );
+ throw new UnrecoverableError(`API key for provider ${provider} not found`);
}
// Extract variables from prompt
diff --git a/worker/src/features/utils/retry-handler.ts b/worker/src/features/utils/retry-handler.ts
index 4e730831c4..59aa86d748 100644
--- a/worker/src/features/utils/retry-handler.ts
+++ b/worker/src/features/utils/retry-handler.ts
@@ -1,4 +1,3 @@
-import { ApiError } from "@langfuse/shared";
import {
convertQueueNameToMetricName,
logger,
@@ -38,8 +37,7 @@ interface RetryConfig {
* @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 handleRetryableError(
- error: unknown,
+export async function retryLLMRateLimitError(
job: {
data: {
timestamp: Date;
@@ -48,15 +46,7 @@ export async function handleRetryableError(
};
},
config: RetryConfig,
-): Promise<boolean> {
- // Only handle specific retryable errors
- if (
- !(error instanceof ApiError) ||
- (error.httpCode !== 429 && error.httpCode < 500)
- ) {
- return false; // Not a retryable error
- }
-
+): Promise<void> {
try {
const jobId = job.data.payload[config.idField];
@@ -72,67 +62,66 @@ export async function handleRetryableError(
logger.info(
`Job ${jobId} is rate limited for more than 24h. Stop retrying.`,
);
- return false; // Don't retry
- } else {
- // Retry the job with delay
- const delay = config.delayFn((job.data.retryBaggage?.attempt ?? 0) + 1);
- const retryBaggage: RetryBaggage | undefined = job.data.retryBaggage
- ? {
- originalJobTimestamp: new Date(
- job.data.retryBaggage.originalJobTimestamp,
- ),
- attempt: job.data.retryBaggage.attempt + 1,
- }
- : undefined;
-
- // Record retry attempt distribution per queue
+ return; // Don't retry
+ }
- if (retryBaggage) {
- recordDistribution(
- `${convertQueueNameToMetricName(config.queueName)}.retries`,
- retryBaggage.attempt,
- {
- queue: config.queueName,
- },
- );
+ // Retry the job with delay
+ const delay = config.delayFn((job.data.retryBaggage?.attempt ?? 0) + 1);
- // 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",
- },
- );
- }
+ const retryBaggage: RetryBaggage | undefined = job.data.retryBaggage
+ ? {
+ originalJobTimestamp: new Date(
+ job.data.retryBaggage.originalJobTimestamp,
+ ),
+ attempt: job.data.retryBaggage.attempt + 1,
+ }
+ : undefined;
- 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
+ if (retryBaggage) {
+ 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 },
);
-
- return true; // Do not continue regular processing, job was added to the queue
}
+
+ 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.`,
+ );
+
+ await config.queue?.add(
+ config.queueName,
+ {
+ name: config.jobName,
+ id: randomUUID(),
+ timestamp: new Date(),
+ payload: job.data.payload,
+ retryBaggage: retryBaggage,
+ },
+ { delay },
+ );
} catch (innerErr) {
const jobId = job.data.payload[config.idField];
logger.error(
`Failed to handle 429 retry for ${jobId}. Continuing regular processing.`,
innerErr,
);
- return false; // Failed to handle retry - fallback to regular processing
+
+ throw innerErr;
}
}
diff --git a/worker/src/features/utils/utilities.ts b/worker/src/features/utils/utilities.ts
index 31ff256927..da02d0fbba 100644
--- a/worker/src/features/utils/utilities.ts
+++ b/worker/src/features/utils/utilities.ts
@@ -1,92 +1,7 @@
-import {
- ChatMessage,
- fetchLLMCompletion,
- LLMJSONSchema,
- logger,
- TraceSinkParams,
-} from "@langfuse/shared/src/server";
-import { ApiError, LLMApiKeySchema, ZodModelConfig } from "@langfuse/shared";
-import { z } from "zod/v4";
-import { ZodSchema as ZodV3Schema } from "zod/v3";
+import crypto from "node:crypto";
+import { logger } from "@langfuse/shared/src/server";
import Handlebars from "handlebars";
-/**
- * Standard error handling for LLM operations
- * Handles common LLM errors like quota limits and throttling with appropriate status codes
- *
- * @param operation - The async LLM operation to execute
- * @param operationName - Name for error context (e.g., "call LLM")
- * @returns The result of the operation or throws an ApiError
- */
-async function withLLMErrorHandling<T>(
- operation: () => Promise<T>,
- operationName: string = "LLM operation",
-): Promise<T> {
- try {
- return await operation();
- } catch (e) {
- // Handle specific LLM provider errors with appropriate status codes
- if (
- e instanceof Error &&
- (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
- ) {
- throw new ApiError(e.name, 429);
- }
-
- // Handle all other errors with preserved status codes
- throw new ApiError(
- `Failed to ${operationName}: ${e}`,
- (e as any)?.response?.status ?? (e as any)?.status,
- );
- }
-}
-
-export async function callLLM(params: {
- llmApiKey: z.infer<typeof LLMApiKeySchema>;
- messages: ChatMessage[];
- modelParams: z.infer<typeof ZodModelConfig>;
- provider: string;
- model: string;
- traceSinkParams?: TraceSinkParams;
- structuredOutputSchema?: ZodV3Schema | LLMJSONSchema;
- throwOnError?: boolean;
-}): Promise<unknown> {
- const {
- llmApiKey,
- messages,
- modelParams,
- provider,
- model,
- traceSinkParams,
- structuredOutputSchema,
- throwOnError,
- } = params;
-
- return withLLMErrorHandling(async () => {
- const { completion, processTracedEvents } = await fetchLLMCompletion({
- streaming: false,
- llmConnection: llmApiKey,
- messages,
- modelParams: {
- provider,
- model,
- adapter: llmApiKey.adapter,
- ...modelParams,
- },
- ...(structuredOutputSchema && { structuredOutputSchema }),
- traceSinkParams,
- maxRetries: 1,
- throwOnError,
- });
-
- if (traceSinkParams) {
- await processTracedEvents();
- }
-
- return completion;
- }, "call LLM");
-}
-
export function compileHandlebarString(
handlebarString: string,
context: Record<string, any>,
@@ -99,3 +14,32 @@ export function compileHandlebarString(
return handlebarString; // Fallback to the original string if Handlebars fails
}
}
+
+/**
+ * Creates a W3C Trace Context compliant trace ID (16 bytes as 32 hex characters).
+ *
+ * @param {string} [seed] - Optional seed string for deterministic trace ID generation.
+ * If provided, generates a trace ID by hashing the seed with SHA-256.
+ * If omitted, generates a cryptographically random trace ID.
+ * @returns {string} A 32-character hexadecimal string representing a 16-byte trace ID.
+ *
+ * @example
+ * // Generate a random trace ID
+ * const traceId = createW3CTraceId();
+ * // => "a3f5b2c8d9e1f4a7b6c3d2e5f8a9b4c7"
+ *
+ * @example
+ * // Generate a deterministic trace ID from a seed
+ * const traceId = createW3CTraceId("my-seed-value");
+ * // => "5d41402abc4b2a76b9719d911017c592"
+ */
+export function createW3CTraceId(seed?: string): string {
+ if (seed) {
+ const data = new TextEncoder().encode(seed);
+ const hash = crypto.createHash("SHA-256").update(data).digest("hex");
+
+ return hash.slice(0, 32); // take first 32 chars (16 bytes worth)
+ } else {
+ return crypto.randomBytes(16).toString("hex"); // already 32 chars
+ }
+}
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 69e1b40b1a..08ef298ec8 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -1,12 +1,6 @@
import { Job } from "bullmq";
-import {
- ApiError,
- BaseError,
- LangfuseNotFoundError,
- QUEUE_ERROR_MESSAGES,
-} from "@langfuse/shared";
-import { kyselyPrisma } from "@langfuse/shared/src/db";
-import { sql } from "kysely";
+import { JobExecutionStatus } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
import {
QueueName,
TQueueJobTypes,
@@ -15,42 +9,19 @@ import {
EvalExecutionQueue,
QueueJobs,
getCurrentSpan,
+ isLLMCompletionError,
} from "@langfuse/shared/src/server";
import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
import { delayInMs } from "./utils/delays";
-import { handleRetryableError } from "../features/utils";
-
-function isExpectedError(error: unknown): boolean {
- return (
- error instanceof LangfuseNotFoundError ||
- (error instanceof BaseError &&
- error.message.includes(
- QUEUE_ERROR_MESSAGES.OUTPUT_TOKENS_TOO_LONG_ERROR,
- )) || // output tokens too long
- (error instanceof BaseError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.API_KEY_ERROR)) || // api key not provided
- (error instanceof BaseError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.NO_DEFAULT_MODEL_ERROR)) || // api key not provided
- (error instanceof ApiError &&
- error.httpCode >= 400 &&
- error.httpCode < 500) || // do not error and retry on 4xx errors. They are visible to the user in the UI but do not alert us.
- (error instanceof ApiError && error.message.includes("TypeError")) || // Zod parsing the response failed. User should update prompt to consistently return expected output structure.
- (error instanceof ApiError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.TOO_LOW_MAX_TOKENS_ERROR)) || // When evaluator model is configured with too low max_tokens, the structured output response is invalid JSON
- (error instanceof ApiError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.INVALID_JSON_ERROR)) || // When evaluator model is not consistently returning valid JSON on structured output calls
- (error instanceof BaseError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.MAPPED_DATA_ERROR)) || // Trace not found.
- (error instanceof ApiError &&
- error.message.includes(QUEUE_ERROR_MESSAGES.TIMEOUT_ERROR)) // LLM provider timeout - graceful failure
- );
-}
+import { createW3CTraceId, retryLLMRateLimitError } from "../features/utils";
+import { isUnrecoverableError } from "../errors/UnrecoverableError";
export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
) => {
try {
await createEvalJobs({
+ sourceEventType: "trace-upsert",
event: job.data.payload,
jobTimestamp: job.data.timestamp,
enforcedJobTimeScope: "NEW", // we must not execute evals which are intended for existing data only.
@@ -71,6 +42,7 @@ export const evalJobDatasetCreatorQueueProcessor = async (
) => {
try {
await createEvalJobs({
+ sourceEventType: "dataset-run-item-upsert",
event: job.data.payload,
jobTimestamp: job.data.timestamp,
enforcedJobTimeScope: "NEW", // we must not execute evals which are intended for existing data only.
@@ -91,6 +63,7 @@ export const evalJobCreatorQueueProcessor = async (
) => {
try {
await createEvalJobs({
+ sourceEventType: "ui-create-eval",
event: job.data.payload,
jobTimestamp: job.data.timestamp,
});
@@ -131,44 +104,85 @@ export const evalJobExecutorQueueProcessor = async (
await evaluate({ event: job.data.payload });
return true;
} catch (e) {
- // If the job fails with a 429, we want to retry it unless it's older than 24h.
- const wasRetried = await handleRetryableError(e, job, {
- table: "job_executions",
- idField: "jobExecutionId",
- queue: EvalExecutionQueue.getInstance(),
- queueName: QueueName.EvaluationExecution,
- jobName: QueueJobs.EvaluationExecution,
- delayFn: delayInMs,
- });
-
- if (wasRetried) {
- return;
- }
+ // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ // β”‚ Job Fails with Error β”‚
+ // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ // β”‚
+ // β–Ό
+ // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ // β”‚ Is it LLMCompletionError with β”‚
+ // β”‚ isRetryable=true (429/5xx)? β”‚
+ // β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”˜
+ // β”‚ Yes β”‚ No
+ // β–Ό β–Ό
+ // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ // β”‚ Is job < 24h old?β”‚ β”‚ Is it retryable? β”‚
+ // β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β”‚ (shouldRetryJob) β”‚
+ // Yes β”‚ β”‚ No β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”˜
+ // β–Ό β–Ό Yesβ”‚ β”‚No
+ // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β–Ό β–Ό
+ // β”‚Set: β”‚ β”‚Set: β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ // β”‚DELAYED β”‚ β”‚ERROR β”‚ β”‚BullMQ β”‚ β”‚Set: β”‚
+ // β”‚Retry in β”‚ β”‚Stop β”‚ β”‚retry β”‚ β”‚ERROR β”‚
+ // β”‚1-25 min β”‚ β”‚ β”‚ β”‚w/ exp. β”‚ β”‚Done β”‚
+ // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚backoff β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
- // we are left with 4xx and application errors here.
+ const executionTraceId = createW3CTraceId(job.data.payload.jobExecutionId);
- const displayError =
- e instanceof BaseError ? e.message : "An internal error occurred";
+ if (isLLMCompletionError(e) && e.isRetryable) {
+ await retryLLMRateLimitError(job, {
+ table: "job_executions",
+ idField: "jobExecutionId",
+ queue: EvalExecutionQueue.getInstance(),
+ queueName: QueueName.EvaluationExecution,
+ jobName: QueueJobs.EvaluationExecution,
+ delayFn: delayInMs,
+ });
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'ERROR'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .set("error", displayError)
- .where("id", "=", job.data.payload.jobExecutionId)
- .where("project_id", "=", job.data.payload.projectId)
- .execute();
+ // 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,
+ },
+ });
- // do not log expected errors (api failures + missing api keys not provided by the user)
- if (isExpectedError(e)) {
+ // 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
+ await prisma.jobExecution.update({
+ where: {
+ id: job.data.payload.jobExecutionId,
+ projectId: job.data.payload.projectId,
+ },
+ data: {
+ status: JobExecutionStatus.ERROR,
+ endTime: new Date(),
+ // Show user-facing error messages (LLM and config errors)
+ error:
+ isLLMCompletionError(e) || isUnrecoverableError(e)
+ ? e.message
+ : "An internal error occurred",
+ executionTraceId,
+ },
+ });
+
+ if (isLLMCompletionError(e) || isUnrecoverableError(e)) return;
+
traceException(e);
logger.error(
`Failed Evaluation_Execution job for id ${job.data.payload.jobExecutionId}`,
e,
);
+
+ // Retry job by rethrowing error
throw e;
}
};
diff --git a/worker/src/queues/experimentQueue.ts b/worker/src/queues/experimentQueue.ts
index e12d0ccade..c70d712ece 100644
--- a/worker/src/queues/experimentQueue.ts
+++ b/worker/src/queues/experimentQueue.ts
@@ -4,14 +4,14 @@ import {
QueueJobs,
QueueName,
TQueueJobTypes,
+ isLLMCompletionError,
logger,
traceException,
} from "@langfuse/shared/src/server";
-import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";
-import { kyselyPrisma } from "@langfuse/shared/src/db";
-import { handleRetryableError } from "../features/utils";
+import { retryLLMRateLimitError } from "../features/utils";
import { delayInMs } from "./utils/delays";
import { createExperimentJobClickhouse } from "../features/experiments/experimentServiceClickhouse";
+import { isUnrecoverableError } from "../errors/UnrecoverableError";
export const experimentCreateQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.ExperimentCreate]>,
@@ -22,59 +22,28 @@ export const experimentCreateQueueProcessor = async (
});
return true;
} catch (e) {
- // If creating any of the dataset run items associated with this experiment create job fails with a 429, we want to retry the experiment creation job unless it's older than 24h.
- const wasRetried = await handleRetryableError(e, job, {
- table: "dataset_runs",
- idField: "runId",
- queue: ExperimentCreateQueue.getInstance(),
- queueName: QueueName.ExperimentCreate,
- jobName: QueueJobs.ExperimentCreateJob,
- delayFn: delayInMs,
- });
+ if (isLLMCompletionError(e) && e.isRetryable) {
+ await retryLLMRateLimitError(job, {
+ table: "dataset_runs",
+ idField: "runId",
+ queue: ExperimentCreateQueue.getInstance(),
+ queueName: QueueName.ExperimentCreate,
+ jobName: QueueJobs.ExperimentCreateJob,
+ delayFn: delayInMs,
+ });
- if (wasRetried) {
return;
}
- if (
- e instanceof InvalidRequestError ||
- e instanceof LangfuseNotFoundError
- ) {
- logger.info(
- `Failed to process experiment create job for project: ${job.data.payload.projectId}`,
- e,
- );
-
- try {
- const currentRun = await kyselyPrisma.$kysely
- .selectFrom("dataset_runs")
- .selectAll()
- .where("id", "=", job.data.payload.runId)
- .where("project_id", "=", job.data.payload.projectId)
- .executeTakeFirst();
-
- if (!currentRun) {
- logger.info(
- `Dataset run configuration is invalid for run ${job.data.payload.runId}`,
- );
- // attempt retrying the job as the run may be created in the meantime
- throw new LangfuseNotFoundError(
- `Dataset run ${job.data.payload.runId} not found`,
- );
- }
+ if (isLLMCompletionError(e) || isUnrecoverableError(e)) return;
- // error cases of invalid configuration (prompt, api key, etc) are handled on the DRI level
- // return true to indicate job was processed successfully and avoid retrying
- return true;
- } catch (e) {
- logger.error("Failed to process experiment create job", e);
- traceException(e);
- throw e;
- }
- }
-
- logger.error("Failed to process experiment create job", e);
+ logger.error(
+ `Failed to process experiment create job for project: ${job.data.payload.projectId}`,
+ e,
+ );
traceException(e);
+
+ // Retry job by rethrowing error
throw e;
}
};
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index a0ba51d1a3..9ce150767c 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -526,6 +526,7 @@ export class IngestionService {
? convertJsonSchemaToRecord(scoreEvent.body.metadata)
: {},
string_value: validatedScore.stringValue,
+ execution_trace_id: validatedScore.executionTraceId,
queue_id: validatedScore.queueId ?? null,
created_at: Date.now(),
updated_at: Date.now(),
@@ -699,6 +700,7 @@ export class IngestionService {
projectId,
traceId: entityId,
exactTimestamp: new Date(finalTraceRecord.timestamp),
+ traceEnvironment: finalTraceRecord.environment,
},
id: randomUUID(),
timestamp: new Date(),