Skip to content

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

chore: use clickhouse in evaluations queues (#4319)

Steffen Schmitza594c142e055
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 447a629afa..828709bb6b 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -326,18 +326,18 @@ jobs:
- name: install dependencies
run: |
pnpm install
+ - name: Install golang-migrate for Clickhouse migrations
+ run: |
+ curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
+ sudo mv migrate /usr/bin/migrate
+ which migrate
- name: Load default env
run: |
cp .env.dev.example .env
+ echo "LANGFUSE_ASYNC_CLICKHOUSE_INGESTION_PROCESSING=true" >> .env
echo "LANGFUSE_ASYNC_INGESTION_PROCESSING=true" >> .env
echo "LANGFUSE_CACHE_API_KEY_ENABLED=true" >> .env
echo "LANGFUSE_CACHE_PROMPT_ENABLED=true" >> .env
- - name: Install golang-migrate for Clickhouse migrations
- run: |
- curl -L https://github.com/golang-migrate/migrate/releases/download/v4.16.2/migrate.linux-amd64.tar.gz | tar xvz
- sudo mv migrate /usr/bin/migrate
- which migrate
-
- name: Run + migrate
run: |
docker compose -f docker-compose.dev.yml up -d
diff --git a/packages/shared/src/server/ingestion/legacy/index.ts b/packages/shared/src/server/ingestion/legacy/index.ts
index 633043a543..a0151c7365 100644
--- a/packages/shared/src/server/ingestion/legacy/index.ts
+++ b/packages/shared/src/server/ingestion/legacy/index.ts
@@ -3,13 +3,7 @@ import z from "zod";
import { ForbiddenError, UnauthorizedError } from "../../../errors";
import { eventTypes, ingestionApiSchema, IngestionEventType } from "../types";
import { getProcessorForEvent } from "./EventProcessor";
-import { TraceUpsertEventType } from "../../queues";
-import {
- convertTraceUpsertEventsToRedisEvents,
- TraceUpsertQueue,
-} from "../../redis/traceUpsert";
import { ApiAccessScope } from "../../auth/types";
-import { redis } from "../../redis/redis";
import { backOff } from "exponential-backoff";
import { Model } from "../../..";
import { logger } from "../../logger";
@@ -163,45 +157,5 @@ export function cleanEvent(obj: unknown): unknown {
}
}
-export const isNotNullOrUndefined = <T>(
- val?: T | null,
-): val is Exclude<T, null | undefined> => !isUndefinedOrNull(val);
-
export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>
val === undefined || val === null;
-
-export const addTracesToTraceUpsertQueue = async (
- batchResults: BatchResult[],
- projectId: string,
-): Promise<void> => {
- const traceEvents: TraceUpsertEventType[] = batchResults
- .filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update.
- .map((result) =>
- result.result &&
- typeof result.result === "object" &&
- "id" in result.result
- ? // ingestion API only gets traces for one projectId
- {
- traceId: result.result.id as string,
- projectId,
- }
- : null,
- )
- .filter(isNotNullOrUndefined);
-
- try {
- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && redis) {
- logger.debug(`Sending ${traceEvents.length} events to worker via Redis`);
-
- const queue = TraceUpsertQueue.getInstance();
- if (!queue) {
- logger.error("TraceUpsertQueue not initialized");
- return;
- }
-
- await queue.addBulk(convertTraceUpsertEventsToRedisEvents(traceEvents));
- }
- } catch (error) {
- logger.error("Error sending events to worker", error);
- }
-};
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
index 1c6e0fadd6..b5bd714b17 100644
--- a/packages/shared/src/server/ingestion/processEventBatch.ts
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -23,7 +23,7 @@ import { IngestionQueue } from "../redis/ingestionQueue";
import { LegacyIngestionQueue } from "../redis/legacyIngestion";
import { redis } from "../redis/redis";
import { S3StorageService } from "../services/S3StorageService";
-import { addTracesToTraceUpsertQueue, handleBatch } from "./legacy";
+import { handleBatch } from "./legacy";
import { getProcessorForEvent } from "./legacy/EventProcessor";
import { eventTypes, ingestionEvent, IngestionEventType } from "./types";
@@ -286,8 +286,6 @@ export const processEventBatch = async (
*******************/
const result = await handleBatch(sortedBatch, authCheck, tokenCountDelegate);
- await addTracesToTraceUpsertQueue(result.results, authCheck.scope.projectId);
-
// in case we did not return early, we return the result here
return aggregateBatchResult(
[...validationErrors, ...authenticationErrors, ...result.errors],
diff --git a/packages/shared/src/server/redis/datasetRunItemUpsert.ts b/packages/shared/src/server/redis/datasetRunItemUpsert.ts
index 25044bd80d..1296b2bfdc 100644
--- a/packages/shared/src/server/redis/datasetRunItemUpsert.ts
+++ b/packages/shared/src/server/redis/datasetRunItemUpsert.ts
@@ -27,7 +27,8 @@ export class DatasetRunItemUpsertQueue {
defaultJobOptions: {
removeOnComplete: true,
removeOnFail: 10_000,
- attempts: 2,
+ attempts: 5,
+ delay: 30_000, // 30 seconds
backoff: {
type: "exponential",
delay: 5000,
diff --git a/packages/shared/src/server/redis/evalExecutionQueue.ts b/packages/shared/src/server/redis/evalExecutionQueue.ts
index 429073d6af..95eb4c2b8c 100644
--- a/packages/shared/src/server/redis/evalExecutionQueue.ts
+++ b/packages/shared/src/server/redis/evalExecutionQueue.ts
@@ -26,7 +26,7 @@ export class EvalExecutionQueue {
defaultJobOptions: {
removeOnComplete: true,
removeOnFail: 10_000,
- attempts: 2,
+ attempts: 10,
backoff: {
type: "exponential",
delay: 5000,
diff --git a/packages/shared/src/server/redis/traceUpsert.ts b/packages/shared/src/server/redis/traceUpsert.ts
index 6b8733e8e7..65993fcb1d 100644
--- a/packages/shared/src/server/redis/traceUpsert.ts
+++ b/packages/shared/src/server/redis/traceUpsert.ts
@@ -32,6 +32,7 @@ export class TraceUpsertQueue {
removeOnComplete: 100, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue
removeOnFail: 100_000,
attempts: 5,
+ delay: 10_000, // 10 seconds
backoff: {
type: "exponential",
delay: 5000,
@@ -48,43 +49,3 @@ export class TraceUpsertQueue {
return TraceUpsertQueue.instance;
}
}
-
-export function convertTraceUpsertEventsToRedisEvents(
- events: TraceUpsertEventType[],
-) {
- const uniqueTracesPerProject = events.reduce((acc, event) => {
- if (!acc.get(event.projectId)) {
- acc.set(event.projectId, new Set());
- }
- acc.get(event.projectId)?.add(event.traceId);
- return acc;
- }, new Map<string, Set<string>>());
-
- return [...uniqueTracesPerProject.entries()]
- .map((tracesPerProject) => {
- const [projectId, traceIds] = tracesPerProject;
-
- return [...traceIds].map((traceId) => ({
- name: QueueJobs.TraceUpsert,
- data: {
- payload: {
- projectId,
- traceId,
- },
- id: randomUUID(),
- timestamp: new Date(),
- name: QueueJobs.TraceUpsert as const,
- },
- opts: {
- removeOnFail: 1_000,
- removeOnComplete: true,
- attempts: 5,
- backoff: {
- type: "exponential",
- delay: 1000,
- },
- },
- }));
- })
- .flat();
-}
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index ec8051a7e6..7ddcc8a976 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -29,7 +29,7 @@ const getS3StorageServiceClient = (bucketName: string): S3StorageService => {
export async function upsertClickhouse<
T extends Record<string, unknown>,
>(opts: {
- table: "scores" | "traces"; // TODO: Modify eventType logic to support more tables going forward
+ table: "scores" | "traces" | "observations";
records: T[];
eventBodyMapper: (body: T) => Record<string, unknown>;
}): Promise<void> {
@@ -37,10 +37,6 @@ export async function upsertClickhouse<
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.table", opts.table);
- // drop trailing s and pretend it's always a create.
- // Only applicable to scores and traces.
- const eventType = `${opts.table.slice(0, -1)}-create`;
-
// If event upload is enabled, we store all rows in S3 to have a backup
if (env.LANGFUSE_S3_EVENT_UPLOAD_ENABLED === "true") {
if (env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET === undefined) {
@@ -51,6 +47,13 @@ export async function upsertClickhouse<
);
await Promise.all(
opts.records.map((record) => {
+ // drop trailing s and pretend it's always a create.
+ // Only applicable to scores and traces.
+ let eventType = `${opts.table.slice(0, -1)}-create`;
+ if (opts.table === "observations") {
+ // @ts-ignore - If it's an observation we now that `type` is a string
+ eventType = `${record["type"].toLowerCase()}-create`;
+ }
s3Client.uploadJson(
`${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${record.project_id}/${getClickhouseEntityType(eventType)}/${record.id}/${randomUUID()}.json`,
[
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 7718b4bf13..5280307333 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -2,6 +2,7 @@ import {
commandClickhouse,
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
+ upsertClickhouse,
} from "./clickhouse";
import { ObservationLevel } from "@prisma/client";
import { logger } from "../logger";
@@ -38,6 +39,58 @@ import {
TRACE_TO_OBSERVATIONS_INTERVAL,
} from "./constants";
+export const checkObservationExists = async (
+ projectId: string,
+ id: string,
+ startTime: Date | undefined,
+): Promise<boolean> => {
+ const query = `
+ SELECT id, project_id
+ FROM observations o
+ WHERE project_id = {projectId: String}
+ AND id = {id: String}
+ ${startTime ? `AND start_time >= {startTime: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
+ ORDER BY event_ts DESC
+ LIMIT 1 BY id, project_id
+ `;
+
+ const rows = await queryClickhouse<{ id: string; project_id: string }>({
+ query,
+ params: {
+ id,
+ projectId,
+ ...(startTime
+ ? { startTime: convertDateToClickhouseDateTime(startTime) }
+ : {}),
+ },
+ });
+
+ return rows.length > 0;
+};
+
+/**
+ * Accepts a trace in a Clickhouse-ready format.
+ * id, project_id, and timestamp must always be provided.
+ */
+export const upsertObservation = async (
+ observation: Partial<ObservationRecordReadType>,
+) => {
+ if (
+ !["id", "project_id", "start_time", "type"].every(
+ (key) => key in observation,
+ )
+ ) {
+ throw new Error(
+ "Identifier fields must be provided to upsert Observation.",
+ );
+ }
+ await upsertClickhouse({
+ table: "observations",
+ records: [observation as ObservationRecordReadType],
+ eventBodyMapper: convertObservation,
+ });
+};
+
export const getObservationsViewForTrace = async (
traceId: string,
projectId: string,
@@ -94,6 +147,65 @@ export const getObservationsViewForTrace = async (
return records.map(convertObservationToView);
};
+export const getObservationForTraceIdByName = async (
+ traceId: string,
+ projectId: string,
+ name: string,
+ timestamp?: Date,
+ fetchWithInputOutput: boolean = false,
+) => {
+ const query = `
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ ${fetchWithInputOutput ? "input, output," : ""}
+ provided_model_name,
+ internal_model_id,
+ model_parameters,
+ provided_usage_details,
+ usage_details,
+ provided_cost_details,
+ cost_details,
+ total_cost,
+ completion_start_time,
+ prompt_id,
+ prompt_name,
+ prompt_version,
+ created_at,
+ updated_at,
+ event_ts
+ FROM observations
+ WHERE trace_id = {traceId: String}
+ AND project_id = {projectId: String}
+ AND name = {name: String}
+ ${timestamp ? `AND start_time >= {traceTimestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ORDER BY event_ts DESC
+ LIMIT 1 BY id, project_id`;
+ const records = await queryClickhouse<ObservationRecordReadType>({
+ query,
+ params: {
+ traceId,
+ projectId,
+ name,
+ ...(timestamp
+ ? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ },
+ });
+
+ return records.map(convertObservationToView);
+};
+
export const getObservationById = async (
id: string,
projectId: string,
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index b94ccde9c6..4b609e0b58 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -12,6 +12,7 @@ import { FilterState } from "../../types";
import {
DateTimeFilter,
FilterList,
+ StringFilter,
} from "../queries/clickhouse-sql/clickhouse-filter";
import { TraceRecordReadType } from "./definitions";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions/mapTracesTable";
@@ -25,6 +26,48 @@ import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import { TRACE_TO_OBSERVATIONS_INTERVAL } from "./constants";
import { FetchTracesTableProps } from "../services/traces-ui-table-service";
+export const checkTraceExists = async (
+ projectId: string,
+ traceId: string,
+ timestamp: Date | undefined,
+ filter: FilterState,
+): Promise<boolean> => {
+ const { tracesFilter } = getProjectIdDefaultFilter(projectId, {
+ tracesPrefix: "t",
+ });
+
+ tracesFilter.push(
+ ...createFilterFromFilterState(filter, tracesTableUiColumnDefinitions),
+ new StringFilter({
+ clickhouseTable: "t",
+ field: "id",
+ operator: "=",
+ value: traceId,
+ }),
+ );
+
+ const tracesFilterRes = tracesFilter.apply();
+
+ const query = `
+ SELECT id, project_id
+ FROM traces t FINAL
+ WHERE ${tracesFilterRes.query}
+ ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ `;
+
+ const rows = await queryClickhouse<{ id: string; project_id: string }>({
+ query,
+ params: {
+ ...tracesFilterRes.params,
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ },
+ });
+
+ return rows.length > 0;
+};
+
/**
* Accepts a trace in a Clickhouse-ready format.
* id, project_id, and timestamp must always be provided.
diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.ts
index 82b321f33d..79c876e05f 100644
--- a/web/src/__e2e__/api.servertest.ts
+++ b/web/src/__e2e__/api.servertest.ts
@@ -163,12 +163,12 @@ describe("Ingestion Pipeline", () => {
// failure due to missing openai key in the pipeline. Expected
expect(evalExecution.status).toBe(JobExecutionStatus.ERROR);
},
- 40000,
- 1000,
+ 50000,
+ 10000,
);
expect(response.status).toBe(207);
- }, 50000);
+ }, 60000);
it("rate limit ingestion", async () => {
// update the org in the database and set the rate limit to 1 for ingestion
diff --git a/web/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue.ts b/web/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue.ts
index 01f8004f8d..1c1c103555 100644
--- a/web/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue.ts
+++ b/web/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue.ts
@@ -1,7 +1,10 @@
import { env } from "@/src/env.mjs";
-import { DatasetRunItemUpsertQueue } from "../../../../../../packages/shared/dist/src/server/redis/datasetRunItemUpsert";
import { randomUUID } from "crypto";
-import { QueueJobs, redis } from "@langfuse/shared/src/server";
+import {
+ QueueJobs,
+ DatasetRunItemUpsertQueue,
+ redis,
+} from "@langfuse/shared/src/server";
export const addDatasetRunItemsToEvalQueue = async ({
projectId,
@@ -18,30 +21,17 @@ export const addDatasetRunItemsToEvalQueue = async ({
const queue = DatasetRunItemUpsertQueue.getInstance();
if (queue) {
- await queue.add(
- QueueJobs.DatasetRunItemUpsert,
- {
- payload: {
- projectId,
- datasetItemId: datasetItemId,
- traceId,
- observationId: observationId ?? undefined,
- },
- id: randomUUID(),
- timestamp: new Date(),
- name: QueueJobs.DatasetRunItemUpsert as const,
+ await queue.add(QueueJobs.DatasetRunItemUpsert, {
+ payload: {
+ projectId,
+ datasetItemId: datasetItemId,
+ traceId,
+ observationId: observationId ?? undefined,
},
- {
- attempts: 5, // retry 3 times
- backoff: {
- type: "exponential",
- delay: 1000,
- },
- delay: 30000, // 10 seconds
- removeOnComplete: true,
- removeOnFail: 1_000,
- },
- );
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.DatasetRunItemUpsert as const,
+ });
}
}
};
diff --git a/web/src/pages/api/public/dataset-run-items.ts b/web/src/pages/api/public/dataset-run-items.ts
index 24922f8d54..9ee6fd01e2 100644
--- a/web/src/pages/api/public/dataset-run-items.ts
+++ b/web/src/pages/api/public/dataset-run-items.ts
@@ -8,6 +8,8 @@ import {
} from "@/src/features/public-api/types/datasets";
import { LangfuseNotFoundError, InvalidRequestError } from "@langfuse/shared";
import { addDatasetRunItemsToEvalQueue } from "@/src/ee/features/evals/server/addDatasetRunItemsToEvalQueue";
+import { getObservationById } from "@langfuse/shared/src/server";
+import { env } from "@/src/env.mjs";
export default withMiddlewares({
POST: createAuthedAPIRoute({
@@ -49,14 +51,20 @@ export default withMiddlewares({
// Backwards compatibility: historically, dataset run items were linked to observations, not traces
if (!traceId && observationId) {
- const observation = observationId
- ? await prisma.observation.findUnique({
- where: {
- id: observationId,
- projectId: auth.scope.projectId,
- },
- })
- : undefined;
+ const observation =
+ env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? await getObservationById(
+ observationId,
+ auth.scope.projectId,
+ true,
+ )
+ : await prisma.observation.findUnique({
+ where: {
+ id: observationId,
+ projectId: auth.scope.projectId,
+ },
+ });
+
if (observationId && !observation) {
throw new LangfuseNotFoundError("Observation not found");
}
@@ -94,7 +102,7 @@ export default withMiddlewares({
const runItem = await prisma.datasetRunItems.create({
data: {
- datasetItemId: datasetItemId,
+ datasetItemId,
traceId: finalTraceId,
observationId,
datasetRunId: run.id,
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 30d852e9b2..a57c2f76d5 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -1,7 +1,13 @@
-import { expect, test, describe, afterAll, beforeAll, vi } from "vitest";
import {
- createDatasetEvalJobs,
- createTraceEvalJobs,
+ expect,
+ test,
+ describe,
+ afterAll,
+ beforeAll,
+ beforeEach,
+} from "vitest";
+import {
+ createEvalJobs,
evaluate,
extractVariablesFromTracingData,
} from "../features/evaluation/evalService";
@@ -18,7 +24,12 @@ import {
import { encrypt } from "@langfuse/shared/encryption";
import { OpenAIServer } from "./network";
import { afterEach } from "node:test";
-import { QueueName } from "@langfuse/shared/src/server";
+import {
+ convertDateToClickhouseDateTime,
+ QueueName,
+ upsertObservation,
+ upsertTrace,
+} from "@langfuse/shared/src/server";
import { Worker, Job, ConnectionOptions } from "bullmq";
import { compileHandlebarString } from "../features/utilities";
@@ -33,6 +44,10 @@ const openAIServer = new OpenAIServer({
});
beforeAll(openAIServer.setup);
+beforeEach(async () => {
+ await pruneDatabase();
+ openAIServer.respondWithDefault();
+});
afterEach(openAIServer.reset);
afterAll(openAIServer.teardown);
@@ -50,7 +65,6 @@ describe("eval service tests", () => {
describe("create eval jobs", () => {
test("creates new 'trace' eval job", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -61,6 +75,14 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await prisma.jobConfiguration.create({
data: {
id: randomUUID(),
@@ -80,7 +102,7 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -96,7 +118,6 @@ describe("eval service tests", () => {
}, 10_000);
test("creates new 'dataset' eval job", async () => {
- await pruneDatabase();
const traceId = randomUUID();
const observationId = randomUUID();
const datasetId = randomUUID();
@@ -110,6 +131,14 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("observations")
.values({
@@ -120,6 +149,16 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ type: "GENERATION",
+ start_time: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("datasets")
.values({
@@ -135,6 +174,8 @@ describe("eval service tests", () => {
id: datasetItemId,
project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
dataset_id: datasetId,
+ source_trace_id: traceId,
+ source_observation_id: observationId,
})
.execute();
@@ -159,7 +200,7 @@ describe("eval service tests", () => {
observationId: observationId,
};
- await createDatasetEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -176,8 +217,221 @@ describe("eval service tests", () => {
expect(jobs[0].start_time).not.toBeNull();
}, 10_000);
+ test("creates new eval job for a dataset on upsert of the trace", async () => {
+ const traceId = randomUUID();
+ const datasetId = randomUUID();
+ const datasetItemId = randomUUID();
+ const datasetRunId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("datasets")
+ .values({
+ id: datasetId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "test-dataset",
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_items")
+ .values({
+ id: datasetItemId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ dataset_id: datasetId,
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_runs")
+ .values({
+ id: datasetRunId,
+ name: randomUUID(),
+ dataset_id: datasetId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_run_items")
+ .values({
+ id: randomUUID(),
+ dataset_item_id: datasetItemId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ dataset_run_id: datasetRunId,
+ trace_id: traceId,
+ })
+ .execute();
+
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "dataset",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payloadDataset = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ datasetItemId: datasetItemId,
+ };
+
+ // This should exit early without an error as there is no trace yet.
+ await createEvalJobs({ event: payloadDataset });
+
+ const jobsAfterDataset = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ // No jobs should have been created.
+ expect(jobsAfterDataset.length).toBe(0);
+
+ // Now upsert the trace and validate that the job was created.
+ await kyselyPrisma.$kysely
+ .insertInto("traces")
+ .values({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ })
+ .execute();
+
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ const payloadTrace = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ };
+
+ await createEvalJobs({ event: payloadTrace });
+
+ const jobsAfterTrace = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobsAfterTrace.length).toBe(1);
+ expect(jobsAfterTrace[0].project_id).toBe(
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ );
+ expect(jobsAfterTrace[0].job_input_trace_id).toBe(traceId);
+ expect(jobsAfterTrace[0].job_input_dataset_item_id).toBe(datasetItemId);
+ expect(jobsAfterTrace[0].status.toString()).toBe("PENDING");
+ expect(jobsAfterTrace[0].start_time).not.toBeNull();
+ }, 10_000);
+
+ test("creates a new eval job for a dataset only if trace _and_ dataset are available", async () => {
+ const traceId = randomUUID();
+ const datasetId = randomUUID();
+ const datasetItemId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("datasets")
+ .values({
+ id: datasetId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "test-dataset",
+ })
+ .execute();
+
+ // Create the trace and send the trace event. No job should be created
+ await kyselyPrisma.$kysely
+ .insertInto("traces")
+ .values({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ })
+ .execute();
+
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "dataset",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ },
+ });
+
+ const payloadTrace = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId,
+ };
+
+ // This should exit early without an error as there is no trace yet.
+ await createEvalJobs({ event: payloadTrace });
+
+ const jobsAfterDataset = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ // No jobs should have been created.
+ expect(jobsAfterDataset.length).toBe(0);
+
+ // Now, create the dataset item and validate that the job was created.
+ await kyselyPrisma.$kysely
+ .insertInto("dataset_items")
+ .values({
+ id: datasetItemId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ dataset_id: datasetId,
+ source_trace_id: traceId,
+ })
+ .execute();
+
+ const payloadDataset = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId,
+ datasetItemId,
+ };
+
+ await createEvalJobs({ event: payloadDataset });
+
+ const jobsAfterTrace = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobsAfterTrace.length).toBe(1);
+ expect(jobsAfterTrace[0].project_id).toBe(
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ );
+ expect(jobsAfterTrace[0].job_input_trace_id).toBe(traceId);
+ expect(jobsAfterTrace[0].job_input_dataset_item_id).toBe(datasetItemId);
+ expect(jobsAfterTrace[0].status.toString()).toBe("PENDING");
+ expect(jobsAfterTrace[0].start_time).not.toBeNull();
+ }, 10_000);
+
test("does not create job for inactive config", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -208,7 +462,7 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -220,7 +474,6 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create eval job for existing job execution", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -231,6 +484,14 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("llm_api_keys")
.values({
@@ -263,8 +524,8 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
- await createTraceEvalJobs({ event: payload }); // calling it twice to check it is only generated once
+ await createEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload }); // calling it twice to check it is only generated once
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -281,7 +542,6 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create job for inactive config", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -312,7 +572,7 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -324,7 +584,6 @@ describe("eval service tests", () => {
}, 10_000);
test("does not create eval job for 0 sample rate", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -367,7 +626,7 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
const jobs = await kyselyPrisma.$kysely
.selectFrom("job_executions")
@@ -379,7 +638,6 @@ describe("eval service tests", () => {
}, 10_000);
test("cancels a job if the second event deselects", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -391,6 +649,15 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("llm_api_keys")
.values({
@@ -450,7 +717,10 @@ describe("eval service tests", () => {
traceId: traceId,
};
- await createTraceEvalJobs({ event: payload });
+ await createEvalJobs({ event: payload });
+
+ // Wait for .5s
+ await new Promise((resolve) => setTimeout(resolve, 500));
// update the trace to deselect the trace
await kyselyPrisma.$kysely
@@ -459,7 +729,15 @@ describe("eval service tests", () => {
.where("id", "=", traceId)
.execute();
- await createTraceEvalJobs({
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ await createEvalJobs({
event: payload,
}); // calling it twice to check it is only generated once
@@ -480,7 +758,6 @@ describe("eval service tests", () => {
describe("execute evals", () => {
test("evals a valid 'trace' event", async () => {
- await pruneDatabase();
openAIServer.respondWithDefault();
const traceId = randomUUID();
@@ -495,6 +772,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
const templateId = randomUUID();
await kyselyPrisma.$kysely
.insertInto("eval_templates")
@@ -597,7 +885,6 @@ describe("eval service tests", () => {
}, 10_000);
test("fails to eval without llm api key", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -692,7 +979,6 @@ describe("eval service tests", () => {
}, 10_000);
test("evals should cancel if job is cancelled", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -778,7 +1064,6 @@ describe("eval service tests", () => {
}, 10_000);
test("evals a valid 'trace' event and inserts score to ingestion pipeline", async () => {
- await pruneDatabase();
openAIServer.respondWithDefault();
const traceId = randomUUID();
@@ -915,7 +1200,6 @@ describe("eval service tests", () => {
describe("test variable extraction", () => {
test("extracts variables from a dataset item", async () => {
- await pruneDatabase();
const datasetId = randomUUID();
const datasetItemId = randomUUID();
const traceId = randomUUID();
@@ -985,7 +1269,6 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a trace", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -999,6 +1282,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
const variableMapping = variableMappingList.parse([
{
langfuseObject: "trace",
@@ -1032,7 +1326,6 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a observation", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -1046,6 +1339,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("observations")
.values({
@@ -1059,6 +1363,19 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "great-llm-name",
+ type: "GENERATION",
+ input: { huhu: "This is a great prompt" },
+ output: { haha: "This is a great response" },
+ start_time: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
const variableMapping = variableMappingList.parse([
{
langfuseObject: "generation",
@@ -1094,7 +1411,6 @@ describe("eval service tests", () => {
}, 10_000);
test("fails if observation is not present", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -1138,7 +1454,6 @@ describe("eval service tests", () => {
}, 10_000);
test("does not fail if observation data is null", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -1152,6 +1467,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
// fetching input and output for an observation which has NULL values
await kyselyPrisma.$kysely
.insertInto("observations")
@@ -1164,6 +1490,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "great-llm-name",
+ type: "GENERATION",
+ start_time: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
const variableMapping = variableMappingList.parse([
{
langfuseObject: "generation",
@@ -1199,7 +1536,6 @@ describe("eval service tests", () => {
}, 10_000);
test("extracts variables from a youngest observation", async () => {
- await pruneDatabase();
const traceId = randomUUID();
await kyselyPrisma.$kysely
@@ -1213,6 +1549,17 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: { input: "This is a great prompt" },
+ output: { output: "This is a great response" },
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("observations")
.values({
@@ -1226,6 +1573,22 @@ describe("eval service tests", () => {
output: { haha: "This is a great response" },
})
.execute();
+
+ await upsertObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "great-llm-name",
+ type: "GENERATION",
+ input: { huhu: "This is a great prompt" },
+ output: { haha: "This is a great response" },
+ start_time: convertDateToClickhouseDateTime(
+ new Date("2022-01-01T00:00:00.000Z"),
+ ),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
await kyselyPrisma.$kysely
.insertInto("observations")
.values({
@@ -1240,6 +1603,21 @@ describe("eval service tests", () => {
})
.execute();
+ await upsertObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "great-llm-name",
+ type: "GENERATION",
+ input: { huhu: "This is a great prompt again" },
+ output: { haha: "This is a great response again" },
+ start_time: convertDateToClickhouseDateTime(
+ new Date("2022-01-02T00:00:00.000Z"),
+ ),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
const variableMapping = variableMappingList.parse([
{
langfuseObject: "generation",
diff --git a/worker/src/__tests__/eventsApi.test.ts b/worker/src/__tests__/eventsApi.test.ts
deleted file mode 100644
index 9877a98ca1..0000000000
--- a/worker/src/__tests__/eventsApi.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { expect, test, describe } from "vitest";
-import { convertTraceUpsertEventsToRedisEvents } from "@langfuse/shared/src/server";
-
-describe.sequential("create redis events", () => {
- test("deduplicate events from the same project id", async () => {
- const events = [
- { traceId: "trace1", projectId: "project1" },
- { traceId: "trace2", projectId: "project1" },
- { traceId: "trace2", projectId: "project2" },
- { traceId: "trace3", projectId: "project2" },
- { traceId: "trace3", projectId: "project2" },
- ];
-
- const jobs = convertTraceUpsertEventsToRedisEvents(events);
-
- expect(jobs).toBeDefined();
- expect(jobs.length).toBe(4);
-
- const traceIdProjectIds = jobs.map((event) => ({
- projectId: event.data.payload.projectId,
- traceId: event.data.payload.traceId,
- }));
-
- expect(traceIdProjectIds).toEqual([
- { traceId: "trace1", projectId: "project1" },
- { traceId: "trace2", projectId: "project1" },
- { traceId: "trace2", projectId: "project2" },
- { traceId: "trace3", projectId: "project2" },
- ]);
- });
-});
diff --git a/worker/src/__tests__/network.ts b/worker/src/__tests__/network.ts
index 1232c9264c..3531e1e379 100644
--- a/worker/src/__tests__/network.ts
+++ b/worker/src/__tests__/network.ts
@@ -1,5 +1,5 @@
import { setupServer } from "msw/node";
-import { HttpResponse, http } from "msw";
+import { HttpResponse, http, passthrough } from "msw";
import { logger } from "@langfuse/shared/src/server";
const DEFAULT_RESPONSE = {
@@ -42,7 +42,7 @@ const DEFAULT_RESPONSE = {
function CompletionHandler(response: HttpResponse) {
return http.post("https://api.openai.com/v1/chat/completions", async () => {
- logger.info("handler");
+ logger.info("openai handler");
return response;
});
}
@@ -53,6 +53,7 @@ function JsonCompletionHandler(data: object) {
function MinioCompletionHandler() {
return http.all("http://localhost:9090*", async (request) => {
+ logger.info("minio handler");
if ((request.params[0] as string).startsWith("/langfuse/events/")) {
return new HttpResponse("Success");
}
@@ -60,6 +61,13 @@ function MinioCompletionHandler() {
});
}
+function ClickHouseCompletionHandler() {
+ return http.all("http://localhost:8123*", async (request) => {
+ logger.info("clickhouse handler");
+ return passthrough();
+ });
+}
+
function ErrorCompletionHandler(status: number, statusText: string) {
return CompletionHandler(
new HttpResponse(null, {
@@ -112,6 +120,7 @@ export class OpenAIServer {
this.internalServer.use(
JsonCompletionHandler(data),
MinioCompletionHandler(),
+ ClickHouseCompletionHandler(),
);
}
diff --git a/worker/src/__tests__/redisConsumer.test.ts b/worker/src/__tests__/redisConsumer.test.ts
index 82f7bff540..1403633559 100644
--- a/worker/src/__tests__/redisConsumer.test.ts
+++ b/worker/src/__tests__/redisConsumer.test.ts
@@ -48,15 +48,19 @@ describe.sequential("handle redis events", () => {
expect(traceUpsertQueue).toBeDefined();
- const job = await traceUpsertQueue?.add(QueueJobs.TraceUpsert, {
- id: randomUUID(),
- timestamp: new Date(),
- payload: {
- projectId: "project-id",
- traceId: "trace-id",
+ const job = await traceUpsertQueue?.add(
+ QueueJobs.TraceUpsert,
+ {
+ id: randomUUID(),
+ timestamp: new Date(),
+ payload: {
+ projectId: "project-id",
+ traceId: "trace-id",
+ },
+ name: QueueJobs.TraceUpsert as const,
},
- name: QueueJobs.TraceUpsert as const,
- });
+ { delay: 0 },
+ );
// Wait for 2s
await new Promise((resolve) => setTimeout(resolve, 2000));
diff --git a/worker/src/env.ts b/worker/src/env.ts
index a3683af855..73b5db4b45 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -91,6 +91,8 @@ const EnvSchema = z.object({
.default(5),
STRIPE_SECRET_KEY: z.string().optional(),
+ LANGFUSE_RETURN_FROM_CLICKHOUSE: z.enum(["true", "false"]).default("false"),
+
// Otel
OTEL_EXPORTER_OTLP_ENDPOINT: z.string().default("http://localhost:4318"),
OTEL_SERVICE_NAME: z.string().default("worker"),
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 05bb91bf17..1382a5b29c 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -1,14 +1,12 @@
import { randomUUID } from "crypto";
import { sql } from "kysely";
import { z } from "zod";
-import { ScoreSource } from "@prisma/client";
+import { ScoreSource, JobConfigState } from "@prisma/client";
import {
QueueJobs,
QueueName,
EvalExecutionEvent,
tableColumnsToSqlFilterAndPrefix,
- TraceUpsertEventSchema,
- DatasetRunItemUpsertEventSchema,
traceException,
S3StorageService,
eventTypes,
@@ -16,8 +14,13 @@ import {
IngestionQueue,
logger,
EvalExecutionQueue,
+ checkTraceExists,
+ checkObservationExists,
+ getTraceById,
+ getObservationForTraceIdByName,
+ TraceUpsertEventType,
+ DatasetRunItemUpsertEventType,
} from "@langfuse/shared/src/server";
-import { JobConfigState } from "@langfuse/shared/src/db";
import {
availableTraceEvalVariables,
ChatMessageRole,
@@ -56,17 +59,17 @@ const getS3StorageServiceClient = (bucketName: string): S3StorageService => {
// this function is used to determine which eval jobs to create for a given trace
// there might be multiple eval jobs to create for a single trace
-export const createTraceEvalJobs = async ({
+export const createEvalJobs = async ({
event,
}: {
- event: z.infer<typeof TraceUpsertEventSchema>;
+ event: TraceUpsertEventType | DatasetRunItemUpsertEventType;
}) => {
+ // Fetch all configs for a given project. Those may be dataset or trace configs.
const configs = await kyselyPrisma.$kysely
.selectFrom("job_configurations")
.selectAll()
.where(sql.raw("job_type::text"), "=", "EVAL")
.where("project_id", "=", event.projectId)
- .where("target_object", "=", "trace")
.execute();
if (configs.length === 0) {
@@ -87,13 +90,23 @@ export const createTraceEvalJobs = async ({
logger.debug("Creating eval job for config", config.id);
const validatedFilter = z.array(singleFilter).parse(config.filter);
- const condition = tableColumnsToSqlFilterAndPrefix(
- validatedFilter,
- evalTraceTableCols,
- "traces",
- );
+ // Check whether the trace already exists in the database.
+ let traceExists: boolean = false;
+ if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true") {
+ traceExists = await checkTraceExists(
+ event.projectId,
+ event.traceId,
+ new Date(),
+ config.target_object === "trace" ? validatedFilter : [],
+ );
+ } else {
+ const condition = tableColumnsToSqlFilterAndPrefix(
+ config.target_object === "trace" ? validatedFilter : [],
+ evalTraceTableCols,
+ "traces",
+ );
- const joinedQuery = Prisma.sql`
+ const joinedQuery = Prisma.sql`
SELECT id
FROM traces as t
WHERE project_id = ${event.projectId}
@@ -101,211 +114,109 @@ export const createTraceEvalJobs = async ({
${condition}
`;
- const traces = await prisma.$queryRaw<Array<{ id: string }>>(joinedQuery);
-
- const existingJob = await kyselyPrisma.$kysely
- .selectFrom("job_executions")
- .select("id")
- .where("project_id", "=", event.projectId)
- .where("job_configuration_id", "=", config.id)
- .where("job_input_trace_id", "=", event.traceId)
- .execute();
-
- // if we matched a trace, we might want to create a job
- if (traces.length > 0) {
- logger.debug(
- `Eval job for config ${config.id} matched trace ids ${JSON.stringify(traces.map((t) => t.id))}`,
- );
-
- const jobExecutionId = randomUUID();
+ const traces = await prisma.$queryRaw<Array<{ id: string }>>(joinedQuery);
+ traceExists = traces.length > 0;
+ }
- // deduplication: if a job exists already for a trace event, we do not create a new one.
- if (existingJob.length > 0) {
- logger.debug(
- `Eval job for config ${config.id} and trace ${event.traceId} already exists`,
+ const isDatasetConfig = config.target_object === "dataset";
+ let datasetItem:
+ | { id: string; sourceObservationId: string | undefined }
+ | undefined;
+ if (isDatasetConfig) {
+ // If the target object is a dataset and the event type has a datasetItemId, we try to fetch it based on our filter
+ if ("datasetItemId" in event && event.datasetItemId) {
+ const condition = tableColumnsToSqlFilterAndPrefix(
+ config.target_object === "dataset" ? validatedFilter : [],
+ evalDatasetFormFilterCols,
+ "dataset_items",
);
- continue;
- }
-
- // apply sampling. Only if the job is sampled, we create a job
- // user supplies a number between 0 and 1, which is the probability of sampling
- if (parseFloat(config.sampling) !== 1) {
- const random = Math.random();
- if (random > parseFloat(config.sampling)) {
- logger.debug(
- `Eval job for config ${config.id} and trace ${event.traceId} was sampled out`,
- );
- continue;
- }
+ const datasetItems = await prisma.$queryRaw<
+ Array<{ id: string; sourceObservationId: string | undefined }>
+ >(Prisma.sql`
+ SELECT id, source_observation_id as "sourceObservationId"
+ FROM dataset_items as di
+ WHERE project_id = ${event.projectId}
+ AND id = ${event.datasetItemId}
+ ${condition}
+ `);
+ datasetItem = datasetItems.shift();
+ } else {
+ // Otherwise, try to find the dataset item id from datasetRunItems.
+ // Here, we can search for the traceId and projectId and should only get one result.
+ const datasetItems = await prisma.$queryRaw<
+ Array<{ id: string; sourceObservationId: string | undefined }>
+ >(Prisma.sql`
+ SELECT dataset_item_id as id, observation_id as "sourceObservationId"
+ FROM dataset_run_items as dri
+ WHERE project_id = ${event.projectId}
+ AND trace_id = ${event.traceId}
+ `);
+ datasetItem = datasetItems.shift();
}
+ }
- logger.debug(
- `Creating eval job for config ${config.id} and trace ${event.traceId}`,
- );
-
- await prisma.jobExecution.create({
- data: {
- id: jobExecutionId,
- projectId: event.projectId,
- jobConfigurationId: config.id,
- jobInputTraceId: event.traceId,
- status: "PENDING",
- startTime: new Date(),
- },
- });
-
- // add the job to the next queue so that eval can be executed
- await EvalExecutionQueue.getInstance()?.add(
- QueueName.EvaluationExecution,
- {
- name: QueueJobs.EvaluationExecution,
- id: randomUUID(),
- timestamp: new Date(),
- payload: {
- projectId: event.projectId,
- jobExecutionId: jobExecutionId,
- delay: config.delay,
- },
- },
- {
- attempts: 10,
- backoff: {
- type: "exponential",
- delay: 1000,
- },
- delay: config.delay, // milliseconds
- removeOnComplete: true,
- removeOnFail: 1_000,
- },
- );
- } else {
- // if we do not have a match, and execution exists, we mark the job as cancelled
- // we do this, because a second trace event might 'deselect' a trace
- logger.debug(`Eval job for config ${config.id} did not match trace`);
- if (existingJob.length > 0) {
- logger.debug(
- `Cancelling eval job for config ${config.id} and trace ${event.traceId}`,
+ // We also need to validate that the observation exists in case an observationId is set
+ // If it's not set, we go into the retry loop. For the other events, we expect that the rerun
+ // is unnecessary, as we're triggering this flow if either event comes in.
+ const observationId =
+ "observationId" in event && event.observationId
+ ? event.observationId
+ : datasetItem?.sourceObservationId;
+ if (observationId) {
+ const observationExists =
+ env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? await checkObservationExists(
+ event.projectId,
+ observationId,
+ new Date(),
+ )
+ : await kyselyPrisma.$kysely
+ .selectFrom("observations")
+ .select("id")
+ .where("project_id", "=", event.projectId)
+ .where("id", "=", observationId)
+ .executeTakeFirst();
+
+ if (!observationExists) {
+ logger.warn(
+ `Observation ${observationId} not found, retrying dataset eval later`,
+ );
+ throw new Error(
+ "Observation not found. Rejecting job to use retry-attempts.",
);
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'CANCELLED'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .where("id", "=", existingJob[0].id)
- .execute();
}
}
- }
-};
-
-// this function is used to determine which eval jobs to create for a given dataset run item
-// there will only be one or no eval jobs to create for a single dataset run item
-export const createDatasetEvalJobs = async ({
- event,
-}: {
- event: z.infer<typeof DatasetRunItemUpsertEventSchema>;
-}) => {
- const configs = await kyselyPrisma.$kysely
- .selectFrom("job_configurations")
- .selectAll()
- .where(sql.raw("job_type::text"), "=", "EVAL")
- .where("project_id", "=", event.projectId)
- .where("target_object", "=", "dataset")
- .execute();
-
- if (configs.length === 0) {
- logger.debug("No evaluation jobs found for project", event.projectId);
- return;
- }
-
- logger.debug(
- `Creating eval jobs for dataset run item ${event.datasetItemId} on project ${event.projectId}`,
- );
-
- for (const config of configs) {
- if (config.status === JobConfigState.INACTIVE) {
- logger.debug(`Skipping inactive config ${config.id}`);
- continue;
- }
-
- logger.debug("Creating eval job for config", config.id);
- const validatedFilter = z.array(singleFilter).parse(config.filter);
-
- const condition = tableColumnsToSqlFilterAndPrefix(
- validatedFilter,
- evalDatasetFormFilterCols,
- "dataset_items",
- );
-
- const joinedQuery = Prisma.sql`
- SELECT id
- FROM dataset_items as di
- WHERE project_id = ${event.projectId}
- AND id = ${event.datasetItemId}
- ${condition}
- `;
-
- const datasetItems =
- await prisma.$queryRaw<Array<{ id: string }>>(joinedQuery);
+ // Fetch the existing job for the given configuration.
+ // We either use it for deduplication or we cancel it in case it became "deselected".
const existingJob = await kyselyPrisma.$kysely
.selectFrom("job_executions")
.select("id")
.where("project_id", "=", event.projectId)
.where("job_configuration_id", "=", config.id)
- .where("job_input_dataset_item_id", "=", event.datasetItemId)
.where("job_input_trace_id", "=", event.traceId)
+ .where(
+ "job_input_dataset_item_id",
+ datasetItem ? "=" : "is",
+ datasetItem ? datasetItem.id : null,
+ )
.where(
"job_input_observation_id",
- event.observationId ? "=" : "is",
- event.observationId ?? null,
+ observationId ? "=" : "is",
+ observationId || null,
)
.execute();
- // if we matched a dataset item, we might want to create a job
- if (datasetItems.length > 0) {
- // check if trace and observation exist, otherwise retry
- // Verify trace exists before proceeding
- const traceExists = await kyselyPrisma.$kysely
- .selectFrom("traces")
- .select("id")
- .where("project_id", "=", event.projectId)
- .where("id", "=", event.traceId)
- .executeTakeFirst();
-
- if (!traceExists) {
- logger.info(
- `Trace ${event.traceId} not found, retrying dataset eval later`,
- );
- throw new Error("Trace not found - initiate retry");
- }
-
- if (event.observationId) {
- const observationExists = await kyselyPrisma.$kysely
- .selectFrom("observations")
- .select("id")
- .where("project_id", "=", event.projectId)
- .where("id", "=", event.observationId)
- .executeTakeFirst();
-
- if (!observationExists) {
- logger.info(
- `Observation ${event.observationId} not found, retrying dataset eval later`,
- );
- throw new Error("Observation not found - initiate retry");
- }
- }
-
- logger.debug(
- `Eval job for config ${config.id} matched dataset run item ids ${JSON.stringify(datasetItems.map((d) => d.id))}`,
- );
-
+ // If we matched a trace for a trace event, we create a job or
+ // if we have both trace and datasetItem.
+ if (traceExists && (!isDatasetConfig || Boolean(datasetItem))) {
const jobExecutionId = randomUUID();
- // deduplication: if a job exists already for the given dataset item, trace and observation, we do not create a new one.
+ // deduplication: if a job exists already for a trace event, we do not create a new one.
if (existingJob.length > 0) {
logger.debug(
- `Eval job for config ${config.id}, dataset item ${event.datasetItemId} already exists for the given run`,
+ `Eval job for config ${config.id} and trace ${event.traceId} already exists`,
);
continue;
}
@@ -332,10 +243,14 @@ export const createDatasetEvalJobs = async ({
projectId: event.projectId,
jobConfigurationId: config.id,
jobInputTraceId: event.traceId,
- jobInputObservationId: event.observationId ?? null,
- jobInputDatasetItemId: event.datasetItemId,
status: "PENDING",
startTime: new Date(),
+ ...(datasetItem
+ ? {
+ jobInputDatasetItemId: datasetItem.id,
+ jobInputObservationId: datasetItem.sourceObservationId || null,
+ }
+ : {}),
},
});
@@ -353,14 +268,7 @@ export const createDatasetEvalJobs = async ({
},
},
{
- attempts: 10,
- backoff: {
- type: "exponential",
- delay: 1000,
- },
delay: config.delay, // milliseconds
- removeOnComplete: true,
- removeOnFail: 1_000,
},
);
} else {
@@ -369,7 +277,7 @@ export const createDatasetEvalJobs = async ({
logger.debug(`Eval job for config ${config.id} did not match trace`);
if (existingJob.length > 0) {
logger.debug(
- `Cancelling eval job for config ${config.id} and dataset item ${event.datasetItemId}`,
+ `Cancelling eval job for config ${config.id} and trace ${event.traceId}`,
);
await kyselyPrisma.$kysely
.updateTable("job_executions")
@@ -382,10 +290,6 @@ export const createDatasetEvalJobs = async ({
}
};
-// this function is used to determine which eval jobs to create for a given trace or dataset run item
-// there might be multiple eval jobs to create for a single trace
-// there might be 0 or 1 eval jobs to create for a single dataset run item
-
// for a single eval job, this function is used to evaluate the job
export const evaluate = async ({
event,
@@ -657,163 +561,172 @@ export async function extractVariablesFromTracingData({
// this here are variables which were inserted by users. Need to validate before DB query.
variableMapping: z.infer<typeof variableMappingList>;
datasetItemId?: string;
-}) {
- const mappingResult: { var: string; value: string }[] = [];
+}): Promise<{ var: string; value: string }[]> {
+ return Promise.all(
+ variables.map(async (variable) => {
+ const mapping = variableMapping.find(
+ (m) => m.templateVariable === variable,
+ );
- // find the context for each variable of the template
- for (const variable of variables) {
- const mapping = variableMapping.find(
- (m) => m.templateVariable === variable,
- );
+ if (!mapping) {
+ logger.debug(`No mapping found for variable ${variable}`);
+ return { var: variable, value: "" };
+ }
- if (!mapping) {
- logger.debug(`No mapping found for variable ${variable}`);
- mappingResult.push({ var: variable, value: "" });
- continue; // no need to fetch additional data
- }
+ if (mapping.langfuseObject === "dataset_item") {
+ if (!datasetItemId) {
+ logger.error(
+ `No dataset item id found for variable ${variable}. Eval will succeed without dataset item input.`,
+ );
+ return { var: variable, value: "" };
+ }
- if (mapping.langfuseObject === "dataset_item") {
- if (!datasetItemId) {
- logger.error(
- `No dataset item id found for variable ${variable}. Eval will succeed without dataset item input.`,
- );
- mappingResult.push({ var: variable, value: "" });
- continue;
- }
+ // find the internal definitions of the column
+ const safeInternalColumn = availableDatasetEvalVariables
+ .find((o) => o.id === "dataset_item")
+ ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
- // find the internal definitions of the column
- const safeInternalColumn = availableDatasetEvalVariables
- .find((o) => o.id === "dataset_item")
- ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
+ // if no column was found, we still process with an empty variable
+ if (!safeInternalColumn?.id) {
+ logger.error(
+ `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
+ );
+ return { var: variable, value: "" };
+ }
- // if no column was found, we still process with an empty variable
- if (!safeInternalColumn?.id) {
- logger.error(
- `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
- );
- mappingResult.push({ var: variable, value: "" });
- continue;
- }
+ const datasetItem = await kyselyPrisma.$kysely
+ .selectFrom("dataset_items as d")
+ .select(
+ sql`${sql.raw(safeInternalColumn.internal)}`.as(
+ safeInternalColumn.id,
+ ),
+ ) // query the internal column name raw
+ .where("id", "=", datasetItemId)
+ .where("project_id", "=", projectId)
+ .executeTakeFirst();
- const datasetItem = await kyselyPrisma.$kysely
- .selectFrom("dataset_items as d")
- .select(
- sql`${sql.raw(safeInternalColumn.internal)}`.as(
- safeInternalColumn.id,
- ),
- ) // query the internal column name raw
- .where("id", "=", datasetItemId)
- .where("project_id", "=", projectId)
- .executeTakeFirst();
-
- // user facing errors
- if (!datasetItem) {
- logger.error(
- `Dataset item ${datasetItemId} for project ${projectId} not found. Eval will succeed without dataset item input. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
- );
- throw new LangfuseNotFoundError(
- `Dataset item ${datasetItemId} for project ${projectId} not found. Eval will succeed without dataset item input. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
- );
+ // user facing errors
+ if (!datasetItem) {
+ logger.error(
+ `Dataset item ${datasetItemId} for project ${projectId} not found. Eval will succeed without dataset item input. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
+ );
+ throw new LangfuseNotFoundError(
+ `Dataset item ${datasetItemId} for project ${projectId} not found. Eval will succeed without dataset item input. Please ensure the mapped data on the dataset item exists and consider extending the job delay.`,
+ );
+ }
+
+ return {
+ var: variable,
+ value: parseUnknownToString(datasetItem[mapping.selectedColumnId]),
+ };
}
- mappingResult.push({
- var: variable,
- value: parseUnknownToString(datasetItem[mapping.selectedColumnId]),
- });
- }
+ if (mapping.langfuseObject === "trace") {
+ // find the internal definitions of the column
+ const safeInternalColumn = availableTraceEvalVariables
+ .find((o) => o.id === "trace")
+ ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
- if (mapping.langfuseObject === "trace") {
- // find the internal definitions of the column
- const safeInternalColumn = availableTraceEvalVariables
- .find((o) => o.id === "trace")
- ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
+ // if no column was found, we still process with an empty variable
+ if (!safeInternalColumn?.id) {
+ logger.error(
+ `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
+ );
+ return { var: variable, value: "" };
+ }
- // if no column was found, we still process with an empty variable
- if (!safeInternalColumn?.id) {
- logger.error(
- `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
- );
- mappingResult.push({ var: variable, value: "" });
- continue;
- }
+ const trace: Record<string, unknown> | undefined =
+ env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? await getTraceById(traceId, projectId)
+ : await kyselyPrisma.$kysely
+ .selectFrom("traces as t")
+ .select(
+ sql`${sql.raw(safeInternalColumn.internal)}`.as(
+ safeInternalColumn.id,
+ ),
+ ) // query the internal column name raw
+ .where("id", "=", traceId)
+ .where("project_id", "=", projectId)
+ .executeTakeFirst();
+
+ // user facing errors
+ if (!trace) {
+ logger.error(
+ `Trace ${traceId} for project ${projectId} not found. Eval will succeed without trace input. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
+ );
+ throw new LangfuseNotFoundError(
+ `Trace ${traceId} for project ${projectId} not found. Eval will succeed without trace input. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
+ );
+ }
- const trace = await kyselyPrisma.$kysely
- .selectFrom("traces as t")
- .select(
- sql`${sql.raw(safeInternalColumn.internal)}`.as(
- safeInternalColumn.id,
- ),
- ) // query the internal column name raw
- .where("id", "=", traceId)
- .where("project_id", "=", projectId)
- .executeTakeFirst();
-
- // user facing errors
- if (!trace) {
- logger.error(
- `Trace ${traceId} for project ${projectId} not found. Eval will succeed without trace input. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
- );
- throw new LangfuseNotFoundError(
- `Trace ${traceId} for project ${projectId} not found. Eval will succeed without trace input. Please ensure the mapped data on the trace exists and consider extending the job delay.`,
- );
+ return {
+ var: variable,
+ value: parseUnknownToString(trace[mapping.selectedColumnId]),
+ };
}
- mappingResult.push({
- var: variable,
- value: parseUnknownToString(trace[mapping.selectedColumnId]),
- });
- }
- if (["generation", "span", "event"].includes(mapping.langfuseObject)) {
- const safeInternalColumn = availableTraceEvalVariables
- .find((o) => o.id === mapping.langfuseObject)
- ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
-
- if (!mapping.objectName) {
- logger.info(
- `No object name found for variable ${variable} and object ${mapping.langfuseObject}`,
- );
- mappingResult.push({ var: variable, value: "" });
- continue;
- }
+ if (["generation", "span", "event"].includes(mapping.langfuseObject)) {
+ const safeInternalColumn = availableTraceEvalVariables
+ .find((o) => o.id === mapping.langfuseObject)
+ ?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
- if (!safeInternalColumn?.id) {
- logger.warn(
- `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
- );
- mappingResult.push({ var: variable, value: "" });
- continue;
- }
+ if (!mapping.objectName) {
+ logger.info(
+ `No object name found for variable ${variable} and object ${mapping.langfuseObject}`,
+ );
+ return { var: variable, value: "" };
+ }
- const observation = await kyselyPrisma.$kysely
- .selectFrom("observations as o")
- .select(
- sql`${sql.raw(safeInternalColumn.internal)}`.as(
- safeInternalColumn.id,
- ),
- ) // query the internal column name raw
- .where("trace_id", "=", traceId)
- .where("project_id", "=", projectId)
- .where("name", "=", mapping.objectName)
- .orderBy("start_time", "desc")
- .executeTakeFirst();
-
- // user facing errors
- if (!observation) {
- logger.error(
- `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
- );
- throw new LangfuseNotFoundError(
- `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
- );
+ if (!safeInternalColumn?.id) {
+ logger.warn(
+ `No column found for variable ${variable} and column ${mapping.selectedColumnId}`,
+ );
+ return { var: variable, value: "" };
+ }
+
+ const observation: Record<string, unknown> | undefined =
+ env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? (
+ await getObservationForTraceIdByName(
+ traceId,
+ projectId,
+ mapping.objectName,
+ undefined,
+ true,
+ )
+ ).shift() // We only take the first match and ignore duplicate generation-names in a trace.
+ : await kyselyPrisma.$kysely
+ .selectFrom("observations as o")
+ .select(
+ sql`${sql.raw(safeInternalColumn.internal)}`.as(
+ safeInternalColumn.id,
+ ),
+ ) // query the internal column name raw
+ .where("trace_id", "=", traceId)
+ .where("project_id", "=", projectId)
+ .where("name", "=", mapping.objectName)
+ .orderBy("start_time", "desc")
+ .executeTakeFirst();
+
+ // user facing errors
+ if (!observation) {
+ logger.error(
+ `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
+ );
+ throw new LangfuseNotFoundError(
+ `Observation ${mapping.objectName} for trace ${traceId} not found. Please ensure the mapped data exists and consider extending the job delay.`,
+ );
+ }
+
+ return {
+ var: variable,
+ value: parseUnknownToString(observation[mapping.selectedColumnId]),
+ };
}
- mappingResult.push({
- var: variable,
- value: parseUnknownToString(observation[mapping.selectedColumnId]),
- });
- }
- }
- return mappingResult;
+ throw new Error(`Unknown object type ${mapping.langfuseObject}`);
+ }),
+ );
}
export const parseUnknownToString = (value: unknown): string => {
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 6d6a544fcb..3247f4ed8d 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -1,10 +1,6 @@
import { Job } from "bullmq";
import { ApiError, BaseError } from "@langfuse/shared";
-import {
- createDatasetEvalJobs,
- createTraceEvalJobs,
- evaluate,
-} from "../features/evaluation/evalService";
+import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
import { kyselyPrisma } from "@langfuse/shared/src/db";
import { sql } from "kysely";
import {
@@ -18,7 +14,7 @@ export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
) => {
try {
- await createTraceEvalJobs({ event: job.data.payload });
+ await createEvalJobs({ event: job.data.payload });
return true;
} catch (e) {
logger.error(
@@ -34,7 +30,7 @@ export const evalJobDatasetCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.DatasetRunItemUpsert]>,
) => {
try {
- await createDatasetEvalJobs({ event: job.data.payload });
+ await createEvalJobs({ event: job.data.payload });
return true;
} catch (e) {
logger.error(
diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.ts
index 640c3834f0..b8284d5702 100644
--- a/worker/src/queues/legacyIngestionQueue.ts
+++ b/worker/src/queues/legacyIngestionQueue.ts
@@ -9,10 +9,7 @@ import {
getClickhouseEntityType,
} from "@langfuse/shared/src/server";
-import {
- handleBatch,
- addTracesToTraceUpsertQueue,
-} from "@langfuse/shared/src/server";
+import { handleBatch } from "@langfuse/shared/src/server";
import { tokenCount } from "../features/tokenisation/usage";
import { env } from "../env";
import { ForbiddenError, UnauthorizedError } from "@langfuse/shared";
@@ -108,12 +105,6 @@ export const legacyIngestionQueueProcessor: Processor = async (
});
throw new Error(`Failed to process ${processingErrors.length} events`);
}
-
- // send out REDIS requests to worker for all trace types
- await addTracesToTraceUpsertQueue(
- result.results,
- job.data.payload.authCheck.scope.projectId,
- );
} catch (e) {
logger.error(
`Failed job legacy ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 502a3f717f..95db176b4b 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -33,11 +33,14 @@ import {
validateAndInflateScore,
UsageCostType,
convertDateToClickhouseDateTime,
+ TraceUpsertQueue,
+ QueueJobs,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
import { ClickhouseWriter, TableName } from "../ClickhouseWriter";
import { convertJsonSchemaToRecord, overwriteObject } from "./utils";
+import { randomUUID } from "crypto";
type InsertRecord =
| TraceRecordInsertType
@@ -270,6 +273,22 @@ export class IngestionService {
}
this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);
+
+ // Add trace into trace upsert queue for eval processing
+ const traceUpsertQueue = TraceUpsertQueue.getInstance();
+ if (!traceUpsertQueue) {
+ logger.error("TraceUpsertQueue is not initialized");
+ return;
+ }
+ await traceUpsertQueue.add(QueueJobs.TraceUpsert, {
+ payload: {
+ projectId: finalTraceRecord.project_id,
+ traceId: finalTraceRecord.id,
+ },
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.TraceUpsert as const,
+ });
}
private async processObservationEventList(params: {