Skip to content

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

feat: expand mutation monitor to handle multiple queues and tables (#10608)

Valery Meleshkine3a5cb978b37
diff --git a/worker/src/__tests__/mutationMonitor.test.ts b/worker/src/__tests__/mutationMonitor.test.ts
index 1c254b546b..d627428af2 100644
--- a/worker/src/__tests__/mutationMonitor.test.ts
+++ b/worker/src/__tests__/mutationMonitor.test.ts
@@ -16,6 +16,13 @@ vi.mock("@langfuse/shared/src/server", async () => {
warn: vi.fn(),
error: vi.fn(),
},
+ QueueName: {
+ TraceDelete: "trace-delete",
+ ScoreDelete: "score-delete",
+ DatasetDelete: "dataset-delete",
+ ProjectDelete: "project-delete",
+ DataRetentionProcessingQueue: "data-retention-processing-queue",
+ },
};
});
@@ -31,266 +38,312 @@ vi.mock("../env", () => ({
}));
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);
- });
+ // Test data
+ const queueTableMapping = {
+ "trace-delete": ["traces", "observations", "scores"],
+ "score-delete": ["scores"],
+ "dataset-delete": ["dataset_run_items_rmt"],
+ "project-delete": [
+ "traces",
+ "observations",
+ "scores",
+ "dataset_run_items_rmt",
+ ],
+ "data-retention-processing-queue": ["traces", "observations", "scores"],
+ };
- afterEach(() => {
- MutationMonitor.stop();
- vi.clearAllMocks();
- });
+ describe("makeDecisions tests", () => {
+ it("should decide to pause queues when scores exceeds MAX", () => {
+ const counts = new Map([
+ ["traces", 10],
+ ["observations", 10],
+ ["scores", 50],
+ ]);
- 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,
- }),
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40, // MAX
+ 15, // SAFE
);
- MutationMonitor.stop();
- expect(shared.logger.info).toHaveBeenCalledWith(
- "Mutation monitor stopped",
+
+ // Pause decisions for queues affecting scores
+ const pauseDecisions = decisions.filter((d) => d.action === "pause");
+ expect(pauseDecisions).toHaveLength(4);
+ expect(pauseDecisions.map((d) => d.queueName)).toContain("trace-delete");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "project-delete",
+ );
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "data-retention-processing-queue",
);
- });
- it("should not start multiple times", () => {
- MutationMonitor.start();
- MutationMonitor.start();
- expect(shared.logger.warn).toHaveBeenCalledWith(
- "Mutation monitor is already running",
+ // Also resume decision for DatasetDelete (its table is safe)
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain(
+ "dataset-delete",
);
});
- });
- 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 },
+ it("should decide to resume all queues when all tables are below SAFE", () => {
+ const counts = new Map([
+ ["traces", 10],
+ ["observations", 12],
+ ["scores", 14], // All < 15
+ ["dataset_run_items_rmt", 5],
]);
- MutationMonitor.start();
-
- // Wait for the check to complete
- await new Promise((resolve) => setTimeout(resolve, 100));
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- 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",
- }),
+ // All queues should have resume decisions (all tables safe)
+ expect(decisions.every((d) => d.action === "resume")).toBe(true);
+ expect(decisions).toHaveLength(5);
+ expect(decisions.map((d) => d.queueName)).toContain("trace-delete");
+ expect(decisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(decisions.map((d) => d.queueName)).toContain("dataset-delete");
+ expect(decisions.map((d) => d.queueName)).toContain("project-delete");
+ expect(decisions.map((d) => d.queueName)).toContain(
+ "data-retention-processing-queue",
);
});
- it("should resume workers when mutations drop below SAFE_COUNT", async () => {
- // First, pause the workers
- queryClickhouseMock.mockResolvedValueOnce([
- { database: "default", table: "traces", mutation_count: 50 },
+ it("should NOT decide to resume queues if ANY of their tables is >= SAFE", () => {
+ const counts = new Map([
+ ["traces", 10],
+ ["observations", 12],
+ ["scores", 15], // At SAFE threshold
+ ["dataset_run_items_rmt", 5],
]);
- 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 },
- ]);
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- // Trigger another check manually by waiting
- await new Promise((resolve) => setTimeout(resolve, 1100));
+ // Only DatasetDelete should have resume (doesn't depend on scores)
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions).toHaveLength(1);
+ expect(resumeDecisions[0].queueName).toBe("dataset-delete");
- 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,
- }),
+ // Queues depending on scores should NOT have resume decisions
+ expect(resumeDecisions.map((d) => d.queueName)).not.toContain(
+ "trace-delete",
+ );
+ expect(resumeDecisions.map((d) => d.queueName)).not.toContain(
+ "score-delete",
);
});
- it("should not pause if already paused", async () => {
- // First pause
- queryClickhouseMock.mockResolvedValue([
- { database: "default", table: "traces", mutation_count: 50 },
+ it("should handle multiple tables over threshold", () => {
+ const counts = new Map([
+ ["traces", 50],
+ ["scores", 45],
+ ["observations", 10],
+ ["dataset_run_items_rmt", 5],
]);
- MutationMonitor.start();
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- expect(mockWorker.pause).toHaveBeenCalledTimes(1);
- vi.clearAllMocks();
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- // Wait for another check cycle
- await new Promise((resolve) => setTimeout(resolve, 1100));
+ // Pause decisions for queues affecting traces/scores
+ const pauseDecisions = decisions.filter((d) => d.action === "pause");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain("trace-delete");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "project-delete",
+ );
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "data-retention-processing-queue",
+ );
- // Should not call pause again
- expect(mockWorker.pause).not.toHaveBeenCalled();
+ // Resume decision for DatasetDelete (its table is safe)
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain(
+ "dataset-delete",
+ );
});
- it("should not resume if already running", async () => {
- queryClickhouseMock.mockResolvedValue([
- { database: "default", table: "traces", mutation_count: 10 },
+ it("should decide to resume ScoreDelete independently", () => {
+ const counts = new Map([
+ ["traces", 20], // In hysteresis zone (between SAFE and MAX)
+ ["observations", 10],
+ ["scores", 10], // Below SAFE
+ ["dataset_run_items_rmt", 5],
]);
- MutationMonitor.start();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- // Should not call resume since it's not paused
- expect(mockWorker.resume).not.toHaveBeenCalled();
+ // ScoreDelete and DatasetDelete should resume (their tables are safe)
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions).toHaveLength(2);
+ expect(resumeDecisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain(
+ "dataset-delete",
+ );
+
+ // TraceDelete should NOT resume (traces=20 >= SAFE=15)
+ expect(resumeDecisions.map((d) => d.queueName)).not.toContain(
+ "trace-delete",
+ );
});
- 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 },
+ it("should handle DatasetDelete independently", () => {
+ const counts = new Map([
+ ["traces", 10],
+ ["observations", 10],
+ ["scores", 10],
+ ["dataset_run_items_rmt", 50],
]);
- 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",
- }),
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
);
- });
- it("should handle empty results (no pending mutations)", async () => {
- queryClickhouseMock.mockResolvedValueOnce([]);
-
- MutationMonitor.start();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ // Pause decisions for queues affecting dataset_run_items_rmt
+ const pauseDecisions = decisions.filter((d) => d.action === "pause");
+ expect(pauseDecisions).toHaveLength(2);
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "dataset-delete",
+ );
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "project-delete",
+ );
- // Should not pause since all counts are 0
- expect(mockWorker.pause).not.toHaveBeenCalled();
- expect(MutationMonitor.getIsPaused()).toBe(false);
+ // Resume decisions for queues only affecting traces/observations/scores
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain("trace-delete");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain(
+ "data-retention-processing-queue",
+ );
});
- it("should handle partial results (some tables missing)", async () => {
- // Only one table returned
- queryClickhouseMock.mockResolvedValueOnce([
- { database: "default", table: "traces", mutation_count: 50 },
+ it("should handle empty mutation counts", () => {
+ const counts = new Map([
+ ["traces", 0],
+ ["observations", 0],
+ ["scores", 0],
+ ["dataset_run_items_rmt", 0],
]);
- MutationMonitor.start();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- // Should still pause because traces exceeds threshold
- expect(mockWorker.pause).toHaveBeenCalledTimes(1);
- expect(MutationMonitor.getIsPaused()).toBe(true);
+ // All queues should have resume decisions (all tables safe)
+ expect(decisions.every((d) => d.action === "resume")).toBe(true);
+ expect(decisions).toHaveLength(5);
});
- it("should stay in hysteresis zone (between SAFE and MAX)", async () => {
- // First, pause the workers
- queryClickhouseMock.mockResolvedValueOnce([
- { database: "default", table: "traces", mutation_count: 50 },
+ it("should handle missing tables in mutation counts", () => {
+ const counts = new Map([
+ ["traces", 50],
+ // observations and scores missing (treated as 0)
]);
- 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 },
- ]);
+ const decisions = MutationMonitor.makeDecisions(
+ counts,
+ queueTableMapping,
+ 40,
+ 15,
+ );
- await new Promise((resolve) => setTimeout(resolve, 1100));
+ // Pause decisions for queues affecting traces
+ const pauseDecisions = decisions.filter((d) => d.action === "pause");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain("trace-delete");
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "project-delete",
+ );
+ expect(pauseDecisions.map((d) => d.queueName)).toContain(
+ "data-retention-processing-queue",
+ );
- // Should remain paused (hysteresis)
- expect(mockWorker.resume).not.toHaveBeenCalled();
- expect(MutationMonitor.getIsPaused()).toBe(true);
+ // Resume decisions for queues not affecting traces
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain("score-delete");
+ expect(resumeDecisions.map((d) => d.queueName)).toContain(
+ "dataset-delete",
+ );
});
});
- describe("error handling", () => {
- it("should handle ClickHouse query errors gracefully", async () => {
- queryClickhouseMock.mockRejectedValueOnce(new Error("ClickHouse error"));
+ describe("integration tests", () => {
+ let mockWorkers: Map<string, Partial<Worker>>;
+ let queryClickhouseMock: ReturnType<typeof vi.fn>;
- MutationMonitor.start();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ beforeEach(() => {
+ MutationMonitor.resetState();
+ MutationMonitor.stop();
- expect(shared.logger.error).toHaveBeenCalledWith(
- "Error checking ClickHouse mutations",
- expect.any(Error),
+ mockWorkers = new Map();
+ const queueNames = [
+ "trace-delete",
+ "score-delete",
+ "dataset-delete",
+ "project-delete",
+ "data-retention-processing-queue",
+ ];
+
+ queueNames.forEach((queueName) => {
+ mockWorkers.set(queueName, {
+ pause: vi.fn().mockResolvedValue(undefined),
+ resume: vi.fn().mockResolvedValue(undefined),
+ });
+ });
+
+ queryClickhouseMock = vi.mocked(shared.queryClickhouse);
+ vi.mocked(WorkerManager.getWorker).mockImplementation(
+ (queueName: string) => mockWorkers.get(queueName) as Worker,
);
- // 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",
- );
+ afterEach(() => {
+ MutationMonitor.stop();
+ vi.clearAllMocks();
});
- it("should handle worker.pause errors gracefully", async () => {
- mockWorker.pause = vi
- .fn()
- .mockRejectedValueOnce(new Error("Pause failed"));
-
+ it("should execute pause decisions from ClickHouse data", 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();
await new Promise((resolve) => setTimeout(resolve, 100));
- expect(shared.logger.error).toHaveBeenCalledWith(
- "Error pausing TraceDelete workers",
- expect.any(Error),
- );
+ // TraceDelete should be paused
+ expect(mockWorkers.get("trace-delete")?.pause).toHaveBeenCalled();
+ expect(mockWorkers.get("project-delete")?.pause).toHaveBeenCalled();
+ expect(
+ mockWorkers.get("data-retention-processing-queue")?.pause,
+ ).toHaveBeenCalled();
});
- it("should handle worker.resume errors gracefully", async () => {
+ it("should execute resume decisions", async () => {
// First pause
queryClickhouseMock.mockResolvedValueOnce([
{ database: "default", table: "traces", mutation_count: 50 },
@@ -298,22 +351,31 @@ describe("MutationMonitor", () => {
MutationMonitor.start();
await new Promise((resolve) => setTimeout(resolve, 100));
- vi.clearAllMocks();
- // Mock resume to fail
- mockWorker.resume = vi
- .fn()
- .mockRejectedValueOnce(new Error("Resume failed"));
+ expect(mockWorkers.get("trace-delete")?.pause).toHaveBeenCalled();
+ vi.clearAllMocks();
- // Now drop mutations
+ // Then drop below SAFE
queryClickhouseMock.mockResolvedValueOnce([
{ database: "default", table: "traces", mutation_count: 10 },
+ { database: "default", table: "observations", mutation_count: 10 },
+ { database: "default", table: "scores", mutation_count: 10 },
]);
await new Promise((resolve) => setTimeout(resolve, 1100));
+ // Should resume
+ expect(mockWorkers.get("trace-delete")?.resume).toHaveBeenCalled();
+ });
+
+ it("should handle ClickHouse errors gracefully", async () => {
+ queryClickhouseMock.mockRejectedValueOnce(new Error("ClickHouse error"));
+
+ MutationMonitor.start();
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
expect(shared.logger.error).toHaveBeenCalledWith(
- "Error resuming TraceDelete workers",
+ "Error checking ClickHouse mutations",
expect.any(Error),
);
});
diff --git a/worker/src/features/mutation-monitoring/mutationMonitor.ts b/worker/src/features/mutation-monitoring/mutationMonitor.ts
index 27779fcf24..e494c5d723 100644
--- a/worker/src/features/mutation-monitoring/mutationMonitor.ts
+++ b/worker/src/features/mutation-monitoring/mutationMonitor.ts
@@ -12,16 +12,46 @@ interface MutationCount {
mutation_count: number;
}
+type QueueAction = "pause" | "resume";
+
+interface QueueDecision {
+ queueName: QueueName;
+ action: QueueAction;
+ reason: string;
+}
+
export class MutationMonitor {
private static timeoutId: NodeJS.Timeout | null = null;
- private static isPaused = false;
+ private static pausedQueues: Set<QueueName> = new Set();
private static isRunning = false;
private static readonly TABLES_TO_MONITOR = [
"traces",
"observations",
"scores",
+ "dataset_run_items_rmt",
];
+ // Mapping of which ClickHouse tables each deletion queue affects
+ private static readonly QUEUE_TABLE_MAPPING: Partial<
+ Record<QueueName, string[]>
+ > = {
+ [QueueName.TraceDelete]: ["traces", "observations", "scores"],
+ [QueueName.ScoreDelete]: ["scores"],
+ [QueueName.DatasetDelete]: ["dataset_run_items_rmt"],
+ [QueueName.ProjectDelete]: [
+ "traces",
+ "observations",
+ "scores",
+ "dataset_run_items_rmt",
+ ],
+ [QueueName.DataRetentionProcessingQueue]: [
+ "traces",
+ "observations",
+ "scores",
+ ],
+ [QueueName.BatchActionQueue]: ["traces", "observations", "scores"],
+ };
+
/**
* Start the mutation monitoring service
*/
@@ -90,6 +120,74 @@ export class MutationMonitor {
}
}
+ /**
+ * Decision function - determines which queues to pause/resume
+ */
+ public static makeDecisions(
+ mutationCounts: Map<string, number>,
+ queueTableMapping: Partial<Record<QueueName, string[]>>,
+ maxThreshold: number,
+ safeThreshold: number,
+ ): QueueDecision[] {
+ const decisions: QueueDecision[] = [];
+ const decisionMap: Map<QueueName, QueueAction> = new Map();
+
+ // Find tables over MAX threshold
+ const tablesOverMax = Array.from(mutationCounts.entries())
+ .filter(([, count]) => count >= maxThreshold)
+ .map(([table]) => table);
+
+ const tableToQueuesMap: Map<string, QueueName[]> = Object.entries(
+ queueTableMapping,
+ ).reduce((map, [queue, tables]) => {
+ for (const table of tables) {
+ if (!map.has(table)) {
+ map.set(table, []);
+ }
+ map.get(table)!.push(queue as QueueName);
+ }
+ return map;
+ }, new Map());
+
+ // Decision 1: Pause queues affecting over-threshold tables
+ for (const table of tablesOverMax) {
+ const affectedQueues = tableToQueuesMap.get(table) || [];
+ for (const queue of affectedQueues) {
+ if (!decisionMap.has(queue)) {
+ decisions.push({
+ queueName: queue,
+ action: "pause",
+ reason: `${table}=${mutationCounts.get(table)}`,
+ });
+ decisionMap.set(queue, "pause");
+ }
+ }
+ }
+
+ // Decision 2: Resume queues where ALL tables are safe
+ for (const [queue, tables] of Object.entries(queueTableMapping)) {
+ const allSafe = tables.every(
+ (table) => (mutationCounts.get(table) ?? 0) < safeThreshold,
+ );
+
+ if (allSafe) {
+ if (!decisionMap.has(queue as QueueName)) {
+ decisionMap.set(queue as QueueName, "resume");
+ decisions.push({
+ queueName: queue as QueueName,
+ action: "resume",
+ reason: "",
+ });
+ } else {
+ // if there is a contradictory action, we log an error
+ logger.error(`Contradictory decisions for ${queue}`);
+ }
+ }
+ }
+
+ return decisions;
+ }
+
/**
* Check ClickHouse mutations and pause/resume workers as needed
*/
@@ -124,31 +222,34 @@ export class MutationMonitor {
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,
+ pausedQueues: Array.from(this.pausedQueues),
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);
+ const decisions = this.makeDecisions(
+ mutationCounts,
+ this.QUEUE_TABLE_MAPPING,
+ env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,
+ env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT,
+ );
+
+ // Separate decisions by action
+ const pauseDecisions = decisions.filter((d) => d.action === "pause");
+ const resumeDecisions = decisions.filter((d) => d.action === "resume");
+
+ // Execute pause decisions
+ if (pauseDecisions.length > 0) {
+ const queuesToPause = new Set(pauseDecisions.map((d) => d.queueName));
+ const reasons = pauseDecisions.map((d) => d.reason);
+ await this.pauseWorkers(queuesToPause, mutationCounts, reasons);
+ }
+
+ // Execute resume decisions
+ if (resumeDecisions.length > 0) {
+ const queuesToResume = new Set(resumeDecisions.map((d) => d.queueName));
+ await this.resumeWorkers(queuesToResume, mutationCounts);
}
} catch (error) {
logger.error("Error checking ClickHouse mutations", error);
@@ -156,86 +257,93 @@ export class MutationMonitor {
}
/**
- * Pause TraceDelete workers to reduce mutation load on ClickHouse
+ * Pause workers (pure execution - no decision logic)
*/
private static async pauseWorkers(
- maxMutationCount: number,
- tableWithMaxMutations: string | undefined,
+ queuesToPause: Set<QueueName>,
mutationCounts: Map<string, number>,
+ offendingTables: string[],
): 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;
+ for (const queueName of queuesToPause) {
+ // Skip if already paused (optimization)
+ if (this.pausedQueues.has(queueName)) {
+ continue;
}
- await worker.pause();
- this.isPaused = true;
+ try {
+ const worker = WorkerManager.getWorker(queueName);
+ if (!worker) {
+ logger.warn(`${queueName} worker not found, cannot pause`);
+ continue;
+ }
- 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);
+ await worker.pause();
+ this.pausedQueues.add(queueName);
+
+ logger.warn(`Paused ${queueName}`, {
+ reason: `tables over threshold: ${offendingTables.join(", ")}`,
+ threshold: env.LANGFUSE_DELETION_MUTATIONS_MAX_COUNT,
+ mutationCounts: Object.fromEntries(mutationCounts),
+ });
+ } catch (error) {
+ logger.error(`Error pausing ${queueName}`, error);
+ }
}
}
/**
- * Resume TraceDelete workers after mutation load has decreased
+ * Resume workers (pure execution - no decision logic)
*/
private static async resumeWorkers(
- maxMutationCount: number,
+ queuesToResume: Set<QueueName>,
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;
+ for (const queueName of queuesToResume) {
+ // Skip if not paused (optimization)
+ if (!this.pausedQueues.has(queueName)) {
+ continue;
}
- await worker.resume();
- this.isPaused = false;
+ try {
+ const worker = WorkerManager.getWorker(queueName);
+ if (!worker) {
+ logger.warn(`${queueName} worker not found, cannot resume`);
+ continue;
+ }
- logger.info(
- "Mutations below safe threshold, resuming TraceDelete workers",
- {
+ await worker.resume();
+ this.pausedQueues.delete(queueName);
+
+ logger.info(`Resumed ${queueName}`, {
+ reason: "all tables below safe threshold",
safeThreshold: env.LANGFUSE_DELETION_MUTATIONS_SAFE_COUNT,
- maxMutationCount,
mutationCounts: Object.fromEntries(mutationCounts),
- },
- );
- } catch (error) {
- logger.error("Error resuming TraceDelete workers", error);
+ });
+ } catch (error) {
+ logger.error(`Error resuming ${queueName}`, error);
+ }
}
}
/**
- * Get the current pause state (useful for testing)
+ * Get the paused queues (useful for testing)
+ */
+ public static getPausedQueues(): Set<QueueName> {
+ return new Set(this.pausedQueues);
+ }
+
+ /**
+ * Check if a specific queue is paused (useful for testing)
*/
- public static getIsPaused(): boolean {
- return this.isPaused;
+ public static isQueuePaused(queue: QueueName): boolean {
+ return this.pausedQueues.has(queue);
}
/**
* Reset the state (useful for testing)
*/
public static resetState(): void {
- this.isPaused = false;
+ this.pausedQueues.clear();
this.isRunning = false;
if (this.timeoutId !== null) {
clearTimeout(this.timeoutId);