Skip to content

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

feat(evals, ui): enable deletion of evaluator via UI, DeleteButton refactor (#6247)

David Alexander Pfeiffer2bca2899f421
diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.ts
index 8b122b168f..7355871cc6 100644
--- a/packages/shared/src/server/test-utils/org-factory.ts
+++ b/packages/shared/src/server/test-utils/org-factory.ts
@@ -29,7 +29,7 @@ export const createOrgProjectAndApiKey = async (
}),
},
});
- await prisma.project.create({
+ const project = await prisma.project.create({
data: {
id: projectId,
name: v4(),
@@ -50,5 +50,5 @@ export const createOrgProjectAndApiKey = async (
},
});
- return { projectId, publicKey, secretKey, auth };
+ return { projectId, orgId: org.id, publicKey, secretKey, auth, org, project };
};
diff --git a/web/src/__tests__/async/evals-trpc.servertest.ts b/web/src/__tests__/async/evals-trpc.servertest.ts
index 39dd1985ac..08a2c36303 100644
--- a/web/src/__tests__/async/evals-trpc.servertest.ts
+++ b/web/src/__tests__/async/evals-trpc.servertest.ts
@@ -1,21 +1,16 @@
/** @jest-environment node */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
-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 { prisma } from "@langfuse/shared/src/db";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import type { Session } from "next-auth";
-describe("evals trpc", () => {
- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+const __orgIds: string[] = [];
- beforeEach(async () => {
- await pruneDatabase();
- await prisma.jobExecution.deleteMany();
- await prisma.jobConfiguration.deleteMany();
- await prisma.evalTemplate.deleteMany();
- });
+async function prepare() {
+ const { project, org } = await createOrgProjectAndApiKey();
const session: Session = {
expires: "1",
@@ -25,18 +20,18 @@ describe("evals trpc", () => {
name: "Demo User",
organizations: [
{
- id: "seed-org-id",
- name: "Test Organization",
+ id: org.id,
+ name: org.name,
role: "OWNER",
plan: "cloud:hobby",
cloudConfig: undefined,
projects: [
{
- id: projectId,
+ id: project.id,
role: "ADMIN",
retentionDays: 30,
deletedAt: null,
- name: "Test Project",
+ name: project.name,
},
],
},
@@ -47,17 +42,36 @@ describe("evals trpc", () => {
},
admin: true,
},
- environment: {} as any,
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:hobby",
+ },
};
const ctx = createInnerTRPCContext({ session });
const caller = appRouter.createCaller({ ...ctx, prisma });
+ __orgIds.push(org.id);
+
+ return { project, org, session, ctx, caller };
+}
+
+describe("evals trpc", () => {
+ afterAll(async () => {
+ await prisma.organization.deleteMany({
+ where: {
+ id: { in: __orgIds },
+ },
+ });
+ });
+
describe("evals.allConfigs", () => {
it("should retrieve all evaluator configurations with execution status counts", async () => {
+ const { project, caller } = await prepare();
+
const evalJobConfig1 = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -73,7 +87,7 @@ describe("evals trpc", () => {
data: {
jobConfigurationId: evalJobConfig1.id,
status: "PENDING",
- projectId,
+ projectId: project.id,
},
});
@@ -81,7 +95,7 @@ describe("evals trpc", () => {
data: {
jobConfigurationId: evalJobConfig1.id,
status: "COMPLETED",
- projectId,
+ projectId: project.id,
},
});
@@ -89,13 +103,13 @@ describe("evals trpc", () => {
data: {
jobConfigurationId: evalJobConfig1.id,
status: "ERROR",
- projectId,
+ projectId: project.id,
},
});
const evalJobConfig2 = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -108,7 +122,7 @@ describe("evals trpc", () => {
});
const response = await caller.evals.allConfigs({
- projectId,
+ projectId: project.id,
limit: 10,
page: 0,
});
@@ -147,9 +161,11 @@ describe("evals trpc", () => {
describe("evals.updateConfig", () => {
it("should update an evaluator configuration", async () => {
+ const { project, caller } = await prepare();
+
const evalJobConfig = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -163,7 +179,7 @@ describe("evals trpc", () => {
});
const response = await caller.evals.updateEvalJob({
- projectId,
+ projectId: project.id,
evalConfigId: evalJobConfig.id,
config: {
status: "INACTIVE",
@@ -187,9 +203,11 @@ describe("evals trpc", () => {
});
it("when the evaluator ran on existing traces, time scope cannot be changed to NEW only", async () => {
+ const { project, caller } = await prepare();
+
const evalJobConfig = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -204,7 +222,7 @@ describe("evals trpc", () => {
expect(
caller.evals.updateEvalJob({
- projectId,
+ projectId: project.id,
evalConfigId: evalJobConfig.id,
config: {
timeScope: ["NEW"],
@@ -216,9 +234,11 @@ describe("evals trpc", () => {
});
it("when the evaluator ran on existing traces, it cannot be deactivated", async () => {
+ const { project, caller } = await prepare();
+
const evalJobConfig = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -233,7 +253,7 @@ describe("evals trpc", () => {
expect(
caller.evals.updateEvalJob({
- projectId,
+ projectId: project.id,
evalConfigId: evalJobConfig.id,
config: {
status: "INACTIVE",
@@ -245,9 +265,11 @@ describe("evals trpc", () => {
});
it("when the evaluator ran on existing traces, it can be deactivated if it should also run on new traces", async () => {
+ const { project, caller } = await prepare();
+
const evalJobConfig = await prisma.jobConfiguration.create({
data: {
- projectId,
+ projectId: project.id,
jobType: "EVAL",
scoreName: "test-score",
filter: [],
@@ -261,7 +283,7 @@ describe("evals trpc", () => {
});
const response = await caller.evals.updateEvalJob({
- projectId,
+ projectId: project.id,
evalConfigId: evalJobConfig.id,
config: {
status: "INACTIVE",
@@ -284,4 +306,319 @@ describe("evals trpc", () => {
expect(updatedJob?.timeScope).toEqual(["EXISTING", "NEW"]);
});
});
+
+ describe("evals.deleteEvalJob", () => {
+ it("should successfully delete an eval job", async () => {
+ const { project, caller } = await prepare();
+
+ // Create a job to delete
+ const evalJobConfig = await prisma.jobConfiguration.create({
+ data: {
+ projectId: project.id,
+ jobType: "EVAL",
+ scoreName: "test-score",
+ filter: [],
+ targetObject: "trace",
+ variableMapping: [],
+ sampling: 1,
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ },
+ });
+
+ // Create multiple job executions with different statuses
+ await Promise.all([
+ prisma.jobExecution.create({
+ data: {
+ jobConfigurationId: evalJobConfig.id,
+ status: "COMPLETED",
+ projectId: project.id,
+ },
+ }),
+ prisma.jobExecution.create({
+ data: {
+ jobConfigurationId: evalJobConfig.id,
+ status: "PENDING",
+ projectId: project.id,
+ },
+ }),
+ prisma.jobExecution.create({
+ data: {
+ jobConfigurationId: evalJobConfig.id,
+ status: "ERROR",
+ projectId: project.id,
+ error: "Test error",
+ },
+ }),
+ ]);
+
+ // Verify job executions exist before deletion
+ const beforeJobExecutions = await prisma.jobExecution.findMany({
+ where: {
+ jobConfigurationId: evalJobConfig.id,
+ },
+ });
+ expect(beforeJobExecutions).toHaveLength(3);
+
+ // Delete the job
+ await caller.evals.deleteEvalJob({
+ projectId: project.id,
+ evalConfigId: evalJobConfig.id,
+ });
+
+ // Verify job is deleted
+ const deletedJob = await prisma.jobConfiguration.findUnique({
+ where: {
+ id: evalJobConfig.id,
+ },
+ });
+ expect(deletedJob).toBeNull();
+
+ // Verify all job executions are deleted (cascade)
+ const afterJobExecutions = await prisma.jobExecution.findMany({
+ where: {
+ jobConfigurationId: evalJobConfig.id,
+ },
+ });
+ expect(afterJobExecutions).toHaveLength(0);
+ });
+
+ it("should throw error when trying to delete non-existent eval job", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.evals.deleteEvalJob({
+ projectId: project.id,
+ evalConfigId: "non-existent-id",
+ }),
+ ).rejects.toThrow("Job not found");
+ });
+
+ it("should throw error when user lacks evalJob:CUD access scope", async () => {
+ const { project, session } = await prepare();
+
+ // Create a session with limited permissions
+ const limitedSession: Session = {
+ ...session,
+ user: {
+ id: session.user!.id,
+ name: session.user!.name,
+ canCreateOrganizations: session.user!.canCreateOrganizations,
+ admin: false,
+ featureFlags: session.user!.featureFlags,
+ organizations: [
+ {
+ ...session.user!.organizations[0],
+ role: "MEMBER",
+ projects: [
+ {
+ ...session.user!.organizations[0].projects[0],
+ role: "VIEWER", // VIEWER role doesn't have evalTemplate:CUD scope
+ },
+ ],
+ },
+ ],
+ },
+ expires: session.expires,
+ environment: session.environment,
+ };
+ const limitedCtx = createInnerTRPCContext({ session: limitedSession });
+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
+
+ // Create a job
+ const evalJobConfig = await prisma.jobConfiguration.create({
+ data: {
+ projectId: project.id,
+ jobType: "EVAL",
+ scoreName: "test-score",
+ filter: [],
+ targetObject: "trace",
+ variableMapping: [],
+ sampling: 1,
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ },
+ });
+
+ // Attempt to delete with limited permissions
+ await expect(
+ limitedCaller.evals.deleteEvalJob({
+ projectId: project.id,
+ evalConfigId: evalJobConfig.id,
+ }),
+ ).rejects.toThrow("User does not have access to this resource or action");
+ });
+ });
+
+ // TODO: moved to LFE-4573
+ // describe("evals.deleteEvalTemplate", () => {
+ // it("should successfully delete an eval template", async () => {
+ // const { project, caller } = await prepare();
+
+ // // Create a template to delete
+ // const evalTemplate = await prisma.evalTemplate.create({
+ // data: {
+ // projectId: project.id,
+ // name: "test-template",
+ // version: 1,
+ // prompt: "test prompt",
+ // model: "test-model",
+ // modelParams: {},
+ // vars: [],
+ // outputSchema: {
+ // score: "test-score",
+ // reasoning: "test-reasoning",
+ // },
+ // provider: "test-provider",
+ // },
+ // });
+
+ // // Delete the template
+ // await caller.evals.deleteEvalTemplate({
+ // projectId: project.id,
+ // evalTemplateId: evalTemplate.id,
+ // });
+
+ // // Verify template is deleted
+ // const deletedTemplate = await prisma.evalTemplate.findUnique({
+ // where: {
+ // id: evalTemplate.id,
+ // },
+ // });
+ // expect(deletedTemplate).toBeNull();
+ // });
+
+ // it("should set evalTemplateId to null for associated eval jobs when template is deleted", async () => {
+ // const { project, caller } = await prepare();
+
+ // // Create a template
+ // const evalTemplate = await prisma.evalTemplate.create({
+ // data: {
+ // projectId: project.id,
+ // name: "test-template",
+ // version: 1,
+ // prompt: "test prompt",
+ // model: "test-model",
+ // modelParams: {},
+ // vars: [],
+ // outputSchema: {
+ // score: "test-score",
+ // reasoning: "test-reasoning",
+ // },
+ // provider: "test-provider",
+ // },
+ // });
+
+ // // Create an eval job linked to this template
+ // const evalJob = await prisma.jobConfiguration.create({
+ // data: {
+ // projectId: project.id,
+ // jobType: "EVAL",
+ // scoreName: "test-score",
+ // filter: [],
+ // targetObject: "trace",
+ // variableMapping: [],
+ // sampling: 1,
+ // delay: 0,
+ // status: "ACTIVE",
+ // timeScope: ["NEW"],
+ // evalTemplateId: evalTemplate.id,
+ // },
+ // });
+
+ // // Delete the template
+ // await caller.evals.deleteEvalTemplate({
+ // projectId: project.id,
+ // evalTemplateId: evalTemplate.id,
+ // });
+
+ // // Verify template is deleted
+ // const deletedTemplate = await prisma.evalTemplate.findUnique({
+ // where: {
+ // id: evalTemplate.id,
+ // },
+ // });
+ // expect(deletedTemplate).toBeNull();
+
+ // // Verify eval job still exists but has evalTemplateId set to null
+ // const updatedJob = await prisma.jobConfiguration.findUnique({
+ // where: {
+ // id: evalJob.id,
+ // },
+ // });
+ // expect(updatedJob).not.toBeNull();
+ // expect(updatedJob?.evalTemplateId).toBeNull();
+ // });
+
+ // it("should throw error when trying to delete non-existent eval template", async () => {
+ // const { project, caller } = await prepare();
+
+ // await expect(
+ // caller.evals.deleteEvalTemplate({
+ // projectId: project.id,
+ // evalTemplateId: "non-existent-id",
+ // }),
+ // ).rejects.toThrow("Template not found");
+ // });
+
+ // it("should throw error when user lacks evalTemplate:CUD access scope", async () => {
+ // const { project, session } = await prepare();
+
+ // // Create a session with limited permissions
+ // const limitedSession: Session = {
+ // ...session,
+ // user: {
+ // id: session.user!.id,
+ // name: session.user!.name,
+ // canCreateOrganizations: session.user!.canCreateOrganizations,
+ // admin: false,
+ // featureFlags: session.user!.featureFlags,
+ // organizations: [
+ // {
+ // ...session.user!.organizations[0],
+ // role: "MEMBER",
+ // projects: [
+ // {
+ // ...session.user!.organizations[0].projects[0],
+ // role: "VIEWER", // VIEWER role doesn't have evalTemplate:CUD scope
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // expires: session.expires,
+ // environment: session.environment,
+ // };
+ // const limitedCtx = createInnerTRPCContext({ session: limitedSession });
+ // const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
+
+ // // Create a template
+ // const evalTemplate = await prisma.evalTemplate.create({
+ // data: {
+ // projectId: project.id,
+ // name: "test-template",
+ // version: 1,
+ // prompt: "test prompt",
+ // model: "test-model",
+ // modelParams: {},
+ // vars: [],
+ // outputSchema: {
+ // score: "test-score",
+ // reasoning: "test-reasoning",
+ // },
+ // provider: "test-provider",
+ // },
+ // });
+
+ // // Attempt to delete with limited permissions
+ // await expect(
+ // limitedCaller.evals.deleteEvalTemplate({
+ // projectId: project.id,
+ // evalTemplateId: evalTemplate.id,
+ // }),
+ // ).rejects.toThrow("User does not have access to this resource or action");
+ // });
+ // });
});
diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsx
index d2c22decc3..dcf431707a 100644
--- a/web/src/components/deleteButton.tsx
+++ b/web/src/components/deleteButton.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useRouter } from "next/router";
import {
Popover,
@@ -6,7 +6,7 @@ import {
PopoverTrigger,
} from "@/src/components/ui/popover";
import { Button } from "@/src/components/ui/button";
-import { TrashIcon } from "lucide-react";
+import { LockIcon, TrashIcon } from "lucide-react";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { type ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";
import { api } from "@/src/utils/api";
@@ -14,57 +14,75 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
-interface DeleteButtonProps {
+export type DeleteButtonProps = {
itemId: string;
projectId: string;
isTableAction?: boolean;
- scope: ProjectScope;
- invalidateFunc: () => void;
- type: "trace" | "dataset";
+ scope?: ProjectScope;
+ invalidateFunc?: () => void;
redirectUrl?: string;
deleteConfirmation?: string;
icon?: boolean;
-}
+ enabled?: boolean;
+};
+
+type BaseDeleteButtonProps = DeleteButtonProps & {
+ scope: NonNullable<DeleteButtonProps["scope"]>;
+ invalidateFunc: NonNullable<DeleteButtonProps["invalidateFunc"]>;
+ captureDeleteOpen: (
+ capture: ReturnType<typeof usePostHogClientCapture>,
+ isTableAction: boolean,
+ ) => void;
+ captureDeleteSuccess: (
+ capture: ReturnType<typeof usePostHogClientCapture>,
+ isTableAction: boolean,
+ ) => void;
+ entityToDeleteName: string;
+ executeDeleteMutation: (onSuccess: () => void) => Promise<void>;
+ isDeleteMutationLoading: boolean;
+};
-export function DeleteButton({
+function DeleteButton({
itemId,
projectId,
isTableAction = false,
scope,
invalidateFunc,
- type,
redirectUrl,
deleteConfirmation,
icon = false,
-}: DeleteButtonProps) {
+ enabled = true,
+ captureDeleteOpen,
+ captureDeleteSuccess,
+ entityToDeleteName,
+ executeDeleteMutation,
+ isDeleteMutationLoading,
+}: BaseDeleteButtonProps) {
const [isDeleted, setIsDeleted] = useState(false);
const router = useRouter();
const capture = usePostHogClientCapture();
const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");
const hasAccess = useHasProjectAccess({ projectId, scope: scope });
- const traceMutation = api.traces.deleteMany.useMutation({
- onSuccess: () => {
- setIsDeleted(true);
- showSuccessToast({
- title: "Trace deleted",
- description:
- "Selected trace will be deleted. Traces are removed asynchronously and may continue to be visible for up to 15 minutes.",
- });
- !isTableAction && redirectUrl
- ? void router.push(redirectUrl)
- : invalidateFunc();
- },
- });
- const datasetMutation = api.datasets.deleteDataset.useMutation({
- onSuccess: () => {
+
+ const onDeleteSuccess = useMemo(() => {
+ return () => {
setIsDeleted(true);
+ captureDeleteSuccess(capture, isTableAction);
!isTableAction && redirectUrl
? void router.push(redirectUrl)
: invalidateFunc();
- },
- });
+ };
+ }, [
+ isTableAction,
+ redirectUrl,
+ invalidateFunc,
+ router,
+ captureDeleteSuccess,
+ capture,
+ ]);
return (
<Popover key={itemId}>
@@ -72,23 +90,21 @@ export function DeleteButton({
<Button
variant={icon ? "outline" : "ghost"}
size={icon ? "icon" : "default"}
- disabled={!hasAccess}
+ disabled={!hasAccess || !enabled}
onClick={(e) => {
e.stopPropagation();
- type === "trace"
- ? capture("trace:delete_form_open", {
- source: isTableAction ? "table-single-row" : "trace detail",
- })
- : capture("datasets:delete_form_open", {
- source: "dataset",
- });
+ captureDeleteOpen(capture, isTableAction);
}}
>
{icon ? (
<TrashIcon className="h-4 w-4" />
) : (
<>
- <TrashIcon className="mr-2 h-4 w-4" />
+ {hasAccess ? (
+ <TrashIcon className="mr-2 h-4 w-4" />
+ ) : (
+ <LockIcon className="mr-2 h-4 w-4" />
+ )}
Delete
</>
)}
@@ -98,7 +114,7 @@ export function DeleteButton({
<h2 className="text-md mb-3 font-semibold">Please confirm</h2>
<p className="mb-3 text-sm">
This action cannot be undone and removes all the data associated with
- this {type}.
+ this {entityToDeleteName}.
</p>
{deleteConfirmation && (
<div className="mb-4 grid w-full gap-1.5">
@@ -113,57 +129,207 @@ export function DeleteButton({
</div>
)}
<div className="flex justify-end space-x-4">
- {type === "trace" ? (
- <Button
- type="button"
- variant="destructive"
- loading={traceMutation.isLoading || isDeleted}
- onClick={() => {
- if (
- deleteConfirmation &&
- deleteConfirmationInput !== deleteConfirmation
- ) {
- alert("Please type the correct confirmation");
- return;
- }
- void traceMutation.mutateAsync({
- traceIds: [itemId],
- projectId,
- });
- capture("trace:delete", {
- source: isTableAction ? "table-single-row" : "trace",
- });
- }}
- >
- Delete trace
- </Button>
- ) : (
- <Button
- type="button"
- variant="destructive"
- loading={datasetMutation.isLoading || isDeleted}
- onClick={() => {
- if (
- deleteConfirmation &&
- deleteConfirmationInput !== deleteConfirmation
- ) {
- alert("Please type the correct confirmation");
- return;
- }
- void datasetMutation.mutateAsync({
- projectId,
- datasetId: itemId,
- });
- capture("datasets:delete_dataset_button_click", {
- source: isTableAction ? "table-single-row" : "dataset",
- });
- }}
- >
- Delete dataset
- </Button>
- )}
+ <Button
+ type="button"
+ variant="destructive"
+ loading={isDeleteMutationLoading || isDeleted}
+ onClick={() => {
+ if (
+ deleteConfirmation &&
+ deleteConfirmationInput !== deleteConfirmation
+ ) {
+ alert("Please type the correct confirmation");
+ return;
+ }
+ void executeDeleteMutation(onDeleteSuccess);
+ }}
+ >
+ Delete {entityToDeleteName}
+ </Button>
</div>
</PopoverContent>
</Popover>
);
}
+
+export function DeleteTraceButton(props: DeleteButtonProps) {
+ const utils = api.useUtils();
+ const {
+ itemId,
+ projectId,
+ scope = "traces:delete",
+ invalidateFunc = () => void utils.traces.all.invalidate(),
+ } = props;
+ const traceMutation = api.traces.deleteMany.useMutation();
+ const executeDeleteMutation = async (onSuccess: () => void) => {
+ try {
+ await traceMutation.mutateAsync({
+ traceIds: [itemId],
+ projectId,
+ });
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ showSuccessToast({
+ title: "Trace deleted",
+ description:
+ "Selected trace will be deleted. Traces are removed asynchronously and may continue to be visible for up to 15 minutes.",
+ });
+ onSuccess();
+ };
+ const hasTraceDeletionEntitlement = useHasEntitlement("trace-deletion");
+ return (
+ <DeleteButton
+ {...props}
+ scope={scope}
+ invalidateFunc={invalidateFunc}
+ captureDeleteOpen={(capture, isTableAction) =>
+ capture("trace:delete_form_open", {
+ source: isTableAction ? "table-single-row" : "trace detail",
+ })
+ }
+ captureDeleteSuccess={(capture, isTableAction) =>
+ capture("trace:delete", {
+ source: isTableAction ? "table-single-row" : "trace",
+ })
+ }
+ entityToDeleteName="trace"
+ executeDeleteMutation={executeDeleteMutation}
+ isDeleteMutationLoading={traceMutation.isLoading}
+ enabled={hasTraceDeletionEntitlement}
+ />
+ );
+}
+
+export function DeleteDatasetButton(props: DeleteButtonProps) {
+ const utils = api.useUtils();
+ const {
+ itemId,
+ projectId,
+ scope = "datasets:CUD",
+ invalidateFunc = () => void utils.datasets.invalidate(),
+ } = props;
+ const datasetMutation = api.datasets.deleteDataset.useMutation();
+ const executeDeleteMutation = async (onSuccess: () => void) => {
+ try {
+ await datasetMutation.mutateAsync({
+ datasetId: itemId,
+ projectId,
+ });
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ onSuccess();
+ };
+ return (
+ <DeleteButton
+ {...props}
+ scope={scope}
+ invalidateFunc={invalidateFunc}
+ captureDeleteOpen={(capture, isTableAction) =>
+ capture("datasets:delete_form_open", {
+ source: isTableAction ? "table-single-row" : "dataset",
+ })
+ }
+ captureDeleteSuccess={(capture, isTableAction) =>
+ capture("datasets:delete_dataset_button_click", {
+ source: isTableAction ? "table-single-row" : "dataset",
+ })
+ }
+ entityToDeleteName="dataset"
+ executeDeleteMutation={executeDeleteMutation}
+ isDeleteMutationLoading={datasetMutation.isLoading}
+ />
+ );
+}
+
+export function DeleteEvaluatorButton(props: DeleteButtonProps) {
+ const utils = api.useUtils();
+ const {
+ itemId,
+ projectId,
+ scope = "evalJob:CUD",
+ invalidateFunc = () => void utils.evals.invalidate(),
+ } = props;
+ const evaluatorMutation = api.evals.deleteEvalJob.useMutation();
+ const executeDeleteMutation = async (onSuccess: () => void) => {
+ try {
+ await evaluatorMutation.mutateAsync({
+ evalConfigId: itemId,
+ projectId,
+ });
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ onSuccess();
+ };
+ const hasModelBasedEvaluationEntitlement = useHasEntitlement(
+ "model-based-evaluations",
+ );
+ return (
+ <DeleteButton
+ {...props}
+ scope={scope}
+ invalidateFunc={invalidateFunc}
+ captureDeleteOpen={(capture, isTableAction) =>
+ capture("eval_config:delete_form_open", {
+ source: isTableAction ? "table-single-row" : "evaluator",
+ })
+ }
+ captureDeleteSuccess={(capture, isTableAction) =>
+ capture("eval_config:delete_evaluator_button_click", {
+ source: isTableAction ? "table-single-row" : "evaluator",
+ })
+ }
+ entityToDeleteName="evaluator"
+ executeDeleteMutation={executeDeleteMutation}
+ isDeleteMutationLoading={evaluatorMutation.isLoading}
+ enabled={hasModelBasedEvaluationEntitlement}
+ />
+ );
+}
+
+// TODO: Moved to LFE-4573
+// export function DeleteEvaluatorTemplateButton(props: DeleteButtonProps) {
+// const utils = api.useUtils();
+// const { itemId, projectId,
+// scope = "evalTemplate:CUD",
+// invalidateFunc = () => void utils.evals.invalidate(),
+// } = props;
+// const templateMutation = api.evals.deleteEvalTemplate.useMutation();
+// const executeDeleteMutation = async (onSuccess: () => void) => {
+// try {
+// await templateMutation.mutateAsync({
+// evalTemplateId: itemId,
+// projectId,
+// });
+// } catch (error) {
+// return Promise.reject(error);
+// }
+// onSuccess();
+// };
+// const hasModelBasedEvaluationEntitlement = useHasEntitlement(
+// "model-based-evaluations",
+// );
+// return (
+// <DeleteButton
+// {...props}
+// scope={scope}
+// invalidateFunc={invalidateFunc}
+// captureDeleteOpen={(capture, isTableAction) =>
+// capture("eval_templates:delete_form_open", {
+// source: isTableAction ? "table-single-row" : "template",
+// })
+// }
+// captureDeleteSuccess={(capture, isTableAction) =>
+// capture("eval_templates:delete_template_button_click", {
+// source: isTableAction ? "table-single-row" : "template",
+// })
+// }
+// entityToDeleteName="template"
+// executeDeleteMutation={executeDeleteMutation}
+// isDeleteMutationLoading={templateMutation.isLoading}
+// enabled={hasModelBasedEvaluationEntitlement}
+// />
+// );
+// }
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index baff6269ba..b29869be27 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -21,7 +21,7 @@ import {
} from "use-query-params";
import type Decimal from "decimal.js";
import { numberFormatter, usdFormatter } from "@/src/utils/numbers";
-import { DeleteButton } from "@/src/components/deleteButton";
+import { DeleteTraceButton } from "@/src/components/deleteButton";
import {
formatAsLabel,
LevelColors,
@@ -880,29 +880,27 @@ export default function TracesTable({
isPinned: true,
cell: ({ row }) => {
const traceId: TracesTableRow["id"] = row.getValue("id");
- return traceId &&
- typeof traceId === "string" &&
- hasTraceDeletionEntitlement ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost">
- <MoreVertical className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem asChild>
- <DeleteButton
- itemId={traceId}
- projectId={projectId}
- scope="traces:delete"
- invalidateFunc={() => void utils.traces.all.invalidate()}
- type="trace"
- isTableAction={true}
- />
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- ) : undefined;
+ return (
+ traceId &&
+ typeof traceId === "string" && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost">
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <DeleteTraceButton
+ itemId={traceId}
+ projectId={projectId}
+ isTableAction
+ />
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ );
},
},
];
diff --git a/web/src/components/trace/TracePage.tsx b/web/src/components/trace/TracePage.tsx
index bcb6b25033..1d7a10dd47 100644
--- a/web/src/components/trace/TracePage.tsx
+++ b/web/src/components/trace/TracePage.tsx
@@ -5,8 +5,7 @@ import { useRouter } from "next/router";
import { api } from "@/src/utils/api";
import { StarTraceDetailsToggle } from "@/src/components/star-toggle";
import { ErrorPage } from "@/src/components/error-page";
-import { DeleteButton } from "@/src/components/deleteButton";
-import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+import { DeleteTraceButton } from "@/src/components/deleteButton";
import Page from "@/src/components/layouts/page";
import { Trace } from "@/src/components/trace";
import { TagTraceDetailsPopover } from "@/src/features/tag/components/TagTraceDetailsPopover";
@@ -20,7 +19,6 @@ export function TracePage({
timestamp?: Date;
}) {
const router = useRouter();
- const utils = api.useUtils();
const trace = api.traces.byIdWithObservationsAndScores.useQuery(
{
@@ -70,8 +68,6 @@ export function TracePage({
withDefault(StringParam, "details"),
);
- const hasTraceDeletionEntitlement = useHasEntitlement("trace-deletion");
-
if (trace.error?.data?.code === "UNAUTHORIZED")
return <ErrorPage message="You do not have access to this trace." />;
@@ -153,18 +149,13 @@ export function TracePage({
}}
listKey="traces"
/>
- {hasTraceDeletionEntitlement && (
- <DeleteButton
- itemId={traceId}
- projectId={trace.data.projectId}
- scope="traces:delete"
- invalidateFunc={() => void utils.traces.all.invalidate()}
- type="trace"
- redirectUrl={`/project/${router.query.projectId as string}/traces`}
- deleteConfirmation={trace.data.name ?? ""}
- icon
- />
- )}
+ <DeleteTraceButton
+ itemId={traceId}
+ projectId={trace.data.projectId}
+ redirectUrl={`/project/${router.query.projectId as string}/traces`}
+ deleteConfirmation={trace.data.name ?? ""}
+ icon
+ />
</>
),
}}
diff --git a/web/src/ee/features/evals/components/eval-template-detail.tsx b/web/src/ee/features/evals/components/eval-template-detail.tsx
index bbfdcc05bf..8bb0b9c1db 100644
--- a/web/src/ee/features/evals/components/eval-template-detail.tsx
+++ b/web/src/ee/features/evals/components/eval-template-detail.tsx
@@ -45,6 +45,8 @@ export const EvalTemplateDetail = () => {
},
);
+ // const utils = api.useUtils();
+
return (
<Page
withPadding
@@ -77,6 +79,18 @@ export const EvalTemplateDetail = () => {
);
}}
/>
+ {/* TODO: moved to LFE-4573 */}
+ {/* <DeleteEvaluatorTemplateButton
+ itemId={templateId}
+ projectId={projectId}
+ redirectUrl={`/project/${projectId}/evals/templates`}
+ deleteConfirmation={
+ template.data != null
+ ? `${template.data.name}-v${template.data.version}`
+ : undefined
+ }
+ enabled={!template.isLoading}
+ /> */}
</>
),
}}
@@ -145,7 +159,7 @@ export function UpdateTemplate({
}) {
const hasAccess = useHasProjectAccess({
projectId,
- scope: "evalTemplate:create",
+ scope: "evalTemplate:CUD",
});
const capture = usePostHogClientCapture();
diff --git a/web/src/ee/features/evals/components/evaluator-detail.tsx b/web/src/ee/features/evals/components/evaluator-detail.tsx
index 4b43ec0e54..c809dd3904 100644
--- a/web/src/ee/features/evals/components/evaluator-detail.tsx
+++ b/web/src/ee/features/evals/components/evaluator-detail.tsx
@@ -37,6 +37,7 @@ import {
type JobExecutionState,
generateJobExecutionCounts,
} from "@/src/ee/features/evals/utils/job-execution-utils";
+import { DeleteEvaluatorButton } from "@/src/components/deleteButton";
const JobExecutionCounts = ({
jobExecutionsByState,
@@ -140,6 +141,13 @@ export const EvaluatorDetail = () => {
listKey="evals"
/>
)}
+ <DeleteEvaluatorButton
+ itemId={evaluatorId}
+ projectId={projectId}
+ redirectUrl={`/project/${projectId}/evals`}
+ deleteConfirmation={evaluator.data?.scoreName}
+ icon
+ />
</>
),
}}
diff --git a/web/src/ee/features/evals/pages/templates.tsx b/web/src/ee/features/evals/pages/templates.tsx
index 3547141fef..52cd854b5b 100644
--- a/web/src/ee/features/evals/pages/templates.tsx
+++ b/web/src/ee/features/evals/pages/templates.tsx
@@ -18,7 +18,7 @@ export default function TemplatesPage() {
const capture = usePostHogClientCapture();
const hasWriteAccess = useHasProjectAccess({
projectId,
- scope: "evalTemplate:create",
+ scope: "evalTemplate:CUD",
});
const hasReadAccess = useHasProjectAccess({
diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.ts
index e275ac8c1a..35a231bcf4 100644
--- a/web/src/ee/features/evals/server/router.ts
+++ b/web/src/ee/features/evals/server/router.ts
@@ -710,7 +710,7 @@ export const evalRouter = createTRPCRouter({
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "evalTemplate:create",
+ scope: "evalTemplate:CUD",
});
const matchingLLMKey = await ctx.prisma.llmApiKeys.findFirst({
@@ -940,6 +940,98 @@ export const evalRouter = createTRPCRouter({
return updatedJob;
}),
+ deleteEvalJob: protectedProjectProcedure
+ .input(z.object({ projectId: z.string(), evalConfigId: z.string() }))
+ .mutation(async ({ ctx, input: { projectId, evalConfigId } }) => {
+ throwIfNoEntitlement({
+ entitlement: "model-based-evaluations",
+ projectId: projectId,
+ sessionUser: ctx.session.user,
+ });
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: projectId,
+ scope: "evalJob:CUD",
+ });
+
+ const existingJob = await ctx.prisma.jobConfiguration.findUnique({
+ where: {
+ id: evalConfigId,
+ projectId: projectId,
+ },
+ });
+
+ if (!existingJob) {
+ logger.warn(
+ `Job for deletion not found for project ${projectId} and id ${evalConfigId}`,
+ );
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Job not found",
+ });
+ }
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "job",
+ resourceId: evalConfigId,
+ action: "delete",
+ });
+
+ await ctx.prisma.jobConfiguration.delete({
+ where: {
+ id: evalConfigId,
+ projectId: projectId,
+ },
+ });
+ }),
+
+ // TODO: moved to LFE-4573
+ // deleteEvalTemplate: protectedProjectProcedure
+ // .input(z.object({ projectId: z.string(), evalTemplateId: z.string() }))
+ // .mutation(async ({ ctx, input: { projectId, evalTemplateId } }) => {
+ // throwIfNoEntitlement({
+ // entitlement: "model-based-evaluations",
+ // projectId: projectId,
+ // sessionUser: ctx.session.user,
+ // });
+ // throwIfNoProjectAccess({
+ // session: ctx.session,
+ // projectId: projectId,
+ // scope: "evalTemplate:CUD",
+ // });
+
+ // const existingTemplate = await ctx.prisma.evalTemplate.findUnique({
+ // where: {
+ // id: evalTemplateId,
+ // projectId: projectId,
+ // },
+ // });
+
+ // if (!existingTemplate) {
+ // logger.warn(
+ // `Template for deletion not found for project ${projectId} and id ${evalTemplateId}`,
+ // );
+ // throw new TRPCError({
+ // code: "NOT_FOUND",
+ // message: "Template not found",
+ // });
+ // }
+
+ // await auditLog({
+ // session: ctx.session,
+ // resourceType: "evalTemplate",
+ // resourceId: evalTemplateId,
+ // action: "delete",
+ // });
+
+ // await ctx.prisma.evalTemplate.delete({
+ // where: {
+ // id: evalTemplateId,
+ // projectId: projectId,
+ // },
+ // });
+ // }),
getLogs: protectedProjectProcedure
.input(
z.object({
diff --git a/web/src/features/datasets/components/DatasetActionButton.tsx b/web/src/features/datasets/components/DatasetActionButton.tsx
index c38ec94719..87cc793d29 100644
--- a/web/src/features/datasets/components/DatasetActionButton.tsx
+++ b/web/src/features/datasets/components/DatasetActionButton.tsx
@@ -77,6 +77,7 @@ export const DatasetActionButton = (props: DatasetActionButtonProps) => {
variant={props.variant || "ghost"}
size={props.size || "icon"}
className={props.className}
+ disabled={!hasAccess}
onClick={() => {
setOpen(true);
capture("datasets:update_form_open", {
@@ -97,6 +98,7 @@ export const DatasetActionButton = (props: DatasetActionButtonProps) => {
variant={props.variant || "ghost"}
size={props.size}
className={props.className}
+ disabled={!hasAccess}
onClick={() => {
setOpen(true);
capture("datasets:delete_form_open", {
@@ -104,7 +106,11 @@ export const DatasetActionButton = (props: DatasetActionButtonProps) => {
});
}}
>
- <Trash className="mr-2 h-4 w-4" />
+ {hasAccess ? (
+ <Trash className="mr-2 h-4 w-4" />
+ ) : (
+ <LockIcon className="mr-2 h-4 w-4" aria-hidden="true" />
+ )}
Delete
</Button>
) : (
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 239e0fc3bf..e7b4a6151a 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -67,6 +67,8 @@ const events = {
"activate",
"deactivate",
"update",
+ "delete_form_open",
+ "delete_evaluator_button_click",
],
eval_templates: [
"view_version",
@@ -74,6 +76,8 @@ const events = {
"update_form_open",
"new_form_submit",
"update_form_submit",
+ "delete_form_open",
+ "delete_template_button_click",
],
integrations: ["posthog_form_submitted", "blob_storage_form_submitted"],
sign_in: ["cloud_region_switch", "button_click"],
diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.ts
index cdcead2111..751ca30b3c 100644
--- a/web/src/features/rbac/constants/projectAccessRights.ts
+++ b/web/src/features/rbac/constants/projectAccessRights.ts
@@ -37,7 +37,7 @@ const projectScopes = [
"batchExports:create",
"batchExports:read",
- "evalTemplate:create",
+ "evalTemplate:CUD",
"evalTemplate:read",
"evalJob:read",
"evalJob:CUD",
@@ -86,7 +86,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"prompts:CUD",
"prompts:read",
"models:CUD",
- "evalTemplate:create",
+ "evalTemplate:CUD",
"evalTemplate:read",
"evalJob:CUD",
"evalJob:read",
@@ -127,7 +127,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"prompts:CUD",
"prompts:read",
"models:CUD",
- "evalTemplate:create",
+ "evalTemplate:CUD",
"evalTemplate:read",
"evalJob:CUD",
"evalJob:read",
@@ -162,7 +162,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"datasets:CUD",
"prompts:CUD",
"prompts:read",
- "evalTemplate:create",
+ "evalTemplate:CUD",
"evalTemplate:read",
"evalJob:read",
"evalJob:CUD",
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
index 562fc1cf89..bb5bf81856 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
@@ -9,7 +9,7 @@ import {
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
-import { DeleteButton } from "@/src/components/deleteButton";
+import { DeleteDatasetButton } from "@/src/components/deleteButton";
import { DuplicateDatasetButton } from "@/src/features/datasets/components/DuplicateDatasetButton";
import { useState } from "react";
import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
@@ -265,13 +265,9 @@ export default function Dataset() {
/>
</DropdownMenuItem>
<DropdownMenuItem asChild>
- <DeleteButton
+ <DeleteDatasetButton
itemId={datasetId}
projectId={projectId}
- isTableAction={false}
- scope="datasets:CUD"
- invalidateFunc={() => void utils.datasets.invalidate()}
- type="dataset"
redirectUrl={`/project/${projectId}/datasets`}
deleteConfirmation={dataset.data?.name}
/>
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
index 0328afbc99..3e6f61fe8d 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
@@ -9,7 +9,7 @@ import Link from "next/link";
import { DatasetItemsTable } from "@/src/features/datasets/components/DatasetItemsTable";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
import { DatasetActionButton } from "@/src/features/datasets/components/DatasetActionButton";
-import { DeleteButton } from "@/src/components/deleteButton";
+import { DeleteDatasetButton } from "@/src/components/deleteButton";
import { NewDatasetItemButton } from "@/src/features/datasets/components/NewDatasetItemButton";
import { DuplicateDatasetButton } from "@/src/features/datasets/components/DuplicateDatasetButton";
import { UploadDatasetCsvButton } from "@/src/features/datasets/components/UploadDatasetCsvButton";
@@ -33,7 +33,6 @@ export default function DatasetItems() {
const router = useRouter();
const projectId = router.query.projectId as string;
const datasetId = router.query.datasetId as string;
- const utils = api.useUtils();
const dataset = api.datasets.byId.useQuery({
datasetId,
@@ -127,13 +126,9 @@ export default function DatasetItems() {
/>
</DropdownMenuItem>
<DropdownMenuItem asChild>
- <DeleteButton
+ <DeleteDatasetButton
itemId={datasetId}
projectId={projectId}
- isTableAction={false}
- scope="datasets:CUD"
- invalidateFunc={() => void utils.datasets.invalidate()}
- type="dataset"
redirectUrl={`/project/${projectId}/datasets`}
deleteConfirmation={dataset.data?.name}
/>
diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.ts
index 2001049267..4883ed4bf5 100644
--- a/worker/src/ee/evaluation/evalService.ts
+++ b/worker/src/ee/evaluation/evalService.ts
@@ -306,7 +306,14 @@ export const evaluate = async ({
.selectAll()
.where("id", "=", event.jobExecutionId)
.where("project_id", "=", event.projectId)
- .executeTakeFirstOrThrow();
+ .executeTakeFirst();
+
+ if (!job) {
+ logger.info(
+ `Job execution with id ${event.jobExecutionId} for project ${event.projectId} not found. This was likely deleted by the user.`,
+ );
+ return;
+ }
if (!job?.job_input_trace_id) {
throw new ForbiddenError(