Skip to content

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

chore(worker): warn on inconsistent provided usage_details totals (LFE-10743) (#14875)

Niklas Semmlerc06430ea56d5
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 6a1f7970ff..6e61d027dc 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -241,6 +241,14 @@ export class IngestionService {
const input = this.stringify(eventData.input);
const output = this.stringify(eventData.output);
+ // Runs outside the modelName gate below so model-less events with provided
+ // usage are still checked.
+ this.warnOnUsageTotalMismatch(
+ eventData.providedUsageDetails ?? {},
+ { id: eventData.spanId, project_id: eventData.projectId },
+ "events",
+ );
+
// Perform lookups for prompt and model/usage enrichment
const [prompt, generationUsage] = await Promise.all([
// Lookup prompt by name and version
@@ -910,6 +918,20 @@ export class IngestionService {
mergedObservationRecord.tool_call_names = normalizedTools.toolCallNames;
}
+ // Only check when the incoming events carry usage themselves — partial
+ // updates merge stale usage back in from ClickHouse and must not re-fire.
+ if (
+ observationRecords.some(
+ (record) => Object.keys(record.provided_usage_details ?? {}).length > 0,
+ )
+ ) {
+ this.warnOnUsageTotalMismatch(
+ mergedObservationRecord.provided_usage_details ?? {},
+ mergedObservationRecord,
+ "legacy",
+ );
+ }
+
const generationUsage = await this.getGenerationUsage({
projectId,
observationRecord: mergedObservationRecord,
@@ -1226,19 +1248,9 @@ export class IngestionService {
"usage_details" | "provided_usage_details"
>
> {
- // 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(
+ const providedUsageDetails = IngestionService.normalizeProvidedUsageDetails(
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
@@ -1352,6 +1364,83 @@ export class IngestionService {
};
}
+ // 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.
+ private static normalizeProvidedUsageDetails(
+ providedUsageDetails: Record<string, unknown>,
+ ): Record<string, number> {
+ const normalized: Record<string, number> = {};
+ for (const [key, value] of Object.entries(providedUsageDetails)) {
+ if (value != null) {
+ const numValue = Number(value);
+ if (!isNaN(numValue) && numValue >= 0) {
+ normalized[key] = numValue;
+ }
+ }
+ }
+ return normalized;
+ }
+
+ private static lastUsageTotalMismatchLogAt = 0;
+ private static readonly USAGE_TOTAL_MISMATCH_TOLERANCE = 0.01;
+ private static readonly USAGE_TOTAL_MISMATCH_LOG_INTERVAL_MS = 60_000;
+
+ /**
+ * Detects the double-count class from
+ * https://github.com/langfuse/langfuse/issues/10592: instrumentors that send
+ * an inclusive `input` alongside cache buckets while providing a smaller
+ * `total`. Warn only — buckets can be genuinely additive (e.g. Bedrock cache
+ * writes), so auto-correcting could corrupt valid payloads.
+ *
+ * Called once per write path (`legacy` merge path, `events` direct path);
+ * dual-write mode fires both, so the metric carries a write_path tag to keep
+ * the counts reconcilable.
+ */
+ private warnOnUsageTotalMismatch(
+ rawProvidedUsageDetails: Record<string, unknown>,
+ observationRecord: Pick<ObservationRecordInsertType, "id" | "project_id">,
+ writePath: "legacy" | "events",
+ ): void {
+ const providedUsageDetails = IngestionService.normalizeProvidedUsageDetails(
+ rawProvidedUsageDetails,
+ );
+ const providedTotal = providedUsageDetails.total;
+ if (providedTotal == null) return;
+
+ const bucketSum = Object.entries(providedUsageDetails)
+ .filter(([key]) => key !== "total")
+ .reduce((sum, [, value]) => sum + value, 0);
+ const tolerance = Math.max(
+ 1,
+ providedTotal * IngestionService.USAGE_TOTAL_MISMATCH_TOLERANCE,
+ );
+ if (bucketSum <= providedTotal + tolerance) return;
+
+ recordIncrement("langfuse.ingestion.usage_details.total_mismatch", 1, {
+ write_path: writePath,
+ });
+
+ const now = Date.now();
+ if (
+ now - IngestionService.lastUsageTotalMismatchLogAt <
+ IngestionService.USAGE_TOTAL_MISMATCH_LOG_INTERVAL_MS
+ ) {
+ return;
+ }
+ IngestionService.lastUsageTotalMismatchLogAt = now;
+ logger.warn(
+ "Sum of provided non-total usage_details buckets exceeds provided total; the instrumentor may be sending an inclusive input alongside cache buckets",
+ {
+ projectId: observationRecord.project_id,
+ observationId: observationRecord.id,
+ providedTotal,
+ bucketSum,
+ providedUsageDetails,
+ writePath,
+ },
+ );
+ }
+
static calculateUsageCosts(
modelPrices:
| Array<{ usageType: string; price: Decimal }>
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index e4adc9cec0..57bec634b0 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { Price } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";
import { IngestionService } from "../../IngestionService";
import * as clickhouseWriteExports from "../../ClickhouseWriter";
@@ -1369,4 +1369,241 @@ describe("Token Cost Calculation", () => {
expect(generation.usage_details.total).toBe(100);
});
});
+
+ describe("usage details total consistency guard", () => {
+ // Detects the double-count class from https://github.com/langfuse/langfuse/issues/10592:
+ // instrumentors sending an inclusive `input` alongside cache buckets while also
+ // providing a smaller `total`.
+
+ it("should warn when provided non-total buckets sum to more than the provided total", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ const eventRecord = await (mockIngestionService as any).createEventRecord(
+ {
+ projectId,
+ spanId: generationId,
+ startTime: new Date().toISOString(),
+ modelName,
+ // Inclusive input alongside cache buckets: 100 + 80 + 50 > 150
+ providedUsageDetails: {
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ },
+ },
+ "testfile.txt",
+ );
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(1);
+ expect(mismatchWarnings[0][1]).toMatchObject({
+ projectId,
+ observationId: generationId,
+ providedTotal: 150,
+ bucketSum: 230,
+ writePath: "events",
+ });
+
+ // Warn only — the provided values must be written unchanged
+ expect(eventRecord.usage_details).toEqual({
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ });
+ });
+
+ it("should not warn when provided buckets are consistent with the provided total", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ await (mockIngestionService as any).createEventRecord(
+ {
+ projectId,
+ spanId: generationId,
+ startTime: new Date().toISOString(),
+ modelName,
+ // Exclusive input: 20 + 80 + 50 === 150
+ providedUsageDetails: {
+ input: 20,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ },
+ },
+ "testfile.txt",
+ );
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(0);
+ });
+
+ it("should not warn when no total is provided", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ await (mockIngestionService as any).createEventRecord(
+ {
+ projectId,
+ spanId: generationId,
+ startTime: new Date().toISOString(),
+ modelName,
+ providedUsageDetails: {
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ },
+ },
+ "testfile.txt",
+ );
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(0);
+ });
+
+ it("should warn on the direct event path even when no model is provided", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ await (mockIngestionService as any).createEventRecord(
+ {
+ projectId,
+ spanId: generationId,
+ startTime: new Date().toISOString(),
+ providedUsageDetails: {
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ },
+ },
+ "testfile.txt",
+ );
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(1);
+ expect(mismatchWarnings[0][1]).toMatchObject({
+ projectId,
+ observationId: generationId,
+ });
+ });
+
+ it("should log the warning at most once per rate-limit interval", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+
+ for (const spanId of [uuidv4(), uuidv4()]) {
+ await (mockIngestionService as any).createEventRecord(
+ {
+ projectId,
+ spanId,
+ startTime: new Date().toISOString(),
+ modelName,
+ providedUsageDetails: {
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ },
+ },
+ "testfile.txt",
+ );
+ }
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(1);
+ });
+
+ it("should warn on the legacy merge path when incoming events carry inconsistent usage", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ startTime: new Date().toISOString(),
+ model: modelName,
+ usageDetails: {
+ input: 100,
+ cache_read_input_tokens: 80,
+ output: 50,
+ total: 150,
+ },
+ },
+ },
+ ];
+
+ await (mockIngestionService as any).processObservationEventList({
+ projectId,
+ entityId: generationId,
+ createdAtTimestamp: new Date(),
+ observationEventList: events,
+ });
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(1);
+ expect(mismatchWarnings[0][1]).toMatchObject({
+ projectId,
+ observationId: generationId,
+ writePath: "legacy",
+ });
+ });
+
+ it("should not warn on the legacy merge path when incoming events carry no usage", async () => {
+ (IngestionService as any).lastUsageTotalMismatchLogAt = 0;
+ const warnSpy = vi.spyOn(logger, "warn");
+ const generationId = uuidv4();
+
+ // Partial update without usage: the guard must not fire even if merged
+ // state contains usage (here there is none, but the gate is on the
+ // incoming events).
+ const events = [
+ {
+ id: uuidv4(),
+ type: "generation-update",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ startTime: new Date().toISOString(),
+ output: "updated output",
+ },
+ },
+ ];
+
+ await (mockIngestionService as any).processObservationEventList({
+ projectId,
+ entityId: generationId,
+ createdAtTimestamp: new Date(),
+ observationEventList: events,
+ });
+
+ const mismatchWarnings = warnSpy.mock.calls.filter(([message]) =>
+ String(message).includes("exceeds provided total"),
+ );
+ expect(mismatchWarnings).toHaveLength(0);
+ });
+ });
});