Skip to content

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

fix(otel): process legacy media and classify data uris (#15353)

Hassieb Pakzad7c8621411f33
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.test.ts b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
index 9f4a85d454..fc179708ef 100644
--- a/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
@@ -16,6 +16,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(value, {
processCandidate,
onInvalidCandidate,
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
});
@@ -25,6 +26,28 @@ describe("transformMediaPayload", () => {
expect(onDetectionPath).not.toHaveBeenCalled();
});
+ it("ignores data prefixes embedded in a larger identifier", async () => {
+ const processCandidate = vi.fn();
+ const onInvalidCandidate = vi.fn();
+ const onIgnoredCandidate = vi.fn();
+ const value = `metadata:image/png;base64,${PNG_BASE64}`;
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate,
+ onInvalidCandidate,
+ onIgnoredCandidate,
+ onDetectionPath: vi.fn(),
+ });
+
+ expect(transformed.value).toBe(value);
+ expect(processCandidate).not.toHaveBeenCalled();
+ expect(onInvalidCandidate).not.toHaveBeenCalled();
+ expect(onIgnoredCandidate).toHaveBeenCalledWith(
+ "data_uri",
+ "implausible_data_uri_prefix",
+ );
+ });
+
it("scans adversarial repeated data prefixes in linear time", async () => {
const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
const onDetectionPath = vi.fn();
@@ -35,6 +58,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(value, {
processCandidate,
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
});
const elapsedMs = performance.now() - startedAt;
@@ -59,6 +83,7 @@ describe("transformMediaPayload", () => {
{
processCandidate,
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
},
);
@@ -74,6 +99,27 @@ describe("transformMediaPayload", () => {
);
});
+ it.each([".", ";", "?", "!"])(
+ "processes an embedded Data URI followed by %s",
+ async (punctuation) => {
+ const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+
+ const transformed = await transformMediaPayload(
+ `media: ${dataUri}${punctuation}`,
+ {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
+ onDetectionPath: vi.fn(),
+ },
+ );
+
+ expect(transformed.value).toBe(`media: ${MEDIA_REFERENCE}${punctuation}`);
+ expect(processCandidate).toHaveBeenCalledOnce();
+ },
+ );
+
it("processes Data URIs with media type parameters", async () => {
const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
const textBase64 = Buffer.from("hello").toString("base64");
@@ -82,6 +128,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(`file: ${dataUri}`, {
processCandidate,
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath: vi.fn(),
});
@@ -111,6 +158,7 @@ describe("transformMediaPayload", () => {
{
processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
},
);
@@ -137,6 +185,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(value, {
processCandidate,
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath: vi.fn(),
});
@@ -165,6 +214,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(value, {
processCandidate,
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
});
@@ -182,6 +232,7 @@ describe("transformMediaPayload", () => {
const transformed = await transformMediaPayload(value, {
processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath,
});
@@ -209,6 +260,7 @@ describe("transformMediaPayload", () => {
await transformMediaPayload(value, {
processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath: vi.fn(),
});
@@ -234,6 +286,7 @@ describe("transformMediaPayload", () => {
await transformMediaPayload(value, {
processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
onInvalidCandidate: vi.fn(),
+ onIgnoredCandidate: vi.fn(),
onDetectionPath: vi.fn(),
});
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.ts b/packages/shared/src/server/media/MediaPayloadProcessor.ts
index 9126ba9230..5875515b27 100644
--- a/packages/shared/src/server/media/MediaPayloadProcessor.ts
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.ts
@@ -16,6 +16,18 @@ export type MediaPayloadKind =
| "ai_sdk_v6"
| "ai_sdk_v7";
+export type MediaInvalidReason =
+ | "empty_payload"
+ | "invalid_base64"
+ | "invalid_base64_length"
+ | "invalid_base64_padding"
+ | "malformed_data_uri_header"
+ | "decode_failed";
+
+export type MediaIgnoredReason =
+ | "implausible_data_uri_prefix"
+ | "unsupported_content_type";
+
export type MediaPayloadCandidate = {
encodedData: string;
encoding: "base64" | "python_bytes_literal";
@@ -40,15 +52,36 @@ type TransformParams = {
processCandidate: (
candidate: MediaPayloadCandidate,
) => Promise<string | undefined>;
- onInvalidCandidate: (kind: MediaPayloadKind) => void;
+ onInvalidCandidate: (
+ kind: MediaPayloadKind,
+ reason: MediaInvalidReason,
+ ) => void;
+ onIgnoredCandidate: (
+ kind: MediaPayloadKind,
+ reason: MediaIgnoredReason,
+ ) => void;
onDetectionPath: (path: MediaDetectionPath, checkedBytes: number) => void;
};
-type DataUriOccurrence = {
- start: number;
- end: number;
- candidate?: MediaPayloadCandidate;
-};
+type DataUriOccurrence =
+ | {
+ start: number;
+ end: number;
+ status: "valid";
+ candidate: MediaPayloadCandidate;
+ }
+ | {
+ start: number;
+ end: number;
+ status: "invalid";
+ reason: MediaInvalidReason;
+ }
+ | {
+ start: number;
+ end: number;
+ status: "ignored";
+ reason: MediaIgnoredReason;
+ };
type TransformState = {
changed: boolean;
@@ -172,12 +205,7 @@ async function replaceDataUris(
): Promise<{ value: string; bytesRemoved: number }> {
params.onDetectionPath("data_uri", Buffer.byteLength(value, "utf8"));
const occurrences = findDataUris(value);
- if (occurrences.length === 0) {
- if (value.startsWith(DATA_URI_PREFIX)) {
- params.onInvalidCandidate("data_uri");
- }
- return { value, bytesRemoved: 0 };
- }
+ if (occurrences.length === 0) return { value, bytesRemoved: 0 };
let output = "";
let cursor = 0;
@@ -186,8 +214,11 @@ async function replaceDataUris(
for (const occurrence of occurrences) {
const original = value.slice(occurrence.start, occurrence.end);
output += value.slice(cursor, occurrence.start);
- if (!occurrence.candidate) {
- params.onInvalidCandidate("data_uri");
+ if (occurrence.status === "invalid") {
+ params.onInvalidCandidate("data_uri", occurrence.reason);
+ output += original;
+ } else if (occurrence.status === "ignored") {
+ params.onIgnoredCandidate("data_uri", occurrence.reason);
output += original;
} else {
const resolvedReplacement = await params.processCandidate(
@@ -221,15 +252,30 @@ function findDataUris(value: string): DataUriOccurrence[] {
let start = value.indexOf(DATA_URI_PREFIX, cursor);
if (start === -1) break;
+ if (!hasPlausibleDataUriBoundary(value, start)) {
+ occurrences.push({
+ start,
+ end: start + DATA_URI_PREFIX.length,
+ status: "ignored",
+ reason: "implausible_data_uri_prefix",
+ });
+ cursor = start + DATA_URI_PREFIX.length;
+ continue;
+ }
+
let headerCursor = start + DATA_URI_PREFIX.length;
let contentTypeEnd: number | undefined;
let markerStart: number | undefined;
while (headerCursor < value.length) {
if (value.startsWith(DATA_URI_PREFIX, headerCursor)) {
- start = headerCursor;
- headerCursor += DATA_URI_PREFIX.length;
- contentTypeEnd = undefined;
- markerStart = undefined;
+ if (hasPlausibleDataUriBoundary(value, headerCursor)) {
+ start = headerCursor;
+ headerCursor += DATA_URI_PREFIX.length;
+ contentTypeEnd = undefined;
+ markerStart = undefined;
+ } else {
+ headerCursor += DATA_URI_PREFIX.length;
+ }
continue;
}
const code = value.charCodeAt(headerCursor);
@@ -251,6 +297,20 @@ function findDataUris(value: string): DataUriOccurrence[] {
}
const dataStart = markerStart + BASE64_MARKER.length;
+ const contentType = value.slice(
+ start + DATA_URI_PREFIX.length,
+ contentTypeEnd ?? markerStart,
+ );
+ const header = value.slice(start + DATA_URI_PREFIX.length, markerStart);
+ const invalidHeader = getInvalidDataUriHeaderReason(header, contentType);
+ if (invalidHeader) {
+ // Do not walk a potentially multi-megabyte body when its prefix already
+ // proves that it cannot be uploaded.
+ occurrences.push({ start, end: dataStart, ...invalidHeader });
+ cursor = dataStart;
+ continue;
+ }
+
let end = dataStart;
let padding = 0;
let valid = true;
@@ -265,34 +325,123 @@ function findDataUris(value: string): DataUriOccurrence[] {
end += 1;
}
- const contentType = value.slice(
- start + DATA_URI_PREFIX.length,
- contentTypeEnd ?? markerStart,
- );
const base64Data = value.slice(dataStart, end);
- occurrences.push({
- start,
- end,
- candidate:
- valid &&
- base64Data.length > 0 &&
- base64Data.length % 4 !== 1 &&
- isMediaContentType(contentType)
- ? {
- encodedData: base64Data,
- encoding: "base64",
- contentType,
- kind: "data_uri",
- source: "base64_data_uri",
- }
- : undefined,
- });
+
+ if (base64Data.length === 0) {
+ occurrences.push({
+ start,
+ end,
+ status: "invalid",
+ reason:
+ end < value.length && !isDataUriTerminator(value.charCodeAt(end))
+ ? "invalid_base64"
+ : "empty_payload",
+ });
+ } else if (
+ end < value.length &&
+ !isDataUriTerminator(value.charCodeAt(end))
+ ) {
+ occurrences.push({
+ start,
+ end,
+ status: "invalid",
+ reason: "invalid_base64",
+ });
+ } else if (!valid) {
+ occurrences.push({
+ start,
+ end,
+ status: "invalid",
+ reason: "invalid_base64_padding",
+ });
+ } else if (base64Data.length % 4 === 1) {
+ occurrences.push({
+ start,
+ end,
+ status: "invalid",
+ reason: "invalid_base64_length",
+ });
+ } else {
+ occurrences.push({
+ start,
+ end,
+ status: "valid",
+ candidate: {
+ encodedData: base64Data,
+ encoding: "base64",
+ contentType: contentType as MediaContentType,
+ kind: "data_uri",
+ source: "base64_data_uri",
+ },
+ });
+ }
cursor = Math.max(end, dataStart);
}
return occurrences;
}
+function getInvalidDataUriHeaderReason(
+ header: string,
+ contentType: string,
+):
+ | {
+ status: "invalid";
+ reason: "malformed_data_uri_header";
+ }
+ | {
+ status: "ignored";
+ reason: "unsupported_content_type";
+ }
+ | undefined {
+ const parameters = header.slice(contentType.length);
+ if (
+ !/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/.test(
+ contentType,
+ ) ||
+ !/^(?:;[A-Za-z0-9!#$&^_.+-]+=[^;,\s"'<>[\]{}]+)*$/.test(parameters)
+ ) {
+ return { status: "invalid", reason: "malformed_data_uri_header" };
+ }
+ if (!isMediaContentType(contentType)) {
+ return { status: "ignored", reason: "unsupported_content_type" };
+ }
+}
+
+function hasPlausibleDataUriBoundary(value: string, start: number): boolean {
+ if (start === 0) return true;
+ const previousCode = value.charCodeAt(start - 1);
+ return !(
+ (previousCode >= 48 && previousCode <= 57) ||
+ (previousCode >= 65 && previousCode <= 90) ||
+ (previousCode >= 97 && previousCode <= 122) ||
+ previousCode === 45 ||
+ previousCode === 95
+ );
+}
+
+function isDataUriTerminator(code: number): boolean {
+ // Embedded Data URIs commonly end immediately before sentence punctuation.
+ return (
+ Number.isNaN(code) ||
+ code === 9 ||
+ code === 10 ||
+ code === 13 ||
+ code === 32 ||
+ code === 33 ||
+ code === 34 ||
+ code === 39 ||
+ code === 41 ||
+ code === 44 ||
+ code === 46 ||
+ code === 59 ||
+ code === 62 ||
+ code === 63 ||
+ code === 93 ||
+ code === 125
+ );
+}
+
/**
* Traverses a structured payload and mutates it in place for every successful
* media replacement. Candidate operations run sequentially after discovery to
@@ -473,12 +622,16 @@ async function replaceStructuredMedia(
if (isMediaReference(media.content) || isRemoteUrl(media.content)) return;
const candidate = parseStructuredMediaCandidate(media);
- if (!candidate) {
- params.onInvalidCandidate(media.kind);
+ if (candidate.status === "ignored") {
+ params.onIgnoredCandidate(media.kind, candidate.reason);
+ return;
+ }
+ if (candidate.status === "invalid") {
+ params.onInvalidCandidate(media.kind, candidate.reason);
return;
}
- const replacement = await params.processCandidate(candidate);
+ const replacement = await params.processCandidate(candidate.candidate);
if (replacement) {
defineOwnValue(media.target, media.property, replacement);
return Math.max(
@@ -491,46 +644,62 @@ async function replaceStructuredMedia(
function parseStructuredMediaCandidate(
media: StructuredMedia,
-): MediaPayloadCandidate | undefined {
- if (!isMediaContentType(media.contentType)) return;
+):
+ | { status: "valid"; candidate: MediaPayloadCandidate }
+ | { status: "invalid"; reason: MediaInvalidReason }
+ | { status: "ignored"; reason: MediaIgnoredReason } {
+ if (!isMediaContentType(media.contentType)) {
+ return { status: "ignored", reason: "unsupported_content_type" };
+ }
if (media.content.startsWith(DATA_URI_PREFIX)) {
const occurrences = findDataUris(media.content);
- const candidate =
+ const occurrence =
occurrences.length === 1 &&
occurrences[0]?.start === 0 &&
occurrences[0]?.end === media.content.length
- ? occurrences[0].candidate
+ ? occurrences[0]
: undefined;
- return candidate
- ? {
- ...candidate,
- contentType: media.contentType,
- kind: media.kind,
- source: "bytes",
- }
- : undefined;
+ if (!occurrence) {
+ return { status: "invalid", reason: "invalid_base64" };
+ }
+ if (occurrence.status !== "valid") return occurrence;
+ return {
+ status: "valid",
+ candidate: {
+ ...occurrence.candidate,
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ },
+ };
}
if (isPythonBytesLiteral(media.content)) {
return {
- encodedData: media.content,
- encoding: "python_bytes_literal",
- contentType: media.contentType,
- kind: media.kind,
- source: "bytes",
+ status: "valid",
+ candidate: {
+ encodedData: media.content,
+ encoding: "python_bytes_literal",
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ },
};
}
return isValidBase64(media.content)
? {
- encodedData: media.content,
- encoding: "base64",
- contentType: media.contentType,
- kind: media.kind,
- source: "bytes",
+ status: "valid",
+ candidate: {
+ encodedData: media.content,
+ encoding: "base64",
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ },
}
- : undefined;
+ : { status: "invalid", reason: "invalid_base64" };
}
function isPythonBytesLiteral(value: string): boolean {
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.test.ts b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
index 644eff9b54..0428070f88 100644
--- a/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
@@ -12,7 +12,8 @@ import type { MediaField } from "../../domain/media";
import { recordDistribution, recordIncrement } from "../instrumentation";
import {
processOtelMedia,
- type OtelMediaEvent,
+ type OtelMediaPayload,
+ type OtelMediaTarget,
type UploadOtelMedia,
} from "./OtelMediaProcessor";
@@ -34,15 +35,20 @@ const PYTHON_BYTES_LITERAL =
const MEDIA_REFERENCE = `@@@langfuseMedia:type=image/png|id=${MEDIA_ID}|source=base64_data_uri@@@`;
function createEvent(params: { value: unknown; field?: MediaField }): {
- event: OtelMediaEvent;
- body: OtelMediaEvent;
+ event: OtelMediaTarget;
+ body: OtelMediaPayload;
} {
- const body: OtelMediaEvent = {
- traceId: TRACE_ID,
- spanId: SPAN_ID,
+ const body: OtelMediaPayload = {
[params.field ?? "input"]: params.value,
};
- return { event: body, body };
+ return {
+ event: {
+ traceId: TRACE_ID,
+ observationId: SPAN_ID,
+ payload: body,
+ },
+ body,
+ };
}
function createUploadMock(
@@ -52,12 +58,13 @@ function createUploadMock(
}
async function processEvents(
- events: OtelMediaEvent[],
+ targets: OtelMediaTarget[],
uploadMedia: UploadOtelMedia = createUploadMock(),
) {
return processOtelMedia({
- events,
+ targets,
projectId: "project-id",
+ writePath: "direct",
mediaBucket: "media-bucket",
mediaPrefix: "media/",
uploadMedia,
@@ -86,12 +93,12 @@ describe("processOtelMedia", () => {
expect(recordIncrement).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.detection_check",
1,
- { path: "data_uri" },
+ { path: "data_uri", write_path: "direct" },
);
expect(recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.detection_check_byte_length",
Buffer.byteLength(dataUri, "utf8"),
- { path: "data_uri" },
+ { path: "data_uri", write_path: "direct" },
);
expect(recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.byte_length",
@@ -99,6 +106,7 @@ describe("processOtelMedia", () => {
{
outcome: "uploaded",
media_kind: "data_uri",
+ write_path: "direct",
},
);
expect(result).toMatchObject({
@@ -129,6 +137,7 @@ describe("processOtelMedia", () => {
{
outcome: "reused",
media_kind: "data_uri",
+ write_path: "direct",
},
);
});
@@ -136,8 +145,6 @@ describe("processOtelMedia", () => {
it("processes every normalized media field and ignores unrelated fields", async () => {
const dataUri = `data:image/png;base64,${PNG_BASE64}`;
const body = {
- traceId: TRACE_ID,
- spanId: SPAN_ID,
input: dataUri,
output: dataUri,
metadata: { image: dataUri },
@@ -145,7 +152,16 @@ describe("processOtelMedia", () => {
};
const uploadMedia = createUploadMock();
- await processEvents([body], uploadMedia);
+ await processEvents(
+ [
+ {
+ traceId: TRACE_ID,
+ observationId: SPAN_ID,
+ payload: body,
+ },
+ ],
+ uploadMedia,
+ );
expect(uploadMedia).toHaveBeenCalledTimes(3);
expect(uploadMedia).toHaveBeenNthCalledWith(
@@ -263,6 +279,7 @@ describe("processOtelMedia", () => {
expect(result).toMatchObject({
uploaded: 1,
invalid: 0,
+ ignored: 0,
candidates: 1,
bytesProcessed: PYTHON_BYTES.length,
});
@@ -308,10 +325,31 @@ describe("processOtelMedia", () => {
expect(body.input).toBe(reference);
});
- it.each([
- ["an unsupported media type", "data:application/x-test;base64,dGVzdA=="],
- ["invalid base64", "data:image/png;base64,%%%"],
- ])("leaves %s unchanged", async (_, value) => {
+ it("classifies unsupported Data URI content types as ignored", async () => {
+ const value = "data:application/x-test;base64,dGVzdA==";
+ const { event, body } = createEvent({ value });
+ const uploadMedia = createUploadMock();
+
+ const result = await processEvents([event], uploadMedia);
+
+ expect(uploadMedia).not.toHaveBeenCalled();
+ expect(body.input).toBe(value);
+ expect(result.invalid).toBe(0);
+ expect(result.ignored).toBe(1);
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media",
+ 1,
+ {
+ outcome: "ignored",
+ media_kind: "data_uri",
+ reason: "unsupported_content_type",
+ write_path: "direct",
+ },
+ );
+ });
+
+ it("classifies malformed Data URI base64 as invalid", async () => {
+ const value = "data:image/png;base64,%%%";
const { event, body } = createEvent({ value });
const uploadMedia = createUploadMock();
@@ -320,5 +358,32 @@ describe("processOtelMedia", () => {
expect(uploadMedia).not.toHaveBeenCalled();
expect(body.input).toBe(value);
expect(result.invalid).toBe(1);
+ expect(result.ignored).toBe(0);
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media",
+ 1,
+ {
+ outcome: "invalid",
+ media_kind: "data_uri",
+ reason: "invalid_base64",
+ write_path: "direct",
+ },
+ );
+ });
+
+ it("links trace-level media without an observation id", async () => {
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const body = { input: dataUri };
+ const uploadMedia = createUploadMock();
+
+ await processEvents([{ traceId: TRACE_ID, payload: body }], uploadMedia);
+
+ expect(uploadMedia).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceId: TRACE_ID,
+ observationId: undefined,
+ }),
+ );
+ expect(body.input).toBe(MEDIA_REFERENCE);
});
});
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.ts b/packages/shared/src/server/otel/OtelMediaProcessor.ts
index eb35da5432..9a90c1b5ec 100644
--- a/packages/shared/src/server/otel/OtelMediaProcessor.ts
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.ts
@@ -4,26 +4,39 @@ import { logger } from "../logger";
import {
transformMediaPayload,
type MediaDetectionPath,
+ type MediaIgnoredReason,
+ type MediaInvalidReason,
type MediaPayloadCandidate,
type MediaPayloadKind,
} from "../media/MediaPayloadProcessor";
import type { UploadMediaForTraceResult } from "../media/mediaService";
export type OtelMediaKind = MediaPayloadKind;
+export type OtelMediaWritePath = "direct" | "legacy";
-/** A normalized OTEL observation destined for direct events-table storage. */
-export type OtelMediaEvent = {
- traceId: string;
- spanId: string;
+/** Mutable input, output, and metadata fields owned by one normalized event. */
+export type OtelMediaPayload = {
input?: unknown;
output?: unknown;
metadata?: unknown;
};
+/**
+ * Storage context plus the mutable normalized payload to inspect.
+ *
+ * `observationId` is absent for trace-level input, output, and metadata.
+ * Successful media replacements mutate `payload` in place.
+ */
+export type OtelMediaTarget = {
+ traceId: string;
+ observationId?: string;
+ payload: OtelMediaPayload;
+};
+
export type UploadOtelMedia = (params: {
projectId: string;
traceId: string;
- observationId: string;
+ observationId?: string;
field: MediaField;
contentType: MediaContentType;
contentBytes: Buffer;
@@ -37,8 +50,10 @@ export type OtelMediaProcessResult = {
uploaded: number;
/** Candidates already present in media storage and linked without uploading. */
reused: number;
- /** Values matching a media shape but failing MIME type or base64 validation. */
+ /** Plausible media values that fail header, base64, or decoding validation. */
invalid: number;
+ /** Unsupported media types and implausible Data URI prefix matches. */
+ ignored: number;
/** Valid candidates whose upload or media-link operation failed. */
failed: number;
/**
@@ -63,8 +78,9 @@ export type OtelMediaProcessResult = {
type ProcessContext = {
projectId: string;
traceId: string;
- observationId: string;
+ observationId?: string;
field: MediaField;
+ writePath: OtelMediaWritePath;
mediaBucket: string;
mediaPrefix: string;
uploadMedia: UploadOtelMedia;
@@ -72,8 +88,8 @@ type ProcessContext = {
};
/**
- * Detects and uploads embedded media for normalized OTEL events that are
- * destined for direct persistence in the events table.
+ * Detects and uploads embedded media for normalized OTEL payloads selected by
+ * either the direct or legacy events-table persistence path.
*
* Events, fields, and candidates are processed sequentially to bound peak
* decoded media memory. Successful replacements mutate each event in place.
@@ -81,17 +97,26 @@ type ProcessContext = {
* reflected in the returned counters instead of failing the whole run.
*/
export async function processOtelMedia(params: {
- events: OtelMediaEvent[];
+ targets: OtelMediaTarget[];
projectId: string;
+ writePath: OtelMediaWritePath;
mediaBucket: string;
mediaPrefix: string;
uploadMedia: UploadOtelMedia;
}): Promise<OtelMediaProcessResult> {
- const { events, projectId, mediaBucket, mediaPrefix, uploadMedia } = params;
+ const {
+ targets,
+ projectId,
+ writePath,
+ mediaBucket,
+ mediaPrefix,
+ uploadMedia,
+ } = params;
const result: OtelMediaProcessResult = {
uploaded: 0,
reused: 0,
invalid: 0,
+ ignored: 0,
failed: 0,
bytesRemoved: 0,
candidates: 0,
@@ -107,16 +132,17 @@ export async function processOtelMedia(params: {
structured_payload: 0,
},
};
- for (const event of events) {
+ for (const target of targets) {
for (const field of ["input", "output", "metadata"] as const) {
- const originalValue = event[field];
+ const originalValue = target.payload[field];
if (originalValue == null) continue;
const context: ProcessContext = {
projectId,
- traceId: event.traceId,
- observationId: event.spanId,
+ traceId: target.traceId,
+ observationId: target.observationId,
field,
+ writePath,
mediaBucket,
mediaPrefix,
uploadMedia,
@@ -124,7 +150,10 @@ export async function processOtelMedia(params: {
};
const transformed = await transformMediaPayload(originalValue, {
processCandidate: (candidate) => processCandidate(candidate, context),
- onInvalidCandidate: (kind) => recordInvalidCandidate(kind, context),
+ onInvalidCandidate: (kind, reason) =>
+ recordInvalidCandidate(kind, reason, context),
+ onIgnoredCandidate: (kind, reason) =>
+ recordIgnoredCandidate(kind, reason, context),
onDetectionPath: (path, checkedBytes) =>
recordDetectionCheck(path, checkedBytes, context),
});
@@ -132,13 +161,14 @@ export async function processOtelMedia(params: {
// Structured objects are mutated by transformMediaPayload itself and keep
// their identity. Strings instead return a new value that must be assigned.
if (transformed.value !== originalValue) {
- event[field] = transformed.value;
+ target.payload[field] = transformed.value;
}
if (transformed.bytesRemoved > 0) {
result.bytesRemoved += transformed.bytesRemoved;
recordDistribution(
"langfuse.ingestion.otel.media.bytes_removed",
transformed.bytesRemoved,
+ { write_path: context.writePath },
);
}
}
@@ -164,11 +194,11 @@ async function processCandidate(
? Buffer.from(candidate.encodedData, "base64")
: decodePythonBytesLiteral(candidate.encodedData);
if (contentBytes.length === 0) {
- recordInvalidCandidate(candidate.kind, context);
+ recordInvalidCandidate(candidate.kind, "empty_payload", context);
return;
}
} catch {
- recordInvalidCandidate(candidate.kind, context);
+ recordInvalidCandidate(candidate.kind, "decode_failed", context);
return;
}
@@ -191,6 +221,7 @@ async function processCandidate(
recordIncrement("langfuse.ingestion.otel.media", 1, {
outcome: uploadResult.outcome,
media_kind: candidate.kind,
+ write_path: context.writePath,
});
recordDistribution(
"langfuse.ingestion.otel.media.byte_length",
@@ -198,6 +229,7 @@ async function processCandidate(
{
outcome: uploadResult.outcome,
media_kind: candidate.kind,
+ write_path: context.writePath,
},
);
@@ -207,6 +239,7 @@ async function processCandidate(
recordIncrement("langfuse.ingestion.otel.media", 1, {
outcome: "failed",
media_kind: candidate.kind,
+ write_path: context.writePath,
});
logger.warn(
"OTEL media upload failed; leaving normalized value unchanged",
@@ -310,21 +343,39 @@ function recordDetectionCheck(
context.result.detectionCheckedBytes[path] += checkedBytes;
recordIncrement("langfuse.ingestion.otel.media.detection_check", 1, {
path,
+ write_path: context.writePath,
});
recordDistribution(
"langfuse.ingestion.otel.media.detection_check_byte_length",
checkedBytes,
- { path },
+ { path, write_path: context.writePath },
);
}
function recordInvalidCandidate(
kind: MediaPayloadKind,
+ reason: MediaInvalidReason,
context: ProcessContext,
): void {
context.result.invalid += 1;
recordIncrement("langfuse.ingestion.otel.media", 1, {
outcome: "invalid",
media_kind: kind,
+ reason,
+ write_path: context.writePath,
+ });
+}
+
+function recordIgnoredCandidate(
+ kind: MediaPayloadKind,
+ reason: MediaIgnoredReason,
+ context: ProcessContext,
+): void {
+ context.result.ignored += 1;
+ recordIncrement("langfuse.ingestion.otel.media", 1, {
+ outcome: "ignored",
+ media_kind: kind,
+ reason,
+ write_path: context.writePath,
});
}
diff --git a/worker/src/features/otel-media/processOtelMedia.test.ts b/worker/src/features/otel-media/processOtelMedia.test.ts
index 294c38398d..2dbddfefba 100644
--- a/worker/src/features/otel-media/processOtelMedia.test.ts
+++ b/worker/src/features/otel-media/processOtelMedia.test.ts
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => {
});
vi.mock("@langfuse/shared/src/server", () => ({
+ getClickhouseEntityType: (eventType: string) =>
+ eventType === "trace-create" ? "trace" : "observation",
instrumentAsync: mocks.instrumentAsync,
logger: mocks.logger,
processOtelMedia: vi.fn(),
@@ -23,16 +25,22 @@ vi.mock("@langfuse/shared/src/server", () => ({
uploadMediaForTrace: vi.fn(),
}));
-import { processOtelEventMedia } from "./processOtelMedia";
+import type { IngestionEventType } from "@langfuse/shared/src/server";
+import {
+ createDirectOtelMediaTargets,
+ createLegacyOtelMediaTargets,
+ processOtelEventMedia,
+} from "./processOtelMedia";
const processResult = {
uploaded: 1,
reused: 2,
invalid: 3,
- failed: 4,
- bytesRemoved: 5,
- candidates: 6,
- bytesProcessed: 7,
+ ignored: 4,
+ failed: 5,
+ bytesRemoved: 6,
+ candidates: 7,
+ bytesProcessed: 8,
detectionChecks: {
data_uri: 8,
stringified_json: 9,
@@ -58,12 +66,13 @@ describe("processOtelEventMedia", () => {
const processMedia = vi.fn().mockResolvedValue(processResult);
await processOtelEventMedia({
- eventInputs: [
+ targets: createDirectOtelMediaTargets([
eventInput,
{ traceId: "trace-id", spanId: "without-media-fields" },
{ traceId: "trace-id", input: "missing-span-id" },
null,
- ],
+ ]),
+ writePath: "direct",
projectId: "project-id",
fileKey: "file-key",
mediaBucket: "media-bucket",
@@ -72,7 +81,16 @@ describe("processOtelEventMedia", () => {
});
expect(processMedia).toHaveBeenCalledWith(
- expect.objectContaining({ events: [eventInput] }),
+ expect.objectContaining({
+ targets: [
+ {
+ traceId: "trace-id",
+ observationId: "observation-id",
+ payload: eventInput,
+ },
+ ],
+ writePath: "direct",
+ }),
);
expect(mocks.instrumentAsync).toHaveBeenCalledWith(
{ name: "langfuse.ingestion.otel.media.process" },
@@ -81,22 +99,27 @@ describe("processOtelEventMedia", () => {
expect(mocks.span.setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
"langfuse.ingestion.otel.media.uploaded": 1,
- "langfuse.ingestion.otel.media.bytes_processed": 7,
+ "langfuse.ingestion.otel.media.ignored": 4,
+ "langfuse.ingestion.otel.media.bytes_processed": 8,
+ "langfuse.ingestion.otel.media.write_path": "direct",
"langfuse.ingestion.otel.media.detection_checks.stringified_json": 9,
"langfuse.ingestion.otel.media.detection_checked_bytes.structured_payload": 12,
}),
);
expect(mocks.recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.batch_byte_length",
- 7,
+ 8,
+ { write_path: "direct" },
);
expect(mocks.recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.batch_checked_byte_length",
33,
+ { write_path: "direct" },
);
expect(mocks.recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.processing_duration_ms",
expect.any(Number),
+ { write_path: "direct" },
);
});
@@ -104,7 +127,10 @@ describe("processOtelEventMedia", () => {
const processMedia = vi.fn();
await processOtelEventMedia({
- eventInputs: [{ traceId: "trace-id", spanId: "observation-id" }],
+ targets: createDirectOtelMediaTargets([
+ { traceId: "trace-id", spanId: "observation-id" },
+ ]),
+ writePath: "direct",
projectId: "project-id",
fileKey: "file-key",
mediaBucket: "media-bucket",
@@ -121,13 +147,14 @@ describe("processOtelEventMedia", () => {
await expect(
processOtelEventMedia({
- eventInputs: [
+ targets: createDirectOtelMediaTargets([
{
traceId: "trace-id",
spanId: "observation-id",
input: "input",
},
- ],
+ ]),
+ writePath: "direct",
projectId: "project-id",
fileKey: "file-key",
mediaBucket: "media-bucket",
@@ -139,6 +166,7 @@ describe("processOtelEventMedia", () => {
expect(mocks.recordDistribution).toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.processing_duration_ms",
expect.any(Number),
+ { write_path: "direct" },
);
expect(mocks.recordDistribution).not.toHaveBeenCalledWith(
"langfuse.ingestion.otel.media.batch_byte_length",
@@ -149,4 +177,41 @@ describe("processOtelEventMedia", () => {
expect.objectContaining({ projectId: "project-id", fileKey: "file-key" }),
);
});
+
+ it("creates legacy targets that retain trace and observation body references", () => {
+ const traceBody = {
+ id: "trace-id",
+ timestamp: "2026-07-23T00:00:00.000Z",
+ input: "trace-input",
+ };
+ const observationBody = {
+ id: "observation-id",
+ traceId: "trace-id",
+ startTime: "2026-07-23T00:00:00.000Z",
+ input: "observation-input",
+ };
+ const events = [
+ {
+ id: "trace-event-id",
+ type: "trace-create",
+ timestamp: "2026-07-23T00:00:00.000Z",
+ body: traceBody,
+ },
+ {
+ id: "observation-event-id",
+ type: "span-create",
+ timestamp: "2026-07-23T00:00:00.000Z",
+ body: observationBody,
+ },
+ ] as unknown as IngestionEventType[];
+
+ expect(createLegacyOtelMediaTargets(events)).toEqual([
+ { traceId: "trace-id", payload: traceBody },
+ {
+ traceId: "trace-id",
+ observationId: "observation-id",
+ payload: observationBody,
+ },
+ ]);
+ });
});
diff --git a/worker/src/features/otel-media/processOtelMedia.ts b/worker/src/features/otel-media/processOtelMedia.ts
index 1f2169d63b..bc29ab1262 100644
--- a/worker/src/features/otel-media/processOtelMedia.ts
+++ b/worker/src/features/otel-media/processOtelMedia.ts
@@ -1,17 +1,21 @@
import {
+ getClickhouseEntityType,
instrumentAsync,
logger,
processOtelMedia,
recordDistribution,
- type OtelMediaEvent,
+ type IngestionEventType,
+ type OtelMediaPayload,
+ type OtelMediaTarget,
+ type OtelMediaWritePath,
uploadMediaForTrace,
} from "@langfuse/shared/src/server";
const MEDIA_FIELDS = ["input", "output", "metadata"] as const;
/**
- * Worker integration point for media in normalized OTEL events. The ingestion
- * queue calls this only for enabled direct events-table writes.
+ * Worker integration point for media in normalized OTEL payloads selected for
+ * persistence by the ingestion queue.
*
* Responsibilities are split across three layers:
* - This adapter filters event shapes and owns storage configuration,
@@ -22,12 +26,13 @@ const MEDIA_FIELDS = ["input", "output", "metadata"] as const;
* Data URI/provider-shape detection and replacement algorithm. It has no
* knowledge of OTEL, storage, projects, or tracing.
*
- * Successful replacements mutate each event in place. Missing storage
+ * Successful replacements mutate each target payload in place. Missing storage
* configuration or unexpected processing errors are logged and swallowed so
* media extraction cannot reject the enclosing OTEL ingestion job.
*/
export async function processOtelEventMedia(params: {
- eventInputs: unknown[];
+ targets: OtelMediaTarget[];
+ writePath: OtelMediaWritePath;
projectId: string;
fileKey: string;
mediaBucket?: string;
@@ -35,7 +40,8 @@ export async function processOtelEventMedia(params: {
processMedia?: typeof processOtelMedia;
}): Promise<void> {
const {
- eventInputs,
+ targets,
+ writePath,
projectId,
fileKey,
mediaBucket,
@@ -51,8 +57,7 @@ export async function processOtelEventMedia(params: {
return;
}
- const events = eventInputs.filter(isOtelMediaEvent);
- if (events.length === 0) return;
+ if (targets.length === 0) return;
try {
await instrumentAsync(
@@ -61,8 +66,9 @@ export async function processOtelEventMedia(params: {
const startedAt = Date.now();
try {
const result = await processMedia({
- events,
+ targets,
projectId,
+ writePath,
mediaBucket,
mediaPrefix,
uploadMedia: uploadMediaForTrace,
@@ -72,7 +78,9 @@ export async function processOtelEventMedia(params: {
"langfuse.ingestion.otel.media.uploaded": result.uploaded,
"langfuse.ingestion.otel.media.reused": result.reused,
"langfuse.ingestion.otel.media.invalid": result.invalid,
+ "langfuse.ingestion.otel.media.ignored": result.ignored,
"langfuse.ingestion.otel.media.failed": result.failed,
+ "langfuse.ingestion.otel.media.write_path": writePath,
"langfuse.ingestion.otel.media.candidates": result.candidates,
"langfuse.ingestion.otel.media.bytes_processed":
result.bytesProcessed,
@@ -94,6 +102,7 @@ export async function processOtelEventMedia(params: {
recordDistribution(
"langfuse.ingestion.otel.media.batch_byte_length",
result.bytesProcessed,
+ { write_path: writePath },
);
recordDistribution(
"langfuse.ingestion.otel.media.batch_checked_byte_length",
@@ -101,11 +110,13 @@ export async function processOtelEventMedia(params: {
(total, bytes) => total + bytes,
0,
),
+ { write_path: writePath },
);
} finally {
recordDistribution(
"langfuse.ingestion.otel.media.processing_duration_ms",
Date.now() - startedAt,
+ { write_path: writePath },
);
}
},
@@ -118,15 +129,70 @@ export async function processOtelEventMedia(params: {
}
}
-function isOtelMediaEvent(value: unknown): value is OtelMediaEvent {
+/**
+ * Creates media targets for direct events-table inputs without cloning their
+ * potentially large input, output, or metadata values.
+ */
+export function createDirectOtelMediaTargets(
+ eventInputs: unknown[],
+): OtelMediaTarget[] {
+ const targets: OtelMediaTarget[] = [];
+ for (const value of eventInputs) {
+ if (!isRecordWithMediaFields(value)) continue;
+ if (typeof value.traceId !== "string" || typeof value.spanId !== "string") {
+ continue;
+ }
+ targets.push({
+ traceId: value.traceId,
+ observationId: value.spanId,
+ payload: value,
+ });
+ }
+ return targets;
+}
+
+/**
+ * Creates media targets for normalized legacy trace and observation events.
+ *
+ * The returned targets reference each event's existing `body`; successful
+ * replacements therefore reach both legacy persistence and event forwarding
+ * without copying or synchronizing large payloads.
+ */
+export function createLegacyOtelMediaTargets(
+ events: IngestionEventType[],
+): OtelMediaTarget[] {
+ const targets: OtelMediaTarget[] = [];
+ for (const event of events) {
+ const body: unknown = event.body;
+ if (!isRecordWithMediaFields(body)) continue;
+
+ const entityType = getClickhouseEntityType(event.type);
+ if (entityType === "trace" && typeof body.id === "string") {
+ targets.push({ traceId: body.id, payload: body });
+ continue;
+ }
+ if (
+ entityType === "observation" &&
+ typeof body.traceId === "string" &&
+ typeof body.id === "string"
+ ) {
+ targets.push({
+ traceId: body.traceId,
+ observationId: body.id,
+ payload: body,
+ });
+ }
+ }
+ return targets;
+}
+
+function isRecordWithMediaFields(
+ value: unknown,
+): value is Record<string, unknown> & OtelMediaPayload {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return false;
}
- const event = value as Record<string, unknown>;
- return (
- typeof event.traceId === "string" &&
- typeof event.spanId === "string" &&
- MEDIA_FIELDS.some((field) => event[field] != null)
- );
+ const record = value as Record<string, unknown>;
+ return MEDIA_FIELDS.some((field) => record[field] != null);
}
diff --git a/worker/src/queues/__tests__/otelDirectEventWrite.test.ts b/worker/src/queues/__tests__/otelDirectEventWrite.test.ts
index 664fde32b9..636d7eb202 100644
--- a/worker/src/queues/__tests__/otelDirectEventWrite.test.ts
+++ b/worker/src/queues/__tests__/otelDirectEventWrite.test.ts
@@ -3,9 +3,28 @@ import {
checkHeaderBasedDirectWrite,
checkSdkVersionRequirements,
getSdkInfoFromResourceSpans,
+ shouldProcessLegacyOtelMedia,
type SdkInfo,
} from "../otelIngestionQueue";
+describe("shouldProcessLegacyOtelMedia", () => {
+ it("processes media whenever legacy tables are written", () => {
+ expect(
+ shouldProcessLegacyOtelMedia({
+ mediaUploadEnabled: true,
+ writesToLegacyTables: true,
+ }),
+ ).toBe(true);
+ });
+
+ it.each([
+ { mediaUploadEnabled: false, writesToLegacyTables: true },
+ { mediaUploadEnabled: true, writesToLegacyTables: false },
+ ])("skips media when legacy processing is disabled", (params) => {
+ expect(shouldProcessLegacyOtelMedia(params)).toBe(false);
+ });
+});
+
describe("checkHeaderBasedDirectWrite", () => {
it.each<{
input: Parameters<typeof checkHeaderBasedDirectWrite>[0];
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
index b1921e30e9..e60bb33e30 100644
--- a/worker/src/queues/otelIngestionQueue.ts
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -46,7 +46,22 @@ import {
scheduleObservationEvals,
createObservationEvalSchedulerDeps,
} from "../features/evaluation/observationEval";
-import { processOtelEventMedia } from "../features/otel-media/processOtelMedia";
+import {
+ createDirectOtelMediaTargets,
+ createLegacyOtelMediaTargets,
+ processOtelEventMedia,
+} from "../features/otel-media/processOtelMedia";
+
+/**
+ * Legacy media processing follows legacy persistence, independently of
+ * whether the same batch also qualifies for a direct events-table write.
+ */
+export function shouldProcessLegacyOtelMedia(params: {
+ mediaUploadEnabled: boolean;
+ writesToLegacyTables: boolean;
+}): boolean {
+ return params.mediaUploadEnabled && params.writesToLegacyTables;
+}
/**
* Check if HTTP headers from the SDK request indicate the batch is eligible
@@ -433,7 +448,12 @@ export const otelIngestionQueueProcessorBuilder = (
// validation already guarantees useDirectEventWrite is true here, so
// observations and traces don't need the mergeAndWrite / IngestionQueue
// detour that would otherwise populate the legacy tables.
- const skipLegacyWrites = !v4WritesToLegacyTables(env);
+ const writesToLegacyTables = v4WritesToLegacyTables(env);
+ const skipLegacyWrites = !writesToLegacyTables;
+ const shouldProcessLegacyMedia = shouldProcessLegacyOtelMedia({
+ mediaUploadEnabled: env.LANGFUSE_OTEL_MEDIA_UPLOAD_ENABLED === "true",
+ writesToLegacyTables,
+ });
if (skipLegacyWrites) {
span?.setAttribute(
@@ -445,6 +465,20 @@ export const otelIngestionQueueProcessorBuilder = (
const shouldForwardToEventsTable =
!useDirectEventWrite && v4WritesToEventsTable(env);
+ if (shouldProcessLegacyMedia) {
+ // 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({
+ targets: createLegacyOtelMediaTargets(traces.concat(observations)),
+ writePath: "legacy",
+ projectId,
+ fileKey,
+ mediaBucket: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ mediaPrefix: env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX,
+ });
+ }
+
// 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.
@@ -517,7 +551,8 @@ export const otelIngestionQueueProcessorBuilder = (
shouldWriteToEventsTable
) {
await processOtelEventMedia({
- eventInputs,
+ targets: createDirectOtelMediaTargets(eventInputs),
+ writePath: "direct",
projectId,
fileKey,
mediaBucket: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,