Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix: ensure correct numeric handling of usage_details values instead of concatenation (#11472)

Steffen Schmitzc6207c0f62eb
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index 86a55fbeba..522ffe0d73 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -93,6 +93,11 @@ const RawUsageDetails = z.record(z.string(), z.unknown()).transform((val) => {
for (const [key, value] of Object.entries(val)) {
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
result[key] = value;
+ } else if (typeof value === "string") {
+ const parsed = parseInt(value, 10);
+ if (!isNaN(parsed) && parsed >= 0) {
+ result[key] = parsed;
+ }
}
}
diff --git a/web/src/__tests__/async/otel-api.servertest.ts b/web/src/__tests__/async/otel-api.servertest.ts
index ed6971e9e9..2fc757cc83 100644
--- a/web/src/__tests__/async/otel-api.servertest.ts
+++ b/web/src/__tests__/async/otel-api.servertest.ts
@@ -1,6 +1,10 @@
import { makeAPICall } from "@/src/__tests__/test-utils";
import waitForExpect from "wait-for-expect";
-import { getObservationById, getTraceById } from "@langfuse/shared/src/server";
+import {
+ getObservationById,
+ getObservationByIdFromEventsTable,
+ getTraceById,
+} from "@langfuse/shared/src/server";
import { randomBytes } from "crypto";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -30,14 +34,8 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {
},
spans: [
{
- traceId: {
- type: "Buffer",
- data: traceId,
- },
- spanId: {
- type: "Buffer",
- data: spanId,
- },
+ traceId,
+ spanId,
name: "my-generation",
kind: 1,
startTimeUnixNano: {
@@ -110,14 +108,8 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {
},
spans: [
{
- traceId: {
- type: "Buffer",
- data: traceId,
- },
- spanId: {
- type: "Buffer",
- data: spanId,
- },
+ traceId,
+ spanId,
name: "my-generation",
kind: 1,
startTimeUnixNano: {
@@ -225,6 +217,119 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {
expect(response.status).toBe(200);
});
+ // Skipping for now, as this requires direct writes into the events table without dual write.
+ it.skip("should correctly convert string usage_details to numbers and compute total", async () => {
+ // This test verifies that usage_details values sent as strings are correctly
+ // converted to numbers, and the total is computed via numeric addition (not
+ // string concatenation). This was a bug where "100" + "200" = "100200" instead of 300.
+ const traceId = randomBytes(16);
+ const spanId = randomBytes(8);
+
+ const payload = {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: [],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "pydantic-ai",
+ version: "v1.0.0",
+ attributes: [
+ {
+ key: "public_key",
+ value: { stringValue: "pk-lf-1234567890" },
+ },
+ ],
+ },
+ spans: [
+ {
+ traceId,
+ spanId,
+ name: "pydantic-ai-generation",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 466848096,
+ high: 406528574,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 467248096,
+ high: 406528574,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "langfuse.environment",
+ value: { stringValue: "sdk-experiment" },
+ },
+ {
+ key: "langfuse.observation.type",
+ value: {
+ stringValue: "generation",
+ },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: {
+ stringValue: "test-model",
+ },
+ },
+ // These are string values that should be converted to numbers
+ // The OTEL protocol can send these as stringValue
+ {
+ key: "gen_ai.usage.input_tokens",
+ value: { stringValue: "100" }, // String, should become number 100
+ },
+ {
+ key: "gen_ai.usage.output_tokens",
+ value: { stringValue: "200" }, // String, should become number 200
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/otel/v1/traces",
+ payload,
+ );
+
+ expect(response.status).toBe(200);
+
+ await waitForExpect(async () => {
+ const observation = await getObservationByIdFromEventsTable({
+ projectId,
+ id: spanId.toString("hex"),
+ });
+
+ expect(observation).toBeDefined();
+ expect(observation!.id).toBe(spanId.toString("hex"));
+ expect(observation!.name).toBe("pydantic-ai-generation");
+
+ // Verify usage details are stored as numbers, not strings
+ // The total should be 100 + 200 = 300 (numeric addition)
+ // NOT "100" + "200" = "100200" (string concatenation)
+ expect(observation!.totalUsage).toBe(300);
+
+ // Also verify the individual values are numbers
+ const usageDetails = observation!.usageDetails as Record<string, unknown>;
+ expect(usageDetails).toBeDefined();
+ expect(typeof usageDetails.input).toBe("number");
+ expect(typeof usageDetails.output).toBe("number");
+ expect(usageDetails.input).toBe(100);
+ expect(usageDetails.output).toBe(200);
+ expect(usageDetails.total).toBe(300);
+ }, 25_000);
+ }, 30_000);
+
it("should transform deployment.environment to lowercase", async () => {
const traceId = randomBytes(16);
const spanId = randomBytes(8);
@@ -254,14 +359,8 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {
},
spans: [
{
- traceId: {
- type: "Buffer",
- data: traceId,
- },
- spanId: {
- type: "Buffer",
- data: spanId,
- },
+ traceId,
+ spanId,
name: "test-span",
kind: 1,
startTimeUnixNano: {
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 71c110f6ab..5b203cb212 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -1211,11 +1211,19 @@ export class IngestionService {
"usage_details" | "provided_usage_details"
>
> {
- const providedUsageDetails = Object.fromEntries(
- Object.entries(observationRecord.provided_usage_details).filter(
- ([_k, v]) => v != null && v >= 0,
- ),
- );
+ // Convert all values to numbers to handle cases where ClickHouse returns UInt64 as strings.
+ // This prevents string concatenation bugs like "100" + "200" = "100200" instead of 300.
+ const providedUsageDetails: Record<string, number> = {};
+ for (const [key, value] of Object.entries(
+ observationRecord.provided_usage_details,
+ )) {
+ if (value != null) {
+ const numValue = Number(value);
+ if (!isNaN(numValue) && numValue >= 0) {
+ providedUsageDetails[key] = numValue;
+ }
+ }
+ }
if (
// Manual tokenisation when no user provided usage and generation has not status ERROR
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index 6ebebd8ce6..e3dd957795 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -1272,4 +1272,76 @@ describe("Token Cost Calculation", () => {
expect(generation.usage_details.output).toBeUndefined();
expect(generation.usage_details.total).toBeUndefined();
});
+
+ describe("string to number conversion in getUsageUnits", () => {
+ // These tests verify that usage_details values are correctly converted to numbers
+ // even when they come in as strings (which can happen when reading from ClickHouse,
+ // as the ClickHouse JS client may return UInt64 values as strings).
+ // This prevents string concatenation bugs like "100" + "200" = "100200" instead of 300.
+
+ it("should correctly convert string usage values to numbers and compute total", async () => {
+ const generationId = uuidv4();
+
+ // Simulate usageDetails coming from ClickHouse as strings
+ const events = [
+ {
+ id: generationId,
+ startTime: new Date().toISOString(),
+ modelName,
+ // These string values simulate what ClickHouse might return for UInt64
+ providedUsageDetails: {
+ input: "100" as unknown as number,
+ output: "200" as unknown as number,
+ },
+ },
+ ];
+
+ await (mockIngestionService as any).writeEvent(events[0], "testfile.txt");
+
+ expect(mockAddToClickhouseWriter).toHaveBeenCalled();
+ const args = mockAddToClickhouseWriter.mock.calls[0];
+ const generation = args[1];
+
+ // Values should be numbers, not strings
+ expect(typeof generation.usage_details.input).toBe("number");
+ expect(typeof generation.usage_details.output).toBe("number");
+ expect(typeof generation.usage_details.total).toBe("number");
+
+ // Total should be numeric addition (300), not string concatenation ("100200")
+ expect(generation.usage_details.input).toBe(100);
+ expect(generation.usage_details.output).toBe(200);
+ expect(generation.usage_details.total).toBe(300);
+ });
+
+ it("should ignore invalid string values that cannot be converted to numbers", async () => {
+ const generationId = uuidv4();
+
+ const events = [
+ {
+ id: generationId,
+ startTime: new Date().toISOString(),
+ modelName,
+ // These string values simulate what ClickHouse might return for UInt64
+ providedUsageDetails: {
+ input: "100" as unknown as number,
+ output: "non_a_number" as unknown as number,
+ },
+ },
+ ];
+
+ await (mockIngestionService as any).writeEvent(events[0], "testfile.txt");
+
+ // Invalid values should be ignored
+ expect(mockAddToClickhouseWriter).toHaveBeenCalled();
+ const args = mockAddToClickhouseWriter.mock.calls[0];
+ const generation = args[1];
+
+ // Values should be numbers, not strings
+ expect(typeof generation.usage_details.input).toBe("number");
+ expect(typeof generation.usage_details.total).toBe("number");
+
+ expect(generation.usage_details.input).toBe(100);
+ expect(generation.usage_details.total).toBe(100);
+ });
+ });
});