🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(worker): add secondary otel ingestion queue (#13490)
Steffen Schmitz63f81db83883
diff --git a/.env.dev-redis-cluster.example b/.env.dev-redis-cluster.exampleindex 5a5db14018..1872169bb7 100644--- a/.env.dev-redis-cluster.example+++ b/.env.dev-redis-cluster.example@@ -81,6 +81,7 @@ REDIS_CLUSTER_NODES="127.0.0.1:6370,127.0.0.1:6371,127.0.0.1:6372,127.0.0.1:6373LANGFUSE_INGESTION_QUEUE_SHARD_COUNT=8LANGFUSE_INGESTION_SECONDARY_QUEUE_SHARD_COUNT=8LANGFUSE_OTEL_INGESTION_QUEUE_SHARD_COUNT=4+LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_SHARD_COUNT=4LANGFUSE_EVAL_EXECUTION_QUEUE_SHARD_COUNT=4LANGFUSE_EVAL_EXECUTION_SECONDARY_QUEUE_SHARD_COUNT=4LANGFUSE_LLM_AS_JUDGE_EXECUTION_QUEUE_SHARD_COUNT=4diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 4acad41860..e4e33bfc90 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -109,6 +109,10 @@ const EnvSchema = z.object({.number().positive().default(1),+ LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_SHARD_COUNT: z.coerce+ .number()+ .positive()+ .default(1),LANGFUSE_OTEL_MAX_SPAN_BYTES: z.coerce.number().positive().default(9_500_000), // 9.5MB — just under ClickHouse's 10MB min_chunk_bytes_for_parallel_parsing defaultLANGFUSE_EVAL_EXECUTION_QUEUE_SHARD_COUNT: z.coerce.number()diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 43225002e3..75c004bdce 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -329,6 +329,7 @@ export enum QueueName {DatasetRunItemUpsert = "dataset-run-item-upsert-queue",BatchExport = "batch-export-queue",OtelIngestionQueue = "otel-ingestion-queue",+ OtelIngestionSecondaryQueue = "secondary-otel-ingestion-queue", // Separates high priority + high throughput projects from other projects.IngestionQueue = "ingestion-queue", // Process single events with S3-mergeIngestionSecondaryQueue = "secondary-ingestion-queue", // Separates high priority + high throughput projects from other projects.CloudUsageMeteringQueue = "cloud-usage-metering-queue",@@ -369,7 +370,6 @@ export enum QueueJobs {CloudFreeTierUsageThresholdJob = "cloud-free-tier-usage-threshold-job",OtelIngestionJob = "otel-ingestion-job",IngestionJob = "ingestion-job",- IngestionSecondaryJob = "secondary-ingestion-job",ExperimentCreateJob = "experiment-create-job",PostHogIntegrationJob = "posthog-integration-job",PostHogIntegrationProcessingJob = "posthog-integration-processing-job",@@ -463,6 +463,12 @@ export type TQueueJobTypes = {payload: OtelIngestionEventQueueType;name: QueueJobs.OtelIngestionJob;};+ [QueueName.OtelIngestionSecondaryQueue]: {+ timestamp: Date;+ id: string;+ payload: OtelIngestionEventQueueType;+ name: QueueJobs.OtelIngestionJob;+ };[QueueName.IngestionQueue]: {timestamp: Date;id: string;diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex 7b7a54e6b2..c114a3d46d 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -40,6 +40,7 @@ export function getQueue(| QueueName.LLMAsJudgeExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue>,): Queue | null {switch (queueName) {diff --git a/packages/shared/src/server/redis/otelIngestionQueue.ts b/packages/shared/src/server/redis/otelIngestionQueue.tsindex 4c6c84a05a..0751b14610 100644--- a/packages/shared/src/server/redis/otelIngestionQueue.ts+++ b/packages/shared/src/server/redis/otelIngestionQueue.ts@@ -96,3 +96,94 @@ export class OtelIngestionQueue {return queueInstance;}}++export class SecondaryOtelIngestionQueue {+ private static instances: Map<+ number,+ Queue<TQueueJobTypes[QueueName.OtelIngestionSecondaryQueue]> | null+ > = new Map();++ public static getShardNames() {+ return Array.from(+ { length: env.LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_SHARD_COUNT },+ (_, i) =>+ `${QueueName.OtelIngestionSecondaryQueue}${i > 0 ? `-${i}` : ""}`,+ );+ }++ static getShardIndexFromShardName(+ shardName: string | undefined,+ ): number | null {+ if (!shardName) return null;++ const shardIndex =+ shardName === QueueName.OtelIngestionSecondaryQueue+ ? 0+ : parseInt(+ shardName.replace(`${QueueName.OtelIngestionSecondaryQueue}-`, ""),+ 10,+ );++ if (isNaN(shardIndex)) return null;+ return shardIndex;+ }++ /**+ * Get the secondary otel ingestion queue instance for the given sharding key or shard name.+ * @param shardingKey - ShardingKey is being hashed and randomly allocated to a shard. Should be `projectId-fileKey`.+ * @param shardName - Name of the shard. Should be `secondary-otel-ingestion-queue-${shardIndex}` or plainly `secondary-otel-ingestion-queue` for the first shard.+ */+ public static getInstance({+ shardingKey,+ shardName,+ }: {+ shardingKey?: string;+ shardName?: string;+ } = {}): Queue<TQueueJobTypes[QueueName.OtelIngestionSecondaryQueue]> | null {+ const shardIndex =+ SecondaryOtelIngestionQueue.getShardIndexFromShardName(shardName) ??+ (env.REDIS_CLUSTER_ENABLED === "true" && shardingKey+ ? getShardIndex(+ shardingKey,+ env.LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_SHARD_COUNT,+ )+ : 0);++ if (SecondaryOtelIngestionQueue.instances.has(shardIndex)) {+ return SecondaryOtelIngestionQueue.instances.get(shardIndex) || null;+ }++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ const name = `${QueueName.OtelIngestionSecondaryQueue}${shardIndex > 0 ? `-${shardIndex}` : ""}`;+ const queueInstance = newRedis+ ? new Queue<TQueueJobTypes[QueueName.OtelIngestionSecondaryQueue]>(name, {+ connection: newRedis,+ prefix: getQueuePrefix(name),+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100_000,+ attempts: 5,+ backoff: {+ type: "exponential",+ delay: 5000,+ },+ },+ })+ : null;++ queueInstance?.on("error", (err) => {+ logger.error(+ `SecondaryOtelIngestionQueue shard ${shardIndex} error`,+ err,+ );+ });++ SecondaryOtelIngestionQueue.instances.set(shardIndex, queueInstance);++ return queueInstance;+ }+}diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 2f40d497e0..c27d151ebb 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -5,6 +5,7 @@ import {LLMAsJudgeExecutionQueue,SecondaryEvalExecutionQueue,SecondaryIngestionQueue,+ SecondaryOtelIngestionQueue,createBasicAuthHeader,getQueue,IngestionQueue,@@ -94,6 +95,7 @@ export const getQueues = () => {...SecondaryEvalExecutionQueue.getShardNames(),...LLMAsJudgeExecutionQueue.getShardNames(),...OtelIngestionQueue.getShardNames(),+ ...SecondaryOtelIngestionQueue.getShardNames(),...TraceUpsertQueue.getShardNames(),);@@ -126,20 +128,27 @@ export const getQueues = () => {}): queueName.startsWith(QueueName.TraceUpsert)? TraceUpsertQueue.getInstance({ shardName: queueName })- : queueName.startsWith(QueueName.OtelIngestionQueue)- ? OtelIngestionQueue.getInstance({ shardName: queueName })- : getQueue(- queueName as Exclude<- QueueName,- | QueueName.IngestionQueue- | QueueName.IngestionSecondaryQueue- | QueueName.EvaluationExecution- | QueueName.EvaluationExecutionSecondaryQueue- | QueueName.LLMAsJudgeExecution- | QueueName.TraceUpsert- | QueueName.OtelIngestionQueue- >,- ),+ : queueName.startsWith(QueueName.OtelIngestionSecondaryQueue)+ ? SecondaryOtelIngestionQueue.getInstance({+ shardName: queueName,+ })+ : queueName.startsWith(QueueName.OtelIngestionQueue)+ ? OtelIngestionQueue.getInstance({+ shardName: queueName,+ })+ : getQueue(+ queueName as Exclude<+ QueueName,+ | QueueName.IngestionQueue+ | QueueName.IngestionSecondaryQueue+ | QueueName.EvaluationExecution+ | QueueName.EvaluationExecutionSecondaryQueue+ | QueueName.LLMAsJudgeExecution+ | QueueName.TraceUpsert+ | QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue+ >,+ ),);};diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.tsindex 69397a1edc..ceda3c02cd 100644--- a/web/src/pages/api/admin/bullmq/index.ts+++ b/web/src/pages/api/admin/bullmq/index.ts@@ -12,6 +12,7 @@ import {TraceUpsertQueue,IngestionEvent,OtelIngestionQueue,+ SecondaryOtelIngestionQueue,} from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";@@ -76,6 +77,7 @@ export default async function handler(...LLMAsJudgeExecutionQueue.getShardNames(),...TraceUpsertQueue.getShardNames(),...OtelIngestionQueue.getShardNames(),+ ...SecondaryOtelIngestionQueue.getShardNames(),]),);const queueCounts = await Promise.all(@@ -104,6 +106,12 @@ export default async function handler(});} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });+ } else if (+ queueName.startsWith(QueueName.OtelIngestionSecondaryQueue)+ ) {+ queue = SecondaryOtelIngestionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {queue = OtelIngestionQueue.getInstance({ shardName: queueName });} else {@@ -117,6 +125,7 @@ export default async function handler(| QueueName.LLMAsJudgeExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue>,);}@@ -163,6 +172,12 @@ export default async function handler(});} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });+ } else if (+ queueName.startsWith(QueueName.OtelIngestionSecondaryQueue)+ ) {+ queue = SecondaryOtelIngestionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {queue = OtelIngestionQueue.getInstance({ shardName: queueName });} else {@@ -176,6 +191,7 @@ export default async function handler(| QueueName.LLMAsJudgeExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue>,);}@@ -232,6 +248,12 @@ export default async function handler(});} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });+ } else if (+ queueName.startsWith(QueueName.OtelIngestionSecondaryQueue)+ ) {+ queue = SecondaryOtelIngestionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {queue = OtelIngestionQueue.getInstance({ shardName: queueName });} else {@@ -245,6 +267,7 @@ export default async function handler(| QueueName.LLMAsJudgeExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue>,);}diff --git a/worker/src/app.ts b/worker/src/app.tsindex 10759dc622..2d6c5b71d2 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -35,6 +35,7 @@ import {IngestionQueue,SecondaryIngestionQueue,OtelIngestionQueue,+ SecondaryOtelIngestionQueue,TraceUpsertQueue,CloudFreeTierUsageThresholdQueue,CloudUsageMeteringQueue,@@ -75,7 +76,7 @@ import { DlqRetryService } from "./services/dlq/dlqRetryService";import { entityChangeQueueProcessor } from "./queues/entityChangeQueue";import { webhookProcessor } from "./queues/webhooks";import { datasetDeleteProcessor } from "./queues/datasetDelete";-import { otelIngestionQueueProcessor } from "./queues/otelIngestionQueue";+import { otelIngestionQueueProcessorBuilder } from "./queues/otelIngestionQueue";import { eventPropagationProcessor } from "./queues/eventPropagationQueue";import { notificationQueueProcessor } from "./queues/notificationQueue";import {@@ -318,7 +319,7 @@ if (env.QUEUE_CONSUMER_OTEL_INGESTION_QUEUE_IS_ENABLED === "true") {shardNames.forEach((shardName) => {WorkerManager.register(shardName as QueueName,- otelIngestionQueueProcessor,+ otelIngestionQueueProcessorBuilder(true), // this might redirect to secondary queue{concurrency: env.LANGFUSE_OTEL_INGESTION_QUEUE_PROCESSING_CONCURRENCY,},@@ -326,6 +327,20 @@ if (env.QUEUE_CONSUMER_OTEL_INGESTION_QUEUE_IS_ENABLED === "true") {});}+if (env.QUEUE_CONSUMER_OTEL_INGESTION_SECONDARY_QUEUE_IS_ENABLED === "true") {+ const shardNames = SecondaryOtelIngestionQueue.getShardNames();+ shardNames.forEach((shardName) => {+ WorkerManager.register(+ shardName as QueueName,+ otelIngestionQueueProcessorBuilder(false),+ {+ concurrency:+ env.LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_PROCESSING_CONCURRENCY,+ },+ );+ });+}+if (env.QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED === "true") {// Register workers for all ingestion queue shardsconst shardNames = IngestionQueue.getShardNames();diff --git a/worker/src/env.ts b/worker/src/env.tsindex dd5dbf9956..3cdab3b60b 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -71,6 +71,13 @@ const EnvSchema = z.object({.number().positive().default(5),+ LANGFUSE_OTEL_INGESTION_SECONDARY_QUEUE_PROCESSING_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(1),+ LANGFUSE_SECONDARY_OTEL_INGESTION_QUEUE_ENABLED_PROJECT_IDS: z+ .string()+ .optional(),LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number().positive()@@ -235,6 +242,9 @@ const EnvSchema = z.object({QUEUE_CONSUMER_OTEL_INGESTION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),+ QUEUE_CONSUMER_OTEL_INGESTION_SECONDARY_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),QUEUE_CONSUMER_INGESTION_SECONDARY_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 819f923f0f..01cdc12d49 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -14,6 +14,7 @@ import {recordHistogram,recordIncrement,redis,+ SecondaryOtelIngestionQueue,TQueueJobTypes,traceException,compareVersions,@@ -189,326 +190,357 @@ export function checkSdkVersionRequirements(}}-export const otelIngestionQueueProcessor: Processor = async (- job: Job<TQueueJobTypes[QueueName.OtelIngestionQueue]>,-): Promise<void> => {- try {- const projectId = job.data.payload.authCheck.scope.projectId;- const publicKey = job.data.payload.data.publicKey;- const fileKey = job.data.payload.data.fileKey;- const auth = job.data.payload.authCheck;-- const span = getCurrentSpan();- if (span) {- span.setAttribute("messaging.bullmq.job.input.id", job.data.id);- span.setAttribute(- "messaging.bullmq.job.input.projectId",- job.data.payload.authCheck.scope.projectId,- );- span.setAttribute(- "messaging.bullmq.job.input.fileKey",- job.data.payload.data.fileKey,- );- }- logger.debug(`Processing ${fileKey} for project ${projectId}`);-- // TODO: Do we need to add these files into the blob_storage_file_log?- // We could recommend lifecycle rules due to the immutability properties.- // Otherwise, we'd probably have to upsert one row per generated event further below.- // Easy change, but needs alignment.-- // Download file from blob storage- const resourceSpans = await getS3EventStorageClient(- env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,- ).download(fileKey);-- recordHistogram(- "langfuse.ingestion.s3_file_size_bytes",- resourceSpans.length, // At this point it's still a string.- {- skippedS3List: "true",- otel: "true",- },- );+export const otelIngestionQueueProcessorBuilder = (+ enableRedirectToSecondaryQueue: boolean,+): Processor => {+ const projectIdsToRedirectToSecondaryQueue =+ env.LANGFUSE_SECONDARY_OTEL_INGESTION_QUEUE_ENABLED_PROJECT_IDS?.split(+ ",",+ ) ?? [];++ return async (+ job: Job<TQueueJobTypes[QueueName.OtelIngestionQueue]>,+ ): Promise<void> => {+ try {+ const projectId = job.data.payload.authCheck.scope.projectId;+ const publicKey = job.data.payload.data.publicKey;+ const fileKey = job.data.payload.data.fileKey;+ const auth = job.data.payload.authCheck;++ const span = getCurrentSpan();+ if (span) {+ span.setAttribute("messaging.bullmq.job.input.id", job.data.id);+ span.setAttribute(+ "messaging.bullmq.job.input.projectId",+ job.data.payload.authCheck.scope.projectId,+ );+ span.setAttribute(+ "messaging.bullmq.job.input.fileKey",+ job.data.payload.data.fileKey,+ );+ }+ logger.debug(`Processing ${fileKey} for project ${projectId}`);++ // Check if project should be redirected to secondary queue+ if (+ enableRedirectToSecondaryQueue &&+ projectIdsToRedirectToSecondaryQueue.includes(projectId)+ ) {+ logger.debug(+ `Redirecting otel ingestion event to secondary queue for project ${projectId}`,+ );+ const shardingKey = `${projectId}-${fileKey}`;+ const secondaryQueue = SecondaryOtelIngestionQueue.getInstance({+ shardingKey,+ });+ if (secondaryQueue) {+ await secondaryQueue.add(+ QueueName.OtelIngestionSecondaryQueue,+ job.data,+ );+ // Forwarded to secondary queue; stop processing here.+ return;+ }+ }- // Parse spans from S3 download- let parsedSpans = JSON.parse(resourceSpans);+ // TODO: Do we need to add these files into the blob_storage_file_log?+ // We could recommend lifecycle rules due to the immutability properties.+ // Otherwise, we'd probably have to upsert one row per generated event further below.+ // Easy change, but needs alignment.++ // Download file from blob storage+ const resourceSpans = await getS3EventStorageClient(+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ ).download(fileKey);++ recordHistogram(+ "langfuse.ingestion.s3_file_size_bytes",+ resourceSpans.length, // At this point it's still a string.+ {+ skippedS3List: "true",+ otel: "true",+ },+ );- // Apply ingestion masking if enabled (EE feature)- if (isIngestionMaskingEnabled()) {- const maskingResult = await applyIngestionMasking({- data: parsedSpans,- projectId,- orgId: job.data.payload.authCheck.scope.orgId,- propagatedHeaders: job.data.payload.propagatedHeaders,- });+ // Parse spans from S3 download+ let parsedSpans = JSON.parse(resourceSpans);- if (!maskingResult.success) {- // Fail-closed: drop event. Emit the S3 location so operators can- // scan logs to identify which raw payloads need to be replayed via- // worker/src/scripts/replayIngestionEventsV2 once the upstream- // masking callback is healthy again.- logger.warn(`Dropping OTEL event due to masking failure`, {+ // Apply ingestion masking if enabled (EE feature)+ if (isIngestionMaskingEnabled()) {+ const maskingResult = await applyIngestionMasking({+ data: parsedSpans,projectId,orgId: job.data.payload.authCheck.scope.orgId,- fileKey,- error: maskingResult.error,propagatedHeaders: job.data.payload.propagatedHeaders,});- return;- }- parsedSpans = maskingResult.data;- }- // Generate events via OtelIngestionProcessor- const processor = new OtelIngestionProcessor({- projectId,- publicKey,- });- const events: IngestionEventType[] =- await processor.processToIngestionEvents(parsedSpans);- // Here, we split the events into observations and non-observations.- // Observations go into the IngestionService directly whereas the non-observations make another run through the processEventBatch method.- const traces = events.filter(- (e) => getClickhouseEntityType(e.type) !== "observation",- );- // We need to parse each incoming observation through our ingestion schema to make use of its included transformations.- const ingestionSchema = createIngestionEventSchema();- const observations = events- .filter((e) => getClickhouseEntityType(e.type) === "observation")- .map((o) => ingestionSchema.safeParse(o))- .flatMap((o) => {- if (!o.success) {- logger.warn(- `Failed to parse otel observation for project ${projectId} in ${fileKey}: ${o.error}`,- {- error: o.error,- fileKey,- },- );- return [];+ if (!maskingResult.success) {+ // Fail-closed: drop event. Emit the S3 location so operators can+ // scan logs to identify which raw payloads need to be replayed via+ // worker/src/scripts/replayIngestionEventsV2 once the upstream+ // masking callback is healthy again.+ logger.warn(`Dropping OTEL event due to masking failure`, {+ projectId,+ orgId: job.data.payload.authCheck.scope.orgId,+ fileKey,+ error: maskingResult.error,+ propagatedHeaders: job.data.payload.propagatedHeaders,+ });+ return;}- return [o.data];- });+ parsedSpans = maskingResult.data;+ }- // In the next row, we only consider observations. The traces will be recorded in processEventBatch.- recordIncrement("langfuse.ingestion.event", observations.length, {- source: "otel",- });- // Record more stats specific to the Otel processing- recordDistribution("langfuse.ingestion.otel.trace_count", traces.length);- recordDistribution(- "langfuse.ingestion.otel.observation_count",- observations.length,- );- span?.setAttribute("langfuse.ingestion.otel.trace_count", traces.length);- span?.setAttribute(- "langfuse.ingestion.otel.observation_count",- observations.length,- );+ // Generate events via OtelIngestionProcessor+ const processor = new OtelIngestionProcessor({+ projectId,+ publicKey,+ });+ const events: IngestionEventType[] =+ await processor.processToIngestionEvents(parsedSpans);+ // Here, we split the events into observations and non-observations.+ // Observations go into the IngestionService directly whereas the non-observations make another run through the processEventBatch method.+ const traces = events.filter(+ (e) => getClickhouseEntityType(e.type) !== "observation",+ );+ // We need to parse each incoming observation through our ingestion schema to make use of its included transformations.+ const ingestionSchema = createIngestionEventSchema();+ const observations = events+ .filter((e) => getClickhouseEntityType(e.type) === "observation")+ .map((o) => ingestionSchema.safeParse(o))+ .flatMap((o) => {+ if (!o.success) {+ logger.warn(+ `Failed to parse otel observation for project ${projectId} in ${fileKey}: ${o.error}`,+ {+ error: o.error,+ fileKey,+ },+ );+ return [];+ }+ return [o.data];+ });- // Ensure required infra config is present- if (!redis) throw new Error("Redis not available");- if (!prisma) throw new Error("Prisma not available");+ // In the next row, we only consider observations. The traces will be recorded in processEventBatch.+ recordIncrement("langfuse.ingestion.event", observations.length, {+ source: "otel",+ });+ // Record more stats specific to the Otel processing+ recordDistribution("langfuse.ingestion.otel.trace_count", traces.length);+ recordDistribution(+ "langfuse.ingestion.otel.observation_count",+ observations.length,+ );+ span?.setAttribute("langfuse.ingestion.otel.trace_count", traces.length);+ span?.setAttribute(+ "langfuse.ingestion.otel.observation_count",+ observations.length,+ );- const ingestionService = new IngestionService(- redis,- prisma,- ClickhouseWriter.getInstance(),- clickhouseClient(),- );+ // Ensure required infra config is present+ if (!redis) throw new Error("Redis not available");+ if (!prisma) throw new Error("Prisma not available");- // Decide whether observations should be processed via new flow (directly to events table)- // or via the dual write (staging table and batch job to events).- //- // Priority 1: HTTP headers from the SDK request (batch-level decision).- // - x-langfuse-sdk-name/version: Python >= 4.0.0 or JS >= 5.0.0- // - x-langfuse-ingestion-version: "4" (custom OTel exporter opt-in)- // When headers qualify, ALL spans in the batch (including third-party scoped) use direct write.- //- // Priority 2 (fallback): Per-span OTEL scope inspection (legacy).- // - scope.name contains "langfuse", sdk-experiment environment, Python >= 3.9.0 or JS >= 4.4.0- const headerBasedDirectWrite = checkHeaderBasedDirectWrite({- sdkName: job.data.payload.sdkName,- sdkVersion: job.data.payload.sdkVersion,- ingestionVersion: job.data.payload.ingestionVersion,- });-- let useDirectEventWrite = headerBasedDirectWrite;-- if (!useDirectEventWrite) {- const hasExperimentEnvironment = observations.some((o) => {- const body = o.body as { environment?: string };- return body.environment === "sdk-experiment";- });- const sdkInfo =- parsedSpans.length > 0- ? getSdkInfoFromResourceSpans(parsedSpans[0])- : {- scopeName: null,- scopeVersion: null,- telemetrySdkLanguage: null,- };- useDirectEventWrite = checkSdkVersionRequirements(- sdkInfo,- hasExperimentEnvironment,+ const ingestionService = new IngestionService(+ redis,+ prisma,+ ClickhouseWriter.getInstance(),+ clickhouseClient(),);- }- const writePath = useDirectEventWrite- ? headerBasedDirectWrite- ? "direct_header"- : "direct_scope"- : "dual";- span?.setAttribute("langfuse.ingestion.otel.write_path", writePath);- recordIncrement("langfuse.ingestion.otel.write_path", 1, {- path: writePath,- });-- const shouldForwardToEventsTable =- !useDirectEventWrite &&- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true";-- // Running everything concurrently might be detrimental to the event loop, but has probably- // the highest possible throughput. Therefore, we start with a Promise.all.- // If necessary, we may use a for each instead.-- // Process observations via mergeAndWrite- const observationWritePromise = Promise.all(- observations.map((observation) =>- ingestionService.mergeAndWrite(- getClickhouseEntityType(observation.type),- auth.scope.projectId,- observation.body.id || "", // id is always defined for observations- new Date(), // Use the current timestamp as event time- [observation],- shouldForwardToEventsTable,- ),- ),- );+ // Decide whether observations should be processed via new flow (directly to events table)+ // or via the dual write (staging table and batch job to events).+ //+ // Priority 1: HTTP headers from the SDK request (batch-level decision).+ // - x-langfuse-sdk-name/version: Python >= 4.0.0 or JS >= 5.0.0+ // - x-langfuse-ingestion-version: "4" (custom OTel exporter opt-in)+ // When headers qualify, ALL spans in the batch (including third-party scoped) use direct write.+ //+ // Priority 2 (fallback): Per-span OTEL scope inspection (legacy).+ // - scope.name contains "langfuse", sdk-experiment environment, Python >= 3.9.0 or JS >= 4.4.0+ const headerBasedDirectWrite = checkHeaderBasedDirectWrite({+ sdkName: job.data.payload.sdkName,+ sdkVersion: job.data.payload.sdkVersion,+ ingestionVersion: job.data.payload.ingestionVersion,+ });- // Process traces and observations concurrently- await Promise.all([- observationWritePromise,- processEventBatch(traces, auth, {- delay: 0,- source: "otel",- forwardToEventsTable: shouldForwardToEventsTable,- }),- ]);-- // Process events for observation evals and direct event writes- // This phase handles two independent concerns:- // 1. Scheduling observation-level evals (if eval configs exist)- // 2. Writing directly to events table (if SDK version requirements are met)- //- // Both require enriched event records with trace-level attributes- // (userId, sessionId, tags, release) that processToEvent provides.- const eventInputs = processor.processToEvent(parsedSpans);-- if (eventInputs.length === 0) {- return;- }+ let useDirectEventWrite = headerBasedDirectWrite;- // Determine what processing is needed- const shouldWriteToEventsTable =- env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&- useDirectEventWrite;-- const evalConfigs = await fetchObservationEvalConfigs(projectId).catch(- (error) => {- traceException(error);- logger.warn(- `Failed to fetch observation eval configs for project ${projectId}`,- error,+ if (!useDirectEventWrite) {+ const hasExperimentEnvironment = observations.some((o) => {+ const body = o.body as { environment?: string };+ return body.environment === "sdk-experiment";+ });+ const sdkInfo =+ parsedSpans.length > 0+ ? getSdkInfoFromResourceSpans(parsedSpans[0])+ : {+ scopeName: null,+ scopeVersion: null,+ telemetrySdkLanguage: null,+ };+ useDirectEventWrite = checkSdkVersionRequirements(+ sdkInfo,+ hasExperimentEnvironment,);+ }- return [];- },- );- const hasEvalConfigs = evalConfigs.length > 0;+ const writePath = useDirectEventWrite+ ? headerBasedDirectWrite+ ? "direct_header"+ : "direct_scope"+ : "dual";+ span?.setAttribute("langfuse.ingestion.otel.write_path", writePath);+ recordIncrement("langfuse.ingestion.otel.write_path", 1, {+ path: writePath,+ });- // Early exit if no processing needed- if (!hasEvalConfigs && !shouldWriteToEventsTable) {- return;- }+ const shouldForwardToEventsTable =+ !useDirectEventWrite &&+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true";++ // Running everything concurrently might be detrimental to the event loop, but has probably+ // the highest possible throughput. Therefore, we start with a Promise.all.+ // If necessary, we may use a for each instead.++ // Process observations via mergeAndWrite+ const observationWritePromise = Promise.all(+ observations.map((observation) =>+ ingestionService.mergeAndWrite(+ getClickhouseEntityType(observation.type),+ auth.scope.projectId,+ observation.body.id || "", // id is always defined for observations+ new Date(), // Use the current timestamp as event time+ [observation],+ shouldForwardToEventsTable,+ ),+ ),+ );- // Create scheduler deps only if we have eval configs- const evalSchedulerDeps = hasEvalConfigs- ? createObservationEvalSchedulerDeps()- : null;-- await Promise.all(- // Process each event independently- eventInputs.map(async (eventInput) => {- // Step 1: Create enriched event record (required for both evals and writes)- let eventRecord;- try {- eventRecord = await ingestionService.createEventRecord(- eventInput,- fileKey,- );- } catch (error) {+ // Process traces and observations concurrently+ await Promise.all([+ observationWritePromise,+ processEventBatch(traces, auth, {+ delay: 0,+ source: "otel",+ forwardToEventsTable: shouldForwardToEventsTable,+ }),+ ]);++ // Process events for observation evals and direct event writes+ // This phase handles two independent concerns:+ // 1. Scheduling observation-level evals (if eval configs exist)+ // 2. Writing directly to events table (if SDK version requirements are met)+ //+ // Both require enriched event records with trace-level attributes+ // (userId, sessionId, tags, release) that processToEvent provides.+ const eventInputs = processor.processToEvent(parsedSpans);++ if (eventInputs.length === 0) {+ return;+ }++ // Determine what processing is needed+ const shouldWriteToEventsTable =+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" &&+ useDirectEventWrite;++ const evalConfigs = await fetchObservationEvalConfigs(projectId).catch(+ (error) => {traceException(error);- logger.error(- `Failed to create event record for project ${eventInput.projectId} and observation ${eventInput.spanId}`,- { error, fileKey },+ logger.warn(+ `Failed to fetch observation eval configs for project ${projectId}`,+ error,);- return;- }+ return [];+ },+ );+ const hasEvalConfigs = evalConfigs.length > 0;- // Step 2: Schedule observation evals (independent of event writes)- if (hasEvalConfigs && evalSchedulerDeps) {- try {- const observation =- convertEventRecordToObservationForEval(eventRecord);-- await scheduleObservationEvals({- observation,- configs: evalConfigs,- schedulerDeps: evalSchedulerDeps,- });- } catch (error) {- traceException(error);+ // Early exit if no processing needed+ if (!hasEvalConfigs && !shouldWriteToEventsTable) {+ return;+ }- logger.error(- `Failed to schedule observation evals for project ${eventInput.projectId} and observation ${eventInput.spanId}`,- { error, fileKey },- );- }- }+ // Create scheduler deps only if we have eval configs+ const evalSchedulerDeps = hasEvalConfigs+ ? createObservationEvalSchedulerDeps()+ : null;- // Step 3: Write to events table (independent of eval scheduling)- if (shouldWriteToEventsTable) {+ await Promise.all(+ // Process each event independently+ eventInputs.map(async (eventInput) => {+ // Step 1: Create enriched event record (required for both evals and writes)+ let eventRecord;try {- ingestionService.writeEventRecord(eventRecord);+ eventRecord = await ingestionService.createEventRecord(+ eventInput,+ fileKey,+ );} catch (error) {traceException(error);logger.error(- `Failed to write event record for ${eventInput.spanId}`,+ `Failed to create event record for project ${eventInput.projectId} and observation ${eventInput.spanId}`,{ error, fileKey },);++ return;}- }- }),- );- } catch (e) {- const fileKey = job.data.payload.data.fileKey;- if (e instanceof ForbiddenError) {++ // Step 2: Schedule observation evals (independent of event writes)+ if (hasEvalConfigs && evalSchedulerDeps) {+ try {+ const observation =+ convertEventRecordToObservationForEval(eventRecord);++ await scheduleObservationEvals({+ observation,+ configs: evalConfigs,+ schedulerDeps: evalSchedulerDeps,+ });+ } catch (error) {+ traceException(error);++ logger.error(+ `Failed to schedule observation evals for project ${eventInput.projectId} and observation ${eventInput.spanId}`,+ { error, fileKey },+ );+ }+ }++ // Step 3: Write to events table (independent of eval scheduling)+ if (shouldWriteToEventsTable) {+ try {+ ingestionService.writeEventRecord(eventRecord);+ } catch (error) {+ traceException(error);+ logger.error(+ `Failed to write event record for ${eventInput.spanId}`,+ { error, fileKey },+ );+ }+ }+ }),+ );+ } catch (e) {+ const fileKey = job.data.payload.data.fileKey;+ if (e instanceof ForbiddenError) {+ traceException(e);+ logger.warn(`Failed to parse otel observation: ${e.message}`, {+ error: e,+ fileKey,+ });+ return;+ }++ logger.error(+ `Failed job otel ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,+ { error: e, fileKey },+ );traceException(e);- logger.warn(`Failed to parse otel observation: ${e.message}`, {- error: e,- fileKey,- });- return;+ throw e;}-- logger.error(- `Failed job otel ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,- { error: e, fileKey },- );- traceException(e);- throw e;- }+ };};diff --git a/worker/src/queues/shardedQueueRegistry.ts b/worker/src/queues/shardedQueueRegistry.tsindex 8ab55218db..3405e1c464 100644--- a/worker/src/queues/shardedQueueRegistry.ts+++ b/worker/src/queues/shardedQueueRegistry.ts@@ -6,6 +6,7 @@ import {IngestionQueue,SecondaryIngestionQueue,OtelIngestionQueue,+ SecondaryOtelIngestionQueue,TraceUpsertQueue,EvalExecutionQueue,SecondaryEvalExecutionQueue,@@ -36,6 +37,12 @@ export const SHARDED_QUEUES: ShardedQueueDef[] = [getInstance: (shard) =>OtelIngestionQueue.getInstance({ shardName: shard }),},+ {+ baseQueueName: QueueName.OtelIngestionSecondaryQueue,+ getShardNames: () => SecondaryOtelIngestionQueue.getShardNames(),+ getInstance: (shard) =>+ SecondaryOtelIngestionQueue.getInstance({ shardName: shard }),+ },{baseQueueName: QueueName.TraceUpsert,getShardNames: () => TraceUpsertQueue.getShardNames(),@@ -87,6 +94,7 @@ export function resolveQueueInstance(queueName: string): Queue | null {| QueueName.LLMAsJudgeExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue>,);}