Skip to content

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

fix(server): ingest flattened experiment metadata (#13368)

Hassieb Pakzad20b81b3b7f65
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 15382435b0..e504570482 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -2028,54 +2028,28 @@ export class OtelIngestionProcessor {
attributes: Record<string, unknown>,
domain: "trace" | "observation",
): Record<string, unknown> {
- let topLevelMetadata: 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") {
- topLevelMetadata = JSON.parse(langfuseMetadataAttribute as string);
- } else if (typeof langfuseMetadataAttribute === "object") {
- topLevelMetadata = langfuseMetadataAttribute as Record<
- string,
- unknown
- >;
- }
- } catch {
- // Continue with nested metadata extraction
- }
- }
-
- const langfuseMetadata: Record<string, unknown> = {};
-
- for (const [key, value] of Object.entries(attributes)) {
- for (const prefix of [
+ const topLevelMetadata = this.parseMetadataAttribute(
+ attributes[metadataKeyPrefix] || attributes["langfuse.metadata"],
+ );
+ const langfuseMetadata = this.extractPrefixedMetadataAttributes({
+ attributes,
+ prefixes: [
metadataKeyPrefix,
"langfuse.metadata",
"ai.telemetry.metadata",
- ]) {
- if (
- key.startsWith(`${prefix}.`) &&
- // Filter out the Vercel AI SDK trace attribute keys
- ![
- "ai.telemetry.metadata.userId",
- "ai.telemetry.metadata.sessionId",
- "ai.telemetry.metadata.tags",
- "ai.telemetry.metadata.langfusePrompt",
- ].includes(key)
- ) {
- const newKey = key.replace(`${prefix}.`, "");
- langfuseMetadata[newKey] = value;
- }
- }
- }
+ ],
+ excludedKeys: new Set([
+ "ai.telemetry.metadata.userId",
+ "ai.telemetry.metadata.sessionId",
+ "ai.telemetry.metadata.tags",
+ "ai.telemetry.metadata.langfusePrompt",
+ ]),
+ });
// Vercel AI SDK
const tools =
@@ -2697,6 +2671,68 @@ export class OtelIngestionProcessor {
return [];
}
+ private parseMetadataAttribute(value: unknown): Record<string, unknown> {
+ if (!value) {
+ return {};
+ }
+
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object"
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+ }
+
+ if (typeof value === "object") {
+ return value as Record<string, unknown>;
+ }
+
+ return {};
+ }
+
+ private extractPrefixedMetadataAttributes(params: {
+ attributes: Record<string, unknown>;
+ prefixes: string[];
+ excludedKeys?: Set<string>;
+ }): Record<string, unknown> {
+ const { attributes, prefixes, excludedKeys = new Set<string>() } = params;
+ const metadata: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(attributes)) {
+ for (const prefix of prefixes) {
+ if (!key.startsWith(`${prefix}.`) || excludedKeys.has(key)) {
+ continue;
+ }
+
+ const metadataKey = key.slice(prefix.length + 1);
+ if (!metadataKey) {
+ continue;
+ }
+
+ metadata[metadataKey] = value;
+ }
+ }
+
+ return metadata;
+ }
+
+ private extractMetadataFromPrefix(params: {
+ attributes: Record<string, unknown>;
+ prefix: string;
+ }): Record<string, unknown> {
+ const { attributes, prefix } = params;
+ return {
+ ...this.parseMetadataAttribute(attributes[prefix]),
+ ...this.extractPrefixedMetadataAttributes({
+ attributes,
+ prefixes: [prefix],
+ }),
+ };
+ }
+
/**
* Extracts experiment-related fields from span attributes.
* Returns undefined for fields that are not present.
@@ -2734,35 +2770,19 @@ export class OtelIngestionProcessor {
attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_VERSION];
// Extract experiment metadata
- const experimentMetadataStr =
- attributes[LangfuseOtelSpanAttributes.EXPERIMENT_METADATA];
- let experimentMetadata: Record<string, unknown> = {};
- if (experimentMetadataStr && typeof experimentMetadataStr === "string") {
- try {
- experimentMetadata = JSON.parse(experimentMetadataStr);
- } catch {
- // If parsing fails, treat as empty
- }
- }
- const experimentMetadataFlattened =
- flattenJsonToPathArrays(experimentMetadata);
+ const experimentMetadataFlattened = flattenJsonToPathArrays(
+ this.extractMetadataFromPrefix({
+ attributes,
+ prefix: LangfuseOtelSpanAttributes.EXPERIMENT_METADATA,
+ }),
+ );
// Extract experiment item metadata
- const experimentItemMetadataStr =
- attributes[LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_METADATA];
- let experimentItemMetadata: Record<string, unknown> = {};
- if (
- experimentItemMetadataStr &&
- typeof experimentItemMetadataStr === "string"
- ) {
- try {
- experimentItemMetadata = JSON.parse(experimentItemMetadataStr);
- } catch {
- // If parsing fails, treat as empty
- }
- }
const experimentItemMetadataFlattened = flattenJsonToPathArrays(
- experimentItemMetadata,
+ this.extractMetadataFromPrefix({
+ attributes,
+ prefix: LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_METADATA,
+ }),
);
return {
diff --git a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
index d3892e4a2c..1b6817cbe1 100644
--- a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
+++ b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts
@@ -138,6 +138,19 @@ async function processAndCreateEvent(
return { eventRecord, nameToValue };
}
+function arraysToRecord(
+ names: string[],
+ values: Array<string | null | undefined>,
+) {
+ return names.reduce<Record<string, string | null | undefined>>(
+ (acc, name, index) => {
+ acc[name] = values[index];
+ return acc;
+ },
+ {},
+ );
+}
+
describe("OTel metadata processing", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -184,4 +197,137 @@ describe("OTel metadata processing", () => {
expect(nameToValue["scope.attributes"]).toBeUndefined();
});
});
+
+ describe("experiment metadata", () => {
+ it("extracts serialized and flattened experiment metadata attributes", async () => {
+ const otelSpan = {
+ resource: {
+ attributes: [
+ {
+ key: "telemetry.sdk.language",
+ value: { stringValue: "python" },
+ },
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "4.5.0",
+ attributes: [
+ { key: "public_key", value: { stringValue: "pk-test" } },
+ ],
+ },
+ spans: [
+ {
+ traceId: createBufferId("bb9cee80f1800c7d51ef67439c379032"),
+ spanId: createBufferId("c874c627f90e96a6"),
+ name: "experiment-child-span",
+ kind: 1,
+ startTimeUnixNano: createNanoTimestamp(
+ BigInt(1777044156622912000),
+ ),
+ endTimeUnixNano: createNanoTimestamp(
+ BigInt(1777044156622993000),
+ ),
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "generation" },
+ },
+ {
+ key: "langfuse.experiment.id",
+ value: { stringValue: "972b5387f1607558" },
+ },
+ {
+ key: "langfuse.experiment.name",
+ value: {
+ stringValue: "myexp - 2026-04-24T15:22:36.622383Z",
+ },
+ },
+ {
+ key: "langfuse.experiment.metadata",
+ value: {
+ stringValue: JSON.stringify({
+ source: "serialized",
+ override: "serialized-value",
+ nested: { key: "nested-value" },
+ }),
+ },
+ },
+ {
+ key: "langfuse.experiment.metadata.override",
+ value: { stringValue: "flattened-value" },
+ },
+ {
+ key: "langfuse.experiment.metadata.region",
+ value: { stringValue: "emea" },
+ },
+ {
+ key: "langfuse.experiment.item.id",
+ value: { stringValue: "80db4ccdca106d37" },
+ },
+ {
+ key: "langfuse.experiment.item.root_observation_id",
+ value: { stringValue: "842d3593cd7c818e" },
+ },
+ {
+ key: "langfuse.experiment.item.metadata",
+ value: {
+ stringValue: JSON.stringify({
+ legacy: true,
+ continent: "serialized-continent",
+ }),
+ },
+ },
+ {
+ key: "langfuse.experiment.item.metadata.continent",
+ value: { stringValue: "Europe" },
+ },
+ {
+ key: "langfuse.experiment.item.metadata.position",
+ value: { intValue: 3 },
+ },
+ {
+ key: "langfuse.observation.metadata.continent",
+ value: { stringValue: "observation-continent" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const { eventRecord, nameToValue } =
+ await processAndCreateEvent(otelSpan);
+
+ expect(eventRecord.experiment_id).toBe("972b5387f1607558");
+ expect(eventRecord.experiment_item_id).toBe("80db4ccdca106d37");
+ expect(nameToValue["continent"]).toBe("observation-continent");
+
+ expect(
+ arraysToRecord(
+ eventRecord.experiment_metadata_names,
+ eventRecord.experiment_metadata_values,
+ ),
+ ).toEqual({
+ source: "serialized",
+ override: "flattened-value",
+ "nested.key": "nested-value",
+ region: "emea",
+ });
+ expect(
+ arraysToRecord(
+ eventRecord.experiment_item_metadata_names,
+ eventRecord.experiment_item_metadata_values,
+ ),
+ ).toEqual({
+ legacy: "true",
+ continent: "Europe",
+ position: "3",
+ });
+ });
+ });
});