🪢 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: add score deletion to UI (#5956)
Steffen Schmitzdc8a99732482
diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.tsindex c3ebb02769..434ec014ab 100644--- a/packages/shared/scripts/prepareClickhouse.ts+++ b/packages/shared/scripts/prepareClickhouse.ts@@ -145,7 +145,7 @@ export const prepareClickhouse = async (const scoresQuery = `INSERT INTO scores- SELECT toString(floor(randUniform(0, 100))) AS id,+ SELECT toString(number) AS id,toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,'${projectId}' AS project_id,'default' AS environment,diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.tsindex 0e2abb43d1..da71a41eaa 100644--- a/packages/shared/src/features/batchAction/types.ts+++ b/packages/shared/src/features/batchAction/types.ts@@ -10,6 +10,7 @@ export enum BatchActionType {}const ActionIdSchema = z.enum([+ "score-delete","trace-delete","trace-add-to-annotation-queue",]);diff --git a/web/src/__tests__/async/scores-trpc.servertest.ts b/web/src/__tests__/async/scores-trpc.servertest.tsnew file mode 100644index 0000000000..c19f5ded33--- /dev/null+++ b/web/src/__tests__/async/scores-trpc.servertest.ts@@ -0,0 +1,163 @@+/** @jest-environment node */+/* eslint-disable @typescript-eslint/no-unsafe-member-access */++const mockAddScoreDelete = jest.fn();+const mockAddBatchAction = jest.fn();++jest.mock("@langfuse/shared/src/server", () => {+ const originalModule = jest.requireActual("@langfuse/shared/src/server");+ return {+ ...originalModule,+ ScoreDeleteQueue: {+ getInstance: jest.fn(() => ({+ add: mockAddScoreDelete,+ })),+ },+ BatchActionQueue: {+ getInstance: jest.fn(() => ({+ add: mockAddBatchAction,+ })),+ },+ };+});++import type { Session } from "next-auth";+import { pruneDatabase } from "@/src/__tests__/test-utils";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createScore,+ createScoresCh,+ ScoreDeleteQueue,+ BatchActionQueue,+ QueueJobs,+} from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";++describe("scores trpc", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ beforeEach(pruneDatabase);++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ describe("scores.deleteMany", () => {+ it("should delete scores by ids", async () => {+ // Setup+ const createdScore = createScore({+ project_id: projectId,+ });+ await createScoresCh([createdScore]);+ const scoreDeleteQueue = ScoreDeleteQueue.getInstance();++ // When+ await caller.scores.deleteMany({+ projectId,+ scoreIds: [createdScore.id],+ });++ // Then+ expect(scoreDeleteQueue.add).toHaveBeenCalledWith(+ QueueJobs.ScoreDelete,+ expect.objectContaining({+ payload: expect.objectContaining({+ projectId,+ scoreIds: [createdScore.id],+ }),+ }),+ );+ });++ it("should delete scores via batch query", async () => {+ // Setup+ const scoreName = randomUUID();+ const createdScore = createScore({+ project_id: projectId,+ name: scoreName,+ });+ await createScoresCh([createdScore]);+ const batchActionQueue = BatchActionQueue.getInstance();++ // When+ await caller.scores.deleteMany({+ projectId,+ scoreIds: null,+ isBatchAction: true,+ query: {+ orderBy: { column: "timestamp", order: "ASC" },+ filter: [+ {+ column: "name",+ operator: "=",+ value: scoreName,+ type: "string",+ },+ ],+ },+ });++ // Then+ expect(batchActionQueue.add).toHaveBeenCalledWith(+ QueueJobs.BatchActionProcessingJob,+ expect.objectContaining({+ payload: expect.objectContaining({+ projectId,+ actionId: "score-delete",+ }),+ }),+ expect.objectContaining({}),+ );+ });++ it("should throw an error if batchAction and scoreIds are missing", async () => {+ // When+ const promise = caller.scores.deleteMany({+ projectId,+ scoreIds: null,+ isBatchAction: false,+ });++ // Then+ await expect(promise).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message:+ "Either batchAction or scoreIds must be provided to delete scores.",+ });+ });+ });+});diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex 153fb242be..6e2b235f35 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -22,6 +22,8 @@ import {isPresent,type FilterState,type ScoreDataType,+ BatchExportTableName,+ BatchActionType,} from "@langfuse/shared";import { useQueryParams, withDefault, NumberParam } from "use-query-params";import TagList from "@/src/features/tag/components/TagList";@@ -33,6 +35,14 @@ import {convertSelectedEnvironmentsToFilter,} from "@/src/hooks/use-environment-filter";import { Badge } from "@/src/components/ui/badge";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";+import React, { useState } from "react";+import type { TableAction } from "@/src/features/table/types";+import type { RowSelectionState } from "@tanstack/react-table";+import { useHasEntitlement } from "@/src/features/entitlements/hooks";+import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";+import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";export type ScoresTableRow = {id: string;@@ -89,10 +99,13 @@ export default function ScoresTable({hiddenColumns?: string[];localStorageSuffix?: string;}) {+ const utils = api.useUtils();+ const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});const [paginationState, setPaginationState] = useQueryParams({pageIndex: withDefault(NumberParam, 0),pageSize: withDefault(NumberParam, 50),});+ const { selectAll, setSelectAll } = useSelectAll(projectId, "scores");const [rowHeight, setRowHeight] = useRowHeightLocalStorage("scores", "s");const { selectedOption, dateRange, setDateRangeAndOption } =@@ -173,6 +186,39 @@ export default function ScoresTable({const totalScoreCountQuery = api.scores.countAll.useQuery(getCountPayload);const totalCount = totalScoreCountQuery.data?.totalCount ?? null;+ // TODO: Implement+ const scoreDeleteMutation = api.scores.deleteMany.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Scores deleted",+ description:+ "Selected scores will be deleted. Scores are removed asynchronously and may continue to be visible for up to 15 minutes.",+ });+ },+ onSettled: () => {+ void utils.scores.all.invalidate();+ },+ });++ const hasTraceDeletionEntitlement = useHasEntitlement("trace-deletion");++ const handleDeleteScores = async ({ projectId }: { projectId: string }) => {+ const selectedScoreIds = Object.keys(selectedRows).filter((scoreId) =>+ scores.data?.scores.map((s) => s.id).includes(scoreId),+ );++ await scoreDeleteMutation.mutateAsync({+ projectId,+ scoreIds: selectedScoreIds,+ query: {+ filter: filterState,+ orderBy: orderByState,+ },+ isBatchAction: selectAll,+ });+ setSelectedRows({});+ };+const filterOptions = api.scores.filterOptions.useQuery({projectId,@@ -194,7 +240,14 @@ export default function ScoresTable({},);+ const { selectActionColumn } = TableSelectionManager<ScoresTableRow>({+ projectId,+ tableName: "scores",+ setSelectedRows,+ });+const rawColumns: LangfuseColumnDef<ScoresTableRow>[] = [+ selectActionColumn,{accessorKey: "traceId",id: "traceId",@@ -423,6 +476,25 @@ export default function ScoresTable({},];+ const tableActions: TableAction[] = [+ ...(hasTraceDeletionEntitlement+ ? [+ {+ id: "score-delete",+ type: BatchActionType.Delete,+ label: "Delete Scores",+ description:+ "This action permanently deletes scores and cannot be undone. Score deletion happens asynchronously and may take up to 15 minutes.",+ accessCheck: {+ scope: "traces:delete",+ entitlement: "trace-deletion",+ },+ execute: handleDeleteScores,+ } as TableAction,+ ]+ : []),+ ];+const columns = rawColumns.filter((c) => !!c.id && !hiddenColumns.includes(c.id),);@@ -488,10 +560,32 @@ export default function ScoresTable({setColumnVisibility={setColumnVisibility}columnOrder={columnOrder}setColumnOrder={setColumnOrder}+ actionButtons={[+ Object.keys(selectedRows).filter((scoreId) =>+ scores.data?.scores.map((s) => s.id).includes(scoreId),+ ).length > 0 ? (+ <TableActionMenu+ key="scores-multi-select-actions"+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Scores}+ />+ ) : null,+ ]}rowHeight={rowHeight}setRowHeight={setRowHeight}selectedOption={selectedOption}setDateRangeAndOption={setDateRangeAndOption}+ multiSelect={{+ selectAll,+ setSelectAll,+ selectedRowIds: Object.keys(selectedRows).filter((scoreId) =>+ scores.data?.scores.map((s) => s.id).includes(scoreId),+ ),+ setRowSelection: setSelectedRows,+ totalCount,+ ...paginationState,+ }}environmentFilter={{values: selectedEnvironments,onValueChange: setSelectedEnvironments,@@ -526,6 +620,8 @@ export default function ScoresTable({onColumnVisibilityChange={setColumnVisibility}columnOrder={columnOrder}onColumnOrderChange={setColumnOrder}+ rowSelection={selectedRows}+ setRowSelection={setSelectedRows}rowHeight={rowHeight}/></>diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 5607fdb330..7cfd9cf5f4 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -24,6 +24,9 @@ import {LangfuseNotFoundError,InvalidRequestError,InternalServerError,+ BatchActionQuerySchema,+ BatchActionType,+ BatchExportTableName,} from "@langfuse/shared";import {getScoresGroupedByNameSourceType,@@ -42,6 +45,8 @@ import {QueueJobs,} from "@langfuse/shared/src/server";import { v4 } from "uuid";+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";+import { createBatchActionJob } from "@/src/features/table/server/createBatchActionJob";import { TRPCError } from "@trpc/server";import { randomUUID } from "crypto";@@ -160,6 +165,78 @@ export const scoresRouter = createTRPCRouter({tags: tags,};}),+ deleteMany: protectedProjectProcedure+ .input(+ z.object({+ scoreIds: z+ .array(z.string())+ .min(1, "Minimum 1 scoreId is required.")+ .nullable(),+ projectId: z.string(),+ query: BatchActionQuerySchema.optional(),+ isBatchAction: z.boolean().default(false),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ // We reuse the trace-deletion entitlement here as this is a very similar and destructive operation.+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "traces:delete",+ });++ throwIfNoEntitlement({+ entitlement: "trace-deletion",+ projectId: input.projectId,+ sessionUser: ctx.session.user,+ });++ if (input.isBatchAction && input.query) {+ return createBatchActionJob({+ projectId: input.projectId,+ actionId: "score-delete",+ actionType: BatchActionType.Delete,+ tableName: BatchExportTableName.Scores,+ session: ctx.session,+ query: input.query,+ });+ }+ if (input.scoreIds) {+ const scoreDeleteQueue = ScoreDeleteQueue.getInstance();+ if (!scoreDeleteQueue) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "ScoreDeleteQueue not initialized",+ });+ }++ await Promise.all(+ input.scoreIds.map((scoreId) =>+ auditLog({+ resourceType: "score",+ resourceId: scoreId,+ action: "delete",+ session: ctx.session,+ }),+ ),+ );++ return scoreDeleteQueue.add(QueueJobs.ScoreDelete, {+ timestamp: new Date(),+ id: randomUUID(),+ payload: {+ projectId: input.projectId,+ scoreIds: input.scoreIds,+ },+ name: QueueJobs.ScoreDelete,+ });+ }+ throw new TRPCError({+ message:+ "Either batchAction or scoreIds must be provided to delete scores.",+ code: "BAD_REQUEST",+ });+ }),createAnnotationScore: protectedProjectProcedure.input(CreateAnnotationScoreData).mutation(async ({ input, ctx }) => {diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex abf4bc2675..7bef323dac 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -260,7 +260,7 @@ export const traceRouter = createTRPCRouter({deleteMany: protectedProjectProcedure.input(z.object({- traceIds: z.array(z.string()).min(1, "Minimum 1 trace_Id is required."),+ traceIds: z.array(z.string()).min(1, "Minimum 1 traceId is required."),projectId: z.string(),query: BatchActionQuerySchema.optional(),isBatchAction: z.boolean().default(false),