🪢 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
feat(annotation-ui): rollback optimistic score writes on error (#10371)
marliessophie63b36d9bed2d
diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsxindex e3f91ad8cb..087af02d2c 100644--- a/web/src/features/scores/components/AnnotationForm.tsx+++ b/web/src/features/scores/components/AnnotationForm.tsx@@ -271,20 +271,49 @@ function InnerAnnotationForm<Target extends ScoreTarget>({deleteMutation.isPending,]);+ const rollbackDeleteError = (+ index: number,+ field: (typeof controlledFields)[number],+ previousScore: {+ id: string | null;+ value?: number | null;+ stringValue?: string | null;+ comment?: string | null;+ timestamp?: Date | null;+ },+ ) => {+ // Rollback field array+ update(index, {+ name: field.name,+ dataType: field.dataType,+ configId: field.configId,+ ...previousScore,+ });+ // Rollback form values directly to ensure sync+ form.setValue(`scoreData.${index}.id`, previousScore.id);+ form.setValue(`scoreData.${index}.value`, previousScore.value);+ form.setValue(`scoreData.${index}.stringValue`, previousScore.stringValue);+ form.setValue(`scoreData.${index}.comment`, previousScore.comment);+ form.setValue(`scoreData.${index}.timestamp`, previousScore.timestamp);+ form.setError(`scoreData.${index}.value`, {+ type: "server",+ message: "Failed to delete score",+ });+ };+const handleDeleteScore = (index: number) => {const field = controlledFields[index];- if (field.id) {- deleteMutation.mutate({- id: field.id,- projectId: scoreMetadata.projectId,- });- }-- // Capture delete event- capture("score:delete", analyticsData);+ // Capture previous state for rollback+ const previousScore = {+ id: field.id,+ value: field.value,+ stringValue: field.stringValue,+ comment: field.comment,+ timestamp: field.timestamp,+ };- // Remove from form+ // Optimistically clear formform.clearErrors(`scoreData.${index}.value`);update(index, {name: field.name,@@ -295,6 +324,52 @@ function InnerAnnotationForm<Target extends ScoreTarget>({stringValue: null,comment: null,});++ // Fire mutation with rollback+ if (previousScore.id) {+ deleteMutation.mutate(+ {+ id: previousScore.id,+ projectId: scoreMetadata.projectId,+ },+ {+ onError: () => rollbackDeleteError(index, field, previousScore),+ },+ );+ }++ // Capture delete event+ capture("score:delete", analyticsData);+ };++ const rollbackUpdateError = (+ index: number,+ previousValue?: number | null,+ previousStringValue?: string | null,+ ) => {+ form.setValue(`scoreData.${index}.value`, previousValue);+ form.setValue(`scoreData.${index}.stringValue`, previousStringValue);+ form.setError(`scoreData.${index}.value`, {+ type: "server",+ message: "Failed to update score",+ });+ };++ const rollbackCreateError = (+ index: number,+ previousValue?: number | null,+ previousStringValue?: string | null,+ previousId?: string | null,+ previousTimestamp?: Date | null,+ ) => {+ form.setValue(`scoreData.${index}.id`, previousId);+ form.setValue(`scoreData.${index}.timestamp`, previousTimestamp);+ form.setValue(`scoreData.${index}.value`, previousValue);+ form.setValue(`scoreData.${index}.stringValue`, previousStringValue);+ form.setError(`scoreData.${index}.value`, {+ type: "server",+ message: "Failed to create score",+ });};const handleUpsert = (@@ -305,10 +380,14 @@ function InnerAnnotationForm<Target extends ScoreTarget>({const field = controlledFields[index];if (!field) return;- // Clear errors- form.clearErrors(`scoreData.${index}.value`);+ // Capture previous form state for rollback+ const previousValue = field.value;+ const previousStringValue = field.stringValue;+ const previousId = field.id;+ const previousTimestamp = field.timestamp;- // Keep form state in sync - update both value and stringValue+ // Clear errors and update form optimistically+ form.clearErrors(`scoreData.${index}.value`);form.setValue(`scoreData.${index}.value`, value);form.setValue(`scoreData.${index}.stringValue`, stringValue);@@ -328,22 +407,39 @@ function InnerAnnotationForm<Target extends ScoreTarget>({};if (scoreId) {- updateMutation.mutate({- ...baseScoreData,- id: scoreId,- timestamp: scoreTimestamp ?? undefined,- } as UpdateAnnotationScoreData);+ updateMutation.mutate(+ {+ ...baseScoreData,+ id: scoreId,+ timestamp: scoreTimestamp ?? undefined,+ } as UpdateAnnotationScoreData,+ {+ onError: () =>+ rollbackUpdateError(index, previousValue, previousStringValue),+ },+ );} else {const id = uuid();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);+ createMutation.mutate(+ {+ ...baseScoreData,+ id,+ timestamp,+ } as CreateAnnotationScoreData,+ {+ onError: () =>+ rollbackCreateError(+ index,+ previousValue,+ previousStringValue,+ previousId,+ previousTimestamp,+ ),+ },+ );}};@@ -353,6 +449,10 @@ function InnerAnnotationForm<Target extends ScoreTarget>({if (!config || !field) return;+ if (field.value === null || field.value === undefined) {+ return; // Don't create/update score with empty value+ }+// Client-side validation - don't fire mutation if invalidconst errorMessage = validateNumericScore({value: field.value,@@ -387,23 +487,45 @@ function InnerAnnotationForm<Target extends ScoreTarget>({handleUpsert(index, numericCategoryValue, stringValue);};+ const rollbackCommentError = (+ index: number,+ field: (typeof controlledFields)[number],+ previousComment?: string | null,+ ) => {+ update(index, {+ ...field,+ comment: previousComment,+ });+ form.setError(`scoreData.${index}.comment`, {+ type: "server",+ message: "Failed to update comment",+ });+ };+const handleCommentUpdate = (index: number, newComment: string | null) => {const field = controlledFields[index];if (!field || !field.id) return;- // Update form with the new comment value+ const previousComment = field.comment;++ // Optimistically update formupdate(index, {...field,comment: newComment,});- // Fire mutation with new comment (only pass necessary fields)- updateMutation.mutate({- ...field,- ...scoreMetadata,- scoreTarget,- comment: newComment,- } as UpdateAnnotationScoreData);+ // Fire mutation+ updateMutation.mutate(+ {+ ...field,+ ...scoreMetadata,+ scoreTarget,+ comment: newComment,+ } as UpdateAnnotationScoreData,+ {+ onError: () => rollbackCommentError(index, field, previousComment),+ },+ );};return (diff --git a/web/src/features/scores/contexts/ScoreCacheContext.tsx b/web/src/features/scores/contexts/ScoreCacheContext.tsxindex 9b7e7229a8..13f3306a40 100644--- a/web/src/features/scores/contexts/ScoreCacheContext.tsx+++ b/web/src/features/scores/contexts/ScoreCacheContext.tsx@@ -38,10 +38,25 @@ export type CachedScore = Pick<};type ScoreCacheContextValue = {+ /** Add or update a score in the cache (for optimistic updates) */set: (id: string, score: CachedScore) => void;++ /** Retrieve a score from the cache */get: (id: string) => CachedScore | undefined;++ /** Mark a score as deleted (user-initiated delete, adds to deletedIds Set + removes from cache Map) */delete: (id: string) => void;++ /** Rollback a failed optimistic set/update (removes from cache without marking as deleted) */+ rollbackSet: (id: string) => void;++ /** Rollback a failed delete (removes from deletedIds Set, optionally restores to cache Map if score provided) */+ rollbackDelete: (id: string, score?: CachedScore) => void;++ /** Check if a score is marked as deleted */isDeleted: (id: string) => boolean;++ /** Clear all cached scores and deletedIds */clear: () => void;getAllForTarget: (@@ -101,6 +116,33 @@ export function ScoreCacheProvider({ children }: { children: ReactNode }) {});}, []);+ const rollbackSet = useCallback((id: string) => {+ // Remove from cache without marking as deleted+ setCache((prev) => {+ if (!prev.has(id)) return prev;+ const newCache = new Map(prev);+ newCache.delete(id);+ return newCache;+ });+ }, []);++ const rollbackDelete = useCallback((id: string, score?: CachedScore) => {+ setDeletedIds((prev) => {+ if (!prev.has(id)) return prev;+ const newSet = new Set(prev);+ newSet.delete(id);+ return newSet;+ });++ if (score) {+ setCache((prev) => {+ const newCache = new Map(prev);+ newCache.set(id, score);+ return newCache;+ });+ }+ }, []);+const isDeleted = useCallback((id: string) => {return deletedIds.has(id);@@ -175,6 +217,8 @@ export function ScoreCacheProvider({ children }: { children: ReactNode }) {set,get,delete: deleteScore,+ rollbackSet,+ rollbackDelete,isDeleted,clear,getAllForTarget,diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.tsindex daa6b83941..db2d6175ff 100644--- a/web/src/features/scores/hooks/useScoreMutations.ts+++ b/web/src/features/scores/hooks/useScoreMutations.ts@@ -5,6 +5,7 @@ import {} from "@/src/features/scores/lib/helpers";import { useScoreCache } from "@/src/features/scores/contexts/ScoreCacheContext";import { type ScoreTarget } from "@langfuse/shared";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";export function useScoreMutations({scoreTarget,@@ -21,14 +22,11 @@ export function useScoreMutations({set: cacheSet,get: cacheGet,delete: cacheDelete,+ rollbackSet: cacheRollbackSet,+ rollbackDelete: cacheRollbackDelete,setColumn: cacheSetColumn,} = useScoreCache();- // Rather than rolling back optimistic updates, we reload the page to clear the cache and invalidate trpc queries- const onError = () => {- window.location.reload();- };-// Create mutations with cache writesconst createMutation = api.scores.createAnnotationScore.useMutation({onMutate: (variables) => {@@ -60,15 +58,22 @@ export function useScoreMutations({comment: variables.comment ?? null,timestamp: variables.timestamp ?? new Date(),});++ return { scoreId: variables.id! };+ },+ onError: (err, variables) => {+ if (!variables.id) return;+ // Rollback failed create from cache+ cacheRollbackSet(variables.id);+ showErrorToast("Failed to create score", err.message, "WARNING");},- onError,});const updateMutation = api.scores.updateAnnotationScore.useMutation({onMutate: (variables) => {- const existing = cacheGet(variables.id);+ const previousCacheValue = cacheGet(variables.id);- if (!existing) {+ if (!previousCacheValue) {// Write to cache for optimistic updatecacheSet(variables.id, {id: variables.id,@@ -91,22 +96,43 @@ export function useScoreMutations({} else {// Merge update into existing cache entrycacheSet(variables.id, {- ...existing,- value: variables.value ?? existing.value,- stringValue: variables.stringValue ?? existing.stringValue,+ ...previousCacheValue,+ value: variables.value ?? previousCacheValue.value,+ stringValue: variables.stringValue ?? previousCacheValue.stringValue,comment: variables.comment ?? null,});}++ return { previousCacheValue };+ },+ onError: (err, variables, context) => {+ // Rollback cache+ if (context?.previousCacheValue) {+ // Had cache entry → restore previous value+ cacheSet(variables.id, context.previousCacheValue);+ } else {+ // No cache entry → was DB-persisted → rollback optimistic update+ cacheRollbackSet(variables.id);+ }+ showErrorToast("Failed to update score", err.message, "WARNING");},- onError,});const deleteMutation = api.scores.deleteAnnotationScore.useMutation({onMutate: (variables) => {+ // Snapshot score before delete (may be undefined)+ const previousCacheValue = cacheGet(variables.id);+// Mark score as deletedcacheDelete(variables.id);++ return { previousCacheValue };+ },+ onError: (err, variables, context) => {+ // Rollback+ cacheRollbackDelete(variables.id, context?.previousCacheValue);+ showErrorToast("Failed to delete score", err.message, "WARNING");},- onError,});return {