Skip to content

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

fix: renew media retention leases during blob cleanup (#15416)

Valery Meleshkin5d28cbbab6e1
diff --git a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
index 8dd057810d..c4e346d76d 100644
--- a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
+++ b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts
@@ -35,6 +35,8 @@ type BlobCleanupPipelineOptions = {
// Refs buffered before a single tombstone insert. Larger batches mean fewer,
// bigger inserts (ClickHouse best practice; less part-count pressure).
tombstoneFlushSize?: number;
+ // Called serially after each successful S3 batch.
+ onProgress?: () => Promise<void>;
};
export const deleteIngestionEventsFromS3AndClickhouseForScores = async (
@@ -55,6 +57,7 @@ export const deleteIngestionEventsFromS3AndClickhouseForScores = async (
s3ChunkSize: p.s3ChunkSize,
s3Concurrency: p.s3Concurrency,
tombstoneFlushSize: p.tombstoneFlushSize,
+ onProgress: p.onProgress,
});
};
@@ -78,6 +81,7 @@ export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces =
s3ChunkSize: p.s3ChunkSize,
s3Concurrency: p.s3Concurrency,
tombstoneFlushSize: p.tombstoneFlushSize,
+ onProgress: p.onProgress,
});
};
@@ -96,6 +100,7 @@ export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject = (
s3ChunkSize: options?.s3ChunkSize,
s3Concurrency: options?.s3Concurrency,
tombstoneFlushSize: options?.tombstoneFlushSize,
+ onProgress: options?.onProgress,
});
};
@@ -183,6 +188,7 @@ async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(
BlobStorageFileRefRecordReadType[]
>) {
pendingTombstones.push(...deletedRefs);
+ await p.onProgress?.();
if (pendingTombstones.length >= tombstoneFlushSize) {
await flushTombstones();
}
diff --git a/worker/src/__tests__/ingestionFileDeletion.test.ts b/worker/src/__tests__/ingestionFileDeletion.test.ts
index 2601f86c01..af8c02e99e 100644
--- a/worker/src/__tests__/ingestionFileDeletion.test.ts
+++ b/worker/src/__tests__/ingestionFileDeletion.test.ts
@@ -141,6 +141,36 @@ describe("ingestion file deletion pipeline", () => {
}
});
+ it("checkpoints a deleted S3 batch when progress reporting fails", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await seedRefs(projectId, 1, { uploadFiles: false });
+
+ const eventStorageClient = getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ );
+ const deleteFilesSpy = vi
+ .spyOn(eventStorageClient, "deleteFiles")
+ .mockResolvedValue(undefined);
+ const onProgress = vi.fn().mockRejectedValue(new Error("lease lost"));
+
+ await expect(
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
+ projectId,
+ undefined,
+ {
+ s3ChunkSize: 1,
+ s3Concurrency: 1,
+ tombstoneFlushSize: 100,
+ onProgress,
+ },
+ ),
+ ).rejects.toThrow("lease lost");
+
+ expect(deleteFilesSpy).toHaveBeenCalledOnce();
+ expect(onProgress).toHaveBeenCalledOnce();
+ expect(await visibleBucketPaths(projectId)).toHaveLength(0);
+ });
+
it("rethrows on a failed chunk, tombstones only the chunks that succeeded, and leaves the failed chunk retry-able", async () => {
const { projectId } = await createOrgProjectAndApiKey();
await seedRefs(projectId, 13);
diff --git a/worker/src/__tests__/mediaRetentionCleaner.test.ts b/worker/src/__tests__/mediaRetentionCleaner.test.ts
index 3d036657ed..78499df1d6 100644
--- a/worker/src/__tests__/mediaRetentionCleaner.test.ts
+++ b/worker/src/__tests__/mediaRetentionCleaner.test.ts
@@ -5,6 +5,7 @@ import {
findExpiredMediaBatchByProjectId,
findNextMediaRetentionProject,
getS3MediaStorageClient,
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { MediaRetentionCleaner } from "../features/media-retention-cleaner";
@@ -37,6 +38,12 @@ vi.mock("../env", async () => {
const mockDeleteFiles = vi.fn().mockResolvedValue(undefined);
const mockS3Client = { deleteFiles: mockDeleteFiles };
+class TestMediaRetentionCleaner extends MediaRetentionCleaner {
+ public getLockForTest() {
+ return this.lock;
+ }
+}
+
async function createTestMedia(
projectId: string,
createdAt: Date,
@@ -106,6 +113,64 @@ describe("MediaRetentionCleaner", () => {
});
describe("processBatch", () => {
+ it("keeps the project retryable when blob cleanup loses the lock", 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 originalBlobStorageFlag = env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG;
+ Object.assign(env, {
+ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG: "true",
+ });
+
+ let now = Date.now();
+ const dateNowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
+ try {
+ const cleaner = new TestMediaRetentionCleaner();
+ const extendSpy = vi
+ .spyOn(cleaner.getLockForTest(), "extend")
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+ let cleanupFinished = false;
+ vi.mocked(
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
+ ).mockImplementation(async (_projectId, _cutoffDate, options) => {
+ now += 6 * 60 * 1000;
+ await options?.onProgress?.();
+ cleanupFinished = true;
+ });
+
+ await cleaner.processBatch();
+
+ expect(extendSpy).toHaveBeenCalledTimes(2);
+ expect(cleanupFinished).toBe(false);
+ await expect(getMediaCount(projectId)).resolves.toBe(1);
+ await expect(findNextMediaRetentionProject()).resolves.toEqual(
+ expect.objectContaining({ projectId }),
+ );
+ expect(
+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject,
+ ).toHaveBeenCalledWith(
+ projectId,
+ expect.any(Date),
+ expect.objectContaining({ onProgress: expect.any(Function) }),
+ );
+ } finally {
+ dateNowSpy.mockRestore();
+ Object.assign(env, {
+ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG: originalBlobStorageFlag,
+ });
+ }
+ });
+
it("runs again immediately after work and waits when empty", async () => {
await drainExpiredMedia();
diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.ts
index 722d1a637f..ec76d52dd3 100644
--- a/worker/src/features/batch-data-retention-cleaner/index.ts
+++ b/worker/src/features/batch-data-retention-cleaner/index.ts
@@ -15,7 +15,10 @@ import {
} from "@langfuse/shared/src/server";
import { env } from "../../env";
import { getRetentionCutoffDate } from "../utils";
-import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";
+import {
+ PeriodicExclusiveRunner,
+ PeriodicExclusiveRunnerLeaseLostError,
+} from "../../utils/PeriodicExclusiveRunner";
// Tables for batch data retention cleaning (ClickHouse only; also no dataset_run_items)
export const BATCH_DATA_RETENTION_TABLES = [
@@ -31,13 +34,6 @@ export type BatchDataRetentionTable =
const METRIC_PREFIX = "langfuse.batch_data_retention_cleaner";
-class BatchDataRetentionCleanerLeaseLostError extends Error {
- constructor(tableName: BatchDataRetentionTable) {
- super(`Batch data retention cleaner lost its lease for ${tableName}`);
- this.name = "BatchDataRetentionCleanerLeaseLostError";
- }
-}
-
export const BATCH_DATA_RETENTION_CLEANER_LOCK_PREFIX =
"langfuse:batch-data-retention-cleaner";
@@ -143,9 +139,6 @@ function buildRetentionConditions(
export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
private readonly tableName: BatchDataRetentionTable;
private readonly candidateQueryHttpTimeoutSeconds: number;
- private readonly lockExtensionMinIntervalMs: number;
- private lastLockExtensionAt = 0;
- private lockExtensionInFlight: Promise<void> | null = null;
protected get defaultIntervalMs(): number {
return env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_INTERVAL_MS;
@@ -176,7 +169,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
this.candidateQueryHttpTimeoutSeconds = Math.ceil(
candidateQueryTimeoutMs / 1000,
);
- this.lockExtensionMinIntervalMs = Math.floor((lockTtlSeconds * 1000) / 3);
}
/**
@@ -196,39 +188,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
super.start();
}
- /**
- * Renew the lease when work advances, without issuing one Redis command per
- * streamed row. A failed renewal means this worker no longer owns the batch.
- */
- private async extendLockOnProgress(force = false): Promise<void> {
- if (
- !force &&
- Date.now() - this.lastLockExtensionAt < this.lockExtensionMinIntervalMs
- ) {
- return;
- }
-
- if (this.lockExtensionInFlight) {
- return this.lockExtensionInFlight;
- }
-
- const extension = (async () => {
- if (!(await this.lock.extend())) {
- throw new BatchDataRetentionCleanerLeaseLostError(this.tableName);
- }
- this.lastLockExtensionAt = Date.now();
- })();
- this.lockExtensionInFlight = extension;
-
- try {
- await extension;
- } finally {
- if (this.lockExtensionInFlight === extension) {
- this.lockExtensionInFlight = null;
- }
- }
- }
-
/**
* Process a batch for data retention for this table.
* Preflight and deletion are both under lock to avoid redundant expensive queries.
@@ -247,10 +206,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
await this.withLock(
async () => {
- // Each acquisition starts a fresh lease, so progress in a prior run
- // must not throttle the first renewal in this one.
- this.lastLockExtensionAt = 0;
-
// Step 1: Get project workloads (streamed CH candidates + PG config)
const { observedWorkloads, selectedWorkloads, lagMeasurementComplete } =
await this.getProjectWorkloads();
@@ -417,7 +372,7 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
complete: discovery.complete && enrichment.complete,
};
} catch (error) {
- if (error instanceof BatchDataRetentionCleanerLeaseLostError) {
+ if (error instanceof PeriodicExclusiveRunnerLeaseLostError) {
leaseLost = true;
}
throw error;
@@ -534,7 +489,7 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
await this.extendLockOnProgress();
}
} catch (error) {
- if (error instanceof BatchDataRetentionCleanerLeaseLostError) {
+ if (error instanceof PeriodicExclusiveRunnerLeaseLostError) {
throw error;
}
complete = false;
@@ -658,7 +613,7 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
await this.extendLockOnProgress();
return { workloads, complete: true };
} catch (error) {
- if (error instanceof BatchDataRetentionCleanerLeaseLostError) {
+ if (error instanceof PeriodicExclusiveRunnerLeaseLostError) {
throw error;
}
// Preserve the APM error, but let a successful retry keep the runner outcome healthy.
@@ -684,7 +639,7 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {
await this.extendLockOnProgress();
return { workloads, complete: true };
} catch (retryError) {
- if (retryError instanceof BatchDataRetentionCleanerLeaseLostError) {
+ if (retryError instanceof PeriodicExclusiveRunnerLeaseLostError) {
throw retryError;
}
diff --git a/worker/src/features/media-retention-cleaner/index.ts b/worker/src/features/media-retention-cleaner/index.ts
index 1d531b1c56..437172b50b 100644
--- a/worker/src/features/media-retention-cleaner/index.ts
+++ b/worker/src/features/media-retention-cleaner/index.ts
@@ -109,19 +109,21 @@ export class MediaRetentionCleaner extends PeriodicExclusiveRunner {
}
private async processProject(workload: MediaRetentionProject): Promise<void> {
- // Delete media files (S3 + PostgreSQL)
- if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {
- await this.deleteExpiredMedia(workload);
- }
-
// Delete blob storage entries (S3 + ClickHouse soft delete)
if (env.LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG === "true") {
+ await this.extendLockOnProgress();
await removeIngestionEventsFromS3AndDeleteClickhouseRefsForProject(
workload.projectId,
workload.cutoffDate,
+ { onProgress: () => this.extendLockOnProgress() },
);
}
+ // Delete media files (S3 + PostgreSQL)
+ if (env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {
+ await this.deleteExpiredMedia(workload);
+ }
+
logger.info(`${this.name}: Project processed`, {
projectId: workload.projectId,
retentionDays: workload.retentionDays,
diff --git a/worker/src/utils/PeriodicExclusiveRunner.ts b/worker/src/utils/PeriodicExclusiveRunner.ts
index 0d33d0e1e8..c9db61b6c7 100644
--- a/worker/src/utils/PeriodicExclusiveRunner.ts
+++ b/worker/src/utils/PeriodicExclusiveRunner.ts
@@ -2,6 +2,13 @@ import { logger, getCurrentSpan } from "@langfuse/shared/src/server";
import { PeriodicRunner } from "./PeriodicRunner";
import { OnUnavailableBehavior, RedisLock } from "./RedisLock";
+export class PeriodicExclusiveRunnerLeaseLostError extends Error {
+ constructor(runnerName: string) {
+ super(`${runnerName} lost its lease`);
+ this.name = "PeriodicExclusiveRunnerLeaseLostError";
+ }
+}
+
/**
* Abstract base class for periodic tasks that require distributed locking.
*
@@ -14,6 +21,9 @@ import { OnUnavailableBehavior, RedisLock } from "./RedisLock";
export abstract class PeriodicExclusiveRunner extends PeriodicRunner {
protected readonly instanceName: string;
protected readonly lock: RedisLock;
+ private readonly lockExtensionMinIntervalMs: number;
+ private lastLockExtensionAt = 0;
+ private lockExtensionInFlight: Promise<void> | null = null;
constructor(params: {
name: string;
@@ -31,6 +41,9 @@ export abstract class PeriodicExclusiveRunner extends PeriodicRunner {
onUnavailable: params.onUnavailable || "proceed",
onError: (error) => this.markRunFailed(error),
});
+ this.lockExtensionMinIntervalMs = Math.floor(
+ (params.lockTtlSeconds * 1000) / 3,
+ );
}
protected get name(): string {
@@ -49,6 +62,39 @@ export abstract class PeriodicExclusiveRunner extends PeriodicRunner {
return this.execute();
}
+ /**
+ * Renew the lease when work advances, without issuing one Redis command per
+ * progress event. Concurrent callers share the same renewal.
+ */
+ protected async extendLockOnProgress(force = false): Promise<void> {
+ if (
+ !force &&
+ Date.now() - this.lastLockExtensionAt < this.lockExtensionMinIntervalMs
+ ) {
+ return;
+ }
+
+ if (this.lockExtensionInFlight) {
+ return this.lockExtensionInFlight;
+ }
+
+ const extension = (async () => {
+ if (!(await this.lock.extend())) {
+ throw new PeriodicExclusiveRunnerLeaseLostError(this.instanceName);
+ }
+ this.lastLockExtensionAt = Date.now();
+ })();
+ this.lockExtensionInFlight = extension;
+
+ try {
+ await extension;
+ } finally {
+ if (this.lockExtensionInFlight === extension) {
+ this.lockExtensionInFlight = null;
+ }
+ }
+ }
+
/**
* Execute operation under distributed lock.
* Returns operation result, onFailure result, or undefined if lock not acquired.
@@ -58,6 +104,7 @@ export abstract class PeriodicExclusiveRunner extends PeriodicRunner {
onFailure?: (error: unknown) => T | Promise<T | void> | void,
): Promise<T | undefined> {
const result = await this.lock.withLock(async () => {
+ this.lastLockExtensionAt = 0;
try {
return await operation();
} catch (error) {