Skip to content

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

feat: measure OTEL input preparation by media path (#18757)

Valery Meleshkinbd891bac5e4b
diff --git a/worker/src/features/otel-ingestion/processOtelEvents.ts b/worker/src/features/otel-ingestion/processOtelEvents.ts
index af4e6acaea..46a55e0495 100644
--- a/worker/src/features/otel-ingestion/processOtelEvents.ts
+++ b/worker/src/features/otel-ingestion/processOtelEvents.ts
@@ -17,6 +17,7 @@ import { trackTraceBatchActivity } from "../traceBatching/traceBatching";
import {
createDirectOtelMediaTargets,
processOtelEventMedia,
+ type OtelMediaPresence,
} from "../otel-media/processOtelMedia";
import type { IngestionService } from "../../services/IngestionService";
@@ -51,7 +52,7 @@ export async function processOtelEvents({
earlyBatch,
mediaPath,
inputByteLength,
-}: ProcessOtelEventsParams): Promise<void> {
+}: ProcessOtelEventsParams): Promise<OtelMediaPresence | undefined> {
// Process events for observation evals and direct event writes
// This phase handles two independent concerns:
// 1. Scheduling observation-level evals (if eval configs exist)
@@ -90,11 +91,12 @@ export async function processOtelEvents({
});
}
+ let mediaPresence: OtelMediaPresence | undefined;
if (
env.LANGFUSE_OTEL_MEDIA_UPLOAD_ENABLED === "true" &&
shouldWriteToEventsTable
) {
- await processOtelEventMedia({
+ mediaPresence = await processOtelEventMedia({
targets: createDirectOtelMediaTargets(eventInputs),
writePath: "direct",
earlyBatch,
@@ -194,4 +196,5 @@ export async function processOtelEvents({
// The writer has accepted these records; its flush completes separately.
await trackTraceBatchActivity(projectId, traceBatchEvents);
}
+ return mediaPresence;
}
diff --git a/worker/src/features/otel-media/processOtelMedia.test.ts b/worker/src/features/otel-media/processOtelMedia.test.ts
index b6e14fc7b3..509711085a 100644
--- a/worker/src/features/otel-media/processOtelMedia.test.ts
+++ b/worker/src/features/otel-media/processOtelMedia.test.ts
@@ -218,7 +218,7 @@ describe("processOtelEventMedia", () => {
};
const processMedia = vi.fn().mockResolvedValue(processResult);
- await processOtelEventMedia({
+ const mediaPresence = await processOtelEventMedia({
targets: createDirectOtelMediaTargets([
eventInput,
{ traceId: "trace-id", spanId: "without-media-fields" },
@@ -231,6 +231,7 @@ describe("processOtelEventMedia", () => {
processMedia,
});
+ expect(mediaPresence).toBe("present");
expect(processMedia).toHaveBeenCalledWith(
expect.objectContaining({
targets: [
@@ -298,7 +299,7 @@ describe("processOtelEventMedia", () => {
it("does not create a processing span when there are no media fields", async () => {
const processMedia = vi.fn();
- await processOtelEventMedia({
+ const mediaPresence = await processOtelEventMedia({
targets: createDirectOtelMediaTargets([
{ traceId: "trace-id", spanId: "observation-id" },
]),
@@ -308,6 +309,7 @@ describe("processOtelEventMedia", () => {
processMedia,
});
+ expect(mediaPresence).toBe("absent");
expect(processMedia).not.toHaveBeenCalled();
expect(mocks.instrumentAsync).not.toHaveBeenCalled();
});
@@ -329,7 +331,7 @@ describe("processOtelEventMedia", () => {
fileKey: "file-key",
processMedia,
}),
- ).resolves.toBeUndefined();
+ ).resolves.toBe("unknown");
expect(mocks.recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.processing_duration_ms",
diff --git a/worker/src/features/otel-media/processOtelMedia.ts b/worker/src/features/otel-media/processOtelMedia.ts
index 95de0c69c2..7086fb5762 100644
--- a/worker/src/features/otel-media/processOtelMedia.ts
+++ b/worker/src/features/otel-media/processOtelMedia.ts
@@ -20,6 +20,8 @@ import { MediaAssociationOrigin } from "@langfuse/shared";
const MEDIA_FIELDS = ["input", "output", "metadata"] as const;
+export type OtelMediaPresence = "present" | "absent" | "unknown";
+
/**
* Worker integration point for media in normalized OTEL payloads selected for
* persistence by the ingestion queue.
@@ -53,7 +55,7 @@ export async function processOtelEventMedia(params: {
mediaPrefix: string;
inputByteLength?: number;
processMedia?: typeof processOtelMedia;
-}): Promise<void> {
+}): Promise<OtelMediaPresence | undefined> {
const {
targets,
writePath,
@@ -74,14 +76,14 @@ export async function processOtelEventMedia(params: {
return;
}
- if (targets.length === 0) return;
+ if (targets.length === 0) return "absent";
+ let mediaPresence: OtelMediaPresence = "unknown";
try {
await instrumentAsync(
{ name: "langfuse.ingestion.otel.media.process" },
async (span) => {
const startedAt = Date.now();
- let mediaPresence: "present" | "absent" | "unknown" = "unknown";
span.setAttributes({
"langfuse.ingestion.otel.media_path": mediaPath,
});
@@ -171,6 +173,7 @@ export async function processOtelEventMedia(params: {
}
},
);
+ return mediaPresence;
} catch (error) {
if (params.earlyBatch) {
// Unexpected detector failures must not leave pending references in persisted payloads.
@@ -186,6 +189,7 @@ export async function processOtelEventMedia(params: {
"OTEL media processing failed; continuing ingestion with original span values",
{ projectId, fileKey, error },
);
+ return "unknown";
}
}
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
index c82ebb9959..952818b10c 100644
--- a/worker/src/queues/otelIngestionQueue.ts
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -44,6 +44,7 @@ import { ForbiddenError } from "@langfuse/shared";
import {
createLegacyOtelMediaTargets,
processOtelEventMedia,
+ type OtelMediaPresence,
} from "../features/otel-media/processOtelMedia";
import { restoreInlineMedia } from "../features/otel-media/resolveExtractedMedia";
import { processOtelEvents } from "../features/otel-ingestion/processOtelEvents";
@@ -443,6 +444,11 @@ export const otelIngestionQueueProcessorBuilder = (
job: Job<TQueueJobTypes[QueueName.OtelIngestionQueue]>,
): Promise<void> => {
let earlyBatch: EarlyOtelBatch | undefined;
+ let mediaPath: "early" | "reference" | undefined;
+ let mediaPresence: OtelMediaPresence | undefined;
+ let inputByteLength: number | undefined;
+ let inputPreparationDurationMs: number | undefined;
+ const span = getCurrentSpan();
try {
const projectId = job.data.payload.authCheck.scope.projectId;
const publicKey = job.data.payload.data.publicKey ?? "";
@@ -457,7 +463,6 @@ export const otelIngestionQueueProcessorBuilder = (
job.data.payload.sdkVersion || UNKNOWN_INGESTION_SDK_VALUE,
};
- const span = getCurrentSpan();
if (span) {
span.setAttribute("messaging.bullmq.job.input.id", job.data.id);
span.setAttribute(
@@ -504,7 +509,7 @@ export const otelIngestionQueueProcessorBuilder = (
env.LANGFUSE_OTEL_EARLY_MEDIA_EXTRACTION_PROJECT_IDS.includes(
projectId,
));
- const mediaPath = earlyMediaEnabled ? "early" : "reference";
+ mediaPath = earlyMediaEnabled ? "early" : "reference";
span?.setAttribute("langfuse.ingestion.otel.media_path", mediaPath);
// Count selection once per queue attempt, including jobs that later fail.
recordIncrement("langfuse.ingestion.otel.media_path", 1, {
@@ -515,9 +520,9 @@ export const otelIngestionQueueProcessorBuilder = (
env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
);
let parsedSpans: ResourceSpan[];
- let inputByteLength: number;
if (earlyMediaEnabled) {
const bytes = await eventStorage.downloadBytes(fileKey);
+ const preparationStartedAt = performance.now();
inputByteLength = bytes.byteLength;
recordHistogram(
"langfuse.ingestion.s3_file_size_bytes",
@@ -545,9 +550,11 @@ export const otelIngestionQueueProcessorBuilder = (
}
({ batch: earlyBatch, resourceSpans: parsedSpans } =
await parsePreparedOtelBatch(prepared, bytes));
+ inputPreparationDurationMs = performance.now() - preparationStartedAt;
} else {
// Download file from blob storage
const resourceSpans = await eventStorage.download(fileKey);
+ const preparationStartedAt = performance.now();
inputByteLength = Buffer.byteLength(resourceSpans, "utf8");
recordHistogram(
@@ -587,6 +594,7 @@ export const otelIngestionQueueProcessorBuilder = (
}
parsedSpans = maskingResult.data;
}
+ inputPreparationDurationMs = performance.now() - preparationStartedAt;
}
// Generate events via OtelIngestionProcessor
@@ -789,7 +797,7 @@ export const otelIngestionQueueProcessorBuilder = (
// Process the exact normalized representation written by the legacy
// path. Targets retain body references, so replacements also reach
// events-table forwarding when that destination is enabled.
- await processOtelEventMedia({
+ const legacyMediaPresence = await processOtelEventMedia({
targets: createLegacyOtelMediaTargets(traces.concat(observations)),
writePath: "legacy",
earlyBatch,
@@ -800,6 +808,12 @@ export const otelIngestionQueueProcessorBuilder = (
mediaBucket: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
mediaPrefix: env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX,
});
+ if (legacyMediaPresence) {
+ mediaPresence = combineOtelMediaPresence(
+ mediaPresence,
+ legacyMediaPresence,
+ );
+ }
}
// Running everything concurrently might be detrimental to the event loop, but has probably
@@ -837,7 +851,7 @@ export const otelIngestionQueueProcessorBuilder = (
// Determine what processing is needed
const shouldWriteToEventsTable =
v4WritesToEventsTable(env) && useDirectEventWrite;
- await processOtelEvents({
+ const directMediaPresence = await processOtelEvents({
processor,
resourceSpans: parsedSpans,
ingestionService,
@@ -848,6 +862,12 @@ export const otelIngestionQueueProcessorBuilder = (
mediaPath,
inputByteLength,
});
+ if (directMediaPresence) {
+ mediaPresence = combineOtelMediaPresence(
+ mediaPresence,
+ directMediaPresence,
+ );
+ }
} catch (e) {
const fileKey = job.data.payload.data.fileKey;
if (e instanceof ForbiddenError) {
@@ -873,6 +893,88 @@ export const otelIngestionQueueProcessorBuilder = (
throw e;
} finally {
await earlyBatch?.dispose();
+ setOtelInputPreparationSpanAttributes(span, {
+ durationMs: inputPreparationDurationMs,
+ mediaPath,
+ mediaPresence,
+ });
+ recordOtelInputPreparationMetrics({
+ durationMs: inputPreparationDurationMs,
+ mediaPath,
+ mediaPresence,
+ inputByteLength,
+ });
}
};
};
+
+function combineOtelMediaPresence(
+ current: OtelMediaPresence | undefined,
+ next: OtelMediaPresence,
+): OtelMediaPresence {
+ if (current === "present" || next === "present") return "present";
+ if (current === "unknown" || next === "unknown") return "unknown";
+ return "absent";
+}
+
+function setOtelInputPreparationSpanAttributes(
+ span: ReturnType<typeof getCurrentSpan>,
+ params: {
+ durationMs?: number;
+ mediaPath?: "early" | "reference";
+ mediaPresence?: OtelMediaPresence;
+ },
+): void {
+ if (params.mediaPath) {
+ span?.setAttribute(
+ "langfuse.ingestion.otel.media_presence",
+ params.mediaPresence ?? "unknown",
+ );
+ if (params.mediaPresence && params.mediaPresence !== "unknown") {
+ span?.setAttribute(
+ "langfuse.ingestion.otel.media_detected",
+ params.mediaPresence === "present",
+ );
+ }
+ }
+ if (params.durationMs !== undefined) {
+ span?.setAttribute(
+ "langfuse.ingestion.otel.input_preparation_duration_ms",
+ params.durationMs,
+ );
+ }
+}
+
+function recordOtelInputPreparationMetrics(params: {
+ durationMs?: number;
+ mediaPath?: "early" | "reference";
+ mediaPresence?: OtelMediaPresence;
+ inputByteLength?: number;
+}): void {
+ if (params.durationMs === undefined || !params.mediaPath) return;
+
+ // The duration is captured after download and before event conversion.
+ // Media classification comes from the existing downstream detector.
+ const tags = {
+ media_path: params.mediaPath,
+ media_presence: params.mediaPresence ?? "unknown",
+ };
+ recordDistribution(
+ "langfuse.ingestion.otel.input_preparation_duration_ms",
+ params.durationMs,
+ tags,
+ );
+ recordIncrement("langfuse.ingestion.otel.input_preparation_sample", 1, tags);
+ recordIncrement(
+ "langfuse.ingestion.otel.input_preparation_duration_total_ms",
+ params.durationMs,
+ tags,
+ );
+ if (params.inputByteLength && params.inputByteLength > 0) {
+ recordIncrement(
+ "langfuse.ingestion.otel.input_preparation_bytes_total",
+ params.inputByteLength,
+ tags,
+ );
+ }
+}