Skip to content

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

feat(worker): add BullMQ stall + blob export observability (LFE-10388) (#14379)

Niklas Semmler0fd6ae2cabc1
diff --git a/worker/src/__tests__/inFlightExports.unit.test.ts b/worker/src/__tests__/inFlightExports.unit.test.ts
new file mode 100644
index 0000000000..5c58abc5b1
--- /dev/null
+++ b/worker/src/__tests__/inFlightExports.unit.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// The tracker only needs a logger; stub the heavy shared server barrel.
+vi.mock("@langfuse/shared/src/server", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import {
+ registerInFlightBlobExport,
+ unregisterInFlightBlobExport,
+ getInFlightBlobExportCount,
+ logInFlightBlobExportsOnShutdown,
+ resetInFlightBlobExports,
+} from "../features/blobstorage/inFlightExports";
+
+const makeEntry = (table: string) => ({
+ jobId: `job-${table}`,
+ projectId: "p-1",
+ table,
+ minTimestamp: "2025-12-01T00:00:00.000Z",
+ maxTimestamp: "2025-12-02T00:00:00.000Z",
+ startedAt: 1,
+});
+
+describe("inFlightExports", () => {
+ // Singleton registry — drain it so tests are order-independent.
+ beforeEach(() => resetInFlightBlobExports());
+
+ it("tracks and clears in-flight exports by handle", () => {
+ expect(getInFlightBlobExportCount()).toBe(0);
+
+ const h1 = registerInFlightBlobExport(makeEntry("traces"));
+ const h2 = registerInFlightBlobExport(makeEntry("scores"));
+ expect(getInFlightBlobExportCount()).toBe(2);
+
+ unregisterInFlightBlobExport(h1);
+ expect(getInFlightBlobExportCount()).toBe(1);
+
+ unregisterInFlightBlobExport(h2);
+ expect(getInFlightBlobExportCount()).toBe(0);
+ });
+
+ it("keeps distinct entries for the same project/table pair", () => {
+ const h1 = registerInFlightBlobExport(makeEntry("observations"));
+ const h2 = registerInFlightBlobExport(makeEntry("observations"));
+ expect(h1).not.toBe(h2);
+ expect(getInFlightBlobExportCount()).toBe(2);
+
+ unregisterInFlightBlobExport(h1);
+ unregisterInFlightBlobExport(h2);
+ expect(getInFlightBlobExportCount()).toBe(0);
+ });
+
+ it("logInFlightBlobExportsOnShutdown does not throw whether empty or populated", () => {
+ expect(() => logInFlightBlobExportsOnShutdown()).not.toThrow();
+
+ const h = registerInFlightBlobExport(makeEntry("traces"));
+ expect(() => logInFlightBlobExportsOnShutdown()).not.toThrow();
+ unregisterInFlightBlobExport(h);
+ });
+});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 14b79f7f6d..7d71d3701f 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -1,5 +1,7 @@
import { pipeline, Transform } from "stream";
import { createGzip } from "zlib";
+import { hostname } from "os";
+import { monitorEventLoopDelay } from "perf_hooks";
import { Job } from "bullmq";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -15,6 +17,7 @@ import {
getEventsForBlobStorageExport,
getCurrentSpan,
instrumentAsync,
+ recordGauge,
BlobStorageIntegrationProcessingQueue,
queryClickhouse,
QueueJobs,
@@ -25,6 +28,10 @@ import {
blobStorageEndpointConnectionValidationOptions,
validateBlobStorageEndpoint,
} from "@langfuse/shared/src/server";
+import {
+ registerInFlightBlobExport,
+ unregisterInFlightBlobExport,
+} from "./inFlightExports";
import {
BlobStorageIntegrationType,
BlobStorageIntegrationFileType,
@@ -41,6 +48,8 @@ import { env, v4AllowPreviewOptIn } from "../../env";
export const BLOB_STORAGE_LAG_BUFFER_MS = 20 * 60 * 1000; // 20-minute lag buffer
+const HOST_NAME = hostname();
+
export async function* enrichObservationStream(
stream: AsyncGenerator<Record<string, unknown>>,
projectId: string,
@@ -246,6 +255,8 @@ const processBlobStorageExport = async (config: {
compressed: boolean;
convertV4LatencyToSeconds: boolean;
exportFieldGroups?: ObservationFieldGroupFull[];
+ bullmqJobId: string | undefined;
+ bullmqAttemptsMade: number;
}) => {
logger.info(
`[BLOB INTEGRATION] Processing ${config.table} export for project ${config.projectId}`,
@@ -286,6 +297,27 @@ const processBlobStorageExport = async (config: {
"blob.window.maxTimestamp",
config.maxTimestamp.toISOString(),
);
+ // Identity + host to group concurrent duplicate runs of the same window.
+ if (config.bullmqJobId !== undefined) {
+ span.setAttribute("messaging.bullmq.job.id", config.bullmqJobId);
+ }
+ span.setAttribute("job.attemptsMade", config.bullmqAttemptsMade);
+ span.setAttribute("host.name", HOST_NAME);
+
+ // Event-loop delay during the stream: if it spikes, lock renewal can't
+ // fire and the job re-enqueues as stalled (LFE-10063). Torn down below.
+ const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });
+ eventLoopDelay.enable();
+
+ // In-flight so a SIGTERM abort is loggable distinctly from a stall-timeout.
+ const inFlightHandle = registerInFlightBlobExport({
+ jobId: config.bullmqJobId,
+ projectId: config.projectId,
+ table: config.table,
+ minTimestamp: config.minTimestamp.toISOString(),
+ maxTimestamp: config.maxTimestamp.toISOString(),
+ startedAt: Date.now(),
+ });
try {
const blobStorageProps = getFileTypeProperties(config.fileType);
@@ -405,6 +437,7 @@ const processBlobStorageExport = async (config: {
logger.info(
`[BLOB INTEGRATION] Successfully exported ${config.table} for project ${config.projectId}: ` +
+ `jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${HOST_NAME} ` +
`rows=${sourceStats.rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` +
`serializedBytes=${serializedCounter.bytes} uploadDurationMs=${Math.round(performance.now() - uploadStartMs)}`,
);
@@ -427,10 +460,35 @@ const processBlobStorageExport = async (config: {
}
} catch (error) {
logger.error(
- `[BLOB INTEGRATION] Error exporting ${config.table} for project ${config.projectId}`,
+ `[BLOB INTEGRATION] Error exporting ${config.table} for project ${config.projectId} ` +
+ `(jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${HOST_NAME})`,
error,
);
throw error;
+ } finally {
+ unregisterInFlightBlobExport(inFlightHandle);
+
+ // ns → ms; the histogram yields NaN/Infinity with zero samples.
+ eventLoopDelay.disable();
+ const toFiniteMs = (ns: number): number =>
+ Number.isFinite(ns) ? ns / 1e6 : 0;
+ const maxMs = toFiniteMs(eventLoopDelay.max);
+ const p99Ms = toFiniteMs(eventLoopDelay.percentile(99));
+ const meanMs = toFiniteMs(eventLoopDelay.mean);
+ const delayTags = { table: config.table, unit: "milliseconds" };
+ recordGauge(
+ "langfuse.blobstorage.event_loop_delay.max",
+ maxMs,
+ delayTags,
+ );
+ recordGauge(
+ "langfuse.blobstorage.event_loop_delay.p99",
+ p99Ms,
+ delayTags,
+ );
+ span.setAttribute("blob.eventLoopDelay.maxMs", Math.round(maxMs));
+ span.setAttribute("blob.eventLoopDelay.p99Ms", Math.round(p99Ms));
+ span.setAttribute("blob.eventLoopDelay.meanMs", Math.round(meanMs));
}
},
);
@@ -445,6 +503,12 @@ export const handleBlobStorageIntegrationProjectJob = async (
if (span) {
span.setAttribute("messaging.bullmq.job.input.jobId", job.data.id);
span.setAttribute("messaging.bullmq.job.input.projectId", projectId);
+ // BullMQ job id (distinct from the payload id above) + attempt count.
+ if (job.id !== undefined) {
+ span.setAttribute("messaging.bullmq.job.id", job.id);
+ }
+ span.setAttribute("job.attemptsMade", job.attemptsMade);
+ span.setAttribute("host.name", HOST_NAME);
}
logger.info(
@@ -565,6 +629,8 @@ export const handleBlobStorageIntegrationProjectJob = async (
convertV4LatencyToSeconds,
exportFieldGroups:
blobStorageIntegration.exportFieldGroups as ObservationFieldGroupFull[],
+ bullmqJobId: job.id,
+ bullmqAttemptsMade: job.attemptsMade,
};
// Check if this project should only export traces (legacy behavior via env var)
diff --git a/worker/src/features/blobstorage/inFlightExports.ts b/worker/src/features/blobstorage/inFlightExports.ts
new file mode 100644
index 0000000000..42dbb863ae
--- /dev/null
+++ b/worker/src/features/blobstorage/inFlightExports.ts
@@ -0,0 +1,59 @@
+import { hostname } from "os";
+import { logger } from "@langfuse/shared/src/server";
+
+const HOST_NAME = hostname();
+
+export type InFlightBlobExport = {
+ jobId: string | undefined;
+ projectId: string;
+ table: string;
+ minTimestamp: string;
+ maxTimestamp: string;
+ startedAt: number;
+};
+
+// Stall-timeouts and SIGTERM aborts look identical from Postgres (both freeze
+// `lastSyncAt`); logging the survivors on shutdown separates the two.
+const inFlightExports = new Map<symbol, InFlightBlobExport>();
+
+// Returns a handle that MUST be passed to unregister in a `finally`.
+export const registerInFlightBlobExport = (
+ entry: InFlightBlobExport,
+): symbol => {
+ const handle = Symbol(`${entry.projectId}:${entry.table}`);
+ inFlightExports.set(handle, entry);
+ return handle;
+};
+
+export const unregisterInFlightBlobExport = (handle: symbol): void => {
+ inFlightExports.delete(handle);
+};
+
+export const getInFlightBlobExportCount = (): number => inFlightExports.size;
+
+// Test helper — clear leaked state between tests.
+export const resetInFlightBlobExports = (): void => {
+ inFlightExports.clear();
+};
+
+// Called on graceful shutdown, before workers close.
+export const logInFlightBlobExportsOnShutdown = (): void => {
+ if (inFlightExports.size === 0) {
+ logger.info(
+ `[BLOB INTEGRATION] No blob storage exports in-flight at shutdown on host ${HOST_NAME}`,
+ );
+ return;
+ }
+
+ const now = Date.now();
+ for (const entry of inFlightExports.values()) {
+ // "in-flight at shutdown", not "aborted": worker.close() drains gracefully,
+ // so this export may still complete within the grace period.
+ logger.warn(
+ `[BLOB INTEGRATION] Blob storage export in-flight at shutdown signal on host ${HOST_NAME}: ` +
+ `jobId=${entry.jobId} projectId=${entry.projectId} table=${entry.table} ` +
+ `window=[${entry.minTimestamp}, ${entry.maxTimestamp}] ` +
+ `elapsedMs=${now - entry.startedAt}`,
+ );
+ }
+};
diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.ts
index 7f71528ed4..b34da39638 100644
--- a/worker/src/queues/workerManager.ts
+++ b/worker/src/queues/workerManager.ts
@@ -1,3 +1,4 @@
+import { hostname } from "os";
import { Job, Processor, Worker, WorkerOptions } from "bullmq";
import {
convertQueueNameToMetricName,
@@ -16,6 +17,8 @@ import {
SHARDED_QUEUE_BASE_NAMES,
} from "./shardedQueueRegistry";
+const HOST_NAME = hostname();
+
export class WorkerManager {
private static workers: { [key: string]: Worker } = {};
@@ -180,5 +183,19 @@ export class WorkerManager {
...shardTag,
});
});
+ // Counts intermediate re-enqueues (LFE-10063), not just the terminal
+ // "stalled more than allowable limit" the "failed" handler catches.
+ worker.on("stalled", (jobId: string) => {
+ // detectedOnHost: the stall-checker pod, which may differ from the pod
+ // whose lock expired.
+ logger.warn(
+ `Queue job ${jobId} in ${queueName} stalled (lock expired, re-enqueued) detectedOnHost=${HOST_NAME}`,
+ );
+ recordIncrement(oldMetric + ".stalled");
+ recordIncrement(baseMetric + ".rate", 1, {
+ type: "stalled",
+ ...shardTag,
+ });
+ });
}
}
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index 5d25acff6d..8265a06c51 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -7,6 +7,7 @@ import { server } from "../index";
import { freeAllTokenizers } from "../features/tokenisation/usage";
import { getTokenCountWorkerManager } from "../features/tokenisation/async-usage";
import { WorkerManager } from "../queues/workerManager";
+import { logInFlightBlobExportsOnShutdown } from "../features/blobstorage/inFlightExports";
import { prisma } from "@langfuse/shared/src/db";
import { BackgroundMigrationManager } from "../backgroundMigrations/backgroundMigrationManager";
import {
@@ -62,6 +63,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
runner.stop();
}
+ // Before closeWorkers(), while the registry is still populated (LFE-10388).
+ logInFlightBlobExportsOnShutdown();
+
// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)
await WorkerManager.closeWorkers();