πͺ’ 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): reject spans with missing or malformed ids with a 400 (#15707)
Steffen Schmitz0e7bee31b9fa
diff --git a/packages/shared/src/server/otel/utils.test.ts b/packages/shared/src/server/otel/utils.test.tsnew file mode 100644index 0000000000..e2bda8f0b2--- /dev/null+++ b/packages/shared/src/server/otel/utils.test.ts@@ -0,0 +1,226 @@+import { describe, expect, it } from "vitest";++import { getOtelIdRejectionReason, validateOtelSpanIds } from "./utils";++const TRACE_ID = "bb14c33c23138873afcc5e6f3c2b5f61"; // 16 bytes+const SPAN_ID = "cb00000daff4e5ae"; // 8 bytes+const traceBytes = Buffer.from(TRACE_ID, "hex");++describe("getOtelIdRejectionReason", () => {+ // Anything parseId can convert must stay accepted, otherwise this validation+ // breaks clients that ingest fine today. Length and encoding are not checked:+ // the OTLP protobuf declares these fields as `bytes` with no length+ // constraint, and the backend stores the id as a String.+ it.each([+ { shape: "hex string", value: TRACE_ID },+ { shape: "Buffer from a protobuf decode", value: traceBytes },+ { shape: "int array from the Python SDK", value: [...traceBytes] },+ { shape: "Uint8Array", value: new Uint8Array([...traceBytes]) },+ {+ shape: "Buffer serialized to JSON",+ value: { type: "Buffer", data: [...traceBytes] },+ },+ { shape: "base64 string", value: traceBytes.toString("base64") },+ { shape: "arbitrary non-hex string", value: "trace-1" },+ // Short, long and all-zero ids convert cleanly and the backend stores them+ // verbatim, so they are the client's business, not ours.+ { shape: "short id", value: Buffer.from([107]) },+ { shape: "span-length id in a traceId", value: SPAN_ID },+ { shape: "over-long id", value: Buffer.alloc(100, 7) },+ { shape: "all-zero id", value: Buffer.alloc(16) },+ { shape: "empty string", value: "" },+ { shape: "empty array", value: [] },+ ])("accepts $shape", ({ value }) => {+ expect(getOtelIdRejectionReason(value)).toBeNull();+ });++ // The production failure: parseId calls Buffer.from() on these and throws+ // ERR_INVALID_ARG_TYPE, which fails the queue job through every retry.+ it.each([+ { shape: "undefined", value: undefined, reason: "absent" },+ { shape: "null", value: null, reason: "absent" },+ { shape: "a number", value: 42, reason: "not_an_id" },+ { shape: "a boolean", value: true, reason: "not_an_id" },+ { shape: "a plain object", value: { foo: "bar" }, reason: "not_an_id" },+ // Buffer.from only revives the `{ type: "Buffer", data }` shape. The+ // worker's processToEvent path passes the raw value, so an untagged+ // envelope throws there even though other call sites unwrap `.data`.+ {+ shape: "an untagged data envelope",+ value: { data: [1, 2, 3, 4] },+ reason: "not_an_id",+ },+ // Buffer.from also accepts any object with a numeric `length` and+ // zero-fills that many bytes. Probing it here would let a tiny request body+ // block the shared web event loop for seconds, so array-likes are matched by+ // shape and rejected. If this ever regresses to calling Buffer.from, this+ // row starts passing the value through and the test fails.+ {+ shape: "a bare array-like",+ value: { length: 8 },+ reason: "not_an_id",+ },+ ] as const)("rejects $shape as $reason", ({ value, reason }) => {+ expect(getOtelIdRejectionReason(value)).toBe(reason);+ });+});++describe("validateOtelSpanIds", () => {+ const wrap = (spans: unknown[], scopeName = "my-tracer") => [+ {+ resource: { attributes: [] },+ scopeSpans: [{ scope: { name: scopeName }, spans }],+ },+ ];++ // The production failure: an OTLP log record decoded as a span. ResourceLogs+ // and ResourceSpans share protobuf field numbers, so the scope name comes+ // through intact while the ids are absent entirely. The worker-side crash this+ // causes is pinned by+ // worker/src/queues/__tests__/otelConversionFailureLogging.test.ts; this+ // asserts it no longer gets that far.+ it("rejects a log record decoded as a span", () => {+ const result = validateOtelSpanIds(+ wrap([{ traceState: "INFO" }], "codex_otel.log_only"),+ );+ expect(result.invalidSpanCount).toBe(1);+ // Both ids fail, so the per-reason counts sum above the span count.+ expect(result.reasonCounts).toEqual({+ "traceId:absent": 1,+ "spanId:absent": 1,+ });+ expect(result.scopeNames).toEqual(["codex_otel.log_only"]);+ });++ // The other decodable log-record shape yields 1- and 3-byte ids. Those convert+ // fine and the backend stores them verbatim, so they are deliberately accepted+ // rather than rejected on length β see getOtelIdRejectionReason.+ it("accepts a span whose ids are short but decodable", () => {+ const result = validateOtelSpanIds(+ wrap([+ {+ traceId: { type: "Buffer", data: [107] },+ spanId: { type: "Buffer", data: [10, 1, 118] },+ },+ ]),+ );+ expect(result).toMatchObject({ totalSpanCount: 1, invalidSpanCount: 0 });+ });++ // parentSpanId reaches parseId too, so a present-but-unconvertible one crashes+ // the worker exactly like a bad traceId. Absent is the common case and stays+ // valid, since the worker only converts it when truthy.+ it("rejects an unconvertible parentSpanId", () => {+ const result = validateOtelSpanIds(+ wrap([{ traceId: TRACE_ID, spanId: SPAN_ID, parentSpanId: 42 }]),+ );+ expect(result.invalidSpanCount).toBe(1);+ expect(result.reasonCounts).toEqual({ "parentSpanId:not_an_id": 1 });+ });++ it.each([+ { shape: "omitted", span: { traceId: TRACE_ID, spanId: SPAN_ID } },+ {+ shape: "an empty string",+ span: { traceId: TRACE_ID, spanId: SPAN_ID, parentSpanId: "" },+ },+ {+ shape: "a valid hex string",+ span: { traceId: TRACE_ID, spanId: SPAN_ID, parentSpanId: SPAN_ID },+ },+ ])("accepts a parentSpanId that is $shape", ({ span }) => {+ expect(validateOtelSpanIds(wrap([span])).invalidSpanCount).toBe(0);+ });++ // Doubles as the happy path: the two valid spans must not be flagged.+ it("reports only the offending spans in a mixed batch", () => {+ const good = { traceId: TRACE_ID, spanId: SPAN_ID };+ const result = validateOtelSpanIds(+ wrap([good, { traceState: "INFO" }, good]),+ );+ expect(result).toMatchObject({ totalSpanCount: 3, invalidSpanCount: 1 });+ });++ // The rejection metric is tagged per reason, so a batch mixing reasons has to+ // split across them rather than attributing every span to the first reason.+ it("counts invalid spans per reason", () => {+ const result = validateOtelSpanIds(+ wrap([+ ...Array.from({ length: 8 }, () => ({ spanId: SPAN_ID })),+ ...Array.from({ length: 2 }, () => ({+ traceId: TRACE_ID,+ spanId: 42,+ })),+ ]),+ );+ expect(result.invalidSpanCount).toBe(10);+ expect(result.reasonCounts).toEqual({+ "traceId:absent": 8,+ "spanId:not_an_id": 2,+ });+ });++ // Absent and empty collections are legitimate and must stay accepted.+ it.each([+ { shape: "non-array", payload: undefined },+ { shape: "empty and null entries", payload: [{}, null] },+ {+ shape: "null scope and spans",+ payload: [{ scopeSpans: [{ scope: null, spans: null }] }],+ },+ { shape: "empty spans", payload: [{ scopeSpans: [{ spans: [] }] }] },+ ])("accepts $shape", ({ payload }) => {+ const result = validateOtelSpanIds(payload);+ expect(result.invalidSpanCount).toBe(0);+ expect(result.malformedCollectionCount).toBe(0);+ });++ // A present-but-non-array collection throws on for...of. The worker iterates+ // these same fields behind a `?? []` fallback that does not guard it, so the+ // job would fail through every retry β the failure mode this validation exists+ // to prevent. Report it so the endpoint rejects, and never throw here, since+ // that would surface as a 500.+ it.each([+ {+ shape: "object scopeSpans",+ payload: [{ scopeSpans: {} }],+ reason: "scopeSpans:not_an_array",+ },+ {+ // Strings are iterable, so the worker walks the characters into zero+ // spans without throwing. Rejected anyway β one rule for these fields.+ shape: "string scopeSpans",+ payload: [{ scopeSpans: "nope" }],+ reason: "scopeSpans:not_an_array",+ },+ {+ shape: "object spans",+ payload: [{ scopeSpans: [{ spans: {} }] }],+ reason: "spans:not_an_array",+ },+ ])("reports $shape without throwing", ({ payload, reason }) => {+ expect(() => validateOtelSpanIds(payload)).not.toThrow();+ const result = validateOtelSpanIds(payload);+ expect(result.malformedCollectionCount).toBe(1);+ expect(result.reasons).toEqual([reason]);+ // No span was reachable, so nothing is attributed to a span.+ expect(result.invalidSpanCount).toBe(0);+ expect(result.totalSpanCount).toBe(0);+ });++ // Scope names are client-controlled and unbounded, so the samples that reach+ // the error message and the log line have to stay capped. Reasons are bounded+ // by construction and so are counted in full.+ it("caps sampled scope names but not reasons", () => {+ const resourceSpans = Array.from({ length: 50 }, (_unused, i) =>+ wrap([{ traceState: "INFO" }], `scope-${i}`),+ ).flat();+ const result = validateOtelSpanIds(resourceSpans, { maxSamples: 2 });+ expect(result.invalidSpanCount).toBe(50);+ expect(result.scopeNames.length).toBe(2);+ expect(result.reasonCounts).toEqual({+ "traceId:absent": 50,+ "spanId:absent": 50,+ });+ });+});diff --git a/packages/shared/src/server/otel/utils.ts b/packages/shared/src/server/otel/utils.tsindex 1783da3204..bc8b5cef03 100644--- a/packages/shared/src/server/otel/utils.ts+++ b/packages/shared/src/server/otel/utils.ts@@ -2,6 +2,178 @@ export function isValidDateString(dateString: string): boolean {return !isNaN(new Date(dateString).getTime());}+export type OtelIdRejectionReason = "absent" | "not_an_id";++/**+ * Whether an OTLP trace/span id can be converted by+ * OtelIngestionProcessor.parseId, which returns strings unchanged and otherwise+ * calls `Buffer.from()`. Returns null when it can.+ */+export function getOtelIdRejectionReason(+ value: unknown,+): OtelIdRejectionReason | null {+ if (value === null || value === undefined) return "absent";++ // parseId short-circuits on strings, so any string is convertible.+ if (typeof value === "string") return null;++ // Uint8Array/Buffer from a protobuf decode, int arrays from the Python SDK.+ if (value instanceof Uint8Array || Array.isArray(value)) return null;++ // A Buffer that has been through JSON. Matched explicitly rather than by+ // probing Buffer.from, which must never see attacker-controlled input on the+ // request path: it also accepts any object carrying a numeric `length` and+ // eagerly zero-fills that many bytes, so `{ length: 8e8 }` in a 94-byte body+ // would block the shared web event loop for seconds. Pathological array-likes+ // are therefore rejected here even though Buffer.from would accept them.+ if (+ typeof value === "object" &&+ (value as { type?: unknown }).type === "Buffer" &&+ Array.isArray((value as { data?: unknown }).data)+ ) {+ return null;+ }++ // Numbers, booleans and every other object shape throw in Buffer.from β+ // including the untagged `{ data: [...] }` envelope, which the worker's+ // processToEvent path (OtelIngestionProcessor.ts:322) hands to parseId+ // without the `?.data` unwrap the other call sites apply.+ return "not_an_id";+}++export interface OtelSpanIdValidationResult {+ totalSpanCount: number;+ invalidSpanCount: number;+ /**+ * `scopeSpans`/`spans` fields that are present but not arrays. Counted+ * separately from `invalidSpanCount` because there is no span to attribute+ * them to β the collection that would hold the spans is itself unusable.+ */+ malformedCollectionCount: number;+ /**+ * Rejections per `<field>:<reason>` pair, e.g.+ * `{ "traceId:absent": 8, "spanId:not_an_id": 2 }`.+ *+ * A span with both a bad traceId and a bad spanId counts once under each, so+ * these can sum above `invalidSpanCount`. The key set is bounded by+ * construction (the id fields x the reason union, plus the two+ * `not_an_array` keys), which is what makes it safe to use as a metric tag+ * and why it is not sampled.+ */+ reasonCounts: Record<string, number>;+ /** Deduped `<field>:<reason>` pairs, e.g. "traceId:absent". */+ reasons: string[];+ /** Deduped instrumentation scope names of the offending spans, sampled. */+ scopeNames: string[];+}++/**+ * Walk a decoded OTLP trace export and report everything that makes it+ * unprocessable downstream: spans whose traceId, spanId or (when present)+ * parentSpanId cannot be converted, and `scopeSpans`/`spans` fields that are+ * present but not arrays.+ *+ * An unconvertible id throws ERR_INVALID_ARG_TYPE in parseId, failing the queue+ * job through every retry attempt. The dominant real-world source is an OTLP+ * *logs* export sent to the traces endpoint β ResourceLogs and ResourceSpans+ * share protobuf field numbers, so log records decode into spans that carry a+ * valid instrumentation scope but no ids at all.+ *+ * Non-array collections cannot be converted either: the worker iterates the+ * same fields behind a `?? []` fallback, which does not guard a non-nullish+ * non-array, so `for...of` throws there and the job fails through every retry.+ * Reporting them here lets the endpoint reject the payload instead. Absent and+ * empty collections stay valid β only a present, non-array value is a defect.+ */+export function validateOtelSpanIds(+ resourceSpans: unknown,+ { maxSamples = 5 }: { maxSamples?: number } = {},+): OtelSpanIdValidationResult {+ let totalSpanCount = 0;+ let invalidSpanCount = 0;+ let malformedCollectionCount = 0;+ const reasonCounts: Record<string, number> = {};+ const scopeNames = new Set<string>();++ const countReason = (reason: string) => {+ reasonCounts[reason] = (reasonCounts[reason] ?? 0) + 1;+ };++ if (!Array.isArray(resourceSpans)) {+ return {+ totalSpanCount,+ invalidSpanCount,+ malformedCollectionCount,+ reasonCounts,+ reasons: [],+ scopeNames: [],+ };+ }++ for (const resourceSpan of resourceSpans) {+ // Never hand a non-array to for...of: a `?? []` fallback does not guard a+ // non-nullish non-iterable (`{}`, a number), and this runs on the request+ // path, so throwing here would surface as a 500 rather than a rejection.+ const scopeSpans = (resourceSpan as any)?.scopeSpans;+ if (!Array.isArray(scopeSpans)) {+ if (scopeSpans !== null && scopeSpans !== undefined) {+ malformedCollectionCount++;+ countReason("scopeSpans:not_an_array");+ }+ continue;+ }++ for (const scopeSpan of scopeSpans) {+ const spans = scopeSpan?.spans;+ if (!Array.isArray(spans)) {+ if (spans !== null && spans !== undefined) {+ malformedCollectionCount++;+ countReason("spans:not_an_array");+ const malformedScope = scopeSpan?.scope?.name;+ if (malformedScope && scopeNames.size < maxSamples) {+ scopeNames.add(String(malformedScope));+ }+ }+ continue;+ }++ for (const span of spans) {+ totalSpanCount++;++ const spanReasons: string[] = [];+ for (const kind of ["traceId", "spanId"] as const) {+ const reason = getOtelIdRejectionReason(span?.[kind]);+ if (reason) spanReasons.push(`${kind}:${reason}`);+ }+ // parentSpanId is optional and the worker only converts it when truthy+ // (OtelIngestionProcessor.ts:325), so an absent one is legitimate and+ // only a present-but-unconvertible value crashes there.+ if (span?.parentSpanId) {+ const reason = getOtelIdRejectionReason(span.parentSpanId);+ if (reason) spanReasons.push(`parentSpanId:${reason}`);+ }+ if (spanReasons.length === 0) continue;++ invalidSpanCount++;+ spanReasons.forEach(countReason);+ const scopeName = scopeSpan?.scope?.name;+ if (scopeName && scopeNames.size < maxSamples) {+ scopeNames.add(String(scopeName));+ }+ }+ }+ }++ return {+ totalSpanCount,+ invalidSpanCount,+ malformedCollectionCount,+ reasonCounts,+ reasons: Object.keys(reasonCounts),+ scopeNames: [...scopeNames],+ };+}+/*** Flattens a nested JSON object into path-based names and string values.* For example: {foo: {bar: "baz", num: 42}} becomes:diff --git a/web/src/__tests__/server/otel-api.servertest.ts b/web/src/__tests__/server/otel-api.servertest.tsindex 9fbac23aa4..48ece9db54 100644--- a/web/src/__tests__/server/otel-api.servertest.ts+++ b/web/src/__tests__/server/otel-api.servertest.ts@@ -488,6 +488,89 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {});});+ // Both rejection gates in one request: spans with unusable ids, and a+ // scopeSpans that is present but not an array. The latter used to be accepted+ // here and then fail the queue job through every retry attempt, because the+ // worker iterates that field behind a `?? []` fallback which does not guard a+ // non-nullish non-array.+ it("should reject unprocessable spans and non-array collections", async () => {+ const response = await makeAPICall<{ error: string }>(+ "POST",+ "/api/public/otel/v1/traces",+ {+ resourceSpans: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: { name: "uvicorn.access" },+ spans: [+ // Both ids absent, and an id of a type Buffer.from rejects.+ { traceState: "INFO" },+ { traceId: 42, spanId: 42 },+ ],+ },+ ],+ },+ { resource: { attributes: [] }, scopeSpans: {} },+ ],+ },+ );++ expect(response.status).toBe(400);+ expect(response.body.error).toContain("2 of 2 span(s)");+ expect(response.body.error).toContain("1 scopeSpans/spans field(s)");+ expect(response.body.error).toContain("scopeSpans:not_an_array");+ expect(response.body.error).toContain("uvicorn.access");+ });++ // An OTLP *logs* export pointed at this endpoint. ResourceLogs and+ // ResourceSpans share protobuf field numbers, so log records decode into+ // spans that keep a valid instrumentation scope but carry no ids, which used+ // to fail in the worker and burn all six queue attempts.+ it("should reject an OTLP logs payload sent to the traces endpoint", async () => {+ const requestBody =+ $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.encode(+ $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.fromObject(+ {+ resourceLogs: [+ {+ resource: { attributes: [] },+ scopeLogs: [+ {+ scope: { name: "codex_otel.log_only" },+ logRecords: [{ severityText: "INFO" }],+ },+ ],+ },+ ],+ },+ ),+ ).finish();++ // makeAPICall JSON-stringifies its body, so send the binary payload+ // with a plain fetch instead.+ const response = await fetch(+ "http://localhost:3000/api/public/otel/v1/traces",+ {+ method: "POST",+ headers: {+ "Content-Type": "application/x-protobuf",+ Authorization: createBasicAuthHeader(+ "pk-lf-1234567890",+ "sk-lf-1234567890",+ ),+ },+ body: requestBody,+ },+ );++ expect(response.status).toBe(400);+ const body = await response.json();+ expect(body.error).toContain("traceId:absent");+ expect(body.error).toContain("codex_otel.log_only");+ });+it("should transform deployment.environment to lowercase", async () => {const traceId = randomBytes(16);const spanId = randomBytes(8);diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 9701735288..318106b550 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -8,6 +8,8 @@ import {markProjectAsOtelUser,createIngestionAttribution,getLangfuseHeaderValue,+ recordIncrement,+ validateOtelSpanIds,} from "@langfuse/shared/src/server";import { z } from "zod";import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";@@ -110,6 +112,94 @@ export default withMiddlewares({return {};}+ // Reject payloads the worker cannot convert: spans whose traceId/spanId is+ // missing or malformed, and scopeSpans/spans fields that are present but+ // not arrays. Both fail in the worker β parseId throws+ // ERR_INVALID_ARG_TYPE or yields a truncated id, and a non-array+ // collection throws on for...of β so the job burns all six attempts before+ // being dropped anyway. Failing here returns a non-retryable status+ // instead.+ //+ // The common source is an OTLP *logs* export pointed at this endpoint.+ // ResourceLogs and ResourceSpans share protobuf field numbers, so log+ // records decode into spans with a valid instrumentation scope but no ids.+ //+ // One invalid span means the whole export is almost certainly malformed,+ // so the batch is rejected as a unit and the response says so explicitly+ // rather than dropping spans silently.+ const idValidation = validateOtelSpanIds(resourceSpans);+ if (+ idValidation.invalidSpanCount > 0 ||+ idValidation.malformedCollectionCount > 0+ ) {+ // One increment per reason, so a batch that mixes reasons splits across+ // them instead of attributing every rejected span to whichever reason+ // happened to come first. The tag set is bounded by construction.+ for (const [reason, count] of Object.entries(+ idValidation.reasonCounts,+ )) {+ recordIncrement(+ "langfuse.ingestion.otel.rejected_invalid_span_ids",+ count,+ { reason },+ );+ }+ const rejectionContext = {+ projectId: auth.scope.projectId,+ invalidSpanCount: idValidation.invalidSpanCount,+ malformedCollectionCount: idValidation.malformedCollectionCount,+ totalSpanCount: idValidation.totalSpanCount,+ reasonCounts: idValidation.reasonCounts,+ instrumentationScopes: idValidation.scopeNames,+ sdkName: req.headers["x-langfuse-sdk-name"],+ };+ logger.warn(+ "Rejecting unprocessable OTEL trace export",+ rejectionContext,+ );++ // Rejecting the batch as a unit rests on the assumption that a bad+ // export is bad throughout: an OTLP logs payload decoded as spans+ // yields uniformly id-less spans, so invalidSpanCount should equal+ // totalSpanCount. Any gap means this rejection just discarded spans+ // that would have ingested fine, which is data loss and invalidates+ // the assumption β escalate so it cannot pass unnoticed among warns.+ const discardedValidSpans =+ idValidation.totalSpanCount - idValidation.invalidSpanCount;+ if (discardedValidSpans > 0) {+ logger.error(+ "Rejected OTEL trace export contained valid spans β batch rejection discarded them",+ { ...rejectionContext, discardedValidSpans },+ );+ }++ const problems: string[] = [];+ if (idValidation.invalidSpanCount > 0) {+ problems.push(+ `${idValidation.invalidSpanCount} of ${idValidation.totalSpanCount} ` ++ `span(s) are missing a traceId or spanId, or carry one that cannot ` ++ `be decoded β each must be a string or a byte array`,+ );+ }+ if (idValidation.malformedCollectionCount > 0) {+ problems.push(+ `${idValidation.malformedCollectionCount} scopeSpans/spans field(s) ` ++ `are present but not arrays`,+ );+ }++ res.status(400);+ return {+ error:+ `Invalid OTLP trace export: ${problems.join("; ")} ` ++ `(${idValidation.reasons.join(", ")}). The entire export was rejected ` ++ `and no spans were ingested. ` ++ `Instrumentation scopes: ${idValidation.scopeNames.join(", ") || "unknown"}. ` ++ `This endpoint accepts OpenTelemetry traces only β if you are exporting ` ++ `OpenTelemetry logs, point your log exporter elsewhere.`,+ };+ }+// Warn on oversized OTEL request bodies (16MB threshold)const bodyBytes = body.byteLength;if (bodyBytes > 16 * 1024 * 1024) {