Skip to content

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

chore: remove mutaiton waiter code path (#11454)

Valery Meleshkin725a88f5ae29
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index b36ec41824..907171d740 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -168,14 +168,6 @@ const EnvSchema = z.object({
.default(80e6), // 80MB
LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS: z.coerce.number().default(600_000), // 10 minutes
LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS: z.coerce.number().default(3), // Maximum attempts for socket hang up errors
- // Async deletion tracking - uses AbortController + query_id polling for DELETE operations
- LANGFUSE_ASYNC_DELETE_TRACKING_ENABLED: z
- .enum(["true", "false"])
- .default("false"),
- LANGFUSE_ASYNC_DELETE_TRACKING_POLL_INTERVAL_MS: z.coerce
- .number()
- .positive()
- .default(60_000), // 1 minute
LANGFUSE_SKIP_S3_LIST_FOR_OBSERVATIONS_PROJECT_IDS: z.string().optional(),
LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS: z
.string()
diff --git a/packages/shared/src/server/clickhouse/mutationWaiter.ts b/packages/shared/src/server/clickhouse/mutationWaiter.ts
deleted file mode 100644
index 334898bb8f..0000000000
--- a/packages/shared/src/server/clickhouse/mutationWaiter.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import { randomUUID } from "crypto";
-import { logger } from "../logger";
-import { ClickHouseSettings } from "@clickhouse/client";
-import { instrumentAsync } from "../instrumentation";
-import { SpanKind } from "@opentelemetry/api";
-import { pollQueryStatus, getQueryError, sleep } from "./queryTracking";
-import { commandClickhouse } from "../repositories/clickhouse";
-import { env } from "../../env";
-
-/**
- * Options for executing a DELETE command with mutation monitoring.
- */
-export interface MutationWaiterOptions {
- tableName: string;
- query: string;
- params?: Record<string, unknown>;
- tags?: Record<string, string>;
- clickhouseSettings?: ClickHouseSettings;
-}
-
-// Top-level constants
-const QUERY_REGISTER_DELAY_MS = 2000;
-const QUERY_NOT_FOUND_RETRY_LIMIT = 10;
-const QUERY_NOT_FOUND_RETRY_DELAY_MS = 1000;
-
-/**
- * Waits for a query to complete by polling system.processes and system.query_log.
- * Optionally aborts an HTTP connection when query is first found running.
- */
-async function waitForQueryCompletion(
- queryId: string,
- timeoutMs: number,
- pollIntervalMs: number,
- abortController?: AbortController,
- tags?: Record<string, string>,
-): Promise<void> {
- const startTime = Date.now();
- let notFoundCount = 0;
-
- while (Date.now() - startTime < timeoutMs) {
- const status = await pollQueryStatus(queryId, tags);
-
- if (status === "completed") {
- logger.info(`Query ${queryId} completed`, {
- durationMs: Date.now() - startTime,
- });
- return;
- }
-
- if (status === "failed") {
- const error = await getQueryError(queryId);
- throw new Error(`Query ${queryId} failed: ${error}`);
- }
-
- if (status === "not_found") {
- notFoundCount++;
- if (notFoundCount >= QUERY_NOT_FOUND_RETRY_LIMIT) {
- throw new Error(
- `Query ${queryId} not found after ${notFoundCount} attempts`,
- );
- }
- logger.debug(
- `Query ${queryId} not visible, waiting... (${notFoundCount}/${QUERY_NOT_FOUND_RETRY_LIMIT})`,
- );
- await sleep(QUERY_NOT_FOUND_RETRY_DELAY_MS);
- continue;
- }
-
- // status === "running" - query found
- notFoundCount = 0;
-
- // Abort HTTP connection on first successful poll (query continues on server)
- if (abortController) {
- logger.info(
- `Query ${queryId} confirmed running, aborting HTTP connection`,
- );
- abortController.abort();
- abortController = undefined; // Only abort once
- }
-
- await sleep(pollIntervalMs);
- }
-
- throw new Error(`Query ${queryId} timeout after ${timeoutMs}ms`);
-}
-
-/**
- * Executes a DELETE command with query tracking via AbortController.
- *
- * This function:
- * 1. Fires the DELETE command with a known query_id and abort_signal
- * 2. Waits for the query to register in ClickHouse
- * 3. Aborts the HTTP connection when query is confirmed running (query continues on server)
- * 4. Polls system.processes + system.query_log for completion
- *
- * This avoids HTTP connection timeouts (socket hang up) for long-running DELETE operations
- * by disconnecting from the HTTP layer while the query continues executing on ClickHouse.
- */
-export async function executeWithMutationMonitoring(
- opts: MutationWaiterOptions,
-): Promise<void> {
- const timeoutMs = env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS;
- const pollIntervalMs = env.LANGFUSE_ASYNC_DELETE_TRACKING_POLL_INTERVAL_MS;
- return instrumentAsync(
- { name: "clickhouse-mutation-waiter", spanKind: SpanKind.CLIENT },
- async (span) => {
- const queryId = `mutation-${opts.tableName}-${randomUUID()}`;
- const abortController = new AbortController();
-
- span.setAttribute("ch.query.id", queryId);
- span.setAttribute("ch.mutation.table", opts.tableName);
- span.setAttribute("ch.query.text", opts.query);
- span.setAttribute("db.system", "clickhouse");
- span.setAttribute("db.operation.name", "MUTATION_WAIT");
-
- logger.info(`Starting mutation ${queryId} for table ${opts.tableName}`, {
- tableName: opts.tableName,
- timeoutMs: timeoutMs,
- pollIntervalMs: pollIntervalMs,
- });
-
- // Track command errors (non-abort)
- let commandError: Error | undefined;
-
- // Fire the DELETE command (blocks until mutation completes, but we'll abort the HTTP connection)
- const commandPromise = commandClickhouse({
- query: opts.query,
- params: opts.params,
- tags: {
- ...opts.tags,
- queryId,
- },
- clickhouseConfigs: {
- // overriding timeout to ensure custom send_progress_in_http_headers
- // configuration is used by getClient
- request_timeout: timeoutMs,
- },
- clickhouseSettings: opts.clickhouseSettings,
- abortSignal: abortController.signal,
- });
-
- // Track errors - suppress expected abort errors, capture others
- commandPromise.catch((err) => {
- const isAbortError =
- err?.name === "AbortError" || err?.message?.includes("aborted");
- if (!isAbortError) {
- commandError = err;
- logger.info(`Mutation ${queryId} promise rejected: ${err?.message}`);
- }
- });
-
- // Wait for query to register in ClickHouse
- await sleep(QUERY_REGISTER_DELAY_MS);
-
- // Poll for completion, abort HTTP connection when query is first found running
- try {
- await waitForQueryCompletion(
- queryId,
- timeoutMs,
- pollIntervalMs,
- abortController,
- );
- } catch (pollError) {
- // If polling failed and we have a command error, prefer the command error
- // as it likely has more context about what went wrong
- if (commandError) {
- throw new Error(
- `Mutation ${queryId} failed: ${commandError.message}`,
- );
- }
- throw pollError;
- }
-
- span.setAttribute("ch.mutation.completed", true);
- },
- );
-}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index c417b95e67..73e134382e 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -34,7 +34,6 @@ export * from "./otel/utils";
export * from "./clickhouse/client";
export * from "./clickhouse/schemaUtils";
export * from "./clickhouse/schema";
-export * from "./clickhouse/mutationWaiter";
export * from "./clickhouse/queryTracking";
export * from "./repositories/definitions";
export * from "../utils/IORepresentation/chatML/types";
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index c88c40014c..3e48b082e6 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -6,7 +6,6 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
-import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { recordDistribution } from "../instrumentation";
import { logger } from "../logger";
@@ -1707,29 +1706,17 @@ export const deleteEventsByProjectId = async (projectId: string) => {
projectId,
};
- if (env.LANGFUSE_ASYNC_DELETE_TRACKING_ENABLED === "true") {
- await executeWithMutationMonitoring({
- tableName: "events",
- query,
- params: { projectId },
- tags,
- clickhouseSettings: {
- send_logs_level: "trace",
- },
- });
- } else {
- await commandClickhouse({
- query,
- params: { projectId },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags,
- clickhouseSettings: {
- send_logs_level: "trace",
- },
- });
- }
+ await commandClickhouse({
+ query,
+ params: { projectId },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags,
+ clickhouseSettings: {
+ send_logs_level: "trace",
+ },
+ });
};
/**
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 2427a831b0..21887fe488 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -29,7 +29,6 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
-import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import {
convertObservation,
enrichObservationWithModelData,
@@ -1262,23 +1261,14 @@ export const deleteObservationsByProjectId = async (projectId: string) => {
projectId,
};
- if (env.LANGFUSE_ASYNC_DELETE_TRACKING_ENABLED === "true") {
- await executeWithMutationMonitoring({
- tableName: "observations",
- query,
- params: { projectId },
- tags,
- });
- } else {
- await commandClickhouse({
- query,
- params: { projectId },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags,
- });
- }
+ await commandClickhouse({
+ query,
+ params: { projectId },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags,
+ });
};
export const deleteObservationsOlderThanDays = async (
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 5a2cf6b282..1d6be8e1be 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -32,7 +32,6 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
-import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import { ScoreRecordReadType } from "./definitions";
import { env } from "../../env";
import { _handleGetScoreById, _handleGetScoresByIds } from "./scores-utils";
@@ -1215,23 +1214,14 @@ export const deleteScoresByProjectId = async (projectId: string) => {
projectId,
};
- if (env.LANGFUSE_ASYNC_DELETE_TRACKING_ENABLED === "true") {
- await executeWithMutationMonitoring({
- tableName: "scores",
- query,
- params: { projectId },
- tags,
- });
- } else {
- await commandClickhouse({
- query,
- params: { projectId },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags,
- });
- }
+ await commandClickhouse({
+ query,
+ params: { projectId },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags,
+ });
};
export const deleteScoresOlderThanDays = async (
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 04a1e38956..7abe81a425 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -22,7 +22,6 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
-import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import { convertClickhouseToDomain } from "./traces_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
@@ -956,23 +955,14 @@ export const deleteTracesByProjectId = async (projectId: string) => {
WHERE project_id = {projectId: String};
`;
- if (env.LANGFUSE_ASYNC_DELETE_TRACKING_ENABLED === "true") {
- await executeWithMutationMonitoring({
- tableName: "traces",
- query,
- params: input.params,
- tags: input.tags,
- });
- } else {
- await commandClickhouse({
- query,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- });
- }
+ await commandClickhouse({
+ query,
+ params: input.params,
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
+ },
+ tags: input.tags,
+ });
},
});
};
diff --git a/worker/src/__tests__/mutationWaiter.test.ts b/worker/src/__tests__/mutationWaiter.test.ts
deleted file mode 100644
index 45a704c382..0000000000
--- a/worker/src/__tests__/mutationWaiter.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { expect, describe, it } from "vitest";
-import {
- createOrgProjectAndApiKey,
- createTrace,
- createTracesCh,
- executeWithMutationMonitoring,
- getTracesByIds,
-} from "@langfuse/shared/src/server";
-import { randomUUID } from "crypto";
-
-describe("MutationWaiter Integration", () => {
- it("should execute DELETE with mutation monitoring and wait for completion", async () => {
- // Setup - create test data
- const { projectId } = await createOrgProjectAndApiKey();
-
- const traceId = randomUUID();
- await createTracesCh([createTrace({ id: traceId, project_id: projectId })]);
-
- // Verify trace exists before deletion
- const tracesBefore = await getTracesByIds([traceId], projectId);
- expect(tracesBefore).toHaveLength(1);
-
- // Execute delete with mutation monitoring
- await executeWithMutationMonitoring({
- tableName: "traces",
- query: `DELETE FROM traces WHERE project_id = {projectId: String} AND id = {traceId: String};`,
- params: {
- projectId,
- traceId,
- },
- tags: { test: "mutationWaiter" },
- timeoutMs: 60_000,
- pollIntervalMs: 500,
- });
-
- // Verify trace is deleted
- const tracesAfter = await getTracesByIds([traceId], projectId);
- expect(tracesAfter).toHaveLength(0);
- }, 60_000);
-});