Skip to content

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

fix(worker): bound media retention cleanup batches (#15226)

Valery Meleshkin9e06844e33c8
diff --git a/packages/shared/src/server/media-deletion.ts b/packages/shared/src/server/media-deletion.ts
index 2cde6b9c8b..682364b950 100644
--- a/packages/shared/src/server/media-deletion.ts
+++ b/packages/shared/src/server/media-deletion.ts
@@ -1,3 +1,4 @@
+import { Prisma } from "@prisma/client";
import chunk from "lodash/chunk";
import { prisma } from "../db";
@@ -9,6 +10,44 @@ interface MediaFileRef {
bucketPath: string;
}
+export interface MediaRetentionProject {
+ projectId: string;
+ retentionDays: number;
+ cutoffDate: Date;
+ secondsPastCutoff: number;
+}
+
+const expiredMediaWorkCondition = (params: {
+ projectId: Prisma.Sql;
+ cutoffDate: Prisma.Sql;
+}) => Prisma.sql`
+ m.project_id = ${params.projectId}
+ AND m.created_at <= ${params.cutoffDate}
+ AND (
+ NOT EXISTS (
+ SELECT 1
+ FROM dataset_item_media dim
+ WHERE dim.project_id = ${params.projectId}
+ AND dim.media_id = m.id
+ AND dim.dataset_item_valid_from IS NOT NULL
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM trace_media tm
+ WHERE tm.project_id = ${params.projectId}
+ AND tm.media_id = m.id
+ AND tm.created_at <= ${params.cutoffDate}
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM observation_media om
+ WHERE om.project_id = ${params.projectId}
+ AND om.media_id = m.id
+ AND om.created_at <= ${params.cutoffDate}
+ )
+ )
+`;
+
/**
* Find all media files for a project (for complete project deletion).
*/
@@ -40,6 +79,65 @@ export async function findExpiredMediaByProjectId(params: {
});
}
+/**
+ * Find the oldest bounded retention batch. Each returned row either deletes
+ * media or removes expired trace/observation links, so every batch progresses.
+ */
+export async function findExpiredMediaBatchByProjectId(params: {
+ projectId: string;
+ cutoffDate: Date;
+ limit: number;
+}): Promise<MediaFileRef[]> {
+ const condition = expiredMediaWorkCondition({
+ projectId: Prisma.sql`${params.projectId}`,
+ cutoffDate: Prisma.sql`${params.cutoffDate}`,
+ });
+
+ return prisma.$queryRaw<MediaFileRef[]>(Prisma.sql`
+ SELECT m.id, m.bucket_path AS "bucketPath"
+ FROM media m
+ WHERE ${condition}
+ ORDER BY m.created_at ASC, m.id ASC
+ LIMIT ${params.limit}
+ `);
+}
+
+/**
+ * Find the project whose oldest actionable media is furthest past retention.
+ * The lateral lookup stops at the first actionable row per project.
+ */
+export async function findNextMediaRetentionProject(): Promise<MediaRetentionProject | null> {
+ const cutoffDate = Prisma.sql`
+ NOW() - p.retention_days * INTERVAL '1 day'
+ `;
+ const condition = expiredMediaWorkCondition({
+ projectId: Prisma.sql`p.id`,
+ cutoffDate,
+ });
+ const rows = await prisma.$queryRaw<MediaRetentionProject[]>(Prisma.sql`
+ SELECT
+ p.id AS "projectId",
+ p.retention_days AS "retentionDays",
+ ${cutoffDate} AS "cutoffDate",
+ EXTRACT(EPOCH FROM (${cutoffDate} - oldest.created_at))::int
+ AS "secondsPastCutoff"
+ FROM projects p
+ CROSS JOIN LATERAL (
+ SELECT m.created_at
+ FROM media m
+ WHERE ${condition}
+ ORDER BY m.created_at ASC
+ LIMIT 1
+ ) oldest
+ WHERE p.retention_days > 0
+ AND p.deleted_at IS NULL
+ ORDER BY "secondsPastCutoff" DESC, p.id ASC
+ LIMIT 1
+ `);
+
+ return rows[0] ?? null;
+}
+
export interface StorageClient {
deleteFiles: (paths: string[]) => Promise<void>;
}
@@ -74,14 +172,17 @@ export async function deleteMediaLinkRowsByProjectId(params: {
/**
* Delete media files from S3 first, then from PostgreSQL.
* S3 is deleted first to avoid orphaned files if PG deletion succeeds but S3 fails.
+ * A link cutoff preserves recent links when retention keeps dataset-protected media.
* Returns the number of media files deleted.
*/
export async function deleteMediaFiles(params: {
projectId: string;
mediaFiles: MediaFileRef[];
storageClient: StorageClient;
+ linkCleanupCutoffDate?: Date;
}): Promise<number> {
- const { projectId, mediaFiles, storageClient } = params;
+ const { projectId, mediaFiles, storageClient, linkCleanupCutoffDate } =
+ params;
if (mediaFiles.length === 0) {
return 0;
@@ -114,27 +215,31 @@ export async function deleteMediaFiles(params: {
(f) => !datasetAssociatedMediaIds.has(f.id),
);
const deletableMediaIds = deletableBatch.map((f) => f.id);
+ const linkCleanupFilter = linkCleanupCutoffDate
+ ? {
+ OR: [
+ { mediaId: { in: deletableMediaIds } },
+ { createdAt: { lte: linkCleanupCutoffDate } },
+ ],
+ }
+ : {};
- // Trace/observation links are cleaned up even for an all-protected batch, so
- // only the S3 delete is skipped when nothing is deletable.
if (deletableBatch.length > 0) {
await storageClient.deleteFiles(deletableBatch.map((f) => f.bucketPath));
}
await prisma.$transaction([
- // Trace/observation links are removed for every media in the batch, not
- // just the deletable ones: their traces/observations are deleted by the
- // same retention job, so the links go even when the media itself is kept
- // for a dataset item.
prisma.traceMedia.deleteMany({
where: {
projectId,
mediaId: { in: mediaIds },
+ ...linkCleanupFilter,
},
}),
prisma.observationMedia.deleteMany({
where: {
projectId,
mediaId: { in: mediaIds },
+ ...linkCleanupFilter,
},
}),
// Sweep leftover pending rows for the deleted media (claimed rows can't
diff --git a/worker/src/__tests__/mediaRetentionCleaner.test.ts b/worker/src/__tests__/mediaRetentionCleaner.test.ts
index ff30776955..3d036657ed 100644
--- a/worker/src/__tests__/mediaRetentionCleaner.test.ts
+++ b/worker/src/__tests__/mediaRetentionCleaner.test.ts
@@ -2,10 +2,13 @@ import { expect, describe, it, vi, beforeEach, afterEach } from "vitest";
import { randomUUID } from "crypto";
import {
createOrgProjectAndApiKey,
+ findExpiredMediaBatchByProjectId,
+ findNextMediaRetentionProject,
getS3MediaStorageClient,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { MediaRetentionCleaner } from "../features/media-retention-cleaner";
+import { env } from "../env";
// Mock S3 and blob storage functions
vi.mock("@langfuse/shared/src/server", async () => {
@@ -18,13 +21,15 @@ vi.mock("@langfuse/shared/src/server", async () => {
});
// Mock the env module to enable S3 bucket
-vi.mock("../../env", async () => {
- const actual = await vi.importActual("../../env");
+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",
+ LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS: 600_000,
+ LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT: 2,
},
};
});
@@ -84,12 +89,9 @@ async function processUntilProjectComplete(
*/
async function drainExpiredMedia(maxIterations = 20): Promise<void> {
for (let i = 0; i < maxIterations; i++) {
- const countBefore = mockDeleteFiles.mock.calls.length;
+ if (!(await findNextMediaRetentionProject())) return;
const cleaner = new MediaRetentionCleaner();
await cleaner.processBatch();
- const countAfter = mockDeleteFiles.mock.calls.length;
- // No new deletions means no more work
- if (countAfter === countBefore) return;
}
}
@@ -104,6 +106,27 @@ describe("MediaRetentionCleaner", () => {
});
describe("processBatch", () => {
+ it("runs again immediately after work and waits when empty", async () => {
+ await drainExpiredMedia();
+
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { retentionDays: 7 },
+ });
+ await createTestMedia(
+ projectId,
+ new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
+ );
+
+ const cleaner = new MediaRetentionCleaner();
+ await expect(cleaner.processBatch()).resolves.toBe(0);
+ await expect(getMediaCount(projectId)).resolves.toBe(0);
+ await expect(cleaner.processBatch()).resolves.toBe(
+ env.LANGFUSE_MEDIA_RETENTION_CLEANER_INTERVAL_MS,
+ );
+ });
+
it("should delete media files older than project retention", async () => {
const now = Date.now();
const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
@@ -134,10 +157,12 @@ describe("MediaRetentionCleaner", () => {
expect(allDeletedPaths).toContain(media.bucketPath);
});
- it("protects claimed-associated media but sweeps pending associations", async () => {
+ it("cleans expired links, preserves recent links, and drains the project", async () => {
await drainExpiredMedia();
+ mockDeleteFiles.mockClear();
const now = Date.now();
- const tenDaysAgo = new Date(now - 10 * 24 * 60 * 60 * 1000);
+ const daysAgo = (days: number) =>
+ new Date(now - days * 24 * 60 * 60 * 1000);
const { projectId } = await createOrgProjectAndApiKey();
await prisma.project.update({
@@ -146,7 +171,7 @@ describe("MediaRetentionCleaner", () => {
});
// Claimed association (validFrom set) protects its media from retention.
- const claimedMedia = await createTestMedia(projectId, tenDaysAgo);
+ const claimedMedia = await createTestMedia(projectId, daysAgo(12));
await prisma.datasetItemMedia.create({
data: {
id: randomUUID(),
@@ -160,11 +185,53 @@ describe("MediaRetentionCleaner", () => {
referenceString: `@@@langfuseMedia:type=image/png|id=${claimedMedia.id}|source=base64@@@`,
},
});
+ const expiredTraceId = randomUUID();
+ await prisma.traceMedia.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ mediaId: claimedMedia.id,
+ traceId: expiredTraceId,
+ field: "input",
+ createdAt: daysAgo(11),
+ },
+ });
+ await prisma.observationMedia.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ mediaId: claimedMedia.id,
+ traceId: expiredTraceId,
+ observationId: randomUUID(),
+ field: "input",
+ createdAt: daysAgo(11),
+ },
+ });
+ const recentTraceId = randomUUID();
+ await prisma.traceMedia.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ mediaId: claimedMedia.id,
+ traceId: recentTraceId,
+ field: "input",
+ },
+ });
+ await prisma.observationMedia.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ mediaId: claimedMedia.id,
+ traceId: recentTraceId,
+ observationId: randomUUID(),
+ field: "input",
+ },
+ });
// Pending association (null validFrom): an abandoned upload that never
// claimed an item. It must not shield the project from the picker, and is
// swept along with its media.
- const pendingMedia = await createTestMedia(projectId, tenDaysAgo);
+ const pendingMedia = await createTestMedia(projectId, daysAgo(11));
await prisma.datasetItemMedia.create({
data: {
id: randomUUID(),
@@ -178,8 +245,47 @@ describe("MediaRetentionCleaner", () => {
referenceString: null,
},
});
+ const firstUnassociatedMedia = await createTestMedia(
+ projectId,
+ daysAgo(10),
+ );
+ const secondUnassociatedMedia = await createTestMedia(
+ projectId,
+ daysAgo(9),
+ );
- await processUntilProjectComplete(projectId);
+ await new MediaRetentionCleaner().processBatch();
+
+ expect(mockDeleteFiles).toHaveBeenCalledWith([pendingMedia.bucketPath]);
+ await expect(
+ prisma.traceMedia.findMany({
+ select: { traceId: true },
+ where: { projectId, mediaId: claimedMedia.id },
+ }),
+ ).resolves.toEqual([{ traceId: recentTraceId }]);
+ await expect(
+ prisma.observationMedia.findMany({
+ select: { traceId: true },
+ where: { projectId, mediaId: claimedMedia.id },
+ }),
+ ).resolves.toEqual([{ traceId: recentTraceId }]);
+ await expect(
+ prisma.media.count({
+ where: {
+ projectId,
+ id: {
+ in: [firstUnassociatedMedia.id, secondUnassociatedMedia.id],
+ },
+ },
+ }),
+ ).resolves.toBe(2);
+
+ await new MediaRetentionCleaner().processBatch();
+
+ expect(mockDeleteFiles).toHaveBeenLastCalledWith([
+ firstUnassociatedMedia.bucketPath,
+ secondUnassociatedMedia.bucketPath,
+ ]);
// Claimed media (and its row) survive; pending media (and its row) are gone.
await expect(
@@ -192,6 +298,16 @@ describe("MediaRetentionCleaner", () => {
where: { projectId_id: { projectId, id: pendingMedia.id } },
}),
).resolves.toBeNull();
+ await expect(
+ prisma.media.count({
+ where: {
+ projectId,
+ id: {
+ in: [firstUnassociatedMedia.id, secondUnassociatedMedia.id],
+ },
+ },
+ }),
+ ).resolves.toBe(0);
await expect(
prisma.datasetItemMedia.count({
where: { projectId, datasetItemValidFrom: { not: null } },
@@ -202,6 +318,13 @@ describe("MediaRetentionCleaner", () => {
where: { projectId, datasetItemValidFrom: null },
}),
).resolves.toBe(0);
+ await expect(
+ findExpiredMediaBatchByProjectId({
+ projectId,
+ cutoffDate: daysAgo(7),
+ limit: 2,
+ }),
+ ).resolves.toEqual([]);
});
it("should NOT delete media within retention period", async () => {
diff --git a/worker/src/features/media-retention-cleaner/index.ts b/worker/src/features/media-retention-cleaner/index.ts
index b04c00f7e4..374db73ec7 100644
--- a/worker/src/features/media-retention-cleaner/index.ts
+++ b/worker/src/features/media-retention-cleaner/index.ts
@@ -1,16 +1,16 @@
-import { prisma } from "@langfuse/shared/src/db";
import {
deleteMediaFiles,
- findExpiredMediaByProjectId,
+ findExpiredMediaBatchByProjectId,
+ findNextMediaRetentionProject,
getS3MediaStorageClient,
logger,
+ type MediaRetentionProject,
recordGauge,
recordIncrement,
removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
traceException,
} 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";
@@ -18,18 +18,11 @@ const METRIC_PREFIX = "langfuse.media_retention_cleaner";
export const MEDIA_RETENTION_CLEANER_LOCK_KEY =
"langfuse:media-retention-cleaner";
-interface ProjectWorkload {
- projectId: string;
- retentionDays: number;
- cutoffDate: Date;
- secondsPastCutoff: number | null;
-}
-
/**
* 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.
+ * Processes one project per iteration (oldest actionable media first).
* Run frequently to process all projects over time.
*/
export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
@@ -62,20 +55,20 @@ export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
}
/**
- * Process expired media for the project with most work.
+ * Process expired media for the project furthest past its cutoff.
* Preflight and deletion are both under lock to avoid redundant expensive queries.
*/
- protected async execute(): Promise<void> {
+ protected async execute(): Promise<number> {
// Reset gauge before attempting lock - ensures it doesn't appear stuck
// if another worker holds the lock
recordGauge(`${METRIC_PREFIX}.seconds_past_cutoff`, 0);
- await this.withLock(
+ const nextDelayMs = await this.withLock(
async () => {
- // Get the project with most expired media (single project per iteration)
- let workload: ProjectWorkload | null;
+ // Get the most overdue project (single project per iteration)
+ let workload: MediaRetentionProject | null;
try {
- workload = await this.getTopProjectWorkload();
+ workload = await findNextMediaRetentionProject();
} catch (error) {
logger.error(`${this.name}: Failed to query project workload`, {
error,
@@ -99,70 +92,24 @@ export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
await this.processProject(workload);
recordIncrement(`${METRIC_PREFIX}.projects_processed`, 1);
- } else {
- logger.info(`${this.name}: No expired media to clean up`);
+ // Without media storage, this workload cannot make progress.
+ return env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET
+ ? 0
+ : this.defaultIntervalMs;
}
+
+ logger.info(`${this.name}: No expired media to clean up`);
+ return this.defaultIntervalMs;
},
() => {
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 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;
- seconds_past_cutoff: number;
- }>
- >`
- SELECT
- p.id as project_id,
- p.retention_days,
- EXTRACT(EPOCH FROM (
- (NOW() - (p.retention_days || ' days')::interval) - MIN(m.created_at)
- ))::int as seconds_past_cutoff
- FROM projects p
- INNER JOIN media m ON m.project_id = p.id
- -- Only a claimed association (validFrom set) protects media; pending rows
- -- (null validFrom) are sweepable, matching deleteMediaFiles. Counting them
- -- here would hide projects whose only expired media is abandoned uploads.
- LEFT JOIN dataset_item_media dim
- ON dim.project_id = m.project_id
- AND dim.media_id = m.id
- AND dim.dataset_item_valid_from IS NOT NULL
- WHERE p.retention_days > 0
- AND p.deleted_at IS NULL
- AND m.created_at <= NOW() - (p.retention_days || ' days')::interval
- AND dim.media_id IS NULL
- GROUP BY p.id, p.retention_days
- ORDER BY seconds_past_cutoff 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),
- secondsPastCutoff: row.seconds_past_cutoff,
- };
+ return nextDelayMs ?? this.defaultIntervalMs;
}
- private async processProject(workload: ProjectWorkload): Promise<void> {
+ private async processProject(workload: MediaRetentionProject): Promise<void> {
// Delete media files (S3 + PostgreSQL)
if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {
await this.deleteExpiredMedia(workload);
@@ -182,10 +129,13 @@ export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
});
}
- private async deleteExpiredMedia(workload: ProjectWorkload): Promise<void> {
- const mediaFiles = await findExpiredMediaByProjectId({
+ private async deleteExpiredMedia(
+ workload: MediaRetentionProject,
+ ): Promise<void> {
+ const mediaFiles = await findExpiredMediaBatchByProjectId({
projectId: workload.projectId,
cutoffDate: workload.cutoffDate,
+ limit: env.LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT,
});
// Record gauge for observed work
@@ -203,6 +153,7 @@ export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
storageClient: getS3MediaStorageClient(
env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET!,
),
+ linkCleanupCutoffDate: workload.cutoffDate,
});
// Record successful deletion metrics