Skip to content

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

feat(otel): upload media during worker ingestion (#15120)

Hassieb Pakzaddc9e36fa2585
diff --git a/.env.dev.example b/.env.dev.example
index 991d17cd93..6b0bc2fddb 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -102,6 +102,8 @@ LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9090
## Necessary for minio compatibility
LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE=true
LANGFUSE_S3_MEDIA_UPLOAD_PREFIX=media/
+# Opt in to extracting and uploading media embedded in OTEL span attributes.
+LANGFUSE_OTEL_MEDIA_UPLOAD_ENABLED=false
# S3 Event Bucket Upload
## Set to true to test uploading all events to S3
diff --git a/.env.prod.example b/.env.prod.example
index 04a816f96c..08d9c5ae68 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -354,6 +354,7 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED=true
# Enable enforcement: send emails and block orgs that exceed free tier limits (default: false)
# LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED=false
+
# Optional BCC address for usage threshold emails (e.g., for CRM integration like HubSpot)
# CLOUD_CRM_EMAIL=
diff --git a/packages/shared/src/domain/index.ts b/packages/shared/src/domain/index.ts
index 78572c2510..bfadb57f19 100644
--- a/packages/shared/src/domain/index.ts
+++ b/packages/shared/src/domain/index.ts
@@ -7,3 +7,4 @@ export * from "./automations";
export * from "./webhooks";
export * from "./prompts";
export * from "./dataset-items";
+export * from "./media";
diff --git a/web/src/features/media/server/getFileExtensionFromContentType.ts b/packages/shared/src/domain/media.ts
similarity index 51%
rename from web/src/features/media/server/getFileExtensionFromContentType.ts
rename to packages/shared/src/domain/media.ts
index fea48d89be..901387f0c7 100644
--- a/web/src/features/media/server/getFileExtensionFromContentType.ts
+++ b/packages/shared/src/domain/media.ts
@@ -1,8 +1,123 @@
-import { MediaContentType, MediaFileExtension } from "../validation";
+export enum MediaContentType {
+ PNG = "image/png",
+ JPEG = "image/jpeg",
+ JPG = "image/jpg",
+ WEBP = "image/webp",
+ GIF = "image/gif",
+ SVG = "image/svg+xml",
+ TIFF = "image/tiff",
+ BMP = "image/bmp",
+ AVIF = "image/avif",
+ HEIC = "image/heic",
+ MP3 = "audio/mpeg",
+ MP3_LEGACY = "audio/mp3",
+ WAV = "audio/wav",
+ OGG = "audio/ogg",
+ OGA = "audio/oga",
+ AAC = "audio/aac",
+ M4A = "audio/mp4",
+ FLAC = "audio/flac",
+ OPUS = "audio/opus",
+ WEBA = "audio/webm",
+ MP4 = "video/mp4",
+ WEBM = "video/webm",
+ VIDEO_OGG = "video/ogg",
+ MPEG = "video/mpeg",
+ MOV = "video/quicktime",
+ AVI = "video/x-msvideo",
+ MKV = "video/x-matroska",
+ TXT = "text/plain",
+ HTML = "text/html",
+ CSS = "text/css",
+ CSV = "text/csv",
+ MARKDOWN = "text/markdown",
+ PYTHON = "text/x-python",
+ JAVASCRIPT = "application/javascript",
+ TYPESCRIPT = "text/x-typescript",
+ YAML = "application/x-yaml",
+ PDF = "application/pdf",
+ DOC = "application/msword",
+ XLS = "application/vnd.ms-excel",
+ XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ZIP = "application/zip",
+ JSON = "application/json",
+ XML = "application/xml",
+ BIN = "application/octet-stream",
+ DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ RTF = "application/rtf",
+ JSONL = "application/x-ndjson",
+ PARQUET = "application/vnd.apache.parquet",
+ GZIP = "application/gzip",
+ TAR = "application/x-tar",
+ SEVEN_Z = "application/x-7z-compressed",
+}
-export const getFileExtensionFromContentType = (
+export enum MediaFileExtension {
+ PNG = "png",
+ JPG = "jpg",
+ JPEG = "jpeg",
+ WEBP = "webp",
+ GIF = "gif",
+ SVG = "svg",
+ TIFF = "tiff",
+ BMP = "bmp",
+ AVIF = "avif",
+ HEIC = "heic",
+ MP3 = "mp3",
+ WAV = "wav",
+ OGG = "ogg",
+ OGA = "oga",
+ AAC = "aac",
+ M4A = "m4a",
+ FLAC = "flac",
+ OPUS = "opus",
+ WEBA = "weba",
+ MP4 = "mp4",
+ WEBM = "webm",
+ OGV = "ogv",
+ MPEG = "mpeg",
+ MOV = "mov",
+ AVI = "avi",
+ MKV = "mkv",
+ TXT = "txt",
+ HTML = "html",
+ CSS = "css",
+ CSV = "csv",
+ MD = "md",
+ PY = "py",
+ JS = "js",
+ TS = "ts",
+ YAML = "yaml",
+ PDF = "pdf",
+ DOC = "doc",
+ XLS = "xls",
+ XLSX = "xlsx",
+ ZIP = "zip",
+ JSON = "json",
+ XML = "xml",
+ BIN = "bin",
+ DOCX = "docx",
+ PPTX = "pptx",
+ RTF = "rtf",
+ JSONL = "jsonl",
+ PARQUET = "parquet",
+ GZ = "gz",
+ TAR = "tar",
+ SEVEN_Z = "7z",
+}
+
+export type MediaField = "input" | "output" | "metadata";
+
+const mediaContentTypes = new Set<string>(Object.values(MediaContentType));
+
+export function isMediaContentType(value: unknown): value is MediaContentType {
+ return typeof value === "string" && mediaContentTypes.has(value);
+}
+
+export function getFileExtensionFromContentType(
contentType: MediaContentType,
-): MediaFileExtension => {
+): MediaFileExtension {
const mimeToExtension: Record<MediaContentType, MediaFileExtension> = {
[MediaContentType.PNG]: MediaFileExtension.PNG,
[MediaContentType.JPEG]: MediaFileExtension.JPEG,
@@ -58,10 +173,10 @@ export const getFileExtensionFromContentType = (
[MediaContentType.SEVEN_Z]: MediaFileExtension.SEVEN_Z,
};
- const extension = mimeToExtension[contentType as MediaContentType];
+ const extension = mimeToExtension[contentType];
if (!extension) {
throw new Error(`Unsupported content type: ${contentType}`);
}
return extension;
-};
+}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 16af87be04..11fcdb0f93 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -5,6 +5,7 @@ import {
} from "./repositories/events";
export * from "./services/StorageService";
+export * from "./media";
export * from "./services/safeBlobKeySegment";
export * from "./ingestion/eventBucketPath";
export * from "./cache";
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.test.ts b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
new file mode 100644
index 0000000000..161ecf43fc
--- /dev/null
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { transformMediaPayload } from "./MediaPayloadProcessor";
+
+const PNG_BASE64 = Buffer.from("test-image").toString("base64");
+const MEDIA_REFERENCE =
+ "@@@langfuseMedia:type=image/png|id=test-media-id|source=base64_data_uri@@@";
+
+describe("transformMediaPayload", () => {
+ it("does not inspect ordinary text containing data prefixes", async () => {
+ const processCandidate = vi.fn();
+ const onInvalidCandidate = vi.fn();
+ const onDetectionPath = vi.fn();
+ const value = "data: is a label, not necessarily an encoded media value";
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate,
+ onInvalidCandidate,
+ onDetectionPath,
+ });
+
+ expect(transformed.value).toBe(value);
+ expect(processCandidate).not.toHaveBeenCalled();
+ expect(onInvalidCandidate).not.toHaveBeenCalled();
+ expect(onDetectionPath).not.toHaveBeenCalled();
+ });
+
+ it("scans adversarial repeated data prefixes in linear time", async () => {
+ const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
+ const onDetectionPath = vi.fn();
+ const repeatedPrefixes = "data:".repeat(256_000);
+ const value = `${repeatedPrefixes}data:image/png;base64,${PNG_BASE64}`;
+ const startedAt = performance.now();
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath,
+ });
+ const elapsedMs = performance.now() - startedAt;
+
+ expect(transformed.value).toBe(`${repeatedPrefixes}${MEDIA_REFERENCE}`);
+ expect(elapsedMs).toBeLessThan(1_000);
+ expect(processCandidate).toHaveBeenCalledTimes(1);
+ expect(onDetectionPath).toHaveBeenCalledOnce();
+ expect(onDetectionPath).toHaveBeenCalledWith(
+ "data_uri",
+ Buffer.byteLength(value, "utf8"),
+ );
+ });
+
+ it("processes each embedded data URI occurrence independently", async () => {
+ const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
+ const onDetectionPath = vi.fn();
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+
+ const transformed = await transformMediaPayload(
+ `${dataUri} between ${dataUri}`,
+ {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath,
+ },
+ );
+
+ expect(transformed.value).toBe(
+ `${MEDIA_REFERENCE} between ${MEDIA_REFERENCE}`,
+ );
+ expect(processCandidate).toHaveBeenCalledTimes(2);
+ expect(onDetectionPath).toHaveBeenCalledOnce();
+ expect(onDetectionPath).toHaveBeenCalledWith(
+ "data_uri",
+ Buffer.byteLength(`${dataUri} between ${dataUri}`, "utf8"),
+ );
+ });
+
+ it("processes Data URIs with media type parameters", async () => {
+ const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
+ const textBase64 = Buffer.from("hello").toString("base64");
+ const dataUri = `data:text/plain;charset=utf-8;base64,${textBase64}`;
+
+ const transformed = await transformMediaPayload(`file: ${dataUri}`, {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath: vi.fn(),
+ });
+
+ expect(transformed.value).toBe(`file: ${MEDIA_REFERENCE}`);
+ expect(processCandidate).toHaveBeenCalledWith({
+ base64Data: textBase64,
+ contentType: "text/plain",
+ kind: "data_uri",
+ source: "base64_data_uri",
+ });
+ });
+
+ it("reports checks of shape-based stringified JSON", async () => {
+ const onDetectionPath = vi.fn();
+
+ await transformMediaPayload(
+ JSON.stringify(
+ {
+ type: "base64",
+ media_type: "image/png",
+ data: PNG_BASE64,
+ },
+ null,
+ 2,
+ ),
+ {
+ processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath,
+ },
+ );
+
+ expect(onDetectionPath).toHaveBeenCalledOnce();
+ expect(onDetectionPath).toHaveBeenCalledWith(
+ "stringified_json",
+ expect.any(Number),
+ );
+ });
+
+ it("processes Data URIs and raw base64 shapes in the same stringified JSON", async () => {
+ const processCandidate = vi.fn().mockResolvedValue(MEDIA_REFERENCE);
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const value = JSON.stringify({
+ image: dataUri,
+ document: {
+ type: "base64",
+ media_type: "image/png",
+ data: PNG_BASE64,
+ },
+ });
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath: vi.fn(),
+ });
+
+ expect(JSON.parse(transformed.value as string)).toEqual({
+ image: MEDIA_REFERENCE,
+ document: {
+ type: "base64",
+ media_type: "image/png",
+ data: MEDIA_REFERENCE,
+ },
+ });
+ expect(processCandidate).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not parse generic stringified JSON with data-like keys", async () => {
+ const processCandidate = vi.fn();
+ const onDetectionPath = vi.fn();
+ const value = JSON.stringify({
+ metadata: {
+ type: "record",
+ media_type: "report",
+ data: "ordinary application data",
+ },
+ });
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate,
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath,
+ });
+
+ expect(transformed.value).toBe(value);
+ expect(processCandidate).not.toHaveBeenCalled();
+ expect(onDetectionPath).not.toHaveBeenCalled();
+ });
+
+ it("processes structured normalized payloads without serializing them first", async () => {
+ const onDetectionPath = vi.fn();
+ const value = {
+ messages: [{ type: "base64", media_type: "image/png", data: PNG_BASE64 }],
+ };
+
+ const transformed = await transformMediaPayload(value, {
+ processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath,
+ });
+
+ expect(transformed.value).toBe(value);
+ expect(value.messages[0]?.data).toBe(MEDIA_REFERENCE);
+ expect(onDetectionPath).toHaveBeenCalledWith(
+ "structured_payload",
+ Buffer.byteLength(PNG_BASE64, "utf8"),
+ );
+ });
+
+ it("replaces an own __proto__ field without invoking its setter", async () => {
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const value: Record<string, unknown> = {};
+ const originalPrototype = Object.getPrototypeOf(value);
+ Object.defineProperty(value, "__proto__", {
+ configurable: true,
+ enumerable: true,
+ get: () => dataUri,
+ set: (replacement: unknown) => {
+ Object.setPrototypeOf(value, { polluted: replacement });
+ },
+ });
+
+ await transformMediaPayload(value, {
+ processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath: vi.fn(),
+ });
+
+ expect(Object.getPrototypeOf(value)).toBe(originalPrototype);
+ expect(Object.getOwnPropertyDescriptor(value, "__proto__")?.value).toBe(
+ MEDIA_REFERENCE,
+ );
+ });
+
+ it("replaces a structured media field without invoking its setter", async () => {
+ const setter = vi.fn();
+ const value: Record<string, unknown> = {
+ type: "base64",
+ media_type: "image/png",
+ };
+ Object.defineProperty(value, "data", {
+ configurable: true,
+ enumerable: true,
+ get: () => PNG_BASE64,
+ set: setter,
+ });
+
+ await transformMediaPayload(value, {
+ processCandidate: vi.fn().mockResolvedValue(MEDIA_REFERENCE),
+ onInvalidCandidate: vi.fn(),
+ onDetectionPath: vi.fn(),
+ });
+
+ expect(setter).not.toHaveBeenCalled();
+ expect(Object.getOwnPropertyDescriptor(value, "data")?.value).toBe(
+ MEDIA_REFERENCE,
+ );
+ });
+});
diff --git a/packages/shared/src/server/media/MediaPayloadProcessor.ts b/packages/shared/src/server/media/MediaPayloadProcessor.ts
new file mode 100644
index 0000000000..493a71fd00
--- /dev/null
+++ b/packages/shared/src/server/media/MediaPayloadProcessor.ts
@@ -0,0 +1,584 @@
+import { isMediaContentType, type MediaContentType } from "../../domain/media";
+
+const MAX_RECURSION_DEPTH = 10;
+const DATA_URI_PREFIX = "data:";
+const BASE64_MARKER = ";base64,";
+const MEDIA_REFERENCE_PREFIX = "@@@langfuseMedia:";
+const MEDIA_REFERENCE_SUFFIX = "@@@";
+const SERIALIZED_PROVIDER_MEDIA_TYPE =
+ /"type"\s*:\s*"(?:base64|media|blob|file)"/;
+
+export type MediaPayloadKind =
+ | "data_uri"
+ | "anthropic"
+ | "vertex"
+ | "gemini"
+ | "ai_sdk_v6"
+ | "ai_sdk_v7";
+
+export type MediaPayloadCandidate = {
+ base64Data: string;
+ contentType: MediaContentType;
+ kind: MediaPayloadKind;
+ source: "base64_data_uri" | "bytes";
+};
+
+export type MediaDetectionPath =
+ | "data_uri"
+ | "stringified_json"
+ | "structured_payload";
+
+export type TransformMediaPayloadResult = {
+ /** Transformed string, or the original structured value mutated in place. */
+ value: unknown;
+ /** UTF-8 bytes removed by successful media-reference replacements. */
+ bytesRemoved: number;
+};
+
+type TransformParams = {
+ processCandidate: (
+ candidate: MediaPayloadCandidate,
+ ) => Promise<string | undefined>;
+ onInvalidCandidate: (kind: MediaPayloadKind) => void;
+ onDetectionPath: (path: MediaDetectionPath, checkedBytes: number) => void;
+};
+
+type DataUriOccurrence = {
+ start: number;
+ end: number;
+ candidate?: MediaPayloadCandidate;
+};
+
+type TransformState = {
+ changed: boolean;
+ bytesRemoved: number;
+ checkedBytes: number;
+};
+
+type TraversalNode = {
+ value: unknown;
+ depth: number;
+ parent: Record<string, unknown> | unknown[];
+ key: string | number;
+};
+
+type StructuredMedia = {
+ target: Record<string, unknown>;
+ property: string;
+ content: string;
+ contentType: string;
+ kind: Exclude<MediaPayloadKind, "data_uri">;
+};
+
+const STRUCTURED_MEDIA_SHAPES = [
+ {
+ type: "base64",
+ contentType: "media_type",
+ property: "data",
+ kind: "anthropic",
+ },
+ {
+ type: "media",
+ contentType: "mime_type",
+ property: "data",
+ kind: "vertex",
+ },
+ {
+ type: "blob",
+ contentType: "mime_type",
+ property: "content",
+ kind: "ai_sdk_v7",
+ },
+] as const;
+
+/**
+ * Finds embedded media in a normalized input, output, or metadata value and
+ * delegates each valid candidate to `processCandidate`.
+ *
+ * String inputs are immutable and return a replacement string when changed.
+ * Object and array inputs are traversed and mutated in place only after a
+ * candidate is processed successfully. Unsupported values, invalid media, and
+ * candidates for which `processCandidate` returns `undefined` stay unchanged.
+ */
+export async function transformMediaPayload(
+ value: unknown,
+ params: TransformParams,
+): Promise<TransformMediaPayloadResult> {
+ if (typeof value !== "string") {
+ if (!isObject(value) && !Array.isArray(value)) {
+ return { value, bytesRemoved: 0 };
+ }
+
+ const state = await transformStructuredValue(value, params, true);
+ return { value, bytesRemoved: state.bytesRemoved };
+ }
+
+ if (isMediaReference(value)) return { value, bytesRemoved: 0 };
+
+ let valueToParse = value;
+ let dataUriResult: Awaited<ReturnType<typeof replaceDataUris>> | undefined;
+ // `;base64,` is a substantially narrower and cheaper precondition than
+ // `data:`. Most ordinary strings therefore avoid the full Data URI scan.
+ if (value.includes(BASE64_MARKER)) {
+ dataUriResult = await replaceDataUris(value, params);
+ valueToParse = dataUriResult.value;
+ }
+
+ const strippedValue = valueToParse.trimStart();
+ if (
+ (!strippedValue.startsWith("{") && !strippedValue.startsWith("[")) ||
+ !mayContainSerializedMedia(valueToParse)
+ ) {
+ return dataUriResult ?? { value, bytesRemoved: 0 };
+ }
+
+ params.onDetectionPath(
+ "stringified_json",
+ Buffer.byteLength(valueToParse, "utf8"),
+ );
+ let parsedValue: unknown;
+ try {
+ parsedValue = JSON.parse(valueToParse);
+ } catch {
+ return dataUriResult ?? { value, bytesRemoved: 0 };
+ }
+
+ if (!isObject(parsedValue) && !Array.isArray(parsedValue)) {
+ return dataUriResult ?? { value, bytesRemoved: 0 };
+ }
+
+ const state = await transformStructuredValue(parsedValue, params, false);
+ if (!state.changed) return dataUriResult ?? { value, bytesRemoved: 0 };
+
+ const transformedValue = JSON.stringify(parsedValue);
+ return {
+ value: transformedValue,
+ bytesRemoved: Math.max(
+ 0,
+ Buffer.byteLength(value, "utf8") -
+ Buffer.byteLength(transformedValue, "utf8"),
+ ),
+ };
+}
+
+/**
+ * Replaces every successfully processed Data URI in a string while preserving
+ * invalid occurrences and all surrounding text. Does not mutate its input.
+ */
+async function replaceDataUris(
+ value: string,
+ params: TransformParams,
+): 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 };
+ }
+
+ let output = "";
+ let cursor = 0;
+ let bytesRemoved = 0;
+
+ 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");
+ output += original;
+ } else {
+ const resolvedReplacement = await params.processCandidate(
+ occurrence.candidate,
+ );
+ output += resolvedReplacement ?? original;
+ if (resolvedReplacement) {
+ bytesRemoved += Math.max(
+ 0,
+ Buffer.byteLength(original, "utf8") -
+ Buffer.byteLength(resolvedReplacement, "utf8"),
+ );
+ }
+ }
+ cursor = occurrence.end;
+ }
+
+ return { value: output + value.slice(cursor), bytesRemoved };
+}
+
+/**
+ * Locates Data URIs with a forward-only scanner. The cursor never moves
+ * backwards, keeping adversarial inputs linear rather than relying on a large
+ * backtracking regular expression.
+ */
+function findDataUris(value: string): DataUriOccurrence[] {
+ const occurrences: DataUriOccurrence[] = [];
+ let cursor = 0;
+
+ while (cursor < value.length) {
+ let start = value.indexOf(DATA_URI_PREFIX, cursor);
+ if (start === -1) break;
+
+ 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;
+ continue;
+ }
+ const code = value.charCodeAt(headerCursor);
+ if (code === 44) break;
+ if (code === 59) {
+ contentTypeEnd ??= headerCursor;
+ if (value.startsWith(BASE64_MARKER, headerCursor)) {
+ markerStart = headerCursor;
+ break;
+ }
+ }
+ headerCursor += 1;
+ }
+
+ if (markerStart === undefined) {
+ if (headerCursor === value.length) break;
+ cursor = headerCursor + 1;
+ continue;
+ }
+
+ const dataStart = markerStart + BASE64_MARKER.length;
+ let end = dataStart;
+ let padding = 0;
+ let valid = true;
+ while (end < value.length && isBase64Character(value.charCodeAt(end))) {
+ const code = value.charCodeAt(end);
+ if (code === 61) {
+ padding += 1;
+ if (padding > 2) valid = false;
+ } else if (padding > 0) {
+ valid = false;
+ }
+ 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)
+ ? {
+ base64Data,
+ contentType,
+ kind: "data_uri",
+ source: "base64_data_uri",
+ }
+ : undefined,
+ });
+ cursor = Math.max(end, dataStart);
+ }
+
+ return occurrences;
+}
+
+/**
+ * Traverses a structured payload and mutates it in place for every successful
+ * media replacement. Candidate operations run sequentially after discovery to
+ * keep traversal stable and peak decoded-media memory bounded.
+ */
+async function transformStructuredValue(
+ value: Record<string, unknown> | unknown[],
+ params: TransformParams,
+ recordStructuredPath: boolean,
+): Promise<TransformState> {
+ const state: TransformState = {
+ changed: false,
+ bytesRemoved: 0,
+ checkedBytes: 0,
+ };
+ // Discover candidates before mutating the tree. This keeps traversal stable
+ // even when a successful operation replaces a node that was just inspected.
+ const operations: Array<() => Promise<void>> = [];
+ const root: Record<string, unknown> = { value };
+ // Use an explicit stack and depth limit so deeply nested user payloads cannot
+ // exhaust the JavaScript call stack.
+ const stack: TraversalNode[] = [
+ { value, depth: 1, parent: root, key: "value" },
+ ];
+
+ while (stack.length > 0) {
+ const node = stack.pop();
+ if (!node || node.depth > MAX_RECURSION_DEPTH) continue;
+
+ if (typeof node.value === "string") {
+ state.checkedBytes += Buffer.byteLength(node.value, "utf8");
+ if (node.value.includes(BASE64_MARKER)) {
+ operations.push(async () => {
+ const transformed = await replaceDataUris(
+ node.value as string,
+ params,
+ );
+ if (transformed.value !== node.value) {
+ setTraversalValue(node, transformed.value);
+ state.changed = true;
+ state.bytesRemoved += transformed.bytesRemoved;
+ }
+ });
+ }
+ continue;
+ }
+
+ if (Array.isArray(node.value)) {
+ for (let index = node.value.length - 1; index >= 0; index -= 1) {
+ stack.push({
+ value: node.value[index],
+ depth: node.depth + 1,
+ parent: node.value,
+ key: index,
+ });
+ }
+ continue;
+ }
+ if (!isObject(node.value)) continue;
+
+ const structuredMedia = matchStructuredMedia(node.value);
+ if (structuredMedia) {
+ state.checkedBytes += Buffer.byteLength(structuredMedia.content, "utf8");
+ operations.push(async () => {
+ const bytesRemoved = await replaceStructuredMedia(
+ structuredMedia,
+ params,
+ );
+ if (bytesRemoved !== undefined) {
+ state.changed = true;
+ state.bytesRemoved += bytesRemoved;
+ }
+ });
+ continue;
+ }
+
+ const entries = Object.entries(node.value);
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
+ const [key, nestedValue] = entries[index]!;
+ stack.push({
+ value: nestedValue,
+ depth: node.depth + 1,
+ parent: node.value,
+ key,
+ });
+ }
+ }
+
+ if (recordStructuredPath) {
+ params.onDetectionPath("structured_payload", state.checkedBytes);
+ }
+ for (const operation of operations) await operation();
+ return state;
+}
+
+function setTraversalValue(node: TraversalNode, value: unknown): void {
+ defineOwnValue(node.parent, node.key, value);
+}
+
+function defineOwnValue(
+ target: object,
+ property: PropertyKey,
+ value: unknown,
+): void {
+ // Avoid invoking user-controlled setters such as an own `__proto__` setter
+ // when replacing values inside parsed or SDK-provided payloads.
+ Object.defineProperty(target, property, {
+ configurable: true,
+ enumerable: true,
+ value,
+ writable: true,
+ });
+}
+
+function matchStructuredMedia(
+ value: Record<string, unknown>,
+): StructuredMedia | undefined {
+ for (const shape of STRUCTURED_MEDIA_SHAPES) {
+ const contentType = value[shape.contentType];
+ const content = value[shape.property];
+ if (
+ value.type === shape.type &&
+ typeof contentType === "string" &&
+ typeof content === "string"
+ ) {
+ return {
+ target: value,
+ property: shape.property,
+ content,
+ contentType,
+ kind: shape.kind,
+ };
+ }
+ }
+
+ if (value.type === "file" && typeof value.mediaType === "string") {
+ const property =
+ typeof value.data === "string"
+ ? "data"
+ : typeof value.image === "string"
+ ? "image"
+ : undefined;
+ if (property) {
+ return {
+ target: value,
+ property,
+ content: value[property] as string,
+ contentType: value.mediaType,
+ kind: "ai_sdk_v6",
+ };
+ }
+ }
+
+ for (const inlineDataKey of ["inline_data", "inlineData"] as const) {
+ const inlineData = value[inlineDataKey];
+ if (!isObject(inlineData) || typeof inlineData.data !== "string") continue;
+ const contentType = inlineData.mime_type ?? inlineData.mimeType;
+ if (typeof contentType === "string") {
+ return {
+ target: inlineData,
+ property: "data",
+ content: inlineData.data,
+ contentType,
+ kind: "gemini",
+ };
+ }
+ }
+}
+
+/**
+ * Processes one recognized provider media object and mutates its media property
+ * in place only when the candidate resolves to a media reference.
+ */
+async function replaceStructuredMedia(
+ media: StructuredMedia,
+ params: TransformParams,
+): Promise<number | undefined> {
+ if (isMediaReference(media.content) || isRemoteUrl(media.content)) return;
+
+ const candidate = parseRawBase64(media);
+ if (!candidate) {
+ params.onInvalidCandidate(media.kind);
+ return;
+ }
+
+ const replacement = await params.processCandidate(candidate);
+ if (replacement) {
+ defineOwnValue(media.target, media.property, replacement);
+ return Math.max(
+ 0,
+ Buffer.byteLength(media.content, "utf8") -
+ Buffer.byteLength(replacement, "utf8"),
+ );
+ }
+}
+
+function parseRawBase64(
+ media: StructuredMedia,
+): MediaPayloadCandidate | undefined {
+ if (!isMediaContentType(media.contentType)) return;
+
+ if (media.content.startsWith(DATA_URI_PREFIX)) {
+ const occurrences = findDataUris(media.content);
+ const candidate =
+ occurrences.length === 1 &&
+ occurrences[0]?.start === 0 &&
+ occurrences[0]?.end === media.content.length
+ ? occurrences[0].candidate
+ : undefined;
+ return candidate
+ ? {
+ ...candidate,
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ }
+ : undefined;
+ }
+
+ return isValidBase64(media.content)
+ ? {
+ base64Data: media.content,
+ contentType: media.contentType,
+ kind: media.kind,
+ source: "bytes",
+ }
+ : undefined;
+}
+
+/**
+ * Cheaply requires a complete provider-specific key combination before the
+ * more expensive JSON.parse and structured traversal. A common `data` key by
+ * itself is deliberately insufficient.
+ */
+function mayContainSerializedMedia(value: string): boolean {
+ const hasData = value.includes('"data"');
+ const hasMimeType = value.includes('"mime_type"');
+ const hasProviderShapeKeys =
+ (hasData && (value.includes('"media_type"') || hasMimeType)) ||
+ (value.includes('"content"') && hasMimeType) ||
+ ((hasData || value.includes('"image"')) && value.includes('"mediaType"'));
+
+ return (
+ (hasProviderShapeKeys && SERIALIZED_PROVIDER_MEDIA_TYPE.test(value)) ||
+ (hasData &&
+ (value.includes('"inline_data"') || value.includes('"inlineData"')) &&
+ (hasMimeType || value.includes('"mimeType"')))
+ );
+}
+
+function isMediaReference(value: string): boolean {
+ return (
+ value.startsWith(MEDIA_REFERENCE_PREFIX) &&
+ value.endsWith(MEDIA_REFERENCE_SUFFIX)
+ );
+}
+
+function isRemoteUrl(value: string): boolean {
+ return value.startsWith("http://") || value.startsWith("https://");
+}
+
+function isValidBase64(value: string): boolean {
+ if (value.length === 0 || value.length % 4 === 1) return false;
+
+ let padding = 0;
+ for (let index = 0; index < value.length; index += 1) {
+ const code = value.charCodeAt(index);
+ if (code === 61) {
+ padding += 1;
+ if (padding > 2) return false;
+ } else if (padding > 0 || !isBase64Character(code, false)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function isBase64Character(code: number, allowPadding = true): boolean {
+ return (
+ (code >= 65 && code <= 90) ||
+ (code >= 97 && code <= 122) ||
+ (code >= 48 && code <= 57) ||
+ code === 43 ||
+ code === 47 ||
+ (allowPadding && code === 61)
+ );
+}
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/shared/src/server/media/index.ts b/packages/shared/src/server/media/index.ts
new file mode 100644
index 0000000000..ee664b5da8
--- /dev/null
+++ b/packages/shared/src/server/media/index.ts
@@ -0,0 +1,2 @@
+export * from "./MediaPayloadProcessor";
+export * from "./mediaService";
diff --git a/packages/shared/src/server/media/mediaService.test.ts b/packages/shared/src/server/media/mediaService.test.ts
new file mode 100644
index 0000000000..926bdec448
--- /dev/null
+++ b/packages/shared/src/server/media/mediaService.test.ts
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ executeRaw: vi.fn(),
+ queryRaw: vi.fn(),
+ findUnique: vi.fn(),
+ updateMany: vi.fn(),
+ update: vi.fn(),
+ uploadFile: vi.fn(),
+}));
+
+vi.mock("../../db", () => ({
+ Prisma: { PrismaClientKnownRequestError: class extends Error {} },
+ prisma: {
+ $executeRaw: mocks.executeRaw,
+ $queryRaw: mocks.queryRaw,
+ media: {
+ findUnique: mocks.findUnique,
+ updateMany: mocks.updateMany,
+ update: mocks.update,
+ },
+ },
+}));
+vi.mock("../instrumentation", () => ({
+ recordHistogram: vi.fn(),
+ recordIncrement: vi.fn(),
+}));
+vi.mock("../s3", () => ({
+ getS3MediaStorageClient: vi.fn(() => ({ uploadFile: mocks.uploadFile })),
+}));
+
+import { MediaContentType } from "../../domain/media";
+import { recordHistogram, recordIncrement } from "../instrumentation";
+import { uploadMediaForTrace } from "./mediaService";
+
+const CONTENT_BYTES = Buffer.from("test-image");
+
+describe("uploadMediaForTrace", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("creates, links, and uploads a new media asset", async () => {
+ mocks.findUnique.mockResolvedValue(null);
+ mocks.updateMany.mockResolvedValue({ count: 1 });
+ mocks.update.mockResolvedValue({});
+ mocks.uploadFile.mockResolvedValue(undefined);
+
+ const result = await uploadMediaForTrace({
+ projectId: "project-id",
+ traceId: "trace-id",
+ observationId: "observation-id",
+ field: "input",
+ contentType: MediaContentType.PNG,
+ contentBytes: CONTENT_BYTES,
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ });
+
+ expect(result).toEqual({
+ mediaId: "n-vgG9Qb-2loPinXEdit_8",
+ outcome: "uploaded",
+ });
+ expect(mocks.executeRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.queryRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: "media/project-id/n-vgG9Qb-2loPinXEdit_8.png",
+ fileType: "image/png",
+ }),
+ );
+ expect(mocks.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: {
+ projectId_id: {
+ projectId: "project-id",
+ id: "n-vgG9Qb-2loPinXEdit_8",
+ },
+ },
+ data: expect.objectContaining({ uploadHttpStatus: 200 }),
+ }),
+ );
+ expect(mocks.uploadFile.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.update.mock.invocationCallOrder[0]!,
+ );
+ expect(mocks.update.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.queryRaw.mock.invocationCallOrder[0]!,
+ );
+ });
+
+ it("does not link media and records storage metrics when upload fails", async () => {
+ const uploadError = Object.assign(new Error("S3 unavailable"), {
+ $metadata: { httpStatusCode: 503 },
+ });
+ mocks.findUnique.mockResolvedValue(null);
+ mocks.updateMany.mockResolvedValue({ count: 1 });
+ mocks.uploadFile.mockRejectedValue(uploadError);
+
+ await expect(
+ uploadMediaForTrace({
+ projectId: "project-id",
+ traceId: "trace-id",
+ observationId: "observation-id",
+ field: "input",
+ contentType: MediaContentType.PNG,
+ contentBytes: CONTENT_BYTES,
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ }),
+ ).rejects.toBe(uploadError);
+
+ expect(mocks.queryRaw).not.toHaveBeenCalled();
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.media.upload_http_status",
+ 1,
+ { status_code: 503 },
+ );
+ expect(recordHistogram).toHaveBeenCalledWith(
+ "langfuse.media.upload_time_ms",
+ expect.any(Number),
+ { status_code: 503 },
+ );
+ });
+
+ it("links but does not re-upload an existing asset", async () => {
+ mocks.findUnique.mockResolvedValue({
+ id: "existing-media-id",
+ uploadHttpStatus: 200,
+ contentType: MediaContentType.PNG,
+ });
+
+ const result = await uploadMediaForTrace({
+ projectId: "project-id",
+ traceId: "trace-id",
+ observationId: "observation-id",
+ field: "output",
+ contentType: MediaContentType.PNG,
+ contentBytes: CONTENT_BYTES,
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ });
+
+ expect(result).toEqual({
+ mediaId: "existing-media-id",
+ outcome: "reused",
+ });
+ expect(mocks.queryRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.executeRaw).not.toHaveBeenCalled();
+ expect(mocks.uploadFile).not.toHaveBeenCalled();
+ });
+
+ it("links trace media when no observation id is provided", async () => {
+ mocks.findUnique.mockResolvedValue({
+ id: "existing-media-id",
+ uploadHttpStatus: 200,
+ contentType: MediaContentType.PNG,
+ });
+
+ await uploadMediaForTrace({
+ projectId: "project-id",
+ traceId: "trace-id",
+ field: "input",
+ contentType: MediaContentType.PNG,
+ contentBytes: CONTENT_BYTES,
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ });
+
+ const query = mocks.queryRaw.mock.calls[0]?.[0] as TemplateStringsArray;
+ expect(query.join(" ")).toContain('INSERT INTO "trace_media"');
+ });
+});
diff --git a/packages/shared/src/server/media/mediaService.ts b/packages/shared/src/server/media/mediaService.ts
new file mode 100644
index 0000000000..159f65b586
--- /dev/null
+++ b/packages/shared/src/server/media/mediaService.ts
@@ -0,0 +1,303 @@
+import { createHash, randomUUID } from "crypto";
+import { Readable } from "stream";
+
+import { Prisma, prisma } from "../../db";
+import {
+ getFileExtensionFromContentType,
+ type MediaContentType,
+ type MediaField,
+} from "../../domain/media";
+import { InternalServerError } from "../../errors";
+import { recordHistogram, recordIncrement } from "../instrumentation";
+import { getS3MediaStorageClient } from "../s3";
+import { summarizeS3Error } from "../services/s3SigningDiagnostics";
+
+/** Derives the stable, URL-safe public media ID from a full SHA-256 hash. */
+export function getMediaId(sha256Hash: string): string {
+ const urlSafeHash = sha256Hash.replaceAll("+", "-").replaceAll("/", "_");
+
+ return urlSafeHash.slice(0, 22);
+}
+
+/** Builds the project-scoped object key used in the configured media bucket. */
+export function getMediaBucketPath(params: {
+ projectId: string;
+ mediaId: string;
+ contentType: MediaContentType;
+ prefix: string;
+}): string {
+ const { projectId, mediaId, contentType, prefix } = params;
+ const fileExtension = getFileExtensionFromContentType(contentType);
+
+ return `${prefix}${projectId}/${mediaId}.${fileExtension}`;
+}
+
+/**
+ * Creates or refreshes a media row while guarding against truncated media-ID
+ * collisions. This mutates database state but does not upload or link media.
+ */
+export async function upsertMediaRecord(params: {
+ mediaId: string;
+ projectId: string;
+ sha256Hash: string;
+ bucketPath: string;
+ uploadBucket: string;
+ contentType: MediaContentType;
+ contentLength: number;
+}): Promise<void> {
+ const {
+ mediaId,
+ projectId,
+ sha256Hash,
+ bucketPath,
+ uploadBucket,
+ contentType,
+ contentLength,
+ } = params;
+
+ // Media has unique constraints for both the public ID and full hash. Absorb
+ // either concurrent insert conflict, then prove both values match before
+ // reusing the row so a truncated-ID collision can never cross-link content.
+ await prisma.$executeRaw`
+ INSERT INTO "media" (
+ "id",
+ "project_id",
+ "sha_256_hash",
+ "bucket_path",
+ "bucket_name",
+ "content_type",
+ "content_length"
+ )
+ VALUES (
+ ${mediaId},
+ ${projectId},
+ ${sha256Hash},
+ ${bucketPath},
+ ${uploadBucket},
+ ${contentType},
+ ${contentLength}
+ )
+ ON CONFLICT DO NOTHING
+ `;
+
+ const result = await prisma.media.updateMany({
+ where: {
+ projectId,
+ id: mediaId,
+ sha256Hash,
+ },
+ data: {
+ bucketName: uploadBucket,
+ bucketPath,
+ contentType,
+ contentLength: BigInt(contentLength),
+ },
+ });
+
+ if (result.count === 0) {
+ throw new InternalServerError(
+ `Media ID collision detected for media ID ${mediaId} in project ${projectId}. The existing media row has a different id or sha_256_hash.`,
+ );
+ }
+}
+
+/**
+ * Idempotently links an uploaded media row to either an observation or trace.
+ * An `observationId` selects `observation_media`; otherwise `trace_media` is
+ * used. This mutates database state only.
+ */
+export async function linkMediaToTraceOrObservation(params: {
+ projectId: string;
+ traceId: string;
+ observationId?: string | null;
+ mediaId: string;
+ field: string;
+}): Promise<void> {
+ const { projectId, traceId, observationId, mediaId, field } = params;
+
+ if (observationId) {
+ await prisma.$queryRaw`
+ INSERT INTO "observation_media" (
+ "id",
+ "project_id",
+ "trace_id",
+ "observation_id",
+ "media_id",
+ "field"
+ )
+ VALUES (
+ ${randomUUID()},
+ ${projectId},
+ ${traceId},
+ ${observationId},
+ ${mediaId},
+ ${field}
+ )
+ ON CONFLICT DO NOTHING
+ `;
+ return;
+ }
+
+ await prisma.$queryRaw`
+ INSERT INTO "trace_media" (
+ "id",
+ "project_id",
+ "trace_id",
+ "media_id",
+ "field"
+ )
+ VALUES (
+ ${randomUUID()},
+ ${projectId},
+ ${traceId},
+ ${mediaId},
+ ${field}
+ )
+ ON CONFLICT DO NOTHING
+ `;
+}
+
+export type UploadMediaForTraceResult = {
+ /** Stable ID referenced from normalized input, output, or metadata. */
+ mediaId: string;
+ /** Whether this call uploaded new bytes or reused an uploaded media row. */
+ outcome: "uploaded" | "reused";
+};
+
+/**
+ * Persists binary media and links it to a trace or observation.
+ *
+ * Content is deduplicated per project by its full SHA-256 hash. For new media,
+ * the link is created only after S3 upload and the media row's upload status
+ * are confirmed, preventing failed uploads from leaving dangling links. This
+ * function mutates PostgreSQL and media storage; it does not mutate its input
+ * parameters or the caller's normalized OTEL payload.
+ */
+export async function uploadMediaForTrace(params: {
+ projectId: string;
+ traceId: string;
+ observationId?: string;
+ field: MediaField;
+ contentType: MediaContentType;
+ contentBytes: Buffer;
+ mediaBucket: string;
+ mediaPrefix: string;
+}): Promise<UploadMediaForTraceResult> {
+ const {
+ projectId,
+ traceId,
+ observationId,
+ field,
+ contentType,
+ contentBytes,
+ mediaBucket,
+ mediaPrefix,
+ } = params;
+ const sha256Hash = createHash("sha256").update(contentBytes).digest("base64");
+ const mediaId = getMediaId(sha256Hash);
+ const existingMedia = await prisma.media.findUnique({
+ where: {
+ projectId_sha256Hash: {
+ projectId,
+ sha256Hash,
+ },
+ },
+ });
+
+ if (
+ existingMedia &&
+ (existingMedia.uploadHttpStatus === 200 ||
+ existingMedia.uploadHttpStatus === 201) &&
+ existingMedia.contentType === contentType
+ ) {
+ await linkMediaToTraceOrObservation({
+ projectId,
+ traceId,
+ observationId,
+ mediaId: existingMedia.id,
+ field,
+ });
+ return { mediaId: existingMedia.id, outcome: "reused" };
+ }
+
+ const bucketPath = getMediaBucketPath({
+ projectId,
+ mediaId,
+ contentType,
+ prefix: mediaPrefix,
+ });
+
+ await upsertMediaRecord({
+ mediaId,
+ projectId,
+ sha256Hash,
+ bucketPath,
+ uploadBucket: mediaBucket,
+ contentType,
+ contentLength: contentBytes.length,
+ });
+
+ const uploadStartedAt = Date.now();
+ try {
+ await getS3MediaStorageClient(mediaBucket).uploadFile({
+ fileName: bucketPath,
+ fileType: contentType,
+ data: Readable.from([contentBytes]),
+ });
+ } catch (error) {
+ const statusCode = summarizeS3Error(error).httpStatusCode ?? 500;
+ recordIncrement("langfuse.media.upload_http_status", 1, {
+ status_code: statusCode,
+ });
+ recordHistogram(
+ "langfuse.media.upload_time_ms",
+ Date.now() - uploadStartedAt,
+ { status_code: statusCode },
+ );
+ throw error;
+ }
+ const uploadTimeMs = Date.now() - uploadStartedAt;
+
+ try {
+ await prisma.media.update({
+ where: {
+ projectId_id: {
+ projectId,
+ id: mediaId,
+ },
+ },
+ data: {
+ uploadedAt: new Date(),
+ uploadHttpStatus: 200,
+ uploadHttpError: null,
+ },
+ });
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ throw new InternalServerError(
+ `Media asset ${mediaId} not found after server-side upload`,
+ );
+ }
+ throw error;
+ }
+
+ await linkMediaToTraceOrObservation({
+ projectId,
+ traceId,
+ observationId,
+ mediaId,
+ field,
+ });
+
+ recordIncrement("langfuse.media.upload_http_status", 1, {
+ status_code: 200,
+ });
+ recordHistogram("langfuse.media.upload_time_ms", uploadTimeMs, {
+ status_code: 200,
+ });
+
+ return { mediaId, outcome: "uploaded" };
+}
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.test.ts b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
new file mode 100644
index 0000000000..70b3675804
--- /dev/null
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.test.ts
@@ -0,0 +1,242 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("../instrumentation", () => ({
+ recordDistribution: vi.fn(),
+ recordIncrement: vi.fn(),
+}));
+vi.mock("../logger", () => ({
+ logger: { warn: vi.fn() },
+}));
+
+import type { MediaField } from "../../domain/media";
+import { recordDistribution, recordIncrement } from "../instrumentation";
+import {
+ processOtelMedia,
+ type OtelMediaEvent,
+ type UploadOtelMedia,
+} from "./OtelMediaProcessor";
+
+const TRACE_ID = "0123456789abcdef0123456789abcdef";
+const SPAN_ID = "0123456789abcdef";
+const MEDIA_ID = "test-media-id";
+const PNG_BYTES = Buffer.from("test-image");
+const PNG_BASE64 = PNG_BYTES.toString("base64");
+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;
+} {
+ const body: OtelMediaEvent = {
+ traceId: TRACE_ID,
+ spanId: SPAN_ID,
+ [params.field ?? "input"]: params.value,
+ };
+ return { event: body, body };
+}
+
+function createUploadMock(
+ outcome: "uploaded" | "reused" = "uploaded",
+): UploadOtelMedia {
+ return vi.fn().mockResolvedValue({ mediaId: MEDIA_ID, outcome });
+}
+
+async function processEvents(
+ events: OtelMediaEvent[],
+ uploadMedia: UploadOtelMedia = createUploadMock(),
+) {
+ return processOtelMedia({
+ events,
+ projectId: "project-id",
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ uploadMedia,
+ });
+}
+
+describe("processOtelMedia", () => {
+ it("uploads a normalized observation Data URI and replaces it after success", async () => {
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const { event, body } = createEvent({ value: dataUri });
+ const uploadMedia = createUploadMock();
+
+ const result = await processEvents([event], uploadMedia);
+
+ expect(uploadMedia).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId: "project-id",
+ traceId: TRACE_ID,
+ observationId: SPAN_ID,
+ field: "input",
+ contentType: "image/png",
+ contentBytes: PNG_BYTES,
+ }),
+ );
+ expect(body.input).toBe(MEDIA_REFERENCE);
+ expect(recordIncrement).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.detection_check",
+ 1,
+ { path: "data_uri" },
+ );
+ expect(recordDistribution).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.detection_check_byte_length",
+ Buffer.byteLength(dataUri, "utf8"),
+ { path: "data_uri" },
+ );
+ expect(result).toMatchObject({
+ candidates: 1,
+ bytesProcessed: PNG_BYTES.length,
+ detectionChecks: {
+ data_uri: 1,
+ stringified_json: 0,
+ structured_payload: 0,
+ },
+ detectionCheckedBytes: {
+ data_uri: Buffer.byteLength(dataUri, "utf8"),
+ stringified_json: 0,
+ structured_payload: 0,
+ },
+ });
+ });
+
+ 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 },
+ unrelated: dataUri,
+ };
+ const uploadMedia = createUploadMock();
+
+ await processEvents([body], uploadMedia);
+
+ expect(uploadMedia).toHaveBeenCalledTimes(3);
+ expect(uploadMedia).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ field: "input" }),
+ );
+ expect(uploadMedia).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ field: "output" }),
+ );
+ expect(uploadMedia).toHaveBeenNthCalledWith(
+ 3,
+ expect.objectContaining({ field: "metadata" }),
+ );
+ expect(body).toMatchObject({
+ input: MEDIA_REFERENCE,
+ output: MEDIA_REFERENCE,
+ metadata: { image: MEDIA_REFERENCE },
+ unrelated: dataUri,
+ });
+ });
+
+ it("replaces an embedded Data URI in a normalized string", async () => {
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const { event, body } = createEvent({ value: `image: ${dataUri}` });
+
+ await processEvents([event]);
+
+ expect(body.input).toBe(`image: ${MEDIA_REFERENCE}`);
+ });
+
+ it.each([
+ [
+ "anthropic",
+ { type: "base64", media_type: "image/png", data: PNG_BASE64 },
+ "data",
+ ],
+ [
+ "vertex",
+ { type: "media", mime_type: "image/png", data: PNG_BASE64 },
+ "data",
+ ],
+ [
+ "gemini",
+ { inline_data: { mime_type: "image/png", data: PNG_BASE64 } },
+ "inline_data.data",
+ ],
+ [
+ "ai_sdk_v6",
+ { type: "file", mediaType: "image/png", data: PNG_BASE64 },
+ "data",
+ ],
+ [
+ "ai_sdk_v7",
+ { type: "blob", mime_type: "image/png", content: PNG_BASE64 },
+ "content",
+ ],
+ ])(
+ "processes %s media in normalized structured values",
+ async (_, mediaValue, referencePath) => {
+ const value = [structuredClone(mediaValue)];
+ const { event } = createEvent({ value });
+ const uploadMedia = createUploadMock();
+
+ const result = await processEvents([event], uploadMedia);
+
+ const reference = referencePath
+ .split(".")
+ .reduce((nested, key) => nested[key], value[0] as any) as string;
+ expect(reference).toBe(
+ `@@@langfuseMedia:type=image/png|id=${MEDIA_ID}|source=bytes@@@`,
+ );
+ expect(uploadMedia).toHaveBeenCalledTimes(1);
+ expect(result.detectionChecks.structured_payload).toBe(1);
+ },
+ );
+
+ it("processes shape-based media in stringified JSON", async () => {
+ const { event, body } = createEvent({
+ value: JSON.stringify([
+ { type: "base64", media_type: "image/png", data: PNG_BASE64 },
+ ]),
+ });
+
+ const result = await processEvents([event]);
+
+ expect(JSON.parse(body.input as string)[0].data).toBe(
+ `@@@langfuseMedia:type=image/png|id=${MEDIA_ID}|source=bytes@@@`,
+ );
+ expect(result.detectionChecks.stringified_json).toBe(1);
+ });
+
+ it("leaves normalized values unchanged when upload fails", async () => {
+ const dataUri = `data:image/png;base64,${PNG_BASE64}`;
+ const { event, body } = createEvent({ value: dataUri });
+ const uploadMedia = vi.fn().mockRejectedValue(new Error("upload failed"));
+
+ await processEvents([event], uploadMedia);
+
+ expect(body.input).toBe(dataUri);
+ });
+
+ it("ignores existing media references", async () => {
+ const reference =
+ "@@@langfuseMedia:type=image/png|id=existing|source=bytes@@@";
+ const { event, body } = createEvent({ value: reference });
+ const uploadMedia = createUploadMock();
+
+ await processEvents([event], uploadMedia);
+
+ expect(uploadMedia).not.toHaveBeenCalled();
+ 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) => {
+ 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(1);
+ });
+});
diff --git a/packages/shared/src/server/otel/OtelMediaProcessor.ts b/packages/shared/src/server/otel/OtelMediaProcessor.ts
new file mode 100644
index 0000000000..6605d37d89
--- /dev/null
+++ b/packages/shared/src/server/otel/OtelMediaProcessor.ts
@@ -0,0 +1,246 @@
+import type { MediaContentType, MediaField } from "../../domain/media";
+import { recordDistribution, recordIncrement } from "../instrumentation";
+import { logger } from "../logger";
+import {
+ transformMediaPayload,
+ type MediaDetectionPath,
+ type MediaPayloadCandidate,
+ type MediaPayloadKind,
+} from "../media/MediaPayloadProcessor";
+import type { UploadMediaForTraceResult } from "../media/mediaService";
+
+export type OtelMediaKind = MediaPayloadKind;
+
+/** A normalized OTEL observation destined for direct events-table storage. */
+export type OtelMediaEvent = {
+ traceId: string;
+ spanId: string;
+ input?: unknown;
+ output?: unknown;
+ metadata?: unknown;
+};
+
+export type UploadOtelMedia = (params: {
+ projectId: string;
+ traceId: string;
+ observationId: string;
+ field: MediaField;
+ contentType: MediaContentType;
+ contentBytes: Buffer;
+ mediaBucket: string;
+ mediaPrefix: string;
+}) => Promise<UploadMediaForTraceResult>;
+
+/** Aggregate outcome and workload counters for one OTEL media-processing run. */
+export type OtelMediaProcessResult = {
+ /** Candidates newly uploaded to media storage. */
+ 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. */
+ invalid: number;
+ /** Valid candidates whose upload or media-link operation failed. */
+ failed: number;
+ /**
+ * UTF-8 byte difference between original and transformed values. For
+ * stringified JSON this also includes whitespace removed by reserialization.
+ */
+ bytesRemoved: number;
+ /** Valid, non-empty candidates decoded and submitted to the upload service. */
+ candidates: number;
+ /** Total decoded binary bytes across all valid candidates. */
+ bytesProcessed: number;
+ /** Number of times each detection algorithm was entered. */
+ detectionChecks: Record<MediaDetectionPath, number>;
+ /**
+ * UTF-8 bytes inspected by each detection algorithm. The same source bytes
+ * may be counted under multiple paths, for example Data URI replacement
+ * followed by stringified-JSON processing.
+ */
+ detectionCheckedBytes: Record<MediaDetectionPath, number>;
+};
+
+type ProcessContext = {
+ projectId: string;
+ traceId: string;
+ observationId: string;
+ field: MediaField;
+ mediaBucket: string;
+ mediaPrefix: string;
+ uploadMedia: UploadOtelMedia;
+ result: OtelMediaProcessResult;
+};
+
+/**
+ * Detects and uploads embedded media for normalized OTEL events that are
+ * destined for direct persistence in the events table.
+ *
+ * Events, fields, and candidates are processed sequentially to bound peak
+ * decoded media memory. Successful replacements mutate each event in place.
+ * Invalid values and failed uploads are left unchanged; their outcomes are
+ * reflected in the returned counters instead of failing the whole run.
+ */
+export async function processOtelMedia(params: {
+ events: OtelMediaEvent[];
+ projectId: string;
+ mediaBucket: string;
+ mediaPrefix: string;
+ uploadMedia: UploadOtelMedia;
+}): Promise<OtelMediaProcessResult> {
+ const { events, projectId, mediaBucket, mediaPrefix, uploadMedia } = params;
+ const result: OtelMediaProcessResult = {
+ uploaded: 0,
+ reused: 0,
+ invalid: 0,
+ failed: 0,
+ bytesRemoved: 0,
+ candidates: 0,
+ bytesProcessed: 0,
+ detectionChecks: {
+ data_uri: 0,
+ stringified_json: 0,
+ structured_payload: 0,
+ },
+ detectionCheckedBytes: {
+ data_uri: 0,
+ stringified_json: 0,
+ structured_payload: 0,
+ },
+ };
+ for (const event of events) {
+ for (const field of ["input", "output", "metadata"] as const) {
+ const originalValue = event[field];
+ if (originalValue == null) continue;
+
+ const context: ProcessContext = {
+ projectId,
+ traceId: event.traceId,
+ observationId: event.spanId,
+ field,
+ mediaBucket,
+ mediaPrefix,
+ uploadMedia,
+ result,
+ };
+ const transformed = await transformMediaPayload(originalValue, {
+ processCandidate: (candidate) => processCandidate(candidate, context),
+ onInvalidCandidate: (kind) => recordInvalidCandidate(kind, context),
+ onDetectionPath: (path, checkedBytes) =>
+ recordDetectionCheck(path, checkedBytes, context),
+ });
+
+ // 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;
+ }
+ if (transformed.bytesRemoved > 0) {
+ result.bytesRemoved += transformed.bytesRemoved;
+ recordDistribution(
+ "langfuse.ingestion.otel.media.bytes_removed",
+ transformed.bytesRemoved,
+ );
+ }
+ }
+ }
+
+ return result;
+}
+
+async function processCandidate(
+ candidate: MediaPayloadCandidate,
+ context: ProcessContext,
+): Promise<string | undefined> {
+ // Base64 decoding and hashing are synchronous and may be expensive for large
+ // media. Yield between candidates so a batch with many items does not hold
+ // the worker event loop continuously. Processing remains sequential to bound
+ // the number of decoded Buffers retained at once.
+ await new Promise<void>((resolve) => setImmediate(resolve));
+
+ let contentBytes: Buffer;
+ try {
+ contentBytes = Buffer.from(candidate.base64Data, "base64");
+ if (contentBytes.length === 0) {
+ recordInvalidCandidate(candidate.kind, context);
+ return;
+ }
+ } catch {
+ recordInvalidCandidate(candidate.kind, context);
+ return;
+ }
+
+ context.result.candidates += 1;
+ context.result.bytesProcessed += contentBytes.length;
+
+ try {
+ const uploadResult = await context.uploadMedia({
+ projectId: context.projectId,
+ traceId: context.traceId,
+ observationId: context.observationId,
+ field: context.field,
+ contentType: candidate.contentType,
+ contentBytes,
+ mediaBucket: context.mediaBucket,
+ mediaPrefix: context.mediaPrefix,
+ });
+
+ context.result[uploadResult.outcome] += 1;
+ recordIncrement("langfuse.ingestion.otel.media", 1, {
+ outcome: uploadResult.outcome,
+ media_kind: candidate.kind,
+ });
+ recordDistribution(
+ "langfuse.ingestion.otel.media.byte_length",
+ contentBytes.length,
+ { media_kind: candidate.kind },
+ );
+
+ return `@@@langfuseMedia:type=${candidate.contentType}|id=${uploadResult.mediaId}|source=${candidate.source}@@@`;
+ } catch (error) {
+ context.result.failed += 1;
+ recordIncrement("langfuse.ingestion.otel.media", 1, {
+ outcome: "failed",
+ media_kind: candidate.kind,
+ });
+ logger.warn(
+ "OTEL media upload failed; leaving normalized value unchanged",
+ {
+ projectId: context.projectId,
+ traceId: context.traceId,
+ observationId: context.observationId,
+ field: context.field,
+ mediaKind: candidate.kind,
+ mediaBytes: contentBytes.length,
+ error,
+ },
+ );
+ }
+}
+
+function recordDetectionCheck(
+ path: MediaDetectionPath,
+ checkedBytes: number,
+ context: ProcessContext,
+): void {
+ context.result.detectionChecks[path] += 1;
+ context.result.detectionCheckedBytes[path] += checkedBytes;
+ recordIncrement("langfuse.ingestion.otel.media.detection_check", 1, {
+ path,
+ });
+ recordDistribution(
+ "langfuse.ingestion.otel.media.detection_check_byte_length",
+ checkedBytes,
+ { path },
+ );
+}
+
+function recordInvalidCandidate(
+ kind: MediaPayloadKind,
+ context: ProcessContext,
+): void {
+ context.result.invalid += 1;
+ recordIncrement("langfuse.ingestion.otel.media", 1, {
+ outcome: "invalid",
+ media_kind: kind,
+ });
+}
diff --git a/packages/shared/src/server/otel/index.ts b/packages/shared/src/server/otel/index.ts
index bb5db04b40..92dae9b006 100644
--- a/packages/shared/src/server/otel/index.ts
+++ b/packages/shared/src/server/otel/index.ts
@@ -1,2 +1,3 @@
export * from "./OtelIngestionProcessor";
+export * from "./OtelMediaProcessor";
export * from "./internalTraceOtelWriter";
diff --git a/web/src/features/media/server/mediaService.ts b/web/src/features/media/server/mediaService.ts
index af308bac9b..2b270b8c15 100644
--- a/web/src/features/media/server/mediaService.ts
+++ b/web/src/features/media/server/mediaService.ts
@@ -1,13 +1,9 @@
-import { randomUUID } from "crypto";
-
import { env } from "@/src/env.mjs";
-import { getFileExtensionFromContentType } from "@/src/features/media/server/getFileExtensionFromContentType";
import { getMediaStorageServiceClient } from "@/src/features/media/server/getMediaStorageClient";
import {
GetMediaResponseSchema,
type GetMediaUploadUrlQuery,
GetMediaUploadUrlResponseSchema,
- type MediaContentType,
type PatchMediaBody,
} from "@/src/features/media/validation";
import {
@@ -18,10 +14,14 @@ import {
import { Prisma, prisma } from "@langfuse/shared/src/db";
import {
declarePendingDatasetItemMedia,
+ getMediaBucketPath,
+ getMediaId,
getCurrentSpan,
+ linkMediaToTraceOrObservation,
logger,
recordHistogram,
recordIncrement,
+ upsertMediaRecord,
} from "@langfuse/shared/src/server";
export async function createMediaUploadUrl(params: {
@@ -96,7 +96,12 @@ export async function createMediaUploadUrl(params: {
);
}
- const bucketPath = getBucketPath({ projectId, mediaId, contentType });
+ const bucketPath = getMediaBucketPath({
+ projectId,
+ mediaId,
+ contentType,
+ prefix: env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX ?? "",
+ });
const uploadUrl = await getMediaStorageServiceClient(
uploadBucket,
).getSignedUploadUrl({
@@ -216,114 +221,3 @@ export async function updateMediaUploadStatus(params: {
);
}
}
-
-async function upsertMediaRecord(params: {
- mediaId: string;
- projectId: string;
- sha256Hash: string;
- bucketPath: string;
- uploadBucket: string;
- contentType: MediaContentType;
- contentLength: number;
-}) {
- const {
- mediaId,
- projectId,
- sha256Hash,
- bucketPath,
- uploadBucket,
- contentType,
- contentLength,
- } = params;
-
- // Media has two unique constraints: (project_id, id) for the public mediaId
- // and (project_id, sha_256_hash) for content dedupe. Under concurrent uploads
- // of the same file, either unique index can observe the speculative insert
- // first. Omitting the conflict target makes DO NOTHING absorb conflicts from
- // both constraints; the guarded Prisma update below then proves that the
- // existing row has both the expected mediaId and full hash before reusing it.
- await prisma.$executeRaw`
- INSERT INTO "media" (
- "id",
- "project_id",
- "sha_256_hash",
- "bucket_path",
- "bucket_name",
- "content_type",
- "content_length"
- )
- VALUES (
- ${mediaId},
- ${projectId},
- ${sha256Hash},
- ${bucketPath},
- ${uploadBucket},
- ${contentType},
- ${contentLength}
- )
- ON CONFLICT DO NOTHING
- `;
-
- const result = await prisma.media.updateMany({
- where: {
- projectId,
- id: mediaId,
- sha256Hash,
- },
- data: {
- bucketName: uploadBucket,
- bucketPath,
- contentType,
- contentLength: BigInt(contentLength),
- },
- });
-
- if (result.count === 0) {
- throw new InternalServerError(
- `Media ID collision detected for media ID ${mediaId} in project ${projectId}. The existing media row has a different id or sha_256_hash.`,
- );
- }
-}
-
-async function linkMediaToTraceOrObservation(params: {
- projectId: string;
- traceId: string;
- observationId?: string | null;
- mediaId: string;
- field: string;
-}) {
- const { projectId, traceId, observationId, mediaId, field } = params;
-
- if (observationId) {
- await prisma.$queryRaw`
- INSERT INTO "observation_media" ("id", "project_id", "trace_id", "observation_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${observationId}, ${mediaId}, ${field})
- ON CONFLICT DO NOTHING;
- `;
- return;
- }
-
- await prisma.$queryRaw`
- INSERT INTO "trace_media" ("id", "project_id", "trace_id", "media_id", "field")
- VALUES (${randomUUID()}, ${projectId}, ${traceId}, ${mediaId}, ${field})
- ON CONFLICT DO NOTHING;
- `;
-}
-
-function getBucketPath(params: {
- projectId: string;
- mediaId: string;
- contentType: MediaContentType;
-}) {
- const { projectId, mediaId, contentType } = params;
- const prefix = env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX ?? "";
- const fileExtension = getFileExtensionFromContentType(contentType);
-
- return `${prefix}${projectId}/${mediaId}.${fileExtension}`;
-}
-
-function getMediaId(sha256Hash: string) {
- const urlSafeHash = sha256Hash.replaceAll("+", "-").replaceAll("/", "_");
-
- return urlSafeHash.slice(0, 22);
-}
diff --git a/web/src/features/media/validation.ts b/web/src/features/media/validation.ts
index 018aec7d4a..2a6aa5fb3d 100644
--- a/web/src/features/media/validation.ts
+++ b/web/src/features/media/validation.ts
@@ -1,6 +1,12 @@
import { z } from "zod";
-import { datasetItemMediaFields } from "@langfuse/shared";
+import {
+ datasetItemMediaFields,
+ MediaContentType,
+ MediaFileExtension,
+} from "@langfuse/shared";
+
+export { MediaContentType, MediaFileExtension };
export enum MediaEnabledFields {
Input = "input",
@@ -12,115 +18,6 @@ export enum MediaEnabledFields {
When adding new media content types, also update the supported content types in the server definition
in fern/apis/server/definition/media.yml and reflect the changes in the SDKs.
*/
-export enum MediaContentType {
- PNG = "image/png",
- JPEG = "image/jpeg",
- JPG = "image/jpg",
- WEBP = "image/webp",
- GIF = "image/gif",
- SVG = "image/svg+xml",
- TIFF = "image/tiff",
- BMP = "image/bmp",
- AVIF = "image/avif",
- HEIC = "image/heic",
- MP3 = "audio/mpeg",
- MP3_LEGACY = "audio/mp3",
- WAV = "audio/wav",
- OGG = "audio/ogg",
- OGA = "audio/oga",
- AAC = "audio/aac",
- M4A = "audio/mp4",
- FLAC = "audio/flac",
- OPUS = "audio/opus",
- WEBA = "audio/webm",
- MP4 = "video/mp4",
- WEBM = "video/webm",
- VIDEO_OGG = "video/ogg",
- MPEG = "video/mpeg",
- MOV = "video/quicktime",
- AVI = "video/x-msvideo",
- MKV = "video/x-matroska",
- TXT = "text/plain",
- HTML = "text/html",
- CSS = "text/css",
- CSV = "text/csv",
- MARKDOWN = "text/markdown",
- PYTHON = "text/x-python",
- JAVASCRIPT = "application/javascript",
- TYPESCRIPT = "text/x-typescript",
- YAML = "application/x-yaml",
- PDF = "application/pdf",
- DOC = "application/msword",
- XLS = "application/vnd.ms-excel",
- XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- ZIP = "application/zip",
- JSON = "application/json",
- XML = "application/xml",
- BIN = "application/octet-stream",
- DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
- PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
- RTF = "application/rtf",
- JSONL = "application/x-ndjson",
- PARQUET = "application/vnd.apache.parquet",
- GZIP = "application/gzip",
- TAR = "application/x-tar",
- SEVEN_Z = "application/x-7z-compressed",
-}
-
-export enum MediaFileExtension {
- PNG = "png",
- JPG = "jpg",
- JPEG = "jpeg",
- WEBP = "webp",
- GIF = "gif",
- SVG = "svg",
- TIFF = "tiff",
- BMP = "bmp",
- AVIF = "avif",
- HEIC = "heic",
- MP3 = "mp3",
- WAV = "wav",
- OGG = "ogg",
- OGA = "oga",
- AAC = "aac",
- M4A = "m4a",
- FLAC = "flac",
- OPUS = "opus",
- WEBA = "weba",
- MP4 = "mp4",
- WEBM = "webm",
- OGV = "ogv",
- MPEG = "mpeg",
- MOV = "mov",
- AVI = "avi",
- MKV = "mkv",
- TXT = "txt",
- HTML = "html",
- CSS = "css",
- CSV = "csv",
- MD = "md",
- PY = "py",
- JS = "js",
- TS = "ts",
- YAML = "yaml",
- PDF = "pdf",
- DOC = "doc",
- XLS = "xls",
- XLSX = "xlsx",
- ZIP = "zip",
- JSON = "json",
- XML = "xml",
- BIN = "bin",
- DOCX = "docx",
- PPTX = "pptx",
- RTF = "rtf",
- JSONL = "jsonl",
- PARQUET = "parquet",
- GZ = "gz",
- TAR = "tar",
- SEVEN_Z = "7z",
-}
-
const commonMediaUploadFields = {
contentType: z.enum(MediaContentType, {
message: `Invalid content type. Only supporting ${Object.values(
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 211d4e7ce1..bd94145dad 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -83,6 +83,9 @@ const EnvSchema = z.object({
.number()
.positive()
.default(1),
+ LANGFUSE_OTEL_MEDIA_UPLOAD_ENABLED: z
+ .enum(["true", "false"])
+ .default("false"),
LANGFUSE_SECONDARY_OTEL_INGESTION_QUEUE_ENABLED_PROJECT_IDS: z
.string()
.optional(),
diff --git a/worker/src/features/otel-media/processOtelMedia.test.ts b/worker/src/features/otel-media/processOtelMedia.test.ts
new file mode 100644
index 0000000000..294c38398d
--- /dev/null
+++ b/worker/src/features/otel-media/processOtelMedia.test.ts
@@ -0,0 +1,152 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ const span = { setAttributes: vi.fn() };
+ return {
+ instrumentAsync: vi.fn(
+ async (
+ _context: unknown,
+ callback: (activeSpan: typeof span) => Promise<unknown>,
+ ) => callback(span),
+ ),
+ logger: { warn: vi.fn() },
+ recordDistribution: vi.fn(),
+ span,
+ };
+});
+
+vi.mock("@langfuse/shared/src/server", () => ({
+ instrumentAsync: mocks.instrumentAsync,
+ logger: mocks.logger,
+ processOtelMedia: vi.fn(),
+ recordDistribution: mocks.recordDistribution,
+ uploadMediaForTrace: vi.fn(),
+}));
+
+import { processOtelEventMedia } from "./processOtelMedia";
+
+const processResult = {
+ uploaded: 1,
+ reused: 2,
+ invalid: 3,
+ failed: 4,
+ bytesRemoved: 5,
+ candidates: 6,
+ bytesProcessed: 7,
+ detectionChecks: {
+ data_uri: 8,
+ stringified_json: 9,
+ structured_payload: 10,
+ },
+ detectionCheckedBytes: {
+ data_uri: 10,
+ stringified_json: 11,
+ structured_payload: 12,
+ },
+};
+
+describe("processOtelEventMedia", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("processes only normalized direct events with media fields", async () => {
+ const eventInput = {
+ traceId: "trace-id",
+ spanId: "observation-id",
+ input: { role: "user" },
+ name: "observation-name",
+ };
+ const processMedia = vi.fn().mockResolvedValue(processResult);
+
+ await processOtelEventMedia({
+ eventInputs: [
+ eventInput,
+ { traceId: "trace-id", spanId: "without-media-fields" },
+ { traceId: "trace-id", input: "missing-span-id" },
+ null,
+ ],
+ projectId: "project-id",
+ fileKey: "file-key",
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ processMedia,
+ });
+
+ expect(processMedia).toHaveBeenCalledWith(
+ expect.objectContaining({ events: [eventInput] }),
+ );
+ expect(mocks.instrumentAsync).toHaveBeenCalledWith(
+ { name: "langfuse.ingestion.otel.media.process" },
+ expect.any(Function),
+ );
+ expect(mocks.span.setAttributes).toHaveBeenCalledWith(
+ expect.objectContaining({
+ "langfuse.ingestion.otel.media.uploaded": 1,
+ "langfuse.ingestion.otel.media.bytes_processed": 7,
+ "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,
+ );
+ expect(mocks.recordDistribution).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.batch_checked_byte_length",
+ 33,
+ );
+ expect(mocks.recordDistribution).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.processing_duration_ms",
+ expect.any(Number),
+ );
+ });
+
+ it("does not create a processing span when there are no media fields", async () => {
+ const processMedia = vi.fn();
+
+ await processOtelEventMedia({
+ eventInputs: [{ traceId: "trace-id", spanId: "observation-id" }],
+ projectId: "project-id",
+ fileKey: "file-key",
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ processMedia,
+ });
+
+ expect(processMedia).not.toHaveBeenCalled();
+ expect(mocks.instrumentAsync).not.toHaveBeenCalled();
+ });
+
+ it("fails open when media processing throws", async () => {
+ const processMedia = vi.fn().mockRejectedValue(new Error("unexpected"));
+
+ await expect(
+ processOtelEventMedia({
+ eventInputs: [
+ {
+ traceId: "trace-id",
+ spanId: "observation-id",
+ input: "input",
+ },
+ ],
+ projectId: "project-id",
+ fileKey: "file-key",
+ mediaBucket: "media-bucket",
+ mediaPrefix: "media/",
+ processMedia,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(mocks.recordDistribution).toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.processing_duration_ms",
+ expect.any(Number),
+ );
+ expect(mocks.recordDistribution).not.toHaveBeenCalledWith(
+ "langfuse.ingestion.otel.media.batch_byte_length",
+ expect.any(Number),
+ );
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ "OTEL media processing failed; continuing ingestion with original span values",
+ expect.objectContaining({ projectId: "project-id", fileKey: "file-key" }),
+ );
+ });
+});
diff --git a/worker/src/features/otel-media/processOtelMedia.ts b/worker/src/features/otel-media/processOtelMedia.ts
new file mode 100644
index 0000000000..1f2169d63b
--- /dev/null
+++ b/worker/src/features/otel-media/processOtelMedia.ts
@@ -0,0 +1,132 @@
+import {
+ instrumentAsync,
+ logger,
+ processOtelMedia,
+ recordDistribution,
+ type OtelMediaEvent,
+ 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.
+ *
+ * Responsibilities are split across three layers:
+ * - This adapter filters event shapes and owns storage configuration,
+ * instrumentation, and fail-open behavior.
+ * - `processOtelMedia` iterates input/output/metadata, supplies OTEL upload
+ * context, and aggregates processing results.
+ * - `transformMediaPayload`, called by `processOtelMedia`, contains the generic
+ * 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
+ * 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[];
+ projectId: string;
+ fileKey: string;
+ mediaBucket?: string;
+ mediaPrefix: string;
+ processMedia?: typeof processOtelMedia;
+}): Promise<void> {
+ const {
+ eventInputs,
+ projectId,
+ fileKey,
+ mediaBucket,
+ mediaPrefix,
+ processMedia = processOtelMedia,
+ } = params;
+
+ if (!mediaBucket) {
+ logger.warn(
+ "OTEL media upload is enabled but no media storage bucket is configured",
+ { projectId, fileKey },
+ );
+ return;
+ }
+
+ const events = eventInputs.filter(isOtelMediaEvent);
+ if (events.length === 0) return;
+
+ try {
+ await instrumentAsync(
+ { name: "langfuse.ingestion.otel.media.process" },
+ async (span) => {
+ const startedAt = Date.now();
+ try {
+ const result = await processMedia({
+ events,
+ projectId,
+ mediaBucket,
+ mediaPrefix,
+ uploadMedia: uploadMediaForTrace,
+ });
+
+ span.setAttributes({
+ "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.failed": result.failed,
+ "langfuse.ingestion.otel.media.candidates": result.candidates,
+ "langfuse.ingestion.otel.media.bytes_processed":
+ result.bytesProcessed,
+ "langfuse.ingestion.otel.media.bytes_removed": result.bytesRemoved,
+ "langfuse.ingestion.otel.media.detection_checks.data_uri":
+ result.detectionChecks.data_uri,
+ "langfuse.ingestion.otel.media.detection_checks.stringified_json":
+ result.detectionChecks.stringified_json,
+ "langfuse.ingestion.otel.media.detection_checks.structured_payload":
+ result.detectionChecks.structured_payload,
+ "langfuse.ingestion.otel.media.detection_checked_bytes.data_uri":
+ result.detectionCheckedBytes.data_uri,
+ "langfuse.ingestion.otel.media.detection_checked_bytes.stringified_json":
+ result.detectionCheckedBytes.stringified_json,
+ "langfuse.ingestion.otel.media.detection_checked_bytes.structured_payload":
+ result.detectionCheckedBytes.structured_payload,
+ });
+
+ recordDistribution(
+ "langfuse.ingestion.otel.media.batch_byte_length",
+ result.bytesProcessed,
+ );
+ recordDistribution(
+ "langfuse.ingestion.otel.media.batch_checked_byte_length",
+ Object.values(result.detectionCheckedBytes).reduce(
+ (total, bytes) => total + bytes,
+ 0,
+ ),
+ );
+ } finally {
+ recordDistribution(
+ "langfuse.ingestion.otel.media.processing_duration_ms",
+ Date.now() - startedAt,
+ );
+ }
+ },
+ );
+ } catch (error) {
+ logger.warn(
+ "OTEL media processing failed; continuing ingestion with original span values",
+ { projectId, fileKey, error },
+ );
+ }
+}
+
+function isOtelMediaEvent(value: unknown): value is OtelMediaEvent {
+ 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)
+ );
+}
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
index 2f2688dffc..b1921e30e9 100644
--- a/worker/src/queues/otelIngestionQueue.ts
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -46,6 +46,7 @@ import {
scheduleObservationEvals,
createObservationEvalSchedulerDeps,
} from "../features/evaluation/observationEval";
+import { processOtelEventMedia } from "../features/otel-media/processOtelMedia";
/**
* Check if HTTP headers from the SDK request indicate the batch is eligible
@@ -318,6 +319,7 @@ export const otelIngestionQueueProcessorBuilder = (
});
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(
@@ -510,6 +512,19 @@ export const otelIngestionQueueProcessorBuilder = (
return;
}
+ if (
+ env.LANGFUSE_OTEL_MEDIA_UPLOAD_ENABLED === "true" &&
+ shouldWriteToEventsTable
+ ) {
+ await processOtelEventMedia({
+ eventInputs,
+ projectId,
+ fileKey,
+ mediaBucket: env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET,
+ mediaPrefix: env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX,
+ });
+ }
+
// Create scheduler deps only if we have eval configs
const evalSchedulerDeps = hasEvalConfigs
? createObservationEvalSchedulerDeps()