🪢 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
fix: reinstanting RedisLock and repeatable job. Away with BullMQ. (#11782)
Valery Meleshkinefc0747232a3
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 53bc1b8ac5..66d10c7ecc 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -80,9 +80,6 @@ export * from "./redis/experimentCreateQueue";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.tsindex 8397c9e278..51c9286ce8 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -205,44 +205,6 @@ export const DeadLetterRetryQueueEventSchema = z.object({timestamp: z.date(),});-export const BATCH_DELETION_TABLES = [- "traces",- "observations",- "scores",- "events",- "dataset_run_items_rmt",-] as const;--export const BatchProjectCleanerJobSchema = z.object({- table: z.enum(BATCH_DELETION_TABLES),-});-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"),@@ -362,9 +324,6 @@ export enum QueueName {EntityChangeQueue = "entity-change-queue",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 {@@ -401,9 +360,6 @@ export enum QueueJobs {EntityChangeJob = "entity-change-job",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.tsdeleted file mode 100644index e58f6d9b9f..0000000000--- a/packages/shared/src/server/redis/batchDataRetentionCleanerQueue.ts+++ /dev/null@@ -1,36 +0,0 @@-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/batchProjectCleanerQueue.ts b/packages/shared/src/server/redis/batchProjectCleanerQueue.tsdeleted file mode 100644index 17b6950cee..0000000000--- a/packages/shared/src/server/redis/batchProjectCleanerQueue.ts+++ /dev/null@@ -1,36 +0,0 @@-import { Queue } from "bullmq";-import { QueueName } from "../queues";-import {- createNewRedisInstance,- redisQueueRetryOptions,- getQueuePrefix,-} from "./redis";-import { logger } from "../logger";--export class BatchProjectCleanerQueue {- private static instance: Queue | null = null;-- public static getInstance(): Queue | null {- if (BatchProjectCleanerQueue.instance) {- return BatchProjectCleanerQueue.instance;- }-- const newRedis = createNewRedisInstance({- enableOfflineQueue: false,- ...redisQueueRetryOptions,- });-- BatchProjectCleanerQueue.instance = newRedis- ? new Queue(QueueName.BatchProjectCleanerQueue, {- connection: newRedis,- prefix: getQueuePrefix(QueueName.BatchProjectCleanerQueue),- })- : null;-- BatchProjectCleanerQueue.instance?.on("error", (err) => {- logger.error("BatchProjectCleanerQueue error", err);- });-- return BatchProjectCleanerQueue.instance;- }-}diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex 4cd89ef930..e4e25cf9a6 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -30,9 +30,6 @@ import { EntityChangeQueue } from "./entityChangeQueue";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@@ -105,12 +102,6 @@ export function getQueue(return EventPropagationQueue.getInstance();case QueueName.NotificationQueue: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.tsdeleted file mode 100644index 7cd15aaa7b..0000000000--- a/packages/shared/src/server/redis/mediaRetentionCleanerQueue.ts+++ /dev/null@@ -1,36 +0,0 @@-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.tsindex 7f7de781c4..ca8e1c0a22 100644--- a/worker/src/__tests__/batchDataRetentionCleaner.test.ts+++ b/worker/src/__tests__/batchDataRetentionCleaner.test.ts@@ -52,7 +52,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify trace was deleted (10 days > 7 days retention)expect(await getClickhouseCount(TABLE, projectId)).toBe(0);@@ -82,7 +83,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify trace was NOT deleted (5 days < 7 days retention)expect(await getClickhouseCount(TABLE, projectId)).toBe(1);@@ -136,7 +138,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectB)).toBe(2);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Only now trace should remain in Aexpect(await getClickhouseCount(TABLE, projectA)).toBe(1);@@ -165,7 +168,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify trace was NOT deleted (no retention policy)expect(await getClickhouseCount(TABLE, projectId)).toBe(1);@@ -195,7 +199,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify trace was NOT deleted (retention disabled)expect(await getClickhouseCount(TABLE, projectId)).toBe(1);@@ -225,7 +230,8 @@ describe("BatchDataRetentionCleaner", () => {]);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify trace was NOT deleted (project is soft-deleted, handled by BatchProjectCleaner)expect(await getClickhouseCount(TABLE, projectId)).toBe(1);@@ -259,7 +265,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify observation was deletedexpect(await getClickhouseCount(TABLE, projectId)).toBe(0);@@ -293,7 +300,8 @@ describe("BatchDataRetentionCleaner", () => {expect(await getClickhouseCount(TABLE, projectId)).toBe(1);// Run processBatch- await BatchDataRetentionCleaner.processBatch(TABLE);+ const cleaner = new BatchDataRetentionCleaner(TABLE);+ await cleaner.processBatch();// Verify score was deletedexpect(await getClickhouseCount(TABLE, projectId)).toBe(0);diff --git a/worker/src/__tests__/batchProjectCleaner.test.ts b/worker/src/__tests__/batchProjectCleaner.test.tsindex 553e33e2b3..2f2b826f3e 100644--- a/worker/src/__tests__/batchProjectCleaner.test.ts+++ b/worker/src/__tests__/batchProjectCleaner.test.ts@@ -1,6 +1,10 @@-import { expect, describe, it } from "vitest";+import { expect, describe, it, afterEach } from "vitest";import { randomUUID } from "crypto";-import { BatchProjectCleaner } from "../features/batch-project-cleaner";+import {+ BatchProjectCleaner,+ BATCH_DELETION_TABLES,+ BATCH_PROJECT_CLEANER_LOCK_PREFIX,+} from "../features/batch-project-cleaner";import {createOrgProjectAndApiKey,createTracesCh,@@ -8,8 +12,10 @@ import {createDatasetRunItemsCh,createDatasetRunItem,queryClickhouse,+ redis,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";+import { env } from "../env";async function getClickhouseCount(table: string,@@ -24,17 +30,39 @@ async function getClickhouseCount(describe("BatchProjectCleaner", () => {const TEST_TABLE = "traces" as const;+ const TEST_LOCK_KEY = `${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${TEST_TABLE}`;++ // Clean up Redis locks after each test+ afterEach(async () => {+ for (const table of BATCH_DELETION_TABLES) {+ await redis?.del(`${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${table}`);+ }+ });describe("processBatch", () => {- it("should do nothing when no deleted projects exist", async () => {+ it("should return sleep interval when no deleted projects exist", async () => {+ // Clean up any soft-deleted projects from other tests+ await prisma.project.updateMany({+ where: { deletedAt: { not: null } },+ data: { deletedAt: null },+ });+// Create an active project (not deleted)await createOrgProjectAndApiKey();- // Should complete without error- await BatchProjectCleaner.processBatch(TEST_TABLE);+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ const nextDelayMs = await cleaner.processBatch();++ expect(nextDelayMs).toBe(+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,+ );++ // Verify lock was not taken+ const lockValue = await redis?.get(TEST_LOCK_KEY);+ expect(lockValue).toBeNull();});- it("should do nothing when deleted project has no ClickHouse data", async () => {+ it("should return sleep interval when deleted project has no ClickHouse data", async () => {// Create and soft-delete a projectconst { projectId } = await createOrgProjectAndApiKey();await prisma.project.update({@@ -42,8 +70,16 @@ describe("BatchProjectCleaner", () => {data: { deletedAt: new Date() },});- // Should complete without error- await BatchProjectCleaner.processBatch(TEST_TABLE);+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ const nextDelayMs = await cleaner.processBatch();++ expect(nextDelayMs).toBe(+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,+ );++ // Verify lock was not taken+ const lockValue = await redis?.get(TEST_LOCK_KEY);+ expect(lockValue).toBeNull();});it("should delete traces for soft-deleted project", async () => {@@ -65,11 +101,17 @@ describe("BatchProjectCleaner", () => {expect(countBefore).toBe(2);// Run processBatch- await BatchProjectCleaner.processBatch(TEST_TABLE);+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ const nextDelayMs = await cleaner.processBatch();// Verify traces were deletedconst countAfter = await getClickhouseCount(TEST_TABLE, projectId);expect(countAfter).toBe(0);++ // Verify returned check interval (work was done)+ expect(nextDelayMs).toBe(+ env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,+ );});it("should not affect traces from active projects", async () => {@@ -97,7 +139,8 @@ describe("BatchProjectCleaner", () => {expect(await getClickhouseCount(TEST_TABLE, activeProjectId)).toBe(3);// Run processBatch- await BatchProjectCleaner.processBatch(TEST_TABLE);+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ await cleaner.processBatch();// Verify only deleted project's traces were removedexpect(await getClickhouseCount(TEST_TABLE, deletedProjectId)).toBe(0);@@ -126,11 +169,67 @@ describe("BatchProjectCleaner", () => {]);// Run processBatch- await BatchProjectCleaner.processBatch(TEST_TABLE);+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ const nextDelayMs = await cleaner.processBatch();// Verify both projects' traces were deletedexpect(await getClickhouseCount(TEST_TABLE, projectId1)).toBe(0);expect(await getClickhouseCount(TEST_TABLE, projectId2)).toBe(0);+ expect(nextDelayMs).toBe(+ env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,+ );+ });++ it("should skip processing when lock is already held", async () => {+ // Create and soft-delete a project+ const { projectId } = await createOrgProjectAndApiKey();+ await prisma.project.update({+ where: { id: projectId },+ data: { deletedAt: new Date() },+ });++ // Insert traces+ await createTracesCh([+ createTrace({ id: randomUUID(), project_id: projectId }),+ ]);++ // Acquire the lock manually+ await redis?.set(TEST_LOCK_KEY, "locked", "EX", 3600, "NX");++ // Run processBatch - should skip because lock is held+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ const nextDelayMs = await cleaner.processBatch();++ // Verify traces were NOT deleted (lock blocked processing)+ expect(await getClickhouseCount(TEST_TABLE, projectId)).toBe(1);+ expect(nextDelayMs).toBe(+ env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,+ );+ });++ it("should release lock after processing completes", async () => {+ // Create and soft-delete a project+ const { projectId } = await createOrgProjectAndApiKey();+ await prisma.project.update({+ where: { id: projectId },+ data: { deletedAt: new Date() },+ });++ // Insert traces+ await createTracesCh([+ createTrace({ id: randomUUID(), project_id: projectId }),+ ]);++ // Run processBatch+ const cleaner = new BatchProjectCleaner(TEST_TABLE);+ await cleaner.processBatch();++ // Verify that traces were deleted, therefore processing occurred+ expect(await getClickhouseCount(TEST_TABLE, projectId)).toBe(0);++ // Verify lock was released+ const lockValue = await redis?.get(TEST_LOCK_KEY);+ expect(lockValue).toBeNull();});it("should delete dataset_run_items for soft-deleted project", async () => {@@ -175,7 +274,8 @@ describe("BatchProjectCleaner", () => {expect(await getClickhouseCount(TABLE, activeProjectId)).toBe(3);// Run processBatch- await BatchProjectCleaner.processBatch(TABLE);+ const cleaner = new BatchProjectCleaner(TABLE);+ await cleaner.processBatch();// Verify only deleted project's items were removedexpect(await getClickhouseCount(TABLE, deletedProjectId)).toBe(0);diff --git a/worker/src/__tests__/mediaRetentionCleaner.test.ts b/worker/src/__tests__/mediaRetentionCleaner.test.tsindex 53a1745344..aa6601f9d2 100644--- a/worker/src/__tests__/mediaRetentionCleaner.test.ts+++ b/worker/src/__tests__/mediaRetentionCleaner.test.ts@@ -72,7 +72,8 @@ async function processUntilProjectComplete(maxIterations = 10,): Promise<void> {for (let i = 0; i < maxIterations; i++) {- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();const count = await getMediaCount(projectId);if (count === 0) return;}@@ -85,7 +86,8 @@ async function processUntilProjectComplete(async function drainExpiredMedia(maxIterations = 20): Promise<void> {for (let i = 0; i < maxIterations; i++) {const countBefore = mockDeleteFiles.mock.calls.length;- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();const countAfter = mockDeleteFiles.mock.calls.length;// No new deletions means no more workif (countAfter === countBefore) return;@@ -155,7 +157,8 @@ describe("MediaRetentionCleaner", () => {expect(await getMediaCount(projectId)).toBe(1);// Run processBatch - should find no work for this project- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify media was NOT deleted (5 days < 7 days retention)expect(await getMediaCount(projectId)).toBe(1);@@ -219,7 +222,8 @@ describe("MediaRetentionCleaner", () => {expect(await getMediaCount(projectId)).toBe(1);// Run processBatch- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify media was NOT deleted (no retention policy)expect(await getMediaCount(projectId)).toBe(1);@@ -246,7 +250,8 @@ describe("MediaRetentionCleaner", () => {expect(await getMediaCount(projectId)).toBe(1);// Run processBatch- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify media was NOT deleted (retention disabled)expect(await getMediaCount(projectId)).toBe(1);@@ -275,7 +280,8 @@ describe("MediaRetentionCleaner", () => {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();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify only old media was deleted (count should be 1)expect(await getMediaCount(projectId)).toBe(1);@@ -302,7 +308,8 @@ describe("MediaRetentionCleaner", () => {await createTestMedia(projectId, tenDaysAgo);// Run processBatch- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify media was NOT deleted (project is soft-deleted, handled by BatchProjectCleaner)expect(await getMediaCount(projectId)).toBe(1);@@ -363,7 +370,8 @@ describe("MediaRetentionCleaner", () => {await createTestMedia(projectId, twoDaysAgo);// Run processBatch - should complete without error- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Verify nothing was deletedexpect(await getMediaCount(projectId)).toBe(1);@@ -409,14 +417,16 @@ describe("MediaRetentionCleaner", () => {});// Run first processBatch - should process projectMany (most work) OR any other pending project- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();// Keep running until both our projects are processedwhile (!processedProjects.includes(projectMany) ||!processedProjects.includes(projectFew)) {- await MediaRetentionCleaner.processBatch();+ const cleaner = new MediaRetentionCleaner();+ await cleaner.processBatch();if (processedProjects.length > 10) break; // Safety limit}diff --git a/worker/src/app.ts b/worker/src/app.tsindex a6ddf3967b..0d93f7d4c1 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -29,7 +29,6 @@ import {PostHogIntegrationQueue,MixpanelIntegrationQueue,QueueName,- QueueJobs,logger,BlobStorageIntegrationQueue,DeadLetterRetryQueue,@@ -38,11 +37,6 @@ import {TraceUpsertQueue,CloudFreeTierUsageThresholdQueue,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";@@ -80,9 +74,15 @@ import { otelIngestionQueueProcessor } from "./queues/otelIngestionQueue";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";+import {+ BatchProjectCleaner,+ BATCH_DELETION_TABLES,+} from "./features/batch-project-cleaner";+import {+ BatchDataRetentionCleaner,+ BATCH_DATA_RETENTION_TABLES,+} from "./features/batch-data-retention-cleaner";+import { MediaRetentionCleaner } from "./features/media-retention-cleaner";const app = express();@@ -563,116 +563,45 @@ if (env.LANGFUSE_MUTATION_MONITOR_ENABLED === "true") {}// Batch project cleaners for bulk deletion of ClickHouse data-if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {- WorkerManager.register(- QueueName.BatchProjectCleanerQueue,- batchProjectCleanerProcessor,- {- concurrency: 1, // only 1 job at a time per process.- limiter: {- max: 1,- duration: env.LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS, // no more than 1 job at a time globally- },- },- );+export const batchProjectCleaners: BatchProjectCleaner[] = [];- // Schedule repeatable jobs for each table- const queue = BatchProjectCleanerQueue.getInstance();- if (queue) {- const tables = BATCH_DELETION_TABLES.filter(- (t) =>- t !== "events" ||- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true",- );- for (const table of tables) {- queue- .upsertJobScheduler(- `batch-project-cleaner-${table}`,- { every: env.LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS },- { name: QueueJobs.BatchProjectCleanerJob, data: { table } },- )- .catch((err) =>- logger.error(`Error scheduling batch-project-cleaner-${table}`, err),- );+if (env.LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED === "true") {+ for (const table of BATCH_DELETION_TABLES) {+ // Only start the events table cleaner if the events table experiment is enabled+ if (+ table !== "events" ||+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ ) {+ const cleaner = new BatchProjectCleaner(table);+ batchProjectCleaners.push(cleaner);+ cleaner.start();}}}// Batch data retention cleaners for bulk deletion of expired ClickHouse data-if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {- const tables = BATCH_DATA_RETENTION_TABLES.filter(- (t) =>- t !== "events" ||- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true",- );-- WorkerManager.register(- QueueName.BatchDataRetentionCleanerQueue,- batchDataRetentionCleanerProcessor,- {- concurrency: 1,- maxStalledCount: 1000,- lockDuration: 60000, // 60 seconds- stalledInterval: 120000, // 120 seconds- limiter: {- max: tables.length, // one job per table at a time globally- duration: env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS, // no more than 1 job at a time globally- },- },- );+export const batchDataRetentionCleaners: BatchDataRetentionCleaner[] = [];- // Schedule repeatable jobs for each table- const dataRetentionQueue = BatchDataRetentionCleanerQueue.getInstance();- if (dataRetentionQueue) {- 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,- ),- );+if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {+ for (const table of BATCH_DATA_RETENTION_TABLES) {+ // Only start the events table cleaner if the events table experiment is enabled+ if (+ table !== "events" ||+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true"+ ) {+ const cleaner = new BatchDataRetentionCleaner(table);+ batchDataRetentionCleaners.push(cleaner);+ cleaner.start();}}+}- // Media retention cleaner for media files and blob storage- WorkerManager.register(- QueueName.MediaRetentionCleanerQueue,- mediaRetentionCleanerProcessor,- {- concurrency: 1,- maxStalledCount: 1000,- lockDuration: 60000, // 60 seconds- stalledInterval: 120000, // 120 seconds- limiter: {- max: 1,- duration: env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS, // no more than 1 job at a time globally- },- },- );+// Media retention cleaner for media files and blob storage+export let mediaRetentionCleaner: MediaRetentionCleaner | null = null;- 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),- );- }+if (env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_ENABLED === "true") {+ mediaRetentionCleaner = new MediaRetentionCleaner();+ mediaRetentionCleaner.start();}process.on("SIGINT", () => onShutdown("SIGINT"));diff --git a/worker/src/env.ts b/worker/src/env.tsindex 2ca16a7863..937f924660 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -325,10 +325,14 @@ const EnvSchema = z.object({LANGFUSE_BATCH_PROJECT_CLEANER_ENABLED: z.enum(["true", "false"]).default("false"),- LANGFUSE_BATCH_PROJECT_CLEANER_INTERVAL_MS: z.coerce+ LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS: z.coerce.number().positive()- .default(3_600_000), // 1hr+ .default(600_000), // 10 minutes between checks after successful processing+ LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS: z.coerce+ .number()+ .positive()+ .default(3_600_000), // 1 hour sleep when there is no data to processLANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT: z.coerce.number().positive()diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.tsindex 8afbb70b87..bd2f0678f7 100644--- a/worker/src/features/batch-data-retention-cleaner/index.ts+++ b/worker/src/features/batch-data-retention-cleaner/index.ts@@ -9,14 +9,27 @@ import {queryClickhouse,recordGauge,recordIncrement,- traceException,- type BatchDataRetentionTable,} from "@langfuse/shared/src/server";import { env } from "../../env";import { getRetentionCutoffDate } from "../utils";+import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";++// Tables for batch data retention cleaning (ClickHouse only; also 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];const METRIC_PREFIX = "langfuse.batch_data_retention_cleaner";+export const BATCH_DATA_RETENTION_CLEANER_LOCK_PREFIX =+ "langfuse:batch-data-retention-cleaner";+export const TIMESTAMP_COLUMN_MAP: Record<BatchDataRetentionTable, string> = {traces: "timestamp",observations: "start_time",@@ -84,9 +97,9 @@ function buildRetentionConditions(* 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 at a time.+ * Each instance processes one table (traces, observations, scores, events).+ * Multiple workers coordinate via Redis distributed locking to ensure only one+ * worker deletes from a given table at a time.** Flow:* 1. Query PG for all projects with retentionDays > 0@@ -95,99 +108,121 @@ function buildRetentionConditions(* 4. Sort by expired count DESC, select top N projects with expired data* 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;- }+export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {+ private readonly tableName: BatchDataRetentionTable;- recordGauge(`${METRIC_PREFIX}.pending_projects`, workloads.length, {- table: tableName,+ protected get defaultIntervalMs(): number {+ return env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS;+ }++ constructor(tableName: BatchDataRetentionTable) {+ // TTL = DELETE timeout + 5 minutes buffer+ const lockTtlSeconds =+ Math.ceil(+ env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_DELETE_TIMEOUT_MS / 1000,+ ) + 300;++ super({+ name: `BatchDataRetentionCleaner(${tableName})`,+ lockKey: `${BATCH_DATA_RETENTION_CLEANER_LOCK_PREFIX}:${tableName}`,+ lockTtlSeconds,});+ this.tableName = tableName;+ }- // Compute seconds past cutoff for each workload- const SECONDS_PER_DAY = 86400;- const secondsPastCutoffByProject = workloads- .filter((w) => w.oldestAgeSeconds !== null)- .map((w) => ({- projectId: w.projectId,- secondsPastCutoff:- w.oldestAgeSeconds! - w.retentionDays * SECONDS_PER_DAY,- }));-- // Compute p90 for the gauge metric (0 when no pending work)- const p90SecondsPastCutoff = percentile(- secondsPastCutoffByProject.map((p) => p.secondsPastCutoff),- 0.9,- );+ /**+ * Start the batch cleaner service+ */+ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ intervalMs: env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS,+ projectLimit: env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_PROJECT_LIMIT,+ deleteTimeoutMs:+ env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_DELETE_TIMEOUT_MS,+ });+ super.start();+ }- recordGauge(- `${METRIC_PREFIX}.seconds_past_cutoff`,- Math.max(p90SecondsPastCutoff, 0),- {- table: tableName,+ /**+ * Process a batch for data retention for this table.+ * Preflight and deletion are both under lock to avoid redundant expensive queries.+ */+ protected async execute(): Promise<void> {+ const timestampColumn = TIMESTAMP_COLUMN_MAP[this.tableName];++ await this.withLock(+ async () => {+ // Step 1: Get project workloads (chunked CH counts + PG retention config)+ const workloads = await this.getProjectWorkloads();++ recordGauge(`${METRIC_PREFIX}.pending_projects`, workloads.length, {+ table: this.tableName,+ });++ // Compute seconds past cutoff for each workload+ const SECONDS_PER_DAY = 86400;+ const secondsPastCutoffByProject = workloads+ .filter((w) => w.oldestAgeSeconds !== null)+ .map((w) => ({+ projectId: w.projectId,+ secondsPastCutoff:+ w.oldestAgeSeconds! - w.retentionDays * SECONDS_PER_DAY,+ }));++ // Compute p90 for the gauge metric (0 when no pending work)+ const p90SecondsPastCutoff = percentile(+ secondsPastCutoffByProject.map((p) => p.secondsPastCutoff),+ 0.9,+ );++ recordGauge(+ `${METRIC_PREFIX}.seconds_past_cutoff`,+ Math.max(p90SecondsPastCutoff, 0),+ {+ table: this.tableName,+ },+ );++ // Step 2: Execute DELETE+ if (workloads.length >= 0) {+ logger.info(+ `${this.instanceName}: Processing ${workloads.length} projects`,+ {+ projectIds: workloads.map((w) => w.projectId),+ secondsPastCutoffByProject,+ },+ );++ await this.executeBatchDelete(timestampColumn, workloads);++ logger.info(`${this.instanceName}: Batch deletion completed`, {+ table: this.tableName,+ projectsProcessed: workloads.length,+ });+ } else {+ logger.info(+ `${this.instanceName}: No projects with retention and data to delete`,+ );+ }++ // Record successful deletion metrics+ recordIncrement(`${METRIC_PREFIX}.delete_successes`, 1, {+ table: this.tableName,+ });+ recordIncrement(+ `${METRIC_PREFIX}.projects_processed`,+ workloads.length,+ {+ table: this.tableName,+ },+ );+ },+ () => {+ recordIncrement(`${METRIC_PREFIX}.delete_failures`, 1, {+ table: this.tableName,+ });},);-- if (workloads.length === 0) {- logger.info(- `${instanceName}: No projects with retention and data to delete`,- );- return;- }-- logger.info(`${instanceName}: Processing ${workloads.length} projects`, {- projectIds: workloads.map((w) => w.projectId),- secondsPastCutoffByProject,- });-- // 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;- }}/**@@ -199,10 +234,8 @@ export class BatchDataRetentionCleaner {** Chunking prevents running into CH query and param size limits.*/- private static async getProjectWorkloads(- tableName: BatchDataRetentionTable,- ): Promise<ProjectWorkload[]> {- const timestampColumn = TIMESTAMP_COLUMN_MAP[tableName];+ private async getProjectWorkloads(): Promise<ProjectWorkload[]> {+ const timestampColumn = TIMESTAMP_COLUMN_MAP[this.tableName];// Step 1: Get all projects with retention from PostgreSQLconst projectsWithRetention = await prisma.project.findMany({@@ -239,11 +272,7 @@ export class BatchDataRetentionCleaner {// Query each chunk in parallel (counts only expired rows)const chunkResults = await Promise.all(chunks.map((chunk) =>- BatchDataRetentionCleaner.countExpiredRowsInChunk(- tableName,- timestampColumn,- chunk,- ),+ this.countExpiredRowsInChunk(timestampColumn, chunk),),);@@ -264,8 +293,7 @@ export class BatchDataRetentionCleaner {* Count expired rows for a chunk of projects in ClickHouse.* Uses the same retention conditions as delete to count only rows that will be deleted.*/- private static async countExpiredRowsInChunk(- tableName: BatchDataRetentionTable,+ private async countExpiredRowsInChunk(timestampColumn: string,projects: ProjectWorkload[],): Promise<ProjectWorkload[]> {@@ -283,7 +311,7 @@ export class BatchDataRetentionCleaner {project_id,count() as count,dateDiff('second', min(event_ts), now()) as oldest_age_seconds- FROM ${tableName}+ FROM ${this.tableName}WHERE ${conditions}GROUP BY project_idHAVING count > 0@@ -298,7 +326,7 @@ export class BatchDataRetentionCleaner {params,tags: {feature: "batch-data-retention-cleaner",- table: tableName,+ table: this.tableName,operation: "count-chunk",},});@@ -329,8 +357,7 @@ export class BatchDataRetentionCleaner {* 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,+ private async executeBatchDelete(timestampColumn: string,workloads: ProjectWorkload[],): Promise<void> {@@ -343,7 +370,7 @@ export class BatchDataRetentionCleaner {workloads,);- const query = `DELETE FROM ${tableName} WHERE ${conditions}`;+ const query = `DELETE FROM ${this.tableName} WHERE ${conditions}`;await commandClickhouse({query,@@ -354,7 +381,7 @@ export class BatchDataRetentionCleaner {},tags: {feature: "batch-data-retention-cleaner",- table: tableName,+ table: this.tableName,operation: "delete",},});diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.tsindex f692345c1b..0c36832b44 100644--- a/worker/src/features/batch-project-cleaner/index.ts+++ b/worker/src/features/batch-project-cleaner/index.ts@@ -4,13 +4,24 @@ import {commandClickhouse,traceException,recordIncrement,- BATCH_DELETION_TABLES,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";++export const BATCH_DELETION_TABLES = [+ "traces",+ "observations",+ "scores",+ "events",+ "dataset_run_items_rmt",+] as const;import { env } from "../../env";+import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";export type BatchDeletionTable = (typeof BATCH_DELETION_TABLES)[number];+export const BATCH_PROJECT_CLEANER_LOCK_PREFIX =+ "langfuse:batch-project-cleaner";+interface ProjectCount {project_id: string;count: number;@@ -19,48 +30,87 @@ interface ProjectCount {/*** BatchProjectCleaner handles bulk deletion of ClickHouse data for soft-deleted projects.*- * Each invocation processes one table (traces, observations, scores, events).- * BullMQ handles distributed locking to ensure only one worker processes- * a given table's job at a time.+ * Each instance processes one table (traces, observations, scores, events).+ * Multiple workers coordinate via Redis distributed locking to ensure only one+ * worker deletes from a given table at a time.** Flow:- * 1. Query PG for projects with deleted_at set- * 2. Query ClickHouse for counts per project- * 3. Execute DELETE- * 4. On failure: re-run count query to determine partial success+ * 1. Query PG for projects with deleted_at set (no lock needed)+ * 2. Query ClickHouse for counts per project (no lock needed)+ * 3. Acquire Redis lock for DELETE only+ * 4. Execute DELETE+ * 5. On failure: re-run count query to determine partial success*/-export class BatchProjectCleaner {+export class BatchProjectCleaner extends PeriodicExclusiveRunner {+ private readonly tableName: BatchDeletionTable;++ protected get defaultIntervalMs(): number {+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;+ }++ constructor(tableName: BatchDeletionTable) {+ // TTL = DELETE timeout + 5 minutes buffer+ const lockTtlSeconds =+ Math.ceil(env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS / 1000) ++ 300;++ super({+ name: `BatchProjectCleaner(${tableName})`,+ lockKey: `${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${tableName}`,+ lockTtlSeconds,+ });+ this.tableName = tableName;+ }++ /**+ * Start the batch cleaner service+ */+ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ checkIntervalMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,+ sleepOnEmptyMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS,+ projectLimit: env.LANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT,+ deleteTimeoutMs: env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS,+ });+ super.start();+ }+/**- * Process a batch of deleted projects for a specific table.+ * Process a batch of deleted projects. Returns the delay until next run.*/- public static async processBatch(- tableName: BatchDeletionTable,- ): Promise<void> {- const instanceName = `BatchProjectCleaner(${tableName})`;+ public override async processBatch(): Promise<number> {+ return this.execute();+ }- // Step 1: Query PG for deleted projects+ /**+ * Process a batch of deleted projects. Returns the delay until next run.+ */+ protected async execute(): Promise<number> {+ // Step 1: Query PG for deleted projects (no lock needed)let deletedProjects: Array<{ id: string }>;try {- deletedProjects = await BatchProjectCleaner.getDeletedProjects();+ deletedProjects = await this.getDeletedProjects();} catch (error) {- logger.error(`${instanceName}: Failed to query deleted projects`, {+ logger.error(`${this.instanceName}: Failed to query deleted projects`, {error,});traceException(error);- return;+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;}- // Step 2: Query ClickHouse for counts per project+ // Step 2: Query ClickHouse for counts per project (no lock needed)let initialCounts: Map<string, number>;try {- initialCounts = await BatchProjectCleaner.getProjectCounts(- tableName,+ initialCounts = await this.getProjectCounts(deletedProjects.map((p) => p.id),);} catch (error) {- logger.error(`${instanceName}: Failed to query ClickHouse counts`, error);+ logger.error(+ `${this.instanceName}: Failed to query ClickHouse counts`,+ error,+ );traceException(error);- return;+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;}// Filter to only projects that have data@@ -70,83 +120,79 @@ export class BatchProjectCleaner {if (projectIdsWithData.length === 0) {logger.info(- `${instanceName}: No data found for deleted projects in ${tableName}`,+ `${this.instanceName}: No data found for deleted projects in ${this.tableName}`,);- return;+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;}- // Step 3: Execute DELETE- try {- await BatchProjectCleaner.executeDelete(tableName, projectIdsWithData);+ // Step 3 & 4: Execute DELETE under distributed lock+ return (+ (await this.withLock(+ async () => {+ await this.executeDelete(projectIdsWithData);- const totalRows = Array.from(initialCounts.values()).reduce(- (sum, count) => sum + count,- 0,- );- logger.info(`${instanceName}: Batch deletion completed`, {- table: tableName,- projectsProcessed: projectIdsWithData.length,- totalRowsTargeted: totalRows,- });- } catch (deleteError) {- // Step 4: On failure, re-run count query to determine partial success- logger.warn(- `${instanceName}: DELETE failed, checking for partial success`,- deleteError,- );- traceException(deleteError);+ const totalRows = Array.from(initialCounts.values()).reduce(+ (sum, count) => sum + count,+ 0,+ );+ logger.info(`${this.instanceName}: Batch deletion completed`, {+ table: this.tableName,+ projectsProcessed: projectIdsWithData.length,+ totalRowsTargeted: totalRows,+ });- // Record DELETE failure metric- recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {- table: tableName,- });+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;+ },+ async (error) => {+ // Step 5: On failure, re-run count query to determine partial success+ recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {+ table: this.tableName,+ });- let finalCounts: Map<string, number> | undefined;- try {- finalCounts = await BatchProjectCleaner.getProjectCounts(- tableName,- projectIdsWithData,- );- } catch (countError) {- // Can't determine partial success- logger.error(- `${instanceName}: Failed to re-query counts after DELETE failure`,- countError,- );- }-- // Calculate projects that couldn't be fully cleaned- const incompleteProjects = finalCounts- ? projectIdsWithData.filter((projectId) => {- const finalCount = finalCounts.get(projectId) ?? 0;- return finalCount > 0;- })- : projectIdsWithData;-- if (incompleteProjects.length > 0) {- recordIncrement(- "langfuse.batch_project_cleaner.incomplete_cleanups",- incompleteProjects.length,- { table: tableName },- );- logger.warn(`${instanceName}: Partial deletion completed`, {- table: tableName,- incompleteProjectCount: incompleteProjects.length,- incompleteProjects: incompleteProjects.slice(0, 10), // Log first 10- error: (deleteError as Error).message,- });- } else {- logger.info(- `${instanceName}: All projects cleaned successfully on re-check`,- );- }-- // Re-throw so BullMQ marks job as failed- throw deleteError;- }+ let finalCounts: Map<string, number> | undefined;+ try {+ finalCounts = await this.getProjectCounts(projectIdsWithData);+ } catch (countError) {+ // Can't determine partial success+ logger.error(+ `${this.instanceName}: Failed to re-query counts after DELETE failure`,+ countError,+ );+ }++ // Calculate projects that couldn't be fully cleaned+ const incompleteProjects = finalCounts+ ? projectIdsWithData.filter((projectId) => {+ const finalCount = finalCounts.get(projectId) ?? 0;+ return finalCount > 0;+ })+ : projectIdsWithData;++ if (incompleteProjects.length > 0) {+ recordIncrement(+ "langfuse.batch_project_cleaner.incomplete_cleanups",+ incompleteProjects.length,+ { table: this.tableName },+ );+ logger.warn(`${this.instanceName}: Partial deletion completed`, {+ table: this.tableName,+ incompleteProjectCount: incompleteProjects.length,+ incompleteProjects: incompleteProjects.slice(0, 10),+ error: (error as Error).message,+ });+ } else {+ logger.info(+ `${this.instanceName}: All projects cleaned successfully on re-check`,+ );+ }++ return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;+ },+ )) ?? env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS+ );}- private static async getDeletedProjects(): Promise<Array<{ id: string }>> {+ private async getDeletedProjects(): Promise<Array<{ id: string }>> {return prisma.project.findMany({select: { id: true },where: {@@ -156,8 +202,7 @@ export class BatchProjectCleaner {});}- private static async getProjectCounts(- tableName: BatchDeletionTable,+ private async getProjectCounts(projectIds: string[],): Promise<Map<string, number>> {if (projectIds.length === 0) {@@ -166,7 +211,7 @@ export class BatchProjectCleaner {const query = `SELECT project_id, count() as count- FROM ${tableName}+ FROM ${this.tableName}WHERE project_id IN ({projectIds: Array(String)})GROUP BY project_idORDER BY count DESC@@ -177,7 +222,7 @@ export class BatchProjectCleaner {params: { projectIds },tags: {feature: "batch-project-cleaner",- table: tableName,+ table: this.tableName,operation: "count",},});@@ -190,16 +235,13 @@ export class BatchProjectCleaner {return counts;}- private static async executeDelete(- tableName: BatchDeletionTable,- projectIds: string[],- ): Promise<void> {+ private async executeDelete(projectIds: string[]): Promise<void> {if (projectIds.length === 0) {return;}const query = `- DELETE FROM ${tableName}+ DELETE FROM ${this.tableName}WHERE project_id IN ({projectIds: Array(String)})`;@@ -211,7 +253,7 @@ export class BatchProjectCleaner {},tags: {feature: "batch-project-cleaner",- table: tableName,+ table: this.tableName,operation: "delete",},});diff --git a/worker/src/features/media-retention-cleaner/index.ts b/worker/src/features/media-retention-cleaner/index.tsindex 1e99a39249..5250b3289e 100644--- a/worker/src/features/media-retention-cleaner/index.ts+++ b/worker/src/features/media-retention-cleaner/index.ts@@ -9,9 +9,13 @@ import {} from "@langfuse/shared/src/server";import { env } from "../../env";import { getRetentionCutoffDate } from "../utils";+import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";const METRIC_PREFIX = "langfuse.media_retention_cleaner";+export const MEDIA_RETENTION_CLEANER_LOCK_KEY =+ "langfuse:media-retention-cleaner";+interface ProjectWorkload {projectId: string;retentionDays: number;@@ -27,16 +31,45 @@ interface ProjectWorkload {* 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";+export class MediaRetentionCleaner extends PeriodicExclusiveRunner {+ protected get defaultIntervalMs(): number {+ return env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS;+ }++ constructor() {+ // TTL = interval + 5 minutes buffer (media deletion can be slow)+ const lockTtlSeconds =+ Math.ceil(env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS / 1000) + 300;++ super({+ name: "MediaRetentionCleaner",+ lockKey: MEDIA_RETENTION_CLEANER_LOCK_KEY,+ lockTtlSeconds,+ onUnavailable: "fail",+ });+ }+ /**+ * Start the media retention cleaner service+ */+ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ intervalMs: env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS,+ itemLimit: env.LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT,+ });+ super.start();+ }++ /**+ * Process expired media for the project with most work.+ */+ protected async execute(): Promise<void> {// Get the project with most expired media (single project per iteration)let workload: ProjectWorkload | null;try {- workload = await MediaRetentionCleaner.getTopProjectWorkload();+ workload = await this.getTopProjectWorkload();} catch (error) {- logger.error(`${instanceName}: Failed to query project workload`, {+ logger.error(`${this.name}: Failed to query project workload`, {error,});traceException(error);@@ -51,7 +84,7 @@ export class MediaRetentionCleaner {);if (!workload) {- logger.info(`${instanceName}: No expired media to clean up`);+ logger.info(`${this.name}: No expired media to clean up`);return;}@@ -60,33 +93,30 @@ export class MediaRetentionCleaner {projectId: workload.projectId,});- logger.info(`${instanceName}: Processing project`, {- projectId: workload.projectId,- retentionDays: workload.retentionDays,- expiredMediaCount: workload.expiredMediaCount,- secondsPastCutoff: workload.secondsPastCutoff,- });-- 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;- }+ // Execute under distributed lock+ await this.withLock(+ async () => {+ logger.info(`${this.instanceName}: Processing project`, {+ projectId: workload.projectId,+ retentionDays: workload.retentionDays,+ expiredMediaCount: workload.expiredMediaCount,+ secondsPastCutoff: workload.secondsPastCutoff,+ });++ await this.processProject(workload);+ recordIncrement(`${METRIC_PREFIX}.projects_processed`, 1);+ },+ () => {+ recordIncrement(`${METRIC_PREFIX}.project_failures`, 1);+ },+ );}/*** 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> {+ private async getTopProjectWorkload(): Promise<ProjectWorkload | null> {const now = new Date();// Single query: join projects with media, filter by retention cutoff, order by count, limit 1@@ -130,12 +160,10 @@ export class MediaRetentionCleaner {};}- private static async processProject(- workload: ProjectWorkload,- ): Promise<void> {+ private async processProject(workload: ProjectWorkload): Promise<void> {// Delete media files (S3 + PostgreSQL)if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {- await MediaRetentionCleaner.deleteExpiredMedia(+ await this.deleteExpiredMedia(workload,env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,);@@ -149,14 +177,14 @@ export class MediaRetentionCleaner {);}- logger.info("MediaRetentionCleaner: Project processed", {+ logger.info(`${this.name}: Project processed`, {projectId: workload.projectId,retentionDays: workload.retentionDays,expiredMediaCount: workload.expiredMediaCount,});}- private static async deleteExpiredMedia(+ private async deleteExpiredMedia(workload: ProjectWorkload,bucket: string,): Promise<void> {@@ -189,7 +217,7 @@ export class MediaRetentionCleaner {projectId: workload.projectId,});- logger.info("MediaRetentionCleaner: Media files deleted", {+ logger.info(`${this.name}: Media files deleted`, {projectId: workload.projectId,count: mediaFiles.length,});diff --git a/worker/src/queues/batchDataRetentionCleanerQueue.ts b/worker/src/queues/batchDataRetentionCleanerQueue.tsdeleted file mode 100644index 980aa3bf6e..0000000000--- a/worker/src/queues/batchDataRetentionCleanerQueue.ts+++ /dev/null@@ -1,34 +0,0 @@-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.tsdeleted file mode 100644index 8a3b5ac03f..0000000000--- a/worker/src/queues/batchProjectCleanerQueue.ts+++ /dev/null@@ -1,28 +0,0 @@-import { Processor } from "bullmq";-import {- logger,- QueueJobs,- BatchProjectCleanerJobType,- BATCH_DELETION_TABLES,-} from "@langfuse/shared/src/server";-import {- BatchProjectCleaner,- BatchDeletionTable,-} from "../features/batch-project-cleaner";--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);- } catch (error) {- logger.error(`Error executing BatchProjectCleaner for ${table}`, error);- throw error;- }- }-};diff --git a/worker/src/queues/mediaRetentionCleanerQueue.ts b/worker/src/queues/mediaRetentionCleanerQueue.tsdeleted file mode 100644index 8f226deabc..0000000000--- a/worker/src/queues/mediaRetentionCleanerQueue.ts+++ /dev/null@@ -1,15 +0,0 @@-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;- }- }-};diff --git a/worker/src/utils/PeriodicExclusiveRunner.ts b/worker/src/utils/PeriodicExclusiveRunner.tsnew file mode 100644index 0000000000..41faba08ca--- /dev/null+++ b/worker/src/utils/PeriodicExclusiveRunner.ts@@ -0,0 +1,80 @@+import { logger, getCurrentSpan } from "@langfuse/shared/src/server";+import { PeriodicRunner } from "./PeriodicRunner";+import { OnUnavailableBehavior, RedisLock } from "./RedisLock";++/**+ * Abstract base class for periodic tasks that require distributed locking.+ *+ * Extends PeriodicRunner with:+ * - Redis distributed locking (via RedisLock)+ * - Common stop() logging+ * - processBatch() public wrapper for testing+ * - withLock() helper for lock + error handling+ */+export abstract class PeriodicExclusiveRunner extends PeriodicRunner {+ protected readonly instanceName: string;+ protected readonly lock: RedisLock;++ constructor(params: {+ name: string;+ lockKey: string;+ lockTtlSeconds: number;+ onUnavailable?: OnUnavailableBehavior;+ }) {+ super();+ this.instanceName = params.name;+ this.lock = new RedisLock(params.lockKey, {+ ttlSeconds: params.lockTtlSeconds,+ name: params.name,+ onUnavailable: params.onUnavailable || "proceed",+ });+ }++ protected get name(): string {+ return this.instanceName;+ }++ public override stop(): void {+ super.stop();+ logger.info(`${this.instanceName} stopped`);+ }++ /**+ * Public wrapper for execute(), used by tests.+ */+ public async processBatch(): Promise<number | void> {+ return this.execute();+ }++ /**+ * Execute operation under distributed lock.+ * Returns operation result, onFailure result, or undefined if lock not acquired.+ */+ protected async withLock<T>(+ operation: () => Promise<T>,+ onFailure?: (error: unknown) => T | Promise<T | void> | void,+ ): Promise<T | undefined> {+ const result = await this.lock.withLock(async () => {+ try {+ return await operation();+ } catch (error) {+ logger.error(`${this.instanceName}: Operation failed`, { error });+ // Error will be traced by parent instrumentAsync in PeriodicRunner+ return await onFailure?.(error);+ }+ });++ // Add lock status to current span+ const span = getCurrentSpan();+ span?.setAttribute("lock.acquired", result !== null);+ span?.setAttribute("lock.key", this.lock.key);++ if (result === null) {+ logger.debug(+ `${this.instanceName}: Lock not acquired, another worker is processing`,+ );+ }++ return result ?? undefined;+ }+}diff --git a/worker/src/utils/PeriodicRunner.ts b/worker/src/utils/PeriodicRunner.tsindex 6dffcf1fa0..9d4ebd6c1e 100644--- a/worker/src/utils/PeriodicRunner.ts+++ b/worker/src/utils/PeriodicRunner.ts@@ -1,4 +1,5 @@-import { logger, traceException } from "@langfuse/shared/src/server";+import { logger, instrumentAsync } from "@langfuse/shared/src/server";+import { SpanKind } from "@opentelemetry/api";/*** Abstract base class for periodic task execution.@@ -34,13 +35,26 @@ export abstract class PeriodicRunner {let nextDelayMs = this.defaultIntervalMs;try {- const result = await this.execute();- if (typeof result === "number") {- nextDelayMs = result;- }+ await instrumentAsync(+ {+ name: `periodic-runner.${this.name}`,+ startNewTrace: true,+ spanKind: SpanKind.INTERNAL,+ },+ async (span) => {+ span.setAttribute("runner.name", this.name);+ span.setAttribute("runner.interval_ms", this.defaultIntervalMs);++ const result = await this.execute();+ if (typeof result === "number") {+ nextDelayMs = result;+ span.setAttribute("runner.next_delay_ms", nextDelayMs);+ }+ },+ );} catch (error) {+ // instrumentAsync already calls traceException, just log herelogger.error(`Unexpected error in ${this.name}`, error);- traceException(error);} finally {this.scheduleNext(nextDelayMs);}diff --git a/worker/src/utils/RedisLock.ts b/worker/src/utils/RedisLock.tsnew file mode 100644index 0000000000..4aaac62270--- /dev/null+++ b/worker/src/utils/RedisLock.ts@@ -0,0 +1,186 @@+import { randomUUID } from "crypto";+import { logger, redis } from "@langfuse/shared/src/server";++export type LockAcquireResult = "acquired" | "held_by_other" | "skipped";++/**+ * Behavior when Redis is unavailable or errors occur during lock acquisition.+ * - "proceed": Allow processing without the lock (optimistic, for non-critical locks)+ * - "fail": Treat as failure to acquire (pessimistic, for critical locks)+ */+export type OnUnavailableBehavior = "proceed" | "fail";++/**+ * Distributed lock implementation using Redis.+ *+ * Features:+ * - Unique lock ownership via UUID to prevent accidental release of another worker's lock+ * - Atomic release using Lua script for check-and-delete+ * - Configurable behavior when Redis is unavailable+ * - TTL-based expiration as safety net+ *+ * Usage:+ * ```typescript+ * // Optimistic: proceed without lock if Redis unavailable+ * const lock = new RedisLock("my-lock-key", {+ * ttlSeconds: 300,+ * onUnavailable: "proceed",+ * });+ *+ * // Pessimistic: fail if Redis unavailable+ * const lock = new RedisLock("critical-lock", {+ * ttlSeconds: 300,+ * onUnavailable: "fail",+ * });+ *+ * const result = await lock.withLock(async () => {+ * // Critical section+ * return someValue;+ * });+ *+ * if (result === null) {+ * // Lock was not acquired+ * }+ * ```+ */+export class RedisLock {+ private readonly lockKey: string;+ private readonly lockValue: string;+ private readonly ttlSeconds: number;+ private readonly name: string;+ private readonly onUnavailable: OnUnavailableBehavior;++ // Lua script for atomic check-and-delete (only delete if we own the lock)+ private static readonly RELEASE_LOCK_SCRIPT = `+ if redis.call("get", KEYS[1]) == ARGV[1] then+ return redis.call("del", KEYS[1])+ else+ return 0+ end+ `;++ public get key(): string {+ return this.lockKey;+ }++ constructor(+ lockKey: string,+ options: {+ ttlSeconds: number;+ /** Optional name for logging */+ name?: string;+ /** Behavior when Redis is unavailable. Default: "proceed" */+ onUnavailable?: OnUnavailableBehavior;+ },+ ) {+ this.lockKey = lockKey;+ this.lockValue = randomUUID();+ this.ttlSeconds = options.ttlSeconds;+ this.name = options.name ?? lockKey;+ this.onUnavailable = options.onUnavailable ?? "proceed";+ }++ /**+ * Execute a callback under the distributed lock.+ * Returns null if lock could not be acquired, otherwise returns the callback result.+ */+ public async withLock<T>(fn: () => Promise<T>): Promise<T | null> {+ const lockResult = await this.acquire();++ // Determine if we should proceed based on result and configuration+ const shouldProceed =+ lockResult === "acquired" ||+ (lockResult === "skipped" && this.onUnavailable === "proceed");++ if (!shouldProceed) {+ return null;+ }++ try {+ return await fn();+ } finally {+ // Only release if we actually acquired the lock (not if Redis was unavailable)+ if (lockResult === "acquired") {+ await this.release();+ }+ }+ }++ /**+ * Attempt to acquire the distributed lock.+ *+ * Returns:+ * - "acquired": lock acquired successfully+ * - "held_by_other": lock is held by another worker+ * - "skipped": Redis unavailable, proceeding without lock+ */+ public async acquire(): Promise<LockAcquireResult> {+ if (!redis) {+ logger.warn(`[${this.name}] Redis unavailable, allowing processing`);+ return "skipped";+ }++ // Random jitter (0-10ms) to prevent lock contention when multiple workers start simultaneously+ await new Promise((resolve) => setTimeout(resolve, Math.random() * 10));++ try {+ const result = await redis.set(+ this.lockKey,+ this.lockValue,+ "EX",+ this.ttlSeconds,+ "NX",+ );+ const acquired = result === "OK";++ if (acquired) {+ logger.debug(+ `[${this.name}] Acquired lock with TTL ${this.ttlSeconds}s`,+ );+ return "acquired";+ }++ return "held_by_other";+ } catch (error) {+ logger.error(+ `[${this.name}] Failed to acquire lock due to an error`,+ error,+ );+ // On error, allow processing but don't claim to hold the lock+ return "skipped";+ }+ }++ /**+ * Release the distributed lock if we own it.+ * Uses a Lua script for atomic check-and-delete to prevent accidentally+ * releasing a lock owned by another worker.+ */+ public async release(): Promise<boolean> {+ if (!redis) {+ return false;+ }++ try {+ const result = await redis.eval(+ RedisLock.RELEASE_LOCK_SCRIPT,+ 1,+ this.lockKey,+ this.lockValue,+ );+ if (result === 1) {+ logger.debug(`[${this.name}] Released lock`);+ return true;+ } else {+ logger.warn(+ `[${this.name}] Lock was not released (not owned or already expired)`,+ );+ return false;+ }+ } catch (error) {+ // Log but don't throw - lock will expire via TTL anyway+ logger.error(`[${this.name}] Failed to release lock`, error);+ return false;+ }+ }+}diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex 105d2efb42..69e3547110 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -10,6 +10,11 @@ import { WorkerManager } from "../queues/workerManager";import { prisma } from "@langfuse/shared/src/db";import { BackgroundMigrationManager } from "../backgroundMigrations/backgroundMigrationManager";import { MutationMonitor } from "../features/mutation-monitoring/mutationMonitor";+import {+ batchProjectCleaners,+ batchDataRetentionCleaners,+ mediaRetentionCleaner,+} from "../app";export const onShutdown: NodeJS.SignalsListener = async (signal) => {logger.info(`Received ${signal}, closing server...`);@@ -22,6 +27,19 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {// Stop mutation monitorMutationMonitor.stop();+ // Stop batch project cleaners+ for (const cleaner of batchProjectCleaners) {+ cleaner.stop();+ }++ // Stop batch data retention cleaners+ for (const cleaner of batchDataRetentionCleaners) {+ cleaner.stop();+ }++ // Stop media retention cleaner+ mediaRetentionCleaner?.stop();+// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)await WorkerManager.closeWorkers();