Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dashboard): add v2 backend path for ModelUsageChart cost/usage-by-type timeseries (#12146)

Valery Meleshkin77cf2586d10a
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 82a9f6c83b..2c62b17c50 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -228,6 +228,18 @@ jobs:
run: |
pnpm run db:migrate
pnpm --filter=shared ch:up
+ - name: Download and extract ClickHouse client for dev-tables setup
+ run: |
+ CH_VERSION="24.9.3.128"
+ ARCH="amd64"
+ wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb
+
+ # The binary is usually located in ./usr/bin/clickhouse in the archive
+ dpkg-deb -x clickhouse-client.deb ch_client_dir
+ sudo cp ch_client_dir/usr/bin/clickhouse /usr/local/bin/
+ - name: Setup Dev Tables
+ run: |
+ pnpm --filter=shared ch:dev-tables
- name: Build
run: pnpm run build
env:
diff --git a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
index c5644bdffa..fff4332dd4 100644
--- a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
+++ b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts
@@ -24,6 +24,7 @@ import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import type { Session } from "next-auth";
import { env } from "@/src/env.mjs";
+import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
// Skip when events table is not enabled (v2 queries require events_core).
const maybe =
@@ -819,6 +820,14 @@ describe("dashboard v1 vs v2 consistency", () => {
// ─── 7. Score-aggregate tRPC endpoint (full getScoreAggregateV2 path) ─
+ // Synthetic data seeds environments "default" and "staging" explicitly.
+ // Seeder data uses "default" and "langfuse-prompt-experiment" for scores
+ // (see data-generators.ts lines 240, 268, 600 and clickhouse-builder.ts).
+ const SCORE_ENVIRONMENTS =
+ DATA_MODE === "seeder"
+ ? ["default", "langfuse-prompt-experiment"]
+ : ["default", "staging"];
+
maybe("score-aggregate tRPC endpoint v2", () => {
const chartInput = (
version: "v1" | "v2",
@@ -1038,7 +1047,7 @@ describe("dashboard v1 vs v2 consistency", () => {
it("should return matching results when environment filter is applied", async () => {
const caller = makeCaller();
- for (const env of ["default", "staging"]) {
+ for (const env of SCORE_ENVIRONMENTS) {
const envFilter: FilterCondition[] = [
{
column: "Environment",
@@ -1053,15 +1062,20 @@ describe("dashboard v1 vs v2 consistency", () => {
caller.dashboard.chart(chartInput("v2", envFilter)),
]);
- // Both should return data (10 traces per environment Γ— 3 score types)
+ // Both should return data
expect(v1Result.length).toBeGreaterThan(0);
- expect(v1Result.length).toBe(v2Result.length);
+ expect(v2Result.length).toBeGreaterThan(0);
const toKey = (r: Record<string, unknown>) =>
`${r.scoreName}|${r.scoreSource}|${r.scoreDataType}`;
const v1Map = new Map(v1Result.map((r) => [toKey(r), r]));
const v2Map = new Map(v2Result.map((r) => [toKey(r), r]));
+ // v2 must contain every key v1 returns, and their counts/averages must agree.
+ // v2 may return additional rows for scores where score.environment β‰  parent
+ // trace.environment: v1 joins traces and applies the environment filter on
+ // t.environment, while v2 filters directly on scores.environment β€” which is
+ // more accurate but may include scores v1 silently drops.
for (const [key, v1Row] of v1Map) {
const v2Row = v2Map.get(key);
expect(v2Row).toBeDefined();
@@ -1304,4 +1318,158 @@ describe("dashboard v1 vs v2 consistency", () => {
expect(Math.abs(v1Lower - v2Lower)).toBeLessThanOrEqual(tolerance);
});
});
+
+ // ─── 9. Model usage by-type timeseries (v2 via executeQuery + pairExpand) ──
+
+ const COST_BY_TYPE_QUERY = "observations-cost-by-type-timeseries" as const;
+ const USAGE_BY_TYPE_QUERY = "observations-usage-by-type-timeseries" as const;
+
+ maybe("model usage by-type timeseries v2", () => {
+ const typeInput = (
+ version: "v1" | "v2",
+ queryName: typeof COST_BY_TYPE_QUERY | typeof USAGE_BY_TYPE_QUERY,
+ ) => ({
+ projectId,
+ from: "traces_observations" as const,
+ select: [],
+ filter: [
+ {
+ column: "startTime",
+ operator: ">=" as const,
+ value: new Date(fromTimestamp7d),
+ type: "datetime" as const,
+ },
+ {
+ column: "startTime",
+ operator: "<" as const,
+ value: new Date(toTimestamp),
+ type: "datetime" as const,
+ },
+ {
+ column: "type",
+ operator: "any of" as const,
+ value: getGenerationLikeTypes(),
+ type: "stringOptions" as const,
+ },
+ ],
+ limit: 10000,
+ version,
+ queryName,
+ });
+
+ /** Sum all rows' `sum` values per `key` across all time buckets. */
+ function sumByKey(rows: DatabaseRow[]): Map<string, number> {
+ const acc = new Map<string, number>();
+ for (const row of rows) {
+ const k = String(row["key"]);
+ acc.set(k, (acc.get(k) ?? 0) + Number(row["sum"] ?? 0));
+ }
+ return acc;
+ }
+
+ describe("cost by type timeseries v2", () => {
+ it("should return valid cost by type data for v2", async () => {
+ const caller = makeCaller();
+ const result = await caller.dashboard.chart(
+ typeInput("v2", COST_BY_TYPE_QUERY),
+ );
+
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+ const keys = new Set(
+ result.map((r) => String((r as DatabaseRow)["key"])),
+ );
+ // Both modes include "total". Seeder data additionally has "input"/"output"
+ // because its cost_details maps are fully populated (see data-generators.ts).
+ // Synthetic data uses { total: ... } only (see seedSynthetic in this file).
+ expect(keys.has("total")).toBe(true);
+ if (DATA_MODE === "seeder") {
+ expect(keys.has("input")).toBe(true);
+ expect(keys.has("output")).toBe(true);
+ }
+ });
+
+ it("should return matching cost totals between v1 and v2", async () => {
+ const caller = makeCaller();
+ const [v1, v2] = await Promise.all([
+ caller.dashboard.chart(typeInput("v1", COST_BY_TYPE_QUERY)),
+ caller.dashboard.chart(typeInput("v2", COST_BY_TYPE_QUERY)),
+ ]);
+
+ const v1Totals = sumByKey(v1 as DatabaseRow[]);
+ const v2Totals = sumByKey(v2 as DatabaseRow[]);
+
+ expect(v1Totals.size).toBeGreaterThan(0);
+ expect(v2Totals.size).toBeGreaterThan(0);
+
+ // Every key present in v1 must also appear in v2
+ for (const key of v1Totals.keys()) {
+ expect(v2Totals.has(key)).toBe(true);
+ }
+
+ // Per-key totals must agree within 5%
+ // (ClickHouse eventual consistency between observations FINAL and events_core)
+ for (const [key, v1Sum] of v1Totals) {
+ const v2Sum = v2Totals.get(key) ?? 0;
+ if (v1Sum === 0) {
+ expect(v2Sum).toBeCloseTo(0, 2);
+ } else {
+ const ratio = v2Sum / v1Sum;
+ expect(ratio).toBeGreaterThanOrEqual(0.95);
+ expect(ratio).toBeLessThanOrEqual(1.05);
+ }
+ }
+ });
+ });
+
+ describe("usage by type timeseries v2", () => {
+ it("should return valid usage by type data for v2", async () => {
+ const caller = makeCaller();
+ const result = await caller.dashboard.chart(
+ typeInput("v2", USAGE_BY_TYPE_QUERY),
+ );
+
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+ const keys = new Set(
+ result.map((r) => String((r as DatabaseRow)["key"])),
+ );
+ // Both modes include "total". Seeder data additionally has "input"/"output".
+ expect(keys.has("total")).toBe(true);
+ if (DATA_MODE === "seeder") {
+ expect(keys.has("input")).toBe(true);
+ expect(keys.has("output")).toBe(true);
+ }
+ });
+
+ it("should return matching usage totals between v1 and v2", async () => {
+ const caller = makeCaller();
+ const [v1, v2] = await Promise.all([
+ caller.dashboard.chart(typeInput("v1", USAGE_BY_TYPE_QUERY)),
+ caller.dashboard.chart(typeInput("v2", USAGE_BY_TYPE_QUERY)),
+ ]);
+
+ const v1Totals = sumByKey(v1 as DatabaseRow[]);
+ const v2Totals = sumByKey(v2 as DatabaseRow[]);
+
+ expect(v1Totals.size).toBeGreaterThan(0);
+ expect(v2Totals.size).toBeGreaterThan(0);
+
+ for (const key of v1Totals.keys()) {
+ expect(v2Totals.has(key)).toBe(true);
+ }
+
+ for (const [key, v1Sum] of v1Totals) {
+ const v2Sum = v2Totals.get(key) ?? 0;
+ if (v1Sum === 0) {
+ expect(v2Sum).toBeCloseTo(0, 2);
+ } else {
+ const ratio = v2Sum / v1Sum;
+ expect(ratio).toBeGreaterThanOrEqual(0.95);
+ expect(ratio).toBeLessThanOrEqual(1.05);
+ }
+ }
+ });
+ });
+ });
});
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.ts
index 8b870870a2..b6f2d448f4 100644
--- a/web/src/__tests__/queryBuilder.servertest.ts
+++ b/web/src/__tests__/queryBuilder.servertest.ts
@@ -11,6 +11,8 @@ import {
createObservationsCh,
createTraceScore,
createScoresCh,
+ createEvent,
+ createEventsCh,
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
@@ -3729,6 +3731,378 @@ describe("queryBuilder", () => {
expect(resultWithOpt).toEqual(resultWithoutOpt);
});
});
+
+ describe("pairExpand map expansion (v2)", () => {
+ it("should emit ARRAY JOIN clause for pairExpand dimensions", async () => {
+ const projectId = randomUUID();
+ const builder = new QueryBuilder(undefined, "v2");
+ const { query: sql } = await builder.build(
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ projectId,
+ true,
+ );
+
+ expect(sql).toContain("ARRAY JOIN");
+ expect(sql).toContain(
+ "mapKeys(events_observations.cost_details) AS costType",
+ );
+ expect(sql).toContain(
+ "mapValues(events_observations.cost_details) AS cost_value",
+ );
+ // ARRAY JOIN must appear before WHERE
+ expect(sql.indexOf("ARRAY JOIN")).toBeLessThan(sql.indexOf("WHERE"));
+ // No inline arrayJoin() function call β€” must use clause form
+ expect(sql).not.toMatch(/arrayJoin\(mapKeys/);
+ });
+
+ it("should aggregate cost_details by type correctly", async () => {
+ const projectId = randomUUID();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 10, output: 20, total: 30 },
+ start_time: Date.now() * 1000,
+ }),
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 5, output: 15, total: 20 },
+ start_time: Date.now() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ true,
+ );
+
+ expect(result).toHaveLength(3);
+
+ const inputRow = result.find((r) => r["costType"] === "input");
+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5
+
+ const outputRow = result.find((r) => r["costType"] === "output");
+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15
+
+ const totalRow = result.find((r) => r["costType"] === "total");
+ expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20
+ });
+
+ it("should aggregate usage_details by type correctly", async () => {
+ const projectId = randomUUID();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ usage_details: { input: 100, output: 200, total: 300 },
+ start_time: Date.now() * 1000,
+ }),
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ usage_details: { input: 50, output: 75, total: 125 },
+ start_time: Date.now() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [{ field: "usageType" }],
+ metrics: [{ measure: "usageByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ true,
+ );
+
+ expect(result).toHaveLength(3);
+
+ const inputRow = result.find((r) => r["usageType"] === "input");
+ expect(Number(inputRow?.["sum_usageByType"])).toBe(150); // 100 + 50
+
+ const outputRow = result.find((r) => r["usageType"] === "output");
+ expect(Number(outputRow?.["sum_usageByType"])).toBe(275); // 200 + 75
+ });
+
+ it("should produce timeseries with costType dimension and WITH FILL", async () => {
+ const projectId = randomUUID();
+ const now = new Date();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 10, output: 20 },
+ start_time: now.getTime() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ const builder = new QueryBuilder(undefined, "v2");
+ const { query: sql } = await builder.build(
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: { granularity: "day" },
+ fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),
+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ projectId,
+ true,
+ );
+
+ expect(sql).toContain("WITH FILL");
+ expect(sql).toContain("time_dimension");
+ // GROUP BY parts may be newline-separated in the generated SQL
+ expect(sql).toContain("GROUP BY costType");
+ expect(sql).toMatch(/GROUP BY costType[\s,]+time_dimension/);
+
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: { granularity: "day" },
+ fromTimestamp: new Date(now.getTime() - 2 * 86400000).toISOString(),
+ toTimestamp: new Date(now.getTime() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ true,
+ );
+
+ expect(result.length).toBeGreaterThan(0);
+ expect(result[0]).toHaveProperty("time_dimension");
+ expect(result[0]).toHaveProperty("costType");
+ expect(result[0]).toHaveProperty("sum_costByType");
+ });
+
+ it("should respect type filter with pairExpand dimensions", async () => {
+ const projectId = randomUUID();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 10 },
+ start_time: Date.now() * 1000,
+ }),
+ createEvent({
+ project_id: projectId,
+ type: "SPAN",
+ cost_details: { input: 999 },
+ start_time: Date.now() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [
+ {
+ column: "type",
+ operator: "=",
+ value: "GENERATION",
+ type: "string",
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ true,
+ );
+
+ const inputRow = result.find((r) => r["costType"] === "input");
+ // Only GENERATION row contributes: 10, not 999
+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(10, 2);
+ });
+
+ it("should aggregate cost_details by type correctly via two-level query path", async () => {
+ // Forces the two-level path by passing useSingleLevelOptimization=false.
+ // Verifies that the bare alias reference in buildInnerDimensionsPart
+ // (not any()) is correct when the pairExpand dim is in GROUP BY.
+ const projectId = randomUUID();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 10, output: 20, total: 30 },
+ start_time: Date.now() * 1000,
+ }),
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 5, output: 15, total: 20 },
+ start_time: Date.now() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ false, // force two-level path
+ );
+
+ expect(result).toHaveLength(3);
+
+ const inputRow = result.find((r) => r["costType"] === "input");
+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(15, 2); // 10 + 5
+
+ const outputRow = result.find((r) => r["costType"] === "output");
+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(35, 2); // 20 + 15
+
+ const totalRow = result.find((r) => r["costType"] === "total");
+ expect(Number(totalRow?.["sum_costByType"])).toBeCloseTo(50, 2); // 30 + 20
+ });
+
+ it("should auto-include costType dimension when only costByType measure is requested", async () => {
+ // Verifies requiresDimension: the query builder must inject the costType
+ // dimension automatically so the ARRAY JOIN is emitted and cost_value is in scope.
+ const projectId = randomUUID();
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ type: "GENERATION",
+ cost_details: { input: 7, output: 3 },
+ start_time: Date.now() * 1000,
+ }),
+ ];
+ await createEventsCh(events);
+
+ // No costType dimension requested β€” the builder should add it automatically.
+ const result = await executeQuery(
+ projectId,
+ {
+ view: "observations",
+ dimensions: [], // intentionally empty
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ "v2",
+ true,
+ );
+
+ // costType should appear in results even though it was not explicitly requested
+ expect(result.length).toBeGreaterThan(0);
+ expect(result[0]).toHaveProperty("costType");
+
+ const inputRow = result.find((r) => r["costType"] === "input");
+ expect(Number(inputRow?.["sum_costByType"])).toBeCloseTo(7, 2);
+
+ const outputRow = result.find((r) => r["costType"] === "output");
+ expect(Number(outputRow?.["sum_costByType"])).toBeCloseTo(3, 2);
+ });
+
+ it("should throw when multiple pairExpand dimensions are requested directly", async () => {
+ // Two separate ARRAY JOIN clauses create a cartesian product in ClickHouse.
+ const projectId = randomUUID();
+ const builder = new QueryBuilder(undefined, "v2");
+
+ await expect(
+ builder.build(
+ {
+ view: "observations",
+ dimensions: [{ field: "costType" }, { field: "usageType" }],
+ metrics: [{ measure: "costByType", aggregation: "sum" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ projectId,
+ true,
+ ),
+ ).rejects.toThrow("Only one pairExpand dimension is supported per query");
+ });
+
+ it("should throw when both costByType and usageByType measures are requested (auto-inject creates two pairExpand dims)", async () => {
+ // Each measure auto-injects its required pairExpand dimension via requiresDimension.
+ // Requesting both triggers the multi-pairExpand guard.
+ const projectId = randomUUID();
+ const builder = new QueryBuilder(undefined, "v2");
+
+ await expect(
+ builder.build(
+ {
+ view: "observations",
+ dimensions: [],
+ metrics: [
+ { measure: "costByType", aggregation: "sum" },
+ { measure: "usageByType", aggregation: "sum" },
+ ],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),
+ orderBy: null,
+ },
+ projectId,
+ true,
+ ),
+ ).rejects.toThrow("Only one pairExpand dimension is supported per query");
+ });
+ });
});
describe("validateQuery", () => {
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index fa142a2e31..f34c4bd9ec 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -244,6 +244,73 @@ async function getScoreAggregateV2({
return merged as DatabaseRow[];
}
+async function getObservationsByTypeV2(params: {
+ projectId: string;
+ filter: FilterState;
+ dimensionField: "costType" | "usageType";
+ metricMeasure: "costByType" | "usageByType";
+}): Promise<DatabaseRow[]> {
+ const { projectId, filter, dimensionField, metricMeasure } = params;
+
+ const [from, to] = extractFromAndToTimestampsFromFilter(filter);
+ if (!from?.value || !to?.value) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Time filter required",
+ });
+ }
+
+ // Filter normalisation for the executeQuery (v2) path:
+ //
+ // Filters arriving here originate from two different column-naming conventions:
+ // A) uiTableName format ("Model", "Environment", …) β€” used by globalFilterState
+ // filters that come from the standard dashboard filter bar. These are handled
+ // canonically by mapLegacyUiTableFilterToView (see dashboardUiTableToViewMapping.ts).
+ // B) uiTableId format ("model") β€” used by ModelSelectorPopover, which constructs
+ // its filter using the lower-camel uiTableId rather than the display uiTableName.
+ // mapLegacyUiTableFilterToView matches on uiTableName so it cannot cover this case.
+ //
+ // If additional uiTableId-format filters are introduced here in the future, add them
+ // to the CHART_FILTER_ID_TO_VIEW_FIELD map below (the canonical view field names live
+ // in dashboardUiTableToViewMapping.ts :: viewMappings["observations"]).
+ const CHART_FILTER_ID_TO_VIEW_FIELD: Record<string, string> = {
+ model: "providedModelName",
+ };
+
+ const nonDatetimeFilters = filter.filter((f) => f.type !== "datetime");
+ // Apply standard uiTableName β†’ view field mapping first.
+ const standardMapped = mapLegacyUiTableFilterToView(
+ "observations",
+ nonDatetimeFilters,
+ );
+ // Then patch any remaining uiTableId-format columns.
+ const viewFilters = standardMapped.map((f) => {
+ const viewField = CHART_FILTER_ID_TO_VIEW_FIELD[f.column];
+ return viewField ? { ...f, column: viewField } : f;
+ });
+
+ const q: QueryType = {
+ view: "observations",
+ dimensions: [{ field: dimensionField }],
+ metrics: [{ measure: metricMeasure, aggregation: "sum" }],
+ filters: viewFilters,
+ timeDimension: { granularity: "auto" },
+ fromTimestamp: new Date(from.value as Date).toISOString(),
+ toTimestamp: new Date(to.value as Date).toISOString(),
+ orderBy: null,
+ };
+
+ const rows = await executeQuery(projectId, q, "v2", true);
+
+ // Transform flat rows to { intervalStart, key, sum } expected by the component.
+ const sumField = `sum_${metricMeasure}`;
+ return rows.map((row) => ({
+ intervalStart: new Date(row["time_dimension"] as string),
+ key: row[dimensionField] as string,
+ sum: Number(row[sumField] ?? 0),
+ })) as DatabaseRow[];
+}
+
export const dashboardRouter = createTRPCRouter({
chart: protectedProjectProcedure
.input(
@@ -255,7 +322,6 @@ export const dashboardRouter = createTRPCRouter({
.enum([
// Current score table is weird and does not fit into new model. Keep around as is until we decide what to do with it.
"score-aggregate",
- // Cost by type and usage by type are currently not supported in the new data model.
"observations-usage-by-type-timeseries",
"observations-cost-by-type-timeseries",
])
@@ -292,12 +358,28 @@ export const dashboardRouter = createTRPCRouter({
countScoreId: Number(row.count),
})) as DatabaseRow[];
case "observations-usage-by-type-timeseries":
+ if (input.version === "v2") {
+ return getObservationsByTypeV2({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ dimensionField: "usageType",
+ metricMeasure: "usageByType",
+ });
+ }
const rowsObsType = await getObservationUsageByTypeByTime(
input.projectId,
input.filter ?? [],
);
return rowsObsType as DatabaseRow[];
case "observations-cost-by-type-timeseries":
+ if (input.version === "v2") {
+ return getObservationsByTypeV2({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ dimensionField: "costType",
+ metricMeasure: "costByType",
+ });
+ }
const rowsObsCostByType = await getObservationCostByTypeByTime(
input.projectId,
input.filter ?? [],
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index 3b4ec5b553..d3daa5f0ba 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -1104,6 +1104,28 @@ export const eventsObservationsView: ViewDeclarationType = {
description: "Names of tools that were called by the observation.",
explodeArray: true,
},
+ costType: {
+ sql: "mapKeys(events_observations.cost_details)",
+ alias: "costType",
+ type: "string",
+ description:
+ "Cost category key from cost_details map (e.g. 'input', 'output', 'total').",
+ pairExpand: {
+ valuesSql: "mapValues(events_observations.cost_details)",
+ valueAlias: "cost_value",
+ },
+ },
+ usageType: {
+ sql: "mapKeys(events_observations.usage_details)",
+ alias: "usageType",
+ type: "string",
+ description:
+ "Token usage category key from usage_details map (e.g. 'input', 'output', 'total').",
+ pairExpand: {
+ valuesSql: "mapValues(events_observations.usage_details)",
+ valueAlias: "usage_value",
+ },
+ },
},
measures: {
count: {
@@ -1230,6 +1252,24 @@ export const eventsObservationsView: ViewDeclarationType = {
description: "Number of tool calls per observation.",
unit: "calls",
},
+ costByType: {
+ sql: "cost_value",
+ alias: "costByType",
+ type: "decimal",
+ unit: "USD",
+ requiresDimension: "costType",
+ description:
+ "Sum of cost per category. The costType dimension is auto-included to emit the ARRAY JOIN that brings cost_value into scope.",
+ },
+ usageByType: {
+ sql: "usage_value",
+ alias: "usageByType",
+ type: "integer",
+ unit: "tokens",
+ requiresDimension: "usageType",
+ description:
+ "Sum of token usage per category. The usageType dimension is auto-included to emit the ARRAY JOIN that brings usage_value into scope.",
+ },
},
tableRelations: {
// No traces relation - userId, sessionId, tags are denormalized on events table
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index 3ee289272e..1750703b98 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -26,6 +26,7 @@ type AppliedDimensionType = {
relationTable?: string;
aggregationFunction?: string;
explodeArray?: boolean;
+ pairExpand?: { valuesSql: string; valueAlias: string };
};
type AppliedMetricType = {
@@ -35,6 +36,7 @@ type AppliedMetricType = {
relationTable?: string;
aggs?: Record<string, string>;
measureName: string; // Original measure name for lookups
+ requiresDimension?: string;
};
export class QueryBuilder {
@@ -105,6 +107,7 @@ export class QueryBuilder {
...dim,
table: dim.relationTable || view.name,
explodeArray: dim.explodeArray,
+ pairExpand: dim.pairExpand,
};
});
}
@@ -400,12 +403,19 @@ export class QueryBuilder {
appliedMetrics: AppliedMetricType[],
): boolean {
// Single-level query requires:
- // 1. All metrics have aggs configuration
+ // 1. All metrics are single-level compatible, which means either:
+ // a. They have aggs configuration (@@AGGN@@ templates that resolve to function
+ // calls), OR
+ // b. They are pairExpand value-alias measures (requiresDimension is set). These
+ // reference a plain column brought into scope by the ARRAY JOIN clause and
+ // work correctly with a direct sum()/avg() in a single SELECT.
// 2. No custom aggregation functions on dimensions
- // Measures without .aggs: {} (like uniq(scores.id)) must use two-level approach
+ // Measures without either (like uniq(scores.id)) must use the two-level approach.
const allMetricsHaveAggs =
appliedMetrics.length === 0 ||
- appliedMetrics.every((m) => m.aggs !== undefined);
+ appliedMetrics.every(
+ (m) => m.aggs !== undefined || m.requiresDimension !== undefined,
+ );
// Check if any dimension has custom aggregation
const hasCustomDimensionAgg = appliedDimensions.some(
@@ -495,6 +505,22 @@ export class QueryBuilder {
return relationJoins;
}
+ private buildArrayJoinClause(
+ appliedDimensions: AppliedDimensionType[],
+ ): string {
+ const pairs = appliedDimensions.filter((d) => d.pairExpand);
+ if (pairs.length === 0) return "";
+ // Multiple pairExpand dimensions would produce separate ARRAY JOIN clauses
+ // which ClickHouse executes as a cartesian product β€” almost certainly wrong.
+ if (pairs.length > 1) {
+ throw new InvalidRequestError(
+ `Only one pairExpand dimension is supported per query. Found: ${pairs.map((d) => d.alias ?? d.sql).join(", ")}`,
+ );
+ }
+ const d = pairs[0];
+ return `ARRAY JOIN\n ${d.sql} AS ${d.alias ?? d.sql},\n ${d.pairExpand!.valuesSql} AS ${d.pairExpand!.valueAlias}`;
+ }
+
private buildWhereClause(
filterList: FilterList,
parameters: Record<string, unknown>,
@@ -615,6 +641,17 @@ export class QueryBuilder {
if (dimension.aggregationFunction) {
return `${dimension.aggregationFunction} as ${dimension.alias ?? dimension.sql}`;
}
+ // pairExpand key columns (e.g. costType) are added to the inner GROUP BY in
+ // buildInnerSelect, so they are already deterministic grouping keys here.
+ // Unlike regular dimensions (which are not in GROUP BY and need any() to satisfy
+ // ClickHouse's aggregation rules), wrapping in any() would be wrong: it implies
+ // the value is non-deterministic within the group when it's actually the axis
+ // being grouped on. Use a bare reference instead.
+ // Note: the paired value column (e.g. cost_value) is NOT in GROUP BY and IS
+ // wrapped in any() in buildInnerMetricsPart, so the outer query can re-aggregate it.
+ if (dimension.pairExpand) {
+ return `${dimension.alias} as ${dimension.alias ?? dimension.sql}`;
+ }
// Explode array dimensions using arrayJoin
if (dimension.explodeArray) {
return `arrayJoin(${dimension.sql}) as ${dimension.alias ?? dimension.sql}`;
@@ -643,11 +680,21 @@ export class QueryBuilder {
.map((metric) => {
let sql = metric.sql;
- // For two-level queries, substitute ${aggN} with actual agg function from template
+ // For two-level queries, substitute @@AGGN@@ with actual agg function from template
if (metric.aggs) {
sql = this.substituteAggTemplates(sql, metric.aggs);
}
+ // pairExpand value-alias measures (e.g. costByType, usageByType) reference a raw
+ // column brought into scope by the ARRAY JOIN clause. That column is not in the
+ // inner GROUP BY, so wrap it in any() to satisfy ClickHouse. The outer query then
+ // applies the real aggregation. We scope this to requiresDimension metrics only β€”
+ // other measures use @@AGGN@@ templates that resolve to function calls, so they
+ // never need this treatment.
+ if (metric.requiresDimension && !sql.includes("(")) {
+ sql = `any(${sql})`;
+ }
+
return `${sql} as ${metric.alias || metric.sql}`;
})
.join(",\n");
@@ -666,9 +713,10 @@ export class QueryBuilder {
const projectIdSql = `${actualTableName}.project_id`;
// Build inner GROUP BY - include exploded array dimensions (they must be in GROUP BY after arrayJoin)
+ // Also include pairExpand dimensions (their key column is in scope after ARRAY JOIN clause)
const groupByParts = [projectIdSql, idSql];
for (const dim of appliedDimensions) {
- if (dim.explodeArray) {
+ if (dim.explodeArray || dim.pairExpand) {
groupByParts.push(dim.alias ?? dim.sql);
}
}
@@ -864,6 +912,10 @@ export class QueryBuilder {
dimensionsPart =
appliedDimensions
.map((d) => {
+ if (d.pairExpand) {
+ // Bare reference β€” already projected by the ARRAY JOIN clause
+ return `${d.alias} as ${d.alias ?? d.sql}`;
+ }
if (d.explodeArray) {
return `arrayJoin(${d.sql}) as ${d.alias ?? d.sql}`;
}
@@ -1080,6 +1132,25 @@ export class QueryBuilder {
const appliedDimensions = this.mapDimensions(query.dimensions, view);
const appliedMetrics = this.mapMetrics(query.metrics, view);
+ // Auto-include dimensions required by pairExpand-dependent measures.
+ // e.g. costByType.requiresDimension = "costType": without that dimension the
+ // ARRAY JOIN is never emitted and ClickHouse errors with "unknown column cost_value".
+ for (const metric of appliedMetrics) {
+ if (
+ metric.requiresDimension &&
+ !appliedDimensions.some((d) => d.alias === metric.requiresDimension)
+ ) {
+ const requiredDimDef = view.dimensions[metric.requiresDimension];
+ if (requiredDimDef) {
+ appliedDimensions.push({
+ ...requiredDimDef,
+ table: requiredDimDef.relationTable || view.name,
+ pairExpand: requiredDimDef.pairExpand,
+ });
+ }
+ }
+ }
+
// Create a new FilterList with the mapped filters
let filterList = new FilterList(this.mapFilters(query.filters, view));
@@ -1113,6 +1184,12 @@ export class QueryBuilder {
fromClause += ` ${relationJoins.join(" ")}`;
}
+ // ARRAY JOIN must appear after regular JOINs and before WHERE
+ const arrayJoinClause = this.buildArrayJoinClause(appliedDimensions);
+ if (arrayJoinClause) {
+ fromClause += `\n${arrayJoinClause}`;
+ }
+
// Build WHERE clause with parameters
fromClause += this.buildWhereClause(filterList, parameters);
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index a4522082d9..3fe6e1a40a 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -23,6 +23,12 @@ export const viewDeclaration = z.object({
aggregationFunction: z.string().optional(),
highCardinality: z.boolean().optional(),
explodeArray: z.boolean().optional(),
+ pairExpand: z
+ .object({
+ valuesSql: z.string(),
+ valueAlias: z.string(),
+ })
+ .optional(),
}),
),
measures: z.record(
@@ -35,6 +41,10 @@ export const viewDeclaration = z.object({
type: z.string().optional(),
unit: z.string().optional(),
aggs: z.record(z.string(), z.string()).optional(),
+ // When set, the query builder will auto-include this dimension if it is absent.
+ // Used for pairExpand value-alias measures (e.g. costByType requires costType so
+ // the ARRAY JOIN is emitted and "cost_value" is in scope).
+ requiresDimension: z.string().optional(),
}),
),
tableRelations: z.record(