🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
perf(evals): propagate trace timestamp to eval execution for better trace and observations filtering (#8687)
marliessophie43ffd1b72d68
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 04bf12971a..8c32e69ca8 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -474,6 +474,7 @@ export type JobExecution = {end_time: Timestamp | null;error: string | null;job_input_trace_id: string | null;+ job_input_trace_timestamp: Timestamp | null;job_input_observation_id: string | null;job_input_dataset_item_id: string | null;job_output_score_id: string | null;diff --git a/packages/shared/prisma/migrations/20250825100104_job_executions_add_input_trace_timestamp/migration.sql b/packages/shared/prisma/migrations/20250825100104_job_executions_add_input_trace_timestamp/migration.sqlnew file mode 100644index 0000000000..65c6e74f1c--- /dev/null+++ b/packages/shared/prisma/migrations/20250825100104_job_executions_add_input_trace_timestamp/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "job_executions" ADD COLUMN "job_input_trace_timestamp" TIMESTAMP(3);diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 639323cc36..20c94a5a1d 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -916,6 +916,8 @@ model JobExecution {jobInputTraceId String? @map("job_input_trace_id") // no fk constraint - traces in ClickHouse, deletion handled via project cascade+ jobInputTraceTimestamp DateTime? @map("job_input_trace_timestamp")+jobInputObservationId String? @map("job_input_observation_id") // no fk constraint - observations in ClickHouse, deletion handled via project cascadejobInputDatasetItemId String? @map("job_input_dataset_item_id") // no fk constraint - job execution sensible standalonediff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 24ddce70b7..abdde96dd2 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -227,13 +227,19 @@ export const getObservationsForTrace = async <IncludeIO extends boolean>(});};-export const getObservationForTraceIdByName = async (- traceId: string,- projectId: string,- name: string,- timestamp?: Date,- fetchWithInputOutput: boolean = false,-) => {+export const getObservationForTraceIdByName = async ({+ traceId,+ projectId,+ name,+ timestamp,+ fetchWithInputOutput = false,+}: {+ traceId: string;+ projectId: string;+ name: string;+ timestamp?: Date;+ fetchWithInputOutput?: boolean;+}) => {const query = `SELECTid,diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 8f9808b782..ee206eb991 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -83,6 +83,7 @@ export const getTimeframesTracesAMT = (/*** Checks if trace exists in clickhouse.+ * Additionally, give back the timestamp of the trace as metadata.** @param {string} projectId - Project ID for the trace* @param {string} traceId - ID of the trace to check@@ -94,7 +95,7 @@ export const getTimeframesTracesAMT = (* • Filters within ±2 day window* • Used for validating trace references before eval job creation*/-export const checkTraceExists = async ({+export const checkTraceExistsAndGetTimestamp = async ({projectId,traceId,timestamp,@@ -108,7 +109,7 @@ export const checkTraceExists = async ({filter: FilterState;maxTimeStamp: Date | undefined;exactTimestamp?: Date;-}): Promise<boolean> => {+}): Promise<{ exists: boolean; timestamp?: Date }> => {const { tracesFilter } = getProjectIdDefaultFilter(projectId, {tracesPrefix: "t",});@@ -158,7 +159,7 @@ export const checkTraceExists = async ({`;return measureAndReturn({- operationName: "checkTraceExists",+ operationName: "checkTraceExistsAndGetTimestamp",projectId,minStartTime: timestamp ?? exactTimestamp,input: {@@ -181,7 +182,7 @@ export const checkTraceExists = async ({type: "trace",kind: "exists",projectId,- operation_name: "checkTraceExists",+ operation_name: "checkTraceExistsAndGetTimestamp",},timestamp: timestamp ?? exactTimestamp,},@@ -190,7 +191,8 @@ export const checkTraceExists = async ({${observations_cte}SELECTt.id as id,- t.project_id as project_id+ t.project_id as project_id,+ t.timestamp as timestampFROM traces t FINAL${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}WHERE ${tracesFilterRes.query}@@ -199,16 +201,26 @@ export const checkTraceExists = async ({${maxTimeStamp ? `AND timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}${!maxTimeStamp ? `AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}${exactTimestamp ? `AND timestamp = {exactTimestamp: DateTime64(3)}` : ""}- GROUP BY t.id, t.project_id+ GROUP BY t.id, t.project_id, t.timestamp`;- const rows = await queryClickhouse<{ id: string; project_id: string }>({+ const rows = await queryClickhouse<{+ id: string;+ project_id: string;+ timestamp: string;+ }>({query,params: input.params,tags: { ...input.tags, experiment_amt: "original" },});- return rows.length > 0;+ return {+ exists: rows.length > 0,+ timestamp:+ rows.length > 0+ ? parseClickhouseUTCDateTimeFormat(rows[0].timestamp)+ : undefined,+ };},newExecution: async (input) => {const traceAmt = getTimeframesTracesAMT(input.timestamp);@@ -225,13 +237,23 @@ export const checkTraceExists = async ({AND t.project_id = {projectId: String}`;- const rows = await queryClickhouse<{ id: string; project_id: string }>({+ const rows = await queryClickhouse<{+ id: string;+ project_id: string;+ timestamp: string;+ }>({query,params: input.params,tags: { ...input.tags, experiment_amt: "new" },});- return rows.length > 0;+ return {+ exists: rows.length > 0,+ timestamp:+ rows.length > 0+ ? parseClickhouseUTCDateTimeFormat(rows[0].timestamp)+ : undefined,+ };},});};diff --git a/web/src/__tests__/async/repositories/trace-repository.servertest.ts b/web/src/__tests__/async/repositories/trace-repository.servertest.tsindex 70c996476a..82b6dba99f 100644--- a/web/src/__tests__/async/repositories/trace-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/trace-repository.servertest.ts@@ -1,4 +1,7 @@-import { checkTraceExists, createTracesCh } from "@langfuse/shared/src/server";+import {+ checkTraceExistsAndGetTimestamp,+ createTracesCh,+} from "@langfuse/shared/src/server";import {getTraceById,getTracesBySessionId,@@ -215,7 +218,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);await createObservationsCh(observations);- const exists = await checkTraceExists({+ const { exists } = await checkTraceExistsAndGetTimestamp({projectId,traceId,timestamp: new Date(),@@ -270,7 +273,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);await createObservationsCh(observations);- const exists = await checkTraceExists({+ const { exists } = await checkTraceExistsAndGetTimestamp({projectId,traceId,timestamp: new Date(),@@ -324,7 +327,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);await createObservationsCh(observations);- const exists = await checkTraceExists({+ const { exists } = await checkTraceExistsAndGetTimestamp({projectId,traceId,timestamp: new Date(),@@ -371,7 +374,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);await createObservationsCh(observations);- const exists = await checkTraceExists({+ const { exists } = await checkTraceExistsAndGetTimestamp({projectId,traceId,timestamp: new Date(),@@ -388,7 +391,7 @@ describe("Clickhouse Traces Repository Test", () => {expect(exists).toBe(true);});- it("should handle timestamp filter in checkTraceExists", async () => {+ it("should handle timestamp filter in checkTraceExistsAndGetTimestamp", async () => {const traceId = v4();const trace = createTrace({id: traceId,@@ -402,7 +405,7 @@ describe("Clickhouse Traces Repository Test", () => {await createTracesCh([trace]);- const exists = await checkTraceExists({+ const { exists } = await checkTraceExistsAndGetTimestamp({projectId,traceId,timestamp: new Date(),diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex 30ed0f0d71..304b737fa7 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -15,8 +15,6 @@ import {createTracesCh,upsertObservation,upsertTrace,- checkTraceExists,- getTraceById,createDatasetRunItemsCh,createDatasetRunItem,} from "@langfuse/shared/src/server";diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex a87713d730..cb036a1850 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -14,7 +14,7 @@ import {IngestionQueue,logger,EvalExecutionQueue,- checkTraceExists,+ checkTraceExistsAndGetTimestamp,checkObservationExists,DatasetRunItemUpsertEventType,TraceQueueEventType,@@ -301,6 +301,7 @@ export const createEvalJobs = async ({// Check whether the trace already exists in the database.let traceExists = false;+ let traceTimestamp: Date | undefined = cachedTrace?.timestamp;// Use cached trace for in-memory filtering when possible, i.e. all fields can// be checked in-memory.@@ -324,7 +325,7 @@ export const createEvalJobs = async ({});} else {// Fall back to database query for complex filters or when no cached trace- traceExists = await checkTraceExists({+ const { exists, timestamp } = await checkTraceExistsAndGetTimestamp({projectId: event.projectId,traceId: event.traceId,// Fallback to jobTimestamp if no payload timestamp is set to allow for successful retry attempts.@@ -339,6 +340,8 @@ export const createEvalJobs = async ({? new Date(event.exactTimestamp): undefined,});+ traceExists = exists;+ traceTimestamp = timestamp;recordIncrement("langfuse.evaluation-execution.trace_db_lookup", 1, {hasCached: Boolean(cachedTrace).toString(),requiredDatabaseLookup: requiresDatabaseLookup(traceFilter)@@ -496,6 +499,7 @@ export const createEvalJobs = async ({projectId: event.projectId,jobConfigurationId: config.id,jobInputTraceId: event.traceId,+ jobInputTraceTimestamp: traceTimestamp,jobTemplateId: config.eval_template_id,status: "PENDING",startTime: new Date(),@@ -626,6 +630,7 @@ export const evaluate = async ({projectId: event.projectId,variables: template.vars,traceId: job.job_input_trace_id,+ traceTimestamp: job.job_input_trace_timestamp ?? undefined,datasetItemId: job.job_input_dataset_item_id ?? undefined,variableMapping: parsedVariableMapping,});@@ -798,6 +803,7 @@ export async function extractVariablesFromTracingData({variables,traceId,variableMapping,+ traceTimestamp,datasetItemId,}: {projectId: string;@@ -805,6 +811,7 @@ export async function extractVariablesFromTracingData({traceId: string;// this here are variables which were inserted by users. Need to validate before DB query.variableMapping: z.infer<typeof variableMappingList>;+ traceTimestamp?: Date;datasetItemId?: string;}): Promise<{ var: string; value: string; environment?: string }[]> {// Internal cache for this function call to avoid duplicate database lookups.@@ -897,7 +904,11 @@ export async function extractVariablesFromTracingData({const traceCacheKey = `${projectId}:${traceId}`;let trace = traceCache.get(traceCacheKey);if (!traceCache.has(traceCacheKey)) {- trace = await getTraceById({ traceId, projectId });+ trace = await getTraceById({+ traceId,+ projectId,+ timestamp: traceTimestamp,+ });traceCache.set(traceCacheKey, trace ?? null);}@@ -948,13 +959,13 @@ export async function extractVariablesFromTracingData({const observationCacheKey = `${projectId}:${traceId}:${mapping.objectName}`;let observation = observationCache.get(observationCacheKey);if (!observationCache.has(observationCacheKey)) {- const observations = await getObservationForTraceIdByName(+ const observations = await getObservationForTraceIdByName({traceId,projectId,- mapping.objectName,- undefined,- true,- );+ name: mapping.objectName,+ timestamp: traceTimestamp,+ fetchWithInputOutput: true,+ });observation = observations.shift() || null; // We only take the first match and ignore duplicate generation-names in a trace.observationCache.set(observationCacheKey, observation);}diff --git a/worker/src/services/IngestionService/README.md b/worker/src/services/IngestionService/README.mdindex 95f3789d23..3e22a690b9 100644--- a/worker/src/services/IngestionService/README.md+++ b/worker/src/services/IngestionService/README.md@@ -16,9 +16,9 @@ This requires that the following table schema is manually applied on the databas-- Setup-- Context: https://fiddle.clickhouse.com/d4e84b88-6bd7-455c-9a84-e9126594f92a-+-- TODO: Make sure to update migrateTracesToTracesAMTs.ts if the traces_null schema changes-+-- Create a Null table that serves as a trigger for all materialized views.-- We use a Null engine here to avoid storing intermediate results and save on storage.CREATE TABLE traces_null@@ -496,7 +496,7 @@ This checklist documents all references and invocations to the `traces` table gr### 3. Existence Checks-- [x] **checkTraceExists()** - `packages/shared/src/server/repositories/traces.ts:73-210`+- [x] **checkTraceExistsAndGetTimestamp()** - `packages/shared/src/server/repositories/traces.ts:73-210`- [x] **hasAnyTrace()** - `packages/shared/src/server/repositories/traces.ts:306-356`- [x] **hasAnyUser()** - `packages/shared/src/server/repositories/traces.ts:763-787`@@ -508,8 +508,8 @@ This checklist documents all references and invocations to the `traces` table gr- [x] **generateObservationsForPublicApi()** - `web/src/features/public-api/server/observations.ts:80`- [x] **getObservationsCountForPublicApi()** - `web/src/features/public-api/server/observations.ts:108`- [x] **getObservationsTableInternal()** - `packages/shared/src/server/repositories/observations.ts:565`-- [x] **_handleGenerateScoresForPublicApi()** - `web/src/features/public-api/server/scores.ts:101`-- [x] **_handleGetScoresCountForPublicApi()** - `web/src/features/public-api/server/scores.ts:181`+- [x] **\_handleGenerateScoresForPublicApi()** - `web/src/features/public-api/server/scores.ts:101`+- [x] **\_handleGetScoresCountForPublicApi()** - `web/src/features/public-api/server/scores.ts:181`- [x] **getScoresUiGeneric()** - `packages/shared/src/server/repositories/scores.ts:825`- [x] **getNumericScoreHistogram()** - `packages/shared/src/server/repositories/scores.ts:1074`- [x] **getTracesGroupedByName()** - `packages/shared/src/server/repositories/traces.ts:489-535`@@ -542,6 +542,7 @@ We could use an opt-in on a projectId basis.- [x] **getTracesByIdsForAnyProject()** - `packages/shared/src/server/repositories/traces.ts:1115-1141`### 8. Delete Operations+- [x] **deleteTraces()** - `packages/shared/src/server/repositories/traces.ts:790++`- [x] **deleteTracesOlderThanDays()** - `packages/shared/src/server/repositories/traces.ts:814++`- [x] **deleteTracesByProjectId()** - `packages/shared/src/server/repositories/traces.ts:841++`