Skip to content

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

chore: remove explicit context propagation for queues (#3622)

Steffen Schmitzed083319276b
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.ts
index daeb9e5d71..246a114f0a 100644
--- a/packages/shared/src/server/instrumentation/index.ts
+++ b/packages/shared/src/server/instrumentation/index.ts
@@ -86,18 +86,6 @@ export function instrumentSync<T>(
export const getCurrentSpan = () => opentelemetry.trace.getActiveSpan();
-export const addTraceContext = <T extends Record<string, any>>(
- input: T,
-): T & { _tracecontext?: TCarrier } => {
- const context = {};
- opentelemetry.propagation.inject(opentelemetry.context.active(), context);
-
- return {
- ...input,
- _tracecontext: context,
- };
-};
-
export const traceException = (
ex: unknown,
span?: opentelemetry.Span,
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 9879e13d86..495cf6f40c 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -14,7 +14,6 @@ import {
recordIncrement,
getCurrentSpan,
LegacyIngestionQueue,
- addTraceContext,
S3StorageService,
instrumentAsync,
} from "@langfuse/shared/src/server";
@@ -214,12 +213,12 @@ export default async function handler(
try {
await queue.add(
QueueJobs.LegacyIngestionJob,
- addTraceContext({
+ {
payload: { data: sortedBatch, authCheck: authCheck },
id: randomUUID(),
timestamp: new Date(),
name: QueueJobs.LegacyIngestionJob as const,
- }),
+ },
{
removeOnFail: 1_000_000,
removeOnComplete: true,
diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.ts
index cc9e3b75b7..07f71533e9 100644
--- a/web/src/server/api/routers/batchExport.ts
+++ b/web/src/server/api/routers/batchExport.ts
@@ -12,7 +12,6 @@ import {
type EventBodyType,
EventName,
QueueJobs,
- addTraceContext,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { redis } from "@langfuse/shared/src/server";
@@ -74,15 +73,12 @@ export const batchExportRouter = createTRPCRouter({
};
if (redis && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- await getBatchExportQueue()?.add(
- event.name,
- addTraceContext({
- id: event.payload.batchExportId, // Use the batchExportId to deduplicate when the same job is sent multiple times
- name: QueueJobs.BatchExportJob,
- timestamp: new Date(),
- payload: event.payload,
- }),
- );
+ await getBatchExportQueue()?.add(event.name, {
+ id: event.payload.batchExportId, // Use the batchExportId to deduplicate when the same job is sent multiple times
+ name: QueueJobs.BatchExportJob,
+ timestamp: new Date(),
+ payload: event.payload,
+ });
} else {
await new WorkerClient().sendEvent(event);
}
diff --git a/worker/src/queues/batchExportQueue.ts b/worker/src/queues/batchExportQueue.ts
index 4203d6d6f1..37de690500 100644
--- a/worker/src/queues/batchExportQueue.ts
+++ b/worker/src/queues/batchExportQueue.ts
@@ -3,52 +3,38 @@ import { Job } from "bullmq";
import { BaseError, BatchExportStatus } from "@langfuse/shared";
import { kyselyPrisma } from "@langfuse/shared/src/db";
-import {
- traceException,
- instrumentAsync,
- logger,
-} from "@langfuse/shared/src/server";
+import { traceException, logger } from "@langfuse/shared/src/server";
import { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
import { handleBatchExportJob } from "../features/batchExport/handleBatchExportJob";
-import { SpanKind } from "@opentelemetry/api";
export const batchExportQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.BatchExport]>,
) => {
- return instrumentAsync(
- {
- name: "batchExportJobExecutor",
- spanKind: SpanKind.CONSUMER,
- traceContext: job.data?._tracecontext,
- },
- async () => {
- try {
- logger.info("Executing Batch Export Job", job.data.payload);
- await handleBatchExportJob(job.data.payload);
+ try {
+ logger.info("Executing Batch Export Job", job.data.payload);
+ await handleBatchExportJob(job.data.payload);
- logger.info("Finished Batch Export Job", job.data.payload);
+ logger.info("Finished Batch Export Job", job.data.payload);
- return true;
- } catch (e) {
- const displayError =
- e instanceof BaseError ? e.message : "An internal error occurred";
+ return true;
+ } catch (e) {
+ const displayError =
+ e instanceof BaseError ? e.message : "An internal error occurred";
- await kyselyPrisma.$kysely
- .updateTable("batch_exports")
- .set("status", BatchExportStatus.FAILED)
- .set("finished_at", new Date())
- .set("log", displayError)
- .where("id", "=", job.data.payload.batchExportId)
- .where("project_id", "=", job.data.payload.projectId)
- .execute();
+ await kyselyPrisma.$kysely
+ .updateTable("batch_exports")
+ .set("status", BatchExportStatus.FAILED)
+ .set("finished_at", new Date())
+ .set("log", displayError)
+ .where("id", "=", job.data.payload.batchExportId)
+ .where("project_id", "=", job.data.payload.projectId)
+ .execute();
- logger.error(
- `Failed Batch Export job for id ${job.data.payload.batchExportId}`,
- e,
- );
- traceException(e);
- throw e;
- }
- },
- );
+ logger.error(
+ `Failed Batch Export job for id ${job.data.payload.batchExportId}`,
+ e,
+ );
+ traceException(e);
+ throw e;
+ }
};
diff --git a/worker/src/queues/cloudUsageMeteringQueue.ts b/worker/src/queues/cloudUsageMeteringQueue.ts
index 6193a21435..b772a84de0 100644
--- a/worker/src/queues/cloudUsageMeteringQueue.ts
+++ b/worker/src/queues/cloudUsageMeteringQueue.ts
@@ -4,7 +4,6 @@ import {
logger,
QueueName,
QueueJobs,
- instrumentAsync,
} from "@langfuse/shared/src/server";
import { handleCloudUsageMeteringJob } from "../ee/cloudUsageMetering/handleCloudUsageMeteringJob";
import { env } from "../env";
@@ -36,20 +35,12 @@ if (cloudUsageMeteringQueue) {
export const cloudUsageMeteringQueueProcessor: Processor = async (job) => {
if (job.name === QueueJobs.CloudUsageMeteringJob) {
- return instrumentAsync(
- {
- name: "cloudUsageMeteringJobExecutor",
- traceContext: job.data?._tracecontext,
- },
- async () => {
- logger.info("Executing Cloud Usage Metering Job", job.data);
- try {
- return await handleCloudUsageMeteringJob(job);
- } catch (error) {
- logger.error("Error executing Cloud Usage Metering Job", error);
- throw error;
- }
- },
- );
+ logger.info("Executing Cloud Usage Metering Job", job.data);
+ try {
+ return await handleCloudUsageMeteringJob(job);
+ } catch (error) {
+ logger.error("Error executing Cloud Usage Metering Job", error);
+ throw error;
+ }
}
};
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 6c4c1496c3..e78cdc441e 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -9,13 +9,11 @@ import {
TQueueJobTypes,
logger,
traceException,
- instrumentAsync,
recordIncrement,
recordHistogram,
recordGauge,
getTraceUpsertQueue,
} from "@langfuse/shared/src/server";
-import { SpanKind } from "@opentelemetry/api";
let evalQueue: Queue<TQueueJobTypes[QueueName.EvaluationExecution]> | null =
null;
@@ -40,125 +38,100 @@ export const getEvalQueue = () => {
export const evalJobCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
) => {
- return instrumentAsync(
- {
- name: "evalJobCreator",
- rootSpan: true,
- spanKind: SpanKind.CONSUMER,
- traceContext: job.data?._tracecontext,
- },
- async () => {
- try {
- const startTime = Date.now();
-
- const waitTime = Date.now() - job.timestamp;
- recordIncrement("langfuse.queue.trace_upsert.request");
- recordHistogram("langfuse.queue.trace_upsert.wait_time", waitTime, {
- unit: "milliseconds",
+ try {
+ const startTime = Date.now();
+
+ const waitTime = Date.now() - job.timestamp;
+ recordIncrement("langfuse.queue.trace_upsert.request");
+ recordHistogram("langfuse.queue.trace_upsert.wait_time", waitTime, {
+ unit: "milliseconds",
+ });
+
+ await createEvalJobs({ event: job.data.payload });
+
+ await getTraceUpsertQueue()
+ ?.count()
+ .then((count) => {
+ logger.debug(`Eval creation queue length: ${count}`);
+ recordGauge("trace_upsert_queue_length", count, {
+ unit: "records",
});
-
- await createEvalJobs({ event: job.data.payload });
-
- await getTraceUpsertQueue()
- ?.count()
- .then((count) => {
- logger.debug(`Eval creation queue length: ${count}`);
- recordGauge("trace_upsert_queue_length", count, {
- unit: "records",
- });
- return count;
- })
- .catch();
- recordHistogram(
- "langfuse.queue.trace_upsert.processing_time",
- Date.now() - startTime,
- { unit: "milliseconds" },
- );
- return true;
- } catch (e) {
- logger.error(
- `Failed job Evaluation for traceId ${job.data.payload.traceId}`,
- e,
- );
- traceException(e);
- throw e;
- }
- },
- );
+ return count;
+ })
+ .catch();
+ recordHistogram(
+ "langfuse.queue.trace_upsert.processing_time",
+ Date.now() - startTime,
+ { unit: "milliseconds" },
+ );
+ return true;
+ } catch (e) {
+ logger.error(
+ `Failed job Evaluation for traceId ${job.data.payload.traceId}`,
+ e,
+ );
+ traceException(e);
+ throw e;
+ }
};
export const evalJobExecutorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.EvaluationExecution]>,
) => {
- return instrumentAsync(
- {
- name: "evalJobExecutor",
- spanKind: SpanKind.CONSUMER,
- traceContext: job.data?._tracecontext,
- },
- async () => {
- try {
- logger.info("Executing Evaluation Execution Job", job.data);
- const startTime = Date.now();
-
- const waitTime = Date.now() - job.timestamp;
- recordIncrement("langfuse.queue.evaluation_execution.request");
- recordHistogram(
- "langfuse.queue.evaluation_execution.wait_time",
- waitTime,
- {
- unit: "milliseconds",
- },
- );
-
- await evaluate({ event: job.data.payload });
-
- await getEvalQueue()
- ?.count()
- .then((count) => {
- logger.debug(`Eval execution queue length: ${count}`);
- recordGauge("eval_execution_queue_length", count, {
- unit: "records",
- });
- return count;
- })
- .catch();
- recordHistogram(
- "langfuse.queue.evaluation_execution.processing_time",
- Date.now() - startTime,
- { unit: "milliseconds" },
- );
-
- return true;
- } catch (e) {
- const displayError =
- e instanceof BaseError ? e.message : "An internal error occurred";
-
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'ERROR'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .set("error", displayError)
- .where("id", "=", job.data.payload.jobExecutionId)
- .where("project_id", "=", job.data.payload.projectId)
- .execute();
-
- // do not log expected errors (api failures + missing api keys not provided by the user)
- if (
- !(e instanceof ApiError) &&
- !(
- e instanceof BaseError && e.message.includes("API key for provider")
- )
- ) {
- traceException(e);
- logger.error(
- `Failed Evaluation_Execution job for id ${job.data.payload.jobExecutionId}`,
- e,
- );
- }
-
- throw e;
- }
- },
- );
+ try {
+ logger.info("Executing Evaluation Execution Job", job.data);
+ const startTime = Date.now();
+
+ const waitTime = Date.now() - job.timestamp;
+ recordIncrement("langfuse.queue.evaluation_execution.request");
+ recordHistogram("langfuse.queue.evaluation_execution.wait_time", waitTime, {
+ unit: "milliseconds",
+ });
+
+ await evaluate({ event: job.data.payload });
+
+ await getEvalQueue()
+ ?.count()
+ .then((count) => {
+ logger.debug(`Eval execution queue length: ${count}`);
+ recordGauge("eval_execution_queue_length", count, {
+ unit: "records",
+ });
+ return count;
+ })
+ .catch();
+ recordHistogram(
+ "langfuse.queue.evaluation_execution.processing_time",
+ Date.now() - startTime,
+ { unit: "milliseconds" },
+ );
+
+ return true;
+ } catch (e) {
+ const displayError =
+ e instanceof BaseError ? e.message : "An internal error occurred";
+
+ await kyselyPrisma.$kysely
+ .updateTable("job_executions")
+ .set("status", sql`'ERROR'::"JobExecutionStatus"`)
+ .set("end_time", new Date())
+ .set("error", displayError)
+ .where("id", "=", job.data.payload.jobExecutionId)
+ .where("project_id", "=", job.data.payload.projectId)
+ .execute();
+
+ // do not log expected errors (api failures + missing api keys not provided by the user)
+ if (
+ !(e instanceof ApiError) &&
+ !(e instanceof BaseError && e.message.includes("API key for provider"))
+ ) {
+ traceException(e);
+ logger.error(
+ `Failed Evaluation_Execution job for id ${job.data.payload.jobExecutionId}`,
+ e,
+ );
+ }
+
+ throw e;
+ }
};
diff --git a/worker/src/queues/ingestionFlushQueueExecutor.ts b/worker/src/queues/ingestionFlushQueueExecutor.ts
index 73418668a2..c0bd676764 100644
--- a/worker/src/queues/ingestionFlushQueueExecutor.ts
+++ b/worker/src/queues/ingestionFlushQueueExecutor.ts
@@ -6,84 +6,73 @@ import {
clickhouseClient,
logger,
getIngestionFlushQueue,
- instrumentAsync,
recordIncrement,
recordGauge,
recordHistogram,
} from "@langfuse/shared/src/server";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
import { IngestionService } from "../services/IngestionService";
-import { SpanKind } from "@opentelemetry/api";
const ingestionFlushQueue = getIngestionFlushQueue();
export const ingestionFlushQueueProcessor: Processor = async (job) => {
- return instrumentAsync(
- {
- name: "flush-ingestion-consumer",
- spanKind: SpanKind.CONSUMER,
- traceContext: job.data?._tracecontext,
- },
- async () => {
- if (job.name === QueueJobs.FlushIngestionEntity) {
- const flushKey = job.id;
- if (!flushKey) {
- throw new Error("Flushkey not provided");
- }
+ if (job.name === QueueJobs.FlushIngestionEntity) {
+ const flushKey = job.id;
+ if (!flushKey) {
+ throw new Error("Flushkey not provided");
+ }
- // Log wait time
- const waitTime = Date.now() - job.timestamp;
- recordIncrement("langfuse.queue.ingestion_flush.request");
- recordHistogram("langfuse.queue.ingestion_flush.wait_time", waitTime, {
- unit: "milliseconds",
- });
+ // Log wait time
+ const waitTime = Date.now() - job.timestamp;
+ recordIncrement("langfuse.queue.ingestion_flush.request");
+ recordHistogram("langfuse.queue.ingestion_flush.wait_time", waitTime, {
+ unit: "milliseconds",
+ });
- try {
- // Check dependencies
- if (!redis) throw new Error("Redis not available");
- if (!prisma) throw new Error("Prisma not available");
- if (!ingestionFlushQueue)
- throw new Error("Ingestion flush queue not available");
+ try {
+ // Check dependencies
+ if (!redis) throw new Error("Redis not available");
+ if (!prisma) throw new Error("Prisma not available");
+ if (!ingestionFlushQueue)
+ throw new Error("Ingestion flush queue not available");
- // Flush ingestion buffer
- const processingStartTime = Date.now();
+ // Flush ingestion buffer
+ const processingStartTime = Date.now();
- await new IngestionService(
- redis,
- prisma,
- ClickhouseWriter.getInstance(),
- clickhouseClient,
- ).flush(flushKey);
+ await new IngestionService(
+ redis,
+ prisma,
+ ClickhouseWriter.getInstance(),
+ clickhouseClient,
+ ).flush(flushKey);
- // Log processing time
- const processingTime = Date.now() - processingStartTime;
- logger.debug(
- `Prepared and scheduled CH-write in ${processingTime} ms for ${flushKey}`,
- );
- recordHistogram(
- "langfuse.queue.ingestion_flush.processing_time",
- processingTime,
- {
- unit: "milliseconds",
- },
- );
+ // Log processing time
+ const processingTime = Date.now() - processingStartTime;
+ logger.debug(
+ `Prepared and scheduled CH-write in ${processingTime} ms for ${flushKey}`,
+ );
+ recordHistogram(
+ "langfuse.queue.ingestion_flush.processing_time",
+ processingTime,
+ {
+ unit: "milliseconds",
+ },
+ );
- // Log queue size
- await ingestionFlushQueue
- .count()
- .then((count) => {
- logger.debug(`Ingestion flush queue length: ${count}`);
- recordGauge("langfuse.queue.ingestion_flush.length", count, {
- unit: "records",
- });
- return count;
- })
- .catch();
- } catch (err) {
- logger.error(`Error processing flush request for ${flushKey}`, err);
- throw err;
- }
- }
- },
- );
+ // Log queue size
+ await ingestionFlushQueue
+ .count()
+ .then((count) => {
+ logger.debug(`Ingestion flush queue length: ${count}`);
+ recordGauge("langfuse.queue.ingestion_flush.length", count, {
+ unit: "records",
+ });
+ return count;
+ })
+ .catch();
+ } catch (err) {
+ logger.error(`Error processing flush request for ${flushKey}`, err);
+ throw err;
+ }
+ }
};
diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.ts
index 603e6bdb07..45e06b2257 100644
--- a/worker/src/queues/legacyIngestionQueue.ts
+++ b/worker/src/queues/legacyIngestionQueue.ts
@@ -2,7 +2,6 @@ import { Job, Processor } from "bullmq";
import {
traceException,
LegacyIngestionQueue,
- instrumentAsync,
QueueName,
recordIncrement,
recordGauge,
@@ -16,83 +15,72 @@ import {
sendToWorkerIfEnvironmentConfigured,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../features/tokenisation/usage";
-import { SpanKind } from "@opentelemetry/api";
export const legacyIngestionQueueProcessor: Processor = async (
job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>,
) => {
- return instrumentAsync(
- {
- name: "legacyIngestion",
- spanKind: SpanKind.CONSUMER,
- rootSpan: true,
- traceContext: job.data?._tracecontext,
- },
- async () => {
- try {
- const startTime = Date.now();
- logger.info("Processing legacy ingestion", {
- payload: job.data.payload.data.map(({ body, ...rest }) => {
- let modifiedBody = body;
- if (body && "input" in modifiedBody) {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { input, ...restPayload } = modifiedBody || {};
- modifiedBody = restPayload;
- }
- if (body && "output" in modifiedBody) {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { output, ...restPayload } = modifiedBody || {};
- modifiedBody = restPayload;
- }
- return {
- ...rest,
- body: modifiedBody,
- };
- }),
- });
+ try {
+ const startTime = Date.now();
+ logger.info("Processing legacy ingestion", {
+ payload: job.data.payload.data.map(({ body, ...rest }) => {
+ let modifiedBody = body;
+ if (body && "input" in modifiedBody) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { input, ...restPayload } = modifiedBody || {};
+ modifiedBody = restPayload;
+ }
+ if (body && "output" in modifiedBody) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { output, ...restPayload } = modifiedBody || {};
+ modifiedBody = restPayload;
+ }
+ return {
+ ...rest,
+ body: modifiedBody,
+ };
+ }),
+ });
- const waitTime = Date.now() - job.timestamp;
- recordIncrement("langfuse.queue.legacy_ingestion.request");
- recordHistogram("langfuse.queue.legacy_ingestion.wait_time", waitTime, {
- unit: "milliseconds",
- });
+ const waitTime = Date.now() - job.timestamp;
+ recordIncrement("langfuse.queue.legacy_ingestion.request");
+ recordHistogram("langfuse.queue.legacy_ingestion.wait_time", waitTime, {
+ unit: "milliseconds",
+ });
- const result = await handleBatch(
- job.data.payload.data,
- job.data.payload.authCheck,
- tokenCount,
- );
+ const result = await handleBatch(
+ job.data.payload.data,
+ job.data.payload.authCheck,
+ tokenCount,
+ );
- // send out REDIS requests to worker for all trace types
- await sendToWorkerIfEnvironmentConfigured(
- result.results,
- job.data.payload.authCheck.scope.projectId,
- );
+ // send out REDIS requests to worker for all trace types
+ await sendToWorkerIfEnvironmentConfigured(
+ result.results,
+ job.data.payload.authCheck.scope.projectId,
+ );
- // Log queue size
- await LegacyIngestionQueue.getInstance()
- ?.count()
- .then((count) => {
- logger.debug(`Legacy Ingestion flush queue length: ${count}`);
- recordGauge("langfuse.queue.legacy_ingestion.length", count, {
- unit: "records",
- });
- return count;
- })
- .catch();
- recordHistogram(
- "langfuse.queue.legacy_ingestion.processing_time",
- Date.now() - startTime,
- { unit: "milliseconds" },
- );
- } catch (e) {
- logger.error(
- `Failed job legacy ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
- e,
- );
- traceException(e);
- throw e;
- }
- },
- );
+ // Log queue size
+ await LegacyIngestionQueue.getInstance()
+ ?.count()
+ .then((count) => {
+ logger.debug(`Legacy Ingestion flush queue length: ${count}`);
+ recordGauge("langfuse.queue.legacy_ingestion.length", count, {
+ unit: "records",
+ });
+ return count;
+ })
+ .catch();
+ recordHistogram(
+ "langfuse.queue.legacy_ingestion.processing_time",
+ Date.now() - startTime,
+ { unit: "milliseconds" },
+ );
+ } catch (e) {
+ logger.error(
+ `Failed job legacy ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
+ e,
+ );
+ traceException(e);
+ throw e;
+ }
};