🪢 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
perf: use trace identifier stream to batch delete traces (#7081)
Max Deichmann094a52379576
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex c448395971..a589305f80 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -435,7 +435,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {)SELECT ${sqlSelect}-- FINAL is used for non default ordering and count.- FROM traces t ${["metrics", "rows"].includes(select) && defaultOrder ? "" : "FINAL"}+ FROM traces t ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "" : "FINAL"}${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats os on os.project_id = t.project_id and os.trace_id = t.id` : ""}${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}WHERE t.project_id = {projectId: String}@@ -444,7 +444,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {${chOrderBy}-- This is used for metrics and row queries. Count has only one result.-- This is only used for default ordering. Otherwise, we use final.- ${["metrics", "rows"].includes(select) && defaultOrder ? "LIMIT 1 BY id, project_id" : ""}+ ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "LIMIT 1 BY id, project_id" : ""}${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;@@ -560,10 +560,27 @@ export const getTraceIdentifiers = async (props: {page?: number;clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;}) => {+ const {+ projectId,+ filter,+ searchQuery,+ searchType,+ orderBy,+ limit,+ page,+ clickhouseConfigs,+ } = props;const identifiers = await getTracesTableGeneric({select: "identifiers",tags: { kind: "list" },- ...props,+ projectId,+ filter,+ searchQuery,+ searchType,+ orderBy,+ limit,+ page,+ clickhouseConfigs,});return identifiers.map((row) => ({diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex ac06e65cd7..d3df5f55e5 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -1,9 +1,12 @@import { BatchExportTableName } from "@langfuse/shared";import { BatchActionType } from "@langfuse/shared";import { expect, describe, it, vi } from "vitest";-import { randomUUID } from "crypto";+import { v4 as uuidv4 } from "uuid";import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJob";-import { getDatabaseReadStream } from "../features/database-read-stream/getDatabaseReadStream";+import {+ getDatabaseReadStream,+ getTraceIdentifierStream,+} from "../features/database-read-stream/getDatabaseReadStream";import {createOrgProjectAndApiKey,createTraceScore,@@ -12,9 +15,10 @@ import {createTracesCh,getQueue,getScoresByIds,- logger,+ queryClickhouse,QueueJobs,QueueName,+ logger,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { Decimal } from "decimal.js";@@ -28,7 +32,7 @@ describe("select all test suite", () => {const traces = Array.from({ length: 2500 }).map(() =>createTrace({project_id: projectId,- id: randomUUID(),+ id: uuidv4(),timestamp: new Date("2024-01-01").getTime(),}),);@@ -61,8 +65,31 @@ describe("select all test suite", () => {const remainingRows: any[] = [];for await (const chunk of stream) {- remainingRows.push(chunk);+ remainingRows.push({+ id: chunk.id,+ timestamp: chunk.timestamp,+ projectId: chunk.projectId,+ });+ }++ const ideStream = await getTraceIdentifierStream({+ projectId: projectId,+ cutoffCreatedAt: new Date("2024-01-02"),+ filter: [],+ orderBy: { column: "timestamp", order: "DESC" },+ exportLimit: 1000,+ });++ const remainingRows2: any[] = [];+ for await (const chunk of ideStream) {+ remainingRows2.push({+ id: chunk.id,+ timestamp: chunk.timestamp,+ projectId: chunk.projectId,+ });}++ expect(remainingRows2).toHaveLength(0);expect(remainingRows).toHaveLength(0);});@@ -72,13 +99,13 @@ describe("select all test suite", () => {const traces = [createTrace({project_id: projectId,- id: randomUUID(),+ id: uuidv4(),user_id: "user1",timestamp: new Date("2024-01-01").getTime(),}),createTrace({project_id: projectId,- id: randomUUID(),+ id: uuidv4(),user_id: "user2",timestamp: new Date("2024-01-01").getTime(),}),@@ -134,7 +161,7 @@ describe("select all test suite", () => {// Whenawait handleBatchActionJob({- id: randomUUID(),+ id: uuidv4(),timestamp: new Date(),name: QueueJobs.BatchActionProcessingJob as const,payload: {@@ -162,7 +189,7 @@ describe("select all test suite", () => {const { projectId } = await createOrgProjectAndApiKey();- const traceId1 = randomUUID();+ const traceId1 = uuidv4();const traces = [createTrace({project_id: projectId,@@ -172,7 +199,7 @@ describe("select all test suite", () => {}),createTrace({project_id: projectId,- id: randomUUID(),+ id: uuidv4(),user_id: "user2",timestamp: new Date().getTime(),}),@@ -180,7 +207,7 @@ describe("select all test suite", () => {await createTracesCh(traces);- const templateId = randomUUID();+ const templateId = uuidv4();await prisma.evalTemplate.create({data: {@@ -199,7 +226,7 @@ describe("select all test suite", () => {},});- const configId = randomUUID();+ const configId = uuidv4();await prisma.jobConfiguration.create({data: {id: configId,@@ -223,7 +250,7 @@ describe("select all test suite", () => {});const payload = {- id: randomUUID(),+ id: uuidv4(),timestamp: new Date(),name: QueueJobs.BatchActionProcessingJob as const,payload: {@@ -279,8 +306,8 @@ describe("select all test suite", () => {it("should create eval jobs for historic datasets", async () => {const { projectId } = await createOrgProjectAndApiKey();- const traceId1 = randomUUID();- const traceId2 = randomUUID();+ const traceId1 = uuidv4();+ const traceId2 = uuidv4();const traces = [createTrace({@@ -299,10 +326,10 @@ describe("select all test suite", () => {await createTracesCh(traces);- const datasetName = randomUUID();+ const datasetName = uuidv4();const dataset = await prisma.dataset.create({data: {- id: randomUUID(),+ id: uuidv4(),projectId,name: datasetName,},@@ -310,7 +337,7 @@ describe("select all test suite", () => {const datasetItem1 = await prisma.datasetItem.create({data: {- id: randomUUID(),+ id: uuidv4(),datasetId: dataset.id,input: "Hello, world!",projectId,@@ -319,14 +346,14 @@ describe("select all test suite", () => {const datasetItem2 = await prisma.datasetItem.create({data: {- id: randomUUID(),+ id: uuidv4(),datasetId: dataset.id,input: "Hello, world!",projectId,},});- const runId = randomUUID();+ const runId = uuidv4();const datasetRun = await prisma.datasetRuns.create({data: {@@ -339,7 +366,7 @@ describe("select all test suite", () => {await prisma.datasetRunItems.create({data: {- id: randomUUID(),+ id: uuidv4(),datasetItemId: datasetItem1.id,projectId,traceId: traceId1,@@ -349,7 +376,7 @@ describe("select all test suite", () => {await prisma.datasetRunItems.create({data: {- id: randomUUID(),+ id: uuidv4(),datasetItemId: datasetItem2.id,projectId,traceId: traceId2,@@ -357,7 +384,7 @@ describe("select all test suite", () => {},});- const templateId = randomUUID();+ const templateId = uuidv4();await prisma.evalTemplate.create({data: {@@ -376,7 +403,7 @@ describe("select all test suite", () => {},});- const configId = randomUUID();+ const configId = uuidv4();await prisma.jobConfiguration.create({data: {id: configId,@@ -403,7 +430,7 @@ describe("select all test suite", () => {await queue?.obliterate({ force: true });const payload = {- id: randomUUID(),+ id: uuidv4(),timestamp: new Date(),name: QueueJobs.BatchActionProcessingJob as const,payload: {@@ -457,7 +484,7 @@ describe("select all test suite", () => {const { projectId } = await createOrgProjectAndApiKey();// Create a trace- const traceId = randomUUID();+ const traceId = uuidv4();await createTracesCh([createTrace({project_id: projectId,@@ -467,14 +494,14 @@ describe("select all test suite", () => {]);// Use a non-existent config ID- const nonExistentConfigId = randomUUID();+ const nonExistentConfigId = uuidv4();const queue = getQueue(QueueName.CreateEvalQueue);// Clear any existing jobsawait queue?.obliterate({ force: true });const payload = {- id: randomUUID(),+ id: uuidv4(),timestamp: new Date(),name: QueueJobs.BatchActionProcessingJob as const,payload: {diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex 20643f6231..6e4d07f08c 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -49,6 +49,9 @@ async function processActionChunk(processPostgresTraceDelete(projectId, chunkIds),processClickhouseTraceDelete(projectId, chunkIds),]);+ logger.info(+ `Deleted ${chunkIds.length} traces for project ${projectId}`,+ );break;case "trace-add-to-annotation-queue":@@ -139,14 +142,23 @@ export const handleBatchActionJob = async (throw new Error(`Target ID is required for create action`);}- const dbReadStream = await getDatabaseReadStream({- projectId: projectId,- cutoffCreatedAt: new Date(cutoffCreatedAt),- filter: convertDatesInFiltersFromStrings(query.filter ?? []),- orderBy: query.orderBy,- tableName: tableName as unknown as BatchExportTableName,- exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,- });+ const dbReadStream =+ actionId === "trace-delete"+ ? await getTraceIdentifierStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ orderBy: query.orderBy,+ exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,+ })+ : await getDatabaseReadStream({+ projectId: projectId,+ cutoffCreatedAt: new Date(cutoffCreatedAt),+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ orderBy: query.orderBy,+ tableName: tableName as unknown as BatchExportTableName,+ exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,+ });// Process stream in database-sized batches// 1. Read all records@@ -195,6 +207,7 @@ export const handleBatchActionJob = async (cutoffCreatedAt: new Date(cutoffCreatedAt),filter: convertDatesInFiltersFromStrings(query.filter ?? []),orderBy: query.orderBy,+ exportLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,}) // when reading from clickhouse, we only want to read the necessary identifiers.: await getDatabaseReadStream({projectId: projectId,@@ -262,7 +275,7 @@ export const handleBatchActionJob = async (}}logger.info(- `Batch action job {${count} elements} completed, projectId: ${batchActionJob.payload.projectId}, actionId: ${actionId}`,+ `Batch action job completed, projectId: ${batchActionJob.payload.projectId}, ${count} elements`,);}diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.tsindex d933f21c6b..6afa35d8c1 100644--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts@@ -490,7 +490,7 @@ export const getTraceIdentifierStream = async (props: {return new DatabaseReadStream<TraceIdentifiers>(async (pageSize: number, offset: number) => {- return await getTraceIdentifiers({+ const identifiers = await getTraceIdentifiers({projectId,filter: filter? [...filter, createdAtCutoffFilter]@@ -501,6 +501,7 @@ export const getTraceIdentifierStream = async (props: {page: Math.floor(offset / pageSize),clickhouseConfigs,});+ return identifiers;},env.BATCH_EXPORT_PAGE_SIZE,exportLimit,