🪢 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): bound reconstructed array indices (#15890)
Max Deichmanne6826630f26e
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.tsindex 09e6d51baa..699f26ea41 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts@@ -46,6 +46,8 @@ import {import * as serverBarrel from "../index";const METRIC = "langfuse.ingestion.metadata_dropped";+const ARRAY_ATTRIBUTE_DROPPED_METRIC =+ "langfuse.ingestion.otel.array_attribute_dropped";const PROJECT_ID = "test-project-lfe-14342";const createProcessor = () =>@@ -648,3 +650,77 @@ describe("OTel metadata_dropped metric (LFE-14342)", () => {});});});++describe("OTel reconstructed array drop telemetry", () => {+ beforeEach(() => {+ recordIncrementMock.mockClear();+ });++ const arrayDropCalls = () =>+ recordIncrementMock.mock.calls.filter(+ ([stat]) => stat === ARRAY_ATTRIBUTE_DROPPED_METRIC,+ );++ it("reports an out-of-range array attribute", async () => {+ const processor = createProcessor();+ const batch = buildBatch([+ {+ key: "llm.input_messages.10001.content",+ value: { stringValue: "dropped" },+ },+ ]);++ await processor.processToIngestionEvents(batch);++ expect(arrayDropCalls()).toContainEqual([+ ARRAY_ATTRIBUTE_DROPPED_METRIC,+ 1,+ {+ reason: "reconstruction_budget_exceeded",+ prefix: "llm.input_messages",+ },+ ]);+ });++ it("caps warnings without logging rejected attribute keys or values", async () => {+ const warnSpy = vi+ .spyOn(serverBarrel.logger, "warn")+ .mockImplementation(() => serverBarrel.logger);++ try {+ const batches = Array.from(+ { length: 12 },+ (_, index) =>+ buildBatch([+ {+ key: `llm.input_messages.${10_001 + index}.secret-content`,+ value: { stringValue: `customer-secret-${index}` },+ },+ ])[0],+ );++ await createProcessor().processToIngestionEvents(batches);++ expect(arrayDropCalls().length).toBeGreaterThan(0);+ const arrayDropWarnings = warnSpy.mock.calls.filter(+ ([message]) => String(message) === "OTEL array attribute dropped",+ );+ expect(arrayDropWarnings).toHaveLength(10);+ for (const warning of arrayDropWarnings) {+ expect(warning).toEqual([+ "OTEL array attribute dropped",+ {+ projectId: PROJECT_ID,+ prefix: "llm.input_messages",+ reason: "reconstruction_budget_exceeded",+ droppedAttributeCount: 1,+ },+ ]);+ expect(JSON.stringify(warning)).not.toContain("customer-secret");+ expect(JSON.stringify(warning)).not.toContain("secret-content");+ }+ } finally {+ warnSpy.mockRestore();+ }+ });+});diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 3e39110032..2ef89a60fa 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -98,6 +98,50 @@ interface MetadataDropContext {dropScope: object;}+/**+ * Tracks the total number of array slots that dotted attribute paths would+ * materialize. A path is reserved transactionally: when it would exceed the+ * limit, none of its array lengths are committed.+ *+ * Multiple attributes can point into the same array, so only growth beyond+ * that array's previously reserved length consumes budget. For example,+ * `0.role` and `0.content` together reserve one slot, while `9999.content`+ * reserves 10,000 slots even though it is only one attribute.+ */+class ArraySlotBudget {+ private usedSlots = 0;+ private readonly lengthsByPath = new Map<string, number>();++ constructor(private readonly maxSlots: number) {}++ tryReserve(pathParts: readonly string[]): boolean {+ const pendingLengths = new Map<string, number>();+ let additionalSlots = 0;++ for (let index = 0; index < pathParts.length; index++) {+ const segment = pathParts[index];+ if (!/^\d+$/.test(segment)) continue;++ const arrayPath = pathParts.slice(0, index).join(".");+ const previousLength =+ pendingLengths.get(arrayPath) ?? this.lengthsByPath.get(arrayPath) ?? 0;+ const requiredLength = Number(segment) + 1;+ if (requiredLength > previousLength) {+ additionalSlots += requiredLength - previousLength;+ pendingLengths.set(arrayPath, requiredLength);+ }+ }++ if (this.usedSlots + additionalSlots > this.maxSlots) return false;++ this.usedSlots += additionalSlots;+ pendingLengths.forEach((length, path) =>+ this.lengthsByPath.set(path, length),+ );+ return true;+ }+}+interface CreateTraceEventParams {traceId: string;startTimeISO: string;@@ -196,12 +240,20 @@ const LIVEKIT_DEBUG_SPAN_NAMES = new Set([export class OtelIngestionProcessor {private static readonly OTEL_CONVERSION_FAILURE_METRIC ="langfuse.ingestion.otel.conversion_failure";+ private static readonly OTEL_ARRAY_ATTRIBUTE_DROPPED_METRIC =+ "langfuse.ingestion.otel.array_attribute_dropped";++ // Flattened OTel message attributes name array slots directly, so cap the+ // total logical array length before reconstructing the value.+ private static readonly MAX_OTEL_RECONSTRUCTED_ARRAY_SLOTS = 10_001;private static readonly METADATA_DROP_WARN_CAP = 10;+ private static readonly ARRAY_ATTRIBUTE_DROP_WARN_CAP = 10;private seenTraces: Set<string> = new Set();private reportedMetadataDrops = new WeakMap<object, Set<string>>();private metadataDropWarnCount = 0;+ private arrayAttributeDropWarnCount = 0;private isInitialized = false;private traceEventCounts = {shallow: 0,@@ -1472,6 +1524,15 @@ export class OtelIngestionProcessor {return undefined;}+ /**+ * Rebuilds observation input/output from flattened adapter attributes.+ *+ * TraceLoop and OpenInference encode structured messages in attribute names;+ * for example, `gen_ai.prompt.0.content` becomes `[{ content: value }]`.+ * Numeric path segments therefore become JavaScript array indices. The total+ * logical slots across all nested arrays are bounded, since dimensions can+ * otherwise multiply into a huge sparse structure during serialization.+ */private convertKeyPathToNestedObject(input: Record<string, unknown>,prefix: string,@@ -1480,7 +1541,21 @@ export class OtelIngestionProcessor {return input[prefix];}- const keys = Object.keys(input).map((key) => key.replace(`${prefix}.`, ""));+ const keys: string[] = [];+ const overBudgetKeys: string[] = [];+ const arraySlotBudget = new ArraySlotBudget(+ OtelIngestionProcessor.MAX_OTEL_RECONSTRUCTED_ARRAY_SLOTS,+ );+ for (const inputKey of Object.keys(input)) {+ const key = inputKey.replace(`${prefix}.`, "");+ if (!arraySlotBudget.tryReserve(key.split("."))) {+ overBudgetKeys.push(key);+ continue;+ }++ keys.push(key);+ }+ this.recordArrayAttributesDropped(prefix, overBudgetKeys);const useArray = keys.some((key) => key.match(/^\d+\./));// Blocklist to prevent prototype pollution via crafted OTel attribute keys@@ -1508,7 +1583,8 @@ export class OtelIngestionProcessor {const result: any[] = [];for (const key of keys) {const pathParts = key.split(".");- const index = parseInt(pathParts[0], 10);+ const indexSegment = pathParts[0];+ const index = Number(indexSegment);if (!result[index]) {result[index] = Object.create(null);}@@ -1539,6 +1615,28 @@ export class OtelIngestionProcessor {return result;}+ private recordArrayAttributesDropped(prefix: string, keys: string[]): void {+ if (keys.length === 0) return;++ recordIncrement(+ OtelIngestionProcessor.OTEL_ARRAY_ATTRIBUTE_DROPPED_METRIC,+ keys.length,+ { reason: "reconstruction_budget_exceeded", prefix },+ );+ if (+ this.arrayAttributeDropWarnCount <+ OtelIngestionProcessor.ARRAY_ATTRIBUTE_DROP_WARN_CAP+ ) {+ this.arrayAttributeDropWarnCount += 1;+ logger.warn("OTEL array attribute dropped", {+ projectId: this.projectId,+ prefix,+ reason: "reconstruction_budget_exceeded",+ droppedAttributeCount: keys.length,+ });+ }+ }+private extractInputAndOutput(params: {events: any[];attributes: Record<string, unknown>;diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex ae3bd13988..f1cdd446cc 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -4727,6 +4727,136 @@ describe("OTel Resource Span Mapping", () => {);});+ // TraceLoop flattens prompt arrays into gen_ai.prompt.<index>.* attributes.+ // An unsafe message must not prevent a valid sibling from being ingested.+ it("should ignore out-of-range OTEL message indices without dropping valid messages", async () => {+ const resourceSpan = {+ resource: {},+ scopeSpans: [+ {+ spans: [+ {+ ...defaultSpanProps,+ attributes: [+ {+ key: "gen_ai.prompt.0.content",+ value: { stringValue: "valid message" },+ },+ {+ key: "gen_ai.prompt.10001.content",+ value: { stringValue: "unsafe message" },+ },+ ],+ },+ ],+ },+ ],+ };++ const events = await convertOtelSpanToIngestionEvent(+ resourceSpan,+ new Set(),+ );+ const observation = events.find(+ (event) =>+ event.type.endsWith("-create") && event.type !== "trace-create",+ );++ expect(observation?.body.input).toEqual([{ content: "valid message" }]);+ });++ // OpenInference may place array indices deeper in llm.input_messages paths,+ // so every numeric segment must be checked, not only the first one.+ it("should ignore out-of-range nested OTEL indices", async () => {+ const resourceSpan = {+ resource: {},+ scopeSpans: [+ {+ spans: [+ {+ ...defaultSpanProps,+ attributes: [+ {+ key: "llm.input_messages.0.message.10001.content",+ value: { stringValue: "unsafe content" },+ },+ {+ key: "llm.input_messages.0.message.role",+ value: { stringValue: "user" },+ },+ ],+ },+ ],+ },+ ],+ };++ const events = await convertOtelSpanToIngestionEvent(+ resourceSpan,+ new Set(),+ );+ const observation = events.find(+ (event) =>+ event.type.endsWith("-create") && event.type !== "trace-create",+ );+ const input = observation?.body.input as Array<{+ message: Record<string, unknown>;+ }>;++ expect(input).toHaveLength(1);+ expect(Array.isArray(input[0].message)).toBe(false);+ expect(input[0].message).toEqual({ role: "user" });+ });++ it("should cap total array-slot expansion across nested OTEL paths", async () => {+ const resourceSpan = {+ resource: {},+ scopeSpans: [+ {+ spans: [+ {+ ...defaultSpanProps,+ attributes: [+ {+ key: "llm.input_messages.0.safe",+ value: { stringValue: "preserved sibling" },+ },+ {+ key: "llm.input_messages.0.message.9999.content",+ value: { stringValue: "accepted content" },+ },+ {+ key: "llm.input_messages.1.message.9999.content",+ value: { stringValue: "over budget content" },+ },+ ],+ },+ ],+ },+ ],+ };++ const events = await convertOtelSpanToIngestionEvent(+ resourceSpan,+ new Set(),+ );+ const observation = events.find(+ (event) =>+ event.type.endsWith("-create") && event.type !== "trace-create",+ );+ const input = observation?.body.input as Array<{+ safe?: string;+ message?: Array<{ content: string }>;+ }>;++ expect(input).toHaveLength(1);+ expect(input[0].safe).toBe("preserved sibling");+ expect(input[0].message).toHaveLength(10_000);+ expect(input[0].message?.[9_999]).toEqual({+ content: "accepted content",+ });+ });+// GenAI semantic conventions v1.37+ record prompts/completions on a// gen_ai.client.inference.operation.details span event (e.g. Hindsight)it("should extract input/output from gen_ai.client.inference.operation.details span event", async () => {