Skip to content

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

fix: a workaround for socket hangup issues in our delete pipeline. (#11408)

Valery Meleshkin12733ff7da1e
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 907171d740..98ae32ae4a 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -168,6 +168,16 @@ 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
+ // Mutation monitoring for ClickHouse DELETE operations
+ LANGFUSE_MUTATION_MONITOR_ENABLED: z.enum(["true", "false"]).default("false"),
+ // 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
new file mode 100644
index 0000000000..334898bb8f
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/mutationWaiter.ts
@@ -0,0 +1,177 @@
+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/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.ts
new file mode 100644
index 0000000000..13e92703aa
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/queryTracking.ts
@@ -0,0 +1,132 @@
+import { queryClickhouse } from "../repositories";
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export type QueryStatus = "running" | "completed" | "failed" | "not_found";
+
+// ============================================================================
+// Utilities
+// ============================================================================
+
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+// ============================================================================
+// Query Status Polling
+// ============================================================================
+
+/**
+ * Polls ClickHouse to determine the status of a query by its query_id.
+ * First checks system.processes for running queries, then system.query_log for completed/failed.
+ */
+export async function pollQueryStatus(
+ queryId: string,
+ tags?: Record<string, string>,
+): Promise<QueryStatus> {
+ const tagsWithDefaults = {
+ feature: "query-tracking",
+ operation: "pollQueryStatus",
+ ...tags,
+ };
+ // First check if still running in system.processes
+ const running = await queryClickhouse<{ query_id: string }>({
+ query: `
+ SELECT query_id
+ FROM clusterAllReplicas('default', 'system.processes')
+ WHERE query_id = {queryId: String}
+ LIMIT 1
+ `,
+ params: { queryId },
+ clickhouseConfigs: {
+ request_timeout: 60_000,
+ },
+ clickhouseSettings: {
+ skip_unavailable_shards: 1,
+ },
+ tags: tagsWithDefaults,
+ });
+
+ if (running.length > 0) {
+ return "running";
+ }
+
+ // Check query_log for completion status
+ const result = await queryClickhouse<{
+ type: string;
+ exception_code: string;
+ }>({
+ query: `
+ SELECT type, exception_code
+ FROM clusterAllReplicas('default', 'system.query_log')
+ WHERE query_id = {queryId: String}
+ ORDER BY event_time_microseconds DESC
+ LIMIT 1
+ `,
+ params: { queryId },
+ clickhouseConfigs: {
+ request_timeout: 60_000,
+ },
+ clickhouseSettings: {
+ skip_unavailable_shards: 1,
+ },
+ tags: {
+ feature: "query-tracking",
+ operation: "pollQueryStatus-queryLog",
+ },
+ });
+
+ if (result.length === 0) {
+ return "not_found";
+ }
+
+ const { type, exception_code } = result[0];
+ if (type === "QueryStart") {
+ return "running";
+ }
+
+ if (
+ type === "ExceptionBeforeStart" ||
+ type === "ExceptionWhileProcessing" ||
+ parseInt(exception_code, 10) !== 0
+ ) {
+ return "failed";
+ }
+
+ if (type === "QueryFinish") {
+ return "completed";
+ }
+
+ throw new Error(`Unknown query log type: ${type}`);
+}
+
+/**
+ * Gets the error message for a failed query from system.query_log.
+ */
+export async function getQueryError(
+ queryId: string,
+): Promise<string | undefined> {
+ const result = await queryClickhouse<{ exception_message: string }>({
+ query: `
+ SELECT exception as exception_message
+ FROM clusterAllReplicas('default', 'system.query_log')
+ WHERE query_id = {queryId: String}
+ AND type != 'QueryStart'
+ AND exception != ''
+ ORDER BY event_time_microseconds DESC
+ LIMIT 1
+ `,
+ params: { queryId },
+ clickhouseSettings: {
+ skip_unavailable_shards: 1,
+ },
+ tags: {
+ feature: "query-tracking",
+ operation: "getQueryError",
+ },
+ });
+
+ return result[0]?.exception_message;
+}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 2ca399026e..c417b95e67 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -34,6 +34,8 @@ 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";
export * from "../server/ingestion/types";
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 70af38be28..c88c40014c 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -6,6 +6,7 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
+import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { recordDistribution } from "../instrumentation";
import { logger } from "../logger";
@@ -1699,22 +1700,36 @@ export const deleteEventsByProjectId = async (projectId: string) => {
DELETE FROM events
WHERE project_id = {projectId: String};
`;
- await commandClickhouse({
- query,
- params: { projectId },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: {
- feature: "tracing",
- type: "events",
- kind: "delete",
- projectId,
- },
- clickhouseSettings: {
- send_logs_level: "trace",
- },
- });
+ const tags = {
+ feature: "tracing",
+ type: "events",
+ kind: "delete",
+ 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",
+ },
+ });
+ }
};
/**
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index e81b5488a6..2427a831b0 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -29,6 +29,7 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
+import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import {
convertObservation,
enrichObservationWithModelData,
@@ -1254,21 +1255,30 @@ export const deleteObservationsByProjectId = async (projectId: string) => {
DELETE FROM observations
WHERE project_id = {projectId: String};
`;
- await commandClickhouse({
- query: query,
- params: {
- projectId,
- },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: {
- feature: "tracing",
- type: "observation",
- kind: "delete",
- projectId,
- },
- });
+ const tags = {
+ feature: "tracing",
+ type: "observation",
+ kind: "delete",
+ 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,
+ });
+ }
};
export const deleteObservationsOlderThanDays = async (
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index c12b11e48e..5a2cf6b282 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -32,6 +32,7 @@ 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";
@@ -1207,21 +1208,30 @@ export const deleteScoresByProjectId = async (projectId: string) => {
DELETE FROM scores
WHERE project_id = {projectId: String};
`;
- await commandClickhouse({
- query: query,
- params: {
- projectId,
- },
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: {
- feature: "tracing",
- type: "score",
- kind: "delete",
- projectId,
- },
- });
+ const tags = {
+ feature: "tracing",
+ type: "score",
+ kind: "delete",
+ 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,
+ });
+ }
};
export const deleteScoresOlderThanDays = async (
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 6c5df715eb..04a1e38956 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -22,6 +22,7 @@ import {
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
+import { executeWithMutationMonitoring } from "../clickhouse/mutationWaiter";
import { convertClickhouseToDomain } from "./traces_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
@@ -954,14 +955,24 @@ export const deleteTracesByProjectId = async (projectId: string) => {
DELETE FROM traces
WHERE project_id = {projectId: String};
`;
- await commandClickhouse({
- query: query,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- });
+
+ 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,
+ });
+ }
},
});
};
diff --git a/worker/src/__tests__/mutationWaiter.test.ts b/worker/src/__tests__/mutationWaiter.test.ts
new file mode 100644
index 0000000000..45a704c382
--- /dev/null
+++ b/worker/src/__tests__/mutationWaiter.test.ts
@@ -0,0 +1,40 @@
+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);
+});
diff --git a/worker/src/backgroundMigrations/backfillEventsHistoric.ts b/worker/src/backgroundMigrations/backfillEventsHistoric.ts
index 753f6c2423..64a0eb22cb 100644
--- a/worker/src/backgroundMigrations/backfillEventsHistoric.ts
+++ b/worker/src/backgroundMigrations/backfillEventsHistoric.ts
@@ -4,6 +4,9 @@ import {
commandClickhouse,
logger,
queryClickhouse,
+ pollQueryStatus,
+ getQueryError,
+ sleep,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { env } from "../env";
@@ -62,114 +65,6 @@ export type OnQueryCompleteCallback<T extends BaseChunkTodo> = (
error?: string,
) => Promise<void>;
-// ============================================================================
-// Query Status Polling
-// ============================================================================
-
-type QueryStatus = "running" | "completed" | "failed" | "not_found";
-
-export async function pollQueryStatus(queryId: string): Promise<QueryStatus> {
- // First check if still running in system.processes
- const running = await queryClickhouse<{ query_id: string }>({
- query: `
- SELECT query_id
- FROM clusterAllReplicas('default', 'system.processes')
- WHERE query_id = {queryId: String}
- LIMIT 1
- `,
- params: { queryId },
- clickhouseConfigs: {
- request_timeout: 60_000, // 60s timeout for polling queries
- },
- clickhouseSettings: {
- skip_unavailable_shards: 1,
- },
- tags: {
- feature: "background-migration",
- operation: "pollQueryStatus-processes",
- },
- });
-
- if (running.length > 0) {
- return "running";
- }
-
- // Check query_log for completion status
- const result = await queryClickhouse<{
- type: string;
- exception_code: string;
- }>({
- query: `
- SELECT type, exception_code
- FROM clusterAllReplicas('default', 'system.query_log')
- WHERE query_id = {queryId: String}
- -- AND type != 'QueryStart'
- ORDER BY event_time_microseconds DESC
- LIMIT 1
- `,
- params: { queryId },
- clickhouseConfigs: {
- request_timeout: 60_000, // 60s timeout for polling queries
- },
- clickhouseSettings: {
- skip_unavailable_shards: 1,
- },
- tags: {
- feature: "background-migration",
- operation: "pollQueryStatus-queryLog",
- },
- });
-
- if (result.length === 0) {
- return "not_found";
- }
-
- const { type, exception_code } = result[0];
- if (type === "QueryStart") {
- return "running";
- }
-
- if (
- type === "ExceptionBeforeStart" ||
- type === "ExceptionWhileProcessing" ||
- parseInt(exception_code, 10) !== 0
- ) {
- return "failed";
- }
-
- if (type === "QueryFinish") {
- return "completed";
- }
-
- throw new Error(`Unknown query log type: ${type}`);
-}
-
-export async function getQueryError(
- queryId: string,
-): Promise<string | undefined> {
- const result = await queryClickhouse<{ exception_message: string }>({
- query: `
- SELECT exception as exception_message
- FROM clusterAllReplicas('default', 'system.query_log')
- WHERE query_id = {queryId: String}
- AND type != 'QueryStart'
- AND exception != ''
- ORDER BY event_time_microseconds DESC
- LIMIT 1
- `,
- params: { queryId },
- clickhouseSettings: {
- skip_unavailable_shards: 1,
- },
- tags: {
- feature: "background-migration",
- operation: "getQueryError",
- },
- });
-
- return result[0]?.exception_message;
-}
-
// ============================================================================
// Concurrent Query Manager
// ============================================================================
@@ -273,10 +168,6 @@ export function generateQueryId(chunkId: string): string {
return `backfill-${chunkId}-${randomUUID().slice(0, 8)}`;
}
-export function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
// ============================================================================
// Migration Class
// ============================================================================
diff --git a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts b/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
index fea81182d7..a1fd75c5f7 100644
--- a/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
+++ b/worker/src/backgroundMigrations/backfillEventsHistoricFromParts.ts
@@ -12,10 +12,13 @@ import {
BaseChunkTodo,
ConcurrentQueryManager,
generateQueryId,
+} from "./backfillEventsHistoric";
+
+import {
getQueryError,
pollQueryStatus,
sleep,
-} from "./backfillEventsHistoric";
+} from "@langfuse/shared/src/server";
// This is hard-coded in our migrations and uniquely identifies the row in background_migrations table
const backgroundMigrationId = "d08146bd-3841-4ed3-a42c-5f43ff94b14e";