Skip to content

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

feat(otel-ingestion): handle long-running traces (#7241)

Hassieb Pakzada121e24b790a
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index 722d3ff8bc..b63dc240ea 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -1,14 +1,31 @@
-import {
- convertOtelSpanToIngestionEvent,
- convertNanoTimestampToISO,
-} from "@/src/features/otel/server";
+import { OtelIngestionProcessor } from "@/src/features/otel/server/OtelIngestionProcessor";
import { ingestionEvent } from "@langfuse/shared/src/server";
+// Test helper function to maintain backward compatibility with existing tests
+// This mimics the old convertOtelSpanToIngestionEvent function signature
+async function convertOtelSpanToIngestionEvent(
+ resourceSpan: any,
+ seenTraces: Set<string>,
+ publicKey?: string,
+) {
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ publicKey,
+ });
+
+ // For tests, we bypass Redis initialization and directly set the seen traces
+ // This is safe because we're testing the conversion logic, not the Redis caching
+ (processor as any).seenTraces = seenTraces;
+ (processor as any).isInitialized = true;
+
+ return await processor.processToIngestionEvents([resourceSpan]);
+}
+
describe("OTel Resource Span Mapping", () => {
describe("Langfuse OTEL SDK spans", () => {
const publicKey = "pk-lf-1234567890";
- it("should convert LF-OTEL spans to LF-events", () => {
+ it("should convert LF-OTEL spans to LF-events", async () => {
const langfuseOtelSpans = [
{
resource: {
@@ -239,9 +256,9 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = langfuseOtelSpans.flatMap((span) =>
- convertOtelSpanToIngestionEvent(span, publicKey),
- );
+ const events = (await Promise.all(langfuseOtelSpans.map(async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ))).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const generationEvents = events.filter(
(e) => e.type === "generation-create",
@@ -345,7 +362,7 @@ describe("OTel Resource Span Mapping", () => {
});
});
- it("should create a trace when as_root has been specified", () => {
+ it("should create a trace when as_root has been specified", async () => {
const langfuseOtelSpans = [
{
resource: {
@@ -432,9 +449,9 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = langfuseOtelSpans.flatMap((span) =>
- convertOtelSpanToIngestionEvent(span, publicKey),
- );
+ const events = (await Promise.all(langfuseOtelSpans.map(async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ))).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -463,7 +480,7 @@ describe("OTel Resource Span Mapping", () => {
environment: "production",
});
});
- it("should throw an error if langfuse scope spans have wrong project ID", () => {
+ it("should throw an error if langfuse scope spans have wrong project ID", async () => {
const langfuseOtelSpans = [
{
resource: {
@@ -549,16 +566,16 @@ describe("OTel Resource Span Mapping", () => {
},
];
- expect(() =>
- langfuseOtelSpans.flatMap((span) =>
- convertOtelSpanToIngestionEvent(span, publicKey),
- ),
- ).toThrowError("Langfuse OTEL SDK span has different public key");
+ await expect(
+ Promise.all(langfuseOtelSpans.map(async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ))
+ ).rejects.toThrowError("Langfuse OTEL SDK span has different public key");
});
});
describe("Vendor Spans", () => {
- it("should convert an OpenLit OTel Span to Langfuse Events", () => {
+ it("should convert an OpenLit OTel Span to Langfuse Events", async () => {
// Setup
const resourceSpan = {
resource: {
@@ -734,7 +751,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
// Will throw an error if the parsing fails
@@ -744,7 +764,7 @@ describe("OTel Resource Span Mapping", () => {
expect(parsedEvents).toHaveLength(2);
});
- it("should convert a TraceLoop OTel Span to Langfuse Events", () => {
+ it("should convert a TraceLoop OTel Span to Langfuse Events", async () => {
// Setup
const resourceSpan = {
resource: {
@@ -850,7 +870,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
// Will throw an error if the parsing fails
@@ -860,7 +883,7 @@ describe("OTel Resource Span Mapping", () => {
expect(parsedEvents).toHaveLength(2);
});
- it("LFE-5171: should convert a Semantic Kernel 1.55+ OTel Span with new event-based semantic conventions to Langfuse Events", () => {
+ it("LFE-5171: should convert a Semantic Kernel 1.55+ OTel Span with new event-based semantic conventions to Langfuse Events", async () => {
// Setup - Semantic Kernel 1.55+ uses new event names instead of deprecated gen_ai.content.prompt/completion
const resourceSpan = {
scopeSpans: [
@@ -968,7 +991,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
// Will throw an error if the parsing fails
@@ -1051,7 +1077,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
// Expect a span and a trace to be created
@@ -1078,7 +1107,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
// Check that we create a generation
@@ -1108,7 +1140,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
expect(langfuseEvents[0].body.name).toBe("right name");
@@ -1628,7 +1663,7 @@ describe("OTel Resource Span Mapping", () => {
],
])(
"Attributes: %s",
- (
+ async (
_name: string,
spec: {
entity: string;
@@ -1658,7 +1693,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
const entity: { body: Record<string, any> } =
@@ -1738,7 +1776,7 @@ describe("OTel Resource Span Mapping", () => {
],
])(
"ResourceAttributes: %s",
- (
+ async (
_name: string,
spec: {
entity: string;
@@ -1766,7 +1804,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
const entity: { body: Record<string, any> } =
@@ -1888,27 +1929,31 @@ describe("OTel Resource Span Mapping", () => {
otelEventName: "gen_ai.assistant.message",
otelEventAttributeKey: "tool_calls",
otelEventAttributeValue: {
- stringValue: JSON.stringify([{
- id: "call_123",
- type: "function",
- function: {
- name: "get_weather",
- arguments: '{"location": "Paris"}'
- }
- }]),
+ stringValue: JSON.stringify([
+ {
+ id: "call_123",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: '{"location": "Paris"}',
+ },
+ },
+ ]),
},
entityAttributeKey: "input",
entityAttributeValue: [
{
role: "assistant",
- tool_calls: JSON.stringify([{
- id: "call_123",
- type: "function",
- function: {
- name: "get_weather",
- arguments: '{"location": "Paris"}'
- }
- }]),
+ tool_calls: JSON.stringify([
+ {
+ id: "call_123",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: '{"location": "Paris"}',
+ },
+ },
+ ]),
},
],
},
@@ -2020,7 +2065,7 @@ describe("OTel Resource Span Mapping", () => {
],
])(
"Events: %s",
- (
+ async (
_name: string,
spec: {
entity: string;
@@ -2062,7 +2107,10 @@ describe("OTel Resource Span Mapping", () => {
};
// When
- const langfuseEvents = convertOtelSpanToIngestionEvent(resourceSpan);
+ const langfuseEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
// Then
const entity: { body: Record<string, any> } =
@@ -2074,6 +2122,106 @@ describe("OTel Resource Span Mapping", () => {
);
});
+ describe("Span Counting", () => {
+ it("should count spans correctly across multiple resource spans", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ const resourceSpans = [
+ {
+ scopeSpans: [
+ { spans: [{}, {}, {}] }, // 3 spans
+ { spans: [{}] }, // 1 span
+ ],
+ },
+ {
+ scopeSpans: [
+ { spans: [{}, {}] }, // 2 spans
+ ],
+ },
+ ];
+
+ // Access private method for testing
+ const count = (processor as any).getTotalSpanCount(resourceSpans);
+ expect(count).toBe(6);
+ });
+
+ it("should handle empty resource spans", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ const count = (processor as any).getTotalSpanCount([]);
+ expect(count).toBe(0);
+ });
+
+ it("should handle null/undefined resource spans", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ expect((processor as any).getTotalSpanCount(null)).toBe(0);
+ expect((processor as any).getTotalSpanCount(undefined)).toBe(0);
+ });
+
+ it("should handle malformed resource spans", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ const resourceSpans = [
+ { scopeSpans: null },
+ { scopeSpans: undefined },
+ { scopeSpans: [] },
+ {
+ scopeSpans: [
+ { spans: null },
+ { spans: undefined },
+ { spans: [] },
+ { spans: [{}, {}] }, // 2 valid spans
+ ],
+ },
+ ];
+
+ const count = (processor as any).getTotalSpanCount(resourceSpans);
+ expect(count).toBe(2);
+ });
+
+ it("should return 0 for non-array input", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ expect((processor as any).getTotalSpanCount("not-an-array")).toBe(0);
+ expect((processor as any).getTotalSpanCount({})).toBe(0);
+ expect((processor as any).getTotalSpanCount(123)).toBe(0);
+ });
+
+ it("should handle deeply nested null/undefined structures", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ const resourceSpans = [
+ null,
+ undefined,
+ {},
+ { scopeSpans: [null, undefined, {}] },
+ {
+ scopeSpans: [
+ { spans: [{}, {}] }, // 2 valid spans
+ ],
+ },
+ ];
+
+ const count = (processor as any).getTotalSpanCount(resourceSpans);
+ expect(count).toBe(2);
+ });
+
+ it("should return -1 and not throw on unexpected errors", () => {
+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });
+
+ // Create a malicious object that throws when accessed
+ const maliciousResourceSpan = {
+ get scopeSpans() {
+ throw new Error("Malicious property access");
+ },
+ };
+
+ const count = (processor as any).getTotalSpanCount([maliciousResourceSpan]);
+ expect(count).toBe(-1);
+ });
+ });
+
describe("Timestamp Conversion", () => {
it("should correctly convert OpenTelemetry timestamps to ISO strings", () => {
// Test case with positive low value
@@ -2095,8 +2243,8 @@ describe("OTel Resource Span Mapping", () => {
const expectedEndTime = "2025-04-17T07:39:54.084Z";
// Convert timestamps to ISO strings
- const actualStartTime = convertNanoTimestampToISO(positiveTimestamp);
- const actualEndTime = convertNanoTimestampToISO(negativeTimestamp);
+ const actualStartTime = OtelIngestionProcessor.convertNanoTimestampToISO(positiveTimestamp);
+ const actualEndTime = OtelIngestionProcessor.convertNanoTimestampToISO(negativeTimestamp);
// Verify conversions match expected values
expect(actualStartTime).toBe(expectedStartTime);
@@ -2107,7 +2255,7 @@ describe("OTel Resource Span Mapping", () => {
// Test with string timestamp (nanoseconds)
const stringTimestamp = "1744317592317227000"; // Same as positiveTimestamp above
const expectedStringResult = "2025-04-10T20:39:52.317Z";
- expect(convertNanoTimestampToISO(stringTimestamp)).toBe(
+ expect(OtelIngestionProcessor.convertNanoTimestampToISO(stringTimestamp)).toBe(
expectedStringResult,
);
@@ -2117,9 +2265,606 @@ describe("OTel Resource Span Mapping", () => {
high: 0,
unsigned: true,
};
- expect(convertNanoTimestampToISO(zeroTimestamp)).toBe(
+ expect(OtelIngestionProcessor.convertNanoTimestampToISO(zeroTimestamp)).toBe(
"1970-01-01T00:00:00.000Z",
);
});
});
+
+ describe("Trace seen logic", () => {
+ const publicKey = "pk-lf-1234567890";
+
+ it("should create a shallow trace when seenTraces set is empty for non-root span without trace updates", async () => {
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "test-operation" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // Empty seenTraces set - should create shallow trace for first span
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(2);
+ expect(traceEvents.length).toBe(1);
+ expect(spanEvents.length).toBe(1);
+
+ const traceEvent = traceEvents[0];
+
+ // Should create shallow trace with minimal information
+ expect(traceEvent.body).toMatchObject({
+ id: "95f3b926c7d009925bcb5dbc27311120",
+ timestamp: "2025-05-05T13:42:33.936Z",
+ environment: "default",
+ });
+
+ // Should NOT have name, metadata, etc. since it's a shallow trace
+ expect(traceEvent.body.name).toBeUndefined();
+ expect(traceEvent.body.metadata).toBeUndefined();
+ expect(traceEvent.body.userId).toBeUndefined();
+ expect(traceEvent.body.sessionId).toBeUndefined();
+ });
+
+ it("should NOT create trace when seenTraces set contains the traceId", async () => {
+ const traceId = "95f3b926c7d009925bcb5dbc27311120";
+ const seenTraces = new Set([traceId]);
+
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "test-operation" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // seenTraces contains the traceId - should NOT create trace
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(1);
+ expect(traceEvents.length).toBe(0); // No trace should be created
+ expect(spanEvents.length).toBe(1); // Only span should be created
+
+ const spanEvent = spanEvents[0];
+ expect(spanEvent.body).toMatchObject({
+ id: "d43e37b7d17e5476",
+ traceId: "95f3b926c7d009925bcb5dbc27311120",
+ parentObservationId: "834e28b5917fbef6",
+ name: "child-span",
+ });
+ });
+
+ it("should create full trace for root span even when seenTraces contains traceId", async () => {
+ const traceId = "95f3b926c7d009925bcb5dbc27311120";
+ const seenTraces = new Set([traceId]);
+
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ // No parentSpanId - makes it a root span
+ name: "root-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "root-operation" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // seenTraces contains the traceId, but span is root - should still create full trace
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(2);
+ expect(traceEvents.length).toBe(1); // Trace should be created because it's root span
+ expect(spanEvents.length).toBe(1);
+
+ const traceEvent = traceEvents[0];
+
+ // Should create full trace with name and metadata since it's a root span
+ expect(traceEvent.body).toMatchObject({
+ id: "95f3b926c7d009925bcb5dbc27311120",
+ timestamp: "2025-05-05T13:42:33.936Z",
+ name: "root-span",
+ environment: "default",
+ });
+
+ expect(traceEvent.body.metadata).toBeDefined();
+ });
+
+ it("should create full trace for span with trace updates even when seenTraces contains traceId", async () => {
+ const traceId = "95f3b926c7d009925bcb5dbc27311120";
+ const seenTraces = new Set([traceId]);
+
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "child-span-with-trace-updates",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "langfuse.trace.name",
+ value: { stringValue: "Custom Trace Name" },
+ },
+ {
+ key: "user.id",
+ value: { stringValue: "user-123" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // seenTraces contains the traceId, but span has trace updates - should still create full trace
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(2);
+ expect(traceEvents.length).toBe(1); // Trace should be created because it has trace updates
+ expect(spanEvents.length).toBe(1);
+
+ const traceEvent = traceEvents[0];
+
+ // Should create full trace with trace updates
+ expect(traceEvent.body).toMatchObject({
+ id: "95f3b926c7d009925bcb5dbc27311120",
+ timestamp: "2025-05-05T13:42:33.936Z",
+ name: "Custom Trace Name",
+ userId: "user-123",
+ environment: "default",
+ });
+
+ expect(traceEvent.body.metadata).toBeDefined();
+ });
+
+ it("should create only ONE trace when multiple spans share the same traceId with empty seenTraces", async () => {
+ const sharedTraceId = [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32];
+
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: sharedTraceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "first-child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "first-operation" },
+ },
+ ],
+ status: {},
+ },
+ {
+ traceId: {
+ type: "Buffer",
+ data: sharedTraceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: [180, 95, 123, 45, 67, 89, 101, 112],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "second-child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1150000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1250000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "second-operation" },
+ },
+ ],
+ status: {},
+ },
+ {
+ traceId: {
+ type: "Buffer",
+ data: sharedTraceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: [200, 100, 150, 75, 25, 50, 175, 225],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "third-child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1260000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1360000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "operation.name",
+ value: { stringValue: "third-operation" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // Empty seenTraces set - should create only ONE trace despite multiple spans with same traceId
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(4); // 1 trace + 3 spans
+ expect(traceEvents.length).toBe(1); // Only ONE trace should be created
+ expect(spanEvents.length).toBe(3); // All three spans should be created
+
+ const traceEvent = traceEvents[0];
+
+ // Should create shallow trace with minimal information (from first span processed)
+ expect(traceEvent.body).toMatchObject({
+ id: "95f3b926c7d009925bcb5dbc27311120",
+ timestamp: "2025-05-05T13:42:33.936Z", // timestamp from first span
+ environment: "default",
+ });
+
+ // Verify all spans were created with the same traceId
+ spanEvents.forEach((spanEvent) => {
+ expect(spanEvent.body.traceId).toBe("95f3b926c7d009925bcb5dbc27311120");
+ });
+
+ // Verify span names are correct
+ expect(spanEvents[0].body.name).toBe("first-child-span");
+ expect(spanEvents[1].body.name).toBe("second-child-span");
+ expect(spanEvents[2].body.name).toBe("third-child-span");
+ });
+
+ it("should filter out shallow traces when full traces exist for the same traceId in same batch", async () => {
+ const sharedTraceId = [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32];
+
+ const otelSpans = [
+ {
+ resource: {
+ attributes: [
+ {
+ key: "service.name",
+ value: { stringValue: "test-service" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ // First span: non-root, no trace updates (will create shallow trace)
+ {
+ traceId: {
+ type: "Buffer",
+ data: sharedTraceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: [212, 62, 55, 183, 209, 126, 84, 118],
+ },
+ parentSpanId: {
+ type: "Buffer",
+ data: [131, 78, 40, 181, 145, 127, 190, 246],
+ },
+ name: "child-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1047784088,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1149405088,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [],
+ status: {},
+ },
+ // Second span: root span (will create full trace)
+ {
+ traceId: {
+ type: "Buffer",
+ data: sharedTraceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: [180, 95, 123, 45, 67, 89, 101, 112],
+ },
+ // No parentSpanId = root span
+ name: "root-span",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 1150000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 1250000000,
+ high: 406627672,
+ unsigned: true,
+ },
+ attributes: [],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ // Empty seenTraces set - both spans would normally create traces
+ const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+
+ const traceEvents = events.filter((e) => e.type === "trace-create");
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(events.length).toBe(3); // 1 trace + 2 spans (shallow trace filtered out)
+ expect(traceEvents.length).toBe(1); // Only ONE trace should remain after filtering
+ expect(spanEvents.length).toBe(2); // Both spans should be created
+
+ const traceEvent = traceEvents[0];
+
+ // Should be the FULL trace (from root span), not the shallow one
+ expect(traceEvent.body).toMatchObject({
+ id: "95f3b926c7d009925bcb5dbc27311120",
+ name: "root-span", // Full trace has name
+ environment: "default",
+ });
+
+ // Should have metadata (indicates it's a full trace, not shallow)
+ expect(traceEvent.body.metadata).toBeDefined();
+
+ // Verify both spans were created
+ expect(spanEvents[0].body.name).toBe("child-span");
+ expect(spanEvents[1].body.name).toBe("root-span");
+ });
+ });
});
diff --git a/web/src/features/otel/server/OtelIngestionProcessor.ts b/web/src/features/otel/server/OtelIngestionProcessor.ts
new file mode 100644
index 0000000000..2e251fdaf9
--- /dev/null
+++ b/web/src/features/otel/server/OtelIngestionProcessor.ts
@@ -0,0 +1,1286 @@
+import { randomUUID } from "crypto";
+
+import { ForbiddenError, ObservationLevel } from "@langfuse/shared";
+import {
+ type TraceEventType,
+ type IngestionEventType,
+ redis,
+ logger,
+ instrumentAsync,
+ traceException,
+} from "@langfuse/shared/src/server";
+
+import { LangfuseOtelSpanAttributes } from "./attributes";
+
+// Type definitions for internal processor state
+interface TraceState {
+ hasFullTrace: boolean;
+ shallowEventIds: string[];
+}
+
+export interface OtelIngestionProcessorConfig {
+ projectId: string;
+ publicKey?: string;
+}
+
+interface CreateTraceEventParams {
+ traceId: string;
+ startTimeISO: string;
+ attributes: Record<string, unknown>;
+ resourceAttributes: Record<string, unknown>;
+ resourceAttributeMetadata: Record<string, unknown>;
+ spanAttributesInMetadata: Record<string, unknown>;
+ scopeSpan: any;
+ scopeAttributes: Record<string, unknown>;
+ isLangfuseSDKSpans: boolean;
+ isRootSpan: boolean;
+ hasTraceUpdates: boolean;
+ parentObservationId: string | null;
+ span: any;
+}
+
+interface CreateObservationEventParams {
+ span: any;
+ traceId: string;
+ parentObservationId: string | null;
+ attributes: Record<string, unknown>;
+ resourceAttributes: Record<string, unknown>;
+ resourceAttributeMetadata: Record<string, unknown>;
+ spanAttributeMetadata: Record<string, unknown>;
+ spanAttributesInMetadata: Record<string, unknown>;
+ scopeSpan: any;
+ scopeAttributes: Record<string, unknown>;
+ isLangfuseSDKSpans: boolean;
+ startTimeISO: string;
+ endTimeISO: string;
+}
+
+interface ResourceSpan {
+ resource?: {
+ attributes?: Array<{ key: string; value: any }>;
+ };
+ scopeSpans?: Array<{
+ scope?: {
+ name: string;
+ version?: string;
+ attributes?: Array<{ key: string; value: any }>;
+ };
+ spans?: Array<{
+ traceId: { data?: Buffer } | Buffer;
+ spanId: { data?: Buffer } | Buffer;
+ parentSpanId?: { data?: Buffer } | Buffer;
+ name: string;
+ kind: number;
+ startTimeUnixNano: number | { low: number; high: number };
+ endTimeUnixNano: number | { low: number; high: number };
+ attributes?: Array<{ key: string; value: any }>;
+ events?: any[];
+ status?: { code?: number; message?: string };
+ }>;
+ }>;
+}
+
+/**
+ * Processor class that encapsulates all logic for converting OpenTelemetry
+ * resource spans into Langfuse ingestion events.
+ *
+ * Manages trace deduplication internally and provides a clean interface
+ * for converting OTEL spans to Langfuse events.
+ */
+export class OtelIngestionProcessor {
+ private seenTraces: Set<string> = new Set();
+ private isInitialized = false;
+ private readonly projectId: string;
+ private readonly publicKey?: string;
+
+ constructor(config: OtelIngestionProcessorConfig) {
+ this.projectId = config.projectId;
+ this.publicKey = config.publicKey;
+ }
+
+ /**
+ * Process resource spans and convert them to Langfuse ingestion events.
+ * Handles trace deduplication automatically using internal state.
+ * Initializes seen traces from Redis automatically on first call.
+ * Filters out shallow trace events if full trace events exist for the same traceId.
+ */
+ async processToIngestionEvents(
+ resourceSpans: ResourceSpan[],
+ ): Promise<IngestionEventType[]> {
+ return await instrumentAsync(
+ { name: "otel-ingestion-processor" },
+ async (span) => {
+ span.setAttribute("project_id", this.projectId);
+ span.setAttribute(
+ "total_span_count",
+ this.getTotalSpanCount(resourceSpans),
+ );
+
+ try {
+ // Lazy initialization - load seen traces from Redis if not already done
+ // Seen traces are traces that went through the ingestion pipeline within last 10 minutes
+ if (!this.isInitialized) {
+ this.seenTraces = await this.getSeenTracesSet(resourceSpans);
+ this.isInitialized = true;
+ }
+
+ // Input validation
+ if (!Array.isArray(resourceSpans)) {
+ return [];
+ }
+
+ if (resourceSpans.length === 0) {
+ return [];
+ }
+
+ // Process all events normally first
+ const allEvents = resourceSpans.flatMap((resourceSpan) => {
+ if (!resourceSpan) return [];
+ return this.processResourceSpan(resourceSpan);
+ });
+
+ // Filter out redundant shallow trace events
+ const finalEvents = this.filterRedundantShallowTraces(allEvents);
+
+ span.setAttribute("events_generated", finalEvents.length);
+
+ return finalEvents;
+ } catch (error) {
+ if (error instanceof ForbiddenError) {
+ traceException(error, span);
+ throw error;
+ }
+
+ // Log error but don't throw to avoid breaking the ingestion pipeline
+ logger.error("Error processing OTEL spans:", error);
+ traceException(error, span);
+
+ return [];
+ }
+ },
+ );
+ }
+
+ /**
+ * Filter out shallow trace-create events if a full trace-create event exists for the same traceId.
+ * Maintains optimal trace representation per traceId in the final event list.
+ *
+ * Performance: O(n) where n is the number of events
+ */
+ private filterRedundantShallowTraces(
+ events: IngestionEventType[],
+ ): IngestionEventType[] {
+ if (events.length === 0) return events;
+
+ // Fast path: if no trace-create events, return as-is
+ const hasTraceEvents = events.some(
+ (event) => event.type === "trace-create",
+ );
+ if (!hasTraceEvents) return events;
+
+ // Track trace states by traceId - using simpler structure for better performance
+ const traceStates = new Map<string, TraceState>();
+
+ // Single pass: categorize trace-create events by type
+ for (const event of events) {
+ if (event.type === "trace-create") {
+ const traceId = event.body.id as string;
+
+ if (!traceStates.has(traceId)) {
+ // Initialize entry
+ traceStates.set(traceId, {
+ hasFullTrace: false,
+ shallowEventIds: [],
+ });
+ }
+
+ const traceState = traceStates.get(traceId)!;
+ const isShallowTrace = this.isShallowTraceEvent(event.body);
+
+ if (isShallowTrace) {
+ traceState.shallowEventIds.push(event.id);
+ } else {
+ traceState.hasFullTrace = true;
+ }
+ }
+ }
+
+ // Collect event IDs to exclude (only if we have conflicts)
+ const eventIdsToExclude = new Set<string>();
+ for (const traceState of traceStates.values()) {
+ if (traceState.hasFullTrace && traceState.shallowEventIds.length > 0) {
+ traceState.shallowEventIds.forEach((id) => eventIdsToExclude.add(id));
+ }
+ }
+
+ // Early return if no filtering needed
+ if (eventIdsToExclude.size === 0) return events;
+
+ // Filter out redundant shallow traces
+ return events.filter((event) => !eventIdsToExclude.has(event.id));
+ }
+
+ /**
+ * Determine if a trace event body represents a shallow trace.
+ * Shallow traces only contain minimal fields: id, timestamp, environment.
+ * Full traces have additional meaningful fields like: name, metadata, userId, etc.
+ */
+ private isShallowTraceEvent(traceBody: TraceEventType["body"]): boolean {
+ // Define minimal fields that shallow traces have
+ const SHALLOW_TRACE_FIELDS = new Set(["id", "timestamp", "environment"]);
+
+ // Check for presence of any full trace indicators
+ // These fields indicate a full trace with meaningful trace-level data
+ const FULL_TRACE_INDICATORS = [
+ "name",
+ "metadata",
+ "userId",
+ "sessionId",
+ "public",
+ "tags",
+ "version",
+ "release",
+ "input",
+ "output",
+ ] as const;
+
+ // Fast path: check for any full trace indicators with meaningful values
+ for (const field of FULL_TRACE_INDICATORS) {
+ const value = traceBody[field];
+ if (this.hasMeaningfulValue(value)) {
+ return false; // Has full trace data
+ }
+ }
+
+ // If no full trace indicators, verify it has the basic shallow fields
+ return (
+ SHALLOW_TRACE_FIELDS.has("id") &&
+ this.hasMeaningfulValue(traceBody.id) &&
+ this.hasMeaningfulValue(traceBody.timestamp) &&
+ this.hasMeaningfulValue(traceBody.environment)
+ );
+ }
+
+ /**
+ * Check if a value is meaningful (not null, undefined, empty string, or empty object/array)
+ */
+ private hasMeaningfulValue(value: unknown): boolean {
+ if (value === null || value === undefined || value === "") {
+ return false;
+ }
+ if (Array.isArray(value)) {
+ return value.length > 0;
+ }
+ if (typeof value === "object" && value !== null) {
+ return Object.keys(value).length > 0;
+ }
+ return true;
+ }
+
+ private processResourceSpan(
+ resourceSpan: ResourceSpan,
+ ): IngestionEventType[] {
+ const resourceAttributes = this.extractResourceAttributes(resourceSpan);
+ const events: IngestionEventType[] = [];
+
+ for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {
+ const isLangfuseSDKSpans =
+ scopeSpan.scope?.name.startsWith("langfuse-sdk") ?? false;
+ const scopeAttributes = this.extractScopeAttributes(scopeSpan);
+
+ this.validatePublicKey(isLangfuseSDKSpans, scopeAttributes);
+
+ for (const span of scopeSpan?.spans ?? []) {
+ const spanEvents = this.processSpan(
+ span,
+ scopeSpan,
+ resourceAttributes,
+ scopeAttributes,
+ isLangfuseSDKSpans,
+ );
+ events.push(...spanEvents);
+ }
+ }
+
+ return events;
+ }
+
+ private processSpan(
+ span: any,
+ scopeSpan: any,
+ resourceAttributes: Record<string, unknown>,
+ scopeAttributes: Record<string, unknown>,
+ isLangfuseSDKSpans: boolean,
+ ): IngestionEventType[] {
+ const events: IngestionEventType[] = [];
+ const attributes = this.extractSpanAttributes(span);
+
+ const traceId = Buffer.from(span.traceId?.data ?? span.traceId).toString(
+ "hex",
+ );
+ const parentObservationId = span?.parentSpanId
+ ? Buffer.from(span.parentSpanId?.data ?? span.parentSpanId).toString(
+ "hex",
+ )
+ : null;
+
+ const spanAttributeMetadata = this.extractMetadata(
+ attributes,
+ "observation",
+ );
+ const resourceAttributeMetadata = this.extractMetadata(
+ resourceAttributes,
+ "trace",
+ );
+ const startTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
+ span.startTimeUnixNano,
+ );
+ const endTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
+ span.endTimeUnixNano,
+ );
+
+ const isRootSpan =
+ !parentObservationId ||
+ String(attributes[LangfuseOtelSpanAttributes.AS_ROOT]) === "true";
+
+ const spanAttributesInMetadata = Object.fromEntries(
+ Object.entries(attributes).map(([key, value]) => [
+ key,
+ typeof value === "string" ? value : JSON.stringify(value),
+ ]),
+ );
+
+ const hasTraceUpdates = this.hasTraceUpdates(attributes);
+
+ // Handle trace creation logic with internal seen traces management
+ if (isRootSpan || hasTraceUpdates || !this.seenTraces.has(traceId)) {
+ const traceEvent = this.createTraceEvent({
+ traceId,
+ startTimeISO,
+ attributes,
+ resourceAttributes,
+ resourceAttributeMetadata,
+ spanAttributesInMetadata,
+ scopeSpan,
+ scopeAttributes,
+ isLangfuseSDKSpans,
+ isRootSpan,
+ hasTraceUpdates,
+ parentObservationId,
+ span,
+ });
+ events.push(traceEvent);
+
+ // Update internal seen traces cache
+ this.seenTraces.add(traceId);
+ }
+
+ // Create observation event
+ const observationEvent = this.createObservationEvent({
+ span,
+ traceId,
+ parentObservationId,
+ attributes,
+ resourceAttributes,
+ resourceAttributeMetadata,
+ spanAttributeMetadata,
+ spanAttributesInMetadata,
+ scopeSpan,
+ scopeAttributes,
+ isLangfuseSDKSpans,
+ startTimeISO,
+ endTimeISO,
+ });
+ events.push(observationEvent);
+
+ return events;
+ }
+
+ private createTraceEvent(params: CreateTraceEventParams): IngestionEventType {
+ const {
+ traceId,
+ startTimeISO,
+ attributes,
+ resourceAttributes,
+ resourceAttributeMetadata,
+ spanAttributesInMetadata,
+ scopeSpan,
+ scopeAttributes,
+ isLangfuseSDKSpans,
+ isRootSpan,
+ hasTraceUpdates,
+ parentObservationId,
+ span,
+ } = params;
+
+ // Create shallow trace for new traces without root span or trace updates
+ let trace: TraceEventType["body"] = {
+ id: traceId,
+ timestamp: startTimeISO,
+ environment: this.extractEnvironment(attributes, resourceAttributes),
+ };
+
+ // Create full trace for root spans or spans with trace updates
+ if (isRootSpan || hasTraceUpdates) {
+ trace = {
+ ...trace,
+ name:
+ (attributes[LangfuseOtelSpanAttributes.TRACE_NAME] as string) ??
+ (!parentObservationId
+ ? this.extractName(span.name, attributes)
+ : undefined),
+ metadata: {
+ ...resourceAttributeMetadata,
+ ...this.extractMetadata(attributes, "trace"),
+ ...(isLangfuseSDKSpans
+ ? {}
+ : { attributes: spanAttributesInMetadata }),
+ resourceAttributes,
+ scope: {
+ ...(scopeSpan.scope || {}),
+ attributes: scopeAttributes,
+ },
+ } as Record<string, string | Record<string, string | number>>,
+ version:
+ (attributes?.[LangfuseOtelSpanAttributes.VERSION] as string) ??
+ resourceAttributes?.["service.version"] ??
+ null,
+ release:
+ (attributes?.[LangfuseOtelSpanAttributes.RELEASE] as string) ??
+ resourceAttributes?.[LangfuseOtelSpanAttributes.RELEASE] ??
+ null,
+ userId: this.extractUserId(attributes),
+ sessionId: this.extractSessionId(attributes),
+ public:
+ attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === true ||
+ attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === "true" ||
+ attributes?.["langfuse.public"] === true ||
+ attributes?.["langfuse.public"] === "true",
+ tags: this.extractTags(attributes),
+ environment: this.extractEnvironment(attributes, resourceAttributes),
+ ...this.extractInputAndOutput(span?.events ?? [], attributes, "trace"),
+ };
+ }
+
+ return {
+ id: randomUUID(),
+ type: "trace-create",
+ timestamp: new Date(startTimeISO).toISOString(),
+ body: trace,
+ };
+ }
+
+ private createObservationEvent(
+ params: CreateObservationEventParams,
+ ): IngestionEventType {
+ const {
+ span,
+ traceId,
+ parentObservationId,
+ attributes,
+ resourceAttributes,
+ resourceAttributeMetadata,
+ spanAttributeMetadata,
+ spanAttributesInMetadata,
+ scopeSpan,
+ scopeAttributes,
+ isLangfuseSDKSpans,
+ startTimeISO,
+ endTimeISO,
+ } = params;
+
+ const observation = {
+ id: Buffer.from(span.spanId?.data ?? span.spanId).toString("hex"),
+ traceId,
+ parentObservationId,
+ name: this.extractName(span.name, attributes),
+ startTime: startTimeISO,
+ endTime: endTimeISO,
+ environment: this.extractEnvironment(attributes, resourceAttributes),
+ completionStartTime: this.extractCompletionStartTime(attributes),
+ metadata: {
+ ...resourceAttributeMetadata,
+ ...spanAttributeMetadata,
+ ...(isLangfuseSDKSpans ? {} : { attributes: spanAttributesInMetadata }),
+ resourceAttributes,
+ scope: { ...scopeSpan.scope, attributes: scopeAttributes },
+ },
+ level:
+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] ??
+ (span.status?.code === 2
+ ? ObservationLevel.ERROR
+ : ObservationLevel.DEFAULT),
+ statusMessage:
+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE] ??
+ span.status?.message ??
+ null,
+ version:
+ attributes[LangfuseOtelSpanAttributes.VERSION] ??
+ resourceAttributes?.["service.version"] ??
+ null,
+ modelParameters: this.extractModelParameters(attributes) as any,
+ model: this.extractModelName(attributes),
+ promptName:
+ attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME] ??
+ attributes["langfuse.prompt.name"] ??
+ null,
+ promptVersion:
+ attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION] ??
+ attributes["langfuse.prompt.version"] ??
+ null,
+ usageDetails: this.extractUsageDetails(
+ attributes,
+ isLangfuseSDKSpans,
+ ) as any,
+ costDetails: this.extractCostDetails(
+ attributes,
+ isLangfuseSDKSpans,
+ ) as any,
+ ...this.extractInputAndOutput(span?.events ?? [], attributes),
+ };
+
+ const isGeneration =
+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] ===
+ "generation" ||
+ Boolean(observation.model) ||
+ ("openinference.span.kind" in attributes &&
+ attributes["openinference.span.kind"] === "LLM");
+
+ const isEvent =
+ attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] === "event";
+
+ return {
+ id: randomUUID(),
+ type: isGeneration
+ ? "generation-create"
+ : isEvent
+ ? "event-create"
+ : "span-create",
+ timestamp: new Date().toISOString(),
+ body: observation,
+ } as unknown as IngestionEventType;
+ }
+
+ private validatePublicKey(
+ isLangfuseSDKSpans: boolean,
+ scopeAttributes: Record<string, unknown>,
+ ): void {
+ if (
+ isLangfuseSDKSpans &&
+ (!this.publicKey ||
+ (scopeAttributes["public_key"] as unknown as string) !== this.publicKey)
+ ) {
+ throw new ForbiddenError(
+ `Langfuse OTEL SDK span has different public key '${scopeAttributes["public_key"]}' than used for authentication '${this.publicKey}'. Discarding span.`,
+ );
+ }
+ }
+
+ private hasTraceUpdates(attributes: Record<string, unknown>): boolean {
+ return [
+ LangfuseOtelSpanAttributes.TRACE_NAME,
+ LangfuseOtelSpanAttributes.TRACE_INPUT,
+ LangfuseOtelSpanAttributes.TRACE_OUTPUT,
+ LangfuseOtelSpanAttributes.TRACE_METADATA,
+ LangfuseOtelSpanAttributes.TRACE_USER_ID,
+ LangfuseOtelSpanAttributes.TRACE_SESSION_ID,
+ LangfuseOtelSpanAttributes.TRACE_PUBLIC,
+ LangfuseOtelSpanAttributes.TRACE_TAGS,
+ ].some((traceAttribute) => Boolean(attributes[traceAttribute]));
+ }
+
+ private extractResourceAttributes(
+ resourceSpan: any,
+ ): Record<string, unknown> {
+ return (
+ resourceSpan?.resource?.attributes?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(attr.value);
+ return acc;
+ }, {}) ?? {}
+ );
+ }
+
+ private extractScopeAttributes(scopeSpan: any): Record<string, unknown> {
+ return (
+ scopeSpan?.scope?.attributes?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(attr.value);
+ return acc;
+ }, {}) ?? {}
+ );
+ }
+
+ private extractSpanAttributes(span: any): Record<string, unknown> {
+ return (
+ span?.attributes?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(attr.value);
+ return acc;
+ }, {}) ?? {}
+ );
+ }
+
+ private convertValueToPlainJavascript(value: Record<string, any>): any {
+ if (value.stringValue !== undefined) {
+ return value.stringValue;
+ }
+ if (value.doubleValue !== undefined) {
+ return value.doubleValue;
+ }
+ if (value.boolValue !== undefined) {
+ return value.boolValue;
+ }
+ if (value.arrayValue && value.arrayValue.values !== undefined) {
+ return value.arrayValue.values.map((v: any) =>
+ this.convertValueToPlainJavascript(v),
+ );
+ }
+ if (value.intValue && value.intValue.high === 0) {
+ return value.intValue.low;
+ }
+ if (value.intValue && typeof value.intValue === "number") {
+ return value.intValue;
+ }
+ if (
+ value.intValue &&
+ value.intValue.high === -1 &&
+ value.intValue.low === -1
+ ) {
+ return -1;
+ }
+ if (value.intValue && value.intValue.high !== 0) {
+ return value.intValue.high * Math.pow(2, 32) + value.intValue.low;
+ }
+ return JSON.stringify(value);
+ }
+
+ private convertKeyPathToNestedObject(
+ input: Record<string, unknown>,
+ prefix: string,
+ ): any {
+ if (input[prefix]) {
+ return input[prefix];
+ }
+
+ const keys = Object.keys(input).map((key) => key.replace(`${prefix}.`, ""));
+ const useArray = keys.some((key) => key.match(/^\d+\./));
+
+ if (useArray) {
+ const result: any[] = [];
+ for (const key of keys) {
+ const [index, ikey] = key.split(".", 2) as [number, string];
+ if (!result[index]) {
+ result[index] = {};
+ }
+ result[index][ikey] = input[`${prefix}.${index}.${ikey}`];
+ }
+ return result;
+ } else {
+ const result: Record<string, unknown> = {};
+ for (const key of keys) {
+ result[key] = input[`${prefix}.${key}`];
+ }
+ return result;
+ }
+ }
+
+ private extractInputAndOutput(
+ events: any[],
+ attributes: Record<string, unknown>,
+ domain?: "trace" | "observation",
+ ): { input: any; output: any } {
+ let input = null;
+ let output = null;
+
+ // Langfuse
+ input =
+ domain === "trace" && attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]
+ ? attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]
+ : attributes[LangfuseOtelSpanAttributes.OBSERVATION_INPUT];
+ output =
+ domain === "trace" && attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT]
+ ? attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT]
+ : attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT];
+
+ if (input != null || output != null) {
+ return { input, output };
+ }
+
+ const inputEvents = events.filter(
+ (event: Record<string, unknown>) =>
+ event.name === "gen_ai.system.message" ||
+ event.name === "gen_ai.user.message" ||
+ event.name === "gen_ai.assistant.message" ||
+ event.name === "gen_ai.tool.message",
+ );
+
+ const outputEvents = events.filter(
+ (event: Record<string, unknown>) => event.name === "gen_ai.choice",
+ );
+
+ if (inputEvents.length > 0 || outputEvents.length > 0) {
+ const processedInput =
+ inputEvents.length > 0
+ ? inputEvents.map((event: any) => {
+ const eventAttributes =
+ event.attributes?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(
+ attr.value,
+ );
+ return acc;
+ }, {}) ?? {};
+
+ return {
+ role: event.name.replace("gen_ai.", "").replace(".message", ""),
+ ...eventAttributes,
+ };
+ })
+ : null;
+
+ const processedOutput =
+ outputEvents.length > 0
+ ? outputEvents.map((event: any) => {
+ const eventAttributes =
+ event.attributes?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(
+ attr.value,
+ );
+ return acc;
+ }, {}) ?? {};
+
+ return eventAttributes;
+ })
+ : null;
+
+ return {
+ input: processedInput,
+ output:
+ processedOutput && processedOutput.length === 1
+ ? processedOutput[0]
+ : processedOutput,
+ };
+ }
+
+ // Legacy semantic kernel event definitions
+ input = events.find(
+ (event: Record<string, unknown>) =>
+ event.name === "gen_ai.content.prompt",
+ )?.attributes;
+
+ output = events.find(
+ (event: Record<string, unknown>) =>
+ event.name === "gen_ai.content.completion",
+ )?.attributes;
+
+ if (input || output) {
+ input =
+ input?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(attr.value);
+ return acc;
+ }, {}) ?? {};
+ output =
+ output?.reduce((acc: any, attr: any) => {
+ acc[attr.key] = this.convertValueToPlainJavascript(attr.value);
+ return acc;
+ }, {}) ?? {};
+
+ const { input: eventInput } = this.extractInputAndOutput([], input);
+ const { output: eventOutput } = this.extractInputAndOutput([], output);
+ return { input: eventInput || input, output: eventOutput || output };
+ }
+
+ // Google Vertex AI Agent-Developer-Kit (ADK)
+ input = attributes["gcp.vertex.agent.llm_request"];
+ output = attributes["gcp.vertex.agent.llm_response"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // Logfire uses `prompt` and `all_messages_events` property on spans
+ input = attributes["prompt"];
+ output = attributes["all_messages_events"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // Logfire uses single `events` array for GenAI events
+ const eventsArray = attributes["events"];
+ if (typeof eventsArray === "string" || Array.isArray(eventsArray)) {
+ let events = eventsArray as any[];
+ if (typeof eventsArray === "string") {
+ try {
+ events = JSON.parse(eventsArray);
+ } catch (e) {
+ events = [];
+ }
+ }
+
+ const choiceEvent = events.find(
+ (event) => event["event.name"] === "gen_ai.choice",
+ );
+ const inputEvents = events.filter(
+ (event) => event["event.name"] !== "gen_ai.choice",
+ );
+
+ if (choiceEvent || inputEvents.length > 0) {
+ return {
+ input: inputEvents.length > 0 ? inputEvents : null,
+ output: choiceEvent || null,
+ };
+ }
+ }
+
+ // MLFlow sets mlflow.spanInputs and mlflow.spanOutputs
+ input = attributes["mlflow.spanInputs"];
+ output = attributes["mlflow.spanOutputs"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // TraceLoop sets traceloop.entity.input and traceloop.entity.output
+ input = attributes["traceloop.entity.input"];
+ output = attributes["traceloop.entity.output"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // SmolAgents sets input.value and output.value
+ input = attributes["input.value"];
+ output = attributes["output.value"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // Pydantic and Pipecat uses input and output
+ input = attributes["input"];
+ output = attributes["output"];
+ if (input || output) {
+ return { input, output };
+ }
+
+ // TraceLoop uses attributes property
+ const inputAttributes = Object.keys(attributes).filter((key) =>
+ key.startsWith("gen_ai.prompt"),
+ );
+ const outputAttributes = Object.keys(attributes).filter((key) =>
+ key.startsWith("gen_ai.completion"),
+ );
+ if (inputAttributes.length > 0 || outputAttributes.length > 0) {
+ input = inputAttributes.reduce((acc: any, key) => {
+ acc[key] = attributes[key];
+ return acc;
+ }, {});
+ output = outputAttributes.reduce((acc: any, key) => {
+ acc[key] = attributes[key];
+ return acc;
+ }, {});
+ return {
+ input: this.convertKeyPathToNestedObject(input, "gen_ai.prompt"),
+ output: this.convertKeyPathToNestedObject(output, "gen_ai.completion"),
+ };
+ }
+
+ return { input: null, output: null };
+ }
+
+ private extractEnvironment(
+ attributes: Record<string, unknown>,
+ resourceAttributes: Record<string, unknown>,
+ ): string {
+ const environmentAttributeKeys = [
+ LangfuseOtelSpanAttributes.ENVIRONMENT,
+ "deployment.environment.name",
+ "deployment.environment",
+ ];
+
+ for (const key of environmentAttributeKeys) {
+ if (resourceAttributes[key]) {
+ return resourceAttributes[key] as string;
+ }
+ if (attributes[key]) {
+ return attributes[key] as string;
+ }
+ }
+
+ return "default";
+ }
+
+ private extractName(
+ spanName: string,
+ attributes: Record<string, unknown>,
+ ): string {
+ const nameKeys = ["logfire.msg"];
+ for (const key of nameKeys) {
+ if (attributes[key]) {
+ return typeof attributes[key] === "string"
+ ? (attributes[key] as string)
+ : JSON.stringify(attributes[key]);
+ }
+ }
+
+ return spanName;
+ }
+
+ private extractMetadata(
+ attributes: Record<string, unknown>,
+ domain: "trace" | "observation",
+ ): Record<string, unknown> {
+ let metadata: Record<string, unknown> = {};
+
+ const metadataKeyPrefix =
+ domain === "observation"
+ ? LangfuseOtelSpanAttributes.OBSERVATION_METADATA
+ : LangfuseOtelSpanAttributes.TRACE_METADATA;
+
+ const langfuseMetadataAttribute =
+ attributes[metadataKeyPrefix] || attributes["langfuse.metadata"];
+
+ if (langfuseMetadataAttribute) {
+ try {
+ if (typeof langfuseMetadataAttribute === "string") {
+ metadata = JSON.parse(langfuseMetadataAttribute as string);
+ } else if (typeof langfuseMetadataAttribute === "object") {
+ metadata = langfuseMetadataAttribute as Record<string, unknown>;
+ }
+ } catch (e) {
+ // Continue with nested metadata extraction
+ }
+ }
+
+ const langfuseMetadata: Record<string, unknown> = {};
+
+ for (const [key, value] of Object.entries(attributes)) {
+ for (const prefix of [metadataKeyPrefix, "langfuse.metadata"]) {
+ if (key.startsWith(`${prefix}.`)) {
+ const newKey = key.replace(`${prefix}.`, "");
+ langfuseMetadata[newKey] = value;
+ }
+ }
+ }
+
+ return {
+ ...metadata,
+ ...langfuseMetadata,
+ };
+ }
+
+ private extractUserId(
+ attributes: Record<string, unknown>,
+ ): string | undefined {
+ const userIdKeys = ["langfuse.user.id", "user.id"];
+
+ for (const key of userIdKeys) {
+ if (attributes[key]) {
+ return typeof attributes[key] === "string"
+ ? (attributes[key] as string)
+ : JSON.stringify(attributes[key]);
+ }
+ }
+ }
+
+ private extractSessionId(
+ attributes: Record<string, unknown>,
+ ): string | undefined {
+ const userIdKeys = ["langfuse.session.id", "session.id"];
+
+ for (const key of userIdKeys) {
+ if (attributes[key]) {
+ return typeof attributes[key] === "string"
+ ? (attributes[key] as string)
+ : JSON.stringify(attributes[key]);
+ }
+ }
+ }
+
+ private extractModelParameters(
+ attributes: Record<string, unknown>,
+ ): Record<string, unknown> {
+ if (attributes[LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]) {
+ try {
+ return JSON.parse(
+ attributes[
+ LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS
+ ] as string,
+ );
+ } catch {}
+ }
+
+ if (attributes["llm.invocation_parameters"]) {
+ try {
+ return JSON.parse(attributes["llm.invocation_parameters"] as string);
+ } catch (e) {
+ // fallthrough
+ }
+ }
+
+ if (attributes["model_config"]) {
+ try {
+ return JSON.parse(attributes["model_config"] as string);
+ } catch (e) {
+ // fallthrough
+ }
+ }
+
+ const modelParameters = Object.keys(attributes).filter((key) =>
+ key.startsWith("gen_ai.request."),
+ );
+
+ return modelParameters.reduce((acc: any, key) => {
+ const modelParamKey = key.replace("gen_ai.request.", "");
+ if (modelParamKey !== "model") {
+ acc[modelParamKey] = attributes[key];
+ }
+ return acc;
+ }, {});
+ }
+
+ private extractModelName(
+ attributes: Record<string, unknown>,
+ ): string | undefined {
+ const modelNameKeys = [
+ LangfuseOtelSpanAttributes.OBSERVATION_MODEL,
+ "gen_ai.request.model",
+ "gen_ai.response.model",
+ "llm.model_name",
+ "model",
+ ];
+ for (const key of modelNameKeys) {
+ if (attributes[key]) {
+ return typeof attributes[key] === "string"
+ ? (attributes[key] as string)
+ : JSON.stringify(attributes[key]);
+ }
+ }
+ }
+
+ private extractUsageDetails(
+ attributes: Record<string, unknown>,
+ isLangfuseSDKSpan: boolean,
+ ): Record<string, unknown> {
+ if (isLangfuseSDKSpan) {
+ try {
+ return JSON.parse(
+ attributes[
+ LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS
+ ] as string,
+ );
+ } catch {}
+ }
+
+ const usageDetails = Object.keys(attributes).filter(
+ (key) =>
+ (key.startsWith("gen_ai.usage.") && key !== "gen_ai.usage.cost") ||
+ key.startsWith("llm.token_count"),
+ );
+
+ const usageDetailKeyMapping: Record<string, string> = {
+ prompt_tokens: "input",
+ completion_tokens: "output",
+ total_tokens: "total",
+ input_tokens: "input",
+ output_tokens: "output",
+ prompt: "input",
+ completion: "output",
+ };
+
+ return usageDetails.reduce((acc: any, key) => {
+ const usageDetailKey = key
+ .replace("gen_ai.usage.", "")
+ .replace("llm.token_count.", "");
+ const mappedUsageDetailKey =
+ usageDetailKeyMapping[usageDetailKey] ?? usageDetailKey;
+ const value = Number(attributes[key]);
+ if (!Number.isNaN(value)) {
+ acc[mappedUsageDetailKey] = value;
+ }
+ return acc;
+ }, {});
+ }
+
+ private extractCostDetails(
+ attributes: Record<string, unknown>,
+ isLangfuseSDKSpan: boolean,
+ ): Record<string, unknown> {
+ if (isLangfuseSDKSpan) {
+ try {
+ return JSON.parse(
+ attributes[
+ LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS
+ ] as string,
+ );
+ } catch {}
+ }
+
+ if (attributes["gen_ai.usage.cost"]) {
+ return { total: attributes["gen_ai.usage.cost"] };
+ }
+ return {};
+ }
+
+ private extractCompletionStartTime(attributes: Record<string, unknown>) {
+ try {
+ return JSON.parse(
+ attributes[
+ LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME
+ ] as string,
+ );
+ } catch {}
+
+ return null;
+ }
+
+ private extractTags(attributes: Record<string, unknown>): string[] {
+ const tagsValue =
+ attributes[LangfuseOtelSpanAttributes.TRACE_TAGS] ||
+ attributes["langfuse.tags"];
+
+ if (tagsValue === undefined || tagsValue === null) {
+ return [];
+ }
+
+ if (Array.isArray(tagsValue)) {
+ return tagsValue.map((tag) => String(tag));
+ }
+
+ if (typeof tagsValue === "string" && tagsValue.trim().startsWith("[")) {
+ try {
+ const parsedTags = JSON.parse(tagsValue);
+ if (Array.isArray(parsedTags)) {
+ return parsedTags.map((tag) => String(tag));
+ }
+ } catch (e) {
+ // Continue with other methods
+ }
+ }
+
+ if (typeof tagsValue === "string" && tagsValue.includes(",")) {
+ return tagsValue.split(",").map((tag) => tag.trim());
+ }
+
+ if (typeof tagsValue === "string") {
+ return [tagsValue];
+ }
+
+ return [];
+ }
+
+ /**
+ * Get a set of trace IDs that have been seen recently (from Redis cache).
+ * Returns a Set of trace IDs that should not trigger new trace creation.
+ */
+ private async getSeenTracesSet(resourceSpans: unknown): Promise<Set<string>> {
+ if (!redis) {
+ logger.warn("Redis client not available");
+ return new Set();
+ }
+
+ const traceIds: Set<string> = new Set();
+ if (Array.isArray(resourceSpans)) {
+ resourceSpans.forEach((resourceSpan) => {
+ for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {
+ for (const span of scopeSpan?.spans ?? []) {
+ traceIds.add(
+ Buffer.from(span.traceId?.data ?? span.traceId).toString("hex"),
+ );
+ }
+ }
+ });
+ }
+
+ try {
+ const results = await Promise.all(
+ [...traceIds].map(async (traceId) => {
+ const key = `langfuse:project:${this.projectId}:trace:${traceId}:seen`;
+ const TTLSeconds = 600; // 10 minutes
+ const result = await redis?.call(
+ "SET",
+ key,
+ "1",
+ "NX",
+ "EX",
+ TTLSeconds,
+ );
+
+ return {
+ traceId: traceId,
+ wasSeen: result !== "OK", // Redis returns "OK" if key did not exist, i.e. trace was NOT seen in last TTL seconds
+ };
+ }),
+ );
+
+ const seenTraceIds: Set<string> = new Set();
+ results.forEach((r) => {
+ if (r.wasSeen) {
+ seenTraceIds.add(r.traceId);
+ }
+ });
+
+ return seenTraceIds;
+ } catch (error) {
+ // Redis error will be captured by parent span, just log and continue
+ logger.error("Redis operation failed in getSeenTracesSet:", error);
+
+ // Return empty set to continue processing (fail-safe behavior)
+ return new Set();
+ }
+ }
+
+ /**
+ * Convert OpenTelemetry nano timestamp to ISO string.
+ * Handles various timestamp formats: string, number, or object with high/low bits.
+ */
+ public static convertNanoTimestampToISO(
+ timestamp:
+ | number
+ | string
+ | {
+ high: number;
+ low: number;
+ },
+ ): string {
+ if (typeof timestamp === "string") {
+ return new Date(Number(BigInt(timestamp) / BigInt(1e6))).toISOString();
+ }
+ if (typeof timestamp === "number") {
+ return new Date(timestamp / 1e6).toISOString();
+ }
+
+ // Convert high and low to BigInt
+ const highBits = BigInt(timestamp.high) << BigInt(32);
+ const lowBits = BigInt(timestamp.low >>> 0);
+
+ // Combine high and low bits
+ const nanosBigInt = highBits | lowBits;
+
+ // Convert nanoseconds to milliseconds for JavaScript Date
+ const millisBigInt = nanosBigInt / BigInt(1000000);
+ return new Date(Number(millisBigInt)).toISOString();
+ }
+
+ /**
+ * Count the total number of spans across all resource spans.
+ * Returns -1 if an error occurs during counting to avoid throwing exceptions.
+ */
+ private getTotalSpanCount(resourceSpans: ResourceSpan[]): number {
+ try {
+ if (!Array.isArray(resourceSpans)) {
+ return 0;
+ }
+
+ return resourceSpans.reduce((total, resourceSpan) => {
+ if (!resourceSpan?.scopeSpans) {
+ return total;
+ }
+
+ return (
+ total +
+ resourceSpan.scopeSpans.reduce((count, scopeSpan) => {
+ return count + (scopeSpan?.spans?.length ?? 0);
+ }, 0)
+ );
+ }, 0);
+ } catch (error) {
+ // Log error but never throw - return -1 to indicate counting failed
+ logger.warn("Failed to count total spans:", error);
+ return -1;
+ }
+ }
+}
diff --git a/web/src/features/otel/server/index.ts b/web/src/features/otel/server/index.ts
deleted file mode 100644
index af72002f8a..0000000000
--- a/web/src/features/otel/server/index.ts
+++ /dev/null
@@ -1,839 +0,0 @@
-import { type IngestionEventType } from "@langfuse/shared/src/server";
-import { randomUUID } from "crypto";
-import { ForbiddenError, ObservationLevel } from "@langfuse/shared";
-import { LangfuseOtelSpanAttributes } from "./attributes";
-
-export const convertNanoTimestampToISO = (
- timestamp:
- | number
- | string
- | {
- high: number;
- low: number;
- },
-) => {
- if (typeof timestamp === "string") {
- return new Date(Number(BigInt(timestamp) / BigInt(1e6))).toISOString();
- }
- if (typeof timestamp === "number") {
- return new Date(timestamp / 1e6).toISOString();
- }
-
- // Convert high and low to BigInt
- const highBits = BigInt(timestamp.high) << BigInt(32);
- const lowBits = BigInt(timestamp.low >>> 0);
-
- // Combine high and low bits
- const nanosBigInt = highBits | lowBits;
-
- // Convert nanoseconds to milliseconds for JavaScript Date
- const millisBigInt = nanosBigInt / BigInt(1000000);
- return new Date(Number(millisBigInt)).toISOString();
-};
-
-const convertValueToPlainJavascript = (value: Record<string, any>): any => {
- if (value.stringValue !== undefined) {
- return value.stringValue;
- }
- if (value.doubleValue !== undefined) {
- return value.doubleValue;
- }
- if (value.boolValue !== undefined) {
- return value.boolValue;
- }
- if (value.arrayValue && value.arrayValue.values !== undefined) {
- return value.arrayValue.values.map(convertValueToPlainJavascript);
- }
- if (value.intValue && value.intValue.high === 0) {
- return value.intValue.low;
- }
- if (value.intValue && typeof value.intValue === "number") {
- return value.intValue;
- }
- if (
- value.intValue &&
- value.intValue.high === -1 &&
- value.intValue.low === -1
- ) {
- return -1;
- }
- if (value.intValue && value.intValue.high !== 0) {
- // As JavaScript has native 64-bit support, we try the conversion
- return value.intValue.high * Math.pow(2, 32) + value.intValue.low;
- }
- return JSON.stringify(value);
-};
-
-/**
- * convertKeyPathToNestedObject accepts the result of the naive body parsing and translates it into
- * a nested object. In addition, we remove the prefix from the keys to make them easier to read.
- * Array Example:
- * // Input
- * {
- * gen_ai.completion.0.content: "Hello World",
- * gen_ai.completion.0.role: "assistant"
- * }
- * // Output
- * [{ content: "Hello World", role: "assistant" }]
- *
- * Object Example:
- * // Input
- * {
- * gen_ai.completion.content: "Hello World",
- * gen_ai.completion.role: "assistant"
- * }
- * // Output
- * { content: "Hello World", role: "assistant" }
- *
- * Plain Example:
- * // Input
- * { gen_ai.completion: "Hello World" }
- * // Output
- * "Hello World"
- */
-const convertKeyPathToNestedObject = (
- input: Record<string, unknown>,
- prefix: string,
-): any => {
- // Handle base-case where we only have the prefix as key
- if (input[prefix]) {
- return input[prefix];
- }
-
- // Get all keys and strip the prefix
- const keys = Object.keys(input).map((key) => key.replace(`${prefix}.`, ""));
-
- // If one of the key starts with a number, we assume it's an array
- const useArray = keys.some((key) => key.match(/^\d+\./));
- if (useArray) {
- const result: any[] = [];
- for (const key of keys) {
- const [index, ikey] = key.split(".", 2) as [number, string];
- if (!result[index]) {
- result[index] = {};
- }
- result[index][ikey] = input[`${prefix}.${index}.${ikey}`];
- }
- return result;
- } else {
- const result: Record<string, unknown> = {};
- for (const key of keys) {
- result[key] = input[`${prefix}.${key}`];
- }
- return result;
- }
-};
-
-const extractInputAndOutput = (
- events: any[],
- attributes: Record<string, unknown>,
- domain?: "trace" | "observation",
-): { input: any; output: any } => {
- let input = null;
- let output = null;
-
- // Langfuse
- input =
- domain === "trace" && attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]
- ? attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]
- : attributes[LangfuseOtelSpanAttributes.OBSERVATION_INPUT];
- output =
- domain === "trace" && attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT]
- ? attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT]
- : attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT];
-
- if (input != null || output != null) {
- return { input, output };
- }
-
- const inputEvents = events.filter(
- (event: Record<string, unknown>) =>
- event.name === "gen_ai.system.message" ||
- event.name === "gen_ai.user.message" ||
- event.name === "gen_ai.assistant.message" ||
- event.name === "gen_ai.tool.message",
- );
-
- const outputEvents = events.filter(
- (event: Record<string, unknown>) => event.name === "gen_ai.choice",
- );
-
- if (inputEvents.length > 0 || outputEvents.length > 0) {
- // Convert events to a structured format
- const processedInput =
- inputEvents.length > 0
- ? inputEvents.map((event: any) => {
- const eventAttributes =
- event.attributes?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
-
- return {
- role: event.name.replace("gen_ai.", "").replace(".message", ""),
- ...eventAttributes,
- };
- })
- : null;
-
- const processedOutput =
- outputEvents.length > 0
- ? outputEvents.map((event: any) => {
- const eventAttributes =
- event.attributes?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
-
- return eventAttributes;
- })
- : null;
-
- return {
- input: processedInput,
- output:
- processedOutput && processedOutput.length === 1
- ? processedOutput[0]
- : processedOutput,
- };
- }
-
- // Check legacy semantic kernel event definitions
- input = events.find(
- (event: Record<string, unknown>) => event.name === "gen_ai.content.prompt",
- )?.attributes;
-
- output = events.find(
- (event: Record<string, unknown>) =>
- event.name === "gen_ai.content.completion",
- )?.attributes;
-
- if (input || output) {
- input =
- input?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
- output =
- output?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
- // Here, we are interested in the attributes of the event. Usually gen_ai.prompt and gen_ai.completion.
- // We can use the current function again to extract them from the event attributes.
- const { input: eventInput } = extractInputAndOutput([], input);
- const { output: eventOutput } = extractInputAndOutput([], output);
- return { input: eventInput || input, output: eventOutput || output };
- }
-
- // Google Vertex AI Agent-Developer-Kit (ADK)
- input = attributes["gcp.vertex.agent.llm_request"];
- output = attributes["gcp.vertex.agent.llm_response"];
- if (input || output) {
- return {
- input: input,
- output: output,
- };
- }
-
- // Logfire uses `prompt` and `all_messages_events` property on spans
- input = attributes["prompt"];
- output = attributes["all_messages_events"];
- if (input || output) {
- return { input, output };
- }
-
- // Logfire uses single `events` array for GenAI events.
- const eventsArray = attributes["events"];
- if (typeof eventsArray === "string" || Array.isArray(eventsArray)) {
- let events = eventsArray as any[];
- if (typeof eventsArray === "string") {
- try {
- events = JSON.parse(eventsArray);
- } catch (e) {
- // fallthrough
- events = [];
- }
- }
-
- // Find the gen_ai.choice event for output
- const choiceEvent = events.find(
- (event) => event["event.name"] === "gen_ai.choice",
- );
- // All other events are considered input
- const inputEvents = events.filter(
- (event) => event["event.name"] !== "gen_ai.choice",
- );
-
- if (choiceEvent || inputEvents.length > 0) {
- return {
- input: inputEvents.length > 0 ? inputEvents : null,
- output: choiceEvent || null,
- };
- }
- }
-
- // MLFlow sets mlflow.spanInputs and mlflow.spanOutputs
- input = attributes["mlflow.spanInputs"];
- output = attributes["mlflow.spanOutputs"];
- if (input || output) {
- return { input, output };
- }
-
- // TraceLoop sets traceloop.entity.input and traceloop.entity.output
- input = attributes["traceloop.entity.input"];
- output = attributes["traceloop.entity.output"];
- if (input || output) {
- return { input, output };
- }
-
- // SmolAgents sets input.value and output.value
- input = attributes["input.value"];
- output = attributes["output.value"];
- if (input || output) {
- return { input, output };
- }
-
- // Pydantic and Pipecat uses input and output
- input = attributes["input"];
- output = attributes["output"];
- if (input || output) {
- return { input, output };
- }
-
- // TraceLoop uses attributes property
- const inputAttributes = Object.keys(attributes).filter((key) =>
- key.startsWith("gen_ai.prompt"),
- );
- const outputAttributes = Object.keys(attributes).filter((key) =>
- key.startsWith("gen_ai.completion"),
- );
- if (inputAttributes.length > 0 || outputAttributes.length > 0) {
- input = inputAttributes.reduce((acc: any, key) => {
- acc[key] = attributes[key];
- return acc;
- }, {});
- output = outputAttributes.reduce((acc: any, key) => {
- acc[key] = attributes[key];
- return acc;
- }, {});
- return {
- input: convertKeyPathToNestedObject(input, "gen_ai.prompt"),
- output: convertKeyPathToNestedObject(output, "gen_ai.completion"),
- };
- }
-
- return { input: null, output: null };
-};
-
-const extractEnvironment = (
- attributes: Record<string, unknown>,
- resourceAttributes: Record<string, unknown>,
-): string => {
- const environmentAttributeKeys = [
- LangfuseOtelSpanAttributes.ENVIRONMENT,
- "deployment.environment.name",
- "deployment.environment",
- ];
-
- for (const key of environmentAttributeKeys) {
- if (resourceAttributes[key]) {
- return resourceAttributes[key] as string;
- }
- if (attributes[key]) {
- return attributes[key] as string;
- }
- }
-
- return "default";
-};
-
-const extractName = (
- spanName: string,
- attributes: Record<string, unknown>,
-): string => {
- const nameKeys = ["logfire.msg"];
- for (const key of nameKeys) {
- if (attributes[key]) {
- return typeof attributes[key] === "string"
- ? (attributes[key] as string)
- : JSON.stringify(attributes[key]);
- }
- }
-
- return spanName;
-};
-
-const extractMetadata = (
- attributes: Record<string, unknown>,
- domain: "trace" | "observation",
-): Record<string, unknown> => {
- // Extract top-level metadata object if available
- let metadata: Record<string, unknown> = {};
-
- const metadataKeyPrefix =
- domain === "observation"
- ? LangfuseOtelSpanAttributes.OBSERVATION_METADATA
- : LangfuseOtelSpanAttributes.TRACE_METADATA;
-
- const langfuseMetadataAttribute =
- attributes[metadataKeyPrefix] || attributes["langfuse.metadata"];
-
- if (langfuseMetadataAttribute) {
- try {
- // If it's a string (JSON), parse it
- if (typeof langfuseMetadataAttribute === "string") {
- metadata = JSON.parse(langfuseMetadataAttribute as string);
- }
- // If it's already an object, use it
- else if (typeof langfuseMetadataAttribute === "object") {
- metadata = langfuseMetadataAttribute as Record<string, unknown>;
- }
- } catch (e) {
- // If parsing fails, continue with nested metadata extraction
- }
- }
-
- // Extract metadata from langfuse.metadata.* keys
- const langfuseMetadata: Record<string, unknown> = {};
-
- for (const [key, value] of Object.entries(attributes)) {
- for (const prefix of [metadataKeyPrefix, "langfuse.metadata"]) {
- if (key.startsWith(`${prefix}.`)) {
- const newKey = key.replace(`${prefix}.`, "");
- langfuseMetadata[newKey] = value;
- }
- }
- }
-
- return {
- ...metadata,
- ...langfuseMetadata,
- };
-};
-
-const extractUserId = (
- attributes: Record<string, unknown>,
-): string | undefined => {
- const userIdKeys = ["langfuse.user.id", "user.id"];
-
- for (const key of userIdKeys) {
- if (attributes[key]) {
- return typeof attributes[key] === "string"
- ? (attributes[key] as string)
- : JSON.stringify(attributes[key]);
- }
- }
-};
-
-const extractSessionId = (
- attributes: Record<string, unknown>,
-): string | undefined => {
- const userIdKeys = ["langfuse.session.id", "session.id"];
-
- for (const key of userIdKeys) {
- if (attributes[key]) {
- return typeof attributes[key] === "string"
- ? (attributes[key] as string)
- : JSON.stringify(attributes[key]);
- }
- }
-};
-
-const extractModelParameters = (
- attributes: Record<string, unknown>,
-): Record<string, unknown> => {
- // Langfuse
- if (attributes[LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS]) {
- try {
- return JSON.parse(
- attributes[
- LangfuseOtelSpanAttributes.OBSERVATION_MODEL_PARAMETERS
- ] as string,
- );
- } catch {}
- }
-
- // If we get invocation parameters, we use them as they are
- if (attributes["llm.invocation_parameters"]) {
- try {
- return JSON.parse(attributes["llm.invocation_parameters"] as string);
- } catch (e) {
- // fallthrough
- }
- }
-
- if (attributes["model_config"]) {
- try {
- return JSON.parse(attributes["model_config"] as string);
- } catch (e) {
- // fallthrough
- }
- }
-
- const modelParameters = Object.keys(attributes).filter((key) =>
- key.startsWith("gen_ai.request."),
- );
-
- return modelParameters.reduce((acc: any, key) => {
- const modelParamKey = key.replace("gen_ai.request.", "");
- // avoid double-reporting the model name, already included in native model attribute
- if (modelParamKey !== "model") {
- acc[modelParamKey] = attributes[key];
- }
- return acc;
- }, {});
-};
-
-const extractModelName = (
- attributes: Record<string, unknown>,
-): string | undefined => {
- const modelNameKeys = [
- LangfuseOtelSpanAttributes.OBSERVATION_MODEL,
- "gen_ai.request.model",
- "gen_ai.response.model",
- "llm.model_name",
- "model",
- ];
- for (const key of modelNameKeys) {
- if (attributes[key]) {
- return typeof attributes[key] === "string"
- ? (attributes[key] as string)
- : JSON.stringify(attributes[key]);
- }
- }
-};
-
-const extractUsageDetails = (
- attributes: Record<string, unknown>,
- isLangfuseSDKSpan: boolean,
-): Record<string, unknown> => {
- if (isLangfuseSDKSpan) {
- try {
- return JSON.parse(
- attributes[
- LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS
- ] as string,
- );
- } catch {}
- }
-
- const usageDetails = Object.keys(attributes).filter(
- (key) =>
- (key.startsWith("gen_ai.usage.") && key !== "gen_ai.usage.cost") ||
- key.startsWith("llm.token_count"),
- );
-
- const usageDetailKeyMapping: Record<string, string> = {
- prompt_tokens: "input",
- completion_tokens: "output",
- total_tokens: "total",
- input_tokens: "input",
- output_tokens: "output",
- prompt: "input",
- completion: "output",
- };
-
- return usageDetails.reduce((acc: any, key) => {
- const usageDetailKey = key
- .replace("gen_ai.usage.", "")
- .replace("llm.token_count.", "");
- const mappedUsageDetailKey =
- usageDetailKeyMapping[usageDetailKey] ?? usageDetailKey;
- // Cast the respective key to a number
- const value = Number(attributes[key]);
- if (!Number.isNaN(value)) {
- acc[mappedUsageDetailKey] = value;
- }
- return acc;
- }, {});
-};
-
-const extractCostDetails = (
- attributes: Record<string, unknown>,
- isLangfuseSDKSpan: boolean,
-): Record<string, unknown> => {
- if (isLangfuseSDKSpan) {
- try {
- return JSON.parse(
- attributes[
- LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS
- ] as string,
- );
- } catch {}
- }
-
- if (attributes["gen_ai.usage.cost"]) {
- return { total: attributes["gen_ai.usage.cost"] };
- }
- return {};
-};
-
-const extractCompletionStartTime = (attributes: Record<string, unknown>) => {
- try {
- return JSON.parse(
- attributes[
- LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME
- ] as string,
- );
- } catch {}
-
- return null;
-};
-
-const extractTags = (attributes: Record<string, unknown>): string[] => {
- const tagsValue =
- attributes[LangfuseOtelSpanAttributes.TRACE_TAGS] ||
- attributes["langfuse.tags"];
-
- // If no tags, return empty array
- if (tagsValue === undefined || tagsValue === null) {
- return [];
- }
-
- // If already an array (converted by convertValueToPlainJavascript)
- if (Array.isArray(tagsValue)) {
- return tagsValue.map((tag) => String(tag));
- }
-
- // If JSON string array
- if (typeof tagsValue === "string" && tagsValue.trim().startsWith("[")) {
- try {
- const parsedTags = JSON.parse(tagsValue);
- if (Array.isArray(parsedTags)) {
- return parsedTags.map((tag) => String(tag));
- }
- } catch (e) {
- // If parsing fails, continue with other methods
- }
- }
-
- // If CSV string
- if (typeof tagsValue === "string" && tagsValue.includes(",")) {
- return tagsValue.split(",").map((tag) => tag.trim());
- }
-
- // If single string value
- if (typeof tagsValue === "string") {
- return [tagsValue];
- }
-
- // Fallback to empty array
- return [];
-};
-
-/**
- * Accepts an OpenTelemetry resourceSpan from a ExportTraceServiceRequest and
- * returns a list of Langfuse events.
- * We use a list type here, because a root span should create a trace, i.e. we
- * may have a 1:N case.
- */
-export const convertOtelSpanToIngestionEvent = (
- resourceSpan: any,
- publicKey?: string,
-): IngestionEventType[] => {
- const resourceAttributes =
- resourceSpan?.resource?.attributes?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
-
- const events: IngestionEventType[] = [];
-
- for (const scopeSpan of resourceSpan?.scopeSpans ?? []) {
- const isLangfuseSDKSpans = scopeSpan.scope?.name.startsWith("langfuse-sdk");
-
- const scopeAttributes =
- scopeSpan?.scope?.attributes?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
-
- if (
- isLangfuseSDKSpans &&
- (!publicKey ||
- (scopeAttributes["public_key"] as unknown as string) !== publicKey)
- ) {
- throw new ForbiddenError(
- `Langfuse OTEL SDK span has different public key '${scopeAttributes["public_key"]}' than used for authentication '${publicKey}'. Discarding span.`,
- );
- }
-
- for (const span of scopeSpan?.spans ?? []) {
- const attributes =
- span?.attributes?.reduce((acc: any, attr: any) => {
- acc[attr.key] = convertValueToPlainJavascript(attr.value);
- return acc;
- }, {}) ?? {};
-
- const parentObservationId = span?.parentSpanId
- ? Buffer.from(span.parentSpanId?.data ?? span.parentSpanId).toString(
- "hex",
- )
- : null;
-
- const spanAttributeMetadata = extractMetadata(attributes, "observation");
- const resourceAttributeMetadata = extractMetadata(
- resourceAttributes,
- "trace",
- );
- const startTimeISO = convertNanoTimestampToISO(span.startTimeUnixNano);
- const endTimeISO = convertNanoTimestampToISO(span.endTimeUnixNano);
- const is_root_span =
- !parentObservationId ||
- String(attributes[LangfuseOtelSpanAttributes.AS_ROOT]) === "true";
-
- const spanAttributesInMetadata = Object.fromEntries(
- Object.entries(attributes).map(([key, value]) => [
- key,
- typeof value === "string" ? value : JSON.stringify(value),
- ]),
- );
-
- const hasTraceUpdates = [
- LangfuseOtelSpanAttributes.TRACE_NAME,
- LangfuseOtelSpanAttributes.TRACE_INPUT,
- LangfuseOtelSpanAttributes.TRACE_OUTPUT,
- LangfuseOtelSpanAttributes.TRACE_METADATA,
- LangfuseOtelSpanAttributes.TRACE_USER_ID,
- LangfuseOtelSpanAttributes.TRACE_SESSION_ID,
- LangfuseOtelSpanAttributes.TRACE_PUBLIC,
- LangfuseOtelSpanAttributes.TRACE_TAGS,
- ].some((traceAttribute) => Boolean(attributes[traceAttribute]));
-
- if (is_root_span || hasTraceUpdates) {
- // Create a trace for any root span
- const trace = {
- id: Buffer.from(span.traceId?.data ?? span.traceId).toString("hex"),
- timestamp: startTimeISO,
- name:
- attributes[LangfuseOtelSpanAttributes.TRACE_NAME] ??
- (!parentObservationId
- ? extractName(span.name, attributes)
- : undefined),
- metadata: {
- ...resourceAttributeMetadata,
- ...extractMetadata(attributes, "trace"),
- ...(isLangfuseSDKSpans
- ? {}
- : { attributes: spanAttributesInMetadata }),
- resourceAttributes,
- scope: { ...(scopeSpan.scope || {}), attributes: scopeAttributes },
- },
- version:
- attributes?.[LangfuseOtelSpanAttributes.VERSION] ??
- resourceAttributes?.["service.version"] ??
- null,
- release:
- attributes?.[LangfuseOtelSpanAttributes.RELEASE] ??
- resourceAttributes?.[LangfuseOtelSpanAttributes.RELEASE] ??
- null,
- userId: extractUserId(attributes),
- sessionId: extractSessionId(attributes),
- public:
- attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === true ||
- attributes?.[LangfuseOtelSpanAttributes.TRACE_PUBLIC] === "true" ||
- attributes?.["langfuse.public"] === true ||
- attributes?.["langfuse.public"] === "true",
- tags: extractTags(attributes),
-
- environment: extractEnvironment(attributes, resourceAttributes),
-
- // Input and Output
- ...extractInputAndOutput(span?.events ?? [], attributes, "trace"),
- };
- events.push({
- id: randomUUID(),
- type: "trace-create",
- timestamp: new Date(startTimeISO).toISOString(),
- body: trace,
- });
- }
-
- const observation = {
- // Required fields that must be available
- id: Buffer.from(span.spanId?.data ?? span.spanId).toString("hex"),
- traceId: Buffer.from(span.traceId?.data ?? span.traceId).toString(
- "hex",
- ),
- parentObservationId,
- name: extractName(span.name, attributes),
- startTime: startTimeISO,
- endTime: endTimeISO,
-
- environment: extractEnvironment(attributes, resourceAttributes),
-
- // Additional fields
- completionStartTime: extractCompletionStartTime(attributes),
- metadata: {
- ...resourceAttributeMetadata,
- ...spanAttributeMetadata,
- ...(isLangfuseSDKSpans
- ? {}
- : { attributes: spanAttributesInMetadata }),
- resourceAttributes,
- scope: { ...scopeSpan.scope, attributes: scopeAttributes },
- },
- level:
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] ??
- (span.status?.code === 2
- ? ObservationLevel.ERROR
- : ObservationLevel.DEFAULT),
- statusMessage:
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE] ??
- span.status?.message ??
- null,
- version:
- attributes[LangfuseOtelSpanAttributes.VERSION] ??
- resourceAttributes?.["service.version"] ??
- null,
- modelParameters: extractModelParameters(attributes) as any,
- model: extractModelName(attributes),
-
- promptName:
- attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME] ??
- attributes["langfuse.prompt.name"] ??
- null,
- promptVersion:
- attributes?.[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION] ??
- attributes["langfuse.prompt.version"] ??
- null,
-
- usageDetails: extractUsageDetails(
- attributes,
- isLangfuseSDKSpans,
- ) as any,
- costDetails: extractCostDetails(attributes, isLangfuseSDKSpans) as any,
-
- // Input and Output
- ...extractInputAndOutput(span?.events ?? [], attributes),
- };
-
- // If the span has a model property, we consider it a generation.
- // Just checking for llm.* or gen_ai.* attributes leads to overreporting and wrong
- // aggregations for costs.
- const isGeneration =
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] ===
- "generation" ||
- Boolean(observation.model) ||
- ("openinference.span.kind" in attributes &&
- attributes["openinference.span.kind"] === "LLM");
-
- const isEvent =
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] === "event";
-
- events.push({
- id: randomUUID(),
- type: isGeneration
- ? "generation-create"
- : isEvent
- ? "event-create"
- : "span-create",
- timestamp: new Date().toISOString(),
- body: observation,
- });
- }
- }
-
- return events;
-};
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index 9aaf1dc99b..36bdd1e25c 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -111,7 +111,9 @@ function parseGraph(params: { agentGraphData: AgentGraphDataResponse[] }): {
}
});
- const nodes = [...nodeToParentObservationMap.keys()];
+ const nodes = [
+ ...new Set([...stepToNodeMap.values(), LANGGRAPH_END_NODE_NAME]),
+ ];
const edges = [...stepToNodeMap.entries()]
.sort((a, b) => a[0] - b[0])
.map(([_, node], idx, arr) => ({
diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.ts
index 2eb4000be6..4eb137aeec 100644
--- a/web/src/pages/api/public/otel/v1/traces/index.ts
+++ b/web/src/pages/api/public/otel/v1/traces/index.ts
@@ -7,7 +7,7 @@ import {
} from "@langfuse/shared/src/server";
import { z } from "zod";
import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";
-import { convertOtelSpanToIngestionEvent } from "@/src/features/otel/server";
+import { OtelIngestionProcessor } from "@/src/features/otel/server/OtelIngestionProcessor";
import { gunzip } from "node:zlib";
export const config = {
@@ -89,10 +89,14 @@ export default withMiddlewares({
}
}
- const events: IngestionEventType[] = resourceSpans.flatMap(
- (span: unknown) =>
- convertOtelSpanToIngestionEvent(span, auth.scope.publicKey),
- );
+ // Create and process OTEL resource spans to ingestion events
+ const processor = new OtelIngestionProcessor({
+ projectId: auth.scope.projectId,
+ publicKey: auth.scope.publicKey,
+ });
+ const events: IngestionEventType[] =
+ await processor.processToIngestionEvents(resourceSpans);
+
// We set a delay of 0 for OTel, as we never expect updates.
// We also set the source to "otel" which helps us with metric tracking and skipping list calls for S3.
return processEventBatch(events, auth, 0, "otel");