🪢 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
fix(annotation): update route to upsert along ordering key (#10113)
marliessophie2f9294184d44
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.tsindex ffcf4b4f9d..e9e8bef001 100644--- a/packages/shared/src/features/annotation/types.ts+++ b/packages/shared/src/features/annotation/types.ts@@ -56,6 +56,7 @@ const CreateAnnotationScoreBase = z.object({configId: z.string(),comment: StringNoHTML.nullish(),queueId: z.string().nullish(),+ timestamp: z.date().optional(), // Required for ClickHouse deduplication});const UpdateAnnotationScoreBase = CreateAnnotationScoreBase.extend({diff --git a/packages/shared/src/features/scores/interfaces/ui/types.ts b/packages/shared/src/features/scores/interfaces/ui/types.tsindex 4acdc91af3..4905076405 100644--- a/packages/shared/src/features/scores/interfaces/ui/types.ts+++ b/packages/shared/src/features/scores/interfaces/ui/types.ts@@ -5,6 +5,7 @@ export type BaseAggregate = {comment?: string | null;id?: string | null;hasMetadata?: boolean | null;+ timestamp?: Date | null;};export type CategoricalAggregate = BaseAggregate & {@@ -32,10 +33,10 @@ export type ScoreSimplified = {comment?: string | null;metadata?: MetadataDomain | null;stringValue?: string | null;+ timestamp: Date;};export type LastUserScore = ScoreSimplified & {- timestamp: string;traceId: string;observationId?: string | null;diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 5feee5a6e5..e081708bf2 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -1208,6 +1208,7 @@ export const getAggregatedScoresForPrompts = async (s.source,s.data_type,s.comment,+ s.timestamp,length(mapKeys(s.metadata)) > 0 AS has_metadataFROM scores s FINAL LEFT JOIN observations o FINALON o.trace_id = s.trace_iddiff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.tsindex 23dfb2a24f..5d8115a998 100644--- a/packages/shared/src/server/repositories/scores_converters.ts+++ b/packages/shared/src/server/repositories/scores_converters.ts@@ -11,6 +11,7 @@ export type ScoreAggregation = {source: string;data_type: string;comment: string | null;+ timestamp: Date;};export const convertToScore = (row: ScoreRecordReadType): ScoreDomain => {@@ -48,5 +49,6 @@ export const convertScoreAggregation = (row: ScoreAggregation) => {source: row.source as ScoreSourceType,dataType: row.data_type as ScoreDataType,comment: row.comment,+ timestamp: row.timestamp,};};diff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.tsindex 37650b5cb2..27c6dbe0c9 100644--- a/web/src/__tests__/async/dataset-service.servertest.ts+++ b/web/src/__tests__/async/dataset-service.servertest.ts@@ -321,6 +321,7 @@ describe("Fetch datasets for UI presentation", () => {id: undefined,comment: undefined,hasMetadata: undefined,+ timestamp: undefined,},[`${anotherScoreName.replaceAll("-", "_")}-API-NUMERIC`]: {id: score3.id,@@ -329,6 +330,7 @@ describe("Fetch datasets for UI presentation", () => {average: 1,comment: "some other comment for non run related score",hasMetadata: true,+ timestamp: expect.any(Date),},};@@ -492,6 +494,7 @@ describe("Fetch datasets for UI presentation", () => {comment: "comment",// createScore adds metadata to the scorehasMetadata: true,+ timestamp: expect.any(Date),},};@@ -1273,6 +1276,7 @@ describe("Fetch datasets for UI presentation", () => {values: expect.arrayContaining([100.5]),average: 100.5,comment: "comment",+ timestamp: expect.any(Date),// createScore adds metadata to the scorehasMetadata: true,},diff --git a/web/src/__tests__/mergeScoresWithCache.clienttest.ts b/web/src/__tests__/mergeScoresWithCache.clienttest.tsindex 4e46a1f4b9..1dcda06eed 100644--- a/web/src/__tests__/mergeScoresWithCache.clienttest.ts+++ b/web/src/__tests__/mergeScoresWithCache.clienttest.ts@@ -127,6 +127,9 @@ describe("mergeScoresWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -174,6 +177,9 @@ describe("mergeScoresWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -242,6 +248,9 @@ describe("mergeScoresWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -326,6 +335,9 @@ describe("mergeAggregatesWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -369,6 +381,9 @@ describe("mergeAggregatesWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -412,6 +427,9 @@ describe("mergeAggregatesWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},{id: "score-3",@@ -425,6 +443,9 @@ describe("mergeAggregatesWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -539,6 +560,9 @@ describe("mergeAnnotationScoresWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -583,6 +607,9 @@ describe("mergeAnnotationScoresWithCache", () => {traceId: "trace-1",projectId: "project-1",environment: "production",+ timestamp: new Date(),+ sessionId: null,+ observationId: null,},];@@ -613,9 +640,10 @@ describe("mergeAnnotationScoresWithCache", () => {comment: "Test",traceId: "trace-1",observationId: "obs-1",- sessionId: undefined,+ sessionId: null,projectId: "project-1",environment: "production",+ timestamp: new Date(),},];@@ -638,6 +666,7 @@ describe("mergeAnnotationScoresWithCache", () => {traceId: "trace-1",observationId: "obs-1",sessionId: null,+ timestamp: expect.any(Date),});});});diff --git a/web/src/__tests__/transformScores.clienttest.ts b/web/src/__tests__/transformScores.clienttest.tsindex a5052b97ff..d59c1c81c7 100644--- a/web/src/__tests__/transformScores.clienttest.ts+++ b/web/src/__tests__/transformScores.clienttest.ts@@ -92,6 +92,7 @@ describe("transformToAnnotationScores - flat scores", () => {traceId: "trace-1",observationId: null,sessionId: null,+ timestamp: expect.any(Date),});expect(result[1]).toEqual({id: "score-2",@@ -105,6 +106,7 @@ describe("transformToAnnotationScores - flat scores", () => {traceId: "trace-1",observationId: null,sessionId: null,+ timestamp: expect.any(Date),});});@@ -203,6 +205,7 @@ describe("transformToAnnotationScores - aggregates", () => {values: [8],average: 8,comment: "Good quality",+ timestamp: new Date(),},};@@ -226,6 +229,7 @@ describe("transformToAnnotationScores - aggregates", () => {traceId: "trace-1",observationId: "obs-1",sessionId: null,+ timestamp: expect.any(Date),});});@@ -236,6 +240,7 @@ describe("transformToAnnotationScores - aggregates", () => {type: "CATEGORICAL",values: ["positive"],valueCounts: [{ value: "positive", count: 1 }],+ timestamp: new Date(),comment: null,},};@@ -259,6 +264,7 @@ describe("transformToAnnotationScores - aggregates", () => {traceId: "trace-1",observationId: null,sessionId: null,+ timestamp: expect.any(Date),});});diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsxindex 93f09cde24..e3f91ad8cb 100644--- a/web/src/features/scores/components/AnnotationForm.tsx+++ b/web/src/features/scores/components/AnnotationForm.tsx@@ -313,10 +313,14 @@ function InnerAnnotationForm<Target extends ScoreTarget>({form.setValue(`scoreData.${index}.stringValue`, stringValue);// Fire mutation- const { id: scoreId, ...fieldWithoutId } = field;+ const {+ id: scoreId,+ timestamp: scoreTimestamp,+ ...fieldWithoutIdAndTimestamp+ } = field;const baseScoreData = {- ...fieldWithoutId,+ ...fieldWithoutIdAndTimestamp,...scoreMetadata,value,stringValue,@@ -327,14 +331,18 @@ function InnerAnnotationForm<Target extends ScoreTarget>({updateMutation.mutate({...baseScoreData,id: scoreId,+ timestamp: scoreTimestamp ?? undefined,} as UpdateAnnotationScoreData);} else {const id = uuid();- // Update scoreId in form for future updates+ const timestamp = new Date();+ // Update scoreId and timestamp in form for future updatesform.setValue(`scoreData.${index}.id`, id);+ form.setValue(`scoreData.${index}.timestamp`, timestamp);createMutation.mutate({...baseScoreData,id,+ timestamp,} as CreateAnnotationScoreData);}};@@ -773,6 +781,7 @@ export function AnnotationForm<Target extends ScoreTarget>({value: score.value,stringValue: score.stringValue,comment: score.comment,+ timestamp: score.timestamp,});});@@ -788,6 +797,7 @@ export function AnnotationForm<Target extends ScoreTarget>({value: null,stringValue: null,comment: null,+ timestamp: null,});}});diff --git a/web/src/features/scores/contexts/ScoreCacheContext.tsx b/web/src/features/scores/contexts/ScoreCacheContext.tsxindex 6c7a70dbd6..9b7e7229a8 100644--- a/web/src/features/scores/contexts/ScoreCacheContext.tsx+++ b/web/src/features/scores/contexts/ScoreCacheContext.tsx@@ -30,6 +30,7 @@ export type CachedScore = Pick<| "traceId"| "observationId"| "sessionId"+ | "timestamp"> & {// Score identity - non-nullableconfigId: string;diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.tsindex 80f4fd9a24..daa6b83941 100644--- a/web/src/features/scores/hooks/useScoreMutations.ts+++ b/web/src/features/scores/hooks/useScoreMutations.ts@@ -58,6 +58,7 @@ export function useScoreMutations({value: variables.value ?? null,stringValue: variables.stringValue ?? null,comment: variables.comment ?? null,+ timestamp: variables.timestamp ?? new Date(),});},onError,@@ -85,6 +86,7 @@ export function useScoreMutations({value: variables.value ?? null,stringValue: variables.stringValue ?? null,comment: variables.comment ?? null,+ timestamp: variables.timestamp ?? new Date(),});} else {// Merge update into existing cache entrydiff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.tsindex 143b823a60..fa85d810c9 100644--- a/web/src/features/scores/lib/aggregateScores.ts+++ b/web/src/features/scores/lib/aggregateScores.ts@@ -101,6 +101,7 @@ export const aggregateScores = <T extends ScoreToAggregate>(comment: values.length === 1 ? scores[0].comment : undefined,id: values.length === 1 ? scores[0].id : undefined,hasMetadata: values.length === 1 ? scores[0].hasMetadata : undefined,+ timestamp: values.length === 1 ? scores[0].timestamp : undefined,};} else {const values = scores.map((score) => score.stringValue ?? "n/a");@@ -122,6 +123,7 @@ export const aggregateScores = <T extends ScoreToAggregate>(comment: values.length === 1 ? scores[0].comment : undefined,id: values.length === 1 ? scores[0].id : undefined,hasMetadata: values.length === 1 ? scores[0].hasMetadata : undefined,+ timestamp: values.length === 1 ? scores[0].timestamp : undefined,};}return acc;diff --git a/web/src/features/scores/lib/mergeScoresWithCache.ts b/web/src/features/scores/lib/mergeScoresWithCache.tsindex bf5bbf219d..87ad771576 100644--- a/web/src/features/scores/lib/mergeScoresWithCache.ts+++ b/web/src/features/scores/lib/mergeScoresWithCache.ts@@ -164,6 +164,7 @@ export function mergeAnnotationScoresWithCache(traceId: cached.traceId ?? null,observationId: cached.observationId ?? null,sessionId: cached.sessionId ?? null,+ timestamp: cached.timestamp ?? null,});}});diff --git a/web/src/features/scores/lib/transformScores.ts b/web/src/features/scores/lib/transformScores.tsindex 8aa58e6b07..2f21a23980 100644--- a/web/src/features/scores/lib/transformScores.ts+++ b/web/src/features/scores/lib/transformScores.ts@@ -79,6 +79,7 @@ function transformFlatScores(traceId: score.traceId ?? null,observationId: score.observationId ?? null,sessionId: score.sessionId ?? null,+ timestamp: score.timestamp,};}).filter((score) => score !== null);@@ -120,6 +121,7 @@ function transformAggregates(comment: aggregate.comment ?? null,value: null,stringValue: null,+ timestamp: aggregate.timestamp ?? null,};if (aggregate.type === "NUMERIC") {diff --git a/web/src/features/scores/schema.ts b/web/src/features/scores/schema.tsindex b30ddb8547..4733dfd6a4 100644--- a/web/src/features/scores/schema.ts+++ b/web/src/features/scores/schema.ts@@ -2,8 +2,11 @@ import { ScoreDataType } from "@langfuse/shared";import { z } from "zod/v4";export const AnnotationScoreDataSchema = z.object({- name: z.string(),+ // Required for ClickHouse deduplication (not shown in UI)id: z.string().nullish(),+ timestamp: z.date().nullish(),+ // Required for score writes (shown in UI)+ name: z.string(),value: z.number().nullish(),stringValue: z.string().nullish(),dataType: z.enum(ScoreDataType),diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.tsindex a689b4cf6a..f5b51d0845 100644--- a/web/src/features/scores/types.ts+++ b/web/src/features/scores/types.ts@@ -64,6 +64,7 @@ export type AnnotationScore = {observationId?: string | null;sessionId?: string | null;comment?: string | null;+ timestamp?: Date | null;};type AnalyticsData = {@@ -125,6 +126,7 @@ export type AnnotationScoreFormData = {value?: number | null;stringValue?: string | null;comment?: string | null;+ timestamp?: Date | null;};export type InnerAnnotationFormProps<Target extends ScoreTarget> = {diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex dcf3606fc3..525dcce808 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -351,6 +351,8 @@ export const scoresRouter = createTRPCRouter({input.dataType,);+ const timestamp = input.timestamp ?? new Date();+const score = !!clickhouseScore? {...clickhouseScore,@@ -360,7 +362,7 @@ export const scoresRouter = createTRPCRouter({metadata: {},authorUserId: ctx.session.user.id,queueId: input.queueId ?? null,- timestamp: new Date(),+ timestamp,}: {id: input.id ?? v4(),@@ -382,12 +384,12 @@ export const scoresRouter = createTRPCRouter({executionTraceId: null,createdAt: new Date(),updatedAt: new Date(),- timestamp: new Date(),+ timestamp,};await upsertScore({id: score.id, // Reuse ID that was generated by Prisma- timestamp: convertDateToClickhouseDateTime(new Date()),+ timestamp: convertDateToClickhouseDateTime(timestamp),project_id: input.projectId,environment: input.environment ?? "default",trace_id: inflatedParams.traceId,@@ -431,13 +433,131 @@ export const scoresRouter = createTRPCRouter({scoreId: input.id,source: ScoreSource.ANNOTATION,});+if (!score) {- logger.warn(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,- );- throw new LangfuseNotFoundError(- `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,+ // Clickhouse is eventually consistent; if client provided timestamp, we can upsert along the ordering key+ if (!input.timestamp) {+ logger.warn(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse, and no timestamp provided`,+ );+ throw new LangfuseNotFoundError(+ `No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,+ );+ }++ logger.info(+ `Score ${input.id} not found in ClickHouse for project ${input.projectId}, upserting with provided timestamp`,);++ // Validate config if provided+ const config = await ctx.prisma.scoreConfig.findFirst({+ where: {+ id: input.configId,+ projectId: input.projectId,+ },+ });+ if (!config) {+ throw new LangfuseNotFoundError(+ `No score config with id ${input.configId} in project ${input.projectId}`,+ );+ }++ // Upsert with provided data+ const inflatedParams = isTraceScore(input.scoreTarget)+ ? {+ observationId: input.scoreTarget.observationId ?? null,+ traceId: input.scoreTarget.traceId,+ sessionId: null,+ }+ : {+ observationId: null,+ traceId: null,+ sessionId: input.scoreTarget.sessionId,+ };++ if (inflatedParams.traceId) {+ const clickhouseTrace = await getTraceById({+ traceId: inflatedParams.traceId,+ projectId: input.projectId,+ clickhouseFeatureTag: "annotations-trpc",+ });++ if (!clickhouseTrace) {+ logger.error(+ `No trace with id ${inflatedParams.traceId} in project ${input.projectId} in Clickhouse`,+ );+ throw new LangfuseNotFoundError(+ `No trace with id ${inflatedParams.traceId} in project ${input.projectId} in Clickhouse`,+ );+ }+ } else if (inflatedParams.sessionId) {+ // We consider no longer writing all sessions into postgres, hence we should search for traces with the session id+ const traceIdentifiers = await getTracesIdentifierForSession(+ input.projectId,+ inflatedParams.sessionId,+ );+ if (traceIdentifiers.length === 0) {+ logger.error(+ `No trace referencing session with id ${inflatedParams.sessionId} in project ${input.projectId} in Clickhouse`,+ );+ throw new LangfuseNotFoundError(+ `No trace referencing session with id ${inflatedParams.sessionId} in project ${input.projectId} in Clickhouse`,+ );+ }+ }++ const timestamp = input.timestamp;++ await upsertScore({+ id: input.id,+ timestamp: convertDateToClickhouseDateTime(timestamp),+ project_id: input.projectId,+ environment: input.environment ?? "default",+ trace_id: inflatedParams.traceId,+ observation_id: inflatedParams.observationId,+ session_id: inflatedParams.sessionId,+ name: input.name,+ value: input.value !== null ? input.value : undefined,+ source: ScoreSource.ANNOTATION,+ comment: input.comment,+ author_user_id: ctx.session.user.id,+ config_id: input.configId,+ data_type: input.dataType,+ string_value: input.stringValue,+ queue_id: input.queueId,+ });++ updatedScore = {+ id: input.id,+ projectId: input.projectId,+ environment: input.environment ?? "default",+ traceId: inflatedParams.traceId,+ observationId: inflatedParams.observationId,+ sessionId: inflatedParams.sessionId,+ datasetRunId: null,+ name: input.name,+ dataType: input.dataType ?? null,+ configId: input.configId ?? null,+ metadata: {},+ executionTraceId: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ source: ScoreSource.ANNOTATION,+ value: input.value ?? null,+ stringValue: input.stringValue ?? null,+ comment: input.comment ?? null,+ authorUserId: ctx.session.user.id,+ queueId: input.queueId ?? null,+ timestamp,+ };++ await auditLog({+ session: ctx.session,+ resourceType: "score",+ resourceId: input.id,+ action: "update",+ after: updatedScore,+ });} else {// validate score against configif (score.configId) {@@ -498,7 +618,7 @@ export const scoresRouter = createTRPCRouter({comment: input.comment ?? null,authorUserId: ctx.session.user.id,queueId: input.queueId ?? null,- timestamp: new Date(),+ timestamp: score.timestamp,};await auditLog({@@ -512,6 +632,9 @@ export const scoresRouter = createTRPCRouter({}if (!updatedScore) {+ logger.error(+ `Annotation score ${input.id} could not be updated in project ${input.projectId}`,+ );throw new InternalServerError(`Annotation score could not be updated in project ${input.projectId}`,);