Skip to content

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

feat: an alternative to retention queue: batch-oriented periodic jobs. (#11644)

Valery Meleshkincbd66df3156c
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index fdd82e192b..73cd32a21b 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -80,6 +80,8 @@ export * from "./redis/dlqRetryQueue";
export * from "./redis/entityChangeQueue";
export * from "./redis/eventPropagationQueue";
export * from "./redis/batchProjectCleanerQueue";
+export * from "./redis/batchDataRetentionCleanerQueue";
+export * from "./redis/mediaRetentionCleanerQueue";
export * from "./redis/otelProjectTracking";
export * from "./redis/s3SlowdownTracking";
export * from "./auth/types";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 1c2d159a56..125c6bd7ae 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -212,6 +212,29 @@ export type BatchProjectCleanerJobType = z.infer<
typeof BatchProjectCleanerJobSchema
>;
+// Tables for batch data retention cleaning (ClickHouse only, no dataset_run_items)
+export const BATCH_DATA_RETENTION_TABLES = [
+ "traces",
+ "observations",
+ "scores",
+ "events",
+] as const;
+
+export type BatchDataRetentionTable =
+ (typeof BATCH_DATA_RETENTION_TABLES)[number];
+
+export const BatchDataRetentionCleanerJobSchema = z.object({
+ table: z.enum(BATCH_DATA_RETENTION_TABLES),
+});
+export type BatchDataRetentionCleanerJobType = z.infer<
+ typeof BatchDataRetentionCleanerJobSchema
+>;
+
+export const MediaRetentionCleanerJobSchema = z.object({});
+export type MediaRetentionCleanerJobType = z.infer<
+ typeof MediaRetentionCleanerJobSchema
+>;
+
export const NotificationEventSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("COMMENT_MENTION"),
@@ -328,6 +351,8 @@ export enum QueueName {
EventPropagationQueue = "event-propagation-queue",
NotificationQueue = "notification-queue",
BatchProjectCleanerQueue = "batch-project-cleaner-queue",
+ BatchDataRetentionCleanerQueue = "batch-data-retention-cleaner-queue",
+ MediaRetentionCleanerQueue = "media-retention-cleaner-queue",
}
export enum QueueJobs {
@@ -364,6 +389,8 @@ export enum QueueJobs {
EventPropagationJob = "event-propagation-job",
NotificationJob = "notification-job",
BatchProjectCleanerJob = "batch-project-cleaner-job",
+ BatchDataRetentionCleanerJob = "batch-data-retention-cleaner-job",
+ MediaRetentionCleanerJob = "media-retention-cleaner-job",
}
export type TQueueJobTypes = {
diff --git a/packages/shared/src/server/redis/batchDataRetentionCleanerQueue.ts b/packages/shared/src/server/redis/batchDataRetentionCleanerQueue.ts
new file mode 100644
index 0000000000..e58f6d9b9f
--- /dev/null
+++ b/packages/shared/src/server/redis/batchDataRetentionCleanerQueue.ts
@@ -0,0 +1,36 @@
+import { Queue } from "bullmq";
+import { QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class BatchDataRetentionCleanerQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (BatchDataRetentionCleanerQueue.instance) {
+ return BatchDataRetentionCleanerQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ BatchDataRetentionCleanerQueue.instance = newRedis
+ ? new Queue(QueueName.BatchDataRetentionCleanerQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.BatchDataRetentionCleanerQueue),
+ })
+ : null;
+
+ BatchDataRetentionCleanerQueue.instance?.on("error", (err) => {
+ logger.error("BatchDataRetentionCleanerQueue error", err);
+ });
+
+ return BatchDataRetentionCleanerQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 1e4b7876a4..8491381859 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -30,6 +30,8 @@ import { DatasetDeleteQueue } from "./datasetDelete";
import { EventPropagationQueue } from "./eventPropagationQueue";
import { NotificationQueue } from "./notificationQueue";
import { BatchProjectCleanerQueue } from "./batchProjectCleanerQueue";
+import { BatchDataRetentionCleanerQueue } from "./batchDataRetentionCleanerQueue";
+import { MediaRetentionCleanerQueue } from "./mediaRetentionCleanerQueue";
// IngestionQueue, OtelIngestionQueue, and TraceUpsert are sharded and require a sharding key
// Use IngestionQueue.getInstance({ shardName: queueName }) or TraceUpsertQueue.getInstance({ shardName: queueName }) directly instead
@@ -102,6 +104,10 @@ export function getQueue(
return NotificationQueue.getInstance();
case QueueName.BatchProjectCleanerQueue:
return BatchProjectCleanerQueue.getInstance();
+ case QueueName.BatchDataRetentionCleanerQueue:
+ return BatchDataRetentionCleanerQueue.getInstance();
+ case QueueName.MediaRetentionCleanerQueue:
+ return MediaRetentionCleanerQueue.getInstance();
default: {
const _exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/packages/shared/src/server/redis/mediaRetentionCleanerQueue.ts b/packages/shared/src/server/redis/mediaRetentionCleanerQueue.ts
new file mode 100644
index 0000000000..7cd15aaa7b
--- /dev/null
+++ b/packages/shared/src/server/redis/mediaRetentionCleanerQueue.ts
@@ -0,0 +1,36 @@
+import { Queue } from "bullmq";
+import { QueueName } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+
+export class MediaRetentionCleanerQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (MediaRetentionCleanerQueue.instance) {
+ return MediaRetentionCleanerQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ MediaRetentionCleanerQueue.instance = newRedis
+ ? new Queue(QueueName.MediaRetentionCleanerQueue, {
+ connection: newRedis,
+ prefix: getQueuePrefix(QueueName.MediaRetentionCleanerQueue),
+ })
+ : null;
+
+ MediaRetentionCleanerQueue.instance?.on("error", (err) => {
+ logger.error("MediaRetentionCleanerQueue error", err);
+ });
+
+ return MediaRetentionCleanerQueue.instance;
+ }
+}
diff --git a/worker/src/__tests__/batchDataRetentionCleaner.test.ts b/worker/src/__tests__/batchDataRetentionCleaner.test.ts
new file mode 100644
index 0000000000..7f7de781c4
--- /dev/null
+++ b/worker/src/__tests__/batchDataRetentionCleaner.test.ts
@@ -0,0 +1,302 @@
+import { expect, describe, it } from "vitest";
+import { randomUUID } from "crypto";
+import { BatchDataRetentionCleaner } from "../features/batch-data-retention-cleaner";
+import {
+ createOrgProjectAndApiKey,
+ createTracesCh,
+ createTrace,
+ createObservationsCh,
+ createObservation,
+ createScoresCh,
+ createTraceScore,
+ queryClickhouse,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+
+async function getClickhouseCount(
+ table: string,
+ projectId: string,
+): Promise<number> {
+ const result = await queryClickhouse<{ count: number }>({
+ query: `SELECT count() as count FROM ${table} FINAL WHERE project_id = {projectId: String}`,
+ params: { projectId },
+ });
+ return Number(result[0]?.count ?? 0);
+}
+
+describe("BatchDataRetentionCleaner", () => {
+ describe("processBatch - traces", () => {
+ const TABLE = "traces" as const;
+
+ it("should delete traces older than project retention", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert trace older than retention (10 days old)
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: tenDaysAgo,
+ }),
+ ]);
+
+ // Verify trace exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify trace was deleted (10 days > 7 days retention)
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(0);
+ });
+
+ it("should NOT delete traces within retention period", async () => {
+ const now = Date.now();
+ const fiveDaysAgo = now - 5 * 24 * 60 * 60 * 1000;
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert trace within retention (5 days old)
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: fiveDaysAgo,
+ }),
+ ]);
+
+ // Verify trace exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify trace was NOT deleted (5 days < 7 days retention)
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+ });
+
+ it("should handle projects with different retention times independently", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+ const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000;
+
+ // Project A: 7-day retention (10-day-old data should be deleted)
+ const { projectId: projectA } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectA },
+ data: { retentionDays: 7 },
+ });
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectA,
+ timestamp: tenDaysAgo,
+ }),
+ createTrace({
+ id: randomUUID(),
+ project_id: projectA,
+ timestamp: now,
+ }),
+ ]);
+
+ // Project B: 30-day retention (10-day-old data should be kept)
+ const { projectId: projectB } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectB },
+ data: { retentionDays: 30 },
+ });
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectB,
+ timestamp: tenDaysAgo,
+ }),
+ createTrace({
+ id: randomUUID(),
+ project_id: projectB,
+ timestamp: thirtyDaysAgo,
+ }),
+ ]);
+
+ // Verify both have data before deletion
+ expect(await getClickhouseCount(TABLE, projectA)).toBe(2);
+ expect(await getClickhouseCount(TABLE, projectB)).toBe(2);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Only now trace should remain in A
+ expect(await getClickhouseCount(TABLE, projectA)).toBe(1);
+ // Only tenDaysAgo trace should remain in B
+ expect(await getClickhouseCount(TABLE, projectB)).toBe(1);
+ });
+
+ it("should not affect projects with retention disabled (null)", async () => {
+ const now = Date.now();
+ const old = now - 100 * 24 * 60 * 60 * 1000;
+
+ // Create project without retention (null)
+ const { projectId } = await createOrgProjectAndApiKey();
+ // retentionDays is null by default
+
+ // Insert trace older than typical retention
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: old,
+ }),
+ ]);
+
+ // Verify trace exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify trace was NOT deleted (no retention policy)
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+ });
+
+ it("should not affect projects with retention set to 0", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+
+ // Create project with retentionDays = 0 (disabled)
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 0 },
+ });
+
+ // Insert trace older than typical retention
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: tenDaysAgo,
+ }),
+ ]);
+
+ // Verify trace exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify trace was NOT deleted (retention disabled)
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+ });
+
+ it("should not affect soft-deleted projects", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+
+ // Create soft-deleted project with retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: {
+ retentionDays: 7,
+ deletedAt: new Date(),
+ },
+ });
+
+ // Insert trace
+ await createTracesCh([
+ createTrace({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: tenDaysAgo,
+ }),
+ ]);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify trace was NOT deleted (project is soft-deleted, handled by BatchProjectCleaner)
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+ });
+ });
+
+ describe("processBatch - observations", () => {
+ const TABLE = "observations" as const;
+
+ it("should process observations correctly (uses start_time)", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert observation with old start_time
+ await createObservationsCh([
+ createObservation({
+ id: randomUUID(),
+ project_id: projectId,
+ start_time: tenDaysAgo,
+ }),
+ ]);
+
+ // Verify observation exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify observation was deleted
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(0);
+ });
+ });
+
+ describe("processBatch - scores", () => {
+ const TABLE = "scores" as const;
+
+ it("should process scores correctly (uses timestamp)", async () => {
+ const now = Date.now();
+ const tenDaysAgo = now - 10 * 24 * 60 * 60 * 1000;
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert score with old timestamp
+ await createScoresCh([
+ createTraceScore({
+ id: randomUUID(),
+ project_id: projectId,
+ timestamp: tenDaysAgo,
+ }),
+ ]);
+
+ // Verify score exists before deletion
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(1);
+
+ // Run processBatch
+ await BatchDataRetentionCleaner.processBatch(TABLE);
+
+ // Verify score was deleted
+ expect(await getClickhouseCount(TABLE, projectId)).toBe(0);
+ });
+ });
+});
diff --git a/worker/src/__tests__/mediaRetentionCleaner.test.ts b/worker/src/__tests__/mediaRetentionCleaner.test.ts
new file mode 100644
index 0000000000..53a1745344
--- /dev/null
+++ b/worker/src/__tests__/mediaRetentionCleaner.test.ts
@@ -0,0 +1,430 @@
+import { expect, describe, it, vi, beforeEach, afterEach } from "vitest";
+import { randomUUID } from "crypto";
+import {
+ createOrgProjectAndApiKey,
+ getS3MediaStorageClient,
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { MediaRetentionCleaner } from "../features/media-retention-cleaner";
+
+// Mock S3 and blob storage functions
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ getS3MediaStorageClient: vi.fn(),
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject: vi.fn(),
+ };
+});
+
+// Mock the env module to enable S3 bucket
+vi.mock("../../env", async () => {
+ const actual = await vi.importActual("../../env");
+ return {
+ env: {
+ ...(actual as { env: object }).env,
+ LANGFUSE_S3_MEDIA_UPLOAD_BUCKET: "test-bucket",
+ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG: "false",
+ },
+ };
+});
+
+const mockDeleteFiles = vi.fn().mockResolvedValue(undefined);
+const mockS3Client = { deleteFiles: mockDeleteFiles };
+
+async function createTestMedia(
+ projectId: string,
+ createdAt: Date,
+ id?: string,
+): Promise<{ id: string; bucketPath: string }> {
+ const mediaId = id ?? randomUUID();
+ const bucketPath = `projects/${projectId}/media/${mediaId}`;
+
+ await prisma.media.create({
+ data: {
+ id: mediaId,
+ projectId,
+ sha256Hash: `hash-${randomUUID()}`.padEnd(44, "0"),
+ bucketPath,
+ bucketName: "test-bucket",
+ contentType: "image/png",
+ contentLength: 1024,
+ createdAt,
+ },
+ });
+
+ return { id: mediaId, bucketPath };
+}
+
+async function getMediaCount(projectId: string): Promise<number> {
+ return prisma.media.count({
+ where: { projectId },
+ });
+}
+
+/**
+ * Helper to run processBatch until no more work exists for a specific project.
+ * This handles test isolation when other projects might have expired media.
+ */
+async function processUntilProjectComplete(
+ projectId: string,
+ maxIterations = 10,
+): Promise<void> {
+ for (let i = 0; i < maxIterations; i++) {
+ await MediaRetentionCleaner.processBatch();
+ const count = await getMediaCount(projectId);
+ if (count === 0) return;
+ }
+}
+
+/**
+ * Helper to drain any expired media from other test projects
+ * before running a test that expects specific behavior.
+ */
+async function drainExpiredMedia(maxIterations = 20): Promise<void> {
+ for (let i = 0; i < maxIterations; i++) {
+ const countBefore = mockDeleteFiles.mock.calls.length;
+ await MediaRetentionCleaner.processBatch();
+ const countAfter = mockDeleteFiles.mock.calls.length;
+ // No new deletions means no more work
+ if (countAfter === countBefore) return;
+ }
+}
+
+describe("MediaRetentionCleaner", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(getS3MediaStorageClient).mockReturnValue(mockS3Client as never);
+ });
+
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ describe("processBatch", () => {
+ it("should delete media files older than project retention", async () => {
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert media older than retention (10 days old)
+ const media = await createTestMedia(projectId, tenDaysAgo);
+
+ // Verify media exists before deletion
+ expect(await getMediaCount(projectId)).toBe(1);
+
+ // Run until our project's media is deleted
+ await processUntilProjectComplete(projectId);
+
+ // Verify media was deleted from PostgreSQL
+ expect(await getMediaCount(projectId)).toBe(0);
+
+ // Verify our media was deleted from S3
+ const allDeletedPaths = mockDeleteFiles.mock.calls.flatMap(
+ (call) => call[0] as string[],
+ );
+ expect(allDeletedPaths).toContain(media.bucketPath);
+ });
+
+ it("should NOT delete media within retention period", async () => {
+ const now = Date.now();
+ const fiveDaysAgo = new Date(now - 5 * 24 * 60 * 60 * 1000);
+
+ // Drain any expired media from other tests first
+ await drainExpiredMedia();
+ const callsBeforeTest = mockDeleteFiles.mock.calls.length;
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert media within retention (5 days old)
+ await createTestMedia(projectId, fiveDaysAgo);
+
+ // Verify media exists before deletion
+ expect(await getMediaCount(projectId)).toBe(1);
+
+ // Run processBatch - should find no work for this project
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify media was NOT deleted (5 days < 7 days retention)
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+
+ it("should handle projects with different retention times independently", async () => {
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Project A: 7-day retention (10-day-old data should be deleted)
+ const { projectId: projectA } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectA },
+ data: { retentionDays: 7 },
+ });
+ const mediaA = await createTestMedia(projectA, tenDaysAgo);
+
+ // Project B: 30-day retention (10-day-old data should be kept)
+ const { projectId: projectB } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectB },
+ data: { retentionDays: 30 },
+ });
+ await createTestMedia(projectB, tenDaysAgo);
+
+ // Verify both have media before deletion
+ expect(await getMediaCount(projectA)).toBe(1);
+ expect(await getMediaCount(projectB)).toBe(1);
+
+ // Run until projectA is processed (it has expired media)
+ await processUntilProjectComplete(projectA);
+
+ // Project A's media should be deleted (10 days > 7 days retention)
+ expect(await getMediaCount(projectA)).toBe(0);
+
+ // Project B's media should remain (10 days < 30 days retention)
+ expect(await getMediaCount(projectB)).toBe(1);
+
+ // Verify project A's media was deleted from S3
+ const allDeletedPaths = mockDeleteFiles.mock.calls.flatMap(
+ (call) => call[0] as string[],
+ );
+ expect(allDeletedPaths).toContain(mediaA.bucketPath);
+ });
+
+ it("should not affect projects with retention disabled (null)", async () => {
+ // Drain any expired media from other tests first
+ await drainExpiredMedia();
+
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create project without retention (null)
+ const { projectId } = await createOrgProjectAndApiKey();
+ // retentionDays is null by default
+
+ // Insert media older than typical retention
+ const media = await createTestMedia(projectId, tenDaysAgo);
+
+ // Verify media exists before deletion
+ expect(await getMediaCount(projectId)).toBe(1);
+
+ // Run processBatch
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify media was NOT deleted (no retention policy)
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+
+ it("should not affect projects with retention set to 0", async () => {
+ // Drain any expired media from other tests first
+ await drainExpiredMedia();
+
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create project with retentionDays = 0 (disabled)
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 0 },
+ });
+
+ // Insert media older than typical retention
+ await createTestMedia(projectId, tenDaysAgo);
+
+ // Verify media exists before deletion
+ expect(await getMediaCount(projectId)).toBe(1);
+
+ // Run processBatch
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify media was NOT deleted (retention disabled)
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+
+ it("should delete old media but keep new media", async () => {
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+ const twoDaysAgo = new Date(now - 2 * 24 * 60 * 60 * 1000);
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert mix of old and new media
+ const oldMedia = await createTestMedia(projectId, tenDaysAgo);
+ await createTestMedia(projectId, twoDaysAgo);
+
+ // Verify both media exist before deletion
+ expect(await getMediaCount(projectId)).toBe(2);
+
+ // Run until project is processed
+ await processUntilProjectComplete(projectId, 20);
+ // Note: Project won't reach count=0 since new media remains
+ // Let's just run once and check the result
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify only old media was deleted (count should be 1)
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+
+ it("should not affect soft-deleted projects", async () => {
+ // Drain any expired media from other tests first
+ await drainExpiredMedia();
+
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create soft-deleted project with retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: {
+ retentionDays: 7,
+ deletedAt: new Date(),
+ },
+ });
+
+ // Insert media
+ await createTestMedia(projectId, tenDaysAgo);
+
+ // Run processBatch
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify media was NOT deleted (project is soft-deleted, handled by BatchProjectCleaner)
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+
+ it("should delete from S3 before PostgreSQL", async () => {
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create project with retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert media
+ await createTestMedia(projectId, tenDaysAgo);
+
+ // Track order of operations by checking S3 call happens before media is deleted
+ let s3CalledWhileMediaExists = false;
+
+ mockDeleteFiles.mockImplementation(async (paths: string[]) => {
+ // Check if the paths belong to our test project
+ if (paths[0]?.includes(projectId)) {
+ // Check if media still exists in DB when S3 delete is called
+ const count = await prisma.media.count({ where: { projectId } });
+ if (count > 0) {
+ s3CalledWhileMediaExists = true;
+ }
+ }
+ });
+
+ // Run until our project is processed
+ await processUntilProjectComplete(projectId);
+
+ // Verify S3 was called while media still existed
+ expect(s3CalledWhileMediaExists).toBe(true);
+ // Verify media is now deleted
+ expect(await getMediaCount(projectId)).toBe(0);
+ });
+
+ it("should handle empty result when no expired media exists", async () => {
+ // Drain any expired media from other tests first
+ await drainExpiredMedia();
+
+ const now = Date.now();
+ const twoDaysAgo = new Date(now - 2 * 24 * 60 * 60 * 1000);
+
+ // Create project with 7-day retention
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+
+ // Insert only recent media (within retention)
+ await createTestMedia(projectId, twoDaysAgo);
+
+ // Run processBatch - should complete without error
+ await MediaRetentionCleaner.processBatch();
+
+ // Verify nothing was deleted
+ expect(await getMediaCount(projectId)).toBe(1);
+ });
+ });
+
+ describe("work-based prioritization", () => {
+ it("should process project with most expired items first", async () => {
+ const now = Date.now();
+ const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+
+ // Create two projects, both with 7-day retention
+ const { projectId: projectFew } = await createOrgProjectAndApiKey();
+ const { projectId: projectMany } = await createOrgProjectAndApiKey();
+
+ await prisma.project.update({
+ where: { id: projectFew },
+ data: { retentionDays: 7 },
+ });
+ await prisma.project.update({
+ where: { id: projectMany },
+ data: { retentionDays: 7 },
+ });
+
+ // Project with fewer items: 1 media
+ await createTestMedia(projectFew, tenDaysAgo);
+
+ // Project with more items: 3 media
+ await createTestMedia(projectMany, tenDaysAgo);
+ await createTestMedia(projectMany, tenDaysAgo);
+ await createTestMedia(projectMany, tenDaysAgo);
+
+ // Track which projects are processed
+ const processedProjects: string[] = [];
+ mockDeleteFiles.mockImplementation(async (paths: string[]) => {
+ const projectIdMatch = paths[0]?.match(/projects\/([^/]+)\//);
+ if (projectIdMatch) {
+ const pid = projectIdMatch[1];
+ if (!processedProjects.includes(pid)) {
+ processedProjects.push(pid);
+ }
+ }
+ });
+
+ // Run first processBatch - should process projectMany (most work) OR any other pending project
+ await MediaRetentionCleaner.processBatch();
+
+ // Keep running until both our projects are processed
+ while (
+ !processedProjects.includes(projectMany) ||
+ !processedProjects.includes(projectFew)
+ ) {
+ await MediaRetentionCleaner.processBatch();
+ if (processedProjects.length > 10) break; // Safety limit
+ }
+
+ // Verify projectMany was processed before projectFew
+ // (it has more expired items so should have higher priority)
+ const manyIndex = processedProjects.indexOf(projectMany);
+ const fewIndex = processedProjects.indexOf(projectFew);
+ expect(manyIndex).toBeLessThan(fewIndex);
+ });
+ });
+});
diff --git a/worker/src/app.ts b/worker/src/app.ts
index a799da0dec..dde2de044e 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -39,6 +39,9 @@ import {
EventPropagationQueue,
BatchProjectCleanerQueue,
BATCH_DELETION_TABLES,
+ BatchDataRetentionCleanerQueue,
+ MediaRetentionCleanerQueue,
+ BATCH_DATA_RETENTION_TABLES,
} from "@langfuse/shared/src/server";
import { env } from "./env";
import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
@@ -77,6 +80,8 @@ import { eventPropagationProcessor } from "./queues/eventPropagationQueue";
import { notificationQueueProcessor } from "./queues/notificationQueue";
import { MutationMonitor } from "./features/mutation-monitoring/mutationMonitor";
import { batchProjectCleanerProcessor } from "./queues/batchProjectCleanerQueue";
+import { batchDataRetentionCleanerProcessor } from "./queues/batchDataRetentionCleanerQueue";
+import { mediaRetentionCleanerProcessor } from "./queues/mediaRetentionCleanerQueue";
const app = express();
@@ -553,7 +558,7 @@ if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {
concurrency: 1, // only 1 job at a time per process.
limiter: {
max: 1,
- duration: env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS, // no more than 1 job at a time globally
+ duration: env.LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS, // no more than 1 job at a time globally
},
},
);
@@ -570,7 +575,7 @@ if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {
queue
.upsertJobScheduler(
`batch-project-cleaner-${table}`,
- { every: env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS },
+ { every: env.LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS },
{ name: QueueJobs.BatchProjectCleanerJob, data: { table } },
)
.catch((err) =>
@@ -580,6 +585,68 @@ if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {
}
}
+// Batch data retention cleaners for bulk deletion of expired ClickHouse data
+if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {
+ WorkerManager.register(
+ QueueName.BatchDataRetentionCleanerQueue,
+ batchDataRetentionCleanerProcessor,
+ {
+ concurrency: 1,
+ },
+ );
+
+ // Schedule repeatable jobs for each table
+ const dataRetentionQueue = BatchDataRetentionCleanerQueue.getInstance();
+ if (dataRetentionQueue) {
+ const tables = BATCH_DATA_RETENTION_TABLES.filter(
+ (t) =>
+ t !== "events" ||
+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true",
+ );
+ for (const table of tables) {
+ dataRetentionQueue
+ .upsertJobScheduler(
+ `batch-data-retention-cleaner-${table}`,
+ {
+ every: env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS,
+ },
+ {
+ name: QueueJobs.BatchDataRetentionCleanerJob,
+ data: { table },
+ },
+ )
+ .catch((err) =>
+ logger.error(
+ `Error scheduling batch-data-retention-cleaner-${table}`,
+ err,
+ ),
+ );
+ }
+ }
+
+ // Media retention cleaner for media files and blob storage
+ WorkerManager.register(
+ QueueName.MediaRetentionCleanerQueue,
+ mediaRetentionCleanerProcessor,
+ {
+ concurrency: 1,
+ },
+ );
+
+ const mediaQueue = MediaRetentionCleanerQueue.getInstance();
+ if (mediaQueue) {
+ mediaQueue
+ .upsertJobScheduler(
+ "media-retention-cleaner",
+ { every: env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS },
+ { name: QueueJobs.MediaRetentionCleanerJob, data: {} },
+ )
+ .catch((err) =>
+ logger.error("Error scheduling media-retention-cleaner", err),
+ );
+ }
+}
+
process.on("SIGINT", () => onShutdown("SIGINT"));
process.on("SIGTERM", () => onShutdown("SIGTERM"));
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 286c7d2546..792162c847 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -325,7 +325,7 @@ const EnvSchema = z.object({
LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED: z
.enum(["true", "false"])
.default("false"),
- LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS: z.coerce
+ LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS: z.coerce
.number()
.positive()
.default(3_600_000), // 1hr
@@ -338,6 +338,37 @@ const EnvSchema = z.object({
.positive()
.default(5_400_000), // 1.5 hours for DELETE operations
+ // Batch Data Retention Cleaner configuration (ClickHouse)
+ LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS: z.coerce
+ .number()
+ .positive()
+ .default(3_600_000), // 1 hour between runs
+ LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS: z.coerce
+ .number()
+ .positive()
+ .default(600_000), // 10 minutes between runs
+ LANGFUSE_BATCH_DATA_RETENTION_CLEANER_PROJECT_LIMIT: z.coerce
+ .number()
+ .positive()
+ .default(100), // Max projects per batch DELETE
+ LANGFUSE_BATCH_DATA_RETENTION_CLEANER_CHUNK_SIZE: z.coerce
+ .number()
+ .positive()
+ .default(100), // Chunk size for counting projects in ClickHouse
+ LANGFUSE_BATCH_DATA_RETENTION_CLEANER_DELETE_TIMEOUT_MS: z.coerce
+ .number()
+ .positive()
+ .default(5_400_000), // 1.5 hours for DELETE operations
+
+ // Media Retention Cleaner configuration (S3/PostgreSQL)
+ LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT: z.coerce
+ .number()
+ .positive()
+ .default(10_000), // Max items (media files) to process per batch
+
LANGFUSE_EXPERIMENT_BACKFILL_EXCLUDE_ATTRIBUTES_KEY: z
.enum(["true", "false"])
.default("false"),
diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.ts
new file mode 100644
index 0000000000..19b8299023
--- /dev/null
+++ b/worker/src/features/batch-data-retention-cleaner/index.ts
@@ -0,0 +1,268 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ commandClickhouse,
+ convertDateToClickhouseDateTime,
+ logger,
+ queryClickhouse,
+ recordGauge,
+ recordIncrement,
+ traceException,
+ type BatchDataRetentionTable,
+} from "@langfuse/shared/src/server";
+import { env } from "../../env";
+import { getRetentionCutoffDate } from "../utils";
+
+const METRIC_PREFIX = "langfuse.batch_data_retention_cleaner";
+
+export const TIMESTAMP_COLUMN_MAP: Record<BatchDataRetentionTable, string> = {
+ traces: "timestamp",
+ observations: "start_time",
+ scores: "timestamp",
+ events: "start_time",
+};
+
+interface ProjectWorkload {
+ projectId: string;
+ retentionDays: number;
+ cutoffDate: Date;
+ totalRowCount: number;
+}
+
+interface ProjectCount {
+ project_id: string;
+ count: number;
+}
+
+/**
+ * BatchDataRetentionCleaner handles bulk deletion of ClickHouse data based on
+ * project retention settings.
+ *
+ * Each invocation processes one table (traces, observations, scores, events).
+ * BullMQ handles scheduling. Normally, there shouldn't be more than one job
+ * for a given table's at a time.
+ *
+ * Flow:
+ * 1. Query PG for all projects with retentionDays > 0
+ * 2. Chunk project IDs and query CH for row counts per chunk
+ * 3. Combine results, sort by count DESC, select top N
+ * 4. Calculate cutoff dates based on each project's retentionDays
+ * 5. Execute single batch DELETE with OR conditions
+ */
+export class BatchDataRetentionCleaner {
+ /**
+ * Process a batch for data retention for a specific table.
+ */
+ public static async processBatch(
+ tableName: BatchDataRetentionTable,
+ ): Promise<void> {
+ const instanceName = `BatchDataRetentionCleaner(${tableName})`;
+ const timestampColumn = TIMESTAMP_COLUMN_MAP[tableName];
+
+ // Step 1: Get project workloads (chunked CH counts + PG retention config)
+ let workloads: ProjectWorkload[];
+ try {
+ workloads =
+ await BatchDataRetentionCleaner.getProjectWorkloads(tableName);
+ } catch (error) {
+ logger.error(`${instanceName}: Failed to query project workloads`, {
+ error,
+ });
+ traceException(error);
+ return;
+ }
+
+ if (workloads.length === 0) {
+ logger.info(
+ `${instanceName}: No projects with retention and data to delete`,
+ );
+ return;
+ }
+
+ recordGauge(`${METRIC_PREFIX}.pending_projects`, workloads.length, {
+ table: tableName,
+ });
+
+ logger.info(`${instanceName}: Processing ${workloads.length} projects`, {
+ projectIds: workloads.map((w) => w.projectId),
+ });
+
+ // Step 2: Execute single batch DELETE for all selected projects
+ try {
+ await BatchDataRetentionCleaner.executeBatchDelete(
+ tableName,
+ timestampColumn,
+ workloads,
+ );
+
+ // Record successful deletion metrics
+ recordIncrement(`${METRIC_PREFIX}.delete_successes`, 1, {
+ table: tableName,
+ });
+ recordIncrement(`${METRIC_PREFIX}.projects_processed`, workloads.length, {
+ table: tableName,
+ });
+ logger.info(`${instanceName}: Batch deletion completed`, {
+ table: tableName,
+ projectsProcessed: workloads.length,
+ });
+ } catch (error) {
+ logger.error(`${instanceName}: Batch DELETE failed`, { error });
+ traceException(error);
+
+ recordIncrement(`${METRIC_PREFIX}.delete_failures`, 1, {
+ table: tableName,
+ });
+
+ // Re-throw so BullMQ marks job as failed
+ throw error;
+ }
+ }
+
+ /**
+ * Get project workloads using chunked queries:
+ * 1. PostgreSQL: Get all projects with retention enabled
+ * 2. Chunk project IDs and query ClickHouse for each chunk
+ * 3. Combine results, sort by count, select top N
+ * 4. Calculate cutoffs for selected projects
+ *
+ * Chunking prevents running into CH query and param size limits.
+ */
+ private static async getProjectWorkloads(
+ tableName: BatchDataRetentionTable,
+ ): Promise<ProjectWorkload[]> {
+ // Step 1: Get all projects with retention from PostgreSQL
+ const projectsWithRetention = await prisma.project.findMany({
+ select: { id: true, retentionDays: true },
+ where: {
+ retentionDays: { gt: 0 },
+ deletedAt: null,
+ },
+ });
+
+ if (projectsWithRetention.length === 0) {
+ return [];
+ }
+
+ // Build retention map for later
+ const retentionMap = new Map(
+ projectsWithRetention.map((p) => [p.id, p.retentionDays!]),
+ );
+ const projectIds = projectsWithRetention.map((p) => p.id);
+
+ // Step 2: Chunk project IDs and query ClickHouse for each chunk
+ const chunkSize = env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_CHUNK_SIZE;
+ const chunks: string[][] = [];
+ for (let i = 0; i < projectIds.length; i += chunkSize) {
+ chunks.push(projectIds.slice(i, i + chunkSize));
+ }
+
+ // Query each chunk in parallel
+ const chunkResults = await Promise.all(
+ chunks.map((chunk) =>
+ BatchDataRetentionCleaner.countProjectsInChunk(tableName, chunk),
+ ),
+ );
+
+ // Step 3: Combine results, sort by count DESC, select top N
+ const allCounts = chunkResults.flat();
+ allCounts.sort((a, b) => b.count - a.count);
+ const topN = allCounts.slice(
+ 0,
+ env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_PROJECT_LIMIT,
+ );
+
+ if (topN.length === 0) {
+ return [];
+ }
+
+ // Step 4: Calculate cutoffs for selected projects
+ const now = new Date();
+ return topN.map((p) => {
+ const retentionDays = retentionMap.get(p.project_id)!;
+ return {
+ projectId: p.project_id,
+ retentionDays,
+ cutoffDate: getRetentionCutoffDate(retentionDays, now),
+ totalRowCount: p.count,
+ };
+ });
+ }
+
+ /**
+ * Count rows for a chunk of project IDs in ClickHouse.
+ */
+ private static async countProjectsInChunk(
+ tableName: BatchDataRetentionTable,
+ projectIds: string[],
+ ): Promise<ProjectCount[]> {
+ if (projectIds.length === 0) {
+ return [];
+ }
+
+ const query = `
+ SELECT project_id, count() as count
+ FROM ${tableName}
+ WHERE project_id IN ({projectIds: Array(String)})
+ GROUP BY project_id
+ `;
+
+ const result = await queryClickhouse<ProjectCount>({
+ query,
+ params: { projectIds },
+ tags: {
+ feature: "batch-data-retention-cleaner",
+ table: tableName,
+ operation: "count-chunk",
+ },
+ });
+
+ return result.map((r) => ({
+ project_id: r.project_id,
+ count: Number(r.count),
+ }));
+ }
+
+ /**
+ * Execute batch DELETE with OR conditions for selected projects.
+ * Single query deletes data for all selected projects at once.
+ */
+ private static async executeBatchDelete(
+ tableName: BatchDataRetentionTable,
+ timestampColumn: string,
+ workloads: ProjectWorkload[],
+ ): Promise<void> {
+ if (workloads.length === 0) {
+ return;
+ }
+
+ // Build OR conditions: (project_id = 'p1' AND ts < cutoff1) OR ...
+ const conditions = workloads
+ .map(
+ (_, i) =>
+ `(project_id = {projectId${i}: String} AND ${timestampColumn} < {cutoff${i}: DateTime64(3)})`,
+ )
+ .join(" OR ");
+
+ const params: Record<string, unknown> = {};
+ workloads.forEach((w, i) => {
+ params[`projectId${i}`] = w.projectId;
+ params[`cutoff${i}`] = convertDateToClickhouseDateTime(w.cutoffDate);
+ });
+
+ const query = `DELETE FROM ${tableName} WHERE ${conditions}`;
+
+ await commandClickhouse({
+ query,
+ params,
+ clickhouseConfigs: {
+ request_timeout:
+ env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_DELETE_TIMEOUT_MS,
+ },
+ tags: {
+ feature: "batch-data-retention-cleaner",
+ table: tableName,
+ operation: "delete",
+ },
+ });
+ }
+}
diff --git a/worker/src/features/media-retention-cleaner/index.ts b/worker/src/features/media-retention-cleaner/index.ts
new file mode 100644
index 0000000000..45a302cfb0
--- /dev/null
+++ b/worker/src/features/media-retention-cleaner/index.ts
@@ -0,0 +1,184 @@
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ getS3MediaStorageClient,
+ logger,
+ recordGauge,
+ recordIncrement,
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { env } from "../../env";
+import { getRetentionCutoffDate } from "../utils";
+
+const METRIC_PREFIX = "langfuse.media_retention_cleaner";
+
+interface ProjectWorkload {
+ projectId: string;
+ retentionDays: number;
+ cutoffDate: Date;
+ expiredMediaCount: number;
+}
+
+/**
+ * MediaRetentionCleaner handles periodic deletion of media files and blob storage
+ * entries based on project retention settings.
+ *
+ * Processes one project per iteration (most work first) for simplicity.
+ * Run frequently to process all projects over time.
+ */
+export class MediaRetentionCleaner {
+ public static async processBatch(): Promise<void> {
+ const instanceName = "MediaRetentionCleaner";
+
+ // Get the project with most expired media (single project per iteration)
+ let workload: ProjectWorkload | null;
+ try {
+ workload = await MediaRetentionCleaner.getTopProjectWorkload();
+ } catch (error) {
+ logger.error(`${instanceName}: Failed to query project workload`, {
+ error,
+ });
+ traceException(error);
+ recordIncrement(`${METRIC_PREFIX}.query_failures`, 1);
+ return;
+ }
+
+ if (!workload) {
+ logger.info(`${instanceName}: No expired media to clean up`);
+ return;
+ }
+
+ // Record gauge for observed work
+ recordGauge(`${METRIC_PREFIX}.pending_items`, workload.expiredMediaCount, {
+ projectId: workload.projectId,
+ });
+
+ logger.info(`${instanceName}: Processing project`, {
+ projectId: workload.projectId,
+ retentionDays: workload.retentionDays,
+ expiredMediaCount: workload.expiredMediaCount,
+ });
+
+ try {
+ await MediaRetentionCleaner.processProject(workload);
+ recordIncrement(`${METRIC_PREFIX}.projects_processed`, 1);
+ } catch (error) {
+ logger.error(`${instanceName}: Failed to process project`, {
+ projectId: workload.projectId,
+ retentionDays: workload.retentionDays,
+ error,
+ });
+ traceException(error);
+ recordIncrement(`${METRIC_PREFIX}.project_failures`, 1);
+ throw error;
+ }
+ }
+
+ /**
+ * Get the project with the most expired media (single query via Prisma).
+ * Returns null if no projects have expired media.
+ */
+ private static async getTopProjectWorkload(): Promise<ProjectWorkload | null> {
+ const now = new Date();
+
+ // Single query: join projects with media, filter by retention cutoff, order by count, limit 1
+ // Using raw SQL for the complex per-project cutoff logic
+ const result = await prisma.$queryRaw<
+ Array<{
+ project_id: string;
+ retention_days: number;
+ expired_count: bigint;
+ }>
+ >`
+ SELECT
+ p.id as project_id,
+ p.retention_days,
+ COUNT(m.id) as expired_count
+ FROM projects p
+ INNER JOIN media m ON m.project_id = p.id
+ WHERE p.retention_days > 0
+ AND p.deleted_at IS NULL
+ AND m.created_at <= NOW() - (p.retention_days || ' days')::interval
+ GROUP BY p.id, p.retention_days
+ ORDER BY expired_count DESC
+ LIMIT 1
+ `;
+
+ if (result.length === 0) {
+ return null;
+ }
+
+ const row = result[0];
+ return {
+ projectId: row.project_id,
+ retentionDays: row.retention_days,
+ cutoffDate: getRetentionCutoffDate(row.retention_days, now),
+ expiredMediaCount: Number(row.expired_count),
+ };
+ }
+
+ private static async processProject(
+ workload: ProjectWorkload,
+ ): Promise<void> {
+ // Delete media files (S3 + PostgreSQL)
+ if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {
+ await MediaRetentionCleaner.deleteExpiredMedia(
+ workload,
+ env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ );
+ }
+
+ // Delete blob storage entries (S3 + ClickHouse soft delete)
+ if (env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG === "true") {
+ await removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ workload.projectId,
+ workload.cutoffDate,
+ );
+ }
+
+ logger.info("MediaRetentionCleaner: Project processed", {
+ projectId: workload.projectId,
+ retentionDays: workload.retentionDays,
+ expiredMediaCount: workload.expiredMediaCount,
+ });
+ }
+
+ private static async deleteExpiredMedia(
+ workload: ProjectWorkload,
+ bucket: string,
+ ): Promise<void> {
+ const mediaFiles = await prisma.media.findMany({
+ select: { id: true, bucketPath: true },
+ where: {
+ projectId: workload.projectId,
+ createdAt: { lte: workload.cutoffDate },
+ },
+ });
+
+ if (mediaFiles.length === 0) {
+ return;
+ }
+
+ // Delete from S3 first
+ const mediaStorageClient = getS3MediaStorageClient(bucket);
+ await mediaStorageClient.deleteFiles(mediaFiles.map((f) => f.bucketPath));
+
+ // Delete from PostgreSQL (cascades to traceMedia/observationMedia)
+ await prisma.media.deleteMany({
+ where: {
+ id: { in: mediaFiles.map((f) => f.id) },
+ projectId: workload.projectId,
+ },
+ });
+
+ // Record successful deletion metrics
+ recordIncrement(`${METRIC_PREFIX}.files_deleted`, mediaFiles.length, {
+ projectId: workload.projectId,
+ });
+
+ logger.info("MediaRetentionCleaner: Media files deleted", {
+ projectId: workload.projectId,
+ count: mediaFiles.length,
+ });
+ }
+}
diff --git a/worker/src/features/utils/utilities.ts b/worker/src/features/utils/utilities.ts
index fbe2d1b20a..87d277caf2 100644
--- a/worker/src/features/utils/utilities.ts
+++ b/worker/src/features/utils/utilities.ts
@@ -48,3 +48,16 @@ export function createW3CTraceId(seed?: string): string {
return crypto.randomBytes(16).toString("hex"); // already 32 chars
}
}
+
+const MS_PER_DAY = 24 * 60 * 60 * 1000;
+
+/**
+ * Calculate the retention cutoff date for a given number of retention days.
+ * Returns a Date representing the timestamp before which data should be deleted.
+ */
+export const getRetentionCutoffDate = (
+ retentionDays: number,
+ referenceDate: Date = new Date(),
+): Date => {
+ return new Date(referenceDate.getTime() - retentionDays * MS_PER_DAY);
+};
diff --git a/worker/src/queues/batchDataRetentionCleanerQueue.ts b/worker/src/queues/batchDataRetentionCleanerQueue.ts
new file mode 100644
index 0000000000..980aa3bf6e
--- /dev/null
+++ b/worker/src/queues/batchDataRetentionCleanerQueue.ts
@@ -0,0 +1,34 @@
+import { Processor } from "bullmq";
+import {
+ logger,
+ QueueJobs,
+ BatchDataRetentionCleanerJobType,
+ BatchDataRetentionTable,
+ BATCH_DATA_RETENTION_TABLES,
+} from "@langfuse/shared/src/server";
+import { BatchDataRetentionCleaner } from "../features/batch-data-retention-cleaner";
+
+export const batchDataRetentionCleanerProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.BatchDataRetentionCleanerJob) {
+ const { table } = job.data as BatchDataRetentionCleanerJobType;
+ if (BATCH_DATA_RETENTION_TABLES.indexOf(table) === -1) {
+ logger.error(
+ `Invalid table name for BatchDataRetentionCleaner: ${table}`,
+ );
+ return;
+ }
+
+ logger.info(`Executing BatchDataRetentionCleaner for ${table}`);
+ try {
+ await BatchDataRetentionCleaner.processBatch(
+ table as BatchDataRetentionTable,
+ );
+ } catch (error) {
+ logger.error(
+ `Error executing BatchDataRetentionCleaner for ${table}`,
+ error,
+ );
+ throw error;
+ }
+ }
+};
diff --git a/worker/src/queues/batchProjectCleanerQueue.ts b/worker/src/queues/batchProjectCleanerQueue.ts
index da2c640248..8a3b5ac03f 100644
--- a/worker/src/queues/batchProjectCleanerQueue.ts
+++ b/worker/src/queues/batchProjectCleanerQueue.ts
@@ -3,6 +3,7 @@ import {
logger,
QueueJobs,
BatchProjectCleanerJobType,
+ BATCH_DELETION_TABLES,
} from "@langfuse/shared/src/server";
import {
BatchProjectCleaner,
@@ -12,6 +13,10 @@ import {
export const batchProjectCleanerProcessor: Processor = async (job) => {
if (job.name === QueueJobs.BatchProjectCleanerJob) {
const { table } = job.data as BatchProjectCleanerJobType;
+ if (BATCH_DELETION_TABLES.indexOf(table) === -1) {
+ logger.error(`Invalid table name for BatchProjectCleaner: ${table}`);
+ return;
+ }
logger.info(`Executing BatchProjectCleaner for ${table}`);
try {
await BatchProjectCleaner.processBatch(table as BatchDeletionTable);
diff --git a/worker/src/queues/mediaRetentionCleanerQueue.ts b/worker/src/queues/mediaRetentionCleanerQueue.ts
new file mode 100644
index 0000000000..8f226deabc
--- /dev/null
+++ b/worker/src/queues/mediaRetentionCleanerQueue.ts
@@ -0,0 +1,15 @@
+import { Processor } from "bullmq";
+import { logger, QueueJobs } from "@langfuse/shared/src/server";
+import { MediaRetentionCleaner } from "../features/media-retention-cleaner";
+
+export const mediaRetentionCleanerProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.MediaRetentionCleanerJob) {
+ logger.info("Executing MediaRetentionCleaner");
+ try {
+ await MediaRetentionCleaner.processBatch();
+ } catch (error) {
+ logger.error("Error executing MediaRetentionCleaner", error);
+ throw error;
+ }
+ }
+};