🪢 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): add defensive logging for bad cost/usage details and oversized spans (#12941)
Valery Meleshkin68cc2b24f1fd
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex e0f700487a..6e1166d873 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -97,6 +97,7 @@ const EnvSchema = z.object({.number().positive().default(1),+ LANGFUSE_OTEL_MAX_SPAN_BYTES: z.coerce.number().positive().default(9_500_000), // 9.5MB — just under ClickHouse's 10MB min_chunk_bytes_for_parallel_parsing defaultLANGFUSE_EVAL_EXECUTION_QUEUE_SHARD_COUNT: z.coerce.number().positive()diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex e1f1053f76..65aa580f9a 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -333,13 +333,26 @@ export class OtelIngestionProcessor {},);+ this.logOversizedSpan(span, spanAttributes, {+ spanId,+ traceId,+ eventBytes,+ });+const experimentFields =this.extractExperimentFields(spanAttributes);+ const spanContext = {+ spanId,+ traceId,+ source: "event" as const,+ };+const usageDetails = UsageDetails.safeParse(this.extractUsageDetails(spanAttributes,scopeSpan?.scope?.name ?? "",+ spanContext,),);if (!usageDetails.success) {@@ -438,7 +451,10 @@ export class OtelIngestionProcessor {providedUsageDetails: usageDetails.success? usageDetails.data: undefined,- providedCostDetails: this.extractCostDetails(spanAttributes),+ providedCostDetails: this.extractCostDetails(+ spanAttributes,+ spanContext,+ ),// Propertiestags: this.extractTags(spanAttributes),@@ -955,6 +971,13 @@ export class OtelIngestionProcessor {instrumentationScopeName,});+ const observationSpanId = this.tryParseSpanId(span);+ const observationContext = {+ spanId: observationSpanId,+ traceId,+ source: "ingestion" as const,+ };+const observation = {id: this.parseId(span.spanId?.data ?? span.spanId),traceId,@@ -1008,8 +1031,9 @@ export class OtelIngestionProcessor {usageDetails: this.extractUsageDetails(attributes,instrumentationScopeName,+ observationContext,),- costDetails: this.extractCostDetails(attributes),+ costDetails: this.extractCostDetails(attributes, observationContext),input,output,};@@ -1108,6 +1132,144 @@ export class OtelIngestionProcessor {);}+ private static isPlainObject(+ value: unknown,+ ): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+ }++ private tryParseSpanId(span: any): string {+ try {+ if (span?.spanId != null) {+ return this.parseId(span.spanId?.data ?? span.spanId);+ }+ } catch {+ // Intentionally swallowed — return "unknown" below+ }+ return "unknown";+ }++ /**+ * Parses a JSON-encoded attribute expected to be a plain object.+ * Returns the parsed object on success, {} if present but wrong type (logged),+ * null if absent or unparsable (signals caller to try fallback paths).+ */+ private parseJsonObjectAttribute(+ attributes: Record<string, unknown>,+ key: string,+ context: { spanId: string; traceId: string; source: string },+ ): Record<string, unknown> | null {+ const raw = attributes[key];+ if (!raw) return null;++ const logContext = {+ spanId: context.spanId,+ traceId: context.traceId,+ projectId: this.projectId,+ attribute: key,+ source: context.source,+ };+ const metricTags = {+ attribute: key,+ project_id: this.projectId,+ source: context.source,+ };++ if (typeof raw !== "string") {+ logger.warn("OTEL parseJsonObjectAttribute: non-string value", {+ ...logContext,+ reason: "non_string",+ valueType: typeof raw,+ });+ recordIncrement("langfuse.ingestion.otel.bad_json_attribute", 1, {+ ...metricTags,+ reason: "non_string",+ });+ return {};+ }++ try {+ const parsed = JSON.parse(raw);+ if (!OtelIngestionProcessor.isPlainObject(parsed)) {+ logger.warn("OTEL parseJsonObjectAttribute: non-object parsed value", {+ ...logContext,+ reason: "not_plain_object",+ parsedType: typeof parsed,+ });+ recordIncrement("langfuse.ingestion.otel.bad_json_attribute", 1, {+ ...metricTags,+ reason: "not_plain_object",+ });+ return {};+ }+ return parsed;+ } catch {+ logger.warn("OTEL parseJsonObjectAttribute: invalid JSON", {+ ...logContext,+ reason: "invalid_json",+ });+ recordIncrement("langfuse.ingestion.otel.bad_json_attribute", 1, {+ ...metricTags,+ reason: "invalid_json",+ });+ return null;+ }+ }++ /**+ * Logs details about spans that exceed the size threshold.+ * Does NOT reject — just logs for observability.+ */+ private logOversizedSpan(+ span: any,+ spanAttributes: Record<string, unknown>,+ context: { spanId: string; traceId: string; eventBytes: number },+ ): void {+ const maxBytes = env.LANGFUSE_OTEL_MAX_SPAN_BYTES;+ if (context.eventBytes <= maxBytes) return;++ const fieldThreshold = 1_000_000; // 1MB+ const largeFields: Record<string, number> = {};++ // Check extracted span attributes+ for (const [key, value] of Object.entries(spanAttributes)) {+ if (typeof value === "string") {+ const bytes = Buffer.byteLength(value, "utf8");+ if (bytes > fieldThreshold) {+ largeFields[key] = bytes;+ }+ }+ }++ // Check span events (gen_ai.user.message, gen_ai.choice, etc.)+ // Prompts and completions following OTel GenAI semantic conventions+ // live in span.events[], not in span attributes.+ for (const event of span?.events ?? []) {+ for (const attr of event?.attributes ?? []) {+ const val = attr?.value?.stringValue;+ if (typeof val === "string") {+ const bytes = Buffer.byteLength(val, "utf8");+ if (bytes > fieldThreshold) {+ const fieldKey = `events[${event.name ?? "?"}].${attr.key}`;+ largeFields[fieldKey] = bytes;+ }+ }+ }+ }++ logger.warn("OTEL oversized span detected", {+ spanId: context.spanId,+ traceId: context.traceId,+ projectId: this.projectId,+ eventBytes: context.eventBytes,+ maxBytes,+ largeFields,+ });+ recordIncrement("langfuse.ingestion.otel.oversized_span", 1, {+ project_id: this.projectId,+ });+ }+private convertValueToPlainJavascript(value: Record<string, any>): any {if (value.stringValue !== undefined) {return value.stringValue;@@ -2116,18 +2278,14 @@ export class OtelIngestionProcessor {private extractUsageDetails(attributes: Record<string, unknown>,instrumentationScopeName: string,+ context: { spanId: string; traceId: string; source: string },): Record<string, unknown> {- if (attributes[LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS]) {- try {- return JSON.parse(- attributes[- LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS- ] as string,- );- } catch {- // Fallthrough- }- }+ const fromAttribute = this.parseJsonObjectAttribute(+ attributes,+ LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS,+ context,+ );+ if (fromAttribute !== null) return fromAttribute;// Genkitif (instrumentationScopeName === "genkit-tracer") {@@ -2367,18 +2525,14 @@ export class OtelIngestionProcessor {private extractCostDetails(attributes: Record<string, unknown>,+ context: { spanId: string; traceId: string; source: string },): Record<string, unknown> {- if (attributes[LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS]) {- try {- return JSON.parse(- attributes[- LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS- ] as string,- );- } catch {- // Fallthrough- }- }+ const fromAttribute = this.parseJsonObjectAttribute(+ attributes,+ LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS,+ context,+ );+ if (fromAttribute !== null) return fromAttribute;if (attributes["gen_ai.usage.cost"]) {return { total: attributes["gen_ai.usage.cost"] };diff --git a/worker/src/queues/__tests__/otelToObservationForEval.test.ts b/worker/src/queues/__tests__/otelToObservationForEval.test.tsindex c67c9a2743..b546dd3c49 100644--- a/worker/src/queues/__tests__/otelToObservationForEval.test.ts+++ b/worker/src/queues/__tests__/otelToObservationForEval.test.ts@@ -1563,4 +1563,145 @@ describe("OTEL to ObservationForEval Schema Validation", () => {expect(observations[0].tool_call_count).toBe(0);});});++ describe("Malformed usage_details and cost_details handling", () => {+ function buildSpanWithRawAttributes(+ extraAttrs: Array<{ key: string; value: Record<string, unknown> }>,+ scopeName = "langfuse-sdk",+ ) {+ return {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: scopeName, version: "3.0.0" },+ spans: [+ {+ traceId: createBufferId("1234567890abcdef1234567890malfor"),+ spanId: createBufferId("malformed12345678"),+ name: "malformed-test",+ kind: 1,+ startTimeUnixNano: createNanoTimestamp(+ BigInt(1738242287865000000),+ ),+ endTimeUnixNano: createNanoTimestamp(+ BigInt(1738242289310000000),+ ),+ attributes: [+ {+ key: "langfuse.observation.type",+ value: { stringValue: "generation" },+ },+ {+ key: "langfuse.observation.model.name",+ value: { stringValue: "gpt-4" },+ },+ ...extraAttrs,+ ],+ status: {},+ },+ ],+ },+ ],+ };+ }++ it.each([+ {+ name: "invalid JSON",+ usage: { stringValue: "not json{{{" },+ cost: { stringValue: "{broken" },+ expectedUsage: {},+ expectedCost: {},+ },+ {+ name: "JSON array",+ usage: { stringValue: "[100, 200]" },+ cost: { stringValue: "[0.01]" },+ expectedUsage: {},+ expectedCost: {},+ },+ {+ name: "JSON primitive",+ usage: { stringValue: "42" },+ cost: { stringValue: '"a string"' },+ expectedUsage: {},+ expectedCost: {},+ },+ {+ name: "non-string attribute type",+ usage: { intValue: 12345 },+ cost: { doubleValue: 0.99 },+ expectedUsage: {},+ expectedCost: {},+ },+ {+ name: "attributes omitted entirely",+ usage: null,+ cost: null,+ expectedUsage: {},+ expectedCost: {},+ },+ {+ name: "valid usage but malformed cost",+ usage: { stringValue: '{"input":100,"output":200}' },+ cost: { stringValue: "not json" },+ expectedUsage: { input: 100, output: 200 },+ expectedCost: {},+ },+ ])(+ "should handle $name without data corruption",+ async ({ usage, cost, expectedUsage, expectedCost }) => {+ const attrs: Array<{+ key: string;+ value: Record<string, unknown>;+ }> = [];+ if (usage)+ attrs.push({+ key: "langfuse.observation.usage_details",+ value: usage,+ });+ if (cost)+ attrs.push({+ key: "langfuse.observation.cost_details",+ value: cost,+ });++ const span = buildSpanWithRawAttributes(attrs);+ const observations = await processOtelSpanToObservationForEval(span);++ expect(observations).toHaveLength(1);+ const obs = observations[0];+ expect(observationForEvalSchema.safeParse(obs).success).toBe(true);+ expect(obs.provided_usage_details).toEqual(expectedUsage);+ expect(obs.provided_cost_details).toEqual(expectedCost);+ },+ );++ it("should fall through to gen_ai.usage.* when usage_details is invalid JSON", async () => {+ const span = buildSpanWithRawAttributes(+ [+ {+ key: "langfuse.observation.usage_details",+ value: { stringValue: "{{bad}}" },+ },+ {+ key: "gen_ai.usage.input_tokens",+ value: { intValue: { low: 50, high: 0, unsigned: false } },+ },+ {+ key: "gen_ai.usage.output_tokens",+ value: { intValue: { low: 75, high: 0, unsigned: false } },+ },+ ],+ "ai", // scope name triggers gen_ai.usage.* fallback path+ );++ const observations = await processOtelSpanToObservationForEval(span);+ expect(observations).toHaveLength(1);+ expect(observations[0].provided_usage_details).toMatchObject({+ input: 50,+ output: 75,+ });+ });+ });});diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex 90f747d566..ee71275ace 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -432,8 +432,20 @@ export class ClickhouseWriter {});if (droppedCount > 0) {+ const droppedIds = queueItems+ .filter((item) => item.attempts >= this.maxAttempts)+ .map((item) => {+ const r = item.data as Record<string, unknown>;+ return {+ project_id: r.project_id,+ trace_id: r.trace_id ?? r.id,+ id: r.id,+ };+ });+logger.error(`ClickhouseWriter: Max attempts reached, dropped ${droppedCount} ${tableName} record(s)`,+ { droppedIds },);}}