🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(otel): fix metadata flattening (#12553)
Nimar92997d4f78f2
diff --git a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts b/worker/src/queues/__tests__/otelMetadataProcessing.test.tsnew file mode 100644index 0000000000..7bd2703f48--- /dev/null+++ b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts@@ -0,0 +1,209 @@+/**+ * Tests for OTel metadata processing+ * Flow: ResourceSpan -> processToEvent() -> createEventRecord() -> metadata_names/metadata_raw_values+ *+ * NOTE: The dual-write path (otel-dual-write) uses mapKeys() in SQL which doesn't flatten.+ */+import { describe, it, expect, beforeEach, vi } from "vitest";+import { OtelIngestionProcessor } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { IngestionService } from "../../services/IngestionService";+import * as clickhouseWriterExports from "../../services/ClickhouseWriter";++const mockAddToClickhouseWriter = vi.fn();+vi.mock("../../services/ClickhouseWriter", async (importOriginal) => {+ const original = (await importOriginal()) as object;+ return {+ ...original,+ ClickhouseWriter: {+ getInstance: () => ({+ addToQueue: mockAddToClickhouseWriter,+ }),+ },+ };+});++const mockClickhouseClient = {+ query: async () => ({+ json: async () => [],+ query_id: "test-query-id",+ response_headers: { "x-clickhouse-summary": "[]" },+ }),+};++const ingestionService = new IngestionService(+ null as any,+ prisma,+ clickhouseWriterExports.ClickhouseWriter.getInstance() as any,+ mockClickhouseClient as any,+);++function createNanoTimestamp(nanoTime: bigint): {+ low: number;+ high: number;+ unsigned: boolean;+} {+ const low = Number(nanoTime & BigInt(0xffffffff));+ const high = Number(nanoTime >> BigInt(32));+ return { low, high, unsigned: true };+}++function createBufferId(hexString: string): { type: "Buffer"; data: number[] } {+ const buffer = Buffer.from(hexString, "hex");+ return { type: "Buffer", data: Array.from(buffer) };+}++function buildOtelSpan(params: {+ scopeVersion: string;+ resourceAttrKey: string;+ resourceAttrValue: string;+ scopeAttrKey: string;+ scopeAttrValue: string;+ metadataAttrs: Array<{ key: string; value: Record<string, unknown> }>;+}) {+ return {+ resource: {+ attributes: [+ {+ key: params.resourceAttrKey,+ value: { stringValue: params.resourceAttrValue },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: params.scopeVersion,+ attributes: [+ {+ key: params.scopeAttrKey,+ value: { stringValue: params.scopeAttrValue },+ },+ ],+ },+ spans: [+ {+ traceId: createBufferId("aabbccdd11223344aabbccdd11223344"),+ spanId: createBufferId("1122334455667788"),+ name: "test-span",+ kind: 1,+ startTimeUnixNano: createNanoTimestamp(BigInt(1714488530686000000)),+ endTimeUnixNano: createNanoTimestamp(BigInt(1714488530687000000)),+ attributes: [+ {+ key: "langfuse.observation.type",+ value: { stringValue: "span" },+ },+ ...params.metadataAttrs.map((attr) => ({+ key: `langfuse.observation.metadata.${attr.key}`,+ value: attr.value,+ })),+ ],+ status: {},+ },+ ],+ },+ ],+ };+}++async function processAndCreateEvent(+ otelSpan: ReturnType<typeof buildOtelSpan>,+) {+ const processor = new OtelIngestionProcessor({ projectId: "test-project" });+ const eventInputs = processor.processToEvent([otelSpan]);+ expect(eventInputs.length).toBeGreaterThan(0);++ const eventRecord = await ingestionService.createEventRecord(+ eventInputs[0],+ "test/otel/test.json",+ );++ console.log("metadata_names:", JSON.stringify(eventRecord.metadata_names));+ console.log(+ "metadata_raw_values:",+ JSON.stringify(eventRecord.metadata_raw_values),+ );+ console.log("metadata:", JSON.stringify(eventRecord.metadata));++ const nameToValue = Object.fromEntries(+ eventRecord.metadata_names.map((name, i) => [+ name,+ eventRecord.metadata_raw_values[i],+ ]),+ );++ return { eventRecord, nameToValue };+}++describe("OTel metadata processing", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe("flattening", () => {+ it("flattens resource/scope attrs to dot-notation (SDK v4.0)", async () => {+ const { nameToValue } = await processAndCreateEvent(+ buildOtelSpan({+ scopeVersion: "4.0.0",+ resourceAttrKey: "service.name",+ resourceAttrValue: "svc-a",+ scopeAttrKey: "public_key",+ scopeAttrValue: "pk-test",+ metadataAttrs: [{ key: "env", value: { stringValue: "prod" } }],+ }),+ );++ expect(nameToValue["resourceAttributes.service.name"]).toBe("svc-a");+ expect(nameToValue["scopeAttributes.public_key"]).toBe("pk-test");+ expect(nameToValue["env"]).toBe("prod");+ expect(nameToValue["resourceAttributes"]).toBeUndefined();+ expect(nameToValue["scopeAttributes"]).toBeUndefined();+ });++ it("flattens resource/scope attrs to dot-notation (SDK v3.8)", async () => {+ const { nameToValue } = await processAndCreateEvent(+ buildOtelSpan({+ scopeVersion: "3.8.1",+ resourceAttrKey: "service.name",+ resourceAttrValue: "svc-b",+ scopeAttrKey: "public_key",+ scopeAttrValue: "pk-legacy",+ metadataAttrs: [{ key: "topic", value: { stringValue: "test" } }],+ }),+ );++ expect(nameToValue["resourceAttributes.service.name"]).toBe("svc-b");+ expect(nameToValue["scopeAttributes.public_key"]).toBe("pk-legacy");+ expect(nameToValue["topic"]).toBe("test");+ expect(nameToValue["resourceAttributes"]).toBeUndefined();+ expect(nameToValue["scopeAttributes"]).toBeUndefined();+ });+ });++ describe("json column", () => {+ it("stringifies nested objects in metadata JSON column", async () => {+ const { eventRecord } = await processAndCreateEvent(+ buildOtelSpan({+ scopeVersion: "4.0.0",+ resourceAttrKey: "service.name",+ resourceAttrValue: "svc-a",+ scopeAttrKey: "public_key",+ scopeAttrValue: "pk-test",+ metadataAttrs: [{ key: "env", value: { stringValue: "prod" } }],+ }),+ );++ // metadata JSON column stores stringified values (Record<string, string>)+ const meta = eventRecord.metadata;+ expect(meta.resourceAttributes).toBe(+ JSON.stringify({ "service.name": "svc-a" }),+ );+ expect(meta.scopeAttributes).toBe(+ JSON.stringify({ public_key: "pk-test" }),+ );+ expect(meta.env).toBe("prod");+ });+ });+});diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 21e20ff8e4..4c08ebcf62 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -336,13 +336,17 @@ export class IngestionService {const now = this.getMicrosecondTimestamp();- // Store the full metadata JSON- const metadata = convertRecordValuesToString(eventData.metadata);-- // Flatten to path-based arrays- const flattened = flattenJsonToPathArrays(metadata);+ // Flatten raw metadata first (before stringification destroys nested structure)+ const flattened = eventData.metadata+ ? flattenJsonToPathArrays(eventData.metadata)+ : { names: [], values: [] };const metadataNames = flattened.names;- const metadataValues = flattened.values;+ // Defensive: coerce null/undefined to empty string for Array(String) ClickHouse column.+ // Should not be required as convertValueToPlainJavascript() never returns null.+ const metadataValues = flattened.values.map((v) => v ?? "");++ // Stringify metadata for the JSON column (Record<string, string>)+ const metadata = convertRecordValuesToString(eventData.metadata ?? {});const eventRecord: EventRecordInsertType = {// Required identifiers