🪢 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: adding MutationMonitor component that pauses/resumes TraceDelete based on mutations count (#10574)
Valery Meleshkin78d08f174ec5
diff --git a/worker/src/__tests__/mutationMonitor.test.ts b/worker/src/__tests__/mutationMonitor.test.tsnew file mode 100644index 0000000000..1c254b546b--- /dev/null+++ b/worker/src/__tests__/mutationMonitor.test.ts@@ -0,0 +1,321 @@+import { expect, describe, it, beforeEach, vi, afterEach } from "vitest";+import { MutationMonitor } from "../features/mutation-monitoring/mutationMonitor";+import { WorkerManager } from "../queues/workerManager";+import * as shared from "@langfuse/shared/src/server";+import { Worker } from "bullmq";++// Mock the dependencies+vi.mock("@langfuse/shared/src/server", async () => {+ const actual = await vi.importActual("@langfuse/shared/src/server");+ return {+ ...actual,+ queryClickhouse: vi.fn(),+ logger: {+ info: vi.fn(),+ debug: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ };+});++vi.mock("../queues/workerManager");+vi.mock("../env", () => ({+ env: {+ LANGFUSE_MUTATION_MONITOR_ENABLED: "true",+ LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS: 1000,+ LANGFUSE_DELETION_MUTATIONS_MAX_COUNT: 40,+ LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT: 15,+ CLICKHOUSE_DB: "default",+ },+}));++describe("MutationMonitor", () => {+ let mockWorker: Partial<Worker>;+ let queryClickhouseMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ // Reset state before each test+ MutationMonitor.resetState();+ MutationMonitor.stop();++ // Create mock worker with pause/resume methods+ mockWorker = {+ pause: vi.fn().mockResolvedValue(undefined),+ resume: vi.fn().mockResolvedValue(undefined),+ };++ // Setup mocks+ queryClickhouseMock = vi.mocked(shared.queryClickhouse);+ vi.mocked(WorkerManager.getWorker).mockReturnValue(mockWorker as Worker);+ });++ afterEach(() => {+ MutationMonitor.stop();+ vi.clearAllMocks();+ });++ describe("start and stop", () => {+ it("should stop the monitor", () => {+ MutationMonitor.start();+ // Verify it doesn't throw and logger is called+ expect(shared.logger.info).toHaveBeenCalledWith(+ "Starting mutation monitor",+ expect.objectContaining({+ checkIntervalMs: 1000,+ maxCount: 40,+ safeCount: 15,+ }),+ );+ MutationMonitor.stop();+ expect(shared.logger.info).toHaveBeenCalledWith(+ "Mutation monitor stopped",+ );+ });++ it("should not start multiple times", () => {+ MutationMonitor.start();+ MutationMonitor.start();+ expect(shared.logger.warn).toHaveBeenCalledWith(+ "Mutation monitor is already running",+ );+ });+ });++ describe("mutation checking logic", () => {+ it("should pause workers when any table exceeds MAX_COUNT", async () => {+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ { database: "default", table: "observations", mutation_count: 10 },+ { database: "default", table: "scores", mutation_count: 5 },+ ]);++ MutationMonitor.start();++ // Wait for the check to complete+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(mockWorker.pause).toHaveBeenCalledTimes(1);+ expect(MutationMonitor.getIsPaused()).toBe(true);+ expect(shared.logger.warn).toHaveBeenCalledWith(+ "Mutation threshold exceeded, pausing TraceDelete workers",+ expect.objectContaining({+ threshold: 40,+ maxMutationCount: 50,+ tableWithMaxMutations: "traces",+ }),+ );+ });++ it("should resume workers when mutations drop below SAFE_COUNT", async () => {+ // First, pause the workers+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(MutationMonitor.getIsPaused()).toBe(true);+ vi.clearAllMocks();++ // Now mutations drop below safe threshold+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 10 },+ { database: "default", table: "observations", mutation_count: 5 },+ { database: "default", table: "scores", mutation_count: 2 },+ ]);++ // Trigger another check manually by waiting+ await new Promise((resolve) => setTimeout(resolve, 1100));++ expect(mockWorker.resume).toHaveBeenCalledTimes(1);+ expect(MutationMonitor.getIsPaused()).toBe(false);+ expect(shared.logger.info).toHaveBeenCalledWith(+ "Mutations below safe threshold, resuming TraceDelete workers",+ expect.objectContaining({+ safeThreshold: 15,+ maxMutationCount: 10,+ }),+ );+ });++ it("should not pause if already paused", async () => {+ // First pause+ queryClickhouseMock.mockResolvedValue([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(mockWorker.pause).toHaveBeenCalledTimes(1);+ vi.clearAllMocks();++ // Wait for another check cycle+ await new Promise((resolve) => setTimeout(resolve, 1100));++ // Should not call pause again+ expect(mockWorker.pause).not.toHaveBeenCalled();+ });++ it("should not resume if already running", async () => {+ queryClickhouseMock.mockResolvedValue([+ { database: "default", table: "traces", mutation_count: 10 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ // Should not call resume since it's not paused+ expect(mockWorker.resume).not.toHaveBeenCalled();+ });++ it("should check per-table and pause if ANY table exceeds threshold", async () => {+ // Only observations exceeds threshold+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 10 },+ { database: "default", table: "observations", mutation_count: 45 },+ { database: "default", table: "scores", mutation_count: 5 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(mockWorker.pause).toHaveBeenCalledTimes(1);+ expect(MutationMonitor.getIsPaused()).toBe(true);+ expect(shared.logger.warn).toHaveBeenCalledWith(+ "Mutation threshold exceeded, pausing TraceDelete workers",+ expect.objectContaining({+ maxMutationCount: 45,+ tableWithMaxMutations: "observations",+ }),+ );+ });++ it("should handle empty results (no pending mutations)", async () => {+ queryClickhouseMock.mockResolvedValueOnce([]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ // Should not pause since all counts are 0+ expect(mockWorker.pause).not.toHaveBeenCalled();+ expect(MutationMonitor.getIsPaused()).toBe(false);+ });++ it("should handle partial results (some tables missing)", async () => {+ // Only one table returned+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ // Should still pause because traces exceeds threshold+ expect(mockWorker.pause).toHaveBeenCalledTimes(1);+ expect(MutationMonitor.getIsPaused()).toBe(true);+ });++ it("should stay in hysteresis zone (between SAFE and MAX)", async () => {+ // First, pause the workers+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(MutationMonitor.getIsPaused()).toBe(true);+ vi.clearAllMocks();++ // Now mutations are between SAFE (15) and MAX (40)+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 25 },+ ]);++ await new Promise((resolve) => setTimeout(resolve, 1100));++ // Should remain paused (hysteresis)+ expect(mockWorker.resume).not.toHaveBeenCalled();+ expect(MutationMonitor.getIsPaused()).toBe(true);+ });+ });++ describe("error handling", () => {+ it("should handle ClickHouse query errors gracefully", async () => {+ queryClickhouseMock.mockRejectedValueOnce(new Error("ClickHouse error"));++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(shared.logger.error).toHaveBeenCalledWith(+ "Error checking ClickHouse mutations",+ expect.any(Error),+ );+ // Should not crash+ expect(MutationMonitor.getIsPaused()).toBe(false);+ });++ it("should handle worker not found gracefully", async () => {+ vi.mocked(WorkerManager.getWorker).mockReturnValueOnce(undefined);++ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(shared.logger.warn).toHaveBeenCalledWith(+ "TraceDelete worker not found, cannot pause",+ );+ });++ it("should handle worker.pause errors gracefully", async () => {+ mockWorker.pause = vi+ .fn()+ .mockRejectedValueOnce(new Error("Pause failed"));++ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));++ expect(shared.logger.error).toHaveBeenCalledWith(+ "Error pausing TraceDelete workers",+ expect.any(Error),+ );+ });++ it("should handle worker.resume errors gracefully", async () => {+ // First pause+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 50 },+ ]);++ MutationMonitor.start();+ await new Promise((resolve) => setTimeout(resolve, 100));+ vi.clearAllMocks();++ // Mock resume to fail+ mockWorker.resume = vi+ .fn()+ .mockRejectedValueOnce(new Error("Resume failed"));++ // Now drop mutations+ queryClickhouseMock.mockResolvedValueOnce([+ { database: "default", table: "traces", mutation_count: 10 },+ ]);++ await new Promise((resolve) => setTimeout(resolve, 1100));++ expect(shared.logger.error).toHaveBeenCalledWith(+ "Error resuming TraceDelete workers",+ expect.any(Error),+ );+ });+ });+});diff --git a/worker/src/app.ts b/worker/src/app.tsindex b59e432a43..a280e26b1d 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -72,6 +72,7 @@ import { datasetDeleteProcessor } from "./queues/datasetDelete";import { otelIngestionQueueProcessor } from "./queues/otelIngestionQueue";import { eventPropagationProcessor } from "./queues/eventPropagationQueue";import { notificationQueueProcessor } from "./queues/notificationQueue";+import { MutationMonitor } from "./features/mutation-monitoring/mutationMonitor";const app = express();@@ -529,6 +530,11 @@ if (env.QUEUE_CONSUMER_NOTIFICATION_QUEUE_IS_ENABLED === "true") {);}+if (env.LANGFUSE_MUTATION_MONITOR_ENABLED === "true") {+ // Start the ClickHouse mutation monitor after all workers are registered+ MutationMonitor.start();+}+process.on("SIGINT", () => onShutdown("SIGINT"));process.on("SIGTERM", () => onShutdown("SIGTERM"));diff --git a/worker/src/env.ts b/worker/src/env.tsindex c6291775b1..c541471b43 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -297,6 +297,21 @@ const EnvSchema = z.object({.positive().default(120_000), // 2 minutes+ // ClickHouse mutation monitoring+ LANGFUSE_MUTATION_MONITOR_ENABLED: z.enum(["true", "false"]).default("true"),+ LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS: z.coerce+ .number()+ .positive()+ .default(60_000), // 1 minute+ LANGFUSE_DELETION_MUTATIONS_MAX_COUNT: z.coerce+ .number()+ .positive()+ .default(30),+ LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT: z.coerce+ .number()+ .positive()+ .default(5),+// Deprecated. Do not use!LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z.enum(["true", "false"])diff --git a/worker/src/features/mutation-monitoring/mutationMonitor.ts b/worker/src/features/mutation-monitoring/mutationMonitor.tsnew file mode 100644index 0000000000..1ce263f9c3--- /dev/null+++ b/worker/src/features/mutation-monitoring/mutationMonitor.ts@@ -0,0 +1,243 @@+import {+ logger,+ queryClickhouse,+ QueueName,+} from "@langfuse/shared/src/server";+import { env } from "../../env";+import { WorkerManager } from "../../queues/workerManager";++interface MutationCount {+ database: string;+ table: string;+ mutation_count: number;+}++export class MutationMonitor {+ private static timeoutId: NodeJS.Timeout | null = null;+ private static isPaused = false;+ private static isRunning = false;+ private static readonly TABLES_TO_MONITOR = [+ "traces",+ "observations",+ "scores",+ ];++ /**+ * Start the mutation monitoring service+ */+ public static start(): void {+ if (this.isRunning) {+ logger.warn("Mutation monitor is already running");+ return;+ }++ if (env.LANGFUSE_MUTATION_MONITOR_ENABLED !== "true") {+ logger.info("Mutation monitor is disabled");+ return;+ }++ this.isRunning = true;+ logger.info("Starting mutation monitor", {+ checkIntervalMs: env.LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS,+ maxCount: env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,+ safeCount: env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT,+ });++ // Start the monitoring loop+ void this.checkMutationsAndScheduleNext();+ }++ /**+ * Stop the mutation monitoring service+ */+ public static stop(): void {+ if (!this.isRunning) {+ return;+ }++ this.isRunning = false;+ if (this.timeoutId !== null) {+ clearTimeout(this.timeoutId);+ this.timeoutId = null;+ }+ logger.info("Mutation monitor stopped");+ }++ /**+ * Schedule the next mutation check after the specified interval+ */+ private static scheduleNextCheck(): void {+ if (!this.isRunning) {+ return;+ }++ this.timeoutId = setTimeout(() => {+ void this.checkMutationsAndScheduleNext();+ }, env.LANGFUSE_MUTATION_MONITOR_CHECK_INTERVAL_MS);+ }++ /**+ * Check mutations and schedule the next check (ensures sequential execution)+ */+ private static async checkMutationsAndScheduleNext(): Promise<void> {+ try {+ await this.checkMutations();+ } finally {+ // Always schedule next check, even if current check failed+ this.scheduleNextCheck();+ }+ }++ /**+ * Check ClickHouse mutations and pause/resume workers as needed+ */+ private static async checkMutations(): Promise<void> {+ try {+ const query = `+ SELECT+ database,+ table,+ count() as mutation_count+ FROM system.mutations+ WHERE database = {database: String}+ AND table IN ({tables: Array(String)})+ AND is_done = 0+ GROUP BY database, table+ `;++ const results = await queryClickhouse<MutationCount>({+ query,+ params: {+ database: env.CLICKHOUSE_DB,+ tables: this.TABLES_TO_MONITOR,+ },+ });++ // Create a map of table -> mutation count+ const mutationCounts = new Map<string, number>();+ for (const table of this.TABLES_TO_MONITOR) {+ mutationCounts.set(table, 0);+ }+ for (const result of results) {+ mutationCounts.set(result.table, result.mutation_count);+ }++ // Find the maximum mutation count across all tables+ const maxMutationCount = Math.max(...mutationCounts.values());+ const tableWithMaxMutations = Array.from(mutationCounts.entries()).find(+ ([, count]) => count === maxMutationCount,+ )?.[0];++ logger.debug("Mutation stats", {+ mutationCounts: Object.fromEntries(mutationCounts),+ maxMutationCount,+ tableWithMaxMutations,+ isPaused: this.isPaused,+ threshold: env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,+ });++ // Check if we need to pause or resume workers+ if (maxMutationCount >= env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT) {+ await this.pauseWorkers(+ maxMutationCount,+ tableWithMaxMutations,+ mutationCounts,+ );+ } else if (+ maxMutationCount < env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT+ ) {+ await this.resumeWorkers(maxMutationCount, mutationCounts);+ }+ } catch (error) {+ logger.error("Error checking ClickHouse mutations", error);+ }+ }++ /**+ * Pause TraceDelete workers to reduce mutation load on ClickHouse+ */+ private static async pauseWorkers(+ maxMutationCount: number,+ tableWithMaxMutations: string | undefined,+ mutationCounts: Map<string, number>,+ ): Promise<void> {+ // Only pause if not already paused+ if (this.isPaused) {+ return;+ }++ try {+ const worker = WorkerManager.getWorker(QueueName.TraceDelete);+ if (!worker) {+ logger.warn("TraceDelete worker not found, cannot pause");+ return;+ }++ await worker.pause();+ this.isPaused = true;++ logger.warn("Mutation threshold exceeded, pausing TraceDelete workers", {+ threshold: env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,+ maxMutationCount,+ tableWithMaxMutations,+ mutationCounts: Object.fromEntries(mutationCounts),+ });+ } catch (error) {+ logger.error("Error pausing TraceDelete workers", error);+ }+ }++ /**+ * Resume TraceDelete workers after mutation load has decreased+ */+ private static async resumeWorkers(+ maxMutationCount: number,+ mutationCounts: Map<string, number>,+ ): Promise<void> {+ // Only resume if currently paused+ if (!this.isPaused) {+ return;+ }++ try {+ const worker = WorkerManager.getWorker(QueueName.TraceDelete);+ if (!worker) {+ logger.warn("TraceDelete worker not found, cannot resume");+ return;+ }++ await worker.resume();+ this.isPaused = false;++ logger.info(+ "Mutations below safe threshold, resuming TraceDelete workers",+ {+ safeThreshold: env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT,+ maxMutationCount,+ mutationCounts: Object.fromEntries(mutationCounts),+ },+ );+ } catch (error) {+ logger.error("Error resuming TraceDelete workers", error);+ }+ }++ /**+ * Get the current pause state (useful for testing)+ */+ public static getIsPaused(): boolean {+ return this.isPaused;+ }++ /**+ * Reset the state (useful for testing)+ */+ public static resetState(): void {+ this.isPaused = false;+ this.isRunning = false;+ if (this.timeoutId !== null) {+ clearTimeout(this.timeoutId);+ this.timeoutId = null;+ }+ }+}diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.tsindex 29eb39e69f..a0ceec5599 100644--- a/worker/src/queues/workerManager.ts+++ b/worker/src/queues/workerManager.ts@@ -89,6 +89,10 @@ export class WorkerManager {logger.info("All workers have been closed.");}+ public static getWorker(queueName: QueueName): Worker | undefined {+ return WorkerManager.workers[queueName];+ }+public static register(queueName: QueueName,processor: Processor,diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex 646eab9984..105d2efb42 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -9,6 +9,7 @@ import { getTokenCountWorkerManager } from "../features/tokenisation/async-usageimport { WorkerManager } from "../queues/workerManager";import { prisma } from "@langfuse/shared/src/db";import { BackgroundMigrationManager } from "../backgroundMigrations/backgroundMigrationManager";+import { MutationMonitor } from "../features/mutation-monitoring/mutationMonitor";export const onShutdown: NodeJS.SignalsListener = async (signal) => {logger.info(`Received ${signal}, closing server...`);@@ -18,6 +19,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {server.close();logger.info("Server has been closed.");+ // Stop mutation monitor+ MutationMonitor.stop();+// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)await WorkerManager.closeWorkers();