Skip to content

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

61.3 KB
Raw Blame
import Decimal from "decimal.js";
import { v4 as uuidv4 } from "uuid";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { Price } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";

import { IngestionService } from "../../IngestionService";
import * as clickhouseWriteExports from "../../ClickhouseWriter";

// vi.hoisted ensures this is declared before vi.mock's hoisted factory runs.
// Without it, the variable would be undefined when the factory executes.
const { mockAddToClickhouseWriter } = vi.hoisted(() => ({
  mockAddToClickhouseWriter: vi.fn(),
}));
const mockClickhouseClient = {
  query: async () => ({
    json: async () => [],
    query_id: "1",
    response_headers: { "x-clickhouse-summary": [] },
  }),
};

vi.mock("../../ClickhouseWriter", async (importOriginal) => {
  const original = (await importOriginal()) as {};
  return {
    ...original,
    ClickhouseWriter: {
      getInstance: () => ({
        addToQueue: mockAddToClickhouseWriter,
      }),
    },
  };
});

// 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 sdkAttribution = {
  ingestionApiKey: "pk-lf-test",
  ingestionSdkName: "unknown",
  ingestionSdkVersion: "unknown",
};

const mockIngestionService = new IngestionService(
  null as any,
  prisma,
  clickhouseWriteExports.ClickhouseWriter.getInstance() as any,
  mockClickhouseClient as any,
);

describe("Token Cost Calculation", () => {
  let modelName: string;
  let modelId: string;
  let generationId: string;
  let projectId: string;
  let tokenModelData: {
    id: string;
    modelName: string;
    matchPattern: string;
    tokenizerId: string;
    tokenizerConfig: {
      tokensPerName: number;
      tokenizerModel: string;
      tokensPerMessage: number;
    };
  };

  const modelPrices: Pick<Price, "price" | "usageType">[] = [
    {
      price: new Decimal(0.01),
      usageType: "input",
    },
    {
      price: new Decimal(0.02),
      usageType: "output",
    },
    {
      price: new Decimal(0.03),
      usageType: "total",
    },
  ];

  beforeEach(async () => {
    modelName = `gpt-test-${uuidv4()}`;
    modelId = uuidv4();
    generationId = uuidv4();
    ({ projectId } = await createOrgProjectAndApiKey());
    const matchPattern = `(?i)^(${modelName})$`;
    tokenModelData = {
      id: modelId,
      modelName,
      matchPattern,
      tokenizerId: "openai",
      tokenizerConfig: {
        tokensPerName: 1,
        tokenizerModel: "gpt-4o",
        tokensPerMessage: 3,
      },
    };

    const model = await prisma.model.create({
      data: tokenModelData,
    });
    const pricingTierId = uuidv4();
    await prisma.pricingTier.create({
      data: {
        id: pricingTierId,
        name: "Standard",
        isDefault: true,
        priority: 0,
        conditions: [],
        modelId,
      },
    });

    await Promise.all([
      prisma.price.createMany({
        data: modelPrices.map((price) => ({
          pricingTierId,
          modelId,
          projectId: null,
          usageType: price.usageType,
          price: price.price,
        })),
      }),
    ]);

    vi.clearAllMocks();
  });

  it("should correctly calculate token costs with provided model prices", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: 100,
      output: 200,
      total: 300,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBe(1.0); // 100 tokens * 0.01
    expect(costs.cost_details.output).toBe(4.0); // 200 tokens * 0.02
    expect(costs.cost_details.total).toBe(9.0); // 300 tokens * 0.03
    expect(costs.total_cost).toBe(9.0);
  });

  it("should apply the configured cache-creation price", () => {
    const costs = (IngestionService as any).calculateUsageCosts(
      [
        {
          price: new Decimal(0.00000375),
          usageType: "input_cache_creation",
        },
      ],
      { provided_cost_details: {} },
      { input_cache_creation: 25 },
    );

    expect(costs.cost_details.input_cache_creation).toBe(0.00009375);
    expect(costs.total_cost).toBe(0.00009375);
  });

  it("prices TTL-split cache writes with the aggregate cache-write price when no TTL price exists", () => {
    const costs = (IngestionService as any).calculateUsageCosts(
      [
        {
          price: new Decimal(0.00000375),
          usageType: "cache_creation_input_tokens",
        },
        { price: new Decimal(0.000006), usageType: "input_cache_creation_1h" },
      ],
      { provided_cost_details: {} },
      { input_cache_creation_5m: 2000, input_cache_creation_1h: 10256 },
    );

    expect(costs.cost_details.input_cache_creation_5m).toBe(0.0075);
    expect(costs.cost_details.input_cache_creation_1h).toBeCloseTo(0.061536, 9);
    expect(costs.total_cost).toBeCloseTo(0.069036, 9);
  });

  it("should correctly calculate token costs with user provided costs", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: 100,
      output: 200,
      total: 300,
    };

    const userProvidedCosts = {
      input: 2.0,
      output: 3.0,
      total: 5.0,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      { provided_cost_details: userProvidedCosts },
      usageUnits,
    );

    expect(costs.cost_details.input).toBe(2.0); // Overridden by user provided cost
    expect(costs.cost_details.output).toBe(3.0); // Overridden by user provided cost
    expect(costs.cost_details.total).toBe(5.0); // Overridden by user provided cost
    expect(costs.total_cost).toBe(5.0);
  });

  it("should correctly calculate token costs when only some user provided costs are given", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const data = [
      // missing total
      {
        userProvidedCosts: {
          input: 1,
          output: 2,
        },
        expectedCost: {
          input_cost: 1,
          output_cost: 2,
          total_cost: 3,
        },
      },
      // only total
      {
        userProvidedCosts: {
          total: 2,
        },
        expectedCost: {
          total_cost: 2,
        },
      },
      // missing input
      {
        userProvidedCosts: {
          output: 2,
          total: 2,
        },
        expectedCost: {
          output_cost: 2,
          total_cost: 2,
        },
      },
      // only input
      {
        userProvidedCosts: {
          input: 1,
        },
        expectedCost: {
          input_cost: 1,
          total_cost: 1,
        },
      },

      // missing output
      {
        userProvidedCosts: {
          input: 1,
          total: 1,
        },
        expectedCost: {
          input_cost: 1,
          output_cost: undefined,
          total_cost: 1,
        },
      },

      // only output
      {
        userProvidedCosts: {
          output: 2,
        },
        expectedCost: {
          input_cost: undefined,
          output_cost: 2,
          total_cost: 2,
        },
      },
    ];

    for (const { userProvidedCosts, expectedCost } of data) {
      const usageUnits = {
        input: 0,
        output: 0,
        total: 0,
      };

      const costs = (IngestionService as any).calculateUsageCosts(
        prices as any,
        { provided_cost_details: userProvidedCosts } as any,
        usageUnits,
      );

      expect(costs.cost_details.input).toBe(expectedCost.input_cost);
      expect(costs.cost_details.output).toBe(expectedCost.output_cost);
      expect(costs.cost_details.total).toBe(expectedCost.total_cost);
      expect(costs.total_cost).toBe(expectedCost.total_cost);
    }
  });

  it("should return empty costs if no model is provided", async () => {
    const usageUnits = {
      input: 100,
      output: 200,
      total: 300,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      null,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBeUndefined();
    expect(costs.cost_details.output).toBeUndefined();
    expect(costs.cost_details.total).toBeUndefined();
    expect(costs.total_cost).toBeUndefined();
  });

  it("should handle zero token counts correctly", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: 0,
      output: 0,
      total: 0,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBe(0); // 0 tokens * 0.01
    expect(costs.cost_details.output).toBe(0); // 0 tokens * 0.02
    expect(costs.cost_details.total).toBe(0); // 0 tokens * 0.03
    expect(costs.total_cost).toBe(0);
  });

  it("should handle missing token counts correctly", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: undefined,
      output: undefined,
      total: undefined,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBeUndefined();
    expect(costs.cost_details.output).toBeUndefined();
    expect(costs.cost_details.total).toBeUndefined();
    expect(costs.total_cost).toBeUndefined();
  });

  it("should handle fractional token counts correctly", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: 150.5,
      output: 250.25,
      total: 400.75,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBeCloseTo(1.505); // 150.5 tokens * 0.01
    expect(costs.cost_details.output).toBeCloseTo(5.005); // 250.25 tokens * 0.02
    expect(costs.cost_details.total).toBeCloseTo(12.0225); // 400.75 tokens * 0.03
    expect(costs.total_cost).toBeCloseTo(12.0225);
  });

  it("should handle large token counts correctly", async () => {
    const prices = await prisma.price.findMany({
      where: {
        modelId,
      },
    });

    const usageUnits = {
      input: 1e6,
      output: 2e6,
      total: 3e6,
    };

    const userProvidedCosts = {
      input: null,
      output: null,
      total: null,
    };

    const costs = (IngestionService as any).calculateUsageCosts(
      prices as any,
      userProvidedCosts,
      usageUnits,
    );

    expect(costs.cost_details.input).toBe(10000); // 1e6 tokens * 0.01
    expect(costs.cost_details.output).toBe(40000); // 2e6 tokens * 0.02
    expect(costs.cost_details.total).toBe(90000); // 3e6 tokens * 0.03
    expect(costs.total_cost).toBe(90000);
  });

  it("should correctly match model prices from the database", async () => {
    const generationUsage = {
      model: modelName,
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const generationId = uuidv4();

    const events = [
      {
        id: generationId,
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage.usage.input * modelPrices[0].price.toNumber(),
    );
    expect(generation.cost_details.output).toBe(
      generationUsage.usage.output * modelPrices[1].price.toNumber(),
    );
    expect(generation.cost_details.total).toBe(
      generationUsage.usage.total * modelPrices[2].price.toNumber(),
    );
    expect(generation.usage_details.input).toBe(generationUsage.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage.usage.total);
  });

  it("should overwrite costs for a generation without previous user provided costs", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: modelName,
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage2.usage.input * modelPrices[0].price.toNumber(),
    );
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.output * modelPrices[1].price.toNumber(),
    );
    expect(generation.cost_details.total).toBe(
      generationUsage2.usage.total * modelPrices[2].price.toNumber(),
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should correctly handle first manual tokenization and then provided tokens", async () => {
    const generationUsage1 = {
      model: modelName,
      input: "hello world",
      output: "",
      usage: null,
    };

    const generationUsage2 = {
      output: "whassup",
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage2.usage.input * modelPrices[0].price.toNumber(),
    );
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.output * modelPrices[1].price.toNumber(),
    );
    expect(generation.cost_details.total).toBe(
      generationUsage2.usage.total * modelPrices[2].price.toNumber(),
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should use the matched model of the previous generation call to calculate costs", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: undefined, // No model provided
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage2.usage.input * modelPrices[0].price.toNumber(),
    );
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.output * modelPrices[1].price.toNumber(),
    );
    expect(generation.cost_details.total).toBe(
      generationUsage2.usage.total * modelPrices[2].price.toNumber(),
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should overwrite costs if new costs are user provided", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: modelName,
      usage: {
        input: 100,
        output: 200,
        total: 300,
        inputCost: 1234,
        outputCost: 23523,
        totalCost: 5354,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // User provided cost
    expect(generation.provided_cost_details.input).toBe(
      generationUsage2.usage.inputCost,
    );
    expect(generation.provided_cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.provided_cost_details.total).toBe(
      generationUsage2.usage.totalCost,
    );

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage2.usage.inputCost,
    );
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.cost_details.total).toBe(
      generationUsage2.usage.totalCost,
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should overwrite costs if new costs are user provided and zero", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: modelName,
      usage: {
        input: 100,
        output: 200,
        total: 300,
        inputCost: 0,
        outputCost: 0,
        totalCost: 0,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // User provided cost
    expect(generation.provided_cost_details.input).toBe(
      generationUsage2.usage.inputCost,
    );
    expect(generation.provided_cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.provided_cost_details.total).toBe(
      generationUsage2.usage.totalCost,
    );

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage2.usage.inputCost,
    );
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.cost_details.total).toBe(
      generationUsage2.usage.totalCost,
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should overwrite costs if new costs are user provided and only partial", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: modelName,
      usage: {
        outputCost: 1,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // User provided cost
    expect(generation.provided_cost_details.input).toBe(undefined);
    expect(generation.provided_cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.provided_cost_details.total).toBe(undefined);

    // Calculated cost
    expect(generation.cost_details.input).toBe(undefined);
    expect(generation.cost_details.output).toBe(
      generationUsage2.usage.outputCost,
    );
    expect(generation.cost_details.total).toBe(1);
    expect(generation.usage_details.input).toBe(generationUsage1.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage1.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage1.usage.total);
  });

  it("should not overwrite costs if previous cost were user provided", async () => {
    const generationUsage1 = {
      model: modelName,
      usage: {
        input: 1,
        output: 2,
        total: 3,
        inputCost: 1234,
        outputCost: 23523,
        totalCost: 5354,
      },
    };

    const generationUsage2 = {
      model: modelName,
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched

    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // User provided cost
    expect(generation.provided_cost_details.input).toBe(
      generationUsage1.usage.inputCost,
    );
    expect(generation.provided_cost_details.output).toBe(
      generationUsage1.usage.outputCost,
    );
    expect(generation.provided_cost_details.total).toBe(
      generationUsage1.usage.totalCost,
    );

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage1.usage.inputCost,
    );
    expect(generation.cost_details.output).toBe(
      generationUsage1.usage.outputCost,
    );
    expect(generation.cost_details.total).toBe(
      generationUsage1.usage.totalCost,
    );
    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should not calculate anything if no costs are provided and no model is matched", async () => {
    const generationUsage1 = {
      model: undefined, // No model provided
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: undefined, // No model provided
      usage: {
        input: 100,
        output: 200,
        total: 300,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should not be matched
    expect(generation.internal_model).toBeUndefined();

    expect(generation.internal_model_id).toBeUndefined();

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // No calculated cost
    expect(generation.cost_details.input).toBeUndefined();
    expect(generation.cost_details.output).toBeUndefined();
    expect(generation.cost_details.total).toBeUndefined();

    expect(generation.usage_details.input).toBe(generationUsage2.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage2.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage2.usage.total);
  });

  it("should use the tokens of the previous call without model if model comes with following call", async () => {
    const generationUsage1 = {
      model: undefined, // No model provided
      usage: {
        input: 1,
        output: 2,
        total: 3,
      },
    };

    const generationUsage2 = {
      model: modelName,
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
      {
        id: uuidv4(),
        type: "generation-update",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage2,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });
    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");

    // Model name should be matched
    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // Calculated cost
    expect(generation.cost_details.input).toBe(
      generationUsage1.usage.input * modelPrices[0].price.toNumber(),
    );
    expect(generation.cost_details.output).toBe(
      generationUsage1.usage.output * modelPrices[1].price.toNumber(),
    );
    expect(generation.cost_details.total).toBe(
      generationUsage1.usage.total * modelPrices[2].price.toNumber(),
    );
    expect(generation.usage_details.input).toBe(generationUsage1.usage.input);
    expect(generation.usage_details.output).toBe(generationUsage1.usage.output);
    expect(generation.usage_details.total).toBe(generationUsage1.usage.total);
  });

  it("should skip tokenization and cost calculation if generation status is ERROR", async () => {
    const generationUsage1 = {
      model: modelName,
      input: "hello world",
      output: "hey whassup",
      usage: null,
      level: "ERROR",
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });

    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation).toBeDefined();
    expect(generation.type).toBe("GENERATION");
    expect(generation.level).toBe("ERROR");

    // Model name should be matched
    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // No user provided cost
    expect(generation.provided_cost_details.input).toBeUndefined();
    expect(generation.provided_cost_details.output).toBeUndefined();
    expect(generation.provided_cost_details.total).toBeUndefined();

    // No calculated cost
    expect(generation.cost_details.input).toBeUndefined();
    expect(generation.cost_details.output).toBeUndefined();
    expect(generation.cost_details.total).toBeUndefined();

    expect(generation.usage_details.input).toBeUndefined();
    expect(generation.usage_details.output).toBeUndefined();
    expect(generation.usage_details.total).toBeUndefined();
  });

  describe("tokenizer inference on failed and cancelled generations", () => {
    const gatewayScope = { name: "langfuse-ai-gateway", version: "0.1.0" };
    const gatewayAttribution = {
      ...sdkAttribution,
      ingestionApiKey: "gateway:grant-1",
    };

    beforeEach(() => {
      tokenisationMocks.tokenCountAsyncOverride = async () => 7;
    });

    afterEach(() => {
      tokenisationMocks.tokenCountAsyncOverride = null;
    });

    it("should tokenize a DEFAULT generation on the events table", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          input: "hello world",
          output: "hey whassup",
        },
        "testfile.txt",
      );

      expect(eventRecord.usage_details).toEqual({
        input: 7,
        output: 7,
        total: 14,
      });
    });

    it("should skip tokenization for ERROR generations written to the events table", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          level: "ERROR",
          input: "hello world",
          output: "hey whassup",
        },
        "testfile.txt",
      );

      expect(eventRecord.level).toBe("ERROR");
      expect(eventRecord.model_id).toBe(tokenModelData.id);
      expect(eventRecord.usage_details).toEqual({});
      expect(eventRecord.cost_details).toEqual({});
    });

    it("should not tokenize a cancelled gateway generation on the events table", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          level: "WARNING",
          statusMessage: "Client cancelled the response",
          scopeName: gatewayScope.name,
          metadata: {
            scope: gatewayScope,
            "langfuse.gateway.api_key.id": "gateway-key-1",
          },
          ingestionApiKey: gatewayAttribution.ingestionApiKey,
          input: "hello world",
          output: "[]",
        },
        "testfile.txt",
      );

      expect(eventRecord.model_id).toBe(tokenModelData.id);
      expect(eventRecord.usage_details).toEqual({});
      expect(eventRecord.cost_details).toEqual({});
    });

    it("should tokenize a generation that only claims the gateway scope on the events table", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          level: "WARNING",
          scopeName: gatewayScope.name,
          metadata: { scope: gatewayScope },
          ingestionApiKey: sdkAttribution.ingestionApiKey,
          input: "hello world",
          output: "hey whassup",
        },
        "testfile.txt",
      );

      expect(eventRecord.usage_details).toEqual({
        input: 7,
        output: 7,
        total: 14,
      });
    });

    it("should cost provider-reported usage on a cancelled gateway generation", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          level: "WARNING",
          scopeName: gatewayScope.name,
          metadata: {
            scope: gatewayScope,
            "langfuse.gateway.api_key.id": "gateway-key-1",
          },
          ingestionApiKey: gatewayAttribution.ingestionApiKey,
          providedUsageDetails: { input: 10, output: 5 },
          input: "hello world",
          output: "[]",
        },
        "testfile.txt",
      );

      expect(eventRecord.usage_details).toEqual({
        input: 10,
        output: 5,
        total: 15,
      });
      expect(eventRecord.cost_details.input).toBe(0.1);
      expect(eventRecord.cost_details.output).toBe(0.1);
    });

    it("should not tokenize a cancelled gateway generation on the observations table", async () => {
      const events = [
        {
          id: uuidv4(),
          type: "generation-create",
          timestamp: new Date().toISOString(),
          body: {
            id: generationId,
            startTime: new Date().toISOString(),
            model: modelName,
            level: "WARNING",
            statusMessage: "Client cancelled the response",
            metadata: { scope: gatewayScope },
            input: "hello world",
            output: "[]",
          },
        },
      ];

      await (mockIngestionService as any).processObservationEventList({
        projectId,
        entityId: generationId,
        createdAtTimestamp: new Date(),
        observationEventList: events,
        attribution: gatewayAttribution,
      });

      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({});
    });

    it("should tokenize a generation that only claims the gateway scope on the observations table", async () => {
      const events = [
        {
          id: uuidv4(),
          type: "generation-create",
          timestamp: new Date().toISOString(),
          body: {
            id: generationId,
            startTime: new Date().toISOString(),
            model: modelName,
            level: "WARNING",
            statusMessage: "Client cancelled the response",
            metadata: { scope: gatewayScope },
            input: "hello world",
            output: "hey whassup",
          },
        },
      ];

      await (mockIngestionService as any).processObservationEventList({
        projectId,
        entityId: generationId,
        createdAtTimestamp: new Date(),
        observationEventList: events,
        attribution: sdkAttribution,
      });

      const [tableName, generation] = mockAddToClickhouseWriter.mock.calls[0];
      expect(tableName).toBe("observations");
      expect(generation.internal_model_id).toBe(tokenModelData.id);
      expect(generation.usage_details).toEqual({
        input: 7,
        output: 7,
        total: 14,
      });
    });

    it("should not tokenize a replayed cancelled gateway generation on the events table", async () => {
      const eventRecord = await (mockIngestionService as any).createEventRecord(
        {
          spanId: generationId,
          traceId: uuidv4(),
          projectId,
          startTimeISO: new Date().toISOString(),
          type: "GENERATION",
          modelName,
          level: "WARNING",
          statusMessage: "Client cancelled the response",
          scopeName: gatewayScope.name,
          metadata: { scope: gatewayScope },
          ingestionApiKey: "",
          input: "hello world",
          output: "[]",
        },
        "testfile.txt",
      );

      expect(eventRecord.usage_details).toEqual({});
      expect(eventRecord.cost_details).toEqual({});
    });

    it("should not tokenize a replayed cancelled gateway generation on the observations table", async () => {
      const events = [
        {
          id: uuidv4(),
          type: "generation-create",
          timestamp: new Date().toISOString(),
          body: {
            id: generationId,
            startTime: new Date().toISOString(),
            model: modelName,
            level: "WARNING",
            statusMessage: "Client cancelled the response",
            metadata: { scope: gatewayScope },
            input: "hello world",
            output: "[]",
          },
        },
      ];

      await (mockIngestionService as any).processObservationEventList({
        projectId,
        entityId: generationId,
        createdAtTimestamp: new Date(),
        observationEventList: events,
        attribution: { ...sdkAttribution, ingestionApiKey: "" },
      });

      const [, generation] = mockAddToClickhouseWriter.mock.calls[0];
      expect(generation.usage_details).toEqual({});
      expect(generation.cost_details).toEqual({});
    });
  });

  it("should skip tokenization and leave usage details blank when cost details are provided", async () => {
    const generationUsage1 = {
      model: modelName,
      input: "hello world",
      output: "whassup",
      usage: null,
      costDetails: {
        input: 1,
        output: 2,
      },
    };

    const events = [
      {
        id: uuidv4(),
        type: "generation-create",
        timestamp: new Date().toISOString(),
        body: {
          id: generationId,
          startTime: new Date().toISOString(),
          ...generationUsage1,
        },
      },
    ];

    await (mockIngestionService as any).processObservationEventList({
      projectId,
      entityId: generationId,
      createdAtTimestamp: new Date(),
      observationEventList: events,
      attribution: sdkAttribution,
    });

    expect(mockAddToClickhouseWriter).toHaveBeenCalled();
    const args = mockAddToClickhouseWriter.mock.calls[0];
    const tableName = args[0];
    const generation = args[1];

    expect(tableName).toBe("observations");
    expect(generation.type).toBe("GENERATION");
    expect(generation.internal_model_id).toBe(tokenModelData.id);

    // Provided costs are authoritative (calculateUsageCosts ignores computed
    // usage once any cost point is provided)
    expect(generation.provided_cost_details).toEqual({ input: 1, output: 2 });
    expect(generation.cost_details).toEqual({ input: 1, output: 2, total: 3 });
    expect(generation.total_cost).toBe(3);

    // Tokenization must not run: usage details stay blank
    expect(generation.usage_details).toEqual({});
    expect(generation.provided_usage_details).toEqual({});

    // No pricing tier gets stamped from an empty usage vector
    expect(generation.usage_pricing_tier_id).toBeNull();
    expect(generation.usage_pricing_tier_name).toBeNull();
  });

  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,
          },
        },
      ];

      const eventRecord = await (mockIngestionService as any).createEventRecord(
        events[0],
        "testfile.txt",
      );
      await (mockIngestionService as any).writeEventRecord(eventRecord);

      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,
          },
        },
      ];

      const eventRecord = await (mockIngestionService as any).createEventRecord(
        events[0],
        "testfile.txt",
      );
      await (mockIngestionService as any).writeEventRecord(eventRecord);

      // 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);
    });
  });

  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,
        attribution: sdkAttribution,
      });

      // 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
    // 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 debugSpy = vi.spyOn(logger, "debug");
      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 = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");
      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 = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");
      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 = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");
      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 = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");

      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 = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");
      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,
        attribution: sdkAttribution,
      });

      const mismatchWarnings = debugSpy.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 debugSpy = vi.spyOn(logger, "debug");
      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,
        attribution: sdkAttribution,
      });

      const mismatchWarnings = debugSpy.mock.calls.filter(([message]) =>
        String(message).includes("exceeds provided total"),
      );
      expect(mismatchWarnings).toHaveLength(0);
    });
  });
});