🪢 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
feat: introducing deletion mask cleaner (#14035)
Valery Meleshkined8123ab2d05
diff --git a/.env.prod.example b/.env.prod.exampleindex 58404278d1..d7f3675ace 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -225,6 +225,9 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# CLICKHOUSE_USER=# CLICKHOUSE_PASSWORD=# CLICKHOUSE_CLUSTER_ENABLED=true+# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_ENABLED=false+# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_INTERVAL_MS=3600000+# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS=60000# Ingestion configuration# LANGFUSE_INGESTION_QUEUE_DELAY_MS=diff --git a/worker/src/__tests__/deletedMaskCleaner.test.ts b/worker/src/__tests__/deletedMaskCleaner.test.tsnew file mode 100644index 0000000000..50d4f2e247--- /dev/null+++ b/worker/src/__tests__/deletedMaskCleaner.test.ts@@ -0,0 +1,407 @@+import { randomUUID } from "crypto";+import {+ afterEach,+ describe,+ expect,+ it,+ beforeEach,+ type TestContext,+} from "vitest";+import {+ commandClickhouse,+ createEvent,+ createEventsCh,+ queryClickhouse,+ redis,+} from "@langfuse/shared/src/server";+import { env } from "../env";+import {+ DELETED_MASK_CLEANER_LOCK_KEY,+ DeletedMaskCleaner,+} from "../features/deleted-mask-cleaner";+import {+ buildApplyDeletedMaskQuery,+ buildMutationCountQuery,+ DELETED_MASK_CLEANER_TABLES,+ DELETED_MASK_CLEANER_WORK_QUERY,+ normalizeMutationCounts,+ selectCandidateToProcess,+ type MutationCountRow,+ type WorkCandidateRow,+} from "../features/deleted-mask-cleaner/helpers";++const TEST_TABLE = "events_full" as const;+const PATCH_WAIT_TIMEOUT_MS = 30_000;++interface TableExistsRow {+ count: number | string;+}++let eventsTableEnabled: boolean | undefined;++async function isEventsTableEnabled(): Promise<boolean> {+ if (eventsTableEnabled !== undefined) {+ return eventsTableEnabled;+ }+ try {+ const rows = await queryClickhouse<TableExistsRow>({+ query: `+ SELECT count() AS count+ FROM system.tables+ WHERE database = {database: String}+ AND name = {table: String}+ `,+ params: {+ database: env.CLICKHOUSE_DB,+ table: TEST_TABLE,+ },+ });+ eventsTableEnabled = Number(rows[0]?.count ?? 0) > 0;+ } catch {+ eventsTableEnabled = false;+ }++ return eventsTableEnabled;+}++async function skipUnlessEventsTableEnabled(ctx: TestContext): Promise<void> {+ if (!(await isEventsTableEnabled())) {+ ctx.skip("events table is not enabled in this ClickHouse");+ }++ if (!redis) {+ ctx.skip(+ "Redis must be available for DeletedMaskCleaner integration tests",+ );+ }+}++async function eventually<T>(+ getValue: () => Promise<T>,+ predicate: (value: T) => boolean,+ message: string,+): Promise<T> {+ const deadline = Date.now() + PATCH_WAIT_TIMEOUT_MS;+ let lastValue: T | undefined;++ while (Date.now() < deadline) {+ lastValue = await getValue();+ if (predicate(lastValue)) {+ return lastValue;+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ }++ throw new Error(`${message}. Last value: ${JSON.stringify(lastValue)}`);+}++function getRandomPastMonthPartition(): string {+ const randomValue = Number.parseInt(randomUUID().slice(0, 8), 16);+ const year = 2010 + (randomValue % 15);+ const month = Math.floor(randomValue / 15) % 12;++ return `${year}${String(month + 1).padStart(2, "0")}`;+}++function getTimestampForMonthPartition(partition: string): number {+ const year = Number(partition.slice(0, 4));+ const zeroBasedMonth = Number(partition.slice(4, 6)) - 1;++ return Date.UTC(year, zeroBasedMonth, 15, 12, 0, 0);+}++function workCandidate(+ overrides: Partial<WorkCandidateRow> = {},+): WorkCandidateRow {+ return {+ partition: "patch-a-202405",+ table: "scores",+ partition_to_clean: "202405",+ total_rows: 10,+ ...overrides,+ };+}++async function hasCleanerCandidate(partitionToClean: string): Promise<boolean> {+ const rows = await queryClickhouse<WorkCandidateRow>({+ query: DELETED_MASK_CLEANER_WORK_QUERY,+ params: {+ database: env.CLICKHOUSE_DB,+ tables: Array.from(DELETED_MASK_CLEANER_TABLES),+ },+ });++ return rows.some(+ (row) =>+ row.table === TEST_TABLE && row.partition_to_clean === partitionToClean,+ );+}++async function waitForCleanerCandidate(+ partitionToClean: string,+): Promise<void> {+ await eventually(+ () => hasCleanerCandidate(partitionToClean),+ (hasCandidate) => hasCandidate,+ `Timed out waiting for ClickHouse patch part ${partitionToClean}`,+ );+}++async function waitForCleanerCandidateGone(+ partitionToClean: string,+): Promise<void> {+ await eventually(+ () => hasCleanerCandidate(partitionToClean),+ (hasCandidate) => !hasCandidate,+ `Timed out waiting for ClickHouse patch part ${partitionToClean} to be cleaned`,+ );+}++async function getActiveMutationCount(+ table: string = TEST_TABLE,+): Promise<number> {+ const rows = await queryClickhouse<MutationCountRow>({+ query: buildMutationCountQuery(+ env.CLICKHOUSE_CLUSTER_ENABLED === "true",+ env.CLICKHOUSE_CLUSTER_NAME,+ ),+ params: {+ database: env.CLICKHOUSE_DB,+ tables: [table],+ },+ });++ return Number(rows[0]?.mutation_count ?? 0);+}++async function waitForNoActiveMutations(): Promise<void> {+ await eventually(+ () => getActiveMutationCount(TEST_TABLE),+ (mutationCount) => mutationCount === 0,+ "Timed out waiting for ClickHouse mutations to finish",+ );+}++async function applyDeletedMaskIfNeeded(+ partitionToClean: string,+): Promise<void> {+ if (!(await hasCleanerCandidate(partitionToClean))) {+ return;+ }++ await commandClickhouse({+ query: buildApplyDeletedMaskQuery(+ {+ partition: `patch-cleanup-${partitionToClean}`,+ table: TEST_TABLE,+ partition_to_clean: partitionToClean,+ total_rows: 0,+ },+ {+ database: env.CLICKHOUSE_DB,+ clusterEnabled: env.CLICKHOUSE_CLUSTER_ENABLED === "true",+ clusterName: env.CLICKHOUSE_CLUSTER_NAME,+ },+ ),+ });++ await waitForNoActiveMutations();+ await waitForCleanerCandidateGone(partitionToClean);+}++async function createEventPatchParts(+ partitions: Array<{+ partition: string;+ timestamp: number;+ rows: number;+ }>,+): Promise<string> {+ const projectId = randomUUID();++ await createEventsCh(+ partitions.flatMap(({ timestamp, rows, partition }) =>+ Array.from({ length: rows }, () =>+ createEvent({+ project_id: projectId,+ trace_id: randomUUID(),+ span_id: randomUUID(),+ name: `deleted-mask-cleaner-${partition}`,+ start_time: timestamp * 1000,+ end_time: timestamp * 1000,+ created_at: timestamp * 1000,+ updated_at: timestamp * 1000,+ event_ts: timestamp * 1000,+ }),+ ),+ ),+ );++ await commandClickhouse({+ query: `DELETE FROM ${TEST_TABLE} WHERE project_id = {projectId: String}`,+ params: { projectId },+ clickhouseSettings: {+ lightweight_delete_mode: "lightweight_update_force",+ update_parallel_mode: "sync",+ lightweight_deletes_sync: 2,+ },+ });++ for (const { partition } of partitions) {+ await waitForCleanerCandidate(partition);+ }++ return projectId;+}++describe("DeletedMaskCleaner helpers", () => {+ it("normalizes missing mutation rows to zero counts", () => {+ expect(+ normalizeMutationCounts(+ ["traces", "scores"],+ [{ table: "traces", mutation_count: "3" }],+ ),+ ).toEqual(+ new Map([+ ["traces", 3],+ ["scores", 0],+ ]),+ );+ });++ it("selects the first candidate without active table mutations", () => {+ const candidates: WorkCandidateRow[] = [+ workCandidate({+ table: "traces",+ total_rows: 10,+ }),+ workCandidate({+ partition: "patch-b-202404",+ partition_to_clean: "202404",+ total_rows: 5,+ }),+ ];++ const selection = selectCandidateToProcess(+ candidates,+ new Map([+ ["traces", 1],+ ["scores", 0],+ ]),+ );++ expect(selection.candidate).toEqual(candidates[1]);+ expect(selection.skipped).toEqual([+ { candidate: candidates[0], mutationCount: 1 },+ ]);+ });++ it("returns no candidate when all target tables have active mutations", () => {+ const candidate = workCandidate();++ expect(+ selectCandidateToProcess([candidate], new Map([["scores", 2]])).candidate,+ ).toBeNull();+ });++ it("builds clustered and unclustered APPLY DELETED MASK statements", () => {+ const candidate = workCandidate({+ table: "observations",+ });++ expect(+ buildApplyDeletedMaskQuery(candidate, {+ database: "default",+ clusterEnabled: false,+ }),+ ).toBe(+ "ALTER TABLE `default`.`observations` APPLY DELETED MASK IN PARTITION '202405'",+ );+ expect(+ buildApplyDeletedMaskQuery(candidate, {+ database: "default",+ clusterEnabled: true,+ clusterName: "default",+ }),+ ).toBe(+ "ALTER TABLE `default`.`observations` ON CLUSTER `default` APPLY DELETED MASK IN PARTITION '202405'",+ );+ });++ it("quotes ClickHouse DDL identifiers with non-bare identifier characters", () => {+ expect(+ buildApplyDeletedMaskQuery(workCandidate({ table: "events_full" }), {+ database: "langfuse-prod",+ clusterEnabled: true,+ clusterName: "prod-cluster",+ }),+ ).toBe(+ "ALTER TABLE `langfuse-prod`.`events_full` ON CLUSTER `prod-cluster` APPLY DELETED MASK IN PARTITION '202405'",+ );+ });++ it("rejects empty DDL identifiers and unsafe partition ids", () => {+ const candidate = workCandidate();++ expect(() =>+ buildApplyDeletedMaskQuery(candidate, {+ database: "",+ clusterEnabled: false,+ }),+ ).toThrow("Invalid ClickHouse database");+ expect(() =>+ buildApplyDeletedMaskQuery(+ {+ ...candidate,+ partition_to_clean: "202405'; DROP TABLE scores; --",+ },+ {+ database: "default",+ clusterEnabled: false,+ },+ ),+ ).toThrow("Invalid ClickHouse month partition");+ expect(() => buildMutationCountQuery(true, "")).toThrow(+ "Invalid ClickHouse cluster",+ );+ });+});++describe.sequential("DeletedMaskCleaner integration", () => {+ const cleanupPartitions = new Set<string>();++ beforeEach(async () => {+ await redis?.del(DELETED_MASK_CLEANER_LOCK_KEY);+ }, 30_000);++ afterEach(async () => {+ await redis?.del(DELETED_MASK_CLEANER_LOCK_KEY);+ for (const partition of cleanupPartitions) {+ await applyDeletedMaskIfNeeded(partition);+ }+ cleanupPartitions.clear();+ }, 90_000);++ it("applies a deleted mask for a real events patch partition", async (ctx) => {+ await skipUnlessEventsTableEnabled(ctx);++ const partitionToClean = getRandomPastMonthPartition();+ cleanupPartitions.add(partitionToClean);++ await createEventPatchParts([+ {+ partition: partitionToClean,+ timestamp: getTimestampForMonthPartition(partitionToClean),+ rows: 256,+ },+ ]);++ await expect(hasCleanerCandidate(partitionToClean)).resolves.toBe(true);++ const cleaner = new DeletedMaskCleaner();+ await cleaner.processBatch();++ await waitForNoActiveMutations();+ await waitForCleanerCandidateGone(partitionToClean);+ expect(await redis?.get(DELETED_MASK_CLEANER_LOCK_KEY)).toBeNull();+ }, 90_000);+});diff --git a/worker/src/app.ts b/worker/src/app.tsindex 940424f895..ad2f5dde9a 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -94,6 +94,7 @@ import { BatchTraceDeletionCleaner } from "./features/batch-trace-deletion-cleanimport { BatchProjectMediaCleaner } from "./features/batch-project-media-cleaner";import { BatchProjectBlobCleaner } from "./features/batch-project-blob-cleaner";import { QueueMetricsRunner } from "./features/queue-metrics-runner";+import { DeletedMaskCleaner } from "./features/deleted-mask-cleaner";const app = express();@@ -705,6 +706,14 @@ if (env.LANGFUSE_BATCH_TRACE_DELETION_CLEANER_ENABLED === "true") {batchTraceDeletionCleaner.start();}+// ClickHouse deleted-mask cleaner for physically applying lightweight delete masks+export let deletedMaskCleaner: DeletedMaskCleaner | null = null;++if (env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_ENABLED === "true") {+ deletedMaskCleaner = new DeletedMaskCleaner();+ deletedMaskCleaner.start();+}+// Queue metrics background reporterexport let queueMetricsRunner: QueueMetricsRunner | null = null;diff --git a/worker/src/env.ts b/worker/src/env.tsindex f4883ff0f8..10ed34f02d 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -405,6 +405,19 @@ const EnvSchema = z.object({.positive().default(3_600_000), // 1 hour for DELETE operations+ // ClickHouse deleted-mask cleaner configuration+ LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_ENABLED: z+ .enum(["true", "false"])+ .default("false"),+ LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_INTERVAL_MS: z.coerce+ .number()+ .positive()+ .default(3_600_000), // 1 hour between runs+ LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS: z.coerce+ .number()+ .positive()+ .default(60_000), // Wait up to 1 minute for ALTER submission; mutation can run for hours+// Media Retention Cleaner configuration (S3/PostgreSQL)LANGFUSE_MEDIA_RETENTION_CLEANER_ITEM_LIMIT: z.coerce.number()diff --git a/worker/src/features/deleted-mask-cleaner/helpers.ts b/worker/src/features/deleted-mask-cleaner/helpers.tsnew file mode 100644index 0000000000..15a09628d0--- /dev/null+++ b/worker/src/features/deleted-mask-cleaner/helpers.ts@@ -0,0 +1,183 @@+export const DELETED_MASK_CLEANER_TABLES = [+ "events_core",+ "events_full",+ "traces",+ "observations",+ "scores",+] as const;++const DELETED_MASK_CLEANER_TABLE_SET = new Set<string>(+ DELETED_MASK_CLEANER_TABLES,+);+const MONTH_PARTITION_REGEX = /^\d{6}$/;++export interface WorkCandidateRow {+ partition: string;+ table: string;+ partition_to_clean: string;+ total_rows: number | string;+}++export interface ClickHouseDdlConfig {+ database: string;+ clusterEnabled: boolean;+ clusterName?: string;+}++export interface CandidateSelection {+ candidate: WorkCandidateRow | null;+ skipped: Array<{+ candidate: WorkCandidateRow;+ mutationCount: number;+ }>;+}++export interface MutationCountRow {+ table: string;+ mutation_count: number | string;+}++export const DELETED_MASK_CLEANER_WORK_QUERY = `+ SELECT+ partition,+ table,+ splitByString('-', partition)[3] AS partition_to_clean,+ sum(rows) AS total_rows+ FROM system.parts+ WHERE table IN ({tables: Array(String)})+ AND database = {database: String}+ AND partition LIKE 'patch-%'+ AND partition_to_clean <> ''+ AND partition_to_clean <> toString(toYYYYMM(now()))+ AND active = 1+ GROUP BY partition, table+ ORDER BY total_rows DESC, table+ LIMIT 1 BY table+`;++function assertClickHouseName(value: string, label: string): void {+ if (value.length === 0 || value.includes("\0")) {+ throw new Error(`Invalid ClickHouse ${label}: ${value}`);+ }+}++export function isDeletedMaskCleanerTable(table: string): boolean {+ return DELETED_MASK_CLEANER_TABLE_SET.has(table);+}++function assertTargetTable(table: string): void {+ if (!isDeletedMaskCleanerTable(table)) {+ throw new Error(`Invalid ClickHouse table: ${table}`);+ }+}++function assertMonthPartition(partition: string): void {+ if (!MONTH_PARTITION_REGEX.test(partition)) {+ throw new Error(`Invalid ClickHouse month partition: ${partition}`);+ }+}++function quoteClickhouseString(value: string): string {+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;+}++function quoteClickhouseIdentifier(value: string, label: string): string {+ assertClickHouseName(value, label);+ return `\`${value.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}\``;+}++export function isAbortError(error: unknown): boolean {+ if (!(error instanceof Error)) {+ return false;+ }++ return (+ error.name === "AbortError" ||+ error.message.toLowerCase().includes("aborted")+ );+}++export function selectCandidateToProcess(+ candidates: WorkCandidateRow[],+ mutationCounts: Map<string, number>,+): CandidateSelection {+ const skipped: CandidateSelection["skipped"] = [];++ for (const candidate of candidates) {+ const mutationCount = mutationCounts.get(candidate.table) ?? 0;+ if (mutationCount > 0) {+ skipped.push({ candidate, mutationCount });+ continue;+ }++ return { candidate, skipped };+ }++ return { candidate: null, skipped };+}++export function normalizeMutationCounts(+ tables: string[],+ rows: MutationCountRow[],+): Map<string, number> {+ const mutationCounts = new Map<string, number>();+ for (const table of tables) {+ mutationCounts.set(table, 0);+ }++ for (const row of rows) {+ if (mutationCounts.has(row.table)) {+ mutationCounts.set(row.table, Number(row.mutation_count));+ }+ }++ return mutationCounts;+}++export function buildApplyDeletedMaskQuery(+ candidate: WorkCandidateRow,+ config: ClickHouseDdlConfig,+): string {+ const database = quoteClickhouseIdentifier(config.database, "database");+ assertTargetTable(candidate.table);+ const table = quoteClickhouseIdentifier(candidate.table, "table");+ assertMonthPartition(candidate.partition_to_clean);++ const clusterClause = config.clusterEnabled+ ? (() => {+ if (!config.clusterName) {+ throw new Error(+ "ClickHouse cluster name is required in cluster mode",+ );+ }+ return ` ON CLUSTER ${quoteClickhouseIdentifier(config.clusterName, "cluster")}`;+ })()+ : "";++ return `ALTER TABLE ${database}.${table}${clusterClause} APPLY DELETED MASK IN PARTITION '${candidate.partition_to_clean}'`;+}++export function buildMutationCountQuery(+ clusterEnabled: boolean,+ clusterName: string,+): string {+ if (clusterEnabled) {+ assertClickHouseName(clusterName, "cluster");+ }++ const mutationSource = clusterEnabled+ ? `clusterAllReplicas(${quoteClickhouseString(clusterName)}, 'system.mutations')`+ : "system.mutations";++ return `+ SELECT+ database,+ table,+ count() AS mutation_count+ FROM ${mutationSource}+ WHERE database = {database: String}+ AND table IN ({tables: Array(String)})+ AND is_done = 0+ GROUP BY database, table+ `;+}diff --git a/worker/src/features/deleted-mask-cleaner/index.ts b/worker/src/features/deleted-mask-cleaner/index.tsnew file mode 100644index 0000000000..7eaff07396--- /dev/null+++ b/worker/src/features/deleted-mask-cleaner/index.ts@@ -0,0 +1,219 @@+import {+ commandClickhouse,+ logger,+ queryClickhouse,+ recordGauge,+ recordIncrement,+} from "@langfuse/shared/src/server";+import { env } from "../../env";+import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";+import {+ buildApplyDeletedMaskQuery,+ buildMutationCountQuery,+ DELETED_MASK_CLEANER_TABLES,+ DELETED_MASK_CLEANER_WORK_QUERY,+ isAbortError,+ normalizeMutationCounts,+ selectCandidateToProcess,+ type MutationCountRow,+ type WorkCandidateRow,+} from "./helpers";++export * from "./helpers";++export const DELETED_MASK_CLEANER_LOCK_KEY =+ "langfuse:clickhouse-deleted-mask-cleaner";++const METRIC_PREFIX = "langfuse.clickhouse_deleted_mask_cleaner";++/**+ * DeletedMaskCleaner physically applies ClickHouse lightweight delete masks for+ * old monthly partitions. APPLY DELETED MASK creates a mutation, so each tick+ * submits at most one command and only after checking the target table has no+ * unfinished mutations.+ */+export class DeletedMaskCleaner extends PeriodicExclusiveRunner {+ protected get defaultIntervalMs(): number {+ return env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_INTERVAL_MS;+ }++ constructor() {+ const lockTtlSeconds =+ Math.ceil(+ env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS / 1000,+ ) + 300;++ super({+ name: "DeletedMaskCleaner",+ lockKey: DELETED_MASK_CLEANER_LOCK_KEY,+ lockTtlSeconds,+ onUnavailable: "fail",+ });+ }++ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ intervalMs: env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_INTERVAL_MS,+ submitTimeoutMs:+ env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS,+ tables: DELETED_MASK_CLEANER_TABLES,+ });+ super.start();+ }++ protected async execute(): Promise<void> {+ await this.withLock(+ async () => {+ const candidates = await this.getCandidates();+ recordGauge(`${METRIC_PREFIX}.candidates`, candidates.length);++ if (candidates.length === 0) {+ logger.info(+ `${this.instanceName}: No deleted-mask cleanup candidates`,+ );+ return;+ }++ const candidateTables = Array.from(+ new Set(candidates.map(({ table }) => table)),+ );+ const mutationCounts = normalizeMutationCounts(+ candidateTables,+ await this.getMutationCountRows(candidateTables),+ );++ const selection = selectCandidateToProcess(candidates, mutationCounts);+ for (const skipped of selection.skipped) {+ logger.info(+ `${this.instanceName}: Skipping candidate because target table has active mutations`,+ {+ table: skipped.candidate.table,+ partition: skipped.candidate.partition,+ partitionToClean: skipped.candidate.partition_to_clean,+ mutationCount: skipped.mutationCount,+ },+ );+ recordIncrement(`${METRIC_PREFIX}.candidate_skipped`, 1, {+ table: skipped.candidate.table,+ reason: "active_mutations",+ });+ }++ if (selection.candidate) {+ await this.applyDeletedMask(selection.candidate);+ return;+ }++ logger.info(+ `${this.instanceName}: No candidates were safe to process this tick`,+ );+ },+ (error) => {+ logger.error(`${this.instanceName}: Failed to process cleanup tick`, {+ error,+ });+ recordIncrement(`${METRIC_PREFIX}.failures`, 1);+ },+ );+ }++ private async getCandidates(): Promise<WorkCandidateRow[]> {+ const rows = await queryClickhouse<WorkCandidateRow>({+ query: DELETED_MASK_CLEANER_WORK_QUERY,+ params: {+ database: env.CLICKHOUSE_DB,+ tables: Array.from(DELETED_MASK_CLEANER_TABLES),+ },+ tags: {+ feature: "deleted-mask-cleaner",+ operation: "get-candidates",+ },+ });++ return rows;+ }++ private async getMutationCountRows(+ tables: string[],+ ): Promise<MutationCountRow[]> {+ if (tables.length === 0) {+ return [];+ }++ return queryClickhouse<MutationCountRow>({+ query: buildMutationCountQuery(+ env.CLICKHOUSE_CLUSTER_ENABLED === "true",+ env.CLICKHOUSE_CLUSTER_NAME,+ ),+ params: {+ database: env.CLICKHOUSE_DB,+ tables,+ },+ tags: {+ feature: "deleted-mask-cleaner",+ operation: "get-mutation-counts",+ },+ });+ }++ private async applyDeletedMask(candidate: WorkCandidateRow): Promise<void> {+ const query = buildApplyDeletedMaskQuery(candidate, {+ database: env.CLICKHOUSE_DB,+ clusterEnabled: env.CLICKHOUSE_CLUSTER_ENABLED === "true",+ clusterName: env.CLICKHOUSE_CLUSTER_NAME,+ });++ logger.info(`${this.instanceName}: Applying deleted mask`, {+ table: candidate.table,+ partition: candidate.partition,+ partitionToClean: candidate.partition_to_clean,+ totalRows: Number(candidate.total_rows),+ });++ const abortController = new AbortController();+ const timeoutId = setTimeout(+ () => abortController.abort(),+ env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS,+ );++ try {+ await commandClickhouse({+ query,+ clickhouseSettings: {+ mutations_sync: "0",+ },+ abortSignal: abortController.signal,+ tags: {+ feature: "deleted-mask-cleaner",+ table: candidate.table,+ partition: candidate.partition_to_clean,+ operation: "apply-deleted-mask",+ },+ });++ recordIncrement(`${METRIC_PREFIX}.commands_submitted`, 1, {+ table: candidate.table,+ });+ } catch (error) {+ if (!isAbortError(error)) {+ throw error;+ }++ logger.info(+ `${this.instanceName}: Stopped waiting for deleted-mask command submission`,+ {+ table: candidate.table,+ partition: candidate.partition,+ partitionToClean: candidate.partition_to_clean,+ submitTimeoutMs:+ env.LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS,+ },+ );+ recordIncrement(`${METRIC_PREFIX}.command_submit_aborted`, 1, {+ table: candidate.table,+ });+ } finally {+ clearTimeout(timeoutId);+ }+ }+}diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex d3bcd753ea..4893873a09 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -16,6 +16,7 @@ import {batchProjectMediaCleaner,batchProjectBlobCleaner,batchTraceDeletionCleaner,+ deletedMaskCleaner,queueMetricsRunner,} from "../app";@@ -49,6 +50,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {// Stop batch trace deletion cleanerbatchTraceDeletionCleaner?.stop();+ // Stop deleted-mask cleaner+ deletedMaskCleaner?.stop();+// Stop queue metrics runnerqueueMetricsRunner?.stop();