🪢 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(worker): clamp Decimal64(12) cost values before ClickHouse insertion (#13005)
Valery Meleshkin4a16f6cf3312
diff --git a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.tsindex 435109c64d..b637374aa5 100644--- a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts+++ b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts@@ -12,6 +12,7 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {return {...original,recordHistogram: vi.fn(),+ recordIncrement: vi.fn(),recordCount: vi.fn(),recordGauge: vi.fn(),logger: {@@ -348,6 +349,125 @@ describe("ClickhouseWriter", () => {expect(writer["queue"][TableName.Traces]).toHaveLength(0);});+ describe("Decimal64(12) clamping", () => {+ describe("clampDecimal64Value", () => {+ it.each([+ { input: 0, expected: [0, false], name: "zero" },+ { input: 0.001, expected: [0.001, false], name: "small positive" },+ { input: -42.5, expected: [-42.5, false], name: "small negative" },+ {+ input: 999_999,+ expected: [999_999, false],+ name: "just under limit",+ },+ {+ input: 999_999.999_999,+ expected: [999_999.999_999, false],+ name: "max representable",+ },+ {+ input: 1_000_000,+ expected: [999_999.999_999, true],+ name: "exact limit",+ },+ {+ input: 8_859_794,+ expected: [999_999.999_999, true],+ name: "positive overflow",+ },+ {+ input: -1_000_000,+ expected: [-999_999.999_999, true],+ name: "exact negative limit",+ },+ {+ input: -8_859_794,+ expected: [-999_999.999_999, true],+ name: "negative overflow",+ },+ { input: NaN, expected: [0, true], name: "NaN" },+ { input: Infinity, expected: [0, true], name: "positive Infinity" },+ { input: -Infinity, expected: [0, true], name: "negative Infinity" },+ ])("$name ($input)", ({ input, expected }) => {+ expect(ClickhouseWriter["clampDecimal64Value"](input)).toEqual(+ expected,+ );+ });+ });++ describe("clampDecimal64Map", () => {+ it("returns undefined for undefined input", () => {+ const result = writer["clampDecimal64Map"](undefined, {+ recordId: "r1",+ projectId: "p1",+ fieldName: "cost_details",+ });+ expect(result).toBeUndefined();+ });++ it("returns original map when no values need clamping", () => {+ const map = { input: 0.001, output: 42.5 };+ const result = writer["clampDecimal64Map"](map, {+ recordId: "r1",+ projectId: "p1",+ fieldName: "cost_details",+ });+ expect(result).toBe(map); // same reference, no allocation+ expect(logger.warn).not.toHaveBeenCalled();+ });++ it("clamps multiple overflowing entries correctly", () => {+ const result = writer["clampDecimal64Map"](+ { input: 2_000_000, output: -5_000_000, total: NaN },+ { recordId: "r1", projectId: "p1", fieldName: "cost_details" },+ );+ expect(result).toEqual({+ input: 999_999.999_999,+ output: -999_999.999_999,+ total: 0,+ });+ });++ it("clamps only overflowing entries and logs once", () => {+ const result = writer["clampDecimal64Map"](+ { input: 0.001, output: 8_859_794 },+ { recordId: "r1", projectId: "p1", fieldName: "cost_details" },+ );+ expect(result).toEqual({ input: 0.001, output: 999_999.999_999 });+ expect(logger.warn).toHaveBeenCalledWith(+ "Clamped Decimal64(12) overflow in cost map",+ expect.objectContaining({+ projectId: "p1",+ recordId: "r1",+ fieldName: "cost_details",+ }),+ );+ });+ });++ describe("flush integration", () => {+ it("clamps observation cost fields before inserting", async () => {+ const mockInsert = vi+ .spyOn(clickhouseClientMock, "insert")+ .mockResolvedValue();++ writer.addToQueue(TableName.Observations, {+ id: "obs-1",+ project_id: "proj-1",+ cost_details: { total: 8_859_794 },+ provided_cost_details: { total: 1_234_567 },+ total_cost: 9_999_999,+ } as any);+ await vi.advanceTimersByTimeAsync(writer.writeInterval);++ const inserted = mockInsert.mock.calls[0][0].values[0];+ expect(inserted.cost_details.total).toBe(999_999.999_999);+ expect(inserted.provided_cost_details.total).toBe(999_999.999_999);+ expect(inserted.total_cost).toBe(999_999.999_999);+ });+ });+ });+describe("truncation logic", () => {it("should truncate oversized input field", () => {const largeInput = "a".repeat(2 * 1024 * 1024); // 2MB stringdiff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex ee71275ace..fdfee744ce 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -15,11 +15,20 @@ import {EventRecordInsertType,} from "@langfuse/shared/src/server";+import { Decimal } from "decimal.js";+import { env } from "../../env";import { logger } from "@langfuse/shared/src/server";import { instrumentAsync } from "@langfuse/shared/src/server";import { backOff } from "exponential-backoff";+// Decimal64(12): valid range is (-10^6, 10^6), i.e. 18 total digits with 12 fractional.+// JS double can't represent 999999.999999999999 exactly (rounds to 1e6), so we use a+// value with enough decimal places to be safe while staying representable as a JS number.+const DECIMAL_64_12_LIMIT = new Decimal("1e6");+const DECIMAL_64_12_MAX_NUM = 999_999.999_999;+const DECIMAL_64_12_MIN_NUM = -DECIMAL_64_12_MAX_NUM;+export class ClickhouseWriter {private static instance: ClickhouseWriter | null = null;private static client: ClickhouseClientType | null = null;@@ -268,6 +277,82 @@ export class ClickhouseWriter {return record;}+ private static clampDecimal64Value(value: number): [number, boolean] {+ if (!Number.isFinite(value)) return [0, true];+ if (new Decimal(value).abs().gte(DECIMAL_64_12_LIMIT)) {+ return [value >= 0 ? DECIMAL_64_12_MAX_NUM : DECIMAL_64_12_MIN_NUM, true];+ }+ return [value, false];+ }++ private clampDecimal64Map(+ map: Record<string, number> | undefined,+ context: { recordId: string; projectId: string; fieldName: string },+ ): Record<string, number> | undefined {+ if (!map) return map;++ let result: Record<string, number> | undefined;+ for (const [key, value] of Object.entries(map)) {+ const [cv, wasClamped] = ClickhouseWriter.clampDecimal64Value(value);+ if (wasClamped) {+ result ??= { ...map };+ result[key] = cv;+ }+ }+ if (!result) return map;++ logger.warn("Clamped Decimal64(12) overflow in cost map", {+ projectId: context.projectId,+ recordId: context.recordId,+ fieldName: context.fieldName,+ });+ recordIncrement("langfuse.clickhouse_writer.decimal64_clamped");+ return result;+ }++ private clampDecimal64Fields<T extends TableName>(+ tableName: T,+ record: RecordInsertType<T>,+ ): RecordInsertType<T> {+ const r = record as Record<string, unknown>;+ const ctx = {+ recordId: r.id as string,+ projectId: r.project_id as string,+ };++ switch (tableName) {+ case TableName.Observations:+ case TableName.ObservationsBatchStaging:+ case TableName.EventsFull: {+ r.provided_cost_details = this.clampDecimal64Map(+ r.provided_cost_details as Record<string, number> | undefined,+ { ...ctx, fieldName: "provided_cost_details" },+ );+ r.cost_details = this.clampDecimal64Map(+ r.cost_details as Record<string, number> | undefined,+ { ...ctx, fieldName: "cost_details" },+ );+ if (r.total_cost != null && typeof r.total_cost === "number") {+ const [cv, wasClamped] = ClickhouseWriter.clampDecimal64Value(+ r.total_cost,+ );+ if (wasClamped) {+ r.total_cost = cv;+ logger.warn("Clamped Decimal64(12) overflow in total_cost", {+ projectId: ctx.projectId,+ recordId: ctx.recordId,+ fieldName: "total_cost",+ });+ recordIncrement("langfuse.clickhouse_writer.decimal64_clamped");+ }+ }+ break;+ }+ }++ return record;+ }+private async flush<T extends TableName>(tableName: T, fullQueue = false) {const entityQueue = this.queue[tableName];if (entityQueue.length === 0) return;@@ -296,6 +381,9 @@ export class ClickhouseWriter {const processingStartTime = Date.now();let recordsToWrite = queueItems.map((item) => item.data);+ recordsToWrite = recordsToWrite.map((r) =>+ this.clampDecimal64Fields(tableName, r),+ );let hasBeenTruncated = false;await backOff(