Skip to content

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

fix: delete event files from s3 after retention period end (#5509)

Steffen Schmitz9bf5b829a746
diff --git a/packages/shared/src/server/repositories/eventLog.ts b/packages/shared/src/server/repositories/eventLog.ts
index 5e2e8ec51a..478802b682 100644
--- a/packages/shared/src/server/repositories/eventLog.ts
+++ b/packages/shared/src/server/repositories/eventLog.ts
@@ -4,6 +4,7 @@ import {
queryClickhouseStream,
} from "./clickhouse";
import { EventLogRecordReadType } from "./definitions";
+import { convertDateToClickhouseDateTime } from "../clickhouse/client";
export const getEventLogByProjectAndEntityId = async (
projectId: string,
@@ -45,6 +46,26 @@ export const getEventLogByProjectId = (
});
};
+export const getEventLogByProjectIdBeforeDate = (
+ projectId: string,
+ beforeDate: Date,
+): AsyncGenerator<EventLogRecordReadType> => {
+ const query = `
+ select *
+ from event_log
+ where project_id = {projectId: String}
+ and created_at <= {beforeDate: DateTime64(3)}
+ `;
+
+ return queryClickhouseStream<EventLogRecordReadType>({
+ query,
+ params: {
+ projectId,
+ beforeDate: convertDateToClickhouseDateTime(beforeDate),
+ },
+ });
+};
+
export const deleteEventLogByProjectId = async (
projectId: string,
): Promise<void> => {
@@ -62,3 +83,24 @@ export const deleteEventLogByProjectId = async (
},
});
};
+
+export const deleteEventLogByProjectIdBeforeDate = async (
+ projectId: string,
+ beforeDate: Date,
+): Promise<void> => {
+ const query = `
+ DELETE FROM event_log
+ WHERE project_id = {projectId: String}
+ AND created_at <= {beforeDate: DateTime64(3)};
+ `;
+ await commandClickhouse({
+ query: query,
+ params: {
+ projectId,
+ beforeDate: convertDateToClickhouseDateTime(beforeDate),
+ },
+ clickhouseConfigs: {
+ request_timeout: 120_000, // 2 minutes
+ },
+ });
+};
diff --git a/worker/src/__tests__/dataRetentionProcessing.test.ts b/worker/src/__tests__/dataRetentionProcessing.test.ts
index fe25894469..4e8b40ceb5 100644
--- a/worker/src/__tests__/dataRetentionProcessing.test.ts
+++ b/worker/src/__tests__/dataRetentionProcessing.test.ts
@@ -2,12 +2,15 @@ import { expect, it, describe, beforeAll } from "vitest";
import { env } from "../env";
import { randomUUID } from "crypto";
import {
+ clickhouseClient,
createObservation,
createObservationsCh,
createScore,
createScoresCh,
createTrace,
createTracesCh,
+ getClickhouseEntityType,
+ getEventLogByProjectAndEntityId,
getObservationById,
getScoreById,
getTraceById,
@@ -33,6 +36,162 @@ describe("DataRetentionProcessingJob", () => {
});
});
+ it("should NOT delete event files from cloud storage if after expiry cutoff", async () => {
+ // Setup
+ const baseId = randomUUID();
+ const fileName = `${baseId}.json`;
+ const fileType = "application/json";
+ const data = JSON.stringify({ hello: "world" });
+ const expiresInSeconds = 3600;
+ await storageService.uploadFile({
+ fileName,
+ fileType,
+ data,
+ expiresInSeconds,
+ });
+
+ await clickhouseClient().insert({
+ table: "event_log",
+ format: "JSONEachRow",
+ values: [
+ {
+ id: randomUUID(),
+ project_id: projectId,
+ entity_type: "trace",
+ entity_id: `${baseId}-trace`,
+ event_id: randomUUID(),
+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ bucket_path: fileName,
+ created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).getTime(), // 3 days in the past
+ updated_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).getTime(), // 3 days in the past
+ },
+ ],
+ });
+
+ // When
+ await handleDataRetentionProcessingJob({
+ data: { payload: { projectId, retention: 7 } }, // Delete after 7 days
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ expect(files.map((file) => file.file)).toContain(fileName);
+
+ const eventLogRecord = await getEventLogByProjectAndEntityId(
+ projectId,
+ "trace",
+ `${baseId}-trace`,
+ );
+ expect(eventLogRecord).toHaveLength(1);
+ });
+
+ it("should delete event files from cloud storage if expired", async () => {
+ // Setup
+ const baseId = randomUUID();
+ const fileName = `${baseId}.json`;
+ const fileType = "application/json";
+ const data = JSON.stringify({ hello: "world" });
+ const expiresInSeconds = 3600;
+ await storageService.uploadFile({
+ fileName,
+ fileType,
+ data,
+ expiresInSeconds,
+ });
+
+ await clickhouseClient().insert({
+ table: "event_log",
+ format: "JSONEachRow",
+ values: [
+ {
+ id: randomUUID(),
+ project_id: projectId,
+ entity_type: "trace",
+ entity_id: `${baseId}-trace`,
+ event_id: randomUUID(),
+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ bucket_path: fileName,
+ created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).getTime(), // 30 days in the past
+ updated_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30).getTime(), // 30 days in the past
+ },
+ ],
+ });
+
+ // When
+ await handleDataRetentionProcessingJob({
+ data: { payload: { projectId, retention: 7 } }, // Delete after 7 days
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ expect(files.map((file) => file.file)).not.toContain(fileName);
+
+ const eventLogRecord = await getEventLogByProjectAndEntityId(
+ projectId,
+ "trace",
+ `${baseId}-trace`,
+ );
+ expect(eventLogRecord).toHaveLength(0);
+ });
+
+ it("should NOT delete media files from cloud storage and database if after expiry cutoff", async () => {
+ // Setup
+ const fileName = `${randomUUID()}.txt`;
+ const fileType = "text/plain";
+ const data = "Hello, world!";
+ const expiresInSeconds = 3600;
+ await storageService.uploadFile({
+ fileName,
+ fileType,
+ data,
+ expiresInSeconds,
+ });
+
+ const mediaId = randomUUID();
+ const traceId = randomUUID();
+ await prisma.media.create({
+ data: {
+ id: mediaId,
+ sha256Hash: randomUUID(),
+ projectId,
+ createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), // 3 days in the past
+ bucketPath: fileName,
+ bucketName: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ contentType: fileType,
+ contentLength: 0,
+ },
+ });
+
+ await prisma.traceMedia.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ traceId,
+ mediaId,
+ field: "test",
+ },
+ });
+
+ // When
+ await handleDataRetentionProcessingJob({
+ data: { payload: { projectId, retention: 7 } }, // Delete after 7 days
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ expect(files.map((file) => file.file)).toContain(fileName);
+
+ const media = await prisma.media.findUnique({
+ where: { id: mediaId },
+ });
+ expect(media).toBeDefined();
+
+ const traceMedia = await prisma.traceMedia.findFirst({
+ where: { mediaId },
+ });
+ expect(traceMedia).toBeDefined();
+ });
+
it("should delete media files from cloud storage and database if expired", async () => {
// Setup
const fileName = `${randomUUID()}.txt`;
diff --git a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts
index b07809ff5e..28dd84d877 100644
--- a/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts
+++ b/worker/src/ee/dataRetention/handleDataRetentionProcessingJob.ts
@@ -1,7 +1,9 @@
import {
+ deleteEventLogByProjectIdBeforeDate,
deleteObservationsOlderThanDays,
deleteScoresOlderThanDays,
deleteTracesOlderThanDays,
+ getEventLogByProjectIdBeforeDate,
logger,
StorageService,
StorageServiceFactory,
@@ -26,9 +28,27 @@ const getS3MediaStorageClient = (bucketName: string): StorageService => {
return s3MediaStorageClient;
};
+let s3EventStorageClient: StorageService;
+
+const getS3EventStorageClient = (bucketName: string): StorageService => {
+ if (!s3EventStorageClient) {
+ s3EventStorageClient = StorageServiceFactory.getInstance({
+ bucketName,
+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,
+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
+ }
+ return s3EventStorageClient;
+};
+
export const handleDataRetentionProcessingJob = async (job: Job) => {
const { projectId, retention } = job.data.payload;
+ const cutoffDate = new Date(Date.now() - retention * 24 * 60 * 60 * 1000);
+
// Delete media files if bucket is configured
if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {
logger.info(
@@ -45,7 +65,7 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {
where: {
projectId,
createdAt: {
- lte: new Date(Date.now() - retention * 24 * 60 * 60 * 1000),
+ lte: cutoffDate,
},
},
});
@@ -70,6 +90,26 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {
);
}
+ // Remove event files from S3
+ const eventLogStream = getEventLogByProjectIdBeforeDate(
+ projectId,
+ cutoffDate,
+ );
+ let eventLogPaths: string[] = [];
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ for await (const eventLog of eventLogStream) {
+ eventLogPaths.push(eventLog.bucket_path);
+ if (eventLogPaths.length > 500) {
+ // Delete the current batch and reset the list
+ await eventStorageClient.deleteFiles(eventLogPaths);
+ eventLogPaths = [];
+ }
+ }
+ // Delete any remaining files
+ await eventStorageClient.deleteFiles(eventLogPaths);
+
// Delete ClickHouse (TTL / Delete Queries)
logger.info(
`[Data Retention] Deleting ClickHouse data older than ${retention} days for project ${projectId}`,
@@ -78,6 +118,7 @@ export const handleDataRetentionProcessingJob = async (job: Job) => {
deleteTracesOlderThanDays(projectId, retention),
deleteObservationsOlderThanDays(projectId, retention),
deleteScoresOlderThanDays(projectId, retention),
+ deleteEventLogByProjectIdBeforeDate(projectId, cutoffDate),
]);
logger.info(
`[Data Retention] Deleted ClickHouse data older than ${retention} days for project ${projectId}`,