🪢 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): skip token counts instead of synchronous tokenization fallback (#15627)
Steffen Schmitz61a55660d0d3
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 016985945e..f1c05433b4 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -56,7 +56,6 @@ import {} from "@langfuse/shared/src/server";import { tokenCountAsync } from "../../features/tokenisation/async-usage";-import { tokenCount } from "../../features/tokenisation/usage";import { ClickhouseWriter, TableName } from "../ClickhouseWriter";import {convertJsonSchemaToRecord,@@ -1282,7 +1281,12 @@ export class IngestionService {private async getUsageUnits(observationRecord: Pick<ObservationRecordInsertType,- "provided_usage_details" | "level" | "input" | "output" | "id"+ | "project_id"+ | "provided_usage_details"+ | "level"+ | "input"+ | "output"+ | "id">,model: Model | null | undefined,): Promise<@@ -1321,18 +1325,30 @@ export class IngestionService {}),]);} catch (error) {+ // No synchronous fallback: payloads that make the worker thread+ // exceed its timeout would block the event loop for minutes if+ // re-tokenized on the main thread. Absent counts are+ // detectable by users, unlike a 0 or a bytes-based estimate.logger.warn(- `Async tokenization has failed. Falling back to synchronous tokenization`,- error,+ `Async tokenization failed for observation ${observationRecord.id} in project ${observationRecord.project_id}. Skipping token counts.`,+ {+ projectId: observationRecord.project_id,+ observationId: observationRecord.id,+ modelId: model.id,+ tokenizerId: model.tokenizerId,+ inputBytes:+ typeof observationRecord.input === "string"+ ? observationRecord.input.length+ : undefined,+ outputBytes:+ typeof observationRecord.output === "string"+ ? observationRecord.output.length+ : undefined,+ error,+ },);- newInputCount = tokenCount({- text: observationRecord.input,- model,- });- newOutputCount = tokenCount({- text: observationRecord.output,- model,- });+ span.setAttribute("langfuse.tokenization.skipped", true);+ recordIncrement("langfuse.tokenisation.skipped", 1);}// Tracingdiff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.tsindex 052c4b8ab2..17ffdb4ba3 100644--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts@@ -1,6 +1,6 @@import Decimal from "decimal.js";import { v4 as uuidv4 } from "uuid";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Price } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";@@ -34,6 +34,44 @@ vi.mock("../../ClickhouseWriter", async (importOriginal) => {};});+// Tokenisation mocks delegate to the real implementations unless a test sets an+// override, so tests relying on actual tokenization keep working.+const tokenisationMocks = vi.hoisted(() => ({+ tokenCountAsyncOverride: null as+ | null+ | ((...args: unknown[]) => Promise<number | undefined>),+ syncTokenCountSpy: vi.fn(),+}));++vi.mock(+ "../../../features/tokenisation/async-usage",+ async (importOriginal) => {+ const original = (await importOriginal()) as Record<string, unknown> & {+ tokenCountAsync: (...args: unknown[]) => Promise<number | undefined>;+ };+ return {+ ...original,+ tokenCountAsync: (...args: unknown[]) =>+ tokenisationMocks.tokenCountAsyncOverride+ ? tokenisationMocks.tokenCountAsyncOverride(...args)+ : original.tokenCountAsync(...args),+ };+ },+);++vi.mock("../../../features/tokenisation/usage", async (importOriginal) => {+ const original = (await importOriginal()) as Record<string, unknown> & {+ tokenCount: (...args: unknown[]) => number | undefined;+ };+ return {+ ...original,+ tokenCount: (...args: unknown[]) => {+ tokenisationMocks.syncTokenCountSpy(...args);+ return original.tokenCount(...args);+ },+ };+});+const mockIngestionService = new IngestionService(null as any,prisma,@@ -1370,6 +1408,75 @@ describe("Token Cost Calculation", () => {});});+ describe("async tokenization failure handling", () => {+ // Multi-megabyte payloads make the tokenization worker thread exceed its+ // 30s timeout. The former synchronous fallback re-tokenized the same+ // payload on the main thread and blocked the event loop for minutes.+ // On failure, token counts must be skipped entirely — absent+ // values are detectable by users, unlike a 0 or a bytes-based estimate.++ afterEach(() => {+ tokenisationMocks.tokenCountAsyncOverride = null;+ tokenisationMocks.syncTokenCountSpy.mockClear();+ });++ it("should skip token counts instead of falling back to synchronous tokenization when async tokenization times out", async () => {+ const warnSpy = vi.spyOn(logger, "warn");+ tokenisationMocks.tokenCountAsyncOverride = () =>+ Promise.reject(+ new Error("Token count operation timed out after 30000ms"),+ );++ const events = [+ {+ id: uuidv4(),+ type: "generation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ startTime: new Date().toISOString(),+ model: modelName,+ input: "hello world",+ output: "whassup",+ usage: null,+ },+ },+ ];++ await (mockIngestionService as any).processObservationEventList({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(),+ observationEventList: events,+ });++ // The event loop must never run tokenization on the main thread+ expect(tokenisationMocks.syncTokenCountSpy).not.toHaveBeenCalled();++ // Exactly one structured warn identifies the affected tenant and payload+ const skipWarnings = warnSpy.mock.calls.filter(([message]) =>+ String(message).includes("Skipping token counts"),+ );+ expect(skipWarnings).toHaveLength(1);+ expect(skipWarnings[0][1]).toMatchObject({+ projectId,+ observationId: generationId,+ modelId: tokenModelData.id,+ tokenizerId: "openai",+ inputBytes: expect.any(Number),+ outputBytes: expect.any(Number),+ error: expect.any(Error),+ });++ expect(mockAddToClickhouseWriter).toHaveBeenCalled();+ const [tableName, generation] = mockAddToClickhouseWriter.mock.calls[0];+ expect(tableName).toBe("observations");+ expect(generation.internal_model_id).toBe(tokenModelData.id);+ expect(generation.usage_details).toEqual({});+ expect(generation.cost_details).toEqual({});+ });+ });+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