πͺ’ 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 non-array attributes and events with a 400 (#15793)
Steffen Schmitz7ef70b51d124
diff --git a/packages/shared/src/server/otel/utils.test.ts b/packages/shared/src/server/otel/utils.test.tsindex e2bda8f0b2..0579c49226 100644--- a/packages/shared/src/server/otel/utils.test.ts+++ b/packages/shared/src/server/otel/utils.test.ts@@ -160,6 +160,109 @@ describe("validateOtelSpanIds", () => {});});+ // The production payload (prod-us, 2026-08-04): a hand-rolled exporter that+ // serializes span attributes as a JSON object instead of an OTLP KeyValue+ // list. Every id is valid hex and both collections are arrays, so the id+ // checks wave it through β and then extractSpanAttributes reduces over the+ // object in the worker and fails the file through all six attempts.+ it("rejects span attributes serialized as a JSON object", () => {+ const result = validateOtelSpanIds([+ {+ resource: {+ attributes: [+ { key: "service.name", value: { stringValue: "ai-control-plane" } },+ ],+ },+ scopeSpans: [+ {+ scope: { name: "ai-control-plane.agent", version: "1.0.0" },+ spans: [+ {+ traceId: "631d6c6420ad4a7598b5f496f614c8b5",+ spanId: "424e9dc6ea864dee",+ parentSpanId: "f51a5c11ad4f4a96",+ name: "Capability: document_retrieval",+ kind: "INTERNAL",+ startTimeUnixNano: "1785884062122000000",+ attributes: {+ "capability.id": "document_retrieval",+ "run.id": "agent-1785884041268-eou2re",+ },+ },+ ],+ },+ ],+ },+ ]);+ expect(result).toMatchObject({ totalSpanCount: 1, invalidSpanCount: 1 });+ expect(result.reasonCounts).toEqual({ "attributes:not_an_array": 1 });+ expect(result.scopeNames).toEqual(["ai-control-plane.agent"]);+ });++ // The worker reduces over span attributes and filters over span events, so a+ // present-but-non-array value in any of them throws there just like a bad id.+ // Each is attributable to a span, so each counts as an invalid span and keeps+ // the endpoint's discardedValidSpans invariant exact.+ it.each([+ {+ shape: "object attributes",+ span: {+ traceId: TRACE_ID,+ spanId: SPAN_ID,+ attributes: { "run.id": "agent-1" },+ },+ reason: "attributes:not_an_array",+ },+ {+ shape: "object events",+ span: { traceId: TRACE_ID, spanId: SPAN_ID, events: {} },+ reason: "events:not_an_array",+ },+ {+ shape: "object attributes on a span event",+ span: {+ traceId: TRACE_ID,+ spanId: SPAN_ID,+ events: [{ name: "gen_ai.choice", attributes: { role: "assistant" } }],+ },+ reason: "event.attributes:not_an_array",+ },+ ])("rejects a span with $shape", ({ span, reason }) => {+ const result = validateOtelSpanIds(wrap([span]));+ expect(result).toMatchObject({ totalSpanCount: 1, invalidSpanCount: 1 });+ expect(result.reasons).toEqual([reason]);+ expect(result.scopeNames).toEqual(["my-tracer"]);+ });++ // Resource and scope attributes are reduced before any span is touched, so+ // they fail the file even when the subtree holds no spans at all. There is no+ // span to attribute them to, so they land in malformedCollectionCount.+ it.each([+ {+ shape: "the resource",+ payload: [{ resource: { attributes: {} }, scopeSpans: [] }],+ reason: "resource.attributes:not_an_array",+ },+ {+ shape: "the instrumentation scope",+ payload: [+ {+ scopeSpans: [+ { scope: { name: "my-tracer", attributes: {} }, spans: [] },+ ],+ },+ ],+ reason: "scope.attributes:not_an_array",+ },+ ])("rejects non-array attributes on $shape", ({ payload, reason }) => {+ const result = validateOtelSpanIds(payload);+ expect(result).toMatchObject({+ invalidSpanCount: 0,+ malformedCollectionCount: 1,+ });+ expect(result.reasons).toEqual([reason]);+ });+// Absent and empty collections are legitimate and must stay accepted.it.each([{ shape: "non-array", payload: undefined },@@ -169,6 +272,29 @@ describe("validateOtelSpanIds", () => {payload: [{ scopeSpans: [{ scope: null, spans: null }] }],},{ shape: "empty spans", payload: [{ scopeSpans: [{ spans: [] }] }] },+ // Over-rejection guard: the overwhelming majority of real exports omit or+ // empty these, and flagging them would 400 traffic that ingests fine today.+ {+ shape: "absent and empty attributes and events",+ payload: [+ {+ resource: {},+ scopeSpans: [+ {+ scope: { name: "my-tracer", attributes: [] },+ spans: [+ {+ traceId: TRACE_ID,+ spanId: SPAN_ID,+ attributes: [],+ events: [{ name: "gen_ai.choice" }],+ },+ ],+ },+ ],+ },+ ],+ },])("accepts $shape", ({ payload }) => {const result = validateOtelSpanIds(payload);expect(result.invalidSpanCount).toBe(0);diff --git a/packages/shared/src/server/otel/utils.ts b/packages/shared/src/server/otel/utils.tsindex bc8b5cef03..4b31011859 100644--- a/packages/shared/src/server/otel/utils.ts+++ b/packages/shared/src/server/otel/utils.ts@@ -41,13 +41,25 @@ export function getOtelIdRejectionReason(return "not_an_id";}+/**+ * Whether an OTLP field that must hold a list β `attributes`, `events`,+ * `scopeSpans`, `spans` β is present but not an array. Absent and empty are+ * legitimate and stay valid; only a present, non-array value is a defect.+ */+function isMalformedList(value: unknown): boolean {+ return value !== null && value !== undefined && !Array.isArray(value);+}+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.+ * `scopeSpans`/`spans` fields that are present but not arrays, and non-array+ * `attributes` on a resource or an instrumentation scope. Counted separately+ * from `invalidSpanCount` because there is no span to attribute them to β+ * either the collection that would hold the spans is itself unusable, or the+ * defect sits above the spans and fails the export even when the subtree+ * holds none.*/malformedCollectionCount: number;/**@@ -56,9 +68,9 @@ export interface OtelSpanIdValidationResult {** 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.+ * construction (the id fields x the reason union, plus the `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". */@@ -70,8 +82,8 @@ export interface OtelSpanIdValidationResult {/*** 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.+ * parentSpanId cannot be converted, and `scopeSpans`, `spans`, `attributes` or+ * `events` 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@@ -79,11 +91,19 @@ export interface OtelSpanIdValidationResult {* 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.+ * Non-array collections cannot be converted either. The worker iterates+ * `scopeSpans`/`spans` behind a `?? []` fallback, which does not guard a+ * non-nullish non-array, so `for...of` throws; it reduces over `attributes`+ * (resource, scope, span and span-event level) and filters over `events`, which+ * throw on anything without those methods. The observed source is a hand-rolled+ * OTLP/JSON exporter emitting attributes as a `{key: value}` object instead of a+ * KeyValue list β only reachable over `application/json`, since a protobuf+ * decode always materializes repeated fields as arrays.+ *+ * Reporting all of it here lets the endpoint reject the payload with a 400+ * instead of accepting it and losing the whole file six attempts later. Absent+ * and empty collections stay valid β only a present, non-array value is a+ * defect.*/export function validateOtelSpanIds(resourceSpans: unknown,@@ -110,7 +130,20 @@ export function validateOtelSpanIds(};}+ const sampleScopeName = (scopeName: unknown) => {+ if (scopeName && scopeNames.size < maxSamples) {+ scopeNames.add(String(scopeName));+ }+ };+for (const resourceSpan of resourceSpans) {+ // extractResourceAttributes reduces this before any span is reached, so a+ // map-shaped one fails the export even for a resource carrying no spans.+ if (isMalformedList((resourceSpan as any)?.resource?.attributes)) {+ malformedCollectionCount++;+ countReason("resource.attributes:not_an_array");+ }+// 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.@@ -124,15 +157,20 @@ export function validateOtelSpanIds(}for (const scopeSpan of scopeSpans) {+ // Same as the resource: extractScopeAttributes runs per scopeSpan,+ // independently of how many spans it holds.+ if (isMalformedList(scopeSpan?.scope?.attributes)) {+ malformedCollectionCount++;+ countReason("scope.attributes:not_an_array");+ sampleScopeName(scopeSpan?.scope?.name);+ }+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));- }+ sampleScopeName(scopeSpan?.scope?.name);}continue;}@@ -152,14 +190,30 @@ export function validateOtelSpanIds(const reason = getOtelIdRejectionReason(span.parentSpanId);if (reason) spanReasons.push(`parentSpanId:${reason}`);}++ // Attributed to the span rather than counted as a malformed collection,+ // so that a span carrying one stays outside the endpoint's+ // discardedValidSpans invariant β it is genuinely unprocessable, not a+ // valid span caught by a batch rejection.+ if (isMalformedList(span?.attributes)) {+ spanReasons.push("attributes:not_an_array");+ }+ if (isMalformedList(span?.events)) {+ spanReasons.push("events:not_an_array");+ } else if (Array.isArray(span?.events)) {+ // One bad event is enough to fail the span, and the reason is the same+ // for every further one, so stop at the first.+ if (+ span.events.some((event: any) => isMalformedList(event?.attributes))+ )+ spanReasons.push("event.attributes:not_an_array");+ }+if (spanReasons.length === 0) continue;invalidSpanCount++;spanReasons.forEach(countReason);- const scopeName = scopeSpan?.scope?.name;- if (scopeName && scopeNames.size < maxSamples) {- scopeNames.add(String(scopeName));- }+ sampleScopeName(scopeSpan?.scope?.name);}}}diff --git a/web/src/__tests__/server/otel-api.servertest.ts b/web/src/__tests__/server/otel-api.servertest.tsindex 48ece9db54..8635462efa 100644--- a/web/src/__tests__/server/otel-api.servertest.ts+++ b/web/src/__tests__/server/otel-api.servertest.ts@@ -519,11 +519,57 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {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(+ "1 resource- or scope-level field(s)",+ );expect(response.body.error).toContain("scopeSpans:not_an_array");expect(response.body.error).toContain("uvicorn.access");});+ // The prod-us shape: ids are valid hex and every collection is an array+ // except the span attributes, which a hand-rolled OTLP/JSON exporter emitted+ // as a {key: value} object. It cleared the id validation and then failed in+ // the worker on attributes.reduce, losing the file after all six attempts.+ it("should reject span attributes sent as a JSON object", async () => {+ const response = await makeAPICall<{ error: string }>(+ "POST",+ "/api/public/otel/v1/traces",+ {+ resourceSpans: [+ {+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "ai-control-plane" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: { name: "ai-control-plane.agent", version: "1.0.0" },+ spans: [+ {+ traceId: randomBytes(16).toString("hex"),+ spanId: randomBytes(8).toString("hex"),+ name: "Capability: document_retrieval",+ attributes: { "capability.id": "document_retrieval" },+ },+ ],+ },+ ],+ },+ ],+ },+ );++ expect(response.status).toBe(400);+ expect(response.body.error).toContain("1 of 1 span(s)");+ expect(response.body.error).toContain("attributes:not_an_array");+ expect(response.body.error).toContain("not a JSON object");+ expect(response.body.error).toContain("ai-control-plane.agent");+ });+// 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 useddiff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 318106b550..ecd8093528 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -113,16 +113,18 @@ export default withMiddlewares({}// 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+ // missing or malformed, and scopeSpans/spans/attributes/events fields that+ // are present but not arrays. All 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.+ // collection throws on for...of, reduce or filter β 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.+ // The other observed source is a hand-rolled OTLP/JSON exporter writing+ // attributes as a {key: value} object rather than a KeyValue list.//// 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@@ -164,9 +166,17 @@ export default withMiddlewares({// 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.+ //+ // Only meaningful when every defect was span-attributable. A malformed+ // resource- or scope-level collection fails its whole subtree in the+ // worker no matter how sound the individual spans underneath are, so+ // counting those spans as discarded-but-valid would be a false alarm.const discardedValidSpans =idValidation.totalSpanCount - idValidation.invalidSpanCount;- if (discardedValidSpans > 0) {+ if (+ discardedValidSpans > 0 &&+ idValidation.malformedCollectionCount === 0+ ) {logger.error("Rejected OTEL trace export contained valid spans β batch rejection discarded them",{ ...rejectionContext, discardedValidSpans },@@ -177,14 +187,39 @@ export default withMiddlewares({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`,+ `span(s) cannot be processed`,);}if (idValidation.malformedCollectionCount > 0) {problems.push(- `${idValidation.malformedCollectionCount} scopeSpans/spans field(s) ` +- `are present but not arrays`,+ `${idValidation.malformedCollectionCount} resource- or scope-level ` ++ `field(s) are present but not arrays`,+ );+ }++ // Name the contract that was broken, so a hand-rolled exporter can be+ // corrected from the response alone rather than by guessing at the+ // reason keys.+ const hints: string[] = [];+ if (+ idValidation.reasons.some(+ (reason) =>+ reason.endsWith(":absent") || reason.endsWith(":not_an_id"),+ )+ ) {+ hints.push(+ `traceId and spanId are required on every span, and each must be a ` ++ `string or a byte array.`,+ );+ }+ if (+ idValidation.reasons.some((reason) =>+ reason.endsWith(":not_an_array"),+ )+ ) {+ hints.push(+ `scopeSpans, spans, attributes and events must all be arrays β OTLP ` ++ `attributes are a list of {key, value} entries, not a JSON object.`,);}@@ -192,8 +227,8 @@ export default withMiddlewares({return {error:`Invalid OTLP trace export: ${problems.join("; ")} ` +- `(${idValidation.reasons.join(", ")}). The entire export was rejected ` +- `and no spans were ingested. ` ++ `(${idValidation.reasons.join(", ")}). ${hints.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.`,