Skip to content

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

fix: coalesce batch cleaner count queries across workers (#15495)

Valery Meleshkin715543684a87
diff --git a/worker/src/__tests__/batchProjectCleaner.test.ts b/worker/src/__tests__/batchProjectCleaner.test.ts
index 0b6c4ab92f..7f07f7908c 100644
--- a/worker/src/__tests__/batchProjectCleaner.test.ts
+++ b/worker/src/__tests__/batchProjectCleaner.test.ts
@@ -3,6 +3,7 @@ import { randomUUID } from "crypto";
import {
BatchProjectCleaner,
BATCH_DELETION_TABLES,
+ BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY,
BATCH_PROJECT_CLEANER_LOCK_PREFIX,
} from "../features/batch-project-cleaner";
import {
@@ -19,8 +20,13 @@ import { env } from "../env";
import type { RedisLock } from "../utils/RedisLock";
type TestableBatchProjectCleaner = {
+ countQueryLock: RedisLock;
lock: RedisLock;
+ getCountsAfterDeleteFailure: (
+ projectIds: string[],
+ ) => Promise<Map<string, number> | undefined>;
getProjectCounts: (projectIds: string[]) => Promise<Map<string, number>>;
+ markRunFailed: (error: unknown) => void;
};
async function getClickhouseCount(
@@ -40,6 +46,7 @@ describe("BatchProjectCleaner", () => {
// Clean up Redis locks after each test
afterEach(async () => {
+ await redis?.del(BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY);
for (const table of BATCH_DELETION_TABLES) {
await redis?.del(`${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:${table}`);
}
@@ -220,8 +227,66 @@ describe("BatchProjectCleaner", () => {
// 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,
+ env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS,
+ );
+ });
+
+ it("should back off when the global count lock is held", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { deletedAt: new Date() },
+ });
+ await redis?.set(
+ BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY,
+ "locked",
+ "EX",
+ 60,
+ "NX",
);
+
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const getProjectCountsSpy = vi.spyOn(
+ cleaner as unknown as TestableBatchProjectCleaner,
+ "getProjectCounts",
+ );
+ const nextDelayMs = await cleaner.processBatch();
+
+ expect(getProjectCountsSpy).not.toHaveBeenCalled();
+ expect(nextDelayMs).toBeGreaterThanOrEqual(60_000);
+ expect(nextDelayMs).toBeLessThan(120_000);
+ });
+
+ it("should not fail the run when the count lock cannot be released", async () => {
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const testableCleaner = cleaner as unknown as TestableBatchProjectCleaner;
+ const markRunFailedSpy = vi.spyOn(testableCleaner, "markRunFailed");
+
+ expect(await testableCleaner.countQueryLock.acquire()).toBe("acquired");
+ await redis?.del(BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY);
+ expect(await testableCleaner.countQueryLock.release()).toBe(false);
+
+ expect(markRunFailedSpy).not.toHaveBeenCalled();
+ });
+
+ it("should bypass the count lock when rechecking a failed delete", async () => {
+ const cleaner = new BatchProjectCleaner(TEST_TABLE);
+ const testableCleaner = cleaner as unknown as TestableBatchProjectCleaner;
+ const extendSpy = vi
+ .spyOn(testableCleaner.lock, "extend")
+ .mockResolvedValue(true);
+ const acquireSpy = vi
+ .spyOn(testableCleaner.countQueryLock, "acquire")
+ .mockResolvedValue("held_by_other");
+ const countSpy = vi
+ .spyOn(testableCleaner, "getProjectCounts")
+ .mockResolvedValue(new Map());
+
+ await testableCleaner.getCountsAfterDeleteFailure(["project-id"]);
+
+ expect(extendSpy).toHaveBeenCalledOnce();
+ expect(acquireSpy).not.toHaveBeenCalled();
+ expect(countSpy).toHaveBeenCalledWith(["project-id"]);
});
it("should release lock after processing completes", async () => {
diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.ts
index 8feb3aed15..e342224582 100644
--- a/worker/src/features/batch-project-cleaner/index.ts
+++ b/worker/src/features/batch-project-cleaner/index.ts
@@ -16,42 +16,50 @@ export const BATCH_DELETION_TABLES = [
] as const;
import { env } from "../../env";
import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";
+import { RedisLock } from "../../utils/RedisLock";
export type BatchDeletionTable = (typeof BATCH_DELETION_TABLES)[number];
export const BATCH_PROJECT_CLEANER_LOCK_PREFIX =
"langfuse:batch-project-cleaner";
+export const BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY = `${BATCH_PROJECT_CLEANER_LOCK_PREFIX}:count-query`;
+
+// Safety net for an abandoned lock; successful count queries release it immediately.
+const COUNT_LOCK_TTL_SECONDS = 10 * 60;
+const COUNT_LOCK_RETRY_MIN_MS = 60_000;
+const COUNT_LOCK_RETRY_JITTER_MS = 60_000;
interface ProjectCount {
project_id: string;
count: number;
}
+interface DeleteAttempt {
+ projectIds?: string[];
+}
+
/**
* BatchProjectCleaner handles bulk deletion of ClickHouse data for soft-deleted projects.
*
* Each instance processes one table (traces, observations, scores, events_full, events_core).
- * Multiple workers coordinate via Redis distributed locking to ensure only one
- * worker deletes from a given table at a time.
+ * Multiple workers coordinate via Redis to ensure that only one cleaner runs
+ * per table and only one ClickHouse count query runs across all tables.
*
* Flow:
* 1. Query PG for projects with deleted_at set (no lock needed)
* 2. Acquire the per-table Redis lock
- * 3. Query ClickHouse for counts per project
- * 4. Renew the lock and execute DELETE
- * 5. On failure: re-run count query before releasing the lock
+ * 3. Acquire the global count-query lock and query ClickHouse
+ * 4. Renew the per-table lock and execute DELETE
+ * 5. On failure: renew the per-table lock and re-run the count query directly
*/
export class BatchProjectCleaner extends PeriodicExclusiveRunner {
private readonly tableName: BatchDeletionTable;
+ private readonly countQueryLock: RedisLock;
protected get defaultIntervalMs(): number {
return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
}
- protected get initialDelayMs(): number {
- return BATCH_DELETION_TABLES.indexOf(this.tableName) * 10_000;
- }
-
constructor(tableName: BatchDeletionTable) {
// TTL = DELETE timeout + 5 minutes buffer
const lockTtlSeconds =
@@ -67,6 +75,11 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {
onUnavailable: "fail",
});
this.tableName = tableName;
+ this.countQueryLock = new RedisLock(BATCH_PROJECT_CLEANER_COUNT_LOCK_KEY, {
+ ttlSeconds: COUNT_LOCK_TTL_SECONDS,
+ name: `${this.instanceName}:count-query`,
+ onUnavailable: "fail",
+ });
}
/**
@@ -93,122 +106,173 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {
* 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 }>;
+ const deletedProjectIds = await this.getDeletedProjectIds();
+ if (!deletedProjectIds) {
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ const deleteAttempt: DeleteAttempt = {};
+ const nextDelayMs = await this.withLock(
+ () => this.processDeletedProjects(deletedProjectIds, deleteAttempt),
+ (error) => this.handleDeleteFailure(error, deleteAttempt.projectIds),
+ );
+
+ return nextDelayMs ?? env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;
+ }
+
+ private async getDeletedProjectIds(): Promise<string[] | undefined> {
try {
- deletedProjects = await getDeletedProjects(
+ const deletedProjects = await getDeletedProjects(
env.LANGFUSE_BATCH_PROJECT_CLEANER_PROJECT_LIMIT,
);
+
+ if (deletedProjects.length === 0) {
+ logger.info(`${this.instanceName}: No deleted projects found`);
+ return undefined;
+ }
+
+ return deletedProjects.map((project) => project.id);
} catch (error) {
logger.error(`${this.instanceName}: Failed to query deleted projects`, {
error,
});
this.markRunFailed(error);
+ return undefined;
+ }
+ }
+
+ private async processDeletedProjects(
+ deletedProjectIds: string[],
+ deleteAttempt: DeleteAttempt,
+ ): Promise<number> {
+ let initialCounts: Map<string, number>;
+ try {
+ const counts = await this.getProjectCountsWithLock(deletedProjectIds);
+ if (!counts) {
+ return this.getCountLockRetryDelayMs();
+ }
+ initialCounts = counts;
+ } catch (error) {
+ logger.error(
+ `${this.instanceName}: Failed to query ClickHouse counts`,
+ error,
+ );
+ this.markRunFailed(error);
return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
}
- if (deletedProjects.length === 0) {
- logger.info(`${this.instanceName}: No deleted projects found`);
+ const projectIdsWithData = Array.from(initialCounts.entries())
+ .filter(([, count]) => count > 0)
+ .map(([projectId]) => projectId);
+
+ if (projectIdsWithData.length === 0) {
+ logger.info(
+ `${this.instanceName}: No data found for deleted projects in ${this.tableName}`,
+ );
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
+ }
+
+ await this.extendLockOnProgress(true);
+ deleteAttempt.projectIds = projectIdsWithData;
+ await this.executeDelete(projectIdsWithData);
+
+ 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,
+ });
+
+ return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;
+ }
+
+ private async handleDeleteFailure(
+ error: unknown,
+ deleteAttemptProjectIds?: string[],
+ ): Promise<number> {
+ if (!deleteAttemptProjectIds) {
return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
}
- let deleteAttemptProjectIds: string[] | undefined;
+ recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {
+ table: this.tableName,
+ });
+
+ const finalCounts = await this.getCountsAfterDeleteFailure(
+ deleteAttemptProjectIds,
+ );
+ const incompleteProjects = finalCounts
+ ? deleteAttemptProjectIds.filter(
+ (projectId) => (finalCounts.get(projectId) ?? 0) > 0,
+ )
+ : deleteAttemptProjectIds;
+
+ 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;
+ }
+
+ private async getCountsAfterDeleteFailure(
+ projectIds: string[],
+ ): Promise<Map<string, number> | undefined> {
+ try {
+ await this.extendLockOnProgress(true);
+ return await this.getProjectCounts(projectIds);
+ } catch (error) {
+ logger.error(
+ `${this.instanceName}: Failed to renew lock or re-query counts after DELETE failure`,
+ error,
+ );
+ return undefined;
+ }
+ }
+
+ private async getProjectCountsWithLock(
+ projectIds: string[],
+ ): Promise<Map<string, number> | undefined> {
+ const result = await this.countQueryLock.acquire();
+
+ if (result !== "acquired") {
+ if (result === "held_by_other") {
+ this.markRunSkipped();
+ } else {
+ this.markRunFailed(
+ new Error(`${this.instanceName}: Count-query lock unavailable`),
+ );
+ }
+ return undefined;
+ }
- // Steps 2-5: Keep the entire ClickHouse count/delete cycle under the lock.
+ try {
+ return await this.getProjectCounts(projectIds);
+ } finally {
+ await this.countQueryLock.release();
+ }
+ }
+
+ private getCountLockRetryDelayMs(): number {
return (
- (await this.withLock(
- async () => {
- let initialCounts: Map<string, number>;
- try {
- initialCounts = await this.getProjectCounts(
- deletedProjects.map((p) => p.id),
- );
- } catch (error) {
- logger.error(
- `${this.instanceName}: Failed to query ClickHouse counts`,
- error,
- );
- this.markRunFailed(error);
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
- }
-
- const projectIdsWithData = Array.from(initialCounts.entries())
- .filter(([, count]) => count > 0)
- .map(([projectId]) => projectId);
-
- if (projectIdsWithData.length === 0) {
- logger.info(
- `${this.instanceName}: No data found for deleted projects in ${this.tableName}`,
- );
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
- }
-
- await this.extendLockOnProgress(true);
- deleteAttemptProjectIds = projectIdsWithData;
- await this.executeDelete(projectIdsWithData);
-
- 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,
- });
-
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_CHECK_INTERVAL_MS;
- },
- async (error) => {
- if (!deleteAttemptProjectIds) {
- return env.LANGFUSE_BATCH_PROJECT_CLEANER_SLEEP_ON_EMPTY_MS;
- }
-
- recordIncrement("langfuse.batch_project_cleaner.delete_failures", 1, {
- table: this.tableName,
- });
-
- let finalCounts: Map<string, number> | undefined;
- try {
- await this.extendLockOnProgress(true);
- finalCounts = await this.getProjectCounts(deleteAttemptProjectIds);
- } catch (countError) {
- // Can't determine partial success
- logger.error(
- `${this.instanceName}: Failed to renew lock or re-query counts after DELETE failure`,
- countError,
- );
- }
-
- // Calculate projects that couldn't be fully cleaned
- const incompleteProjects = finalCounts
- ? deleteAttemptProjectIds.filter((projectId) => {
- const finalCount = finalCounts.get(projectId) ?? 0;
- return finalCount > 0;
- })
- : deleteAttemptProjectIds;
-
- 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
+ COUNT_LOCK_RETRY_MIN_MS +
+ Math.floor(Math.random() * COUNT_LOCK_RETRY_JITTER_MS)
);
}
@@ -230,6 +294,10 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {
const results = await queryClickhouse<ProjectCount>({
query,
params: { projectIds },
+ tags: {
+ surface: "worker",
+ route: `batch-project-cleaner/${this.tableName}/count`,
+ },
});
const counts = new Map<string, number>();