Skip to content

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

feat(evals): add single observation evals (#11547)

Hassieb Pakzada604f8e61bd2
diff --git a/.gitignore b/.gitignore
index 7c003fd205..a888924343 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,7 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
+.eslintcache
# local env files
# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 7d2a9203ae..be18047cf3 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -584,18 +584,18 @@ model CronJobs {
}
model Dataset {
- id String @default(cuid())
- projectId String @map("project_id")
+ id String @default(cuid())
+ projectId String @map("project_id")
name String
description String?
metadata Json?
- remoteExperimentUrl String? @map("remote_experiment_url")
- remoteExperimentPayload Json? @map("remote_experiment_payload")
- inputSchema Json? @map("input_schema") @db.Json
- expectedOutputSchema Json? @map("expected_output_schema") @db.Json
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ remoteExperimentUrl String? @map("remote_experiment_url")
+ remoteExperimentPayload Json? @map("remote_experiment_payload")
+ inputSchema Json? @map("input_schema") @db.Json
+ expectedOutputSchema Json? @map("expected_output_schema") @db.Json
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
datasetItems DatasetItem[]
datasetRuns DatasetRuns[]
diff --git a/packages/shared/src/features/evals/observationForEval.ts b/packages/shared/src/features/evals/observationForEval.ts
new file mode 100644
index 0000000000..69ba07e2ef
--- /dev/null
+++ b/packages/shared/src/features/evals/observationForEval.ts
@@ -0,0 +1,164 @@
+import { z } from "zod/v4";
+import { DEFAULT_TRACE_ENVIRONMENT } from "../../server/ingestion/types";
+import { type EventRecordBaseType } from "../../server/repositories/definitions";
+import { ObservationLevel } from "../../domain";
+
+const flexibleUsageCostSchema = z.record(z.string(), z.number().nullable());
+
+export const observationForEvalSchema = z.object({
+ // Identifiers
+ span_id: z.string(),
+ trace_id: z.string(),
+ project_id: z.string(),
+ parent_span_id: z.string().nullish(),
+
+ // Core properties
+ type: z.string(),
+ name: z.string(),
+ environment: z.string().default(DEFAULT_TRACE_ENVIRONMENT),
+ version: z.string().nullish(),
+ level: z.string().default(ObservationLevel.DEFAULT),
+ status_message: z.string().nullish(),
+
+ // Trace-level properties
+ trace_name: z.string().nullish(),
+ user_id: z.string().nullish(),
+ session_id: z.string().nullish(),
+ tags: z.array(z.string()).default([]),
+ release: z.string().nullish(),
+
+ // Model
+ provided_model_name: z.string().nullish(),
+ model_parameters: z.unknown().nullish(),
+
+ // Prompt
+ prompt_id: z.string().nullish(),
+ prompt_name: z.string().nullish(),
+ // Accepts string, number, or any other type from ingestion
+ prompt_version: z.union([z.string().nullish(), z.number().nullish()]),
+
+ // Usage & Cost - accepts number values directly from ingestion
+ provided_usage_details: flexibleUsageCostSchema,
+ provided_cost_details: flexibleUsageCostSchema,
+ usage_details: flexibleUsageCostSchema,
+ cost_details: flexibleUsageCostSchema,
+
+ // Tool calls
+ tool_definitions: z.record(z.string(), z.unknown()).default({}),
+ tool_calls: z.array(z.unknown()).default([]),
+ tool_call_names: z.array(z.string()).default([]),
+
+ // Experiment
+ experiment_id: z.string().nullish(),
+ experiment_name: z.string().nullish(),
+ experiment_description: z.string().nullish(),
+ experiment_dataset_id: z.string().nullish(),
+ experiment_item_id: z.string().nullish(),
+ experiment_item_expected_output: z.string().nullish(),
+ experiment_item_root_span_id: z.string().nullish(),
+
+ // Data - accepts any type (string, array, object) from different OTEL SDKs
+ input: z.unknown().nullish(),
+ output: z.unknown().nullish(),
+ metadata: z.record(z.string(), z.unknown()).nullish(),
+});
+
+export type ObservationForEval = z.infer<typeof observationForEvalSchema>;
+
+export function convertEventRecordToObservationForEval(
+ record: EventRecordBaseType,
+): ObservationForEval {
+ return observationForEvalSchema.parse(record);
+}
+
+export interface ObservationEvalFilterColumn {
+ /** Column identifier (must match an ObservationForEval field name) */
+ id: keyof Pick<
+ ObservationForEval,
+ | "type"
+ | "name"
+ | "environment"
+ | "level"
+ | "version"
+ | "release"
+ | "trace_name"
+ | "user_id"
+ | "session_id"
+ | "tags"
+ | "experiment_dataset_id"
+ | "metadata"
+ >;
+ /** Display name for UI */
+ name: string;
+ /** Filter type for UI rendering */
+ type: "string" | "stringOptions" | "stringObject" | "arrayOptions" | "number";
+}
+
+/**
+ * Columns available for filtering in observation-based evals.
+ * Maps to InMemoryFilterService column mapper.
+ *
+ * These columns can be used in filter conditions to determine
+ * which observations should be evaluated.
+ */
+export const observationEvalFilterColumns: ObservationEvalFilterColumn[] = [
+ // Observation properties
+ { id: "type", name: "Type", type: "stringOptions" },
+ { id: "name", name: "Name", type: "string" },
+ { id: "environment", name: "Environment", type: "stringOptions" },
+ { id: "level", name: "Level", type: "stringOptions" },
+ { id: "version", name: "Version", type: "string" },
+ { id: "release", name: "Release", type: "string" },
+ { id: "trace_name", name: "Trace Name", type: "string" },
+ { id: "user_id", name: "User ID", type: "string" },
+ { id: "session_id", name: "Session ID", type: "string" },
+ { id: "tags", name: "Tags", type: "arrayOptions" },
+ { id: "experiment_dataset_id", name: "Dataset", type: "stringOptions" },
+ { id: "metadata", name: "Metadata", type: "stringObject" },
+];
+
+export interface ObservationEvalVariableColumn {
+ /** Column identifier (must match an ObservationForEval field name) */
+ id: keyof Pick<
+ ObservationForEval,
+ "input" | "output" | "metadata" | "experiment_item_expected_output"
+ >;
+ /** Display name for UI */
+ name: string;
+ /** Description for UI tooltips */
+ description: string;
+ /** Optional type hint for special handling (e.g., stringObject for metadata) */
+ type?: "stringObject";
+}
+
+/**
+ * Columns available for variable extraction in observation-based evals.
+ * These are the fields that can be mapped to template variables.
+ *
+ * When configuring an eval, users can map these columns to template
+ * variables like {{input}}, {{output}}, {{expected_output}}, etc.
+ */
+export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [
+ {
+ id: "input",
+ name: "Input",
+ description: "Observation input data",
+ },
+ {
+ id: "output",
+ name: "Output",
+ description: "Observation output data",
+ },
+ {
+ id: "metadata",
+ name: "Metadata",
+ description: "Observation metadata",
+ type: "stringObject",
+ },
+
+ {
+ id: "experiment_item_expected_output",
+ name: "Experiment Item Expected Output",
+ description: "Expected output from experiment item",
+ },
+];
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 5e6df4786f..b5390a1ea8 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -1,5 +1,17 @@
import z from "zod/v4";
+export const EvalTargetObject = {
+ TRACE: "trace",
+ DATASET: "dataset",
+ EVENT: "event",
+ EXPERIMENT: "experiment",
+} as const;
+
+export type EvalTargetObject =
+ (typeof EvalTargetObject)[keyof typeof EvalTargetObject];
+
+export const EvalTargetObjectSchema = z.enum(Object.values(EvalTargetObject));
+
export const langfuseObjects = [
"trace",
"span",
@@ -157,3 +169,22 @@ export const JobTimeScopeZod = z.enum(["NEW", "EXISTING"]);
export type JobTimeScope = z.infer<typeof JobTimeScopeZod>;
export const TimeScopeSchema = z.array(JobTimeScopeZod).default(["NEW"]);
+
+// Simplified variable mapping for observation-based evals.
+// Unlike trace-based evals, we don't need objectName since we're directly
+// targeting a specific observation - no need to specify which observation to extract from.
+//
+// Note: selectedColumnId must be a valid column ID from observationEvalVariableColumns.
+// See packages/shared/src/features/evals/observationForEval.ts for the source of truth.
+export const observationVariableMapping = z.object({
+ templateVariable: z.string(), // variable name in the template
+ selectedColumnId: z.string(), // column to extract (must match observationEvalVariableColumns)
+ jsonSelector: z.string().nullish(), // optional JSON path selector
+});
+
+export const observationVariableMappingList = z.array(
+ observationVariableMapping,
+);
+export type ObservationVariableMapping = z.infer<
+ typeof observationVariableMapping
+>;
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 659d2f4100..a54c31793f 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -32,6 +32,7 @@ export * from "./server/llm/types";
// evals
export * from "./features/evals/types";
export * from "./features/evals/utilities";
+export * from "./features/evals/observationForEval";
// table actions
export * from "./features/batchExport/types";
export * from "./features/batchAction/types";
diff --git a/packages/shared/src/server/evalJobConfigCache.ts b/packages/shared/src/server/evalJobConfigCache.ts
index af38cc7b20..1e9317c4cc 100644
--- a/packages/shared/src/server/evalJobConfigCache.ts
+++ b/packages/shared/src/server/evalJobConfigCache.ts
@@ -10,73 +10,82 @@ import { redis } from "./";
* database queries and queue processing.
*/
-const NO_JOB_CONFIG_PREFIX = "langfuse:eval:no-job-configs";
+/** Cache types for different eval job configuration targets */
+type EvalConfigCacheType = "traceBased" | "eventBased";
+
+const CACHE_PREFIXES: Record<EvalConfigCacheType, string> = {
+ traceBased: "langfuse:eval:no-trace-and-dataset-job-configs", // for target_object 'trace' | 'observation'
+ eventBased: "langfuse:eval:no-event-and-experiment-job-configs", // for target_object 'event' | 'experiment'
+};
+
+const CACHE_TTL_SECONDS = 600; // 10 minutes
/**
- * Check if a project has no job configurations cached in Redis.
- * Returns true if the cache indicates no eval job configs exist.
- *
- * @param projectId - The project ID to check cache for
- * @returns Promise<boolean> - true if no eval job configs present
+ * Check if a project has no eval configurations cached in Redis.
+ * Returns true if the cache indicates no configs exist.
*/
-export const hasNoJobConfigsCache = async (
+export const hasNoEvalConfigsCache = async (
projectId: string,
+ cacheType: EvalConfigCacheType,
): Promise<boolean> => {
if (!redis) {
return false;
}
try {
- const cacheKey = `${NO_JOB_CONFIG_PREFIX}:${projectId}`;
+ const cacheKey = `${CACHE_PREFIXES[cacheType]}:${projectId}`;
const cached = await redis.get(cacheKey);
+
return Boolean(cached);
} catch (error) {
- logger.error("Failed to check no eval job configs cache", error);
+ logger.error(`Failed to check no ${cacheType} eval configs cache`, error);
+
return false;
}
};
/**
- * Cache that a project has no active job configurations.
- * This is set when a database query returns no active EVAL job configurations.
+ * Cache that a project has no active eval configurations.
* The cache expires after 10 minutes to ensure eventual consistency.
- *
- * @param projectId - The project ID to cache
*/
-export const setNoJobConfigsCache = async (
+export const setNoEvalConfigsCache = async (
projectId: string,
+ cacheType: EvalConfigCacheType,
): Promise<void> => {
if (!redis) {
return;
}
try {
- const cacheKey = `${NO_JOB_CONFIG_PREFIX}:${projectId}`;
- await redis.setex(cacheKey, 600, "1"); // Cache for 10 minutes
- logger.debug(`Cached no eval job configs for project ${projectId}`);
+ const cacheKey = `${CACHE_PREFIXES[cacheType]}:${projectId}`;
+ await redis.setex(cacheKey, CACHE_TTL_SECONDS, "1");
+ logger.debug(
+ `Cached no ${cacheType} eval configs for project ${projectId}`,
+ );
} catch (error) {
- logger.error("Failed to cache no eval job configs status", error);
+ logger.error(`Failed to cache no ${cacheType} eval configs status`, error);
}
};
/**
- * Clear the "no eval job configs" cache for a project.
+ * Clear the "no eval configs" cache for a project.
* Should be called when job configurations are created or activated.
- *
- * @param projectId - The project ID to clear cache for
*/
-export const clearNoJobConfigsCache = async (
+export const clearNoEvalConfigsCache = async (
projectId: string,
+ cacheType: EvalConfigCacheType,
): Promise<void> => {
if (!redis) {
return;
}
try {
- const cacheKey = `${NO_JOB_CONFIG_PREFIX}:${projectId}`;
+ const cacheKey = `${CACHE_PREFIXES[cacheType]}:${projectId}`;
await redis.del(cacheKey);
- logger.debug(`Cleared no eval job configs cache for project ${projectId}`);
+ logger.debug(
+ `Cleared no ${cacheType} eval configs cache for project ${projectId}`,
+ );
} catch (error) {
- logger.error("Failed to clear no eval job configs cache", error);
+ logger.error(`Failed to clear no ${cacheType} eval configs cache`, error);
}
};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index ce3ddbff06..53bc1b8ac5 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -99,6 +99,7 @@ export * from "./repositories/traces";
export * from "./repositories/dataset-items";
export * from "./utils/rendering";
export * from "./redis/evalExecutionQueue";
+export * from "./redis/llmAsJudgeExecutionQueue";
export * from "./services/sessions-ui-table-service";
export * from "./services/DashboardService";
export * from "./services/TableViewService";
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index 56e6b7624a..ea24e017b9 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -228,18 +228,21 @@ const ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE =
INTERNAL_ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE +
" and it must not start with 'langfuse'";
+/** Default environment name used when no environment is specified. */
+export const DEFAULT_TRACE_ENVIRONMENT = "default" as const;
+
const PublicEnvironmentName = z
.string()
.toLowerCase()
.max(40, "Maximum length is 40 characters")
.regex(/^(?!langfuse)[a-z0-9-_]+$/, ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE)
- .default("default");
+ .default(DEFAULT_TRACE_ENVIRONMENT);
const InternalEnvironmentName = z
.string()
.max(40, "Maximum length is 40 characters")
.regex(/^[a-z0-9-_]+$/, INTERNAL_ENVIRONMENT_NAME_REGEX_ERROR_MESSAGE)
- .default("default");
+ .default(DEFAULT_TRACE_ENVIRONMENT);
/** @deprecated Use PublicEnvironmentName or InternalEnvironmentName instead */
export const EnvironmentName = PublicEnvironmentName;
diff --git a/packages/shared/src/server/otel/ObservationTypeMapper.ts b/packages/shared/src/server/otel/ObservationTypeMapper.ts
index ac4d6cf17b..d7572816f1 100644
--- a/packages/shared/src/server/otel/ObservationTypeMapper.ts
+++ b/packages/shared/src/server/otel/ObservationTypeMapper.ts
@@ -413,7 +413,7 @@ export class ObservationTypeMapperRegistry {
attributes: Record<string, unknown>,
resourceAttributes?: Record<string, unknown>,
scopeData?: Record<string, unknown>,
- ): LangfuseObservationType | null {
+ ): LangfuseObservationType {
const sortedMappers = this.getSortedMappers();
for (const mapper of sortedMappers) {
if (mapper.canMap(attributes, resourceAttributes, scopeData)) {
@@ -428,7 +428,7 @@ export class ObservationTypeMapperRegistry {
}
}
- return null;
+ return "SPAN";
}
getMappersForDebugging(): ReadonlyArray<ObservationTypeMapper> {
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 598c09f259..8e24178642 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -18,6 +18,9 @@ import {
instrumentSync,
recordDistribution,
UsageDetails,
+ extractToolsFromObservation,
+ convertDefinitionsToMap,
+ convertCallsToArrays,
} from "../";
import { LangfuseOtelSpanAttributes } from "./attributes";
@@ -287,6 +290,24 @@ export class OtelIngestionProcessor {
);
}
+ let toolDefinitions = undefined;
+ let toolCalls = undefined;
+ let toolCallNames = undefined;
+
+ const { toolDefinitions: rawToolDefinitions, toolArguments } =
+ extractToolsFromObservation(input, output);
+
+ if (rawToolDefinitions.length > 0) {
+ toolDefinitions = convertDefinitionsToMap(rawToolDefinitions);
+ }
+
+ if (toolArguments.length > 0) {
+ const { tool_calls, tool_call_names } =
+ convertCallsToArrays(toolArguments);
+ toolCalls = tool_calls;
+ toolCallNames = tool_call_names;
+ }
+
events.push({
projectId: this.projectId,
traceId,
@@ -365,6 +386,12 @@ export class OtelIngestionProcessor {
null,
userId: this.extractUserId(spanAttributes),
sessionId: this.extractSessionId(spanAttributes),
+ release:
+ (spanAttributes?.[
+ LangfuseOtelSpanAttributes.RELEASE
+ ] as string) ??
+ resourceAttributes?.[LangfuseOtelSpanAttributes.RELEASE] ??
+ null,
input,
output,
@@ -388,6 +415,11 @@ export class OtelIngestionProcessor {
// Experiment fields
...experimentFields,
+
+ // Tool calling
+ toolDefinitions,
+ toolCalls,
+ toolCallNames,
});
}
}
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 125c6bd7ae..8397c9e278 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -8,6 +8,7 @@ import { BatchTableNames } from "../interfaces/tableNames";
import { EventActionSchema } from "../domain";
import { PromptDomainSchema } from "../domain/prompts";
import { ObservationAddToDatasetConfigSchema } from "../features/batchAction/addToDatasetTypes";
+import { EvalTargetObjectSchema } from "../features/evals/types";
export const IngestionEvent = z.object({
data: z.object({
@@ -90,6 +91,13 @@ export const EvalExecutionEvent = z.object({
jobExecutionId: z.string(),
delay: z.number().nullish(),
});
+
+// LLM-as-a-Judge execution for observation-based evals
+export const LLMAsJudgeExecutionEventSchema = z.object({
+ projectId: z.string(),
+ jobExecutionId: z.string(),
+ observationS3Path: z.string(),
+});
export const PostHogIntegrationProcessingEventSchema = z.object({
projectId: z.string(),
});
@@ -159,7 +167,7 @@ export const BatchActionProcessingEventSchema = z.discriminatedUnion(
}),
z.object({
actionId: z.literal("eval-create"),
- targetObject: z.enum(["trace", "dataset"]),
+ targetObject: EvalTargetObjectSchema,
configId: z.string(),
projectId: z.string(),
cutoffCreatedAt: z.date(),
@@ -285,6 +293,9 @@ export type DatasetRunItemUpsertEventType = z.infer<
typeof DatasetRunItemUpsertEventSchema
>;
export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;
+export type LLMAsJudgeExecutionEventType = z.infer<
+ typeof LLMAsJudgeExecutionEventSchema
+>;
export type IngestionEventQueueType = z.infer<typeof IngestionEvent>;
export type OtelIngestionEventQueueType = z.infer<typeof OtelIngestionEvent>;
export type ExperimentCreateEventType = z.infer<
@@ -322,6 +333,7 @@ export enum QueueName {
TraceDelete = "trace-delete",
ProjectDelete = "project-delete",
EvaluationExecution = "evaluation-execution-queue", // Worker executes Evals
+ LLMAsJudgeExecution = "llm-as-a-judge-execution-queue", // Observation-based eval execution
DatasetRunItemUpsert = "dataset-run-item-upsert-queue",
BatchExport = "batch-export-queue",
OtelIngestionQueue = "otel-ingestion-queue",
@@ -361,6 +373,7 @@ export enum QueueJobs {
ProjectDelete = "project-delete",
DatasetRunItemUpsert = "dataset-run-item-upsert",
EvaluationExecution = "evaluation-execution-job",
+ LLMAsJudgeExecution = "llm-as-a-judge-execution-job",
BatchExportJob = "batch-export-job",
CloudUsageMeteringJob = "cloud-usage-metering-job",
CloudSpendAlertJob = "cloud-spend-alert-job",
@@ -438,6 +451,13 @@ export type TQueueJobTypes = {
name: QueueJobs.EvaluationExecution;
retryBaggage?: RetryBaggage;
};
+ [QueueName.LLMAsJudgeExecution]: {
+ timestamp: Date;
+ id: string;
+ payload: LLMAsJudgeExecutionEventType;
+ name: QueueJobs.LLMAsJudgeExecution;
+ retryBaggage?: RetryBaggage;
+ };
[QueueName.BatchExport]: {
timestamp: Date;
id: string;
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 8491381859..4cd89ef930 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -6,6 +6,7 @@ import { CloudSpendAlertQueue } from "./cloudSpendAlertQueue";
import { CloudFreeTierUsageThresholdQueue } from "./cloudFreeTierUsageThresholdQueue";
import { DatasetRunItemUpsertQueue } from "./datasetRunItemUpsert";
import { EvalExecutionQueue } from "./evalExecutionQueue";
+import { LLMAsJudgeExecutionQueue } from "./llmAsJudgeExecutionQueue";
import { ExperimentCreateQueue } from "./experimentCreateQueue";
import { SecondaryIngestionQueue } from "./ingestionQueue";
import { TraceDeleteQueue } from "./traceDelete";
@@ -58,6 +59,8 @@ export function getQueue(
return DatasetDeleteQueue.getInstance();
case QueueName.EvaluationExecution:
return EvalExecutionQueue.getInstance();
+ case QueueName.LLMAsJudgeExecution:
+ return LLMAsJudgeExecutionQueue.getInstance();
case QueueName.ExperimentCreate:
return ExperimentCreateQueue.getInstance();
case QueueName.TraceDelete:
diff --git a/packages/shared/src/server/redis/llmAsJudgeExecutionQueue.ts b/packages/shared/src/server/redis/llmAsJudgeExecutionQueue.ts
new file mode 100644
index 0000000000..a97127e534
--- /dev/null
+++ b/packages/shared/src/server/redis/llmAsJudgeExecutionQueue.ts
@@ -0,0 +1,51 @@
+import { Queue } from "bullmq";
+import { logger } from "../logger";
+import { TQueueJobTypes, QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+
+export class LLMAsJudgeExecutionQueue {
+ private static instance: Queue<
+ TQueueJobTypes[QueueName.LLMAsJudgeExecution]
+ > | null = null;
+
+ public static getInstance(): Queue<
+ TQueueJobTypes[QueueName.LLMAsJudgeExecution]
+ > | null {
+ if (LLMAsJudgeExecutionQueue.instance)
+ return LLMAsJudgeExecutionQueue.instance;
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ LLMAsJudgeExecutionQueue.instance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.LLMAsJudgeExecution]>(
+ QueueName.LLMAsJudgeExecution,
+ {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.LLMAsJudgeExecution),
+ defaultJobOptions: {
+ removeOnComplete: 10_000, // important for job deduplication
+ removeOnFail: 10_000,
+ attempts: 10,
+ backoff: {
+ type: "exponential",
+ delay: 1000,
+ },
+ },
+ },
+ )
+ : null;
+
+ LLMAsJudgeExecutionQueue.instance?.on("error", (err) => {
+ logger.error("LLMAsJudgeExecutionQueue error", err);
+ });
+
+ return LLMAsJudgeExecutionQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index e936a63c3b..4978675f77 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -1,4 +1,5 @@
import z from "zod/v4";
+import { DEFAULT_TRACE_ENVIRONMENT } from "../ingestion/types";
export const clickhouseStringDateSchema = z
.string()
@@ -638,7 +639,7 @@ export const eventRecordBaseSchema = z.object({
// Core properties
name: z.string(),
type: z.string(),
- environment: z.string().default("default"),
+ environment: z.string().default(DEFAULT_TRACE_ENVIRONMENT),
version: z.string().nullish(),
release: z.string().nullish(),
@@ -716,6 +717,9 @@ export const eventRecordBaseSchema = z.object({
is_deleted: z.number(),
});
+// Base type for event records - used by converters that work with both Insert and Read types
+export type EventRecordBaseType = z.infer<typeof eventRecordBaseSchema>;
+
export const eventRecordReadSchema = eventRecordBaseSchema.extend({
metadata_prefixes: z.array(z.string()).default([]),
metadata_hashes: z.array(z.number().int()).default([]),
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.ts
index ac34a6a91d..4a03d51016 100644
--- a/packages/shared/src/server/services/StorageService.ts
+++ b/packages/shared/src/server/services/StorageService.ts
@@ -61,7 +61,10 @@ export interface StorageService {
params: UploadWithSignedUrl,
): Promise<{ signedUrl: string }>;
- uploadJson(path: string, body: Record<string, unknown>[]): Promise<void>;
+ uploadJson(
+ path: string,
+ body: Record<string, unknown>[] | Record<string, unknown>,
+ ): Promise<void>;
download(path: string): Promise<string>;
diff --git a/packages/shared/src/tableDefinitions/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.ts
index d81cb15d9d..4b94240330 100644
--- a/packages/shared/src/tableDefinitions/tracesTable.ts
+++ b/packages/shared/src/tableDefinitions/tracesTable.ts
@@ -211,6 +211,7 @@ export const datasetOnlyCols: ColumnDefinition[] = [datasetCol];
export const evalTraceTableCols: ColumnDefinition[] = tracesOnlyCols;
export const evalDatasetFormFilterCols: ColumnDefinition[] = datasetOnlyCols;
+
export type TraceOptions = {
scores_avg?: Array<string>;
score_categories?: Array<MultiValueOption>;
diff --git a/web/src/__tests__/async/evals-trpc.servertest.ts b/web/src/__tests__/async/evals-trpc.servertest.ts
index 198fd207e5..166e39b783 100644
--- a/web/src/__tests__/async/evals-trpc.servertest.ts
+++ b/web/src/__tests__/async/evals-trpc.servertest.ts
@@ -4,6 +4,7 @@ import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { prisma } from "@langfuse/shared/src/db";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { EvalTargetObject } from "@langfuse/shared";
import type { Session } from "next-auth";
const __orgIds: string[] = [];
@@ -76,7 +77,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -114,7 +115,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -175,7 +176,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -217,7 +218,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -248,7 +249,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -279,7 +280,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -324,7 +325,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -439,7 +440,7 @@ describe("evals trpc", () => {
jobType: "EVAL",
scoreName: "test-score",
filter: [],
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
variableMapping: [],
sampling: 1,
delay: 0,
@@ -524,7 +525,7 @@ describe("evals trpc", () => {
// jobType: "EVAL",
// scoreName: "test-score",
// filter: [],
- // targetObject: "trace",
+ // targetObject: EvalTargetObject.TRACE,
// variableMapping: [],
// sampling: 1,
// delay: 0,
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 4036cbee39..72d8bc15ca 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -18,6 +18,7 @@ import {
JobConfigState,
orderBy,
jsonSchema,
+ EvalTargetObject,
} from "@langfuse/shared";
import {
getQueue,
@@ -30,7 +31,7 @@ import {
orderByToPrismaSql,
DefaultEvalModelService,
testModelCall,
- clearNoJobConfigsCache,
+ clearNoEvalConfigsCache,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { EvalReferencedEvaluators } from "@/src/features/evals/types";
@@ -723,8 +724,9 @@ export const evalRouter = createTRPCRouter({
},
});
- // Clear the "no job configs" cache since we just created a new job configuration
- await clearNoJobConfigsCache(input.projectId);
+ // Clear the "no job configs" caches since we just created a new job configuration
+ await clearNoEvalConfigsCache(input.projectId, "traceBased");
+ await clearNoEvalConfigsCache(input.projectId, "eventBased");
if (input.timeScope.includes("EXISTING")) {
logger.info(
@@ -961,7 +963,7 @@ export const evalRouter = createTRPCRouter({
projectId: projectId,
evalTemplateId: evalTemplateId,
status: oldStatus,
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
},
});
@@ -1072,9 +1074,10 @@ export const evalRouter = createTRPCRouter({
data: config,
});
- // Clear the "no job configs" cache if we're activating a job configuration
+ // Clear the "no job configs" caches if we're activating a job configuration
if (config.status === "ACTIVE") {
- await clearNoJobConfigsCache(projectId);
+ await clearNoEvalConfigsCache(projectId, "traceBased");
+ await clearNoEvalConfigsCache(projectId, "eventBased");
}
if (config.timeScope?.includes("EXISTING")) {
@@ -1152,6 +1155,11 @@ export const evalRouter = createTRPCRouter({
projectId: projectId,
},
});
+
+ // Clear the "no job configs" caches to ensure they are re-evaluated
+ // This is conservative but ensures correctness after deletion
+ await clearNoEvalConfigsCache(projectId, "traceBased");
+ await clearNoEvalConfigsCache(projectId, "eventBased");
}),
// TODO: moved to LFE-4573
diff --git a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
index 27911d2f72..2030c15a31 100644
--- a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
+++ b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
@@ -1,10 +1,10 @@
import { Decimal } from "decimal.js";
-import { type EvalTemplate } from "@langfuse/shared";
+import { type EvalTemplate, EvalTargetObject } from "@langfuse/shared";
import { createDefaultVariableMappings } from "../utils/evaluatorMappingUtils";
import { type PartialConfig } from "@/src/features/evals/types";
export const CONFIG_BASE = {
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
sampling: new Decimal(1),
delay: 30000,
timeScope: ["NEW"],
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index d5ea5e5aac..58c111d3c6 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -1,5 +1,8 @@
-import { BatchExportTableName } from "@langfuse/shared";
-import { BatchActionType } from "@langfuse/shared";
+import {
+ BatchExportTableName,
+ BatchActionType,
+ EvalTargetObject,
+} from "@langfuse/shared";
import { expect, describe, it, vi } from "vitest";
import { v4 as uuidv4 } from "uuid";
import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJob";
@@ -270,7 +273,7 @@ describe("select all test suite", () => {
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -284,7 +287,7 @@ describe("select all test suite", () => {
payload: {
projectId,
actionId: "eval-create" as const,
- targetObject: "trace" as const,
+ targetObject: EvalTargetObject.TRACE,
configId,
cutoffCreatedAt: new Date(),
query: {
@@ -465,7 +468,7 @@ describe("select all test suite", () => {
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -482,7 +485,7 @@ describe("select all test suite", () => {
payload: {
projectId,
actionId: "eval-create" as const,
- targetObject: "dataset" as const,
+ targetObject: EvalTargetObject.DATASET,
configId,
cutoffCreatedAt: new Date(),
query: {
@@ -553,7 +556,7 @@ describe("select all test suite", () => {
payload: {
projectId,
actionId: "eval-create" as const,
- targetObject: "trace" as const,
+ targetObject: EvalTargetObject.TRACE,
configId: nonExistentConfigId,
cutoffCreatedAt: new Date(),
query: {
diff --git a/worker/src/__tests__/evalService.filtering.test.ts b/worker/src/__tests__/evalService.filtering.test.ts
index a677af1e87..58015dd2f9 100644
--- a/worker/src/__tests__/evalService.filtering.test.ts
+++ b/worker/src/__tests__/evalService.filtering.test.ts
@@ -1,4 +1,8 @@
-import { ObservationLevel, singleFilter } from "@langfuse/shared";
+import {
+ ObservationLevel,
+ singleFilter,
+ EvalTargetObject,
+} from "@langfuse/shared";
import {
JobConfiguration,
kyselyPrisma,
@@ -140,7 +144,7 @@ const test = baseTest.extend<{
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
...job,
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 26e2a8c94b..438223f1f8 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -3,6 +3,7 @@ import {
LLMAdapter,
ObservationType,
variableMappingList,
+ EvalTargetObject,
} from "@langfuse/shared";
import { encrypt } from "@langfuse/shared/encryption";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
@@ -599,7 +600,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -682,7 +683,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -757,7 +758,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -779,7 +780,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -854,7 +855,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -948,7 +949,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -1012,6 +1013,84 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
expect(jobsAfterTrace[0].start_time).not.toBeNull();
}, 10_000);
+ test("does not create job for 'event' config", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EVENT,
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ status: "INACTIVE",
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId: traceId,
+ };
+
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ 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 job for 'experiment' config", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const traceId = randomUUID();
+
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EXPERIMENT,
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ status: "INACTIVE",
+ },
+ });
+
+ const payload = {
+ projectId,
+ traceId: traceId,
+ };
+
+ await createEvalJobs({
+ sourceEventType: "trace-upsert",
+ event: payload,
+ jobTimestamp,
+ });
+
+ 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 job for inactive config", async () => {
const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
@@ -1024,7 +1103,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
status: "INACTIVE",
@@ -1084,7 +1163,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -1132,7 +1211,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
status: "INACTIVE",
@@ -1184,7 +1263,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("0"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -1270,7 +1349,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -1340,7 +1419,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
timeScope: ["EXISTING"],
@@ -1356,7 +1435,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
timeScope: ["NEW"],
@@ -1411,7 +1490,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
timeScope: ["NEW"],
@@ -1443,66 +1522,6 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
expect(jobs.length).toBe(1);
}, 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: projectId,
- id: traceId,
- timestamp: timestamp.getTime(),
- });
-
- const observation = createObservation({
- project_id: projectId,
- id: randomUUID(),
- start_time: timestamp.getTime(),
- });
-
- await createObservationsCh([observation]);
- await createTracesCh([trace]);
-
- const jobConfiguration = await prisma.jobConfiguration.create({
- data: {
- id: randomUUID(),
- projectId,
- filter: JSON.parse("[]"),
- jobType: "EVAL",
- delay: 0,
- sampling: new Decimal("1"),
- targetObject: "observation",
- scoreName: "score",
- variableMapping: JSON.parse("[]"),
- timeScope: ["EXISTING"],
- },
- });
-
- const payload = {
- projectId,
- traceId: traceId,
- configId: jobConfiguration.id,
- timestamp: timestamp,
- observationId: observation.id,
- };
-
- await createEvalJobs({
- sourceEventType: "trace-upsert",
- event: payload,
- jobTimestamp,
- enforcedJobTimeScope: "EXISTING", // the config must contain NEW
- });
-
- const jobs = await kyselyPrisma.$kysely
- .selectFrom("job_executions")
- .selectAll()
- .where("project_id", "=", projectId)
- .where("job_configuration_id", "in", [jobConfiguration.id])
- .execute();
-
- expect(jobs.length).toBe(1);
- }, 10_000);
-
test("create eval for trace with timestamp in the near future", async () => {
const { projectId } = await createOrgProjectAndApiKey();
const traceId = randomUUID();
@@ -1515,7 +1534,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
timeScope: ["NEW"],
@@ -1636,7 +1655,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score-alpha",
variableMapping: JSON.parse("[]"),
},
@@ -1654,7 +1673,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score-beta",
variableMapping: JSON.parse("[]"),
},
@@ -1672,7 +1691,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score-gamma",
variableMapping: JSON.parse("[]"),
},
@@ -1780,7 +1799,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score-alpha",
variableMapping: JSON.parse("[]"),
},
@@ -1798,7 +1817,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score-beta",
variableMapping: JSON.parse("[]"),
},
@@ -1876,7 +1895,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -1970,7 +1989,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -2067,7 +2086,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -2168,7 +2187,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -2244,7 +2263,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -2355,7 +2374,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
evalTemplateId: templateId,
@@ -2928,7 +2947,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "test-score",
variableMapping: JSON.parse(
'[{"langfuseObject":"trace","selectedColumnId":"input","templateVariable":"input"}]',
@@ -3011,7 +3030,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -3063,7 +3082,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -3158,7 +3177,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "dataset",
+ targetObject: EvalTargetObject.DATASET,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -3213,7 +3232,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -3265,7 +3284,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
@@ -3318,7 +3337,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
jobType: "EVAL",
delay: 0,
sampling: new Decimal("1"),
- targetObject: "trace",
+ targetObject: EvalTargetObject.TRACE,
scoreName: "score",
variableMapping: JSON.parse("[]"),
},
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 175d3a3a1e..a6ddf3967b 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -13,6 +13,7 @@ import {
evalJobDatasetCreatorQueueProcessor,
evalJobExecutorQueueProcessor,
evalJobTraceCreatorQueueProcessor,
+ llmAsJudgeExecutionQueueProcessor,
} from "./queues/evalQueue";
import { batchExportQueueProcessor } from "./queues/batchExportQueue";
import { onShutdown } from "./utils/shutdown";
@@ -242,6 +243,18 @@ if (env.QUEUE_CONSUMER_EVAL_EXECUTION_QUEUE_IS_ENABLED === "true") {
maxStalledCount: 3,
},
);
+
+ // LLM-as-Judge execution for observation-level evals (uses same env flag as trace evals)
+ WorkerManager.register(
+ QueueName.LLMAsJudgeExecution,
+ llmAsJudgeExecutionQueueProcessor,
+ {
+ concurrency: env.LANGFUSE_EVAL_EXECUTION_WORKER_CONCURRENCY,
+ lockDuration: 60000,
+ stalledInterval: 120000,
+ maxStalledCount: 3,
+ },
+ );
}
if (env.QUEUE_CONSUMER_BATCH_EXPORT_QUEUE_IS_ENABLED === "true") {
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index a7643003fd..541f8d9bf7 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -12,6 +12,7 @@ import {
BatchActionType,
BatchTableNames,
FilterCondition,
+ EvalTargetObject,
} from "@langfuse/shared";
import {
getDatabaseReadStreamPaginated,
@@ -229,7 +230,7 @@ export const handleBatchActionJob = async (
}
const dbReadStream =
- targetObject === "trace"
+ targetObject === EvalTargetObject.TRACE
? await getTraceIdentifierStream({
projectId: projectId,
cutoffCreatedAt: new Date(cutoffCreatedAt),
@@ -256,7 +257,10 @@ export const handleBatchActionJob = async (
let count = 0;
for await (const record of dbReadStream) {
- if (targetObject === "trace" && assertIsTracesTableRecord(record)) {
+ if (
+ targetObject === EvalTargetObject.TRACE &&
+ assertIsTracesTableRecord(record)
+ ) {
const payload = {
projectId: record.projectId,
traceId: record.id,
@@ -273,7 +277,7 @@ export const handleBatchActionJob = async (
});
count++;
} else if (
- targetObject === "dataset" &&
+ targetObject === EvalTargetObject.DATASET &&
assertIsDatasetRunItemTableRecord(record)
) {
const payload = {
diff --git a/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts b/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts
new file mode 100644
index 0000000000..19f06c80b5
--- /dev/null
+++ b/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts
@@ -0,0 +1,406 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
+import { randomUUID } from "crypto";
+import Decimal from "decimal.js";
+import {
+ createOrgProjectAndApiKey,
+ StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { EvalTargetObject } from "@langfuse/shared";
+import { env } from "../../../env";
+import { createObservationEvalSchedulerDeps } from "../observationEval/createSchedulerDeps";
+import { createProductionEvalExecutionDeps } from "../evalExecutionDeps";
+import { JobExecutionStatus } from "@prisma/client";
+
+/**
+ * Integration tests for production dependency factories.
+ *
+ * These tests verify that the production implementations of dependency factories
+ * work correctly with real infrastructure (PostgreSQL, MinIO S3).
+ *
+ * Prerequisites:
+ * - Local PostgreSQL running (via docker compose)
+ * - Local MinIO running on localhost:9090
+ */
+describe("Production Dependency Factories Integration Tests", () => {
+ let s3StorageService: StorageService;
+ const bucketName = env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET || "langfuse";
+ const minioAccessKeyId = "minio";
+ const minioAccessKeySecret = "miniosecret";
+ const minioEndpoint = "http://localhost:9090";
+
+ // Track created files for cleanup
+ let createdS3Paths: string[] = [];
+
+ beforeAll(async () => {
+ // Initialize S3 client for verification and cleanup
+ s3StorageService = StorageServiceFactory.getInstance({
+ accessKeyId: minioAccessKeyId,
+ secretAccessKey: minioAccessKeySecret,
+ bucketName,
+ endpoint: minioEndpoint,
+ region: "auto",
+ forcePathStyle: true,
+ useAzureBlob: false,
+ });
+ });
+
+ beforeEach(() => {
+ createdS3Paths = [];
+ });
+
+ afterAll(async () => {
+ // Clean up S3 files created during tests
+ if (createdS3Paths.length > 0) {
+ try {
+ await s3StorageService.deleteFiles(createdS3Paths);
+ } catch {
+ // Ignore cleanup errors
+ }
+ }
+ });
+
+ describe("createObservationEvalSchedulerDeps", () => {
+ const deps = createObservationEvalSchedulerDeps();
+
+ describe("upsertJobExecution", () => {
+ it("should create a job execution record in the database", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create required job configuration first
+ const jobConfig = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: [],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EVENT,
+ scoreName: "test-score",
+ variableMapping: [],
+ },
+ });
+
+ const jobExecutionId = randomUUID();
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+
+ // Execute
+ const result = await deps.upsertJobExecution({
+ id: jobExecutionId,
+ projectId,
+ jobConfigurationId: jobConfig.id,
+ jobInputTraceId: traceId,
+ jobInputObservationId: observationId,
+ jobTemplateId: null,
+ status: "PENDING",
+ });
+
+ // Verify
+ expect(result).toHaveProperty("id");
+ expect(result.id).toBe(jobExecutionId);
+
+ // Verify in database
+ const dbRecord = await prisma.jobExecution.findUnique({
+ where: { id: result.id },
+ });
+
+ expect(dbRecord).not.toBeNull();
+ expect(dbRecord?.projectId).toBe(projectId);
+ expect(dbRecord?.jobConfigurationId).toBe(jobConfig.id);
+ expect(dbRecord?.jobInputTraceId).toBe(traceId);
+ expect(dbRecord?.jobInputObservationId).toBe(observationId);
+ expect(dbRecord?.status).toBe("PENDING");
+ }, 15_000);
+ });
+
+ describe("uploadObservationToS3", () => {
+ it("should upload observation data to S3 and return the path", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const observationId = randomUUID();
+
+ const observationData = {
+ id: observationId,
+ traceId: randomUUID(),
+ projectId,
+ type: "GENERATION",
+ input: { prompt: "Hello" },
+ output: { response: "World" },
+ model: "gpt-4",
+ environment: "test",
+ };
+
+ // Execute
+ const s3Path = await deps.uploadObservationToS3({
+ projectId,
+ observationId,
+ data: observationData,
+ });
+
+ // Track for cleanup
+ createdS3Paths.push(s3Path);
+
+ // Verify path format (uses env prefix, defaults to "")
+ const prefix = env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX || "";
+ expect(s3Path).toBe(
+ `${prefix}evals/${projectId}/observations/${observationId}.json`,
+ );
+
+ // Verify file exists in S3 by checking it was created with the correct path
+ // Note: Download may fail in test environment without proper S3 setup
+ expect(s3Path).toBeTruthy();
+ });
+ });
+ });
+
+ describe("createProductionEvalExecutionDeps", () => {
+ const deps = createProductionEvalExecutionDeps();
+
+ describe("updateJobExecution", () => {
+ it("should update job execution status to COMPLETED", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create required job configuration
+ const jobConfig = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: [],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EVENT,
+ scoreName: "test-score",
+ variableMapping: [],
+ },
+ });
+
+ // Create a job execution
+ const jobExecution = await prisma.jobExecution.create({
+ data: {
+ projectId,
+ jobConfigurationId: jobConfig.id,
+ jobInputTraceId: randomUUID(),
+ jobInputObservationId: randomUUID(),
+ status: "PENDING",
+ },
+ });
+
+ const scoreId = randomUUID();
+ const traceId = randomUUID();
+ const endTime = new Date();
+
+ // Execute
+ await deps.updateJobExecution({
+ id: jobExecution.id,
+ projectId,
+ data: {
+ status: JobExecutionStatus.COMPLETED,
+ endTime,
+ jobOutputScoreId: scoreId,
+ executionTraceId: traceId,
+ },
+ });
+
+ // Verify
+ const updated = await prisma.jobExecution.findUnique({
+ where: { id: jobExecution.id },
+ });
+
+ expect(updated?.status).toBe("COMPLETED");
+ expect(updated?.endTime).toEqual(endTime);
+ expect(updated?.jobOutputScoreId).toBe(scoreId);
+ expect(updated?.executionTraceId).toBe(traceId);
+ });
+
+ it("should update job execution status to ERROR with error message", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create required job configuration
+ const jobConfig = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: [],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EVENT,
+ scoreName: "test-score",
+ variableMapping: [],
+ },
+ });
+
+ // Create a job execution
+ const jobExecution = await prisma.jobExecution.create({
+ data: {
+ projectId,
+ jobConfigurationId: jobConfig.id,
+ jobInputTraceId: randomUUID(),
+ jobInputObservationId: randomUUID(),
+ status: "PENDING",
+ },
+ });
+
+ // Execute
+ await deps.updateJobExecution({
+ id: jobExecution.id,
+ projectId,
+ data: {
+ status: JobExecutionStatus.ERROR,
+ endTime: new Date(),
+ },
+ });
+
+ // Verify
+ const updated = await prisma.jobExecution.findUnique({
+ where: { id: jobExecution.id },
+ });
+
+ expect(updated?.status).toBe("ERROR");
+ expect(updated?.endTime).toBeTruthy();
+ });
+ });
+
+ describe("uploadScore", () => {
+ it("should upload score event to S3 without throwing", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const scoreId = randomUUID();
+ const eventId = randomUUID();
+
+ const scoreEvent = {
+ id: scoreId,
+ name: "test-eval-score",
+ value: 0.85,
+ traceId: randomUUID(),
+ observationId: randomUUID(),
+ source: "EVAL",
+ comment: "Test evaluation",
+ dataType: "NUMERIC",
+ };
+
+ // Execute - should not throw
+ await expect(
+ deps.uploadScore({
+ projectId,
+ scoreId,
+ eventId,
+ event: scoreEvent,
+ }),
+ ).resolves.not.toThrow();
+ });
+ });
+ });
+
+ describe("Integration: Scheduler creates job that can be updated by Executor", () => {
+ it("should support the full workflow of job creation and status updates", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create required job configuration
+ const jobConfig = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ filter: [],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: EvalTargetObject.EVENT,
+ scoreName: "integration-test-score",
+ variableMapping: [],
+ },
+ });
+
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const jobExecutionId = randomUUID();
+
+ const schedulerDeps = createObservationEvalSchedulerDeps();
+ const executorDeps = createProductionEvalExecutionDeps();
+
+ // Step 1: Scheduler creates job execution
+ await schedulerDeps.upsertJobExecution({
+ id: jobExecutionId,
+ projectId,
+ jobConfigurationId: jobConfig.id,
+ jobInputTraceId: traceId,
+ jobInputObservationId: observationId,
+ jobTemplateId: null,
+ status: "PENDING",
+ });
+
+ // Step 2: Scheduler uploads observation to S3
+ const observationData = {
+ id: observationId,
+ traceId,
+ projectId,
+ type: "GENERATION",
+ input: { prompt: "What is 2+2?" },
+ output: { response: "4" },
+ model: "gpt-4",
+ environment: "test",
+ };
+
+ const s3Path = await schedulerDeps.uploadObservationToS3({
+ projectId,
+ observationId,
+ data: observationData,
+ });
+ createdS3Paths.push(s3Path);
+
+ // Verify job is PENDING
+ let jobExecution = await prisma.jobExecution.findUnique({
+ where: { id: jobExecutionId },
+ });
+ expect(jobExecution?.status).toBe("PENDING");
+
+ // Step 3: Executor processes and updates to COMPLETED
+ const scoreId = randomUUID();
+ const executionTraceId = randomUUID();
+
+ await executorDeps.updateJobExecution({
+ id: jobExecutionId,
+ projectId,
+ data: {
+ status: JobExecutionStatus.COMPLETED,
+ endTime: new Date(),
+ jobOutputScoreId: scoreId,
+ executionTraceId,
+ },
+ });
+
+ // Step 4: Executor uploads score to S3
+ const eventId = randomUUID();
+ await executorDeps.uploadScore({
+ projectId,
+ scoreId,
+ eventId,
+ event: {
+ id: scoreId,
+ name: "integration-test-score",
+ value: 1.0,
+ traceId,
+ observationId,
+ source: "EVAL",
+ dataType: "NUMERIC",
+ },
+ });
+
+ const prefix = env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX || "";
+ createdS3Paths.push(
+ `${prefix}${projectId}/score/${scoreId}/${eventId}.json`,
+ );
+
+ // Verify final state
+ jobExecution = await prisma.jobExecution.findUnique({
+ where: { id: jobExecutionId },
+ });
+
+ expect(jobExecution?.status).toBe("COMPLETED");
+ expect(jobExecution?.jobOutputScoreId).toBe(scoreId);
+ expect(jobExecution?.executionTraceId).toBe(executionTraceId);
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
new file mode 100644
index 0000000000..e1f1661ba5
--- /dev/null
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -0,0 +1,242 @@
+import { randomUUID } from "crypto";
+import { JobExecutionStatus } from "@prisma/client";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ DefaultEvalModelService,
+ fetchLLMCompletion,
+ IngestionQueue,
+ QueueJobs,
+ ScoreEventType,
+} from "@langfuse/shared/src/server";
+import { env } from "../../env";
+import { buildEvalScoreSchema, buildEvalMessages } from "./evalExecutionUtils";
+import { getEvalS3StorageClient } from "./s3StorageClient";
+
+/**
+ * Result of fetching model configuration.
+ */
+export type ModelConfigResult =
+ | {
+ valid: true;
+ config: {
+ provider: string;
+ model: string;
+ apiKey: {
+ adapter: string;
+ [key: string]: unknown;
+ };
+ modelParams: Record<string, unknown>;
+ };
+ }
+ | {
+ valid: false;
+ error: string;
+ };
+
+/**
+ * Parameters for calling the LLM.
+ */
+export interface LLMCallParams {
+ messages: ReturnType<typeof buildEvalMessages>;
+ modelConfig: Extract<ModelConfigResult, { valid: true }>["config"];
+ structuredOutputSchema: ReturnType<typeof buildEvalScoreSchema>;
+ traceSinkParams: {
+ targetProjectId: string;
+ traceId: string;
+ traceName: string;
+ environment: string;
+ metadata: Record<string, unknown>;
+ };
+}
+
+/**
+ * Update data for job execution status.
+ */
+export interface UpdateJobExecutionData {
+ status: JobExecutionStatus;
+ endTime?: Date;
+ jobOutputScoreId?: string;
+ executionTraceId?: string;
+}
+
+/**
+ * Parameters for uploading a score to S3.
+ */
+export interface UploadScoreParams {
+ projectId: string;
+ scoreId: string;
+ eventId: string;
+ event: ScoreEventType;
+}
+
+/**
+ * Parameters for enqueueing score ingestion.
+ */
+export interface EnqueueScoreIngestionParams {
+ projectId: string;
+ scoreId: string;
+ eventId: string;
+}
+
+/**
+ * Parameters for updating a job execution.
+ */
+export interface UpdateJobExecutionParams {
+ id: string;
+ projectId: string;
+ data: UpdateJobExecutionData;
+}
+
+/**
+ * Parameters for fetching model configuration.
+ */
+export interface FetchModelConfigParams {
+ projectId: string;
+ provider?: string;
+ model?: string;
+ modelParams?: Record<string, unknown> | null;
+}
+
+/**
+ * Dependency interface for eval execution.
+ * This allows for easy mocking in tests while providing
+ * a clear contract for all external dependencies.
+ *
+ * Note: Database fetching (job, config, template) is handled by callers,
+ * not by the executor. This interface only covers operations needed
+ * during LLM execution and score persistence.
+ */
+export interface EvalExecutionDeps {
+ // Database operations (for status updates only)
+ updateJobExecution: (params: UpdateJobExecutionParams) => Promise<void>;
+
+ // Storage operations
+ uploadScore: (params: UploadScoreParams) => Promise<void>;
+
+ // Queue operations
+ enqueueScoreIngestion: (params: EnqueueScoreIngestionParams) => Promise<void>;
+
+ // LLM operations
+ callLLM: (params: LLMCallParams) => Promise<unknown>;
+ fetchModelConfig: (
+ params: FetchModelConfigParams,
+ ) => Promise<ModelConfigResult>;
+}
+
+/**
+ * Creates the production implementation of eval execution dependencies.
+ * This is the default implementation used in production code.
+ */
+export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
+ return {
+ updateJobExecution: async ({ id, projectId, data }) => {
+ await prisma.jobExecution.update({
+ where: { id, projectId },
+ data,
+ });
+ },
+
+ uploadScore: async (params) => {
+ const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${params.projectId}/score/${params.scoreId}/${params.eventId}.json`;
+
+ await getEvalS3StorageClient().uploadJson(bucketPath, [
+ params.event as unknown as Record<string, unknown>,
+ ]);
+ },
+
+ enqueueScoreIngestion: async (params) => {
+ const shardingKey = `${params.projectId}-${params.scoreId}`;
+ const queue = IngestionQueue.getInstance({ shardingKey });
+ if (!queue) {
+ throw new Error("Ingestion queue not available");
+ }
+
+ await queue.add(QueueJobs.IngestionJob, {
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.IngestionJob as const,
+ payload: {
+ data: {
+ type: "score-create",
+ eventBodyId: params.scoreId,
+ fileKey: params.eventId,
+ },
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId: params.projectId,
+ },
+ },
+ },
+ });
+ },
+
+ callLLM: async (params) => {
+ // Type assertion needed because the deps interface uses a simplified apiKey type for testability
+ // while the actual fetchLLMCompletion requires a full LlmApiKey type
+ const llmConnection = params.modelConfig.apiKey as unknown as Parameters<
+ typeof fetchLLMCompletion
+ >[0]["llmConnection"];
+
+ const adapter = params.modelConfig.apiKey
+ .adapter as unknown as Parameters<
+ typeof fetchLLMCompletion
+ >[0]["modelParams"]["adapter"];
+
+ return fetchLLMCompletion({
+ streaming: false,
+ llmConnection,
+ messages: params.messages,
+ modelParams: {
+ provider: params.modelConfig.provider,
+ model: params.modelConfig.model,
+ adapter,
+ ...params.modelConfig.modelParams,
+ },
+ structuredOutputSchema: params.structuredOutputSchema,
+ maxRetries: 1,
+ traceSinkParams: {
+ targetProjectId: params.traceSinkParams.targetProjectId,
+ traceId: params.traceSinkParams.traceId,
+ traceName: params.traceSinkParams.traceName,
+ environment: params.traceSinkParams.environment,
+ metadata: params.traceSinkParams.metadata,
+ },
+ });
+ },
+
+ fetchModelConfig: async ({ projectId, provider, model, modelParams }) => {
+ const result = await DefaultEvalModelService.fetchValidModelConfig(
+ projectId,
+ provider,
+ model,
+ modelParams,
+ );
+
+ // Cast to our simplified ModelConfigResult type for the interface
+ return result as ModelConfigResult;
+ },
+ };
+}
+
+/**
+ * Creates a mock implementation of eval execution dependencies for testing.
+ * All functions are no-ops or return null by default.
+ * Override specific functions as needed in tests.
+ */
+export function createMockEvalExecutionDeps(
+ overrides?: Partial<EvalExecutionDeps>,
+): EvalExecutionDeps {
+ const defaultMock: EvalExecutionDeps = {
+ updateJobExecution: async () => {},
+ uploadScore: async () => {},
+ enqueueScoreIngestion: async () => {},
+ callLLM: async () => ({ score: 0.5, reasoning: "Mock response" }),
+ fetchModelConfig: async () => ({
+ valid: false,
+ error: "Mock - no config",
+ }),
+ };
+
+ return { ...defaultMock, ...overrides };
+}
diff --git a/worker/src/features/evaluation/evalExecutionUtils.test.ts b/worker/src/features/evaluation/evalExecutionUtils.test.ts
new file mode 100644
index 0000000000..7457b8f7ba
--- /dev/null
+++ b/worker/src/features/evaluation/evalExecutionUtils.test.ts
@@ -0,0 +1,390 @@
+import { describe, expect, it } from "vitest";
+import {
+ compileEvalPrompt,
+ buildEvalScoreSchema,
+ buildExecutionMetadata,
+ buildEvalMessages,
+ buildScoreEvent,
+ getEnvironmentFromVariables,
+ validateLLMResponse,
+ evalTemplateOutputSchema,
+} from "./evalExecutionUtils";
+import { type ExtractedVariable } from "./evalService";
+import { ChatMessageRole } from "@langfuse/shared";
+import { ChatMessageType } from "@langfuse/shared/src/server";
+
+describe("evalExecutionUtils", () => {
+ describe("compileEvalPrompt", () => {
+ it("should compile template with variables", () => {
+ const params = {
+ templatePrompt: "Evaluate {{input}} and compare to {{output}}",
+ variables: [
+ { var: "input", value: "user question" },
+ { var: "output", value: "model response" },
+ ] as ExtractedVariable[],
+ };
+
+ const result = compileEvalPrompt(params);
+ expect(result).toBe(
+ "Evaluate user question and compare to model response",
+ );
+ });
+
+ it("should handle empty variables array", () => {
+ const params = {
+ templatePrompt: "Plain text without variables",
+ variables: [] as ExtractedVariable[],
+ };
+
+ const result = compileEvalPrompt(params);
+ expect(result).toBe("Plain text without variables");
+ });
+
+ it("should handle variables with special characters", () => {
+ const params = {
+ templatePrompt: "Input: {{input}}",
+ variables: [
+ { var: "input", value: "text with \"quotes\" and 'apostrophes'" },
+ ] as ExtractedVariable[],
+ };
+
+ const result = compileEvalPrompt(params);
+ expect(result).toBe("Input: text with \"quotes\" and 'apostrophes'");
+ });
+
+ it("should handle JSON values in variables", () => {
+ const params = {
+ templatePrompt: "Data: {{data}}",
+ variables: [
+ { var: "data", value: '{"key": "value", "count": 42}' },
+ ] as ExtractedVariable[],
+ };
+
+ const result = compileEvalPrompt(params);
+ expect(result).toBe('Data: {"key": "value", "count": 42}');
+ });
+ });
+
+ describe("buildEvalScoreSchema", () => {
+ it("should build schema with descriptions", () => {
+ const outputSchema = {
+ score: "A number between 0 and 1 indicating accuracy",
+ reasoning: "Explanation of the score",
+ };
+
+ const schema = buildEvalScoreSchema(outputSchema);
+
+ // Validate schema shape
+ expect(schema.shape.score).toBeDefined();
+ expect(schema.shape.reasoning).toBeDefined();
+ });
+
+ it("should validate correct response", () => {
+ const outputSchema = {
+ score: "Score between 0 and 1",
+ reasoning: "The reasoning",
+ };
+
+ const schema = buildEvalScoreSchema(outputSchema);
+ const result = schema.safeParse({
+ score: 0.75,
+ reasoning: "Good accuracy overall",
+ });
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.score).toBe(0.75);
+ expect(result.data.reasoning).toBe("Good accuracy overall");
+ }
+ });
+
+ it("should reject invalid response - missing score", () => {
+ const outputSchema = {
+ score: "Score between 0 and 1",
+ reasoning: "The reasoning",
+ };
+
+ const schema = buildEvalScoreSchema(outputSchema);
+ const result = schema.safeParse({
+ reasoning: "Missing score",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should reject invalid response - string score", () => {
+ const outputSchema = {
+ score: "Score between 0 and 1",
+ reasoning: "The reasoning",
+ };
+
+ const schema = buildEvalScoreSchema(outputSchema);
+ const result = schema.safeParse({
+ score: "0.75",
+ reasoning: "Score is string",
+ });
+
+ expect(result.success).toBe(false);
+ });
+ });
+
+ describe("buildExecutionMetadata", () => {
+ it("should include all provided fields", () => {
+ const params = {
+ jobExecutionId: "exec-123",
+ jobConfigurationId: "config-456",
+ targetTraceId: "trace-789",
+ targetObservationId: "obs-abc",
+ targetDatasetItemId: "dataset-def",
+ };
+
+ const result = buildExecutionMetadata(params);
+
+ expect(result).toEqual({
+ job_execution_id: "exec-123",
+ job_configuration_id: "config-456",
+ target_trace_id: "trace-789",
+ target_observation_id: "obs-abc",
+ target_dataset_item_id: "dataset-def",
+ });
+ });
+
+ it("should exclude null/undefined fields", () => {
+ const params = {
+ jobExecutionId: "exec-123",
+ jobConfigurationId: "config-456",
+ targetTraceId: null,
+ targetObservationId: undefined,
+ targetDatasetItemId: null,
+ };
+
+ const result = buildExecutionMetadata(params);
+
+ expect(result).toEqual({
+ job_execution_id: "exec-123",
+ job_configuration_id: "config-456",
+ });
+ expect(Object.keys(result)).not.toContain("target_trace_id");
+ expect(Object.keys(result)).not.toContain("target_observation_id");
+ expect(Object.keys(result)).not.toContain("target_dataset_item_id");
+ });
+ });
+
+ describe("buildEvalMessages", () => {
+ it("should build user message array", () => {
+ const prompt = "Evaluate this response";
+
+ const result = buildEvalMessages(prompt);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toEqual({
+ type: ChatMessageType.User,
+ role: ChatMessageRole.User,
+ content: "Evaluate this response",
+ });
+ });
+
+ it("should handle multiline prompts", () => {
+ const prompt = "First line\nSecond line\nThird line";
+
+ const result = buildEvalMessages(prompt);
+
+ expect(result[0].content).toBe("First line\nSecond line\nThird line");
+ });
+ });
+
+ describe("buildScoreEvent", () => {
+ it("should build complete score event", () => {
+ const params = {
+ eventId: "event-123",
+ scoreId: "score-456",
+ traceId: "trace-789",
+ observationId: null,
+ scoreName: "accuracy",
+ value: 0.85,
+ reasoning: "High accuracy observed",
+ environment: "production",
+ executionTraceId: "exec-trace-abc",
+ metadata: { job_execution_id: "exec-123" },
+ };
+
+ const result = buildScoreEvent(params);
+
+ expect(result.id).toBe("event-123");
+ expect(result.type).toBe("score-create");
+ expect(result.body.id).toBe("score-456");
+ expect(result.body.traceId).toBe("trace-789");
+ expect(result.body.observationId).toBeNull();
+ expect(result.body.name).toBe("accuracy");
+ expect(result.body.value).toBe(0.85);
+ expect(result.body.comment).toBe("High accuracy observed");
+ expect(result.body.source).toBe("EVAL");
+ expect(result.body.environment).toBe("production");
+ expect(result.body.executionTraceId).toBe("exec-trace-abc");
+ expect(result.body.metadata).toEqual({ job_execution_id: "exec-123" });
+ expect(result.body.dataType).toBe("NUMERIC");
+ });
+
+ it("should include observation ID when provided", () => {
+ const params = {
+ eventId: "event-123",
+ scoreId: "score-456",
+ traceId: "trace-789",
+ observationId: "obs-abc",
+ scoreName: "relevance",
+ value: 0.9,
+ reasoning: "Highly relevant",
+ environment: "default",
+ executionTraceId: "exec-trace-def",
+ metadata: {},
+ };
+
+ const result = buildScoreEvent(params);
+
+ expect(result.body.observationId).toBe("obs-abc");
+ });
+ });
+
+ describe("getEnvironmentFromVariables", () => {
+ it("should return environment from variable that has it", () => {
+ const variables: ExtractedVariable[] = [
+ { var: "input", value: "test" },
+ { var: "output", value: "result", environment: "production" },
+ { var: "context", value: "extra" },
+ ];
+
+ const result = getEnvironmentFromVariables(variables);
+
+ expect(result).toBe("production");
+ });
+
+ it("should return first environment when multiple exist", () => {
+ const variables: ExtractedVariable[] = [
+ { var: "input", value: "test", environment: "staging" },
+ { var: "output", value: "result", environment: "production" },
+ ];
+
+ const result = getEnvironmentFromVariables(variables);
+
+ expect(result).toBe("staging");
+ });
+
+ it("should return undefined when no environment exists", () => {
+ const variables: ExtractedVariable[] = [
+ { var: "input", value: "test" },
+ { var: "output", value: "result" },
+ ];
+
+ const result = getEnvironmentFromVariables(variables);
+
+ expect(result).toBeUndefined();
+ });
+
+ it("should return undefined for empty array", () => {
+ const result = getEnvironmentFromVariables([]);
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe("validateLLMResponse", () => {
+ it("should validate correct response", () => {
+ const schema = buildEvalScoreSchema({
+ score: "Score 0-1",
+ reasoning: "Why",
+ });
+
+ const result = validateLLMResponse({
+ response: { score: 0.8, reasoning: "Good" },
+ schema,
+ });
+
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.score).toBe(0.8);
+ expect(result.data.reasoning).toBe("Good");
+ }
+ });
+
+ it("should return error for invalid response", () => {
+ const schema = buildEvalScoreSchema({
+ score: "Score 0-1",
+ reasoning: "Why",
+ });
+
+ const result = validateLLMResponse({
+ response: { score: "invalid", reasoning: "Test" },
+ schema,
+ });
+
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error).toBeDefined();
+ }
+ });
+
+ it("should return error for null response", () => {
+ const schema = buildEvalScoreSchema({
+ score: "Score 0-1",
+ reasoning: "Why",
+ });
+
+ const result = validateLLMResponse({
+ response: null,
+ schema,
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should return error for missing fields", () => {
+ const schema = buildEvalScoreSchema({
+ score: "Score 0-1",
+ reasoning: "Why",
+ });
+
+ const result = validateLLMResponse({
+ response: { score: 0.5 },
+ schema,
+ });
+
+ expect(result.success).toBe(false);
+ });
+ });
+
+ describe("evalTemplateOutputSchema", () => {
+ it("should validate correct output schema", () => {
+ const result = evalTemplateOutputSchema.safeParse({
+ score: "A number between 0 and 1",
+ reasoning: "Explanation of the score",
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("should reject schema missing score", () => {
+ const result = evalTemplateOutputSchema.safeParse({
+ reasoning: "Only reasoning",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should reject schema missing reasoning", () => {
+ const result = evalTemplateOutputSchema.safeParse({
+ score: "Only score",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("should reject non-string score", () => {
+ const result = evalTemplateOutputSchema.safeParse({
+ score: 0.5,
+ reasoning: "Explanation",
+ });
+
+ expect(result.success).toBe(false);
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/evalExecutionUtils.ts b/worker/src/features/evaluation/evalExecutionUtils.ts
new file mode 100644
index 0000000000..a770e5b950
--- /dev/null
+++ b/worker/src/features/evaluation/evalExecutionUtils.ts
@@ -0,0 +1,180 @@
+import { z } from "zod/v4";
+import { z as zodV3 } from "zod/v3";
+import { ScoreSourceEnum, ChatMessageRole } from "@langfuse/shared";
+import {
+ ChatMessageType,
+ eventTypes,
+ ScoreEventType,
+} from "@langfuse/shared/src/server";
+import { compileTemplateString } from "../utils";
+import { ExtractedVariable } from "./observationEval/extractObservationVariables";
+
+/**
+ * Output schema for eval templates - defines the expected LLM response structure.
+ */
+export const evalTemplateOutputSchema = z.object({
+ score: z.string(),
+ reasoning: z.string(),
+});
+
+export type EvalTemplateOutputSchema = z.infer<typeof evalTemplateOutputSchema>;
+
+/**
+ * Parameters for compiling an eval prompt.
+ */
+export interface CompileEvalPromptParams {
+ templatePrompt: string;
+ variables: ExtractedVariable[];
+}
+
+/**
+ * Compiles an eval prompt template by substituting variables.
+ *
+ * @param params - The template prompt and variables to substitute
+ * @returns The compiled prompt string
+ */
+export function compileEvalPrompt(params: CompileEvalPromptParams): string {
+ const variableMap = Object.fromEntries(
+ params.variables.map(({ var: key, value }) => [key, value]),
+ );
+
+ return compileTemplateString(params.templatePrompt, variableMap);
+}
+
+/**
+ * Builds a Zod v3 schema for validating LLM structured output.
+ * Uses Zod v3 because the LLM completion service requires it.
+ *
+ * @param outputSchema - The parsed output schema from the eval template
+ * @returns A Zod v3 schema for validating LLM responses
+ */
+export function buildEvalScoreSchema(outputSchema: EvalTemplateOutputSchema) {
+ return zodV3.object({
+ reasoning: zodV3.string().describe(outputSchema.reasoning),
+ score: zodV3.number().describe(outputSchema.score),
+ });
+}
+
+/**
+ * Builds execution metadata for tracking and debugging.
+ *
+ * @param params - Job execution identifiers
+ * @returns Record of non-null metadata entries
+ */
+export function buildExecutionMetadata(params: {
+ jobExecutionId: string;
+ jobConfigurationId: string;
+ targetTraceId?: string | null;
+ targetObservationId?: string | null;
+ targetDatasetItemId?: string | null;
+}): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries({
+ job_execution_id: params.jobExecutionId,
+ job_configuration_id: params.jobConfigurationId,
+ target_trace_id: params.targetTraceId,
+ target_observation_id: params.targetObservationId,
+ target_dataset_item_id: params.targetDatasetItemId,
+ }).filter(([, v]) => v != null),
+ ) as Record<string, string>;
+}
+
+/**
+ * Builds the LLM chat messages for eval execution.
+ *
+ * @param prompt - The compiled prompt string
+ * @returns Array of chat messages for the LLM call
+ */
+export function buildEvalMessages(prompt: string) {
+ return [
+ {
+ type: ChatMessageType.User,
+ role: ChatMessageRole.User,
+ content: prompt,
+ } as const,
+ ];
+}
+
+/**
+ * Parameters for building a score event.
+ */
+export interface BuildScoreEventParams {
+ eventId: string;
+ scoreId: string;
+ traceId: string | null;
+ observationId: string | null;
+ scoreName: string;
+ value: number;
+ reasoning: string;
+ environment: string;
+ executionTraceId: string;
+ metadata: Record<string, string>;
+}
+
+/**
+ * Builds a score event for S3 upload and ingestion queue.
+ *
+ * @param params - Score event parameters
+ * @returns A score event ready for persistence
+ */
+export function buildScoreEvent(params: BuildScoreEventParams): ScoreEventType {
+ return {
+ id: params.eventId,
+ timestamp: new Date().toISOString(),
+ type: eventTypes.SCORE_CREATE,
+ body: {
+ id: params.scoreId,
+ traceId: params.traceId,
+ observationId: params.observationId,
+ name: params.scoreName,
+ value: params.value,
+ comment: params.reasoning,
+ source: ScoreSourceEnum.EVAL,
+ environment: params.environment,
+ executionTraceId: params.executionTraceId,
+ metadata: params.metadata,
+ dataType: "NUMERIC",
+ },
+ };
+}
+
+/**
+ * Extracts the environment from extracted variables.
+ * The environment is included on the first variable that has it set.
+ *
+ * @param variables - Array of extracted variables
+ * @returns The environment string or undefined
+ */
+export function getEnvironmentFromVariables(
+ variables: ExtractedVariable[],
+): string | undefined {
+ return variables.find((v) => v.environment)?.environment;
+}
+
+/**
+ * Parameters for validating LLM response.
+ */
+export interface ValidateLLMResponseParams {
+ response: unknown;
+ schema: ReturnType<typeof buildEvalScoreSchema>;
+}
+
+/**
+ * Validates and parses the LLM response against the score schema.
+ *
+ * @param params - The raw LLM response and schema to validate against
+ * @returns Parsed response with score and reasoning, or error
+ */
+export function validateLLMResponse(
+ params: ValidateLLMResponseParams,
+):
+ | { success: true; data: { score: number; reasoning: string } }
+ | { success: false; error: string } {
+ const result = params.schema.safeParse(params.response);
+
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+
+ return { success: false, error: result.error.message };
+}
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 87ccc44ed8..dd869cb71f 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -1,26 +1,24 @@
import { randomUUID } from "crypto";
import { sql } from "kysely";
import { z } from "zod/v4";
-import { z as zodV3 } from "zod/v3";
-import { JobConfigState, JobExecutionStatus } from "@prisma/client";
+import {
+ JobConfigState,
+ JobExecutionStatus,
+ type JobExecution,
+ type JobConfiguration,
+ type EvalTemplate,
+} from "@prisma/client";
import {
QueueJobs,
QueueName,
EvalExecutionEvent,
traceException,
- eventTypes,
- setNoJobConfigsCache,
- IngestionQueue,
logger,
EvalExecutionQueue,
checkTraceExistsAndGetTimestamp,
checkObservationExists,
TraceQueueEventType,
- StorageService,
- StorageServiceFactory,
CreateEvalQueueEventType,
- ChatMessageType,
- DefaultEvalModelService,
getTraceById,
getObservationForTraceIdByName,
InMemoryFilterService,
@@ -28,59 +26,49 @@ import {
getCurrentSpan,
getDatasetItemIdsByTraceIdCh,
mapDatasetRunItemFilterColumn,
- fetchLLMCompletion,
- LangfuseInternalTraceEnvironment,
tableColumnsToSqlFilterAndPrefix,
+ LangfuseInternalTraceEnvironment,
+ DEFAULT_TRACE_ENVIRONMENT,
+ setNoEvalConfigsCache,
} from "@langfuse/shared/src/server";
import {
mapTraceFilterColumn,
requiresDatabaseLookup,
} from "./traceFilterUtils";
import {
- ChatMessageRole,
Prisma,
singleFilter,
variableMappingList,
evalDatasetFormFilterCols,
availableDatasetEvalVariables,
JobTimeScope,
- ScoreSourceEnum,
availableTraceEvalVariables,
variableMapping,
TraceDomain,
Observation,
DatasetItem,
+ EvalTargetObject,
} from "@langfuse/shared";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
-import { compileTemplateString, createW3CTraceId } from "../utils";
-import { env } from "../../env";
+import { createW3CTraceId } from "../utils";
import { JSONPath } from "jsonpath-plus";
import { UnrecoverableError } from "../../errors/UnrecoverableError";
import { ObservationNotFoundError } from "../../errors/ObservationNotFoundError";
-
-let s3StorageServiceClient: StorageService;
-
-// Cached schema for output schema validation (avoids recreating on every evaluate() call)
-const outputSchemaValidator = z.object({
- score: z.string(),
- reasoning: z.string(),
-});
-
-const getS3StorageServiceClient = (bucketName: string): StorageService => {
- if (!s3StorageServiceClient) {
- s3StorageServiceClient = StorageServiceFactory.getInstance({
- bucketName,
- accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
- secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
- endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
- region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
- forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
- awsSse: env.LANGFUSE_S3_EVENT_UPLOAD_SSE,
- awsSseKmsKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_SSE_KMS_KEY_ID,
- });
- }
- return s3StorageServiceClient;
-};
+import {
+ compileEvalPrompt,
+ buildEvalScoreSchema,
+ buildExecutionMetadata,
+ buildEvalMessages,
+ buildScoreEvent,
+ getEnvironmentFromVariables,
+ evalTemplateOutputSchema,
+ validateLLMResponse,
+} from "./evalExecutionUtils";
+import {
+ type EvalExecutionDeps,
+ createProductionEvalExecutionDeps,
+} from "./evalExecutionDeps";
+import { ExtractedVariable } from "./observationEval/extractObservationVariables";
/**
* Determines which eval jobs to create for a given event (traces or dataset run items).
@@ -190,7 +178,11 @@ export const createEvalJobs = async ({
.selectAll()
.where(sql.raw("job_type::text"), "=", "EVAL")
.where("project_id", "=", event.projectId)
- .where(sql.raw("status::text"), "=", "ACTIVE");
+ .where(sql.raw("status::text"), "=", "ACTIVE")
+ .where("target_object", "in", [
+ EvalTargetObject.TRACE,
+ EvalTargetObject.DATASET,
+ ]);
if ("configId" in event) {
// if configid is set in the event, we only want to fetch the one config
@@ -217,7 +209,7 @@ export const createEvalJobs = async ({
// Cache the fact that there are no job configurations for this project
// This helps avoid unnecessary database queries and queue processing
- await setNoJobConfigsCache(event.projectId);
+ await setNoEvalConfigsCache(event.projectId, "traceBased");
return;
}
@@ -296,7 +288,9 @@ export const createEvalJobs = async ({
// Note: We could parallelize this cache fetch with the getTraceById call above.
// This should increase throughput, but will also put more pressure on ClickHouse.
// Will keep it as-is for now, but that might be a useful change.
- const datasetConfigs = configs.filter((c) => c.target_object === "dataset");
+ const datasetConfigs = configs.filter(
+ (c) => c.target_object === EvalTargetObject.DATASET,
+ );
let cachedDatasetItemIds: { id: string; datasetId: string }[] | null = null;
if (datasetConfigs.length > 1) {
try {
@@ -354,7 +348,8 @@ export const createEvalJobs = async ({
// Use cached trace for in-memory filtering when possible, i.e. all fields can
// be checked in-memory.
- const traceFilter = config.target_object === "trace" ? validatedFilter : [];
+ const traceFilter =
+ config.target_object === EvalTargetObject.TRACE ? validatedFilter : [];
if (cachedTrace && !requiresDatabaseLookup(traceFilter)) {
// Evaluate filter in memory using the cached trace
traceExists = InMemoryFilterService.evaluateFilter(
@@ -421,14 +416,16 @@ export const createEvalJobs = async ({
exists: String(traceExists),
});
- const isDatasetConfig = config.target_object === "dataset";
+ const isDatasetConfig = config.target_object === EvalTargetObject.DATASET;
let datasetItem:
| { id: string }
| { id: string; observationId: string | null }
| undefined;
if (isDatasetConfig) {
const condition = tableColumnsToSqlFilterAndPrefix(
- config.target_object === "dataset" ? validatedFilter : [],
+ config.target_object === EvalTargetObject.DATASET
+ ? validatedFilter
+ : [],
evalDatasetFormFilterCols,
"dataset_items",
);
@@ -464,7 +461,9 @@ export const createEvalJobs = async ({
datasetItem = cachedDatasetItemIds.find((di) =>
InMemoryFilterService.evaluateFilter(
di,
- config.target_object === "dataset" ? validatedFilter : [],
+ config.target_object === EvalTargetObject.DATASET
+ ? validatedFilter
+ : [],
mapDatasetRunItemFilterColumn,
),
);
@@ -472,7 +471,10 @@ export const createEvalJobs = async ({
const datasetItemIds = await getDatasetItemIdsByTraceIdCh({
projectId: event.projectId,
traceId: event.traceId,
- filter: config.target_object === "dataset" ? validatedFilter : [],
+ filter:
+ config.target_object === EvalTargetObject.DATASET
+ ? validatedFilter
+ : [],
});
datasetItem = datasetItemIds.shift();
}
@@ -640,181 +642,121 @@ export const createEvalJobs = async ({
}
};
-// for a single eval job, this function is used to evaluate the job
-export const evaluate = async ({
- event,
+/**
+ * Core LLM-as-a-judge evaluation execution.
+ *
+ * This is the shared core logic used by both trace-level evals (via `evaluate()`)
+ * and observation-level evals (via observation eval processor).
+ *
+ * It handles:
+ * - Compiling the prompt with extracted variables
+ * - Calling the LLM with structured output
+ * - Persisting the score to S3 and queueing for ingestion
+ * - Updating job execution status
+ *
+ * Note: Callers are responsible for:
+ * - Fetching and validating job, config, and template
+ * - Checking if job is cancelled
+ * - Extracting variables from trace/observation data
+ *
+ * @param params.projectId - The project ID
+ * @param params.jobExecutionId - The job execution ID
+ * @param params.job - Pre-fetched job execution
+ * @param params.config - Pre-fetched job configuration
+ * @param params.template - Pre-fetched eval template
+ * @param params.extractedVariables - Pre-extracted variables from trace/observation data
+ * @param params.deps - Optional dependency injection for testing (defaults to production deps)
+ */
+export async function executeLLMAsJudgeEvaluation({
+ projectId,
+ jobExecutionId,
+ job,
+ config,
+ template,
+ extractedVariables,
+ environment,
+ deps = createProductionEvalExecutionDeps(),
}: {
- event: z.infer<typeof EvalExecutionEvent>;
-}) => {
- logger.debug(
- `Evaluating job ${event.jobExecutionId} for project ${event.projectId}`,
- );
- // first, fetch all the context required for the evaluation
- const job = await prisma.jobExecution.findFirst({
- where: {
- id: event.jobExecutionId,
- projectId: event.projectId,
- },
- });
-
- if (!job) {
- logger.info(
- `Job execution with id ${event.jobExecutionId} for project ${event.projectId} not found. This was likely deleted by the user.`,
- );
- return;
- }
-
- if (job.status === "CANCELLED" || !job?.jobInputTraceId) {
- logger.debug(`Job ${job.id} for project ${event.projectId} was cancelled.`);
-
- await prisma.jobExecution.delete({
- where: {
- id: job.id,
- projectId: event.projectId,
- },
- });
-
- return;
- }
-
- const config = await prisma.jobConfiguration.findFirst({
- where: {
- id: job.jobConfigurationId,
- projectId: event.projectId,
- },
- });
-
- if (!config || !config.evalTemplateId) {
- logger.error(
- `Evaluation template not found for config: ${config?.evalTemplateId}`,
- );
- throw new UnrecoverableError(
- `Evaluation template not found for config: ${config?.evalTemplateId}`,
- );
- }
-
- const template = await prisma.evalTemplate.findFirstOrThrow({
- where: {
- id: config.evalTemplateId,
- OR: [{ projectId: event.projectId }, { projectId: null }],
- },
- });
-
+ projectId: string;
+ jobExecutionId: string;
+ job: JobExecution;
+ config: JobConfiguration;
+ template: EvalTemplate;
+ extractedVariables: ExtractedVariable[];
+ environment: string;
+ deps?: EvalExecutionDeps;
+}): Promise<void> {
logger.debug(
- `Evaluating job ${job.id} for project ${event.projectId} with template ${template.id}. Searching for context...`,
- );
-
- // selectedcolumnid is not safe to use, needs validation in extractVariablesFromTrace()
- const parsedVariableMapping = variableMappingList.parse(
- config.variableMapping,
+ `Executing LLM-as-judge evaluation for job ${jobExecutionId} in project ${projectId}`,
);
- // extract the variables which need to be inserted into the prompt
- const mappingResult = await extractVariablesFromTracingData({
- projectId: event.projectId,
- variables: template.vars,
- traceId: job.jobInputTraceId,
- traceTimestamp: job.jobInputTraceTimestamp ?? undefined,
- datasetItemId: job.jobInputDatasetItemId ?? undefined,
- variableMapping: parsedVariableMapping,
- });
-
- if (logger.isLevelEnabled("debug")) {
- logger.debug(
- `Evaluating job ${event.jobExecutionId} extracted variables ${JSON.stringify(mappingResult)} `,
- );
- }
-
- // Get environment from trace or observation variables
- const environment = mappingResult.find((r) => r.environment)?.environment;
-
- // compile the prompt and send out the LLM request
- let prompt;
+ // Compile the prompt with extracted variables
+ let prompt: string;
try {
- prompt = compileTemplateString(template.prompt, {
- ...Object.fromEntries(
- mappingResult.map(({ var: key, value }) => [key, value]),
- ),
+ prompt = compileEvalPrompt({
+ templatePrompt: template.prompt,
+ variables: extractedVariables,
});
} catch (e) {
- // in case of a compilation error, we use the original prompt without adding variables.
logger.error(
- `Evaluating job ${event.jobExecutionId} failed to compile prompt. Eval will fail. ${e}`,
+ `Failed to compile prompt for job ${jobExecutionId}. Eval will fail. ${e}`,
);
prompt = template.prompt;
}
logger.debug(
- `Evaluating job ${event.jobExecutionId} compiled prompt ${prompt}`,
+ `Compiled prompt for job ${jobExecutionId}: ${prompt.slice(0, 200)}...`,
);
- const parsedOutputSchema = outputSchemaValidator.parse(template.outputSchema);
+ // Parse and validate output schema
+ const parsedOutputSchema = evalTemplateOutputSchema.safeParse(
+ template.outputSchema,
+ );
- if (!parsedOutputSchema) {
+ if (!parsedOutputSchema.success) {
throw new UnrecoverableError(
- "Output schema not found in evaluation template",
+ "Output schema not found or invalid in evaluation template",
);
}
- const evalScoreSchema = zodV3.object({
- reasoning: zodV3.string().describe(parsedOutputSchema.reasoning),
- score: zodV3.number().describe(parsedOutputSchema.score),
- });
+ const evalScoreSchema = buildEvalScoreSchema(parsedOutputSchema.data);
- const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(
- event.projectId,
- template.provider ?? undefined,
- template.model ?? undefined,
- template.modelParams as Record<string, unknown> | null,
- );
+ // Get model configuration
+ const modelConfig = await deps.fetchModelConfig({
+ projectId,
+ provider: template.provider ?? undefined,
+ model: template.model ?? undefined,
+ modelParams: template.modelParams as Record<string, unknown> | null,
+ });
if (!modelConfig.valid) {
- logger.warn(
- `Evaluating job ${event.jobExecutionId} will fail. ${modelConfig.error}`,
- );
+ logger.warn(`Eval job ${jobExecutionId} will fail. ${modelConfig.error}`);
throw new UnrecoverableError(
- `Invalid model configuration for job ${event.jobExecutionId}: ${modelConfig.error}`,
+ `Invalid model configuration for job ${jobExecutionId}: ${modelConfig.error}`,
);
}
- const messages = [
- {
- type: ChatMessageType.User,
- role: ChatMessageRole.User,
- content: prompt,
- } as const,
- ];
+ // Prepare LLM call
+ const messages = buildEvalMessages(prompt);
- // persist the score and update the job status
const scoreId = randomUUID();
+ const executionTraceId = createW3CTraceId(jobExecutionId);
+
+ const executionMetadata = buildExecutionMetadata({
+ jobExecutionId,
+ jobConfigurationId: job.jobConfigurationId,
+ targetTraceId: job.jobInputTraceId,
+ targetObservationId: job.jobInputObservationId,
+ targetDatasetItemId: job.jobInputDatasetItemId,
+ });
- // 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,
+ // Call LLM
+ const llmOutput = await deps.callLLM({
messages,
- modelParams: {
- provider: modelConfig.config.provider,
- model: modelConfig.config.model,
- adapter: modelConfig.config.apiKey.adapter,
- ...modelConfig.config.modelParams,
- },
+ modelConfig: modelConfig.config,
structuredOutputSchema: evalScoreSchema,
- maxRetries: 1,
traceSinkParams: {
- targetProjectId: event.projectId,
+ targetProjectId: projectId,
traceId: executionTraceId,
traceName: `Execute evaluator: ${template.name}`,
environment: LangfuseInternalTraceEnvironment.LLMJudge,
@@ -825,100 +767,172 @@ export const evaluate = async ({
},
});
- const parsedLLMOutput = evalScoreSchema.safeParse(llmOutput);
+ const parsedLLMOutput = validateLLMResponse({
+ response: llmOutput,
+ schema: evalScoreSchema,
+ });
+
if (!parsedLLMOutput.success) {
throw new UnrecoverableError(
- `Invalid LLM response format from model ${modelConfig.config.model}. Response: ${llmOutput}`,
+ `Invalid LLM response format from model ${modelConfig.config.model}. Error: ${parsedLLMOutput.error}`,
);
}
- if (logger.isLevelEnabled("debug")) {
- logger.debug(
- `Evaluating job ${event.jobExecutionId} Parsed LLM output ${JSON.stringify(parsedLLMOutput)}`,
- );
- }
+ logger.debug(
+ `Job ${jobExecutionId} received LLM output: score=${parsedLLMOutput.data.score}`,
+ );
- const baseScore = {
- id: scoreId,
+ // Build and persist score
+ const eventId = randomUUID();
+ const scoreEvent = buildScoreEvent({
+ eventId,
+ scoreId,
traceId: job.jobInputTraceId,
observationId: job.jobInputObservationId,
- name: config.scoreName,
+ scoreName: config.scoreName,
value: parsedLLMOutput.data.score,
- comment: parsedLLMOutput.data.reasoning,
- source: ScoreSourceEnum.EVAL,
- environment: environment ?? "default",
- executionTraceId: executionTraceId,
+ reasoning: parsedLLMOutput.data.reasoning,
+ environment,
+ executionTraceId,
metadata: executionMetadata,
- };
+ });
- // Write score to S3 and ingest into queue for Clickhouse processing
+ // Write score to S3 and enqueue for ingestion
try {
- const eventId = randomUUID();
- const bucketPath = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${event.projectId}/score/${scoreId}/${eventId}.json`;
- await getS3StorageServiceClient(
- env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
- ).uploadJson(bucketPath, [
- {
- id: eventId,
- timestamp: new Date().toISOString(),
- type: eventTypes.SCORE_CREATE,
- body: {
- ...baseScore,
- dataType: "NUMERIC",
- },
- },
- ]);
+ await deps.uploadScore({
+ projectId,
+ scoreId,
+ eventId,
+ event: scoreEvent,
+ });
- const shardingKey = `${event.projectId}-${scoreId}`;
- const queue = IngestionQueue.getInstance({ shardingKey });
- if (!queue) {
- throw new Error("Ingestion queue not available");
- }
- await queue.add(QueueJobs.IngestionJob, {
- id: randomUUID(),
- timestamp: new Date(),
- name: QueueJobs.IngestionJob as const,
- payload: {
- data: {
- type: eventTypes.SCORE_CREATE,
- eventBodyId: scoreId,
- fileKey: eventId,
- },
- authCheck: {
- validKey: true,
- scope: {
- projectId: event.projectId,
- },
- },
- },
+ await deps.enqueueScoreIngestion({
+ projectId,
+ scoreId,
+ eventId,
});
} catch (e) {
- logger.error(`Failed to add score into IngestionQueue: ${e}`, e);
+ logger.error(`Failed to persist score: ${e}`, e);
traceException(e);
-
throw new Error(`Failed to write score ${scoreId} into IngestionQueue`);
}
+ logger.debug(`Persisted score ${scoreId} for job ${jobExecutionId}`);
+
+ // Update job execution status
+ await deps.updateJobExecution({
+ id: jobExecutionId,
+ projectId,
+ data: {
+ status: JobExecutionStatus.COMPLETED,
+ endTime: new Date(),
+ jobOutputScoreId: scoreId,
+ executionTraceId,
+ },
+ });
+
+ logger.debug(
+ `Eval job ${job.id} completed with score ${parsedLLMOutput.data.score}`,
+ );
+}
+
+/**
+ * Evaluates a trace-level job by extracting variables from tracing data
+ * and calling the shared LLM-as-a-judge execution.
+ */
+export const evaluate = async ({
+ event,
+}: {
+ event: z.infer<typeof EvalExecutionEvent>;
+}) => {
logger.debug(
- `Evaluating job ${event.jobExecutionId} persisted score ${scoreId} for trace ${job.jobInputTraceId}`,
+ `Evaluating trace-level job ${event.jobExecutionId} for project ${event.projectId}`,
);
- await prisma.jobExecution.update({
+ // Fetch job to get trace info for variable extraction
+ const job = await prisma.jobExecution.findFirst({
where: {
id: event.jobExecutionId,
projectId: event.projectId,
},
- data: {
- status: JobExecutionStatus.COMPLETED,
- endTime: new Date(),
- jobOutputScoreId: scoreId,
- executionTraceId,
+ });
+
+ if (!job) {
+ logger.info(
+ `Job execution ${event.jobExecutionId} not found. It may have been deleted.`,
+ );
+ return;
+ }
+
+ if (job.status === "CANCELLED" || !job.jobInputTraceId) {
+ logger.debug(`Job ${job.id} was cancelled or has no trace input.`);
+ await prisma.jobExecution.delete({
+ where: {
+ id: job.id,
+ projectId: event.projectId,
+ },
+ });
+ return;
+ }
+
+ // Fetch config to get variable mapping
+ const config = await prisma.jobConfiguration.findFirst({
+ where: {
+ id: job.jobConfigurationId,
+ projectId: event.projectId,
+ },
+ });
+
+ if (!config || !config.evalTemplateId) {
+ throw new UnrecoverableError(
+ `Job configuration or template not found for job ${job.id}`,
+ );
+ }
+
+ // Fetch template to get variable names
+ const template = await prisma.evalTemplate.findFirst({
+ where: {
+ id: config.evalTemplateId,
+ OR: [{ projectId: event.projectId }, { projectId: null }],
},
});
+ if (!template) {
+ throw new UnrecoverableError(
+ `Evaluation template ${config.evalTemplateId} not found`,
+ );
+ }
+
+ // Extract variables from tracing data
+ const parsedVariableMapping = variableMappingList.parse(
+ config.variableMapping,
+ );
+
+ const extractedVariables = await extractVariablesFromTracingData({
+ projectId: event.projectId,
+ variables: template.vars,
+ traceId: job.jobInputTraceId,
+ traceTimestamp: job.jobInputTraceTimestamp ?? undefined,
+ datasetItemId: job.jobInputDatasetItemId ?? undefined,
+ variableMapping: parsedVariableMapping,
+ });
+
logger.debug(
- `Eval job ${job.id} for project ${event.projectId} completed with score ${parsedLLMOutput.data.score}`,
+ `Extracted ${extractedVariables.length} variables for job ${event.jobExecutionId}`,
);
+
+ // Execute the shared LLM-as-a-judge evaluation
+ await executeLLMAsJudgeEvaluation({
+ projectId: event.projectId,
+ jobExecutionId: event.jobExecutionId,
+ job,
+ config,
+ template,
+ extractedVariables,
+ environment:
+ getEnvironmentFromVariables(extractedVariables) ??
+ DEFAULT_TRACE_ENVIRONMENT,
+ });
};
export async function extractVariablesFromTracingData({
diff --git a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts
new file mode 100644
index 0000000000..c61ae1404d
--- /dev/null
+++ b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts
@@ -0,0 +1,772 @@
+import { describe, expect, it, vi, type Mock } from "vitest";
+import { JobExecutionStatus } from "@prisma/client";
+import { executeLLMAsJudgeEvaluation } from "./evalService";
+import { createMockEvalExecutionDeps } from "./evalExecutionDeps";
+import { UnrecoverableError } from "../../errors/UnrecoverableError";
+import { ExtractedVariable } from "./observationEval/extractObservationVariables";
+import { EvalTargetObject } from "@langfuse/shared";
+
+/**
+ * Unit tests for executeLLMAsJudgeEvaluation with mocked dependencies.
+ *
+ * These tests verify the orchestration logic without hitting real databases,
+ * LLMs, or external services. Each test creates mock deps with specific
+ * overrides to test different scenarios.
+ *
+ * Note: Job fetching, config fetching, template fetching, and cancelled job
+ * handling are now the responsibility of callers (evaluate() and
+ * processObservationEval()), not this function. Tests for those scenarios
+ * have been removed.
+ */
+describe("executeLLMAsJudgeEvaluation", () => {
+ const projectId = "test-project-123";
+ const jobExecutionId = "test-job-execution-456";
+
+ // ============================================================================
+ // Test Fixtures
+ // ============================================================================
+
+ const mockJobExecution = {
+ id: jobExecutionId,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ startTime: new Date(),
+ endTime: null,
+ jobConfigurationId: "config-789",
+ jobInputTraceId: "trace-abc",
+ jobInputTraceTimestamp: new Date(),
+ jobInputObservationId: null,
+ jobInputDatasetItemId: null,
+ jobTemplateId: "template-xyz",
+ error: null,
+ jobOutputScoreId: null,
+ executionTraceId: null,
+ };
+
+ const mockJobConfiguration = {
+ id: "config-789",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId,
+ jobType: "EVAL" as const,
+ evalTemplateId: "template-xyz",
+ scoreName: "accuracy",
+ targetObject: EvalTargetObject.TRACE,
+ filter: [],
+ variableMapping: [],
+ sampling: "1.0",
+ delay: 0,
+ status: "ACTIVE" as const,
+ timeScope: ["NEW" as const],
+ };
+
+ const mockEvalTemplate = {
+ id: "template-xyz",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ name: "Accuracy Evaluator",
+ version: 1,
+ prompt: "Evaluate accuracy of {{output}}",
+ model: "gpt-4",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: {
+ score: "A number between 0 and 1",
+ reasoning: "Explain your reasoning",
+ },
+ vars: ["output"],
+ projectId,
+ };
+
+ const extractedVariables: ExtractedVariable[] = [
+ {
+ var: "output",
+ value: "The model response text",
+ environment: "production",
+ },
+ ];
+
+ // ============================================================================
+ // Mock Helpers
+ // ============================================================================
+
+ /** Default valid model configuration for OpenAI GPT-4 */
+ const defaultModelConfig = {
+ provider: "openai",
+ model: "gpt-4",
+ apiKey: { adapter: "openai", secretKey: "test-key" },
+ modelParams: {},
+ };
+
+ /** Creates a mock for fetchModelConfig that returns a valid config */
+ const mockValidFetchModelConfig = () =>
+ vi.fn().mockResolvedValue({
+ valid: true,
+ config: defaultModelConfig,
+ });
+
+ /** Creates a mock for callLLM with a successful response */
+ const mockSuccessfulLLMCall = (score: number, reasoning: string) =>
+ vi.fn().mockResolvedValue({ score, reasoning });
+
+ /** Creates standard deps with all mocks for a successful execution flow */
+ const createSuccessfulDeps = (
+ overrides: {
+ callLLM?: Mock;
+ uploadScore?: Mock;
+ enqueueScoreIngestion?: Mock;
+ updateJobExecution?: Mock;
+ } = {},
+ ) =>
+ createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: overrides.callLLM ?? mockSuccessfulLLMCall(0.8, "Good"),
+ uploadScore: overrides.uploadScore ?? vi.fn(),
+ enqueueScoreIngestion: overrides.enqueueScoreIngestion ?? vi.fn(),
+ updateJobExecution: overrides.updateJobExecution ?? vi.fn(),
+ });
+
+ /** Standard execution params for most tests */
+ const createExecutionParams = (
+ overrides: {
+ job?: typeof mockJobExecution;
+ template?: typeof mockEvalTemplate;
+ variables?: ExtractedVariable[];
+ environment?: string;
+ deps?: ReturnType<typeof createMockEvalExecutionDeps>;
+ } = {},
+ ) => ({
+ projectId,
+ jobExecutionId,
+ job: overrides.job ?? mockJobExecution,
+ config: mockJobConfiguration,
+ template: overrides.template ?? mockEvalTemplate,
+ extractedVariables: overrides.variables ?? extractedVariables,
+ environment: overrides.environment ?? "production",
+ deps: overrides.deps ?? createSuccessfulDeps(),
+ });
+
+ describe("successful execution", () => {
+ it("should complete evaluation successfully", async () => {
+ const callLLM = mockSuccessfulLLMCall(0.85, "High accuracy observed");
+ const uploadScore = vi.fn();
+ const enqueueScoreIngestion = vi.fn();
+ const updateJobExecution = vi.fn();
+
+ const deps = createSuccessfulDeps({
+ callLLM,
+ uploadScore,
+ enqueueScoreIngestion,
+ updateJobExecution,
+ });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ expect(callLLM).toHaveBeenCalledTimes(1);
+ expect(uploadScore).toHaveBeenCalledTimes(1);
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId,
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ name: "accuracy",
+ value: 0.85,
+ comment: "High accuracy observed",
+ }),
+ }),
+ }),
+ );
+ expect(enqueueScoreIngestion).toHaveBeenCalledTimes(1);
+ expect(updateJobExecution).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: jobExecutionId,
+ projectId,
+ data: expect.objectContaining({
+ status: JobExecutionStatus.COMPLETED,
+ endTime: expect.any(Date),
+ jobOutputScoreId: expect.any(String),
+ executionTraceId: expect.any(String),
+ }),
+ }),
+ );
+ });
+
+ it("should include observation ID in score when present", async () => {
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.9, "Excellent"),
+ uploadScore,
+ });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ job: { ...mockJobExecution, jobInputObservationId: "obs-123" },
+ deps,
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ observationId: "obs-123",
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should use provided environment", async () => {
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({ uploadScore });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ variables: [{ var: "output", value: "test" }],
+ environment: "staging",
+ deps,
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ environment: "staging",
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should use 'default' environment when explicitly passed", async () => {
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.5, "Average"),
+ uploadScore,
+ });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ variables: [{ var: "output", value: "test" }],
+ environment: "default",
+ deps,
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ environment: "default",
+ }),
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("configuration errors", () => {
+ it("should throw UnrecoverableError if model config invalid", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue({
+ valid: false,
+ error: "No API key configured",
+ }),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+
+ it("should throw UnrecoverableError if output schema invalid", async () => {
+ const templateWithBadSchema = {
+ ...mockEvalTemplate,
+ outputSchema: { invalidKey: "value" },
+ };
+
+ await expect(
+ executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ template: templateWithBadSchema,
+ deps: createMockEvalExecutionDeps({}),
+ }),
+ ),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+ });
+
+ describe("LLM response errors", () => {
+ it("should throw UnrecoverableError for invalid LLM response", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: vi.fn().mockResolvedValue({
+ score: "high", // Invalid - should be number
+ reasoning: "Good response",
+ }),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+
+ it("should throw UnrecoverableError for missing LLM response fields", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: vi.fn().mockResolvedValue({
+ score: 0.8,
+ // Missing reasoning field
+ }),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+ });
+
+ describe("score persistence errors", () => {
+ it("should throw error if score upload fails", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: mockSuccessfulLLMCall(0.8, "Good"),
+ uploadScore: vi.fn().mockRejectedValue(new Error("S3 upload failed")),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow("Failed to write score");
+ });
+
+ it("should throw error if score ingestion queue fails", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: mockSuccessfulLLMCall(0.8, "Good"),
+ uploadScore: vi.fn(),
+ enqueueScoreIngestion: vi
+ .fn()
+ .mockRejectedValue(new Error("Queue unavailable")),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow("Failed to write score");
+ });
+ });
+
+ describe("prompt compilation", () => {
+ it("should handle prompt compilation errors gracefully", async () => {
+ const templateWithBadPrompt = {
+ ...mockEvalTemplate,
+ prompt: "Evaluate {{unclosed_bracket",
+ };
+
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.5, "Could not parse properly"),
+ uploadScore,
+ });
+
+ // Should not throw - falls back to raw template
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({ template: templateWithBadPrompt, deps }),
+ );
+
+ expect(uploadScore).toHaveBeenCalled();
+ });
+
+ it("should compile multiple variables into prompt", async () => {
+ const multiVarTemplate = {
+ ...mockEvalTemplate,
+ prompt: "Compare input: {{input}} with output: {{output}}",
+ vars: ["input", "output"],
+ };
+
+ const multiVariables: ExtractedVariable[] = [
+ { var: "input", value: "What is 2+2?" },
+ { var: "output", value: "The answer is 4" },
+ ];
+
+ const callLLM = mockSuccessfulLLMCall(1.0, "Perfect match");
+ const deps = createSuccessfulDeps({ callLLM });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ template: multiVarTemplate,
+ variables: multiVariables,
+ deps,
+ }),
+ );
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: expect.arrayContaining([
+ expect.objectContaining({
+ content:
+ "Compare input: What is 2+2? with output: The answer is 4",
+ }),
+ ]),
+ }),
+ );
+ });
+ });
+
+ describe("LLM call parameters", () => {
+ it("should pass correct traceSinkParams to LLM for observability", async () => {
+ const callLLM = mockSuccessfulLLMCall(0.8, "Good response");
+ const deps = createSuccessfulDeps({ callLLM });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSinkParams: expect.objectContaining({
+ targetProjectId: projectId,
+ traceId: expect.any(String),
+ traceName: `Execute evaluator: ${mockEvalTemplate.name}`,
+ environment: "langfuse-llm-as-a-judge",
+ metadata: expect.objectContaining({
+ job_execution_id: jobExecutionId,
+ job_configuration_id: mockJobExecution.jobConfigurationId,
+ target_trace_id: mockJobExecution.jobInputTraceId,
+ score_id: expect.any(String),
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should pass structured output schema to LLM", async () => {
+ const callLLM = mockSuccessfulLLMCall(0.8, "Good response");
+ const deps = createSuccessfulDeps({ callLLM });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ structuredOutputSchema: expect.objectContaining({
+ shape: expect.objectContaining({
+ reasoning: expect.any(Object),
+ score: expect.any(Object),
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should pass model config to LLM", async () => {
+ const customModelConfig = {
+ provider: "anthropic",
+ model: "claude-3-opus",
+ apiKey: { adapter: "anthropic", secretKey: "anthropic-key" },
+ modelParams: { temperature: 0.5 },
+ };
+
+ const callLLM = mockSuccessfulLLMCall(0.9, "Excellent");
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue({
+ valid: true,
+ config: customModelConfig,
+ }),
+ callLLM,
+ uploadScore: vi.fn(),
+ enqueueScoreIngestion: vi.fn(),
+ updateJobExecution: vi.fn(),
+ });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ modelConfig: customModelConfig,
+ }),
+ );
+ });
+ });
+
+ describe("execution metadata", () => {
+ it("should include dataset item ID in metadata when present", async () => {
+ const callLLM = mockSuccessfulLLMCall(
+ 0.75,
+ "Dataset evaluation complete",
+ );
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({ callLLM, uploadScore });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ job: {
+ ...mockJobExecution,
+ jobInputDatasetItemId: "dataset-item-123",
+ },
+ deps,
+ }),
+ );
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSinkParams: expect.objectContaining({
+ metadata: expect.objectContaining({
+ target_dataset_item_id: "dataset-item-123",
+ }),
+ }),
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ target_dataset_item_id: "dataset-item-123",
+ }),
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should include observation ID in metadata when present", async () => {
+ const callLLM = mockSuccessfulLLMCall(
+ 0.85,
+ "Observation evaluation complete",
+ );
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({ callLLM, uploadScore });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({
+ job: { ...mockJobExecution, jobInputObservationId: "obs-456" },
+ deps,
+ }),
+ );
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSinkParams: expect.objectContaining({
+ metadata: expect.objectContaining({
+ target_observation_id: "obs-456",
+ }),
+ }),
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ target_observation_id: "obs-456",
+ }),
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("should include all job identifiers in full evaluation context", async () => {
+ const fullJob = {
+ ...mockJobExecution,
+ jobInputObservationId: "obs-full",
+ jobInputDatasetItemId: "dataset-full",
+ };
+
+ const callLLM = mockSuccessfulLLMCall(0.95, "Complete evaluation");
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({ callLLM, uploadScore });
+
+ await executeLLMAsJudgeEvaluation(
+ createExecutionParams({ job: fullJob, deps }),
+ );
+
+ const expectedMetadata = {
+ job_execution_id: jobExecutionId,
+ job_configuration_id: fullJob.jobConfigurationId,
+ target_trace_id: fullJob.jobInputTraceId,
+ target_observation_id: "obs-full",
+ target_dataset_item_id: "dataset-full",
+ };
+
+ expect(callLLM).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSinkParams: expect.objectContaining({
+ metadata: expect.objectContaining(expectedMetadata),
+ }),
+ }),
+ );
+
+ expect(uploadScore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: expect.objectContaining({
+ body: expect.objectContaining({
+ metadata: expect.objectContaining(expectedMetadata),
+ }),
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("score event structure", () => {
+ it("should build complete score event with all required fields", async () => {
+ const uploadScore = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.88, "Well structured response"),
+ uploadScore,
+ });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ expect(uploadScore).toHaveBeenCalledWith({
+ projectId,
+ scoreId: expect.any(String),
+ eventId: expect.any(String),
+ event: {
+ id: expect.any(String),
+ timestamp: expect.any(String),
+ type: "score-create",
+ body: {
+ id: expect.any(String),
+ traceId: mockJobExecution.jobInputTraceId,
+ observationId: null,
+ name: mockJobConfiguration.scoreName,
+ value: 0.88,
+ comment: "Well structured response",
+ source: "EVAL",
+ environment: "production",
+ executionTraceId: expect.any(String),
+ metadata: expect.objectContaining({
+ job_execution_id: jobExecutionId,
+ job_configuration_id: mockJobExecution.jobConfigurationId,
+ target_trace_id: mockJobExecution.jobInputTraceId,
+ }),
+ dataType: "NUMERIC",
+ },
+ },
+ });
+ });
+
+ it("should use same scoreId in uploadScore and updateJobExecution", async () => {
+ const uploadScore = vi.fn();
+ const updateJobExecution = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.7, "Consistent IDs"),
+ uploadScore,
+ updateJobExecution,
+ });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ const uploadCall = uploadScore.mock.calls[0][0];
+ const scoreId = uploadCall.scoreId;
+
+ expect(updateJobExecution).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ jobOutputScoreId: scoreId,
+ }),
+ }),
+ );
+ });
+
+ it("should use same executionTraceId in score event and job update", async () => {
+ const uploadScore = vi.fn();
+ const updateJobExecution = vi.fn();
+ const deps = createSuccessfulDeps({
+ callLLM: mockSuccessfulLLMCall(0.6, "Trace ID consistency"),
+ uploadScore,
+ updateJobExecution,
+ });
+
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+
+ const uploadCall = uploadScore.mock.calls[0][0];
+ const executionTraceId = uploadCall.event.body.executionTraceId;
+
+ expect(updateJobExecution).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ executionTraceId,
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("LLM errors", () => {
+ it("should propagate LLM exception for BullMQ retry", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: vi
+ .fn()
+ .mockRejectedValue(new Error("LLM service unavailable")),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow("LLM service unavailable");
+ });
+
+ it("should propagate rate limit errors from LLM", async () => {
+ const rateLimitError = new Error("Rate limit exceeded");
+ (rateLimitError as unknown as { isRetryable: boolean }).isRetryable =
+ true;
+
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: vi.fn().mockRejectedValue(rateLimitError),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow("Rate limit exceeded");
+ });
+ });
+
+ describe("job execution update errors", () => {
+ it("should propagate updateJobExecution errors", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: mockSuccessfulLLMCall(0.8, "Good"),
+ uploadScore: vi.fn(),
+ enqueueScoreIngestion: vi.fn(),
+ updateJobExecution: vi
+ .fn()
+ .mockRejectedValue(new Error("Database connection lost")),
+ });
+
+ await expect(
+ executeLLMAsJudgeEvaluation(createExecutionParams({ deps })),
+ ).rejects.toThrow("Database connection lost");
+ });
+
+ it("should have persisted score before job update fails", async () => {
+ const uploadScore = vi.fn();
+ const enqueueScoreIngestion = vi.fn();
+
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: mockValidFetchModelConfig(),
+ callLLM: mockSuccessfulLLMCall(0.8, "Good"),
+ uploadScore,
+ enqueueScoreIngestion,
+ updateJobExecution: vi
+ .fn()
+ .mockRejectedValue(new Error("Database connection lost")),
+ });
+
+ try {
+ await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));
+ } catch {
+ // Expected to throw
+ }
+
+ // Score should have been persisted before the job update error
+ expect(uploadScore).toHaveBeenCalledTimes(1);
+ expect(enqueueScoreIngestion).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
new file mode 100644
index 0000000000..16c30f5bcf
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
@@ -0,0 +1,443 @@
+import { describe, it, expect } from "vitest";
+import { extractObservationVariables } from "../extractObservationVariables";
+import { type ObservationForEval } from "../types";
+import { type ObservationVariableMapping } from "@langfuse/shared";
+
+describe("extractObservationVariables", () => {
+ const mockObservation: ObservationForEval = {
+ // Core identifiers
+ id: "obs-123",
+ traceId: "trace-456",
+ projectId: "project-789",
+ parentObservationId: null,
+
+ // Observation properties
+ type: "generation",
+ name: "chat-completion",
+ environment: "production",
+ level: "DEFAULT",
+ statusMessage: null,
+ version: "v1.0",
+
+ // Trace-level properties
+ traceName: "my-trace",
+ userId: "user-abc",
+ sessionId: "session-xyz",
+ tags: ["tag1", "tag2"],
+ release: "v2.0.0",
+
+ // Model properties
+ model: "gpt-4",
+ modelParameters: '{"temperature": 0.7}',
+
+ // Prompt properties
+ promptId: null,
+ promptName: null,
+ promptVersion: null,
+
+ // Tool call properties
+ toolDefinitions: { search: '{"description": "Search the web"}' },
+ toolCalls: ['{"name": "search", "args": {"query": "test"}}'],
+ toolCallNames: ["search"],
+
+ // Usage & Cost
+ usageDetails: { input: 100, output: 50 },
+ costDetails: {},
+ providedUsageDetails: {},
+ providedCostDetails: {},
+
+ // Experiment properties
+ experimentId: null,
+ experimentName: null,
+ experimentDescription: null,
+ experimentDatasetId: null,
+ experimentItemId: null,
+ experimentItemExpectedOutput: "expected response",
+
+ // Data fields
+ input: JSON.stringify({
+ prompt: "Hello, how are you?",
+ context: "greeting",
+ }),
+ output: JSON.stringify({
+ response: "I am fine, thank you!",
+ sentiment: "positive",
+ }),
+ metadata: { userId: "user-123", customField: "custom-value" },
+ };
+
+ describe("basic variable extraction", () => {
+ it("should extract input variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "input", selectedColumnId: "input" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("input");
+ expect(result[0].value).toBe(mockObservation.input);
+ });
+
+ it("should extract output variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("output");
+ expect(result[0].value).toBe(mockObservation.output);
+ });
+
+ it("should extract metadata variable as JSON string", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "meta", selectedColumnId: "metadata" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("meta");
+ expect(result[0].value).toBe(JSON.stringify(mockObservation.metadata));
+ });
+
+ it("should extract multiple variables", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "userInput", selectedColumnId: "input" },
+ { templateVariable: "modelOutput", selectedColumnId: "output" },
+ { templateVariable: "metadata", selectedColumnId: "metadata" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(3);
+ expect(result[0].var).toBe("userInput");
+ expect(result[0].value).toBe(mockObservation.input);
+ expect(result[1].var).toBe("modelOutput");
+ expect(result[1].value).toBe(mockObservation.output);
+ expect(result[2].var).toBe("metadata");
+ });
+ });
+
+ describe("tool call extraction", () => {
+ it("should extract toolCalls variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "tools", selectedColumnId: "toolCalls" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("tools");
+ expect(result[0].value).toBe(JSON.stringify(mockObservation.toolCalls));
+ });
+
+ it("should extract toolDefinitions variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "definitions",
+ selectedColumnId: "toolDefinitions",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("definitions");
+ expect(result[0].value).toBe(
+ JSON.stringify(mockObservation.toolDefinitions),
+ );
+ });
+ });
+
+ describe("model extraction", () => {
+ it("should extract model variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "modelName", selectedColumnId: "model" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("modelName");
+ expect(result[0].value).toBe("gpt-4");
+ });
+
+ it("should extract modelParameters variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "params", selectedColumnId: "modelParameters" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("params");
+ expect(result[0].value).toBe(mockObservation.modelParameters);
+ });
+ });
+
+ describe("experiment extraction", () => {
+ it("should extract experimentItemExpectedOutput variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "expected",
+ selectedColumnId: "experimentItemExpectedOutput",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("expected");
+ expect(result[0].value).toBe("expected response");
+ });
+ });
+
+ describe("usage extraction", () => {
+ it("should extract usageDetails variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "usage", selectedColumnId: "usageDetails" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("usage");
+ expect(result[0].value).toBe(
+ JSON.stringify(mockObservation.usageDetails),
+ );
+ });
+
+ it("should extract costDetails variable", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "cost", selectedColumnId: "costDetails" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("cost");
+ expect(result[0].value).toBe(JSON.stringify(mockObservation.costDetails));
+ });
+ });
+
+ describe("JSON selector extraction", () => {
+ it("should apply JSON selector to extract nested field from input", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "prompt",
+ selectedColumnId: "input",
+ jsonSelector: "$.prompt",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ // JSONPath returns an array, which gets JSON-stringified
+ expect(result[0].value).toBe(JSON.stringify(["Hello, how are you?"]));
+ });
+
+ it("should apply JSON selector to extract nested field from output", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "response",
+ selectedColumnId: "output",
+ jsonSelector: "$.response",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(JSON.stringify(["I am fine, thank you!"]));
+ });
+
+ it("should handle null jsonSelector by returning full value", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "input",
+ selectedColumnId: "input",
+ jsonSelector: null,
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(mockObservation.input);
+ });
+
+ it("should handle undefined jsonSelector by returning full value", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "input",
+ selectedColumnId: "input",
+ jsonSelector: undefined,
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(mockObservation.input);
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle empty variable mapping", () => {
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping: [],
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it("should handle null/undefined column values as empty strings", () => {
+ const observationWithNulls: ObservationForEval = {
+ ...mockObservation,
+ input: null as unknown as string,
+ output: undefined as unknown as string,
+ };
+
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "input", selectedColumnId: "input" },
+ { templateVariable: "output", selectedColumnId: "output" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: observationWithNulls,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe("");
+ expect(result[1].value).toBe("");
+ });
+
+ it("should handle invalid JSON selector gracefully", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "field",
+ selectedColumnId: "input",
+ jsonSelector: "$.nonexistent.deeply.nested",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ // JSONPath returns empty array for non-matching paths
+ expect(result[0].value).toBe("[]");
+ });
+
+ it("should handle non-JSON string column with JSON selector", () => {
+ const observationWithPlainText: ObservationForEval = {
+ ...mockObservation,
+ input: "plain text, not JSON",
+ };
+
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "input",
+ selectedColumnId: "input",
+ jsonSelector: "$.field",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: observationWithPlainText,
+ variableMapping,
+ });
+
+ // Should fall back to original value when JSON parsing fails
+ expect(result[0].value).toBe("plain text, not JSON");
+ });
+ });
+
+ describe("column ID mapping", () => {
+ it("should map 'input' to observation input field", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "var", selectedColumnId: "input" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(mockObservation.input);
+ });
+
+ it("should map 'output' to observation output field", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "var", selectedColumnId: "output" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(mockObservation.output);
+ });
+
+ it("should map 'metadata' to observation metadata field as JSON string", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ { templateVariable: "var", selectedColumnId: "metadata" },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result[0].value).toBe(JSON.stringify(mockObservation.metadata));
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts b/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts
new file mode 100644
index 0000000000..f8977862c7
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts
@@ -0,0 +1,981 @@
+import { describe, it, expect, vi } from "vitest";
+import { type Prisma } from "@langfuse/shared/src/db";
+import { scheduleObservationEvals } from "../scheduleObservationEvals";
+import {
+ createTestObservation,
+ createTestEvalConfig,
+ createMockSchedulerDeps,
+} from "./fixtures";
+import { type ObservationForEval, EvalTargetObject } from "@langfuse/shared";
+
+// Mock logger to avoid noise in tests
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ };
+});
+
+describe("Filter Evaluation for Observation Evals", () => {
+ const projectId = "test-project-123";
+
+ /**
+ * Helper to test if an observation matches a filter config.
+ * Returns true if createJobExecution was called (meaning filter matched).
+ */
+ async function testFilterMatch(
+ observation: ObservationForEval,
+ filter: unknown[],
+ ): Promise<boolean> {
+ const config = createTestEvalConfig({
+ projectId,
+ filter,
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ });
+
+ const deps = createMockSchedulerDeps();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: deps,
+ });
+
+ return (
+ (deps.upsertJobExecution as ReturnType<typeof vi.fn>).mock.calls.length >
+ 0
+ );
+ }
+
+ describe("string filters", () => {
+ describe("equals operator", () => {
+ it("should match when name equals filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "=",
+ value: "my-generation",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when name does not equal filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "=",
+ value: "other-name",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("contains operator", () => {
+ it("should match when name contains filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-special-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "special",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when name does not contain filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "special",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("does not contain operator", () => {
+ it("should match when name does not contain filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "does not contain",
+ value: "special",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when name contains filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "my-special-generation",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "does not contain",
+ value: "special",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("starts with operator", () => {
+ it("should match when name starts with filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "chat-completion-v2",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "starts with",
+ value: "chat-",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when name does not start with filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "completion-chat-v2",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "starts with",
+ value: "chat-",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("ends with operator", () => {
+ it("should match when name ends with filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "chat-completion-v2",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "ends with",
+ value: "-v2",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when name does not end with filter value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ name: "chat-completion-v1",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "name",
+ type: "string",
+ operator: "ends with",
+ value: "-v2",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("null/undefined handling", () => {
+ it("should treat null as empty string for string filters", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ version: null as unknown as string,
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "version",
+ type: "string",
+ operator: "=",
+ value: "",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+ });
+
+ describe("stringOptions filters", () => {
+ describe("any of operator", () => {
+ it("should match when type is in allowed list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "GENERATION",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION", "SPAN"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when type is not in allowed list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "EVENT",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION", "SPAN"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should match single value in list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ environment: "production",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+
+ describe("none of operator", () => {
+ it("should match when type is not in excluded list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "EVENT",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["GENERATION", "SPAN"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when type is in excluded list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "GENERATION",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["GENERATION", "SPAN"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("level filtering", () => {
+ it("should filter by log level", async () => {
+ const errorObservation = createTestObservation({
+ project_id: projectId,
+ level: "ERROR",
+ });
+
+ const matched = await testFilterMatch(errorObservation, [
+ {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["ERROR", "WARNING"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+ });
+
+ describe("arrayOptions filters (tags)", () => {
+ describe("any of operator", () => {
+ it("should match when any tag is in filter list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["important", "reviewed", "production"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["important", "critical"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when no tags are in filter list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["test", "staging"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["important", "critical"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should not match when tags is empty array", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: [],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["important"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("none of operator", () => {
+ it("should match when no tags are in excluded list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["reviewed", "production"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "none of",
+ value: ["test", "staging"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when any tag is in excluded list", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["production", "test"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "none of",
+ value: ["test", "staging"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should match when tags is empty (nothing to exclude)", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: [],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "none of",
+ value: ["test"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+
+ describe("all of operator", () => {
+ it("should match when all filter values are in tags", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["important", "reviewed", "production"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "all of",
+ value: ["important", "reviewed"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when not all filter values are in tags", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ tags: ["important", "production"],
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "all of",
+ value: ["important", "reviewed"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+ });
+
+ describe("stringObject filters (metadata)", () => {
+ describe("equals operator with key", () => {
+ it("should match metadata key value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ metadata: { customer: "acme", tier: "premium" },
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "customer",
+ operator: "=",
+ value: "acme",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when metadata key has different value", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ metadata: { customer: "other-corp" },
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "customer",
+ operator: "=",
+ value: "acme",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should not match when metadata key does not exist", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ metadata: { tier: "premium" },
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "customer",
+ operator: "=",
+ value: "acme",
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+ });
+
+ describe("contains operator with key", () => {
+ it("should match when metadata key value contains substring", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ metadata: { environment: "production-us-west-2" },
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "environment",
+ operator: "contains",
+ value: "production",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+ });
+
+ describe("multiple filter conditions (AND logic)", () => {
+ it("should match when all conditions are satisfied", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "GENERATION",
+ level: "DEFAULT",
+ environment: "production",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
+ {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["DEFAULT", "DEBUG"],
+ },
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when any condition fails", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "GENERATION",
+ level: "ERROR", // Doesn't match DEFAULT filter
+ environment: "production",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
+ {
+ column: "level",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["DEFAULT", "DEBUG"],
+ },
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ]);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should handle complex filter combinations", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "GENERATION",
+ name: "chat-completion-handler",
+ tags: ["important", "production"],
+ metadata: { version: "2.0" },
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
+ {
+ column: "name",
+ type: "string",
+ operator: "contains",
+ value: "chat",
+ },
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["important"],
+ },
+ {
+ column: "metadata",
+ type: "stringObject",
+ key: "version",
+ operator: "=",
+ value: "2.0",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+
+ describe("empty filter", () => {
+ it("should match all observations when filter is empty array", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "SPAN",
+ name: "any-name",
+ });
+
+ const matched = await testFilterMatch(observation, []);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should match all observations when filter is null-ish", async () => {
+ const observation = createTestObservation({ project_id: projectId });
+ const config = createTestEvalConfig({
+ projectId,
+ filter: null as unknown as Prisma.JsonValue,
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ });
+
+ const deps = createMockSchedulerDeps();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: deps,
+ });
+
+ expect(deps.upsertJobExecution).toHaveBeenCalled();
+ });
+ });
+
+ describe("trace-level property filtering", () => {
+ it("should filter by trace_name", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ trace_name: "user-query-handler",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "trace_name",
+ type: "string",
+ operator: "contains",
+ value: "query",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should filter by user_id", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ user_id: "user-123",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "user_id",
+ type: "string",
+ operator: "=",
+ value: "user-123",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should filter by session_id", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ session_id: "session-abc",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "session_id",
+ type: "string",
+ operator: "=",
+ value: "session-abc",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should filter by release", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ release: "v2.0.0",
+ });
+
+ const matched = await testFilterMatch(observation, [
+ {
+ column: "release",
+ type: "string",
+ operator: "starts with",
+ value: "v2",
+ },
+ ]);
+
+ expect(matched).toBe(true);
+ });
+ });
+
+ describe("experiment target object filtering", () => {
+ /**
+ * Helper to test experiment target object filtering.
+ * Returns true if createJobExecution was called (meaning filter matched).
+ */
+ async function testExperimentFilterMatch(
+ observation: ObservationForEval,
+ filter: unknown[] = [],
+ ): Promise<boolean> {
+ const config = createTestEvalConfig({
+ projectId,
+ filter,
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ targetObject: EvalTargetObject.EXPERIMENT,
+ });
+
+ const deps = createMockSchedulerDeps();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: deps,
+ });
+
+ return (
+ (deps.upsertJobExecution as ReturnType<typeof vi.fn>).mock.calls
+ .length > 0
+ );
+ }
+
+ it("should match when span_id equals experiment_item_root_span_id", async () => {
+ const spanId = "span-123";
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: spanId,
+ experiment_item_root_span_id: spanId,
+ });
+
+ const matched = await testExperimentFilterMatch(observation);
+
+ expect(matched).toBe(true);
+ });
+
+ it("should not match when span_id does not equal experiment_item_root_span_id", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: "span-123",
+ experiment_item_root_span_id: "span-456",
+ });
+
+ const matched = await testExperimentFilterMatch(observation);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should not match when experiment_item_root_span_id is null", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: "span-123",
+ experiment_item_root_span_id: null,
+ });
+
+ const matched = await testExperimentFilterMatch(observation);
+
+ expect(matched).toBe(false);
+ });
+
+ it("should apply filter conditions when targetObject is EXPERIMENT", async () => {
+ const spanId = "span-123";
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: spanId,
+ experiment_item_root_span_id: spanId,
+ experiment_dataset_id: "dataset-123",
+ });
+
+ // Filter that excludes this observation's dataset
+ const matched = await testExperimentFilterMatch(observation, [
+ {
+ column: "experiment_dataset_id",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["dataset-456"], // Observation has dataset-123
+ },
+ ]);
+
+ // Should NOT match because filter conditions are applied for experiment configs
+ expect(matched).toBe(false);
+ });
+
+ it("should match experiment when filter matches and is root span", async () => {
+ const spanId = "span-123";
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: spanId,
+ experiment_item_root_span_id: spanId,
+ experiment_dataset_id: "dataset-123",
+ });
+
+ // Filter that includes this observation's dataset
+ const matched = await testExperimentFilterMatch(observation, [
+ {
+ column: "experiment_dataset_id",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["dataset-123", "dataset-456"],
+ },
+ ]);
+
+ // Should match because filter passes AND observation is experiment root span
+ expect(matched).toBe(true);
+ });
+
+ it("should not match experiment when filter matches but is not root span", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: "child-span-456",
+ experiment_item_root_span_id: "root-span-123",
+ experiment_dataset_id: "dataset-123",
+ });
+
+ // Filter matches the observation
+ const matched = await testExperimentFilterMatch(observation, [
+ {
+ column: "experiment_dataset_id",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["dataset-123"],
+ },
+ ]);
+
+ // Should NOT match because observation is not the experiment root span
+ expect(matched).toBe(false);
+ });
+
+ it("should not match child spans even if they have experiment properties", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ span_id: "child-span-456",
+ experiment_item_root_span_id: "root-span-123",
+ experiment_id: "exp-1",
+ experiment_name: "my-experiment",
+ });
+
+ const matched = await testExperimentFilterMatch(observation);
+
+ // Child spans should not match, only the root span
+ expect(matched).toBe(false);
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts
new file mode 100644
index 0000000000..af23bdd249
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts
@@ -0,0 +1,346 @@
+import { vi } from "vitest";
+import { randomUUID } from "crypto";
+import { type Prisma } from "@langfuse/shared/src/db";
+import { type ObservationForEval, EvalTargetObject } from "@langfuse/shared";
+import {
+ type ObservationEvalConfig,
+ type ObservationEvalSchedulerDeps,
+} from "../types";
+import { type ObservationEvalProcessorDeps } from "../observationEvalProcessor";
+import {
+ type EvalExecutionDeps,
+ createMockEvalExecutionDeps,
+} from "../../evalExecutionDeps";
+
+/**
+ * Creates a test ObservationForEval with sensible defaults.
+ * All fields can be overridden.
+ * Note: Uses snake_case field names matching eventRecordBaseSchema.
+ */
+export function createTestObservation(
+ overrides: Partial<ObservationForEval> = {},
+): ObservationForEval {
+ return {
+ // Core identifiers
+ span_id: `obs-${randomUUID()}`,
+ trace_id: `trace-${randomUUID()}`,
+ project_id: "test-project-123",
+ parent_span_id: null,
+
+ // Observation properties
+ type: "GENERATION",
+ name: "test-observation",
+ environment: "test",
+ level: "DEFAULT",
+ status_message: null,
+ version: "v1.0",
+
+ // Trace-level properties
+ trace_name: "test-trace",
+ user_id: "user-123",
+ session_id: "session-456",
+ tags: ["test-tag"],
+ release: "v1.0.0",
+
+ // Model properties
+ provided_model_name: "gpt-4",
+ model_parameters: '{"temperature": 0.7}',
+
+ // Prompt properties
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+
+ // Tool call properties
+ tool_definitions: {},
+ tool_calls: [],
+ tool_call_names: [],
+
+ // Usage & Cost
+ usage_details: { input: 100, output: 50 },
+ cost_details: {},
+ provided_usage_details: {},
+ provided_cost_details: {},
+
+ // Experiment properties
+ experiment_id: null,
+ experiment_name: null,
+ experiment_description: null,
+ experiment_dataset_id: null,
+ experiment_item_id: null,
+ experiment_item_expected_output: null,
+ experiment_item_root_span_id: null,
+
+ // Data fields
+ input: '{"prompt": "Hello, how are you?"}',
+ output: '{"response": "I am fine, thank you!"}',
+ metadata: { key: "value" },
+
+ ...overrides,
+ };
+}
+
+/**
+ * Creates a test ObservationEvalConfig with sensible defaults.
+ */
+export function createTestEvalConfig(
+ overrides: Partial<ObservationEvalConfig> = {},
+): ObservationEvalConfig {
+ return {
+ id: `config-${randomUUID()}`,
+ projectId: "test-project-123",
+ filter: [],
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ evalTemplateId: `template-${randomUUID()}`,
+ scoreName: "test-score",
+ targetObject: EvalTargetObject.EVENT,
+ variableMapping: [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ],
+ delay: 0,
+ ...overrides,
+ };
+}
+
+/**
+ * Creates mock scheduler dependencies with vi.fn() for all methods.
+ * Returns both the deps and the mock functions for assertions.
+ */
+export function createMockSchedulerDeps(
+ overrides: Partial<{
+ createJobExecution: ReturnType<typeof vi.fn>;
+ uploadObservationToS3: ReturnType<typeof vi.fn>;
+ enqueueEvalJob: ReturnType<typeof vi.fn>;
+ }> = {},
+): ObservationEvalSchedulerDeps {
+ return {
+ upsertJobExecution:
+ overrides.createJobExecution ??
+ vi.fn().mockResolvedValue({ id: `job-exec-${randomUUID()}` }),
+ uploadObservationToS3:
+ overrides.uploadObservationToS3 ??
+ vi.fn().mockResolvedValue(`observations/test/obs-123.json`),
+ enqueueEvalJob:
+ overrides.enqueueEvalJob ?? vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+/**
+ * Creates mock processor dependencies for observationEvalProcessor.
+ */
+export function createMockProcessorDeps(
+ overrides: Partial<{
+ downloadObservationFromS3: ReturnType<typeof vi.fn>;
+ }> = {},
+): ObservationEvalProcessorDeps {
+ const defaultObservation = createTestObservation();
+
+ return {
+ downloadObservationFromS3:
+ overrides.downloadObservationFromS3 ??
+ vi.fn().mockResolvedValue(JSON.stringify(defaultObservation)),
+ };
+}
+
+/**
+ * Creates a mock job execution record.
+ */
+export function createMockJobExecution(
+ overrides: Partial<{
+ id: string;
+ projectId: string;
+ status: string;
+ jobConfigurationId: string;
+ jobInputTraceId: string | null;
+ jobInputObservationId: string | null;
+ jobInputDatasetItemId: string | null;
+ error: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ startTime: Date | null;
+ endTime: Date | null;
+ jobOutputScoreId: string | null;
+ executionTraceId: string | null;
+ jobTemplateId: string | null;
+ jobInputTraceTimestamp: Date | null;
+ }> = {},
+) {
+ return {
+ id: overrides.id ?? `job-exec-${randomUUID()}`,
+ projectId: overrides.projectId ?? "test-project-123",
+ status: overrides.status ?? "PENDING",
+ jobConfigurationId:
+ overrides.jobConfigurationId ?? `config-${randomUUID()}`,
+ jobInputTraceId: overrides.jobInputTraceId ?? `trace-${randomUUID()}`,
+ jobInputObservationId:
+ overrides.jobInputObservationId ?? `obs-${randomUUID()}`,
+ jobInputDatasetItemId: overrides.jobInputDatasetItemId ?? null,
+ error: overrides.error ?? null,
+ createdAt: overrides.createdAt ?? new Date(),
+ updatedAt: overrides.updatedAt ?? new Date(),
+ startTime: overrides.startTime ?? new Date(),
+ endTime: overrides.endTime ?? null,
+ jobOutputScoreId: overrides.jobOutputScoreId ?? null,
+ executionTraceId: overrides.executionTraceId ?? null,
+ jobTemplateId: overrides.jobTemplateId ?? null,
+ jobInputTraceTimestamp: overrides.jobInputTraceTimestamp ?? null,
+ };
+}
+
+/**
+ * Creates a mock job configuration record.
+ * Use evalTemplate option to include a nested template (for Prisma include queries).
+ */
+export function createMockJobConfiguration(
+ overrides: Partial<{
+ id: string;
+ projectId: string;
+ jobType: string;
+ evalTemplateId: string | null;
+ scoreName: string;
+ targetObject: string;
+ filter: unknown[];
+ variableMapping: unknown[];
+ sampling: string;
+ delay: number;
+ status: string;
+ timeScope: string[];
+ createdAt: Date;
+ updatedAt: Date;
+ evalTemplate: ReturnType<typeof createMockEvalTemplate> | null;
+ }> = {},
+) {
+ const templateId = overrides.evalTemplateId ?? `template-${randomUUID()}`;
+ const projectId = overrides.projectId ?? "test-project-123";
+
+ return {
+ id: overrides.id ?? `config-${randomUUID()}`,
+ projectId,
+ jobType: overrides.jobType ?? "EVAL",
+ evalTemplateId: templateId,
+ scoreName: overrides.scoreName ?? "test-score",
+ targetObject: overrides.targetObject ?? EvalTargetObject.EVENT,
+ filter: overrides.filter ?? [],
+ variableMapping: overrides.variableMapping ?? [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ],
+ sampling: overrides.sampling ?? "1.0",
+ delay: overrides.delay ?? 0,
+ status: overrides.status ?? "ACTIVE",
+ timeScope: overrides.timeScope ?? ["NEW"],
+ createdAt: overrides.createdAt ?? new Date(),
+ updatedAt: overrides.updatedAt ?? new Date(),
+ // Include evalTemplate when provided, or create default one
+ evalTemplate:
+ overrides.evalTemplate !== undefined
+ ? overrides.evalTemplate
+ : createMockEvalTemplate({ id: templateId, projectId }),
+ };
+}
+
+/**
+ * Creates a mock eval template record.
+ */
+export function createMockEvalTemplate(
+ overrides: Partial<{
+ id: string;
+ projectId: string | null;
+ name: string;
+ version: number;
+ prompt: string;
+ model: string;
+ provider: string;
+ modelParams: Record<string, unknown>;
+ outputSchema: Record<string, string>;
+ vars: string[];
+ createdAt: Date;
+ updatedAt: Date;
+ }> = {},
+) {
+ return {
+ id: overrides.id ?? `template-${randomUUID()}`,
+ projectId: overrides.projectId ?? "test-project-123",
+ name: overrides.name ?? "Test Evaluator",
+ version: overrides.version ?? 1,
+ prompt:
+ overrides.prompt ??
+ "Evaluate the following output: {{output}}. Score 0-1.",
+ model: overrides.model ?? "gpt-4",
+ provider: overrides.provider ?? "openai",
+ modelParams: overrides.modelParams ?? {},
+ outputSchema: overrides.outputSchema ?? {
+ score: "A number between 0 and 1",
+ reasoning: "Explain your reasoning",
+ },
+ vars: overrides.vars ?? ["output"],
+ createdAt: overrides.createdAt ?? new Date(),
+ updatedAt: overrides.updatedAt ?? new Date(),
+ };
+}
+
+/**
+ * Creates a fully mocked eval pipeline that connects scheduler → processor → execution.
+ * Useful for E2E-style tests where you want to trace data through the full flow.
+ */
+export function createFullyMockedEvalPipeline(
+ config: {
+ llmResponse?: { score: number; reasoning: string };
+ s3UploadPath?: string;
+ observation?: ObservationForEval;
+ } = {},
+) {
+ const uploadedData = new Map<string, unknown>();
+ const observation = config.observation ?? createTestObservation();
+
+ const schedulerDeps: ObservationEvalSchedulerDeps = {
+ upsertJobExecution: vi
+ .fn()
+ .mockResolvedValue({ id: `job-exec-${randomUUID()}` }),
+ uploadObservationToS3: vi.fn().mockImplementation(async (params) => {
+ const path =
+ config.s3UploadPath ??
+ `evals/${params.projectId}/observations/${params.observationId}.json`;
+ uploadedData.set(path, params.data);
+ return path;
+ }),
+ enqueueEvalJob: vi.fn().mockResolvedValue(undefined),
+ };
+
+ const processorDeps: ObservationEvalProcessorDeps = {
+ downloadObservationFromS3: vi.fn().mockImplementation(async (path) => {
+ const data = uploadedData.get(path);
+ if (data) {
+ return JSON.stringify(data);
+ }
+ return JSON.stringify(observation);
+ }),
+ };
+
+ const executionDeps: EvalExecutionDeps = createMockEvalExecutionDeps({
+ callLLM: vi
+ .fn()
+ .mockResolvedValue(
+ config.llmResponse ?? { score: 0.85, reasoning: "Good response" },
+ ),
+ fetchModelConfig: vi.fn().mockResolvedValue({
+ valid: true,
+ config: {
+ provider: "openai",
+ model: "gpt-4",
+ apiKey: { adapter: "openai", secretKey: "test-key" },
+ modelParams: {},
+ },
+ }),
+ uploadScore: vi.fn().mockResolvedValue(undefined),
+ enqueueScoreIngestion: vi.fn().mockResolvedValue(undefined),
+ updateJobExecution: vi.fn().mockResolvedValue(undefined),
+ });
+
+ return {
+ schedulerDeps,
+ processorDeps,
+ executionDeps,
+ observation,
+ getUploadedData: () => uploadedData,
+ };
+}
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
new file mode 100644
index 0000000000..9b92e67a8a
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
@@ -0,0 +1,637 @@
+import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";
+import { JobExecutionStatus, type Prisma } from "@prisma/client";
+import { randomUUID } from "crypto";
+import { scheduleObservationEvals } from "../scheduleObservationEvals";
+import { processObservationEval } from "../observationEvalProcessor";
+import {
+ createTestObservation,
+ createTestEvalConfig,
+ createFullyMockedEvalPipeline,
+} from "./fixtures";
+import { type ObservationForEval, EvalTargetObject } from "@langfuse/shared";
+
+// Mock prisma for processObservationEval
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ jobExecution: {
+ findFirst: vi.fn(),
+ update: vi.fn(),
+ },
+ jobConfiguration: {
+ findFirst: vi.fn(),
+ },
+ },
+}));
+
+// Mock executeLLMAsJudgeEvaluation
+vi.mock("../../evalService", () => ({
+ executeLLMAsJudgeEvaluation: vi.fn(),
+}));
+
+// Mock logger
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ DEFAULT_TRACE_ENVIRONMENT: "default",
+ };
+});
+
+import { prisma } from "@langfuse/shared/src/db";
+import { executeLLMAsJudgeEvaluation } from "../../evalService";
+
+describe("Observation Eval E2E Pipeline", () => {
+ const projectId = "test-project-123";
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("full pipeline: schedule → process → execute", () => {
+ it("should schedule and process observation through full eval pipeline", async () => {
+ // ARRANGE: Create observation and config
+ const observation = createTestObservation({
+ span_id: `obs-${randomUUID()}`,
+ trace_id: `trace-${randomUUID()}`,
+ project_id: projectId,
+ type: "generation",
+ provided_model_name: "gpt-4",
+ environment: "production",
+ output: '{"response": "The capital of France is Paris."}',
+ });
+
+ const config = createTestEvalConfig({
+ id: `config-${randomUUID()}`,
+ projectId,
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"],
+ },
+ ],
+ variableMapping: [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ],
+ scoreName: "accuracy",
+ });
+
+ // Create mocked pipeline
+ const pipeline = createFullyMockedEvalPipeline({
+ observation,
+ llmResponse: {
+ score: 0.95,
+ reasoning: "Accurate geographic information",
+ },
+ });
+
+ // Track job execution ID
+ let capturedJobExecutionId: string | undefined;
+ const mockCreateJobExecution = vi
+ .fn()
+ .mockImplementation(async (params) => {
+ capturedJobExecutionId = `job-exec-${randomUUID()}`;
+ return { id: capturedJobExecutionId };
+ });
+ pipeline.schedulerDeps.upsertJobExecution = mockCreateJobExecution;
+
+ // ACT: Schedule the observation eval
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: pipeline.schedulerDeps,
+ });
+
+ // ASSERT: Scheduling phase
+ expect(pipeline.schedulerDeps.uploadObservationToS3).toHaveBeenCalledWith(
+ {
+ projectId,
+ observationId: observation.span_id,
+ data: observation,
+ },
+ );
+ expect(mockCreateJobExecution).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId,
+ jobConfigurationId: config.id,
+ jobInputTraceId: observation.trace_id,
+ jobInputObservationId: observation.span_id,
+ status: JobExecutionStatus.PENDING,
+ }),
+ );
+ expect(pipeline.schedulerDeps.enqueueEvalJob).toHaveBeenCalled();
+
+ // Get the S3 path that was used
+ const uploadCall = (pipeline.schedulerDeps.uploadObservationToS3 as Mock)
+ .mock.results[0];
+ const observationS3Path = await uploadCall.value;
+
+ // ARRANGE: Set up mocks for processing phase
+ const mockJob = {
+ id: capturedJobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: config.id,
+ jobInputTraceId: observation.trace_id,
+ jobInputObservationId: observation.span_id,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ startTime: new Date(),
+ endTime: null,
+ error: null,
+ jobOutputScoreId: null,
+ executionTraceId: null,
+ jobTemplateId: null,
+ jobInputDatasetItemId: null,
+ jobInputTraceTimestamp: null,
+ };
+
+ const mockTemplate = {
+ id: config.evalTemplateId,
+ projectId,
+ name: "Accuracy Evaluator",
+ version: 1,
+ prompt: "Evaluate the accuracy of: {{output}}",
+ model: "gpt-4",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: {
+ score: "A number between 0 and 1",
+ reasoning: "Explanation",
+ },
+ vars: ["output"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ const mockConfig = {
+ id: config.id,
+ projectId,
+ jobType: "EVAL",
+ evalTemplateId: config.evalTemplateId,
+ scoreName: config.scoreName,
+ targetObject: EvalTargetObject.EVENT,
+ filter: config.filter,
+ variableMapping: config.variableMapping,
+ sampling: "1.0",
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ evalTemplate: mockTemplate,
+ };
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(mockConfig);
+
+ // ACT: Process the observation eval job
+ await processObservationEval({
+ event: {
+ projectId,
+ jobExecutionId: capturedJobExecutionId!,
+ observationS3Path,
+ },
+ deps: pipeline.processorDeps,
+ });
+
+ // ASSERT: Processing phase
+ expect(
+ pipeline.processorDeps.downloadObservationFromS3,
+ ).toHaveBeenCalledWith(observationS3Path);
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId,
+ jobExecutionId: capturedJobExecutionId,
+ extractedVariables: expect.arrayContaining([
+ expect.objectContaining({
+ var: "output",
+ value: '{"response": "The capital of France is Paris."}',
+ }),
+ ]),
+ environment: "production",
+ }),
+ );
+ });
+
+ it("should not schedule eval when filter does not match", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "span", // Not a generation
+ });
+
+ const config = createTestEvalConfig({
+ projectId,
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"], // Only matches generations
+ },
+ ],
+ });
+
+ const pipeline = createFullyMockedEvalPipeline({ observation });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: pipeline.schedulerDeps,
+ });
+
+ // S3 upload only happens if there are matching configs
+ expect(
+ pipeline.schedulerDeps.uploadObservationToS3,
+ ).not.toHaveBeenCalled();
+ expect(pipeline.schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ expect(pipeline.schedulerDeps.enqueueEvalJob).not.toHaveBeenCalled();
+ });
+
+ it("should not schedule eval when sampled out", async () => {
+ const observation = createTestObservation({ project_id: projectId });
+
+ const config = createTestEvalConfig({
+ projectId,
+ filter: [], // Match all
+ sampling: { toNumber: () => 0 } as unknown as Prisma.Decimal, // 0% sampling
+ });
+
+ const pipeline = createFullyMockedEvalPipeline({ observation });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps: pipeline.schedulerDeps,
+ });
+
+ expect(pipeline.schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ });
+
+ it("should schedule multiple evals for multiple matching configs", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ type: "generation",
+ provided_model_name: "gpt-4",
+ });
+
+ const config1 = createTestEvalConfig({
+ id: "config-1",
+ projectId,
+ scoreName: "accuracy",
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"],
+ },
+ ],
+ });
+
+ const config2 = createTestEvalConfig({
+ id: "config-2",
+ projectId,
+ scoreName: "relevance",
+ filter: [
+ {
+ column: "provided_model_name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["gpt-4"],
+ },
+ ],
+ });
+
+ const config3 = createTestEvalConfig({
+ id: "config-3",
+ projectId,
+ scoreName: "safety",
+ filter: [], // Match all
+ });
+
+ const pipeline = createFullyMockedEvalPipeline({ observation });
+ pipeline.schedulerDeps.upsertJobExecution = vi
+ .fn()
+ .mockResolvedValueOnce({ id: "job-1" })
+ .mockResolvedValueOnce({ id: "job-2" })
+ .mockResolvedValueOnce({ id: "job-3" });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config1, config2, config3],
+ schedulerDeps: pipeline.schedulerDeps,
+ });
+
+ // All three configs should match
+ expect(pipeline.schedulerDeps.upsertJobExecution).toHaveBeenCalledTimes(
+ 3,
+ );
+ expect(pipeline.schedulerDeps.enqueueEvalJob).toHaveBeenCalledTimes(3);
+
+ // S3 upload should only happen once
+ expect(
+ pipeline.schedulerDeps.uploadObservationToS3,
+ ).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("variable extraction scenarios", () => {
+ it("should extract input and output for comparison evals", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ input: '{"question": "What is 2+2?"}',
+ output: '{"answer": "4"}',
+ });
+
+ const config = createTestEvalConfig({
+ projectId,
+ variableMapping: [
+ { templateVariable: "question", selectedColumnId: "input" },
+ { templateVariable: "answer", selectedColumnId: "output" },
+ ],
+ });
+
+ const pipeline = createFullyMockedEvalPipeline({ observation });
+
+ // Set up mocks for processing
+ const mockJob = {
+ id: "job-123",
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: config.id,
+ jobInputTraceId: observation.trace_id,
+ jobInputObservationId: observation.span_id,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ startTime: null,
+ endTime: null,
+ error: null,
+ jobOutputScoreId: null,
+ executionTraceId: null,
+ jobTemplateId: null,
+ jobInputDatasetItemId: null,
+ jobInputTraceTimestamp: null,
+ };
+
+ const mockTemplate = {
+ id: config.evalTemplateId,
+ projectId,
+ name: "Test Eval",
+ version: 1,
+ prompt: "Q: {{question}} A: {{answer}}",
+ model: "gpt-4",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: { score: "0-1", reasoning: "Why" },
+ vars: ["question", "answer"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ const mockConfig = {
+ id: config.id,
+ projectId,
+ jobType: "EVAL",
+ evalTemplateId: config.evalTemplateId,
+ scoreName: config.scoreName,
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ variableMapping: config.variableMapping,
+ sampling: "1.0",
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ evalTemplate: mockTemplate,
+ };
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(mockConfig);
+
+ await processObservationEval({
+ event: {
+ projectId,
+ jobExecutionId: "job-123",
+ observationS3Path: "test-path",
+ },
+ deps: pipeline.processorDeps,
+ });
+
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractedVariables: expect.arrayContaining([
+ expect.objectContaining({
+ var: "question",
+ value: '{"question": "What is 2+2?"}',
+ }),
+ expect.objectContaining({
+ var: "answer",
+ value: '{"answer": "4"}',
+ }),
+ ]),
+ }),
+ );
+ });
+
+ it("should extract expected output for experiment evals", async () => {
+ const observation = createTestObservation({
+ project_id: projectId,
+ output: '{"generated": "Paris"}',
+ experiment_item_expected_output: "Paris",
+ });
+
+ const config = createTestEvalConfig({
+ projectId,
+ variableMapping: [
+ { templateVariable: "generated", selectedColumnId: "output" },
+ {
+ templateVariable: "expected",
+ selectedColumnId: "experiment_item_expected_output",
+ },
+ ],
+ });
+
+ const pipeline = createFullyMockedEvalPipeline({ observation });
+
+ const mockJob = {
+ id: "job-123",
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: config.id,
+ jobInputTraceId: observation.trace_id,
+ jobInputObservationId: observation.span_id,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ startTime: null,
+ endTime: null,
+ error: null,
+ jobOutputScoreId: null,
+ executionTraceId: null,
+ jobTemplateId: null,
+ jobInputDatasetItemId: null,
+ jobInputTraceTimestamp: null,
+ };
+
+ const mockTemplate = {
+ id: config.evalTemplateId,
+ projectId,
+ name: "Test Eval",
+ version: 1,
+ prompt: "Compare {{generated}} to {{expected}}",
+ model: "gpt-4",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: { score: "0-1", reasoning: "Why" },
+ vars: ["generated", "expected"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ const mockConfig = {
+ id: config.id,
+ projectId,
+ jobType: "EVAL",
+ evalTemplateId: config.evalTemplateId,
+ scoreName: config.scoreName,
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ variableMapping: config.variableMapping,
+ sampling: "1.0",
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ evalTemplate: mockTemplate,
+ };
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(mockConfig);
+
+ await processObservationEval({
+ event: {
+ projectId,
+ jobExecutionId: "job-123",
+ observationS3Path: "test-path",
+ },
+ deps: pipeline.processorDeps,
+ });
+
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractedVariables: expect.arrayContaining([
+ expect.objectContaining({
+ var: "expected",
+ value: "Paris",
+ }),
+ ]),
+ }),
+ );
+ });
+ });
+
+ describe("filter scenarios", () => {
+ it("should filter by environment", async () => {
+ const prodObservation = createTestObservation({
+ project_id: projectId,
+ environment: "production",
+ });
+
+ const stagingObservation = createTestObservation({
+ project_id: projectId,
+ environment: "staging",
+ });
+
+ const config = createTestEvalConfig({
+ projectId,
+ filter: [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ],
+ });
+
+ const pipeline1 = createFullyMockedEvalPipeline({
+ observation: prodObservation,
+ });
+ const pipeline2 = createFullyMockedEvalPipeline({
+ observation: stagingObservation,
+ });
+
+ await scheduleObservationEvals({
+ observation: prodObservation,
+ configs: [config],
+ schedulerDeps: pipeline1.schedulerDeps,
+ });
+
+ await scheduleObservationEvals({
+ observation: stagingObservation,
+ configs: [config],
+ schedulerDeps: pipeline2.schedulerDeps,
+ });
+
+ // Production should match
+ expect(pipeline1.schedulerDeps.upsertJobExecution).toHaveBeenCalled();
+ // Staging should not match
+ expect(pipeline2.schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ });
+
+ it("should filter by tags", async () => {
+ const taggedObservation = createTestObservation({
+ project_id: projectId,
+ tags: ["important", "test"],
+ });
+
+ const untaggedObservation = createTestObservation({
+ project_id: projectId,
+ tags: ["other"],
+ });
+
+ const config = createTestEvalConfig({
+ projectId,
+ filter: [
+ {
+ column: "tags",
+ type: "arrayOptions",
+ operator: "any of",
+ value: ["important"],
+ },
+ ],
+ });
+
+ const pipeline1 = createFullyMockedEvalPipeline({
+ observation: taggedObservation,
+ });
+ const pipeline2 = createFullyMockedEvalPipeline({
+ observation: untaggedObservation,
+ });
+
+ await scheduleObservationEvals({
+ observation: taggedObservation,
+ configs: [config],
+ schedulerDeps: pipeline1.schedulerDeps,
+ });
+
+ await scheduleObservationEvals({
+ observation: untaggedObservation,
+ configs: [config],
+ schedulerDeps: pipeline2.schedulerDeps,
+ });
+
+ expect(pipeline1.schedulerDeps.upsertJobExecution).toHaveBeenCalled();
+ expect(pipeline2.schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
new file mode 100644
index 0000000000..7ce05d31d7
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
@@ -0,0 +1,393 @@
+import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";
+import { JobExecutionStatus } from "@prisma/client";
+import {
+ processObservationEval,
+ type ObservationEvalProcessorDeps,
+} from "../observationEvalProcessor";
+import {
+ createTestObservation,
+ createMockJobExecution,
+ createMockJobConfiguration,
+ createMockEvalTemplate,
+ createMockProcessorDeps,
+} from "./fixtures";
+import { UnrecoverableError } from "../../../../errors/UnrecoverableError";
+
+// Mock prisma
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ jobExecution: {
+ findFirst: vi.fn(),
+ update: vi.fn(),
+ },
+ jobConfiguration: {
+ findFirst: vi.fn(),
+ },
+ },
+}));
+
+// Mock executeLLMAsJudgeEvaluation
+vi.mock("../../evalService", () => ({
+ executeLLMAsJudgeEvaluation: vi.fn(),
+}));
+
+// Mock logger
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ DEFAULT_TRACE_ENVIRONMENT: "default",
+ };
+});
+
+import { prisma } from "@langfuse/shared/src/db";
+import { executeLLMAsJudgeEvaluation } from "../../evalService";
+
+describe("processObservationEval", () => {
+ const projectId = "test-project-123";
+ const jobExecutionId = "job-exec-456";
+ const observationS3Path = "evals/test-project-123/observations/obs-789.json";
+
+ const baseEvent = {
+ projectId,
+ jobExecutionId,
+ observationS3Path,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("job execution lookup", () => {
+ it("should return early when job execution is not found", async () => {
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(null);
+
+ const deps = createMockProcessorDeps();
+
+ await processObservationEval({ event: baseEvent, deps });
+
+ expect(prisma.jobExecution.findFirst).toHaveBeenCalledWith({
+ where: {
+ id: jobExecutionId,
+ projectId,
+ },
+ });
+ expect(deps.downloadObservationFromS3).not.toHaveBeenCalled();
+ expect(executeLLMAsJudgeEvaluation).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("job configuration lookup", () => {
+ it("should throw UnrecoverableError when job configuration is not found", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(null);
+
+ const deps = createMockProcessorDeps();
+
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow(UnrecoverableError);
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow("Job configuration or template not found");
+ });
+
+ it("should throw UnrecoverableError when evalTemplate is null", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const configWithoutTemplate = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ evalTemplate: null,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(
+ configWithoutTemplate,
+ );
+
+ const deps = createMockProcessorDeps();
+
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+ });
+
+ describe("S3 download", () => {
+ it("should throw error when S3 download fails (retryable)", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ const deps: ObservationEvalProcessorDeps = {
+ downloadObservationFromS3: vi
+ .fn()
+ .mockRejectedValue(new Error("S3 connection failed")),
+ };
+
+ // S3 connection errors should be retryable (not UnrecoverableError)
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow("Failed to download observation from S3");
+ });
+
+ it("should throw UnrecoverableError when S3 data is invalid JSON", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ const deps: ObservationEvalProcessorDeps = {
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue("not valid json {"),
+ };
+
+ // Invalid JSON is a permanent error - should be UnrecoverableError
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+
+ it("should throw UnrecoverableError when S3 data fails schema validation", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ // Missing required fields - valid JSON but invalid schema
+ const invalidObservation = { id: "obs-123", someField: "value" };
+ const deps: ObservationEvalProcessorDeps = {
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(invalidObservation)),
+ };
+
+ // Schema validation failures are permanent - should be UnrecoverableError
+ await expect(
+ processObservationEval({ event: baseEvent, deps }),
+ ).rejects.toThrow(UnrecoverableError);
+ });
+ });
+
+ describe("successful execution", () => {
+ it("should call executeLLMAsJudgeEvaluation with correct parameters", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ jobInputTraceId: "trace-abc",
+ jobInputObservationId: "obs-xyz",
+ });
+ const template = createMockEvalTemplate({
+ id: "template-456",
+ projectId,
+ prompt: "Evaluate: {{output}}",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ evalTemplateId: "template-456",
+ variableMapping: [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ],
+ evalTemplate: template,
+ });
+ const observation = createTestObservation({
+ id: "obs-xyz",
+ projectId,
+ traceId: "trace-abc",
+ environment: "production",
+ output: '{"response": "test output"}',
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ const deps = createMockProcessorDeps({
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(observation)),
+ });
+
+ await processObservationEval({ event: baseEvent, deps });
+
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId,
+ jobExecutionId,
+ job: expect.objectContaining({ id: jobExecutionId }),
+ config: expect.objectContaining({ id: "config-123" }),
+ template: expect.objectContaining({ id: "template-456" }),
+ extractedVariables: expect.arrayContaining([
+ expect.objectContaining({
+ var: "output",
+ value: '{"response": "test output"}',
+ }),
+ ]),
+ environment: "production",
+ }),
+ );
+ });
+
+ it("should use default environment when observation environment is null", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ variableMapping: [],
+ });
+ const observation = createTestObservation({
+ projectId,
+ environment: undefined as unknown as string,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ const deps = createMockProcessorDeps({
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(observation)),
+ });
+
+ await processObservationEval({ event: baseEvent, deps });
+
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ environment: "default",
+ }),
+ );
+ });
+
+ it("should extract multiple variables from observation", async () => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ variableMapping: [
+ { templateVariable: "input", selectedColumnId: "input" },
+ { templateVariable: "output", selectedColumnId: "output" },
+ {
+ templateVariable: "model",
+ selectedColumnId: "provided_model_name",
+ },
+ ],
+ });
+ const observation = createTestObservation({
+ project_id: projectId,
+ input: '{"prompt": "Hello"}',
+ output: '{"response": "World"}',
+ provided_model_name: "gpt-4",
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ const deps = createMockProcessorDeps({
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(observation)),
+ });
+
+ await processObservationEval({ event: baseEvent, deps });
+
+ expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ extractedVariables: expect.arrayContaining([
+ expect.objectContaining({
+ var: "input",
+ value: '{"prompt": "Hello"}',
+ }),
+ expect.objectContaining({
+ var: "output",
+ value: '{"response": "World"}',
+ }),
+ expect.objectContaining({ var: "model", value: "gpt-4" }),
+ ]),
+ }),
+ );
+ });
+ });
+
+ describe("default dependencies", () => {
+ it("should use default deps when none provided", async () => {
+ // This test verifies the code path where deps are not provided
+ // It will fail due to missing S3 config, but proves the default deps path is exercised
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ // Without injected deps, it will try to use real S3 which should fail
+ await expect(
+ processObservationEval({ event: baseEvent }),
+ ).rejects.toThrow();
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts
new file mode 100644
index 0000000000..5d0ef64ff9
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts
@@ -0,0 +1,235 @@
+import { describe, it, expect } from "vitest";
+import {
+ observationForEvalSchema,
+ type ObservationForEval,
+ observationEvalFilterColumns,
+ observationEvalVariableColumns,
+} from "@langfuse/shared";
+
+describe("observationForEvalSchema", () => {
+ describe("schema field validation", () => {
+ it("should parse valid span_id field", () => {
+ const evalId = observationForEvalSchema.shape.span_id;
+ expect(evalId.parse("test-id")).toBe("test-id");
+ });
+
+ it("should parse valid type field", () => {
+ const evalType = observationForEvalSchema.shape.type;
+ expect(evalType.parse("GENERATION")).toBe("GENERATION");
+ });
+
+ it("should have environment field with default value", () => {
+ // Environment has a default of "default" in the base schema
+ const result = observationForEvalSchema.parse({
+ span_id: "test",
+ trace_id: "trace",
+ project_id: "project",
+ parent_span_id: null,
+ type: "GENERATION",
+ name: "test",
+ level: "DEFAULT",
+ status_message: null,
+ version: null,
+ trace_name: null,
+ user_id: null,
+ session_id: null,
+ tags: [],
+ release: null,
+ provided_model_name: null,
+ model_parameters: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ tool_definitions: {},
+ tool_calls: [],
+ tool_call_names: [],
+ usage_details: {},
+ cost_details: {},
+ provided_usage_details: {},
+ provided_cost_details: {},
+ experiment_id: null,
+ experiment_name: null,
+ experiment_description: null,
+ experiment_dataset_id: null,
+ experiment_item_id: null,
+ experiment_item_expected_output: null,
+ input: null,
+ output: null,
+ metadata: {},
+ });
+
+ expect(result.environment).toBe("default");
+ });
+ });
+
+ describe("schema validation", () => {
+ const validObservation: ObservationForEval = {
+ span_id: "obs-123",
+ trace_id: "trace-456",
+ project_id: "project-789",
+ parent_span_id: null,
+ type: "GENERATION",
+ name: "test-observation",
+ environment: "production",
+ level: "DEFAULT",
+ status_message: null,
+ version: "v1.0",
+ trace_name: "my-trace",
+ user_id: "user-123",
+ session_id: "session-456",
+ tags: ["tag1", "tag2"],
+ release: "v2.0.0",
+ provided_model_name: "gpt-4",
+ model_parameters: '{"temperature": 0.7}',
+ prompt_id: null,
+ prompt_name: "my-prompt",
+ prompt_version: null,
+ tool_definitions: { search: '{"description": "Search"}' },
+ tool_calls: ['{"name": "search"}'],
+ tool_call_names: ["search"],
+ usage_details: { input: 100, output: 50 },
+ cost_details: { total: 0.01 },
+ provided_usage_details: {},
+ provided_cost_details: {},
+ experiment_id: "exp-123",
+ experiment_name: "test-experiment",
+ experiment_description: "A test",
+ experiment_dataset_id: "dataset-123",
+ experiment_item_id: "item-123",
+ experiment_item_expected_output: "expected output",
+ input: '{"prompt": "Hello"}',
+ output: '{"response": "World"}',
+ metadata: { key: "value" },
+ };
+
+ it("should parse a valid observation", () => {
+ const result = observationForEvalSchema.parse(validObservation);
+ expect(result).toEqual(validObservation);
+ });
+
+ it("should accept null for nullable fields", () => {
+ const observationWithNulls: ObservationForEval = {
+ ...validObservation,
+ parent_span_id: null,
+ status_message: null,
+ version: null,
+ trace_name: null,
+ user_id: null,
+ session_id: null,
+ release: null,
+ provided_model_name: null,
+ model_parameters: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ experiment_id: null,
+ experiment_name: null,
+ experiment_description: null,
+ experiment_dataset_id: null,
+ experiment_item_id: null,
+ experiment_item_expected_output: null,
+ input: null,
+ output: null,
+ };
+
+ const result = observationForEvalSchema.parse(observationWithNulls);
+ expect(result.user_id).toBeNull();
+ expect(result.provided_model_name).toBeNull();
+ expect(result.input).toBeNull();
+ });
+
+ it("should accept empty arrays for array fields", () => {
+ const observationWithEmptyArrays = {
+ ...validObservation,
+ tags: [],
+ tool_calls: [],
+ tool_call_names: [],
+ };
+
+ const result = observationForEvalSchema.parse(observationWithEmptyArrays);
+ expect(result.tags).toEqual([]);
+ expect(result.tool_calls).toEqual([]);
+ expect(result.tool_call_names).toEqual([]);
+ });
+
+ it("should accept empty objects for record fields", () => {
+ const observationWithEmptyObjects = {
+ ...validObservation,
+ tool_definitions: {},
+ usage_details: {},
+ cost_details: {},
+ metadata: {},
+ };
+
+ const result = observationForEvalSchema.parse(
+ observationWithEmptyObjects,
+ );
+ expect(result.tool_definitions).toEqual({});
+ expect(result.metadata).toEqual({});
+ });
+
+ it("should fail for missing required fields", () => {
+ const invalidObservation = {
+ span_id: "obs-123",
+ // Missing other required fields
+ };
+
+ expect(() =>
+ observationForEvalSchema.parse(invalidObservation),
+ ).toThrow();
+ });
+ });
+
+ describe("filter columns alignment", () => {
+ it("should have all filter column IDs present in schema", () => {
+ const schemaKeys = Object.keys(observationForEvalSchema.shape);
+
+ for (const column of observationEvalFilterColumns) {
+ expect(schemaKeys).toContain(column.id);
+ }
+ });
+
+ it("should include expected filter columns", () => {
+ const columnIds = observationEvalFilterColumns.map((c) => c.id);
+
+ // Observation properties
+ expect(columnIds).toContain("type");
+ expect(columnIds).toContain("name");
+ expect(columnIds).toContain("environment");
+ expect(columnIds).toContain("level");
+ expect(columnIds).toContain("version");
+
+ // Trace-level properties (snake_case)
+ expect(columnIds).toContain("trace_name");
+ expect(columnIds).toContain("user_id");
+ expect(columnIds).toContain("session_id");
+ expect(columnIds).toContain("tags");
+ expect(columnIds).toContain("release");
+
+ expect(columnIds).toContain("experiment_dataset_id");
+
+ // Metadata
+ expect(columnIds).toContain("metadata");
+ });
+ });
+
+ describe("variable columns alignment", () => {
+ it("should have all variable column IDs present in schema", () => {
+ const schemaKeys = Object.keys(observationForEvalSchema.shape);
+
+ for (const column of observationEvalVariableColumns) {
+ expect(schemaKeys).toContain(column.id);
+ }
+ });
+
+ it("should include expected variable columns", () => {
+ const columnIds = observationEvalVariableColumns.map((c) => c.id);
+
+ // Primary data fields
+ expect(columnIds).toContain("input");
+ expect(columnIds).toContain("output");
+ expect(columnIds).toContain("metadata");
+ expect(columnIds).toContain("experiment_item_expected_output");
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts
new file mode 100644
index 0000000000..108a3d76e7
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts
@@ -0,0 +1,381 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { scheduleObservationEvals } from "../scheduleObservationEvals";
+import {
+ type ObservationForEval,
+ type ObservationEvalConfig,
+ type ObservationEvalSchedulerDeps,
+} from "../types";
+import { type Prisma } from "@langfuse/shared/src/db";
+import { EvalTargetObject, JobExecutionStatus } from "@langfuse/shared";
+import { createW3CTraceId } from "../../../utils";
+
+describe("scheduleObservationEvals", () => {
+ const createMockObservation = (
+ overrides: Partial<ObservationForEval> = {},
+ ): ObservationForEval => ({
+ // Core identifiers (snake_case)
+ span_id: "obs-123",
+ trace_id: "trace-456",
+ project_id: "project-789",
+ parent_span_id: null,
+
+ // Observation properties
+ type: "GENERATION",
+ name: "chat-completion",
+ environment: "production",
+ level: "DEFAULT",
+ status_message: null,
+ version: "v1.0",
+
+ // Trace-level properties
+ trace_name: "my-trace",
+ user_id: "user-abc",
+ session_id: "session-xyz",
+ tags: ["tag1", "tag2"],
+ release: "v2.0.0",
+
+ // Model properties
+ provided_model_name: "gpt-4",
+ model_parameters: '{"temperature": 0.7}',
+
+ // Prompt properties
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+
+ // Tool call properties
+ tool_definitions: {},
+ tool_calls: [],
+ tool_call_names: [],
+
+ // Usage & Cost
+ usage_details: { input: 100, output: 50 },
+ cost_details: {},
+ provided_usage_details: {},
+ provided_cost_details: {},
+
+ // Experiment properties
+ experiment_id: null,
+ experiment_name: null,
+ experiment_description: null,
+ experiment_dataset_id: null,
+ experiment_item_id: null,
+ experiment_item_expected_output: null,
+
+ // Data fields
+ input: '{"prompt": "Hello"}',
+ output: '{"response": "World"}',
+ metadata: { key1: "value1" },
+ ...overrides,
+ });
+
+ const createMockConfig = (
+ overrides: Partial<ObservationEvalConfig> = {},
+ ): ObservationEvalConfig => ({
+ id: "config-1",
+ projectId: "project-789",
+ filter: [],
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ evalTemplateId: "template-1",
+ scoreName: "quality",
+ variableMapping: [],
+ targetObject: EvalTargetObject.EVENT,
+ delay: 0,
+ ...overrides,
+ });
+
+ const createMockSchedulerDeps = (): ObservationEvalSchedulerDeps => ({
+ upsertJobExecution: vi.fn().mockResolvedValue({ id: "job-exec-1" }),
+ uploadObservationToS3: vi
+ .fn()
+ .mockResolvedValue("observations/project-789/obs-123.json"),
+ enqueueEvalJob: vi.fn().mockResolvedValue(undefined),
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("empty configs", () => {
+ it("should return early when configs array is empty", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.uploadObservationToS3).not.toHaveBeenCalled();
+ expect(schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("S3 upload", () => {
+ it("should upload observation to S3 once when configs exist", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [createMockConfig({ id: "config-1" })],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.uploadObservationToS3).toHaveBeenCalledTimes(1);
+ expect(schedulerDeps.uploadObservationToS3).toHaveBeenCalledWith({
+ projectId: "project-789",
+ observationId: "obs-123",
+ data: observation,
+ });
+ });
+
+ it("should upload only once even with multiple configs", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({ id: "config-1" }),
+ createMockConfig({ id: "config-2" }),
+ createMockConfig({ id: "config-3" }),
+ ],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.uploadObservationToS3).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("filter evaluation", () => {
+ it("should skip config and S3 upload when filter does not match", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation({ type: "span" });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"],
+ },
+ ],
+ }),
+ ],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.uploadObservationToS3).not.toHaveBeenCalled();
+ expect(schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).not.toHaveBeenCalled();
+ });
+
+ it("should process config when filter matches", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation({ type: "generation" });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"],
+ },
+ ],
+ }),
+ ],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalled();
+ });
+
+ it("should process config when filter is empty (matches all)", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [createMockConfig({ filter: [] })],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalled();
+ });
+ });
+
+ describe("sampling", () => {
+ it("should skip config and S3 upload when sampled out (sampling rate 0)", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({
+ sampling: { toNumber: () => 0 } as unknown as Prisma.Decimal,
+ }),
+ ],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.uploadObservationToS3).not.toHaveBeenCalled();
+ expect(schedulerDeps.upsertJobExecution).not.toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).not.toHaveBeenCalled();
+ });
+
+ it("should process config when sampling rate is 1 (always sample)", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({
+ sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,
+ }),
+ ],
+ schedulerDeps,
+ });
+
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalled();
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalled();
+ });
+ });
+
+ describe("job creation and enqueuing", () => {
+ it("should create job execution with correct data", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation();
+ const config = createMockConfig();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps,
+ });
+
+ const expectedJobExecutionId = createW3CTraceId(
+ `${config.id}:${observation.span_id}`,
+ );
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalledWith({
+ id: expectedJobExecutionId,
+ projectId: "project-789",
+ jobConfigurationId: "config-1",
+ jobInputTraceId: "trace-456",
+ jobInputObservationId: "obs-123",
+ jobTemplateId: config.evalTemplateId,
+ status: JobExecutionStatus.PENDING,
+ });
+ });
+
+ it("should enqueue job with correct parameters", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ schedulerDeps.uploadObservationToS3 = vi
+ .fn()
+ .mockResolvedValue("observations/project-789/obs-123.json");
+ const observation = createMockObservation();
+ const config = createMockConfig();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [config],
+ schedulerDeps,
+ });
+
+ const expectedJobExecutionId = createW3CTraceId(
+ `${config.id}:${observation.span_id}`,
+ );
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalledWith({
+ jobExecutionId: expectedJobExecutionId,
+ projectId: "project-789",
+ observationS3Path: "observations/project-789/obs-123.json",
+ delay: 0,
+ });
+ });
+ });
+
+ describe("multiple configs", () => {
+ it("should process multiple matching configs independently", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ schedulerDeps.upsertJobExecution = vi
+ .fn()
+ .mockResolvedValueOnce({ id: "job-exec-1" })
+ .mockResolvedValueOnce({ id: "job-exec-2" })
+ .mockResolvedValueOnce({ id: "job-exec-3" });
+ const observation = createMockObservation();
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({ id: "config-1" }),
+ createMockConfig({ id: "config-2" }),
+ createMockConfig({ id: "config-3" }),
+ ],
+ schedulerDeps,
+ });
+
+ // S3 upload only once
+ expect(schedulerDeps.uploadObservationToS3).toHaveBeenCalledTimes(1);
+
+ // Job creation for each config
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalledTimes(3);
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalledTimes(3);
+ });
+
+ it("should skip only non-matching configs", async () => {
+ const schedulerDeps = createMockSchedulerDeps();
+ const observation = createMockObservation({ type: "generation" });
+
+ await scheduleObservationEvals({
+ observation,
+ configs: [
+ createMockConfig({
+ id: "config-1",
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["generation"],
+ },
+ ],
+ }),
+ createMockConfig({
+ id: "config-2",
+ filter: [
+ {
+ column: "type",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["span"],
+ },
+ ],
+ }),
+ createMockConfig({
+ id: "config-3",
+ filter: [],
+ }),
+ ],
+ schedulerDeps,
+ });
+
+ // Should create jobs for config-1 and config-3, but not config-2
+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalledTimes(2);
+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.ts b/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.ts
new file mode 100644
index 0000000000..2750960715
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.ts
@@ -0,0 +1,129 @@
+import { describe, it, expect } from "vitest";
+import { shouldSampleObservation } from "../shouldSampleObservation";
+
+describe("shouldSampleObservation", () => {
+ describe("edge cases", () => {
+ it("should always return true when samplingRate is 1", () => {
+ // Even with random values near the boundary, sampling rate 1 should always pass
+ expect(shouldSampleObservation({ samplingRate: 1, randomValue: 0 })).toBe(
+ true,
+ );
+ expect(
+ shouldSampleObservation({ samplingRate: 1, randomValue: 0.5 }),
+ ).toBe(true);
+ expect(
+ shouldSampleObservation({ samplingRate: 1, randomValue: 0.999 }),
+ ).toBe(true);
+ });
+
+ it("should always return true when samplingRate is greater than 1", () => {
+ // Values > 1 should be treated as 100% sampling
+ expect(
+ shouldSampleObservation({ samplingRate: 1.5, randomValue: 0.999 }),
+ ).toBe(true);
+ expect(
+ shouldSampleObservation({ samplingRate: 100, randomValue: 0.999 }),
+ ).toBe(true);
+ });
+
+ it("should always return false when samplingRate is 0", () => {
+ expect(shouldSampleObservation({ samplingRate: 0, randomValue: 0 })).toBe(
+ false,
+ );
+ expect(
+ shouldSampleObservation({ samplingRate: 0, randomValue: 0.5 }),
+ ).toBe(false);
+ expect(
+ shouldSampleObservation({ samplingRate: 0, randomValue: 0.001 }),
+ ).toBe(false);
+ });
+
+ it("should always return false when samplingRate is negative", () => {
+ // Negative values should be treated as 0% sampling
+ expect(
+ shouldSampleObservation({ samplingRate: -0.5, randomValue: 0 }),
+ ).toBe(false);
+ expect(
+ shouldSampleObservation({ samplingRate: -1, randomValue: 0 }),
+ ).toBe(false);
+ });
+ });
+
+ describe("sampling behavior", () => {
+ it("should return true when randomValue is less than samplingRate", () => {
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.3 }),
+ ).toBe(true);
+ expect(
+ shouldSampleObservation({ samplingRate: 0.8, randomValue: 0.7 }),
+ ).toBe(true);
+ expect(
+ shouldSampleObservation({ samplingRate: 0.1, randomValue: 0.05 }),
+ ).toBe(true);
+ });
+
+ it("should return false when randomValue is greater than or equal to samplingRate", () => {
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.7 }),
+ ).toBe(false);
+ expect(
+ shouldSampleObservation({ samplingRate: 0.3, randomValue: 0.5 }),
+ ).toBe(false);
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5 }),
+ ).toBe(false);
+ });
+
+ it("should handle boundary values correctly", () => {
+ // Just below the threshold - should pass
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.4999 }),
+ ).toBe(true);
+
+ // At the threshold - should not pass (using strict less than)
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5 }),
+ ).toBe(false);
+
+ // Just above the threshold - should not pass
+ expect(
+ shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5001 }),
+ ).toBe(false);
+ });
+ });
+
+ describe("default random value", () => {
+ it("should use Math.random when randomValue is not provided", () => {
+ // Run multiple times to verify it uses randomness
+ // With sampling rate of 1, should always return true
+ for (let i = 0; i < 10; i++) {
+ expect(shouldSampleObservation({ samplingRate: 1 })).toBe(true);
+ }
+
+ // With sampling rate of 0, should always return false
+ for (let i = 0; i < 10; i++) {
+ expect(shouldSampleObservation({ samplingRate: 0 })).toBe(false);
+ }
+ });
+ });
+
+ describe("probabilistic correctness", () => {
+ it("should sample approximately the correct percentage over many iterations", () => {
+ const samplingRate = 0.3;
+ const iterations = 1000;
+ let sampledCount = 0;
+
+ // Use deterministic "random" values spread across [0, 1)
+ for (let i = 0; i < iterations; i++) {
+ const randomValue = i / iterations;
+ if (shouldSampleObservation({ samplingRate, randomValue })) {
+ sampledCount++;
+ }
+ }
+
+ // With evenly distributed random values, exactly 30% should be sampled
+ // (all values from 0 to 0.299 will pass, which is 300 values)
+ expect(sampledCount).toBe(Math.floor(iterations * samplingRate));
+ });
+ });
+});
diff --git a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts
new file mode 100644
index 0000000000..e3b30236d8
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts
@@ -0,0 +1,83 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ LLMAsJudgeExecutionQueue,
+ QueueJobs,
+ QueueName,
+} from "@langfuse/shared/src/server";
+import { env } from "../../../env";
+import { getEvalS3StorageClient } from "../s3StorageClient";
+import { type ObservationEvalSchedulerDeps } from "./types";
+
+/**
+ * Creates production dependencies for the observation eval scheduler.
+ * Wires up real implementations for Prisma, S3, and BullMQ.
+ */
+export function createObservationEvalSchedulerDeps(): ObservationEvalSchedulerDeps {
+ return {
+ upsertJobExecution: async (params) => {
+ const {
+ id,
+ projectId,
+ jobConfigurationId,
+ jobInputTraceId,
+ jobInputObservationId,
+ jobTemplateId,
+ status,
+ } = params;
+
+ const jobExecution = await prisma.jobExecution.upsert({
+ where: {
+ id,
+ projectId,
+ },
+ create: {
+ id,
+ projectId,
+ jobConfigurationId,
+ jobInputTraceId,
+ jobInputObservationId,
+ jobTemplateId,
+ status,
+ },
+ update: {
+ status,
+ },
+ });
+
+ return { id: jobExecution.id };
+ },
+
+ uploadObservationToS3: async (params) => {
+ const path = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}evals/${params.projectId}/observations/${params.observationId}.json`;
+ const s3Client = getEvalS3StorageClient();
+
+ await s3Client.uploadJson(path, params.data);
+
+ return path;
+ },
+
+ enqueueEvalJob: async (params) => {
+ const queue = LLMAsJudgeExecutionQueue.getInstance();
+ if (!queue) {
+ throw new Error("LLMAsJudgeExecutionQueue is not initialized");
+ }
+
+ await queue.add(
+ QueueName.LLMAsJudgeExecution,
+ {
+ name: QueueJobs.LLMAsJudgeExecution,
+ id: params.jobExecutionId,
+ timestamp: new Date(),
+ payload: {
+ projectId: params.projectId,
+ jobExecutionId: params.jobExecutionId,
+ observationS3Path: params.observationS3Path,
+ },
+ },
+ {
+ delay: params.delay,
+ },
+ );
+ },
+ };
+}
diff --git a/worker/src/features/evaluation/observationEval/extractObservationVariables.ts b/worker/src/features/evaluation/observationEval/extractObservationVariables.ts
new file mode 100644
index 0000000000..fe69c6334a
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/extractObservationVariables.ts
@@ -0,0 +1,111 @@
+import { type ObservationForEval } from "./types";
+import { type ObservationVariableMapping } from "@langfuse/shared";
+import { JSONPath } from "jsonpath-plus";
+import { logger } from "@langfuse/shared/src/server";
+
+/**
+ * Extracted variable from observation data for LLM-as-a-judge evaluation.
+ */
+export interface ExtractedVariable {
+ var: string;
+ value: string;
+ environment?: string;
+}
+
+interface ExtractVariablesParams {
+ observation: ObservationForEval;
+ variableMapping: ObservationVariableMapping[];
+}
+
+/**
+ * Extracts variable values from an observation based on the variable mapping.
+ *
+ * For each mapping:
+ * 1. Gets the value from the observation based on selectedColumnId (direct property access)
+ * 2. Optionally applies JSON selector if provided
+ * 3. Returns an array of extracted variables compatible with executeLLMAsJudgeEvaluation()
+ *
+ * Column IDs are typed as keyof ObservationForEval (see observationEvalVariableColumns),
+ * ensuring compile-time safety when adding new columns.
+ *
+ * Note: Environment is passed directly to executeLLMAsJudgeEvaluation() by the caller,
+ * not embedded in variables.
+ */
+export function extractObservationVariables(
+ params: ExtractVariablesParams,
+): ExtractedVariable[] {
+ const { observation, variableMapping } = params;
+ const variables: ExtractedVariable[] = [];
+
+ for (const mapping of variableMapping) {
+ // Direct property access - columnId is typed as keyof ObservationForEval
+ const rawValue =
+ observation[mapping.selectedColumnId as keyof ObservationForEval];
+
+ const extractedValue = mapping.jsonSelector
+ ? applyJsonSelector({ value: rawValue, selector: mapping.jsonSelector })
+ : rawValue;
+
+ variables.push({
+ var: mapping.templateVariable,
+ value: parseUnknownToString(extractedValue),
+ });
+ }
+
+ return variables;
+}
+
+interface ApplyJsonSelectorParams {
+ value: unknown;
+ selector: string;
+}
+
+/**
+ * Applies a JSONPath selector to extract a nested value.
+ * Falls back to the original value if JSON parsing fails.
+ */
+function applyJsonSelector(params: ApplyJsonSelectorParams): unknown {
+ const { value, selector } = params;
+
+ if (value === null || value === undefined) {
+ return value;
+ }
+
+ try {
+ const jsonValue = typeof value === "string" ? JSON.parse(value) : value;
+
+ return JSONPath({
+ path: selector,
+ json: jsonValue,
+ });
+ } catch (error) {
+ logger.debug(
+ `Error applying JSON selector "${selector}". Falling back to original value.`,
+ { error },
+ );
+ return value;
+ }
+}
+
+/**
+ * Converts an unknown value to a string for use in prompt templates.
+ */
+function parseUnknownToString(value: unknown): string {
+ if (value === null || value === undefined) {
+ return "";
+ }
+
+ if (
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean"
+ ) {
+ return value.toString();
+ }
+
+ if (typeof value === "object") {
+ return JSON.stringify(value);
+ }
+
+ return "";
+}
diff --git a/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts b/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts
new file mode 100644
index 0000000000..23ea8be834
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts
@@ -0,0 +1,69 @@
+import { EvalTargetObject } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ logger,
+ hasNoEvalConfigsCache,
+ setNoEvalConfigsCache,
+} from "@langfuse/shared/src/server";
+import { type ObservationEvalConfig } from "./types";
+
+/**
+ * Fetches active observation eval configs for a project.
+ *
+ * Uses a cache to avoid unnecessary database queries:
+ * - If cached as "no configs", returns empty array immediately
+ * - If cache miss, queries database and caches result if empty
+ *
+ * @param projectId - The project ID to fetch configs for
+ * @returns Array of observation eval configs (empty if none exist)
+ */
+export async function fetchObservationEvalConfigs(
+ projectId: string,
+): Promise<ObservationEvalConfig[]> {
+ // Check cache first
+ const hasNoConfigs = await hasNoEvalConfigsCache(projectId, "eventBased");
+ if (hasNoConfigs) {
+ logger.debug(
+ `Skipping observation eval config fetch - no configs cached for project ${projectId}`,
+ );
+
+ return [];
+ }
+
+ // Fetch configs from database
+ const configs = await prisma.jobConfiguration.findMany({
+ where: {
+ projectId,
+ targetObject: {
+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],
+ },
+ status: "ACTIVE",
+ },
+ select: {
+ id: true,
+ projectId: true,
+ filter: true,
+ sampling: true,
+ evalTemplateId: true,
+ scoreName: true,
+ targetObject: true,
+ variableMapping: true,
+ },
+ });
+
+ // Cache if no configs found
+ if (configs.length === 0) {
+ logger.debug(
+ `No observation eval configs found for project ${projectId}, caching`,
+ );
+ await setNoEvalConfigsCache(projectId, "eventBased");
+
+ return [];
+ }
+
+ logger.debug(
+ `Found ${configs.length} observation eval configs for project ${projectId}`,
+ );
+
+ return configs as ObservationEvalConfig[];
+}
diff --git a/worker/src/features/evaluation/observationEval/index.ts b/worker/src/features/evaluation/observationEval/index.ts
new file mode 100644
index 0000000000..c6b75f2ed1
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/index.ts
@@ -0,0 +1,13 @@
+export { scheduleObservationEvals } from "./scheduleObservationEvals";
+export { fetchObservationEvalConfigs } from "./fetchObservationEvalConfigs";
+export { createObservationEvalSchedulerDeps } from "./createSchedulerDeps";
+export {
+ processObservationEval,
+ createObservationEvalProcessorDeps,
+ type ObservationEvalProcessorDeps,
+} from "./observationEvalProcessor";
+export type {
+ ObservationForEval,
+ ObservationEvalConfig,
+ ObservationEvalSchedulerDeps,
+} from "./types";
diff --git a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
new file mode 100644
index 0000000000..66f7525d63
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
@@ -0,0 +1,147 @@
+import { z } from "zod/v4";
+import {
+ DEFAULT_TRACE_ENVIRONMENT,
+ LLMAsJudgeExecutionEventSchema,
+ logger,
+} from "@langfuse/shared/src/server";
+import {
+ observationForEvalSchema,
+ observationVariableMappingList,
+ type ObservationVariableMapping,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { UnrecoverableError } from "../../../errors/UnrecoverableError";
+import { extractObservationVariables } from "./extractObservationVariables";
+import { executeLLMAsJudgeEvaluation } from "../evalService";
+import { getEvalS3StorageClient } from "../s3StorageClient";
+import { type ObservationForEval } from "./types";
+
+/**
+ * Dependencies for processing observation evals.
+ * Allows S3 operations to be injected for testability.
+ */
+export interface ObservationEvalProcessorDeps {
+ downloadObservationFromS3: (path: string) => Promise<string>;
+}
+
+/**
+ * Creates production dependencies for the observation eval processor.
+ */
+export function createObservationEvalProcessorDeps(): ObservationEvalProcessorDeps {
+ return {
+ downloadObservationFromS3: async (path: string) => {
+ const s3Client = getEvalS3StorageClient();
+
+ return s3Client.download(path);
+ },
+ };
+}
+
+/**
+ * Processes an observation-level LLM-as-a-judge evaluation job.
+ *
+ * This function:
+ * 1. Fetches and validates job execution, config, and template
+ * 2. Downloads observation data from S3 (stored during scheduling)
+ * 3. Extracts variables from the observation
+ * 4. Calls the shared executeLLMAsJudgeEvaluation() for LLM call and score persistence
+ */
+export async function processObservationEval({
+ event,
+ deps = createObservationEvalProcessorDeps(),
+}: {
+ event: z.infer<typeof LLMAsJudgeExecutionEventSchema>;
+ deps?: ObservationEvalProcessorDeps;
+}): Promise<void> {
+ logger.debug(
+ `Processing observation eval job ${event.jobExecutionId} for project ${event.projectId}`,
+ );
+
+ // Fetch job execution
+ const job = await prisma.jobExecution.findFirst({
+ where: {
+ id: event.jobExecutionId,
+ projectId: event.projectId,
+ },
+ });
+
+ if (!job) {
+ logger.info(
+ `Job execution ${event.jobExecutionId} not found. It may have been deleted.`,
+ );
+
+ return;
+ }
+
+ // Fetch job configuration
+ const evalJobConfig = await prisma.jobConfiguration.findFirst({
+ where: {
+ id: job.jobConfigurationId,
+ projectId: event.projectId,
+ },
+ include: {
+ evalTemplate: true,
+ },
+ });
+
+ if (!evalJobConfig || !evalJobConfig.evalTemplate) {
+ throw new UnrecoverableError(
+ `Job configuration or template not found for job ${job.id}`,
+ );
+ }
+
+ // Download observation data from S3
+ let observationData: ObservationForEval;
+ let downloadedString: string;
+
+ try {
+ downloadedString = await deps.downloadObservationFromS3(
+ event.observationS3Path,
+ );
+ } catch (e) {
+ // S3 download failures are retryable (network issues, temporary unavailability)
+ throw new Error(
+ `Failed to download observation from S3 at ${event.observationS3Path}: ${e}`,
+ );
+ }
+
+ // Parse and validate the downloaded data - these are permanent failures
+ try {
+ const parsedJson = JSON.parse(downloadedString);
+ observationData = observationForEvalSchema.parse(parsedJson);
+ } catch (e) {
+ // JSON parse errors are permanent - the data won't change on retry
+ throw new UnrecoverableError(
+ `Invalid observation data from S3 at ${event.observationS3Path}: invalid JSON - ${e}`,
+ );
+ }
+
+ logger.debug(
+ `Downloaded observation data for job ${job.id}: span_id=${observationData.span_id}`,
+ );
+
+ // Extract variables from observation
+ const parsedVariableMapping = observationVariableMappingList.parse(
+ evalJobConfig.variableMapping,
+ ) as ObservationVariableMapping[];
+
+ const extractedVariables = extractObservationVariables({
+ observation: observationData,
+ variableMapping: parsedVariableMapping,
+ });
+
+ logger.debug(
+ `Extracted ${extractedVariables.length} variables for job ${job.id}`,
+ );
+
+ // Execute the shared LLM-as-a-judge evaluation
+ await executeLLMAsJudgeEvaluation({
+ projectId: event.projectId,
+ jobExecutionId: event.jobExecutionId,
+ job,
+ config: evalJobConfig,
+ template: evalJobConfig.evalTemplate,
+ extractedVariables,
+ environment: observationData.environment ?? DEFAULT_TRACE_ENVIRONMENT,
+ });
+}
diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
new file mode 100644
index 0000000000..a3755b7a6f
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
@@ -0,0 +1,177 @@
+import {
+ type ObservationForEval,
+ type ObservationEvalConfig,
+ type ObservationEvalSchedulerDeps,
+} from "./types";
+import { shouldSampleObservation } from "./shouldSampleObservation";
+import { InMemoryFilterService, logger } from "@langfuse/shared/src/server";
+import {
+ EvalTargetObject,
+ JobExecutionStatus,
+ type FilterState,
+} from "@langfuse/shared";
+import { createW3CTraceId } from "../../utils";
+
+interface ScheduleObservationEvalsParams {
+ observation: ObservationForEval;
+ configs: ObservationEvalConfig[];
+ schedulerDeps: ObservationEvalSchedulerDeps;
+}
+
+/**
+ * Schedule observation evals for a given observation.
+ *
+ * This function receives pre-fetched configs (already filtered by targetObject: "event" or "experiment"
+ * and project). It evaluates each config's filter and sampling against the observation,
+ * checks for deduplication, and creates job executions for matching configs.
+ *
+ * The observation is uploaded to S3 once (not per config) for efficiency.
+ *
+ * @param params.observation - The ObservationForEval (converted from processToEvent() or ClickHouse)
+ * @param params.configs - Pre-fetched observation eval configs for this project
+ * @param params.schedulerDeps - Dependencies for scheduling (S3, job execution, queue)
+ */
+export async function scheduleObservationEvals(
+ params: ScheduleObservationEvalsParams,
+): Promise<void> {
+ const { observation, configs, schedulerDeps } = params;
+
+ // Early return if no configs
+ if (configs.length === 0) {
+ return;
+ }
+
+ // Filter configs that match this observation (filter + sampling)
+ // This is done before S3 upload to avoid unnecessary uploads
+ const matchingConfigs = configs.filter((config) => {
+ // Check filter
+ const isTargeted = evaluateFilter(observation, config);
+ if (!isTargeted) {
+ logger.debug("Observation does not match eval config filter", {
+ configId: config.id,
+ observationId: observation.span_id,
+ });
+
+ return false;
+ }
+
+ // Check sampling
+ const samplingRate = config.sampling.toNumber();
+ if (!shouldSampleObservation({ samplingRate })) {
+ logger.debug("Observation sampled out for eval config", {
+ configId: config.id,
+ observationId: observation.span_id,
+ samplingRate,
+ });
+
+ return false;
+ }
+
+ return true;
+ });
+
+ // Early return if no configs match - no S3 upload needed
+ if (matchingConfigs.length === 0) return;
+
+ // Upload observation to S3 once
+ const observationS3Path = await schedulerDeps.uploadObservationToS3({
+ projectId: observation.project_id,
+ observationId: observation.span_id,
+ data: observation,
+ });
+
+ // Process each matching config
+ await Promise.all(
+ matchingConfigs.map((matchingConfig) =>
+ processMatchingConfig({
+ observation,
+ matchingConfig,
+ observationS3Path,
+ schedulerDeps,
+ }).catch((error) => {
+ logger.error("Failed to process observation eval config", {
+ configId: matchingConfig.id,
+ observationId: observation.span_id,
+ projectId: observation.project_id,
+ error,
+ });
+ }),
+ ),
+ );
+}
+
+interface ProcessConfigParams {
+ observation: ObservationForEval;
+ matchingConfig: ObservationEvalConfig;
+ observationS3Path: string;
+ schedulerDeps: ObservationEvalSchedulerDeps;
+}
+
+async function processMatchingConfig(
+ params: ProcessConfigParams,
+): Promise<void> {
+ const { observation, matchingConfig, observationS3Path, schedulerDeps } =
+ params;
+
+ const jobExecutionId = createW3CTraceId(
+ `${matchingConfig.id}:${observation.span_id}`,
+ );
+
+ // Create job execution
+ await schedulerDeps.upsertJobExecution({
+ id: jobExecutionId,
+ projectId: observation.project_id,
+ jobConfigurationId: matchingConfig.id,
+ jobInputTraceId: observation.trace_id,
+ jobInputObservationId: observation.span_id,
+ jobTemplateId: matchingConfig.evalTemplateId,
+ status: JobExecutionStatus.PENDING,
+ });
+
+ // Enqueue eval job
+ await schedulerDeps.enqueueEvalJob({
+ jobExecutionId,
+ projectId: observation.project_id,
+ observationS3Path,
+ delay: 0,
+ });
+
+ logger.debug("Scheduled observation eval job", {
+ configId: matchingConfig.id,
+ observationId: observation.span_id,
+ jobExecutionId,
+ });
+}
+
+/**
+ * Evaluate filter conditions against observation.
+ * Returns true if observation matches all filter conditions (or filter is empty).
+ */
+function evaluateFilter(
+ observation: ObservationForEval,
+ config: ObservationEvalConfig,
+): boolean {
+ const filterConditions = config.filter as FilterState;
+ const isExperimentConfig =
+ config.targetObject === EvalTargetObject.EXPERIMENT;
+ const isExperimentRoot =
+ observation.span_id === observation.experiment_item_root_span_id;
+
+ // Empty filter matches all (for filter purposes)
+ const isEmptyFilter =
+ !filterConditions ||
+ !Array.isArray(filterConditions) ||
+ filterConditions.length === 0;
+
+ // Use InMemoryFilterService to evaluate filter if there are conditions
+ const isFilterMatch = isEmptyFilter
+ ? true
+ : InMemoryFilterService.evaluateFilter(
+ observation,
+ filterConditions,
+ (obs, columnId) => obs[columnId as keyof ObservationForEval],
+ );
+
+ // For experiment configs, must also match experiment root span
+ return isExperimentConfig ? isFilterMatch && isExperimentRoot : isFilterMatch;
+}
diff --git a/worker/src/features/evaluation/observationEval/shouldSampleObservation.ts b/worker/src/features/evaluation/observationEval/shouldSampleObservation.ts
new file mode 100644
index 0000000000..3a54dfbd90
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/shouldSampleObservation.ts
@@ -0,0 +1,22 @@
+interface ShouldSampleParams {
+ samplingRate: number;
+ randomValue?: number; // Injectable for testing
+}
+
+/**
+ * Determines whether an observation should be sampled for evaluation.
+ *
+ * @param params.samplingRate - A number between 0 and 1 representing the probability
+ * of sampling. Values >= 1 always sample, values <= 0 never sample.
+ * @param params.randomValue - Optional injectable random value for testing.
+ * If not provided, Math.random() is used.
+ * @returns true if the observation should be sampled, false otherwise.
+ */
+export function shouldSampleObservation(params: ShouldSampleParams): boolean {
+ const { samplingRate, randomValue = Math.random() } = params;
+
+ if (samplingRate >= 1) return true;
+ if (samplingRate <= 0) return false;
+
+ return randomValue < samplingRate;
+}
diff --git a/worker/src/features/evaluation/observationEval/types.ts b/worker/src/features/evaluation/observationEval/types.ts
new file mode 100644
index 0000000000..249ce8d087
--- /dev/null
+++ b/worker/src/features/evaluation/observationEval/types.ts
@@ -0,0 +1,64 @@
+import { JobConfiguration, JobExecutionStatus } from "@langfuse/shared/src/db";
+
+/**
+ * Re-export ObservationForEval as the canonical observation type for eval operations.
+ * This type is used for both filtering and variable extraction.
+ *
+ * @see packages/shared/src/features/evals/observationForEval.ts for schema definition
+ */
+export {
+ type ObservationForEval,
+ observationForEvalSchema,
+ observationEvalFilterColumns,
+ observationEvalVariableColumns,
+} from "@langfuse/shared";
+
+/**
+ * Observation eval job configuration.
+ * Represents a job configuration with targetObject: "event".
+ * Passed to the scheduler after being fetched once per batch.
+ */
+export type ObservationEvalConfig = Pick<
+ JobConfiguration,
+ | "id"
+ | "projectId"
+ | "filter"
+ | "sampling"
+ | "evalTemplateId"
+ | "scoreName"
+ | "targetObject"
+ | "variableMapping"
+ | "delay"
+>;
+
+/**
+ * Dependencies for scheduling observation evals.
+ * The scheduler receives pre-fetched configs and creates job executions.
+ */
+export interface ObservationEvalSchedulerDeps {
+ /** Create a job execution record in the database */
+ upsertJobExecution: (params: {
+ id: string;
+ projectId: string;
+ jobConfigurationId: string;
+ jobInputTraceId: string;
+ jobInputObservationId: string;
+ jobTemplateId: string | null;
+ status: JobExecutionStatus;
+ }) => Promise<{ id: string }>;
+
+ /** Upload observation data to S3 for later retrieval */
+ uploadObservationToS3: (params: {
+ projectId: string;
+ observationId: string;
+ data: Record<string, unknown>;
+ }) => Promise<string>;
+
+ /** Enqueue the eval job for execution */
+ enqueueEvalJob: (params: {
+ jobExecutionId: string;
+ projectId: string;
+ observationS3Path: string;
+ delay: number;
+ }) => Promise<void>;
+}
diff --git a/worker/src/features/evaluation/s3StorageClient.ts b/worker/src/features/evaluation/s3StorageClient.ts
new file mode 100644
index 0000000000..c9be75d010
--- /dev/null
+++ b/worker/src/features/evaluation/s3StorageClient.ts
@@ -0,0 +1,35 @@
+import {
+ StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+import { env } from "../../env";
+
+/**
+ * Singleton S3 storage client for eval operations.
+ * Used by both eval execution (score upload) and observation eval scheduling (observation upload).
+ */
+let s3StorageServiceClient: StorageService | null = null;
+
+/**
+ * Gets the singleton S3 storage client for eval operations.
+ * Creates the client on first call using environment configuration.
+ *
+ * @param bucketName - The S3 bucket name to use
+ * @returns The S3 storage service client
+ */
+export function getEvalS3StorageClient(): StorageService {
+ if (!s3StorageServiceClient) {
+ s3StorageServiceClient = StorageServiceFactory.getInstance({
+ bucketName: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ awsSse: env.LANGFUSE_S3_EVENT_UPLOAD_SSE,
+ awsSseKmsKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_SSE_KMS_KEY_ID,
+ });
+ }
+
+ return s3StorageServiceClient;
+}
diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
index 680248dbc7..b0974276ee 100644
--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts
+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
@@ -475,7 +475,7 @@ export function enrichSpansWithExperiment(
}
/**
- * Write enriched spans to the events table using IngestionService.writeEvent().
+ * Write enriched spans to the events table using IngestionService.writeEventRecord().
* Converts EnrichedSpan to EventInput format.
*/
export async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {
@@ -574,7 +574,11 @@ export async function writeEnrichedSpans(spans: EnrichedSpan[]): Promise<void> {
experimentItemMetadataValues: span.experiment_item_metadata_values,
};
- await ingestionService.writeEvent(eventInput, ""); // Empty fileKey since we're not storing raw events
+ const eventRecord = await ingestionService.createEventRecord(
+ eventInput,
+ "",
+ ); // Empty fileKey since we're not storing raw events
+ ingestionService.writeEventRecord(eventRecord);
}
logger.info(
diff --git a/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts
new file mode 100644
index 0000000000..27684fdf1d
--- /dev/null
+++ b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts
@@ -0,0 +1,392 @@
+import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";
+import { Job } from "bullmq";
+import { JobExecutionStatus } from "@prisma/client";
+import { llmAsJudgeExecutionQueueProcessor } from "../evalQueue";
+import { QueueName, type TQueueJobTypes } from "@langfuse/shared/src/server";
+import { UnrecoverableError } from "../../errors/UnrecoverableError";
+
+// Mock prisma
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ jobExecution: {
+ update: vi.fn(),
+ },
+ },
+}));
+
+// Mock processObservationEval
+vi.mock("../../features/evaluation/observationEval", () => ({
+ processObservationEval: vi.fn(),
+}));
+
+// Mock logger and span
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ traceException: vi.fn(),
+ getCurrentSpan: vi.fn().mockReturnValue({
+ setAttribute: vi.fn(),
+ }),
+ LLMAsJudgeExecutionQueue: {
+ getInstance: vi.fn().mockReturnValue({
+ add: vi.fn(),
+ }),
+ },
+ isLLMCompletionError: vi.fn(),
+ };
+});
+
+// Mock retryLLMRateLimitError
+vi.mock("../../features/utils", () => ({
+ createW3CTraceId: vi.fn().mockReturnValue("test-trace-id"),
+ retryLLMRateLimitError: vi.fn(),
+}));
+
+// Mock isUnrecoverableError
+vi.mock("../../errors/UnrecoverableError", async () => {
+ const actual = await vi.importActual("../../errors/UnrecoverableError");
+ return {
+ ...actual,
+ isUnrecoverableError: vi.fn(),
+ };
+});
+
+import { prisma } from "@langfuse/shared/src/db";
+import { processObservationEval } from "../../features/evaluation/observationEval";
+import {
+ isLLMCompletionError,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { retryLLMRateLimitError } from "../../features/utils";
+import { isUnrecoverableError } from "../../errors/UnrecoverableError";
+
+describe("llmAsJudgeExecutionQueueProcessor", () => {
+ const projectId = "test-project-123";
+ const jobExecutionId = "job-exec-456";
+ const observationS3Path = "evals/test/observation.json";
+
+ const createMockJob = (
+ overrides: Partial<TQueueJobTypes[QueueName.LLMAsJudgeExecution]> = {},
+ ): Job<TQueueJobTypes[QueueName.LLMAsJudgeExecution]> => {
+ return {
+ data: {
+ id: "queue-job-123",
+ name: "LLMAsJudgeExecution",
+ timestamp: new Date(),
+ payload: {
+ projectId,
+ jobExecutionId,
+ observationS3Path,
+ },
+ retryBaggage: { attempt: 0 },
+ ...overrides,
+ },
+ } as unknown as Job<TQueueJobTypes[QueueName.LLMAsJudgeExecution]>;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (isLLMCompletionError as Mock).mockReturnValue(false);
+ (isUnrecoverableError as Mock).mockReturnValue(false);
+ });
+
+ describe("successful processing", () => {
+ it("should process observation eval successfully and return true", async () => {
+ (processObservationEval as Mock).mockResolvedValue(undefined);
+
+ const job = createMockJob();
+ const result = await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(result).toBe(true);
+ expect(processObservationEval).toHaveBeenCalledWith({
+ event: {
+ projectId,
+ jobExecutionId,
+ observationS3Path,
+ },
+ });
+ });
+
+ it("should set span attributes for tracing", async () => {
+ const mockSpan = { setAttribute: vi.fn() };
+ const { getCurrentSpan } = await import("@langfuse/shared/src/server");
+ (getCurrentSpan as Mock).mockReturnValue(mockSpan);
+ (processObservationEval as Mock).mockResolvedValue(undefined);
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ "messaging.bullmq.job.input.jobExecutionId",
+ jobExecutionId,
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ "messaging.bullmq.job.input.projectId",
+ projectId,
+ );
+ });
+ });
+
+ describe("LLM rate limit errors (retryable)", () => {
+ it("should schedule retry and set DELAYED status for retryable LLM errors", async () => {
+ const rateLimitError = new Error("Rate limit exceeded");
+ (processObservationEval as Mock).mockRejectedValue(rateLimitError);
+ (isLLMCompletionError as Mock).mockReturnValue(true);
+ // Mark as retryable
+ (rateLimitError as unknown as { isRetryable: boolean }).isRetryable =
+ true;
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(retryLLMRateLimitError).toHaveBeenCalledWith(
+ job,
+ expect.objectContaining({
+ table: "job_executions",
+ idField: "jobExecutionId",
+ }),
+ );
+
+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({
+ where: {
+ id: jobExecutionId,
+ projectId,
+ },
+ data: expect.objectContaining({
+ status: JobExecutionStatus.DELAYED,
+ executionTraceId: "test-trace-id",
+ }),
+ });
+ });
+
+ it("should not rethrow error after scheduling retry", async () => {
+ const rateLimitError = new Error("Rate limit exceeded");
+ (rateLimitError as unknown as { isRetryable: boolean }).isRetryable =
+ true;
+ (processObservationEval as Mock).mockRejectedValue(rateLimitError);
+ (isLLMCompletionError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+
+ // Should not throw
+ await expect(
+ llmAsJudgeExecutionQueueProcessor(job),
+ ).resolves.not.toThrow();
+ });
+ });
+
+ describe("LLM completion errors (non-retryable)", () => {
+ it("should set ERROR status for non-retryable LLM errors", async () => {
+ const llmError = new Error("Invalid API key");
+ (llmError as unknown as { isRetryable: boolean }).isRetryable = false;
+ (processObservationEval as Mock).mockRejectedValue(llmError);
+ (isLLMCompletionError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({
+ where: {
+ id: jobExecutionId,
+ projectId,
+ },
+ data: expect.objectContaining({
+ status: JobExecutionStatus.ERROR,
+ endTime: expect.any(Date),
+ error: "Invalid API key",
+ executionTraceId: "test-trace-id",
+ }),
+ });
+ });
+
+ it("should not rethrow non-retryable LLM errors", async () => {
+ const llmError = new Error("Invalid API key");
+ (llmError as unknown as { isRetryable: boolean }).isRetryable = false;
+ (processObservationEval as Mock).mockRejectedValue(llmError);
+ (isLLMCompletionError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+
+ // Should not throw - error is handled gracefully
+ await expect(
+ llmAsJudgeExecutionQueueProcessor(job),
+ ).resolves.not.toThrow();
+ });
+ });
+
+ describe("UnrecoverableError handling", () => {
+ it("should set ERROR status with user-facing message for UnrecoverableError", async () => {
+ const unrecoverableError = new UnrecoverableError(
+ "Job configuration not found",
+ );
+ (processObservationEval as Mock).mockRejectedValue(unrecoverableError);
+ (isUnrecoverableError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({
+ where: {
+ id: jobExecutionId,
+ projectId,
+ },
+ data: expect.objectContaining({
+ status: JobExecutionStatus.ERROR,
+ endTime: expect.any(Date),
+ error: "Job configuration not found",
+ executionTraceId: "test-trace-id",
+ }),
+ });
+ });
+
+ it("should not rethrow UnrecoverableError", async () => {
+ const unrecoverableError = new UnrecoverableError("Config not found");
+ (processObservationEval as Mock).mockRejectedValue(unrecoverableError);
+ (isUnrecoverableError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+
+ // Should not throw
+ await expect(
+ llmAsJudgeExecutionQueueProcessor(job),
+ ).resolves.not.toThrow();
+ });
+
+ it("should not call traceException for UnrecoverableError", async () => {
+ const unrecoverableError = new UnrecoverableError("Config not found");
+ (processObservationEval as Mock).mockRejectedValue(unrecoverableError);
+ (isUnrecoverableError as Mock).mockReturnValue(true);
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(traceException).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("unexpected errors (retryable by BullMQ)", () => {
+ it("should set ERROR status with generic message for unexpected errors", async () => {
+ const unexpectedError = new Error("Database connection failed");
+ (processObservationEval as Mock).mockRejectedValue(unexpectedError);
+
+ const job = createMockJob();
+
+ // Should rethrow for BullMQ retry
+ await expect(llmAsJudgeExecutionQueueProcessor(job)).rejects.toThrow(
+ "Database connection failed",
+ );
+
+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({
+ where: {
+ id: jobExecutionId,
+ projectId,
+ },
+ data: expect.objectContaining({
+ status: JobExecutionStatus.ERROR,
+ error: "An internal error occurred",
+ executionTraceId: "test-trace-id",
+ }),
+ });
+ });
+
+ it("should call traceException for unexpected errors", async () => {
+ const unexpectedError = new Error("Unexpected failure");
+ (processObservationEval as Mock).mockRejectedValue(unexpectedError);
+
+ const job = createMockJob();
+
+ try {
+ await llmAsJudgeExecutionQueueProcessor(job);
+ } catch {
+ // Expected to throw
+ }
+
+ expect(traceException).toHaveBeenCalledWith(unexpectedError);
+ });
+
+ it("should rethrow unexpected errors for BullMQ retry", async () => {
+ const unexpectedError = new Error("Network timeout");
+ (processObservationEval as Mock).mockRejectedValue(unexpectedError);
+
+ const job = createMockJob();
+
+ await expect(llmAsJudgeExecutionQueueProcessor(job)).rejects.toThrow(
+ "Network timeout",
+ );
+ });
+ });
+
+ describe("execution trace ID", () => {
+ it("should generate deterministic trace ID from job execution ID", async () => {
+ const error = new UnrecoverableError("Test error");
+ (processObservationEval as Mock).mockRejectedValue(error);
+ (isUnrecoverableError as Mock).mockReturnValue(true);
+
+ const { createW3CTraceId } = await import("../../features/utils");
+
+ const job = createMockJob();
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(createW3CTraceId).toHaveBeenCalledWith(jobExecutionId);
+ });
+ });
+
+ describe("retry baggage tracking", () => {
+ it("should track retry attempt in span attributes", async () => {
+ const mockSpan = { setAttribute: vi.fn() };
+ const { getCurrentSpan } = await import("@langfuse/shared/src/server");
+ (getCurrentSpan as Mock).mockReturnValue(mockSpan);
+ (processObservationEval as Mock).mockResolvedValue(undefined);
+
+ const job = createMockJob({
+ retryBaggage: { attempt: 3 },
+ });
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ "messaging.bullmq.job.input.retryBaggage.attempt",
+ 3,
+ );
+ });
+
+ it("should default to 0 when retry baggage is missing", async () => {
+ const mockSpan = { setAttribute: vi.fn() };
+ const { getCurrentSpan } = await import("@langfuse/shared/src/server");
+ (getCurrentSpan as Mock).mockReturnValue(mockSpan);
+ (processObservationEval as Mock).mockResolvedValue(undefined);
+
+ const job = createMockJob();
+ delete (job.data as { retryBaggage?: unknown }).retryBaggage;
+
+ await llmAsJudgeExecutionQueueProcessor(job);
+
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ "messaging.bullmq.job.input.retryBaggage.attempt",
+ 0,
+ );
+ });
+ });
+
+ describe("null span handling", () => {
+ it("should handle null span gracefully", async () => {
+ const { getCurrentSpan } = await import("@langfuse/shared/src/server");
+ (getCurrentSpan as Mock).mockReturnValue(null);
+ (processObservationEval as Mock).mockResolvedValue(undefined);
+
+ const job = createMockJob();
+
+ // Should not throw
+ await expect(
+ llmAsJudgeExecutionQueueProcessor(job),
+ ).resolves.not.toThrow();
+ expect(processObservationEval).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/worker/src/queues/__tests__/otelToObservationForEval.test.ts b/worker/src/queues/__tests__/otelToObservationForEval.test.ts
new file mode 100644
index 0000000000..e812a452fa
--- /dev/null
+++ b/worker/src/queues/__tests__/otelToObservationForEval.test.ts
@@ -0,0 +1,1513 @@
+/**
+ * Test suite to verify that OTEL events coming through the ingestion pipeline
+ * correctly conform to the ObservationForEval schema.
+ *
+ * This is critical because:
+ * 1. OTEL events are the primary ingestion path for observation-level evals
+ * 2. If the schema validation fails, observation evals become ineffective
+ * 3. We need to ensure all typical fields are correctly mapped
+ *
+ * Flow tested:
+ * ResourceSpan -> processToEvent() -> createEventRecord() -> convertEventRecordToObservationForEval()
+ */
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { OtelIngestionProcessor } from "@langfuse/shared/src/server";
+import {
+ convertEventRecordToObservationForEval,
+ observationForEvalSchema,
+ type ObservationForEval,
+} from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { IngestionService } from "../../services/IngestionService";
+import * as clickhouseWriterExports from "../../services/ClickhouseWriter";
+
+// Mock ClickhouseWriter to avoid actual database writes
+const mockAddToClickhouseWriter = vi.fn();
+vi.mock("../../services/ClickhouseWriter", async (importOriginal) => {
+ const original = (await importOriginal()) as object;
+ return {
+ ...original,
+ ClickhouseWriter: {
+ getInstance: () => ({
+ addToQueue: mockAddToClickhouseWriter,
+ }),
+ },
+ };
+});
+
+// Mock ClickhouseClient to return empty results (no existing records)
+const mockClickhouseClient = {
+ query: async () => ({
+ json: async () => [],
+ query_id: "test-query-id",
+ response_headers: { "x-clickhouse-summary": "[]" },
+ }),
+};
+
+// Create IngestionService instance with mocked dependencies
+// Note: redis is null as we don't need it for createEventRecord
+// prisma is used for prompt/model lookups (will return null if not found)
+const ingestionService = new IngestionService(
+ null as any,
+ prisma,
+ clickhouseWriterExports.ClickhouseWriter.getInstance() as any,
+ mockClickhouseClient as any,
+);
+
+/**
+ * Helper to create protobuf-style timestamp from nanoseconds
+ */
+function createNanoTimestamp(nanoTime: bigint): {
+ low: number;
+ high: number;
+ unsigned: boolean;
+} {
+ const low = Number(nanoTime & BigInt(0xffffffff));
+ const high = Number(nanoTime >> BigInt(32));
+ return { low, high, unsigned: true };
+}
+
+/**
+ * Helper to create Buffer-style ID from hex string
+ */
+function createBufferId(hexString: string): { type: "Buffer"; data: number[] } {
+ const buffer = Buffer.from(hexString, "hex");
+ return { type: "Buffer", data: Array.from(buffer) };
+}
+
+/**
+ * Process a ResourceSpan through the full pipeline and return the ObservationForEval
+ */
+async function processOtelSpanToObservationForEval(
+ resourceSpan: any,
+ projectId = "test-project",
+): Promise<ObservationForEval[]> {
+ const processor = new OtelIngestionProcessor({ projectId });
+
+ // Process to EventInput array using the real OtelIngestionProcessor
+ const eventInputs = processor.processToEvent([resourceSpan]);
+
+ // Convert each EventInput to EventRecordInsertType using the real IngestionService
+ // Then convert to ObservationForEval
+ const results: ObservationForEval[] = [];
+ for (const eventInput of eventInputs) {
+ const eventRecord = await ingestionService.createEventRecord(
+ eventInput,
+ "test/otel/test.json",
+ );
+ const observation = convertEventRecordToObservationForEval(eventRecord);
+ results.push(observation);
+ }
+
+ return results;
+}
+
+describe("OTEL to ObservationForEval Schema Validation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("Langfuse SDK spans", () => {
+ it("should convert a Langfuse SDK generation span to valid ObservationForEval", async () => {
+ const langfuseOtelSpan = {
+ resource: {
+ attributes: [
+ { key: "telemetry.sdk.language", value: { stringValue: "python" } },
+ {
+ key: "telemetry.sdk.name",
+ value: { stringValue: "opentelemetry" },
+ },
+ { key: "telemetry.sdk.version", value: { stringValue: "1.32.0" } },
+ {
+ key: "langfuse.environment",
+ value: { stringValue: "production" },
+ },
+ { key: "langfuse.release", value: { stringValue: "0.0.1" } },
+ { key: "service.name", value: { stringValue: "test-service" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "3.0.0",
+ attributes: [
+ { key: "public_key", value: { stringValue: "pk-lf-test" } },
+ ],
+ },
+ spans: [
+ {
+ traceId: createBufferId("2cce18f7e8cd065a0b4e634eef728391"),
+ spanId: createBufferId("57f0255417974100"),
+ parentSpanId: createBufferId("dfe387fea7ef3b02"),
+ name: "test-generation",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1714488530686000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1714488530687000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.level",
+ value: { stringValue: "WARNING" },
+ },
+ {
+ key: "langfuse.observation.status_message",
+ value: { stringValue: "test status" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: {
+ stringValue: '[{"role": "user", "content": "hello"}]',
+ },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: {
+ stringValue:
+ '{"role": "assistant", "content": "hi there"}',
+ },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: { stringValue: "gpt-4" },
+ },
+ {
+ key: "langfuse.observation.prompt.name",
+ value: { stringValue: "my-prompt" },
+ },
+ {
+ key: "langfuse.observation.prompt.version",
+ value: { intValue: { low: 1, high: 0, unsigned: false } },
+ },
+ {
+ key: "langfuse.observation.usage_details",
+ value: {
+ stringValue: '{"input": 100, "output": 50}',
+ },
+ },
+ {
+ key: "langfuse.observation.cost_details",
+ value: {
+ stringValue: '{"input": 0.001, "output": 0.002}',
+ },
+ },
+ // Model parameters are extracted from gen_ai.request.* attributes
+ {
+ key: "gen_ai.request.temperature",
+ value: { doubleValue: 0.7 },
+ },
+ {
+ key: "langfuse.observation.metadata.custom_key",
+ value: { stringValue: '"custom_value"' },
+ },
+ {
+ key: "langfuse.trace.name",
+ value: { stringValue: "test-trace" },
+ },
+ { key: "user.id", value: { stringValue: "user-123" } },
+ { key: "session.id", value: { stringValue: "session-456" } },
+ {
+ key: "langfuse.version",
+ value: { stringValue: "v1.0.0" },
+ },
+ {
+ key: "langfuse.trace.tags",
+ value: {
+ arrayValue: {
+ values: [
+ { stringValue: "tag1" },
+ { stringValue: "tag2" },
+ ],
+ },
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations = await processOtelSpanToObservationForEval(
+ langfuseOtelSpan,
+ "test-project",
+ );
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance first
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate required identifiers
+ expect(obs.span_id).toBe("57f0255417974100");
+ expect(obs.trace_id).toBe("2cce18f7e8cd065a0b4e634eef728391");
+ expect(obs.project_id).toBe("test-project");
+ expect(obs.parent_span_id).toBe("dfe387fea7ef3b02");
+
+ // Validate core properties
+ expect(obs.type).toBe("GENERATION");
+ expect(obs.name).toBe("test-generation");
+ expect(obs.environment).toBe("production");
+ expect(obs.level).toBe("WARNING");
+ expect(obs.status_message).toBe("test status");
+ expect(obs.version).toBe("v1.0.0");
+
+ // Validate trace-level properties
+ expect(obs.trace_name).toBe("test-trace");
+ expect(obs.user_id).toBe("user-123");
+ expect(obs.session_id).toBe("session-456");
+ expect(obs.tags).toEqual(["tag1", "tag2"]);
+ expect(obs.release).toBe("0.0.1");
+
+ // Validate model properties
+ expect(obs.provided_model_name).toBe("gpt-4");
+ // model_parameters comes as object from createEventRecord (schema accepts both string and object)
+ expect(obs.model_parameters).toEqual({ temperature: 0.7 });
+
+ // Validate prompt properties
+ expect(obs.prompt_name).toBe("my-prompt");
+ // prompt_version comes as number from createEventRecord (schema accepts both string and number)
+ expect(obs.prompt_version).toBe(1);
+
+ // Validate usage/cost
+ expect(obs.provided_usage_details).toEqual({ input: 100, output: 50 });
+ expect(obs.provided_cost_details).toEqual({
+ input: 0.001,
+ output: 0.002,
+ });
+
+ // Validate I/O
+ expect(obs.input).toBe('[{"role": "user", "content": "hello"}]');
+ expect(obs.output).toBe('{"role": "assistant", "content": "hi there"}');
+
+ // Validate metadata is an object
+ expect(typeof obs.metadata).toBe("object");
+ });
+
+ it("should convert a Langfuse SDK span with minimal attributes", async () => {
+ const minimalOtelSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("1234567890abcdef1234567890abcdef"),
+ spanId: createBufferId("abcdef1234567890"),
+ name: "minimal-span",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1714488530686000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1714488530687000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations = await processOtelSpanToObservationForEval(
+ minimalOtelSpan,
+ "test-project",
+ );
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Required fields should be present
+ expect(obs.span_id).toBe("abcdef1234567890");
+ expect(obs.trace_id).toBe("1234567890abcdef1234567890abcdef");
+ expect(obs.project_id).toBe("test-project");
+ expect(obs.type).toBe("SPAN");
+ expect(obs.name).toBe("minimal-span");
+ expect(obs.level).toBe("DEFAULT");
+ expect(obs.environment).toBe("default");
+
+ // Nullable fields should be null or undefined (nullish)
+ expect(obs.parent_span_id).toBeFalsy();
+ expect(obs.user_id).toBeFalsy();
+ expect(obs.session_id).toBeFalsy();
+ expect(obs.provided_model_name).toBeFalsy();
+ expect(obs.input).toBeFalsy();
+ expect(obs.output).toBeFalsy();
+
+ // Array/object fields should have defaults
+ expect(obs.tags).toEqual([]);
+ expect(obs.tool_calls).toEqual([]);
+ expect(obs.tool_definitions).toEqual({});
+ });
+ });
+
+ describe("Vendor SDK spans", () => {
+ it("should convert an OpenLit span to valid ObservationForEval", async () => {
+ const openLitSpan = {
+ resource: {
+ attributes: [
+ { key: "telemetry.sdk.language", value: { stringValue: "python" } },
+ { key: "telemetry.sdk.name", value: { stringValue: "openlit" } },
+ { key: "telemetry.sdk.version", value: { stringValue: "1.27.0" } },
+ { key: "service.name", value: { stringValue: "default" } },
+ {
+ key: "deployment.environment",
+ value: { stringValue: "production" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "openlit.otel.tracing" },
+ spans: [
+ {
+ traceId: createBufferId("ea6737084c1c2984a54a3e3962d3595f"),
+ spanId: createBufferId("b904bffb20be6d7e"),
+ name: "openai.chat.completions",
+ kind: 3,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241187653000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241188827000000),
+ ),
+ attributes: [
+ { key: "gen_ai.system", value: { stringValue: "openai" } },
+ {
+ key: "gen_ai.operation.name",
+ value: { stringValue: "chat" },
+ },
+ {
+ key: "gen_ai.request.model",
+ value: { stringValue: "gpt-3.5-turbo" },
+ },
+ {
+ key: "gen_ai.usage.input_tokens",
+ value: { intValue: { low: 14, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.output_tokens",
+ value: { intValue: { low: 96, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.total_tokens",
+ value: { intValue: { low: 110, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.cost",
+ value: { doubleValue: 0.000151 },
+ },
+ ],
+ events: [
+ {
+ name: "gen_ai.content.prompt",
+ attributes: [
+ {
+ key: "gen_ai.prompt",
+ value: {
+ stringValue: "user: What is LLM Observability?",
+ },
+ },
+ ],
+ },
+ {
+ name: "gen_ai.content.completion",
+ attributes: [
+ {
+ key: "gen_ai.completion",
+ value: { stringValue: "LLM Observability is..." },
+ },
+ ],
+ },
+ ],
+ status: { code: 1 },
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(openLitSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate key fields
+ expect(obs.type).toBe("GENERATION");
+ expect(obs.environment).toBe("production");
+ expect(obs.provided_model_name).toBe("gpt-3.5-turbo");
+
+ // Usage should be extracted
+ expect(obs.provided_usage_details).toMatchObject({
+ input: 14,
+ output: 96,
+ total: 110,
+ });
+ });
+
+ it("should convert a TraceLoop span to valid ObservationForEval", async () => {
+ const traceLoopSpan = {
+ resource: {
+ attributes: [
+ { key: "service.name", value: { stringValue: "traceloop-app" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "opentelemetry.instrumentation.openai.v1",
+ version: "0.33.9",
+ },
+ spans: [
+ {
+ traceId: createBufferId("e4ef45025c9b40924bff175e2b125b5b"),
+ spanId: createBufferId("aabf16e416ae4952"),
+ name: "openai.chat",
+ kind: 3,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241287865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241289310000000),
+ ),
+ attributes: [
+ { key: "llm.request.type", value: { stringValue: "chat" } },
+ { key: "gen_ai.system", value: { stringValue: "OpenAI" } },
+ {
+ key: "gen_ai.request.model",
+ value: { stringValue: "gpt-3.5-turbo" },
+ },
+ {
+ key: "gen_ai.response.model",
+ value: { stringValue: "gpt-3.5-turbo-0125" },
+ },
+ {
+ key: "llm.usage.total_tokens",
+ value: { intValue: { low: 187, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.completion_tokens",
+ value: { intValue: { low: 173, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.prompt_tokens",
+ value: { intValue: { low: 14, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.prompt.0.role",
+ value: { stringValue: "user" },
+ },
+ {
+ key: "gen_ai.prompt.0.content",
+ value: { stringValue: "What is LLM Observability?" },
+ },
+ {
+ key: "gen_ai.completion.0.role",
+ value: { stringValue: "assistant" },
+ },
+ {
+ key: "gen_ai.completion.0.content",
+ value: {
+ stringValue: "LLM Observability is a strategy...",
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(traceLoopSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate model extraction (should get response.model)
+ expect(obs.provided_model_name).toBe("gpt-3.5-turbo-0125");
+
+ // Validate usage extraction (TraceLoop uses different keys)
+ expect(obs.provided_usage_details).toMatchObject({
+ input: 14,
+ output: 173,
+ });
+ });
+
+ it("should convert a Vercel AI SDK span to valid ObservationForEval", async () => {
+ const vercelAISpan = {
+ resource: {
+ attributes: [
+ { key: "telemetry.sdk.language", value: { stringValue: "nodejs" } },
+ { key: "service.name", value: { stringValue: "vercel-app" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "ai" },
+ spans: [
+ {
+ traceId: createBufferId("f1e2d3c4b5a69788f1e2d3c4b5a69788"),
+ spanId: createBufferId("1122334455667788"),
+ name: "ai.generateText",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241387865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241389310000000),
+ ),
+ attributes: [
+ { key: "ai.model.id", value: { stringValue: "gpt-4-turbo" } },
+ {
+ key: "ai.operationId",
+ value: { stringValue: "generateText" },
+ },
+ {
+ key: "ai.telemetry.functionId",
+ value: { stringValue: "chat" },
+ },
+ {
+ key: "ai.prompt.messages",
+ value: {
+ stringValue: '[{"role":"user","content":"Say hello"}]',
+ },
+ },
+ {
+ key: "ai.response.text",
+ value: { stringValue: "Hello! How can I help you today?" },
+ },
+ {
+ key: "gen_ai.usage.input_tokens",
+ value: { intValue: { low: 10, high: 0, unsigned: false } },
+ },
+ {
+ key: "gen_ai.usage.output_tokens",
+ value: { intValue: { low: 8, high: 0, unsigned: false } },
+ },
+ {
+ key: "ai.telemetry.metadata.userId",
+ value: { stringValue: "vercel-user-123" },
+ },
+ {
+ key: "ai.telemetry.metadata.sessionId",
+ value: { stringValue: "vercel-session-456" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(vercelAISpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate model extraction
+ expect(obs.provided_model_name).toBe("gpt-4-turbo");
+
+ // Validate user/session from Vercel AI SDK metadata
+ expect(obs.user_id).toBe("vercel-user-123");
+ expect(obs.session_id).toBe("vercel-session-456");
+
+ // Validate I/O extraction
+ expect(obs.input).toBe('[{"role":"user","content":"Say hello"}]');
+ expect(obs.output).toBe("Hello! How can I help you today?");
+ });
+ });
+
+ describe("Schema field coverage", () => {
+ it("should correctly map all ObservationForEval fields", async () => {
+ // Create a span with all possible fields populated
+ const fullOtelSpan = {
+ resource: {
+ attributes: [
+ { key: "telemetry.sdk.language", value: { stringValue: "python" } },
+ { key: "langfuse.environment", value: { stringValue: "staging" } },
+ { key: "langfuse.release", value: { stringValue: "v2.0.0" } },
+ {
+ key: "service.name",
+ value: { stringValue: "full-test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.5.0" },
+ spans: [
+ {
+ traceId: createBufferId("abcdef1234567890abcdef1234567890"),
+ spanId: createBufferId("1234567890abcdef"),
+ parentSpanId: createBufferId("fedcba0987654321"),
+ name: "full-test-observation",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241487865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241489310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.level",
+ value: { stringValue: "ERROR" },
+ },
+ {
+ key: "langfuse.observation.status_message",
+ value: { stringValue: "Rate limit exceeded" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: { stringValue: '{"query": "test input"}' },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: { stringValue: '{"result": "test output"}' },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: { stringValue: "claude-3-opus" },
+ },
+ // Model parameters are extracted from gen_ai.request.* attributes
+ {
+ key: "gen_ai.request.temperature",
+ value: { doubleValue: 0.5 },
+ },
+ {
+ key: "gen_ai.request.max_tokens",
+ value: {
+ intValue: { low: 1000, high: 0, unsigned: false },
+ },
+ },
+ {
+ key: "langfuse.observation.prompt.name",
+ value: { stringValue: "analysis-prompt" },
+ },
+ {
+ key: "langfuse.observation.prompt.version",
+ value: { intValue: { low: 3, high: 0, unsigned: false } },
+ },
+ {
+ key: "langfuse.observation.usage_details",
+ value: {
+ stringValue:
+ '{"input": 500, "output": 200, "total": 700}',
+ },
+ },
+ {
+ key: "langfuse.observation.cost_details",
+ value: {
+ stringValue: '{"input": 0.015, "output": 0.030}',
+ },
+ },
+ {
+ key: "langfuse.observation.metadata.request_id",
+ value: { stringValue: '"req-12345"' },
+ },
+ {
+ key: "langfuse.observation.metadata.source",
+ value: { stringValue: '"api"' },
+ },
+ {
+ key: "langfuse.trace.name",
+ value: { stringValue: "full-test-trace" },
+ },
+ { key: "user.id", value: { stringValue: "user-full-test" } },
+ {
+ key: "session.id",
+ value: { stringValue: "session-full-test" },
+ },
+ {
+ key: "langfuse.version",
+ value: { stringValue: "v1.5.0" },
+ },
+ {
+ key: "langfuse.trace.tags",
+ value: {
+ arrayValue: {
+ values: [
+ { stringValue: "production" },
+ { stringValue: "high-priority" },
+ { stringValue: "monitored" },
+ ],
+ },
+ },
+ },
+ ],
+ status: { code: 2, message: "Error" },
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(fullOtelSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate all fields from observationForEvalSchema are present
+ const schemaKeys = Object.keys(observationForEvalSchema.shape);
+ for (const key of schemaKeys) {
+ expect(obs).toHaveProperty(key);
+ }
+
+ // Validate specific field values
+ expect(obs.span_id).toBe("1234567890abcdef");
+ expect(obs.trace_id).toBe("abcdef1234567890abcdef1234567890");
+ expect(obs.parent_span_id).toBe("fedcba0987654321");
+ expect(obs.type).toBe("GENERATION");
+ expect(obs.name).toBe("full-test-observation");
+ expect(obs.environment).toBe("staging");
+ expect(obs.version).toBe("v1.5.0");
+ expect(obs.release).toBe("v2.0.0");
+ expect(obs.level).toBe("ERROR");
+ expect(obs.status_message).toBe("Rate limit exceeded");
+ expect(obs.trace_name).toBe("full-test-trace");
+ expect(obs.user_id).toBe("user-full-test");
+ expect(obs.session_id).toBe("session-full-test");
+ expect(obs.tags).toEqual(["production", "high-priority", "monitored"]);
+ expect(obs.provided_model_name).toBe("claude-3-opus");
+ expect(obs.model_parameters).toEqual({
+ temperature: 0.5,
+ max_tokens: 1000,
+ });
+ expect(obs.prompt_name).toBe("analysis-prompt");
+ expect(obs.prompt_version).toBe(3);
+ expect(obs.input).toBe('{"query": "test input"}');
+ expect(obs.output).toBe('{"result": "test output"}');
+ });
+
+ it("should handle experiment fields correctly", async () => {
+ const experimentSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("1234567890123456789012345678abcd"),
+ spanId: createBufferId("exp1234567890123"),
+ name: "experiment-run",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241587865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241589310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.experiment.id",
+ value: { stringValue: "exp-001" },
+ },
+ {
+ key: "langfuse.experiment.name",
+ value: { stringValue: "Prompt Optimization v2" },
+ },
+ {
+ key: "langfuse.experiment.description",
+ value: { stringValue: "Testing new prompt templates" },
+ },
+ {
+ key: "langfuse.experiment.dataset.id",
+ value: { stringValue: "dataset-test-001" },
+ },
+ {
+ key: "langfuse.experiment.item.id",
+ value: { stringValue: "item-123" },
+ },
+ {
+ key: "langfuse.experiment.item.expected_output",
+ value: { stringValue: '{"expected": "result"}' },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: { stringValue: '{"test": "input"}' },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: { stringValue: '{"test": "output"}' },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(experimentSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate experiment fields
+ expect(obs.experiment_id).toBe("exp-001");
+ expect(obs.experiment_name).toBe("Prompt Optimization v2");
+ expect(obs.experiment_description).toBe("Testing new prompt templates");
+ expect(obs.experiment_dataset_id).toBe("dataset-test-001");
+ expect(obs.experiment_item_id).toBe("item-123");
+ expect(obs.experiment_item_expected_output).toBe(
+ '{"expected": "result"}',
+ );
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle spans with empty strings correctly", async () => {
+ const emptyStringSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("12345678901234567890123456789012"),
+ spanId: createBufferId("empty123456789ab"),
+ name: "",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241687865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241689310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: { stringValue: "" },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: { stringValue: "" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(emptyStringSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Empty name should use span name (which is empty)
+ expect(obs.name).toBe("");
+ });
+
+ it("should handle spans with special characters in values", async () => {
+ const specialCharsSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("12345678901234561234567890123456"),
+ spanId: createBufferId("spec123456789abc"),
+ name: "span-with-special-chars",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241787865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241789310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: {
+ stringValue:
+ '{"message": "Hello! <script>alert(1)</script>"}',
+ },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: {
+ stringValue: 'Line1\\nLine2\\tTabbed\\"Quoted\\"',
+ },
+ },
+ {
+ key: "langfuse.trace.tags",
+ value: {
+ arrayValue: {
+ values: [
+ { stringValue: "tag-with-dash" },
+ { stringValue: "tag_with_underscore" },
+ { stringValue: "tag.with" },
+ ],
+ },
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(specialCharsSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate special characters are preserved
+ expect(obs.input).toContain("<script>");
+ expect(obs.tags).toEqual([
+ "tag-with-dash",
+ "tag_with_underscore",
+ "tag.with",
+ ]);
+ });
+
+ it("should handle spans with very large input/output", async () => {
+ const largeContent = "x".repeat(100000); // 100KB of data
+ const largeSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("12345678901234567890123456781234"),
+ spanId: createBufferId("large12345678901"),
+ name: "large-io-span",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241887865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241889310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: { stringValue: largeContent },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: { stringValue: largeContent },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations = await processOtelSpanToObservationForEval(largeSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate large content is preserved
+ expect(obs.input?.length).toBe(100000);
+ expect(obs.output?.length).toBe(100000);
+ });
+
+ it("should handle different observation types", async () => {
+ const observationTypes = [
+ "span",
+ "generation",
+ "event",
+ "agent",
+ "tool",
+ "chain",
+ "retriever",
+ "evaluator",
+ "guardrail",
+ "embedding",
+ ];
+
+ for (const obsType of observationTypes) {
+ // Create valid hex string for traceId (32 chars = 16 bytes)
+ const typeHex = obsType.padEnd(16, "0").slice(0, 16);
+ const traceIdHex = `${typeHex}${typeHex}`;
+ // Create valid hex string for spanId (16 chars = 8 bytes)
+ const spanIdHex = `${obsType.slice(0, 8).padEnd(8, "0")}12345678`;
+
+ const typeSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId(traceIdHex),
+ spanId: createBufferId(spanIdHex),
+ name: `${obsType}-test`,
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241987865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738241989310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: obsType },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(typeSpan);
+
+ expect(observations).toHaveLength(1);
+ expect(observations[0].type).toBe(obsType.toUpperCase());
+
+ // Validate schema conformance for each type
+ const result = observationForEvalSchema.safeParse(observations[0]);
+ expect(result.success).toBe(true);
+ }
+ });
+
+ it("should handle metadata with nested objects", async () => {
+ const nestedMetadataSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("12345678901234567890123456789abc"),
+ spanId: createBufferId("nest123456789012"),
+ name: "nested-metadata-span",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242087865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242089310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ {
+ key: "langfuse.observation.metadata",
+ value: {
+ stringValue: JSON.stringify({
+ nested: {
+ deeply: {
+ value: "found",
+ },
+ },
+ array: [1, 2, 3],
+ mixed: {
+ string: "text",
+ number: 42,
+ boolean: true,
+ },
+ }),
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(nestedMetadataSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate metadata is present (as flattened or stringified)
+ expect(obs.metadata).toBeDefined();
+ expect(typeof obs.metadata).toBe("object");
+ });
+ });
+
+ describe("Multiple spans in single batch", () => {
+ it("should process multiple spans and all conform to schema", async () => {
+ const multiSpanBatch = {
+ resource: {
+ attributes: [
+ { key: "langfuse.environment", value: { stringValue: "test" } },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("12345678901234567890123456789def"),
+ spanId: createBufferId("aaaa1234567890ab"),
+ name: "span-1",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242187865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242189310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ ],
+ status: {},
+ },
+ {
+ traceId: createBufferId("12345678901234567890123456789def"),
+ spanId: createBufferId("bbbb2345678901bc"),
+ parentSpanId: createBufferId("aaaa1234567890ab"),
+ name: "generation-1",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242189400000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242189500000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: { stringValue: "gpt-4" },
+ },
+ ],
+ status: {},
+ },
+ {
+ traceId: createBufferId("12345678901234567890123456789def"),
+ spanId: createBufferId("cccc3456789012cd"),
+ parentSpanId: createBufferId("aaaa1234567890ab"),
+ name: "tool-call",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242189600000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242189700000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "tool" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(multiSpanBatch);
+
+ expect(observations).toHaveLength(3);
+
+ // All observations should have the same trace_id
+ expect(observations[0].trace_id).toBe("12345678901234567890123456789def");
+ expect(observations[1].trace_id).toBe("12345678901234567890123456789def");
+ expect(observations[2].trace_id).toBe("12345678901234567890123456789def");
+
+ // Parent-child relationships should be preserved
+ // Note: nullish fields may be null or undefined depending on the processing path
+ expect(observations[0].parent_span_id).toBeFalsy();
+ expect(observations[1].parent_span_id).toBe("aaaa1234567890ab");
+ expect(observations[2].parent_span_id).toBe("aaaa1234567890ab");
+
+ // All should conform to schema
+ for (const obs of observations) {
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+ }
+ });
+ });
+
+ describe("Usage and cost details", () => {
+ it("should correctly extract and transform usage details from OTEL spans", async () => {
+ const usageSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("1234567890123456789012345678cdef"),
+ spanId: createBufferId("usage12345678901"),
+ name: "usage-test",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242287865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242289310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: { stringValue: "gpt-4" },
+ },
+ {
+ key: "langfuse.observation.usage_details",
+ value: {
+ stringValue: JSON.stringify({
+ input: 100,
+ output: 200,
+ total: 300,
+ cached_input: 50,
+ }),
+ },
+ },
+ {
+ key: "langfuse.observation.cost_details",
+ value: {
+ stringValue: JSON.stringify({
+ input: 0.01,
+ output: 0.02,
+ total: 0.03,
+ }),
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations = await processOtelSpanToObservationForEval(usageSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Validate usage details
+ expect(obs.provided_usage_details).toEqual({
+ input: 100,
+ output: 200,
+ total: 300,
+ cached_input: 50,
+ });
+
+ // Validate cost details
+ expect(obs.provided_cost_details).toEqual({
+ input: 0.01,
+ output: 0.02,
+ total: 0.03,
+ });
+ });
+ });
+
+ describe("Tool calls extraction", () => {
+ it("should correctly extract tool definitions and calls", async () => {
+ const toolCallSpan = {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "langfuse-sdk", version: "3.0.0" },
+ spans: [
+ {
+ traceId: createBufferId("123456789012345678901234567890ab"),
+ spanId: createBufferId("tool1234567890ab"),
+ name: "tool-call-test",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242387865000000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1738242389310000000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: { stringValue: "gpt-4" },
+ },
+ {
+ key: "langfuse.observation.input",
+ value: {
+ stringValue: JSON.stringify({
+ messages: [
+ { role: "user", content: "What is the weather?" },
+ ],
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get current weather",
+ parameters: {
+ type: "object",
+ properties: {
+ location: { type: "string" },
+ },
+ },
+ },
+ },
+ ],
+ }),
+ },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: {
+ stringValue: JSON.stringify({
+ choices: [
+ {
+ message: {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: '{"location": "San Francisco"}',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const observations =
+ await processOtelSpanToObservationForEval(toolCallSpan);
+
+ expect(observations).toHaveLength(1);
+ const obs = observations[0];
+
+ // Validate schema conformance
+ const result = observationForEvalSchema.safeParse(obs);
+ expect(result.success).toBe(true);
+
+ // Tool definitions and calls are extracted by IngestionService
+ // They should be present in the observation
+ expect(obs.tool_definitions).toBeDefined();
+ expect(obs.tool_calls).toBeDefined();
+ expect(obs.tool_call_names).toBeDefined();
+ });
+ });
+});
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 0062a9f423..2c1cf21bf0 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -7,11 +7,13 @@ import {
logger,
traceException,
EvalExecutionQueue,
+ LLMAsJudgeExecutionQueue,
QueueJobs,
getCurrentSpan,
isLLMCompletionError,
} from "@langfuse/shared/src/server";
import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
+import { processObservationEval } from "../features/evaluation/observationEval";
import { delayInMs } from "./utils/delays";
import { createW3CTraceId, retryLLMRateLimitError } from "../features/utils";
import { isUnrecoverableError } from "../errors/UnrecoverableError";
@@ -219,3 +221,87 @@ export const evalJobExecutorQueueProcessor = async (
throw e;
}
};
+
+/**
+ * Processor for observation-level LLM-as-a-judge evaluation jobs.
+ * This handles evals triggered during OTEL ingestion for single observations.
+ */
+export const llmAsJudgeExecutionQueueProcessor = async (
+ job: Job<TQueueJobTypes[QueueName.LLMAsJudgeExecution]>,
+) => {
+ try {
+ logger.debug("Executing LLM-as-Judge Observation Evaluation Job", job.data);
+
+ const span = getCurrentSpan();
+
+ if (span) {
+ span.setAttribute(
+ "messaging.bullmq.job.input.jobExecutionId",
+ job.data.payload.jobExecutionId,
+ );
+ span.setAttribute(
+ "messaging.bullmq.job.input.projectId",
+ job.data.payload.projectId,
+ );
+ span.setAttribute(
+ "messaging.bullmq.job.input.retryBaggage.attempt",
+ job.data.retryBaggage?.attempt ?? 0,
+ );
+ }
+
+ await processObservationEval({ event: job.data.payload });
+ return true;
+ } catch (e) {
+ const executionTraceId = createW3CTraceId(job.data.payload.jobExecutionId);
+
+ if (isLLMCompletionError(e) && e.isRetryable) {
+ await retryLLMRateLimitError(job, {
+ table: "job_executions",
+ idField: "jobExecutionId",
+ queue: LLMAsJudgeExecutionQueue.getInstance(),
+ queueName: QueueName.LLMAsJudgeExecution,
+ jobName: QueueJobs.LLMAsJudgeExecution,
+ delayFn: delayInMs,
+ });
+
+ await prisma.jobExecution.update({
+ where: {
+ id: job.data.payload.jobExecutionId,
+ projectId: job.data.payload.projectId,
+ },
+ data: {
+ status: JobExecutionStatus.DELAYED,
+ executionTraceId,
+ },
+ });
+
+ return;
+ }
+
+ await prisma.jobExecution.update({
+ where: {
+ id: job.data.payload.jobExecutionId,
+ projectId: job.data.payload.projectId,
+ },
+ data: {
+ status: JobExecutionStatus.ERROR,
+ endTime: new Date(),
+ error:
+ isLLMCompletionError(e) || isUnrecoverableError(e)
+ ? e.message
+ : "An internal error occurred",
+ executionTraceId,
+ },
+ });
+
+ if (isLLMCompletionError(e) || isUnrecoverableError(e)) return;
+
+ traceException(e);
+ logger.error(
+ `Failed LLM-as-Judge execution job for id ${job.data.payload.jobExecutionId}`,
+ e,
+ );
+
+ throw e;
+ }
+};
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
index 0842a25b8a..a05effcc32 100644
--- a/worker/src/queues/otelIngestionQueue.ts
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -23,7 +23,15 @@ import { env } from "../env";
import { IngestionService } from "../services/IngestionService";
import { prisma } from "@langfuse/shared/src/db";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
-import { ForbiddenError } from "@langfuse/shared";
+import {
+ ForbiddenError,
+ convertEventRecordToObservationForEval,
+} from "@langfuse/shared";
+import {
+ fetchObservationEvalConfigs,
+ scheduleObservationEvals,
+ createObservationEvalSchedulerDeps,
+} from "../features/evaluation/observationEval";
/**
* SDK information extracted from OTEL resourceSpans.
@@ -236,45 +244,127 @@ export const otelIngestionQueueProcessor: Processor = async (
// Running everything concurrently might be detrimental to the event loop, but has probably
// the highest possible throughput. Therefore, we start with a Promise.all.
// If necessary, we may use a for each instead.
- await Promise.all(
- [
- // Process traces
- processEventBatch(traces, auth, {
- delay: 0,
- source: "otel",
- forwardToEventsTable: shouldForwardToEventsTable,
- }),
- // Process observations
- observations.map((observation) =>
- ingestionService.mergeAndWrite(
- getClickhouseEntityType(observation.type),
- auth.scope.projectId,
- observation.body.id || "", // id is always defined for observations
- new Date(), // Use the current timestamp as event time
- [observation],
- shouldForwardToEventsTable,
- ),
+
+ // Process observations via mergeAndWrite
+ const observationWritePromise = Promise.all(
+ observations.map((observation) =>
+ ingestionService.mergeAndWrite(
+ getClickhouseEntityType(observation.type),
+ auth.scope.projectId,
+ observation.body.id || "", // id is always defined for observations
+ new Date(), // Use the current timestamp as event time
+ [observation],
+ shouldForwardToEventsTable,
),
- ].flat(),
+ ),
);
- // If inserts into the events table are enabled AND observations qualify for direct write,
- // run the dedicated processing for the otel spans and move them into the dedicated IngestionService processor.
- if (
+ // Process traces and observations concurrently
+ await Promise.all([
+ observationWritePromise,
+ processEventBatch(traces, auth, {
+ delay: 0,
+ source: "otel",
+ forwardToEventsTable: shouldForwardToEventsTable,
+ }),
+ ]);
+
+ // Process events for observation evals and direct event writes
+ // This phase handles two independent concerns:
+ // 1. Scheduling observation-level evals (if eval configs exist)
+ // 2. Writing directly to events table (if SDK version requirements are met)
+ //
+ // Both require enriched event records with trace-level attributes
+ // (userId, sessionId, tags, release) that processToEvent provides.
+ const eventInputs = processor.processToEvent(parsedSpans);
+
+ if (eventInputs.length === 0) {
+ return;
+ }
+
+ // Determine what processing is needed
+ const shouldWriteToEventsTable =
env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&
- useDirectEventWrite
- ) {
- try {
- const events = processor.processToEvent(parsedSpans);
- await Promise.all(
- events.map((e) => ingestionService.writeEvent(e, fileKey)),
+ useDirectEventWrite;
+
+ const evalConfigs = await fetchObservationEvalConfigs(projectId).catch(
+ (error) => {
+ traceException(error);
+ logger.warn(
+ `Failed to fetch observation eval configs for project ${projectId}`,
+ error,
);
- } catch (e) {
- traceException(e); // Mark span as errored
- logger.warn(`Failed to process events for ${projectId}: ${e}`, e);
- // Fallthrough while setting is experimental
- }
+
+ return [];
+ },
+ );
+ const hasEvalConfigs = evalConfigs.length > 0;
+
+ // Early exit if no processing needed
+ if (!hasEvalConfigs && !shouldWriteToEventsTable) {
+ return;
}
+
+ // Create scheduler deps only if we have eval configs
+ const evalSchedulerDeps = hasEvalConfigs
+ ? createObservationEvalSchedulerDeps()
+ : null;
+
+ await Promise.all(
+ // Process each event independently
+ eventInputs.map(async (eventInput) => {
+ // Step 1: Create enriched event record (required for both evals and writes)
+ let eventRecord;
+ try {
+ eventRecord = await ingestionService.createEventRecord(
+ eventInput,
+ fileKey,
+ );
+ } catch (error) {
+ traceException(error);
+ logger.error(
+ `Failed to create event record for project ${eventInput.projectId} and observation ${eventInput.spanId}`,
+ error,
+ );
+
+ return;
+ }
+
+ // Step 2: Schedule observation evals (independent of event writes)
+ if (hasEvalConfigs && evalSchedulerDeps) {
+ try {
+ const observation =
+ convertEventRecordToObservationForEval(eventRecord);
+
+ await scheduleObservationEvals({
+ observation,
+ configs: evalConfigs,
+ schedulerDeps: evalSchedulerDeps,
+ });
+ } catch (error) {
+ traceException(error);
+
+ logger.error(
+ `Failed to schedule observation evals for project ${eventInput.projectId} and observation ${eventInput.spanId}`,
+ error,
+ );
+ }
+ }
+
+ // Step 3: Write to events table (independent of eval scheduling)
+ if (shouldWriteToEventsTable) {
+ try {
+ ingestionService.writeEventRecord(eventRecord);
+ } catch (error) {
+ traceException(error);
+ logger.error(
+ `Failed to write event record for ${eventInput.spanId}`,
+ error,
+ );
+ }
+ }
+ }),
+ );
} catch (e) {
if (e instanceof ForbiddenError) {
traceException(e);
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index cd6f3b409e..d18f26a6c5 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -42,13 +42,13 @@ import {
validateAndInflateScore,
DatasetRunItemRecordInsertType,
EventRecordInsertType,
- hasNoJobConfigsCache,
traceException,
flattenJsonToPathArrays,
getDatasetItemById,
extractToolsFromObservation,
convertDefinitionsToMap,
convertCallsToArrays,
+ hasNoEvalConfigsCache,
} from "@langfuse/shared/src/server";
import { tokenCountAsync } from "../../features/tokenisation/async-usage";
@@ -280,19 +280,26 @@ export class IngestionService {
}
/**
- * Writes a single event directly to the events table.
- * Unlike other ingestion methods, this does not perform merging since
- * events are immutable and written once.
+ * Creates an EventRecordInsertType from EventInput.
+ * Performs all necessary enrichments:
+ * - Prompt lookup (by name + version)
+ * - Model/usage enrichment (tokenization, cost calculation)
+ * - Metadata flattening
+ * - Timestamp normalization
*
- * @param eventData - The event data to write
+ * This is the single point of transformation from loose EventInput
+ * to strict EventRecordInsertType.
+ *
+ * @param eventData - The event data from processToEvent()
* @param fileKey - The file key where the raw event data is stored
+ * @returns The enriched event record ready for writing or eval scheduling
*/
- public async writeEvent(
+ public async createEventRecord(
eventData: EventInput,
fileKey: string,
- ): Promise<void> {
+ ): Promise<EventRecordInsertType> {
logger.debug(
- `Writing event for project ${eventData.projectId} and span ${eventData.spanId}`,
+ `Creating event record for project ${eventData.projectId} and span ${eventData.spanId}`,
);
// Perform lookups for prompt and model/usage enrichment
@@ -450,7 +457,16 @@ export class IngestionService {
is_deleted: 0,
};
- // Write directly to ClickHouse queue (no merging for immutable events)
+ return eventRecord;
+ }
+
+ /**
+ * Writes an event record directly to the events table.
+ * Use createEventRecord() first to get the record, then call this to write.
+ *
+ * @param eventRecord - The event record to write
+ */
+ public writeEventRecord(eventRecord: EventRecordInsertType): void {
this.clickHouseWriter.addToQueue(TableName.Events, eventRecord);
}
@@ -762,7 +778,10 @@ export class IngestionService {
// Add trace into trace upsert queue for eval processing
// First check if we already know this project has no job configurations
- const hasNoJobConfigs = await hasNoJobConfigsCache(projectId);
+ const hasNoJobConfigs = await hasNoEvalConfigsCache(
+ projectId,
+ "traceBased",
+ );
if (hasNoJobConfigs) {
logger.debug(
`Skipping TraceUpsert queue for project ${projectId} - no job configs cached`,
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index e3dd957795..ececb64b4d 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -1296,7 +1296,11 @@ describe("Token Cost Calculation", () => {
},
];
- await (mockIngestionService as any).writeEvent(events[0], "testfile.txt");
+ const eventRecord = await (mockIngestionService as any).createEventRecord(
+ events[0],
+ "testfile.txt",
+ );
+ (mockIngestionService as any).writeEventRecord(eventRecord);
expect(mockAddToClickhouseWriter).toHaveBeenCalled();
const args = mockAddToClickhouseWriter.mock.calls[0];
@@ -1329,7 +1333,11 @@ describe("Token Cost Calculation", () => {
},
];
- await (mockIngestionService as any).writeEvent(events[0], "testfile.txt");
+ const eventRecord = await (mockIngestionService as any).createEventRecord(
+ events[0],
+ "testfile.txt",
+ );
+ (mockIngestionService as any).writeEventRecord(eventRecord);
// Invalid values should be ignored
expect(mockAddToClickhouseWriter).toHaveBeenCalled();