Skip to content

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

feat: add trace delete API endpoints (#5931)

Steffen Schmitz330cca6978a1
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index 8bc311b101..e21216136b 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -15,6 +15,15 @@ service:
type: string
docs: The unique langfuse identifier of a trace
response: commons.TraceWithFullDetails
+ delete:
+ docs: Delete a specific trace
+ method: DELETE
+ path: /traces/{traceId}
+ path-parameters:
+ traceId:
+ type: string
+ docs: The unique langfuse identifier of the trace to delete
+ response: DeleteTraceResponse
list:
docs: Get list of traces
method: GET
@@ -55,12 +64,27 @@ service:
allow-multiple: true
docs: Optional filter for traces where the environment is one of the provided values.
response: Traces
+ deleteMultiple:
+ docs: Delete multiple traces
+ method: DELETE
+ path: /traces
+ request:
+ name: DeleteTracesRequest
+ body:
+ properties:
+ traceIds:
+ type: list<string>
+ docs: List of trace IDs to delete
+ response: DeleteTraceResponse
types:
Traces:
properties:
data: list<commons.TraceWithDetails>
meta: pagination.MetaResponse
+ DeleteTraceResponse:
+ properties:
+ message: string
Sort:
properties:
id: string
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 159add2d64..3a8c54b2dd 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2536,6 +2536,52 @@ paths:
schema: {}
security:
- BasicAuth: []
+ delete:
+ description: Delete a specific trace
+ operationId: trace_delete
+ tags:
+ - Trace
+ parameters:
+ - name: traceId
+ in: path
+ description: The unique langfuse identifier of the trace to delete
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeleteTraceResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
/api/public/traces:
get:
description: Get list of traces
@@ -2675,6 +2721,60 @@ paths:
schema: {}
security:
- BasicAuth: []
+ delete:
+ description: Delete multiple traces
+ operationId: trace_deleteMultiple
+ tags:
+ - Trace
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeleteTraceResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ traceIds:
+ type: array
+ items:
+ type: string
+ description: List of trace IDs to delete
+ required:
+ - traceIds
components:
schemas:
CreateCommentRequest:
@@ -5174,6 +5274,14 @@ components:
required:
- data
- meta
+ DeleteTraceResponse:
+ title: DeleteTraceResponse
+ type: object
+ properties:
+ message:
+ type: string
+ required:
+ - message
Sort:
title: Sort
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 8e2f030060..d8a4ca1e3d 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1913,6 +1913,38 @@
},
"response": []
},
+ {
+ "_type": "endpoint",
+ "name": "Delete",
+ "request": {
+ "description": "Delete a specific trace",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/traces/:traceId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "traces",
+ ":traceId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "traceId",
+ "value": "",
+ "description": "The unique langfuse identifier of the trace to delete"
+ }
+ ]
+ },
+ "header": [],
+ "method": "DELETE",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
{
"_type": "endpoint",
"name": "List",
@@ -1998,6 +2030,39 @@
"body": null
},
"response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Delete Multiple",
+ "request": {
+ "description": "Delete multiple traces",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/traces",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "traces"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "DELETE",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"traceIds\": [\n \"example\"\n ]\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
}
]
}
diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.ts
index 59dbfb4f87..518bc380d9 100644
--- a/web/src/__tests__/async/traces-api.servertest.ts
+++ b/web/src/__tests__/async/traces-api.servertest.ts
@@ -3,6 +3,7 @@ import {
createScore,
createScoresCh,
createTrace,
+ getTraceById,
} from "@langfuse/shared/src/server";
import {
createObservationsCh,
@@ -13,18 +14,23 @@ import {
makeZodVerifiedAPICallSilent,
} from "@/src/__tests__/test-utils";
import {
+ DeleteTracesV1Response,
+ DeleteTraceV1Response,
GetTracesV1Response,
GetTraceV1Response,
} from "@/src/features/public-api/types/traces";
import { randomUUID } from "crypto";
import { snakeCase } from "lodash";
+import waitForExpect from "wait-for-expect";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
describe("/api/public/traces API Endpoint", () => {
it("should create and get a trace via /traces", async () => {
const createdTrace = createTrace({
name: "trace-name",
user_id: "user-1",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
release: "1.0.0",
version: "2.0.0",
@@ -64,7 +70,7 @@ describe("/api/public/traces API Endpoint", () => {
expect(trace.body.release).toBe("1.0.0");
expect(trace.body.externalId).toBeNull();
expect(trace.body.version).toBe("2.0.0");
- expect(trace.body.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.body.projectId).toBe(projectId);
expect(trace.body.latency).toBeCloseTo(100, 2);
expect(trace.body.observations.length).toBe(2);
expect(trace.body.scores.length).toBe(0);
@@ -90,7 +96,7 @@ describe("/api/public/traces API Endpoint", () => {
name: "trace-name",
user_id: "user-1",
timestamp: timestamp.getTime(),
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value", jsonKey: JSON.stringify({ foo: "bar" }) },
release: "1.0.0",
version: "2.0.0",
@@ -139,7 +145,7 @@ describe("/api/public/traces API Endpoint", () => {
expect(trace.metadata.jsonKey).toEqual({ foo: "bar" });
expect(trace.externalId).toBeNull();
expect(trace.version).toBe("2.0.0");
- expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.projectId).toBe(projectId);
expect(trace.latency).toBe(100);
expect(trace.observations.length).toBe(2);
expect(trace.scores.length).toBe(0);
@@ -158,13 +164,13 @@ describe("/api/public/traces API Endpoint", () => {
async (prop: string, value: string) => {
const createdTrace = createTrace({
[snakeCase(prop)]: value,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
});
// Create a trace in the project that should not be returned
const dummyTrace = createTrace({
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
});
@@ -179,7 +185,7 @@ describe("/api/public/traces API Endpoint", () => {
expect(traces.body.meta.totalItems).toBe(1);
expect(traces.body.data.length).toBe(1);
const trace = traces.body.data[0];
- expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.projectId).toBe(projectId);
expect((trace as any)[prop]).toBe(value);
},
);
@@ -190,7 +196,7 @@ describe("/api/public/traces API Endpoint", () => {
const createdTrace = createTrace({
id: traceId,
name: "trace-name",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
environment,
});
@@ -201,13 +207,13 @@ describe("/api/public/traces API Endpoint", () => {
createObservation({
trace_id: traceId,
environment,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
}),
// Create one that does not belong to the same environment
createObservation({
trace_id: traceId,
environment: "default",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
}),
]);
@@ -215,13 +221,13 @@ describe("/api/public/traces API Endpoint", () => {
createScore({
trace_id: traceId,
environment,
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
}),
// Create one that does not belong to the same environment
createScore({
trace_id: traceId,
environment: "default",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
}),
]);
@@ -234,7 +240,7 @@ describe("/api/public/traces API Endpoint", () => {
expect(traces.body.meta.totalItems).toBe(1);
expect(traces.body.data.length).toBe(1);
const trace = traces.body.data[0];
- expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.projectId).toBe(projectId);
expect(trace.observations.length).toBe(1);
expect(trace.scores.length).toBe(1);
});
@@ -243,7 +249,7 @@ describe("/api/public/traces API Endpoint", () => {
const tag = randomUUID();
const createdTrace = createTrace({
name: "trace-name",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
@@ -259,26 +265,26 @@ describe("/api/public/traces API Endpoint", () => {
expect(traces.body.meta.totalItems).toBe(1);
expect(traces.body.data.length).toBe(1);
const trace = traces.body.data[0];
- expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.projectId).toBe(projectId);
});
it("should fetch all traces with pagination", async () => {
const tag = randomUUID();
const createdTrace1 = createTrace({
name: "trace-name",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
const createdTrace2 = createTrace({
name: "trace-name",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
const createdTrace3 = createTrace({
name: "trace-name",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
@@ -295,20 +301,20 @@ describe("/api/public/traces API Endpoint", () => {
expect(traces.body.data.length).toBe(1);
expect(traces.body.meta.totalPages).toBe(3);
const trace = traces.body.data[0];
- expect(trace.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(trace.projectId).toBe(projectId);
});
it("should fetch all traces with custom order", async () => {
const tag = randomUUID();
const createdTrace1 = createTrace({
name: "trace-name1",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
const createdTrace2 = createTrace({
name: "trace-name2",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: "value" },
tags: [tag],
});
@@ -344,7 +350,7 @@ describe("/api/public/traces API Endpoint", () => {
const trace = createTrace({
id: traceId,
name: "trace-name1",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: JSON.stringify({ foo: "bar" }) },
input: JSON.stringify({
args: [
@@ -381,7 +387,7 @@ describe("/api/public/traces API Endpoint", () => {
const trace = createTrace({
id: traceId,
name: "trace-name1",
- project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ project_id: projectId,
metadata: { key: JSON.stringify({ foo: "bar" }) },
input: JSON.stringify({
args: [
@@ -410,4 +416,59 @@ describe("/api/public/traces API Endpoint", () => {
],
});
});
+
+ it("should delete a single trace via DELETE /traces/:traceId", async () => {
+ // Setup
+ const createdTrace = createTrace({
+ name: "trace-to-delete",
+ project_id: projectId,
+ });
+ await createTracesCh([createdTrace]);
+
+ // When
+ const deleteResponse = await makeZodVerifiedAPICall(
+ DeleteTraceV1Response,
+ "DELETE",
+ `/api/public/traces/${createdTrace.id}`,
+ );
+
+ // Then
+ expect(deleteResponse.status).toBe(200);
+ await waitForExpect(async () => {
+ const trace = await getTraceById(createdTrace.id, projectId);
+ expect(trace).toBeUndefined();
+ }, 10_000);
+ }, 10_000);
+
+ it("should delete multiple traces via DELETE /traces", async () => {
+ // Setup
+ const createdTrace1 = createTrace({
+ name: "trace-to-delete-1",
+ project_id: projectId,
+ });
+ const createdTrace2 = createTrace({
+ name: "trace-to-delete-2",
+ project_id: projectId,
+ });
+ await createTracesCh([createdTrace1, createdTrace2]);
+
+ // When
+ const deleteResponse = await makeZodVerifiedAPICall(
+ DeleteTracesV1Response,
+ "DELETE",
+ `/api/public/traces`,
+ {
+ traceIds: [createdTrace1.id, createdTrace2.id],
+ },
+ );
+
+ // Then
+ expect(deleteResponse.status).toBe(200);
+ await waitForExpect(async () => {
+ const trace1 = await getTraceById(createdTrace1.id, projectId);
+ expect(trace1).toBeUndefined();
+ const trace2 = await getTraceById(createdTrace2.id, projectId);
+ expect(trace2).toBeUndefined();
+ }, 25_000);
+ }, 30_000);
});
diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.ts
index 766a57623d..513b8d997f 100644
--- a/web/src/features/public-api/types/traces.ts
+++ b/web/src/features/public-api/types/traces.ts
@@ -88,3 +88,25 @@ export const GetTraceV1Response = APIExtendedTrace.extend({
scores: z.array(APIScoreSchema),
observations: z.array(APIObservation),
}).strict();
+
+// DELETE /api/public/traces/{traceId}
+export const DeleteTraceV1Query = z.object({
+ traceId: z.string(),
+});
+export const DeleteTraceV1Response = z
+ .object({
+ message: z.string(),
+ })
+ .strict();
+
+// DELETE /api/public/traces
+export const DeleteTracesV1Body = z
+ .object({
+ traceIds: z.array(z.string()).min(1, "At least 1 traceId is required."),
+ })
+ .strict();
+export const DeleteTracesV1Response = z
+ .object({
+ message: z.string(),
+ })
+ .strict();
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index 8be262eede..6aaa7c6f83 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -4,6 +4,8 @@ import { transformDbToApiObservation } from "@/src/features/public-api/types/obs
import {
GetTraceV1Query,
GetTraceV1Response,
+ DeleteTraceV1Query,
+ DeleteTraceV1Response,
} from "@/src/features/public-api/types/traces";
import {
filterAndValidateDbScoreList,
@@ -15,8 +17,13 @@ import {
getScoresForTraces,
getTraceById,
traceException,
+ QueueJobs,
+ TraceDeleteQueue,
} from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
+import { randomUUID } from "crypto";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { TRPCError } from "@trpc/server";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -127,4 +134,43 @@ export default withMiddlewares({
};
},
}),
+
+ DELETE: createAuthedAPIRoute({
+ name: "Delete Single Trace",
+ querySchema: DeleteTraceV1Query,
+ responseSchema: DeleteTraceV1Response,
+ fn: async ({ query, auth }) => {
+ const { traceId } = query;
+
+ const traceDeleteQueue = TraceDeleteQueue.getInstance();
+ if (!traceDeleteQueue) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "TraceDeleteQueue not initialized",
+ });
+ }
+
+ await auditLog({
+ resourceType: "trace",
+ resourceId: traceId,
+ action: "delete",
+ projectId: auth.scope.projectId,
+ apiKeyId: auth.scope.apiKeyId,
+ orgId: auth.scope.orgId,
+ });
+
+ // Add to delete queue
+ await traceDeleteQueue.add(QueueJobs.TraceDelete, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ payload: {
+ projectId: auth.scope.projectId,
+ traceIds: [traceId],
+ },
+ name: QueueJobs.TraceDelete,
+ });
+
+ return { message: "Trace deleted successfully" };
+ },
+ }),
});
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index f2e41d4ffe..41f2486101 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -3,12 +3,19 @@ import {
GetTracesV1Query,
GetTracesV1Response,
PostTracesV1Response,
+ DeleteTracesV1Body,
+ DeleteTracesV1Response,
} from "@/src/features/public-api/types/traces";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { processEventBatch } from "@langfuse/shared/src/server";
-import { eventTypes, logger } from "@langfuse/shared/src/server";
+import {
+ eventTypes,
+ logger,
+ QueueJobs,
+ TraceDeleteQueue,
+} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
import { telemetry } from "@/src/features/telemetry";
@@ -16,6 +23,9 @@ import {
generateTracesForPublicApi,
getTracesCountForPublicApi,
} from "@/src/features/public-api/server/traces";
+import { TRPCError } from "@trpc/server";
+import { randomUUID } from "crypto";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
export default withMiddlewares({
POST: createAuthedAPIRoute({
@@ -87,4 +97,46 @@ export default withMiddlewares({
};
},
}),
+
+ DELETE: createAuthedAPIRoute({
+ name: "Delete Multiple Traces",
+ bodySchema: DeleteTracesV1Body,
+ responseSchema: DeleteTracesV1Response,
+ fn: async ({ body, auth }) => {
+ const { traceIds } = body;
+
+ const traceDeleteQueue = TraceDeleteQueue.getInstance();
+ if (!traceDeleteQueue) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "TraceDeleteQueue not initialized",
+ });
+ }
+
+ await Promise.all(
+ traceIds.map((traceId) =>
+ auditLog({
+ resourceType: "trace",
+ resourceId: traceId,
+ action: "delete",
+ projectId: auth.scope.projectId,
+ apiKeyId: auth.scope.apiKeyId,
+ orgId: auth.scope.orgId,
+ }),
+ ),
+ );
+
+ await traceDeleteQueue.add(QueueJobs.TraceDelete, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ payload: {
+ projectId: auth.scope.projectId,
+ traceIds: traceIds,
+ },
+ name: QueueJobs.TraceDelete,
+ });
+
+ return { message: "Traces deleted successfully" };
+ },
+ }),
});