Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

test(ingestion): red tests for metadata_dropped metric (LFE-14342, LFE-14345) (#15269)

Niklas Semmlere0d2bde60b12
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts
new file mode 100644
index 0000000000..09e6d51baa
--- /dev/null
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.metadataDropped.test.ts
@@ -0,0 +1,650 @@
+/**
+ * LFE-14342: `langfuse.ingestion.metadata_dropped` counter at the OTel
+ * metadata drop site (`parseMetadataAttribute` drop branches).
+ *
+ * Spec under test:
+ * - Counter name: langfuse.ingestion.metadata_dropped
+ * - Tags: reason ∈ {non_object_top_level, parse_failure, primitive},
+ * source = otel, domain ∈ {trace, observation}
+ * - project_id must NOT be a metric tag (cardinality)
+ * - No behavior change to what the processor returns
+ * - Dotted-key metadata (langfuse.*.metadata.foo) stays increment-free
+ *
+ * recordIncrement is mocked at module level: the processor imports it from
+ * the src/server barrel, which re-exports ./instrumentation β€” mocking the
+ * instrumentation module intercepts the call. The "mock plumbing" test
+ * proves that interception chain holds.
+ */
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+const { recordIncrementMock } = vi.hoisted(() => ({
+ recordIncrementMock: vi.fn(),
+}));
+
+vi.mock("../instrumentation", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../instrumentation")>();
+ return {
+ ...actual,
+ recordIncrement: recordIncrementMock,
+ };
+});
+
+// processToIngestionEvents awaits redis.set (seen-traces tracking); CI's
+// tests-shared job has REDIS_HOST set but no Redis server, so ioredis
+// queues the command forever and the suite times out. Stub the client
+// (not null β€” the null path adds a logger.warn, which would break the
+// warn-cap exactly-10 assertion).
+vi.mock("../redis/redis", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../redis/redis")>()),
+ redis: { set: vi.fn().mockResolvedValue("OK") },
+}));
+
+import {
+ OtelIngestionProcessor,
+ type ResourceSpan,
+} from "./OtelIngestionProcessor";
+import * as serverBarrel from "../index";
+
+const METRIC = "langfuse.ingestion.metadata_dropped";
+const PROJECT_ID = "test-project-lfe-14342";
+
+const createProcessor = () =>
+ new OtelIngestionProcessor({
+ projectId: PROJECT_ID,
+ publicKey: "pk-test",
+ sdkName: "python",
+ sdkVersion: "3.8.1",
+ });
+
+type OtelAttribute = { key: string; value: Record<string, unknown> };
+
+const buildBatch = (attributes: OtelAttribute[]): ResourceSpan[] => [
+ {
+ resource: {
+ attributes: [{ key: "service.name", value: { stringValue: "test-svc" } }],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "3.8.1",
+ attributes: [
+ { key: "public_key", value: { stringValue: "pk-test" } },
+ ],
+ },
+ spans: [
+ {
+ traceId: Buffer.from("0123456789abcdef0123456789abcdef", "hex"),
+ spanId: Buffer.from("0123456789abcdef", "hex"),
+ name: "test-span",
+ kind: 1,
+ startTimeUnixNano: "1752384000000000000",
+ endTimeUnixNano: "1752384001000000000",
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "span" },
+ },
+ ...attributes,
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+];
+
+const droppedCalls = () =>
+ recordIncrementMock.mock.calls.filter(([stat]) => stat === METRIC);
+
+const expectDropTags = (
+ call: unknown[],
+ expected: { reason: string; source: string; domain: string },
+) => {
+ const [, value, tags] = call as [
+ string,
+ number | undefined,
+ Record<string, string | number>,
+ ];
+ // recordIncrement(stat) defaults to 1; explicit 1 is equivalent.
+ expect(value ?? 1).toBe(1);
+ expect(tags).toEqual(expect.objectContaining(expected));
+ // Acceptance criterion: project_id is NOT a metric tag (cardinality).
+ expect(Object.keys(tags ?? {})).not.toContain("project_id");
+ expect(Object.keys(tags ?? {})).not.toContain("projectId");
+};
+
+describe("OTel metadata_dropped metric (LFE-14342)", () => {
+ beforeEach(() => {
+ recordIncrementMock.mockClear();
+ });
+
+ it("mock plumbing: server barrel re-exports the mocked recordIncrement", () => {
+ // Load-bearing sanity: the processor imports recordIncrement from the
+ // barrel; if this fails, every red test below would be a false red.
+ expect(serverBarrel.recordIncrement).toBe(recordIncrementMock);
+ });
+
+ describe("drop branches on langfuse.observation.metadata (source=otel, domain=observation)", () => {
+ it("increments with reason=parse_failure when the metadata string is invalid JSON", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: "{invalid json" },
+ },
+ ]),
+ );
+
+ // No behavior change: events are still produced, metadata is dropped.
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "parse_failure",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it("increments with reason=non_object_top_level when the metadata string parses to a non-object", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: "42" },
+ },
+ ]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "non_object_top_level",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it("increments with reason=primitive when the metadata attribute is a non-string primitive", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { intValue: 42 },
+ },
+ ]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "primitive",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+ });
+
+ describe("trace domain", () => {
+ it("increments with domain=trace when langfuse.trace.metadata is dropped", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.trace.metadata",
+ value: { stringValue: "{invalid json" },
+ },
+ ]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls.length).toBeGreaterThanOrEqual(1);
+ const traceCall = calls.find(
+ ([, , tags]) =>
+ (tags as Record<string, string> | undefined)?.domain === "trace",
+ );
+ expect(traceCall).toBeDefined();
+ expectDropTags(traceCall!, {
+ reason: "parse_failure",
+ source: "otel",
+ domain: "trace",
+ });
+ });
+ });
+
+ describe("events path (processToEvent)", () => {
+ it("increments on a dropped observation metadata attribute in the events path too", () => {
+ const events = createProcessor().processToEvent(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: "{invalid json" },
+ },
+ ]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls.length).toBeGreaterThanOrEqual(1);
+ expectDropTags(calls[0], {
+ reason: "parse_failure",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+ });
+
+ describe("silence on valid input", () => {
+ it("does not increment for a valid JSON-object metadata attribute", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: JSON.stringify({ env: "prod" }) },
+ },
+ ]),
+ );
+
+ // Fixture proof: the metadata value flows through into the output.
+ expect(JSON.stringify(events)).toContain("prod");
+ expect(droppedCalls()).toHaveLength(0);
+ });
+
+ it("does not increment for dotted-key metadata attributes", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.observation.metadata.foo",
+ value: { stringValue: "bar-value" },
+ },
+ {
+ key: "langfuse.trace.metadata.baz",
+ value: { stringValue: "qux-value" },
+ },
+ ]),
+ );
+
+ // Fixture proof: dotted-key metadata survives.
+ expect(JSON.stringify(events)).toContain("bar-value");
+ expect(droppedCalls()).toHaveLength(0);
+ });
+ });
+
+ // Reviewer ruling 1 (round 1): one increment per dropped attribute VALUE
+ // per job β€” deduped across the two pipelines the worker runs on the SAME
+ // processor instance, and across domain extractions of a shared attribute
+ // key. Domain tag of a shared key is the first-seen domain.
+ describe("exactly-once semantics across pipelines and domains", () => {
+ const expectSingleDrop = (expectedReason: string) => {
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ const [, value, tags] = calls[0] as [
+ string,
+ number | undefined,
+ Record<string, string | number>,
+ ];
+ expect(value ?? 1).toBe(1);
+ expect(tags).toEqual(
+ expect.objectContaining({ reason: expectedReason, source: "otel" }),
+ );
+ expect(["trace", "observation"]).toContain(tags?.domain);
+ expect(Object.keys(tags ?? {})).not.toContain("project_id");
+ expect(Object.keys(tags ?? {})).not.toContain("projectId");
+ };
+
+ it("counts a dropped attribute once when both pipelines run on one processor instance", async () => {
+ // Mirrors the worker job: processToIngestionEvents then processToEvent
+ // with the same parsed spans on the same instance.
+ const processor = createProcessor();
+ const batch = buildBatch([
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: "{invalid json" },
+ },
+ ]);
+
+ const ingestionEvents = await processor.processToIngestionEvents(batch);
+ const events = processor.processToEvent(batch);
+
+ expect(ingestionEvents.length).toBeGreaterThan(0);
+ expect(events.length).toBeGreaterThan(0);
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "parse_failure",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it("counts the shared langfuse.metadata compat key once across trace and observation extraction", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.metadata",
+ value: { stringValue: "{invalid json" },
+ },
+ ]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+ expectSingleDrop("parse_failure");
+ });
+
+ // Reviewer ruling 2 (round 1): falsy-but-present values on the compat
+ // key are drops β€” non-string primitives as reason=primitive, "" as
+ // reason=parse_failure (JSON.parse("") throws). Returned values stay
+ // unchanged; a truly absent attribute stays increment-free.
+ it("counts langfuse.metadata = false as a primitive drop", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([{ key: "langfuse.metadata", value: { boolValue: false } }]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+ expectSingleDrop("primitive");
+ });
+
+ it("counts langfuse.metadata = 0 as a primitive drop", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([{ key: "langfuse.metadata", value: { intValue: 0 } }]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+ expectSingleDrop("primitive");
+ });
+
+ it('counts langfuse.metadata = "" as a parse_failure drop', async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([{ key: "langfuse.metadata", value: { stringValue: "" } }]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+ expectSingleDrop("parse_failure");
+ });
+
+ it("does not increment when no metadata attribute is present at all", async () => {
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([]),
+ );
+
+ expect(events.length).toBeGreaterThan(0);
+ expect(droppedCalls()).toHaveLength(0);
+ });
+
+ it("does not increment for a valid JSON object on the langfuse.metadata compat key", async () => {
+ // Fixture proof that the compat key reaches metadata extraction at
+ // all β€” if this fails, the falsy-value fixtures above cannot reach
+ // the parser either (report as a finding, not a test problem).
+ const events = await createProcessor().processToIngestionEvents(
+ buildBatch([
+ {
+ key: "langfuse.metadata",
+ value: { stringValue: JSON.stringify({ env: "compat-prod" }) },
+ },
+ ]),
+ );
+
+ expect(JSON.stringify(events)).toContain("compat-prod");
+ expect(droppedCalls()).toHaveLength(0);
+ });
+ });
+
+ // Adversarial-gate rulings (round 2). Shared fixture builders for
+ // multi-resourceSpan / multi-span batches.
+ describe("adversarial rulings", () => {
+ const makeSpan = (attributes: OtelAttribute[], spanIdHex: string) => ({
+ traceId: Buffer.from("0123456789abcdef0123456789abcdef", "hex"),
+ spanId: Buffer.from(spanIdHex, "hex"),
+ name: "test-span",
+ kind: 1,
+ startTimeUnixNano: "1752384000000000000",
+ endTimeUnixNano: "1752384001000000000",
+ attributes: [
+ { key: "langfuse.observation.type", value: { stringValue: "span" } },
+ ...attributes,
+ ],
+ status: {},
+ });
+
+ const makeResourceSpan = (
+ resourceAttrs: OtelAttribute[],
+ spans: ReturnType<typeof makeSpan>[],
+ ): ResourceSpan => ({
+ resource: {
+ attributes: [
+ { key: "service.name", value: { stringValue: "test-svc" } },
+ ...resourceAttrs,
+ ],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "3.8.1",
+ attributes: [
+ { key: "public_key", value: { stringValue: "pk-test" } },
+ ],
+ },
+ spans,
+ },
+ ],
+ });
+
+ const expectDropReasons = (expectedReasons: string[]) => {
+ const calls = droppedCalls();
+ expect(
+ calls
+ .map(
+ ([, , tags]) =>
+ (tags as Record<string, string> | undefined)?.reason,
+ )
+ .sort(),
+ ).toEqual([...expectedReasons].sort());
+ for (const [, value, tags] of calls) {
+ expect((value as number | undefined) ?? 1).toBe(1);
+ expect(tags).toEqual(expect.objectContaining({ source: "otel" }));
+ expect(["trace", "observation"]).toContain(
+ (tags as Record<string, string>)?.domain,
+ );
+ expect(Object.keys(tags ?? {})).not.toContain("project_id");
+ expect(Object.keys(tags ?? {})).not.toContain("projectId");
+ }
+ };
+
+ // RULING A: dedup is scoped per resourceSpan, not per processor
+ // instance β€” distinct resourceSpans in one job count separately.
+ describe("resource-scope dedup", () => {
+ it("counts bad resource-level metadata once per resourceSpan, not once per job", async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [{ key: "langfuse.metadata", value: { stringValue: "{bad-one" } }],
+ [makeSpan([], "0000000000000001")],
+ ),
+ makeResourceSpan(
+ [{ key: "langfuse.metadata", value: { stringValue: "{bad-two" } }],
+ [makeSpan([], "0000000000000002")],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ expectDropReasons(["parse_failure", "parse_failure"]);
+ });
+
+ it("counts one resourceSpan's bad resource-level metadata once even with multiple spans", async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [{ key: "langfuse.metadata", value: { stringValue: "{bad-one" } }],
+ [
+ makeSpan([], "0000000000000001"),
+ makeSpan([], "0000000000000002"),
+ ],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ expectDropReasons(["parse_failure"]);
+ });
+ });
+
+ // RULING B: falsy-but-present PRIMARY keys count (supersedes the
+ // compat-key-only scoping of round-1 ruling 2). Truly-absent stays
+ // zero β€” pinned by "does not increment when no metadata attribute is
+ // present at all" above.
+ describe("falsy-present primary keys", () => {
+ it("counts langfuse.observation.metadata = false as a primitive drop", async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [],
+ [
+ makeSpan(
+ [
+ {
+ key: "langfuse.observation.metadata",
+ value: { boolValue: false },
+ },
+ ],
+ "0000000000000001",
+ ),
+ ],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "primitive",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it("counts langfuse.observation.metadata = 0 as a primitive drop", async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [],
+ [
+ makeSpan(
+ [
+ {
+ key: "langfuse.observation.metadata",
+ value: { intValue: 0 },
+ },
+ ],
+ "0000000000000001",
+ ),
+ ],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "primitive",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it('counts langfuse.observation.metadata = "" as a parse_failure drop', async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [],
+ [
+ makeSpan(
+ [
+ {
+ key: "langfuse.observation.metadata",
+ value: { stringValue: "" },
+ },
+ ],
+ "0000000000000001",
+ ),
+ ],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectDropTags(calls[0], {
+ reason: "parse_failure",
+ source: "otel",
+ domain: "observation",
+ });
+ });
+
+ it("counts a falsy-present primary key AND a malformed compat key as two drops", async () => {
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan(
+ [],
+ [
+ makeSpan(
+ [
+ {
+ key: "langfuse.observation.metadata",
+ value: { boolValue: false },
+ },
+ {
+ key: "langfuse.metadata",
+ value: { stringValue: "{bad" },
+ },
+ ],
+ "0000000000000001",
+ ),
+ ],
+ ),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ expectDropReasons(["parse_failure", "primitive"]);
+ });
+ });
+
+ // RULING C: logger.warn from the drop path is capped at 10 per
+ // processor instance (per job); the metric keeps counting past the cap.
+ describe("warn cap", () => {
+ it("caps drop-path warns at 10 per instance while increments keep counting", async () => {
+ const warnSpy = vi
+ .spyOn(serverBarrel.logger, "warn")
+ .mockImplementation(() => serverBarrel.logger);
+
+ try {
+ const spans = Array.from({ length: 12 }, (_, i) =>
+ makeSpan(
+ [
+ {
+ key: "langfuse.observation.metadata",
+ // Distinct malformed values so per-value dedup keeps all 12.
+ value: { stringValue: `{bad-${i}` },
+ },
+ ],
+ `00000000000000${(i + 1).toString(16).padStart(2, "0")}`,
+ ),
+ );
+
+ const events = await createProcessor().processToIngestionEvents([
+ makeResourceSpan([], spans),
+ ]);
+
+ expect(events.length).toBeGreaterThan(0);
+ expect(droppedCalls().length).toBeGreaterThan(10);
+ expect(warnSpy).toHaveBeenCalledTimes(10);
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+ });
+ });
+});
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 04351b3ee4..a1d1f0c43f 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -60,12 +60,19 @@ export interface OtelIngestionProcessorConfig {
fileKey?: string;
}
+interface MetadataDropContext {
+ domain: string;
+ attributeKey: string;
+ dropScope: object;
+}
+
interface CreateTraceEventParams {
traceId: string;
startTimeISO: string;
attributes: Record<string, unknown>;
resourceAttributes: Record<string, unknown>;
resourceAttributeMetadata: Record<string, unknown>;
+ spanAttributeMetadata: Record<string, unknown>;
scopeSpan: any;
scopeAttributes: Record<string, unknown>;
isLangfuseSDKSpans: boolean;
@@ -158,7 +165,11 @@ export class OtelIngestionProcessor {
private static readonly OTEL_CONVERSION_FAILURE_METRIC =
"langfuse.ingestion.otel.conversion_failure";
+ private static readonly METADATA_DROP_WARN_CAP = 10;
+
private seenTraces: Set<string> = new Set();
+ private reportedMetadataDrops = new WeakMap<object, Set<string>>();
+ private metadataDropWarnCount = 0;
private isInitialized = false;
private traceEventCounts = {
shallow: 0,
@@ -295,10 +306,12 @@ export class OtelIngestionProcessor {
const spanMetadata = this.extractMetadata(
spanAttributes,
"observation",
+ span,
);
const traceMetadata = this.extractMetadata(
spanAttributes,
"trace",
+ span,
);
const { input, output, filteredAttributes } =
@@ -368,8 +381,10 @@ export class OtelIngestionProcessor {
eventBytes,
});
- const experimentFields =
- this.extractExperimentFields(spanAttributes);
+ const experimentFields = this.extractExperimentFields(
+ spanAttributes,
+ span,
+ );
const spanContext = {
spanId,
@@ -805,10 +820,12 @@ export class OtelIngestionProcessor {
const spanAttributeMetadata = this.extractMetadata(
attributes,
"observation",
+ span,
);
const resourceAttributeMetadata = this.extractMetadata(
resourceAttributes,
"trace",
+ resourceAttributes,
);
const { startTimeISO, endTimeISO } =
OtelIngestionProcessor.resolveSpanTimestamps({
@@ -830,6 +847,7 @@ export class OtelIngestionProcessor {
attributes,
resourceAttributes,
resourceAttributeMetadata,
+ spanAttributeMetadata,
scopeSpan,
scopeAttributes,
isLangfuseSDKSpans,
@@ -871,6 +889,7 @@ export class OtelIngestionProcessor {
attributes,
resourceAttributes,
resourceAttributeMetadata,
+ spanAttributeMetadata,
scopeSpan,
scopeAttributes,
isLangfuseSDKSpans,
@@ -905,8 +924,8 @@ export class OtelIngestionProcessor {
this.extractName(span.name, attributes),
metadata: {
...resourceAttributeMetadata,
- ...this.extractMetadata(attributes, "trace"),
- ...this.extractMetadata(attributes, "observation"),
+ ...this.extractMetadata(attributes, "trace", span),
+ ...spanAttributeMetadata,
...(isLangfuseSDKSpans ? {} : { attributes: filteredAttributes }),
resourceAttributes,
scope: {
@@ -938,7 +957,7 @@ export class OtelIngestionProcessor {
name: attributes[LangfuseOtelSpanAttributes.TRACE_NAME] as string,
metadata: {
...resourceAttributeMetadata,
- ...this.extractMetadata(attributes, "trace"),
+ ...this.extractMetadata(attributes, "trace", span),
// removed to not remove trace metadata->attributes through subsequent observations
// ...(isLangfuseSDKSpans
// ? {}
@@ -2147,14 +2166,31 @@ export class OtelIngestionProcessor {
private extractMetadata(
attributes: Record<string, unknown>,
domain: "trace" | "observation",
+ dropScope: object,
): Record<string, unknown> {
const metadataKeyPrefix =
domain === "observation"
? LangfuseOtelSpanAttributes.OBSERVATION_METADATA
: LangfuseOtelSpanAttributes.TRACE_METADATA;
+ // A falsy-present primary key dies at the `||` fallback below and never
+ // reaches the parser: count it here, emission-only. Falsy compat values
+ // survive the fallback and are counted by the parser itself.
+ const primaryValue = attributes[metadataKeyPrefix];
+ if (primaryValue !== undefined && primaryValue !== null && !primaryValue) {
+ this.recordMetadataDropped(
+ typeof primaryValue === "string" ? "parse_failure" : "primitive",
+ { domain, attributeKey: metadataKeyPrefix, dropScope },
+ );
+ }
+
const topLevelMetadata = this.parseMetadataAttribute(
- attributes[metadataKeyPrefix] || attributes["langfuse.metadata"],
+ primaryValue || attributes["langfuse.metadata"],
+ {
+ domain,
+ attributeKey: primaryValue ? metadataKeyPrefix : "langfuse.metadata",
+ dropScope,
+ },
);
const langfuseMetadata = this.extractPrefixedMetadataAttributes({
attributes,
@@ -2817,18 +2853,64 @@ export class OtelIngestionProcessor {
return [];
}
- private parseMetadataAttribute(value: unknown): Record<string, unknown> {
- if (!value) {
+ // One increment per dropped attribute VALUE: deduped per drop scope β€”
+ // the span object for span attributes (shared across both worker
+ // pipelines) or the per-resourceSpan attributes object for resource
+ // attributes β€” on (attribute key, reason). Distinct spans/resourceSpans
+ // in one job count separately; the first-seen domain wins the tag.
+ // Warns are capped per instance, increments are not.
+ private recordMetadataDropped(
+ reason: string,
+ context: MetadataDropContext,
+ ): void {
+ const { domain, attributeKey, dropScope } = context;
+ let seen = this.reportedMetadataDrops.get(dropScope);
+ if (!seen) {
+ seen = new Set();
+ this.reportedMetadataDrops.set(dropScope, seen);
+ }
+ const dedupeKey = `${attributeKey}|${reason}`;
+ if (seen.has(dedupeKey)) {
+ return;
+ }
+ seen.add(dedupeKey);
+
+ recordIncrement("langfuse.ingestion.metadata_dropped", 1, {
+ reason,
+ source: "otel",
+ domain,
+ });
+ if (
+ this.metadataDropWarnCount < OtelIngestionProcessor.METADATA_DROP_WARN_CAP
+ ) {
+ this.metadataDropWarnCount += 1;
+ logger.warn("OTEL metadata attribute dropped", {
+ projectId: this.projectId,
+ reason,
+ domain,
+ attributeKey,
+ });
+ }
+ }
+
+ private parseMetadataAttribute(
+ value: unknown,
+ context: MetadataDropContext,
+ ): Record<string, unknown> {
+ if (value === undefined || value === null) {
return {};
}
if (typeof value === "string") {
try {
const parsed = JSON.parse(value);
- return parsed && typeof parsed === "object"
- ? (parsed as Record<string, unknown>)
- : {};
+ if (parsed && typeof parsed === "object") {
+ return parsed as Record<string, unknown>;
+ }
+ this.recordMetadataDropped("non_object_top_level", context);
+ return {};
} catch {
+ this.recordMetadataDropped("parse_failure", context);
return {};
}
}
@@ -2837,6 +2919,7 @@ export class OtelIngestionProcessor {
return value as Record<string, unknown>;
}
+ this.recordMetadataDropped("primitive", context);
return {};
}
@@ -2868,10 +2951,16 @@ export class OtelIngestionProcessor {
private extractMetadataFromPrefix(params: {
attributes: Record<string, unknown>;
prefix: string;
+ domain: string;
+ dropScope: object;
}): Record<string, unknown> {
- const { attributes, prefix } = params;
+ const { attributes, prefix, domain, dropScope } = params;
return {
- ...this.parseMetadataAttribute(attributes[prefix]),
+ ...this.parseMetadataAttribute(attributes[prefix], {
+ domain,
+ attributeKey: prefix,
+ dropScope,
+ }),
...this.extractPrefixedMetadataAttributes({
attributes,
prefixes: [prefix],
@@ -2883,7 +2972,10 @@ export class OtelIngestionProcessor {
* Extracts experiment-related fields from span attributes.
* Returns undefined for fields that are not present.
*/
- private extractExperimentFields(attributes: Record<string, unknown>): {
+ private extractExperimentFields(
+ attributes: Record<string, unknown>,
+ dropScope: object,
+ ): {
experimentId?: string;
experimentName?: string;
experimentDescription?: string;
@@ -2920,6 +3012,8 @@ export class OtelIngestionProcessor {
this.extractMetadataFromPrefix({
attributes,
prefix: LangfuseOtelSpanAttributes.EXPERIMENT_METADATA,
+ domain: "experiment",
+ dropScope,
}),
);
@@ -2928,6 +3022,8 @@ export class OtelIngestionProcessor {
this.extractMetadataFromPrefix({
attributes,
prefix: LangfuseOtelSpanAttributes.EXPERIMENT_ITEM_METADATA,
+ domain: "experiment_item",
+ dropScope,
}),
);
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 594559afb7..4b517b80e7 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -568,6 +568,7 @@ export class IngestionService {
? undefined
: convertDateToClickhouseDateTime(new Date(minTimestamp));
const unexpectedScoreValidationErrors: unknown[] = [];
+ let expectedScoreValidationDrops = 0;
const [clickhouseScoreRecord, scoreRecords] = await Promise.all([
this.getClickhouseRecord({
projectId,
@@ -622,9 +623,11 @@ export class IngestionService {
// Gracefully handle any score schema validation errors, skip the score insert and reject silently.
} catch (error) {
if (
- !(error instanceof InvalidRequestError) &&
- !(error instanceof LangfuseNotFoundError)
+ error instanceof InvalidRequestError ||
+ error instanceof LangfuseNotFoundError
) {
+ expectedScoreValidationDrops += 1;
+ } else {
unexpectedScoreValidationErrors.push(error);
}
@@ -656,6 +659,16 @@ export class IngestionService {
);
}
+ // Count drops only on an attempt that proceeds: a rethrowing batch is
+ // redelivered, and counting it would inflate the metric once per retry.
+ for (let i = 0; i < expectedScoreValidationDrops; i++) {
+ recordIncrement("langfuse.ingestion.metadata_dropped", 1, {
+ reason: "score_validation_dropped",
+ source: "api",
+ domain: "score",
+ });
+ }
+
if (scoreRecords.length === 0 && !clickhouseScoreRecord) {
logger.warn(
`No valid score records found for project: ${projectId} and score: ${entityId}`,
diff --git a/worker/src/services/IngestionService/tests/scoreValidationDroppedMetric.unit.test.ts b/worker/src/services/IngestionService/tests/scoreValidationDroppedMetric.unit.test.ts
new file mode 100644
index 0000000000..e473afdfed
--- /dev/null
+++ b/worker/src/services/IngestionService/tests/scoreValidationDroppedMetric.unit.test.ts
@@ -0,0 +1,241 @@
+/**
+ * LFE-14345: `langfuse.ingestion.metadata_dropped` counter at the score
+ * validation drop site (catch in processScoreEventList).
+ *
+ * Spec under test:
+ * - The catch that silently filters score events on validation failure
+ * (InvalidRequestError / LangfuseNotFoundError) emits the counter with
+ * reason=score_validation_dropped, domain=score, source=api.
+ * - Existing behavior is preserved: the event is still filtered, valid
+ * events in the same batch are still written, unexpected errors still
+ * reject the batch (and must NOT emit the drop counter β€” a rejected
+ * batch is retried, not silently lost).
+ * - project_id is NOT a metric tag; tenant attribution via a log line
+ * that includes the projectId.
+ */
+import { expect, describe, it, vi, beforeEach } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ recordIncrement: vi.fn(),
+ // When set, replaces validateAndInflateScore for the next calls.
+ validateAndInflateScoreOverride: undefined as
+ | ((...args: unknown[]) => unknown)
+ | undefined,
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@langfuse/shared/src/server")>();
+ return {
+ ...actual,
+ recordIncrement: mocks.recordIncrement,
+ validateAndInflateScore: (...args: unknown[]) =>
+ mocks.validateAndInflateScoreOverride
+ ? mocks.validateAndInflateScoreOverride(...args)
+ : (actual.validateAndInflateScore as (...a: unknown[]) => unknown)(
+ ...args,
+ ),
+ };
+});
+
+import { IngestionService } from "../../IngestionService";
+import { logger, type ScoreEventType } from "@langfuse/shared/src/server";
+import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";
+import { TableName } from "../../ClickhouseWriter";
+
+const METRIC = "langfuse.ingestion.metadata_dropped";
+const PROJECT_ID = "test-project-lfe-14345";
+const TIMESTAMP = "2024-10-12T12:13:14.123Z";
+
+const droppedCalls = () =>
+ mocks.recordIncrement.mock.calls.filter(([stat]) => stat === METRIC);
+
+const expectScoreDropTags = (call: unknown[]) => {
+ const [, value, tags] = call as [
+ string,
+ number | undefined,
+ Record<string, string | number>,
+ ];
+ expect(value ?? 1).toBe(1);
+ expect(tags).toEqual(
+ expect.objectContaining({
+ reason: "score_validation_dropped",
+ source: "api",
+ domain: "score",
+ }),
+ );
+ // Acceptance criterion: project_id is NOT a metric tag (cardinality).
+ expect(Object.keys(tags ?? {})).not.toContain("project_id");
+ expect(Object.keys(tags ?? {})).not.toContain("projectId");
+};
+
+const createService = () => {
+ const addToQueue = vi.fn();
+ const ingestionService = new IngestionService(
+ {} as any,
+ {} as any,
+ { addToQueue } as any,
+ {} as any,
+ );
+ vi.spyOn(ingestionService as any, "getClickhouseRecord").mockResolvedValue(
+ null,
+ );
+ return { ingestionService, addToQueue };
+};
+
+const scoreEvent = (body: Record<string, unknown>): ScoreEventType =>
+ ({
+ id: "event-id",
+ timestamp: TIMESTAMP,
+ type: "score-create",
+ body: {
+ id: "score-id",
+ dataType: "NUMERIC",
+ source: "API",
+ traceId: "trace-id",
+ environment: "default",
+ ...body,
+ },
+ }) as ScoreEventType;
+
+const invalidScoreEvent = () =>
+ scoreEvent({ name: "invalid-score", value: "not-a-number" });
+
+const validScoreEvent = () => scoreEvent({ name: "valid-score", value: 1 });
+
+const processScores = (
+ ingestionService: IngestionService,
+ scoreEventList: ScoreEventType[],
+) =>
+ (ingestionService as any).processScoreEventList({
+ projectId: PROJECT_ID,
+ entityId: "score-id",
+ createdAtTimestamp: new Date(TIMESTAMP),
+ scoreEventList,
+ attribution: {
+ ingestionApiKey: "pk-lf-unit-test",
+ ingestionSdkName: "langfuse-test",
+ ingestionSdkVersion: "0.0.0",
+ },
+ });
+
+describe("score validation drop metric (LFE-14345)", () => {
+ beforeEach(() => {
+ mocks.recordIncrement.mockClear();
+ mocks.validateAndInflateScoreOverride = undefined;
+ vi.restoreAllMocks();
+ });
+
+ it("emits score_validation_dropped when a score fails validation (InvalidRequestError path)", async () => {
+ const { ingestionService, addToQueue } = createService();
+ const loggerCalls: unknown[][] = [];
+ for (const level of ["info", "warn", "error"] as const) {
+ vi.spyOn(logger, level).mockImplementation((...args: unknown[]) => {
+ loggerCalls.push(args);
+ return logger;
+ });
+ }
+
+ // Existing behavior: batch with no valid records is silently rejected.
+ await expect(
+ processScores(ingestionService, [invalidScoreEvent()]),
+ ).resolves.toBeUndefined();
+ expect(addToQueue).not.toHaveBeenCalled();
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectScoreDropTags(calls[0]);
+
+ // Acceptance criterion: tenant attribution via logs β€” a log line
+ // emitted during the drop includes the projectId.
+ expect(JSON.stringify(loggerCalls)).toContain(PROJECT_ID);
+ });
+
+ it("emits score_validation_dropped when validation throws LangfuseNotFoundError", async () => {
+ const { ingestionService, addToQueue } = createService();
+ mocks.validateAndInflateScoreOverride = () =>
+ Promise.reject(new LangfuseNotFoundError("score config not found"));
+
+ await expect(
+ processScores(ingestionService, [validScoreEvent()]),
+ ).resolves.toBeUndefined();
+ expect(addToQueue).not.toHaveBeenCalled();
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectScoreDropTags(calls[0]);
+ });
+
+ it("increments once per dropped event and still writes the valid score of a mixed batch", async () => {
+ const { ingestionService, addToQueue } = createService();
+
+ await expect(
+ processScores(ingestionService, [invalidScoreEvent(), validScoreEvent()]),
+ ).resolves.toBeUndefined();
+
+ // Existing behavior: the valid score is still written.
+ const scoreWrite = addToQueue.mock.calls.find(
+ ([table]) => table === TableName.Scores,
+ );
+ expect(scoreWrite).toBeDefined();
+
+ const calls = droppedCalls();
+ expect(calls).toHaveLength(1);
+ expectScoreDropTags(calls[0]);
+ });
+
+ it("does not emit for a batch of valid scores", async () => {
+ const { ingestionService, addToQueue } = createService();
+
+ await expect(
+ processScores(ingestionService, [validScoreEvent()]),
+ ).resolves.toBeUndefined();
+
+ expect(
+ addToQueue.mock.calls.find(([table]) => table === TableName.Scores),
+ ).toBeDefined();
+ expect(droppedCalls()).toHaveLength(0);
+ });
+
+ it("does not emit for unexpected errors β€” those reject the batch instead of dropping it", async () => {
+ const { ingestionService, addToQueue } = createService();
+ vi.spyOn(
+ ingestionService as any,
+ "getMillisecondTimestamp",
+ ).mockImplementation(() => {
+ throw new Error("unexpected timestamp failure");
+ });
+
+ await expect(
+ processScores(ingestionService, [validScoreEvent()]),
+ ).rejects.toThrow("Unexpected error(s) validating score batch");
+
+ expect(addToQueue).not.toHaveBeenCalled();
+ expect(droppedCalls()).toHaveLength(0);
+ });
+
+ it("does not emit when a rethrowing batch also contains an expected validation failure (retry overcount)", async () => {
+ // Greptile finding on PR #15269 / extended ruling: a batch containing
+ // ANY unexpected error rejects and gets redelivered β€” counting the
+ // expected drop on such an attempt inflates the metric once per retry.
+ // Drops are counted only on the attempt that completes.
+ const { ingestionService, addToQueue } = createService();
+
+ let validationCall = 0;
+ mocks.validateAndInflateScoreOverride = () => {
+ validationCall += 1;
+ return validationCall === 1
+ ? Promise.reject(new InvalidRequestError("expected validation drop"))
+ : Promise.reject(new Error("unexpected validation crash"));
+ };
+
+ await expect(
+ processScores(ingestionService, [validScoreEvent(), validScoreEvent()]),
+ ).rejects.toThrow("Unexpected error(s) validating score batch");
+
+ // Both events were validated: one expected drop + one unexpected error.
+ expect(validationCall).toBe(2);
+ expect(addToQueue).not.toHaveBeenCalled();
+ expect(droppedCalls()).toHaveLength(0);
+ });
+});