Skip to content

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

chore: fix dataset eval executions for historic evals (#7001)

Max Deichmanncf52dce773da
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 6b58c0742f..fc57ec1189 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -42,12 +42,19 @@ import { recordDistribution } from "../instrumentation";
* • Filters within ±2 day window
* • Used for validating trace references before eval job creation
*/
-export const checkTraceExists = async (
- projectId: string,
- traceId: string,
- timestamp: Date,
- filter: FilterState,
-): Promise<boolean> => {
+export const checkTraceExists = async ({
+ projectId,
+ traceId,
+ timestamp,
+ filter,
+ maxTimeStamp,
+}: {
+ projectId: string;
+ traceId: string;
+ timestamp: Date;
+ filter: FilterState;
+ maxTimeStamp: Date | undefined;
+}): Promise<boolean> => {
const { tracesFilter } = getProjectIdDefaultFilter(projectId, {
tracesPrefix: "t",
});
@@ -102,7 +109,8 @@ export const checkTraceExists = async (
WHERE ${tracesFilterRes.query}
AND t.project_id = {projectId: String}
AND timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}
- AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY
+ ${maxTimeStamp ? `AND timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}
+ ${!maxTimeStamp ? `AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}
GROUP BY t.id, t.project_id
`;
@@ -115,6 +123,9 @@ export const checkTraceExists = async (
...(timestamp
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
+ ...(maxTimeStamp
+ ? { maxTimeStamp: convertDateToClickhouseDateTime(maxTimeStamp) }
+ : {}),
},
tags: {
feature: "tracing",
diff --git a/web/src/__tests__/async/repositories/trace-repository.servertest.ts b/web/src/__tests__/async/repositories/trace-repository.servertest.ts
index 608bed840e..cee983761e 100644
--- a/web/src/__tests__/async/repositories/trace-repository.servertest.ts
+++ b/web/src/__tests__/async/repositories/trace-repository.servertest.ts
@@ -16,13 +16,15 @@ describe("Clickhouse Traces Repository Test", () => {
});
it("should throw if no traces are found", async () => {
- expect(await getTraceById({ traceId: v4(), projectId: v4() })).toBeUndefined();
+ expect(
+ await getTraceById({ traceId: v4(), projectId: v4() }),
+ ).toBeUndefined();
});
it("should return a trace if it exists", async () => {
const traceId = v4();
- const trace = {
+ const trace = createTrace({
id: traceId,
project_id: projectId,
session_id: v4(),
@@ -47,7 +49,7 @@ describe("Clickhouse Traces Repository Test", () => {
updated_at: Date.now(),
event_ts: Date.now(),
is_deleted: 0,
- };
+ });
await createTracesCh([trace]);
@@ -71,7 +73,7 @@ describe("Clickhouse Traces Repository Test", () => {
expect(result.userId).toEqual(trace.user_id);
expect(result.sessionId).toEqual(trace.session_id);
expect(result.public).toEqual(trace.public);
- expect(result.input).toEqual(JSON.parse(trace.input));
+ expect(result.input).toEqual(JSON.parse(trace.input ?? "{}"));
expect(result.output).toEqual("regular string");
expect(result.metadata).toEqual(trace.metadata);
expect(result.createdAt).toEqual(new Date(trace.created_at));
@@ -81,7 +83,7 @@ describe("Clickhouse Traces Repository Test", () => {
it("should find a trace if no timestamp is provided", async () => {
const traceId = v4();
- const trace = {
+ const trace = createTrace({
id: traceId,
project_id: projectId,
session_id: v4(),
@@ -98,7 +100,7 @@ describe("Clickhouse Traces Repository Test", () => {
updated_at: Date.now(),
event_ts: Date.now(),
is_deleted: 0,
- };
+ });
await createTracesCh([trace]);
@@ -126,7 +128,7 @@ describe("Clickhouse Traces Repository Test", () => {
});
it("should retrieve traces by session ID", async () => {
const sessionId = v4();
- const trace1 = {
+ const trace1 = createTrace({
id: v4(),
project_id: projectId,
session_id: sessionId,
@@ -143,9 +145,9 @@ describe("Clickhouse Traces Repository Test", () => {
updated_at: Date.now(),
event_ts: Date.now(),
is_deleted: 0,
- };
+ });
- const trace2 = {
+ const trace2 = createTrace({
id: v4(),
project_id: projectId,
session_id: sessionId,
@@ -162,7 +164,7 @@ describe("Clickhouse Traces Repository Test", () => {
updated_at: Date.now(),
event_ts: Date.now(),
is_deleted: 0,
- };
+ });
await createTracesCh([trace1, trace2]);
@@ -212,14 +214,20 @@ describe("Clickhouse Traces Repository Test", () => {
await createTracesCh([trace]);
await createObservationsCh(observations);
- const exists = await checkTraceExists(projectId, traceId, new Date(), [
- {
- type: "stringOptions",
- column: "level",
- operator: "any of",
- value: ["ERROR"],
- },
- ]);
+ const exists = await checkTraceExists({
+ projectId,
+ traceId,
+ timestamp: new Date(),
+ filter: [
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ],
+ maxTimeStamp: undefined,
+ });
expect(exists).toBe(true);
});
@@ -261,14 +269,20 @@ describe("Clickhouse Traces Repository Test", () => {
await createTracesCh([trace]);
await createObservationsCh(observations);
- const exists = await checkTraceExists(projectId, traceId, new Date(), [
- {
- type: "stringOptions",
- column: "level",
- operator: "none of",
- value: ["ERROR"],
- },
- ]);
+ const exists = await checkTraceExists({
+ projectId,
+ traceId,
+ timestamp: new Date(),
+ filter: [
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "none of",
+ value: ["ERROR"],
+ },
+ ],
+ maxTimeStamp: undefined,
+ });
expect(exists).toBe(false);
});
it("should check if trace exists without level filter", async () => {
@@ -309,7 +323,13 @@ describe("Clickhouse Traces Repository Test", () => {
await createTracesCh([trace]);
await createObservationsCh(observations);
- const exists = await checkTraceExists(projectId, traceId, new Date(), []);
+ const exists = await checkTraceExists({
+ projectId,
+ traceId,
+ timestamp: new Date(),
+ filter: [],
+ maxTimeStamp: undefined,
+ });
expect(exists).toBe(true);
});
it("should check if trace exists with error level count > 0", async () => {
@@ -350,14 +370,20 @@ describe("Clickhouse Traces Repository Test", () => {
await createTracesCh([trace]);
await createObservationsCh(observations);
- const exists = await checkTraceExists(projectId, traceId, new Date(), [
- {
- type: "number",
- column: "errorCount",
- operator: ">",
- value: 0,
- },
- ]);
+ const exists = await checkTraceExists({
+ projectId,
+ traceId,
+ timestamp: new Date(),
+ filter: [
+ {
+ type: "number",
+ column: "errorCount",
+ operator: ">",
+ value: 0,
+ },
+ ],
+ maxTimeStamp: undefined,
+ });
expect(exists).toBe(true);
});
});
diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.ts
index b0d5b7c4cb..df6663d17a 100644
--- a/web/src/ee/features/evals/server/router.ts
+++ b/web/src/ee/features/evals/server/router.ts
@@ -830,7 +830,7 @@ export const evalRouter = createTRPCRouter({
cutoffCreatedAt: new Date(),
targetObject: input.target,
query: {
- where: input.filter ?? [],
+ filter: input.filter ?? [],
orderBy: {
column: "timestamp",
order: "DESC",
diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.ts
index 9350dc2add..107f291064 100644
--- a/worker/src/ee/evaluation/evalService.ts
+++ b/worker/src/ee/evaluation/evalService.ts
@@ -194,14 +194,24 @@ export const createEvalJobs = async ({
logger.debug("Creating eval job for config", config.id);
const validatedFilter = z.array(singleFilter).parse(config.filter);
+ const maxTimeStamp =
+ "timestamp" in event &&
+ new Date(event.timestamp).getTime() === new Date("2020-01-01").getTime() // min time for historic evals
+ ? new Date()
+ : undefined;
+
// Check whether the trace already exists in the database.
- const traceExists = await checkTraceExists(
- event.projectId,
- event.traceId,
+ const traceExists = await checkTraceExists({
+ projectId: event.projectId,
+ traceId: event.traceId,
// Fallback to jobTimestamp if no payload timestamp is set to allow for successful retry attempts.
- "timestamp" in event ? new Date(event.timestamp) : new Date(jobTimestamp),
- config.target_object === "trace" ? validatedFilter : [],
- );
+ timestamp:
+ "timestamp" in event
+ ? new Date(event.timestamp)
+ : new Date(jobTimestamp),
+ filter: config.target_object === "trace" ? validatedFilter : [],
+ maxTimeStamp,
+ });
const isDatasetConfig = config.target_object === "dataset";
let datasetItem: { id: string } | undefined;
@@ -313,7 +323,7 @@ export const createEvalJobs = async ({
}
logger.debug(
- `Creating eval job for config ${config.id} and trace ${event.traceId}`,
+ `Creating eval job execution for config ${config.id} and trace ${event.traceId}`,
);
await prisma.jobExecution.create({
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 0438c6e9aa..0dc01b3b39 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -8,7 +8,6 @@ import {
TQueueJobTypes,
} from "@langfuse/shared/src/server";
import {
- BatchActionQuery,
BatchActionType,
BatchExportTableName,
FilterCondition,
@@ -24,15 +23,10 @@ import { randomUUID } from "node:crypto";
import { processClickhouseScoreDelete } from "../scores/processClickhouseScoreDelete";
const CHUNK_SIZE = 1000;
-const convertDatesInQuery = (query: BatchActionQuery) => {
- if (!query.filter) return query;
-
- return {
- ...query,
- filter: query.filter.map((f: FilterCondition) =>
- f.type === "datetime" ? { ...f, value: new Date(f.value) } : f,
- ),
- };
+const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {
+ return filters.map((f: FilterCondition) =>
+ f.type === "datetime" ? { ...f, value: new Date(f.value) } : f,
+ );
};
/**
@@ -145,7 +139,8 @@ export const handleBatchActionJob = async (
const dbReadStream = await getDatabaseReadStream({
projectId: projectId,
cutoffCreatedAt: new Date(cutoffCreatedAt),
- ...convertDatesInQuery(query),
+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),
+ orderBy: query.orderBy,
tableName: tableName as unknown as BatchExportTableName,
exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,
});
@@ -193,7 +188,8 @@ export const handleBatchActionJob = async (
const dbReadStream = await getDatabaseReadStream({
projectId: projectId,
cutoffCreatedAt: new Date(cutoffCreatedAt),
- ...convertDatesInQuery(query),
+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),
+ orderBy: query.orderBy,
tableName:
targetObject === "trace"
? BatchExportTableName.Traces
diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
index 7499e3f48c..720dc6bb25 100644
--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts
+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
@@ -4,6 +4,7 @@ import {
TimeFilter,
BatchExportQueryType,
ScoreDomain,
+ evalDatasetFormFilterCols,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -19,6 +20,7 @@ import {
getTracesTableMetrics,
getTracesByIds,
getScoresForTraces,
+ tableColumnsToSqlFilterAndPrefix,
} from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
import { env } from "../../env";
@@ -375,6 +377,12 @@ export const getDatabaseReadStream = async ({
case "dataset_run_items": {
return new DatabaseReadStream<unknown>(
async (pageSize: number, offset: number) => {
+ const condition = tableColumnsToSqlFilterAndPrefix(
+ filter ?? [],
+ evalDatasetFormFilterCols,
+ "dataset_items",
+ );
+
const items = await prisma.$queryRaw<
Array<{
id: string;
@@ -394,7 +402,7 @@ export const getDatabaseReadStream = async ({
JOIN datasets d ON di.dataset_id = d.id AND d.project_id = dri.project_id
WHERE dri.project_id = ${projectId}
AND dri.created_at < ${cutoffCreatedAt}
-
+ ${condition}
ORDER BY dri.created_at DESC
LIMIT ${pageSize}
OFFSET ${offset}