Skip to content

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

feat: make v2 metrics completely compatible with v1 (#10995)

Valery Meleshkin90b26167edc6
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.ts
index 4b90a4be2b..022b636a61 100644
--- a/web/src/__tests__/async/metrics-v2-api.servertest.ts
+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts
@@ -3,7 +3,7 @@ import {
makeZodVerifiedAPICall,
makeAPICall,
} from "@/src/__tests__/test-utils";
-import { GetMetricsV2Response } from "@/src/features/public-api/types/metrics";
+import { GetMetricsV1Response } from "@/src/features/public-api/types/metrics";
import {
createEvent,
createEventsCh,
@@ -91,7 +91,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -110,7 +110,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -137,7 +137,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -208,7 +208,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
// Make the API call
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(histogramQuery))}`,
);
@@ -243,8 +243,9 @@ describe("/api/public/v2/metrics API Endpoint", () => {
});
maybe("Denormalized Trace Fields", () => {
- ["traceId", "userId", "sessionId", "tags", "release"].forEach((field) => {
- it(`should support ${field} dimension from events table`, async () => {
+ it.each([["traceId"], ["userId"], ["sessionId"], ["tags"], ["release"]])(
+ "Denormalized field: %s",
+ async (field) => {
const query = {
view: "observations",
dimensions: [{ field }],
@@ -254,7 +255,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -267,8 +268,8 @@ describe("/api/public/v2/metrics API Endpoint", () => {
x.count_count && x[field] ? (x.count_count as number) > 0 : false,
).length,
).toBeGreaterThan(0);
- });
- });
+ },
+ );
it("should support multiple denormalized dimensions together", async () => {
const query = {
@@ -284,7 +285,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -294,67 +295,32 @@ describe("/api/public/v2/metrics API Endpoint", () => {
});
});
- maybe("Validation - Trace-JOIN Dimensions", () => {
- it("should reject traceName dimension (requires traces JOIN)", async () => {
- const query = {
- view: "observations",
- dimensions: [{ field: "traceName" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
- toTimestamp: new Date().toISOString(),
- };
-
- const response = await makeAPICall(
- "GET",
- `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
- );
-
- expect(response.status).toBe(400);
- // Zod validation returns generic "Invalid request data"
- expect(response.body.message).toContain("Invalid request data");
- });
-
- it("should reject traceRelease dimension (requires traces JOIN)", async () => {
- const query = {
- view: "observations",
- dimensions: [{ field: "traceRelease" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
- toTimestamp: new Date().toISOString(),
- };
-
- const response = await makeAPICall(
- "GET",
- `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
- );
-
- expect(response.status).toBe(400);
- // Zod validation returns generic "Invalid request data"
- expect(response.body.message).toContain("Invalid request data");
- });
-
- it("should reject traceVersion dimension (requires traces JOIN)", async () => {
- const query = {
- view: "observations",
- dimensions: [{ field: "traceVersion" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
- toTimestamp: new Date().toISOString(),
- };
+ maybe("Validation - Backwards-Compatible Trace Dimensions", () => {
+ it.each([["traceName"], ["traceRelease"], ["traceVersion"]])(
+ "should support %s dimension",
+ async (dimensionField) => {
+ const query = {
+ view: "observations",
+ dimensions: [{ field: dimensionField }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
- const response = await makeAPICall(
- "GET",
- `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
- );
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
- expect(response.status).toBe(400);
- // Zod validation returns generic "Invalid request data"
- expect(response.body.message).toContain("Invalid request data");
- });
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ },
+ );
});
maybe("Validation - View Support", () => {
- it("should reject traces view (not supported in V2)", async () => {
+ it("should support traces view", async () => {
const query = {
view: "traces",
metrics: [{ measure: "count", aggregation: "count" }],
@@ -362,12 +328,14 @@ describe("/api/public/v2/metrics API Endpoint", () => {
toTimestamp: new Date().toISOString(),
};
- const response = await makeAPICall(
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
- expect(response.status).toBe(400);
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
});
it("should support scores-numeric view", async () => {
@@ -379,7 +347,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -399,7 +367,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -427,7 +395,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -453,7 +421,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -575,7 +543,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
// Make the API call
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(validQuery))}`,
);
@@ -650,7 +618,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -683,7 +651,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -714,7 +682,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -736,6 +704,8 @@ describe("/api/public/v2/metrics API Endpoint", () => {
const eventsScoreUserId = "events-score-user";
const eventsScoreTags = ["events-tag-1", "events-tag-2"];
const eventsScoreRelease = "events-v3.0.0";
+ const eventsScoreTraceName = "events-trace-name";
+ const eventsScoreVersion = "events-v1.2.3";
beforeAll(async () => {
if (!hasEvents) return;
@@ -750,6 +720,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
span_id: eventsObservationId,
trace_id: eventsScoreTraceId,
project_id: projectId,
+ trace_name: eventsScoreTraceName,
name: "test-observation-for-score",
provided_model_name: "gpt-4-turbo",
start_time: Date.now() * 1000,
@@ -757,6 +728,7 @@ describe("/api/public/v2/metrics API Endpoint", () => {
session_id: eventsScoreSessionId,
tags: eventsScoreTags,
release: eventsScoreRelease,
+ version: eventsScoreVersion,
}),
]);
@@ -777,25 +749,244 @@ describe("/api/public/v2/metrics API Endpoint", () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
- it("should support userId dimension via events JOIN", async () => {
+ it.each([
+ [
+ "traceName",
+ eventsScoreTraceName,
+ (row: any) => row.traceName === eventsScoreTraceName,
+ ],
+ [
+ "userId",
+ eventsScoreUserId,
+ (row: any) => row.userId === eventsScoreUserId,
+ ],
+ ["tags", eventsScoreTags, (row: any) => Array.isArray(row.tags)],
+ [
+ "traceRelease",
+ eventsScoreRelease,
+ (row: any) => row.traceRelease === eventsScoreRelease,
+ ],
+ [
+ "traceVersion",
+ eventsScoreVersion,
+ (row: any) => row.traceVersion === eventsScoreVersion,
+ ],
+ ])(
+ "should support %s dimension via events JOIN",
+ async (dimensionField, expectedValue, findRowFn) => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: dimensionField }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-events",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ if (dimensionField === "tags") {
+ expect(response.body.data.length).toBeGreaterThan(0);
+ } else {
+ const foundRow = response.body.data.find(findRowFn);
+ expect(foundRow).toBeDefined();
+ }
+ },
+ );
+ });
+
+ maybe("Scores Views - Observation Dimensions via Events", () => {
+ let obsEventsTraceId: string;
+ let obsEventsObservationId: string;
+
+ beforeAll(async () => {
+ if (!hasEvents) return;
+
+ obsEventsTraceId = randomUUID();
+ obsEventsObservationId = randomUUID();
+
+ await createEventsCh([
+ createEvent({
+ id: obsEventsObservationId,
+ span_id: obsEventsObservationId,
+ trace_id: obsEventsTraceId,
+ project_id: projectId,
+ name: "test-observation-for-score-v2",
+ provided_model_name: "gpt-4-turbo",
+ start_time: Date.now() * 1000,
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ id: randomUUID(),
+ project_id: projectId,
+ trace_id: obsEventsTraceId,
+ observation_id: obsEventsObservationId,
+ session_id: "obs-events-test-session",
+ name: "score-with-observation-v2",
+ value: 95,
+ data_type: "NUMERIC",
+ timestamp: Date.now(),
+ }),
+ ]);
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ it.each([
+ [
+ "observationModelName",
+ "gpt-4-turbo",
+ (row: any) => row.observationModelName === "gpt-4-turbo",
+ ],
+ [
+ "observationName",
+ "test-observation-for-score-v2",
+ (row: any) => row.observationName === "test-observation-for-score-v2",
+ ],
+ ])(
+ "should support %s dimension via events table",
+ async (dimensionField, expectedValue, findRowFn) => {
+ const query = {
+ view: "scores-numeric",
+ dimensions: [{ field: dimensionField }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "score-with-observation-v2",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+
+ // Should be able to access observation fields via events table JOIN
+ const foundRow = response.body.data.find(findRowFn);
+ expect(foundRow).toBeDefined();
+ },
+ );
+ });
+
+ maybe("Traces View - V2 Events Table", () => {
+ let testTraceId: string;
+ const nowMs = Date.now();
+ const now = nowMs * 1000; // microseconds
+
+ beforeAll(async () => {
+ if (!hasEvents) return;
+
+ testTraceId = randomUUID();
+
+ // Create multiple observations with different tags to test aggregation
+ const traceEvents = [
+ createEvent({
+ id: randomUUID(),
+ span_id: randomUUID(),
+ trace_id: testTraceId,
+ project_id: projectId,
+ trace_name: "test-trace-v2",
+ type: "GENERATION",
+ name: "observation-1",
+ start_time: now,
+ end_time: now + 1000000, // +1 second
+ user_id: "trace-user-v2",
+ session_id: "trace-session-v2",
+ tags: ["api", "prod"],
+ release: "v2.1.0",
+ version: "1.0",
+ environment: "production",
+ usage_details: { input: 100, output: 50, total: 150 },
+ total_cost: 0.01,
+ }),
+ createEvent({
+ id: randomUUID(),
+ span_id: randomUUID(),
+ trace_id: testTraceId,
+ project_id: projectId,
+ trace_name: "test-trace-v2",
+ type: "SPAN",
+ name: "observation-2",
+ start_time: now + 500000, // +0.5 seconds
+ end_time: now + 2000000, // +2 seconds
+ user_id: "trace-user-v2",
+ session_id: "trace-session-v2",
+ tags: ["api", "v2"],
+ release: "v2.1.0",
+ usage_details: { input: 200, output: 100, total: 300 },
+ total_cost: 0.02,
+ }),
+ ];
+
+ await createEventsCh(traceEvents);
+
+ // Create a trace-level score
+ await createScoresCh([
+ {
+ id: randomUUID(),
+ trace_id: testTraceId,
+ project_id: projectId,
+ name: "trace-quality",
+ value: 0.95,
+ data_type: "NUMERIC",
+ source: "API",
+ timestamp: now,
+ environment: "production",
+ metadata: { quality: "high" },
+ is_deleted: 0,
+ created_at: now,
+ updated_at: now,
+ event_ts: now,
+ },
+ ]);
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ });
+
+ it.each([
+ ["name", "test-trace-v2"],
+ ["userId", "trace-user-v2"],
+ ["sessionId", "trace-session-v2"],
+ ["release", "v2.1.0"],
+ ["version", "1.0"],
+ ["environment", "production"],
+ ])("should support %s dimension", async (dimension, expectedValue) => {
const query = {
- view: "scores-numeric",
- dimensions: [{ field: "userId" }],
+ view: "traces",
+ dimensions: [{ field: dimension }],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "name",
- operator: "=",
- value: "score-with-events",
- type: "string",
- },
- ],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -803,169 +994,117 @@ describe("/api/public/v2/metrics API Endpoint", () => {
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
- const userData = response.body.data.find(
- (row: any) => row.userId === eventsScoreUserId,
+ const row = response.body.data.find(
+ (r: any) => r[dimension] === expectedValue,
);
- expect(userData).toBeDefined();
+ expect(row).toBeDefined();
+ expect(row?.count_count).toBeGreaterThan(0);
});
- it("should support tags dimension via events JOIN", async () => {
+ it("should aggregate tags from all observations in trace", async () => {
const query = {
- view: "scores-numeric",
+ view: "traces",
dimensions: [{ field: "tags" }],
metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "name",
- operator: "=",
- value: "score-with-events",
- type: "string",
- },
- ],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
- expect(response.body.data.length).toBeGreaterThan(0);
+
+ // Tags should be union of all tags from observations: ["api", "prod", "v2"]
+ const traceRow = response.body.data.find(
+ (r: any) => Array.isArray(r.tags) && r.tags.includes("api"),
+ );
+ expect(traceRow).toBeDefined();
+ expect(traceRow?.tags).toContain("api");
+ // Should contain tags from both observations (deduped)
+ expect(traceRow?.tags.length).toBeGreaterThanOrEqual(2);
});
- it("should support release dimension via events JOIN", async () => {
+ it.each([
+ ["count", "count"],
+ ["observationsCount", "sum"],
+ ["scoresCount", "sum"],
+ ["totalTokens", "sum"],
+ ["totalCost", "sum"],
+ ["latency", "avg"],
+ ])("should support %s measure", async (measure, aggregation) => {
const query = {
- view: "scores-numeric",
- dimensions: [{ field: "release" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "name",
- operator: "=",
- value: "score-with-events",
- type: "string",
- },
- ],
+ view: "traces",
+ metrics: [{ measure, aggregation }],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
+ expect(response.body.data.length).toBeGreaterThan(0);
- const releaseData = response.body.data.find(
- (row: any) => row.release === eventsScoreRelease,
- );
- expect(releaseData).toBeDefined();
+ const metricKey = `${aggregation}_${measure}`;
+ expect(response.body.data[0]).toHaveProperty(metricKey);
});
- });
- maybe("Scores Views - Validation (Reject traceName)", () => {
- it("should reject traceName dimension in scores-numeric (not on events table)", async () => {
+ it("should convert latency from microseconds to milliseconds", async () => {
const query = {
- view: "scores-numeric",
- dimensions: [{ field: "traceName" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
- toTimestamp: new Date().toISOString(),
+ view: "traces",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "latency", aggregation: "avg" }],
+ filters: [
+ {
+ column: "name",
+ operator: "=",
+ value: "test-trace-v2",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(nowMs - 86400000).toISOString(),
+ toTimestamp: new Date(nowMs + 1000).toISOString(),
};
- const response = await makeAPICall(
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
- expect(response.status).toBe(400);
- expect(response.body.message).toContain("Invalid request data");
- });
-
- it("should reject traceName in scores-categorical view", async () => {
- const query = {
- view: "scores-categorical",
- dimensions: [{ field: "traceName" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
- toTimestamp: new Date().toISOString(),
- };
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
- const response = await makeAPICall(
- "GET",
- `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ const traceData = response.body.data.find(
+ (r: any) => r.name === "test-trace-v2",
);
+ expect(traceData).toBeDefined();
- expect(response.status).toBe(400);
- expect(response.body.message).toContain("Invalid request data");
- });
- });
-
- maybe("Scores Views - Observation Dimensions via Events", () => {
- let obsEventsTraceId: string;
- let obsEventsObservationId: string;
-
- beforeAll(async () => {
- if (!hasEvents) return;
-
- obsEventsTraceId = randomUUID();
- obsEventsObservationId = randomUUID();
-
- await createEventsCh([
- createEvent({
- id: obsEventsObservationId,
- span_id: obsEventsObservationId,
- trace_id: obsEventsTraceId,
- project_id: projectId,
- name: "test-observation-for-score-v2",
- provided_model_name: "gpt-4-turbo",
- start_time: Date.now() * 1000,
- }),
- ]);
-
- await createScoresCh([
- createTraceScore({
- id: randomUUID(),
- project_id: projectId,
- trace_id: obsEventsTraceId,
- observation_id: obsEventsObservationId,
- session_id: "obs-events-test-session",
- name: "score-with-observation-v2",
- value: 95,
- data_type: "NUMERIC",
- timestamp: Date.now(),
- }),
- ]);
-
- await new Promise((resolve) => setTimeout(resolve, 50));
+ // Latency should be in milliseconds (2 seconds based on test data)
+ const avgLatency = traceData?.avg_latency as number;
+ expect(avgLatency).toBeGreaterThan(1000); // At least 1 second
+ expect(avgLatency).toBeLessThan(3000); // Less than 3 seconds
});
- it("should support observationModelName dimension via events table JOIN", async () => {
+ it("should count trace-level scores only (not observation-level)", async () => {
const query = {
- view: "scores-numeric",
- dimensions: [{ field: "observationModelName" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "name",
- operator: "=",
- value: "score-with-observation-v2",
- type: "string",
- },
- ],
+ view: "traces",
+ metrics: [{ measure: "scoresCount", aggregation: "sum" }],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -973,32 +1112,26 @@ describe("/api/public/v2/metrics API Endpoint", () => {
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
- // Should be able to access observation fields via events table JOIN
- const modelData = response.body.data.find(
- (row: any) => row.observationModelName === "gpt-4-turbo",
- );
- expect(modelData).toBeDefined();
+ // Should have trace-level scores counted
+ const totalScores = response.body.data[0]?.sum_scoresCount;
+ expect(totalScores).toBeGreaterThan(0);
});
- it("should support observationName dimension from events table", async () => {
+ it("should support multiple dimensions and metrics together", async () => {
const query = {
- view: "scores-numeric",
- dimensions: [{ field: "observationName" }],
- metrics: [{ measure: "count", aggregation: "count" }],
- filters: [
- {
- column: "name",
- operator: "=",
- value: "score-with-observation-v2",
- type: "string",
- },
+ view: "traces",
+ dimensions: [{ field: "environment" }, { field: "release" }],
+ metrics: [
+ { measure: "count", aggregation: "count" },
+ { measure: "totalCost", aggregation: "sum" },
+ { measure: "observationsCount", aggregation: "sum" },
],
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
toTimestamp: new Date().toISOString(),
};
const response = await makeZodVerifiedAPICall(
- GetMetricsV2Response,
+ GetMetricsV1Response,
"GET",
`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
);
@@ -1006,10 +1139,13 @@ describe("/api/public/v2/metrics API Endpoint", () => {
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
- const obsNameData = response.body.data.find(
- (row: any) => row.observationName === "test-observation-for-score-v2",
+ const prodRow = response.body.data.find(
+ (r: any) => r.environment === "production" && r.release === "v2.1.0",
);
- expect(obsNameData).toBeDefined();
+ expect(prodRow).toBeDefined();
+ expect(prodRow?.count_count).toBeGreaterThan(0);
+ expect(prodRow?.sum_totalCost).toBeGreaterThan(0);
+ expect(prodRow?.sum_observationsCount).toBeGreaterThanOrEqual(2);
});
});
});
diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.ts
index c8216cff8f..1a73de8bc7 100644
--- a/web/src/features/public-api/types/metrics.ts
+++ b/web/src/features/public-api/types/metrics.ts
@@ -119,94 +119,3 @@ export const GetMetricsDailyV1Response = z
meta: paginationMetaResponseZod,
})
.strict();
-
-/**
- * V2 API - Events Table Only
- */
-
-// V2-specific view enum (observations only, no traces)
-export const v2Views = z.enum([
- "observations", // Maps to events-observations internally
- "scores-numeric",
- "scores-categorical",
-]);
-
-// V2 Query Object (similar to v1 but with v2Views and no traceXYZ fields validation)
-export const MetricsV2QueryObject = z
- .object({
- view: v2Views, // Limited to observations and scores
- dimensions: z.array(dimension).optional().default([]),
- metrics: z.array(metric),
- filters: z.array(singleFilter).optional().default([]),
- timeDimension: z
- .object({
- granularity: granularities,
- })
- .nullable()
- .optional()
- .default(null),
- fromTimestamp: z.string().datetime({ offset: true }),
- toTimestamp: z.string().datetime({ offset: true }),
- orderBy: z
- .array(
- z.object({
- field: z.string(),
- direction: z.enum(["asc", "desc"]),
- }),
- )
- .nullable()
- .optional()
- .default(null),
- config: z
- .object({
- bins: z.number().int().min(1).max(100).optional(),
- row_limit: z.number().int().positive().lte(1000).optional(),
- })
- .optional(),
- })
- .refine(
- (query) =>
- new Date(query.fromTimestamp).getTime() <
- new Date(query.toTimestamp).getTime(),
- {
- message: "fromTimestamp must be before toTimestamp",
- },
- )
- .refine(
- (query) => {
- // Validate that trace-JOIN-only dimensions are not used
- const traceJoinOnlyDimensions = [
- "traceName",
- "traceRelease",
- "traceVersion",
- ];
- const usesTraceJoinDimensions = query.dimensions?.some((dim) =>
- traceJoinOnlyDimensions.includes(dim.field),
- );
- return !usesTraceJoinDimensions;
- },
- {
- message:
- "V2 metrics API does not support the traceName, traceRelease and traceVersion dimensions.",
- },
- );
-
-// GET /api/public/v2/metrics
-export const GetMetricsV2Query = z.object({
- query: z
- .string()
- .transform((str) => {
- try {
- return JSON.parse(str);
- } catch (e) {
- throw new InvalidRequestError(
- "Invalid JSON in query parameter: " + (e as Error).message,
- );
- }
- })
- .pipe(MetricsV2QueryObject),
-});
-
-export const GetMetricsV2Response = z.object({
- data: z.array(z.record(z.string(), z.unknown())),
-});
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index f3ab75d9cb..31b77ee162 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -154,6 +154,155 @@ export const traceView: ViewDeclarationType = {
baseCte: `traces FINAL`,
};
+export const eventsTracesView: ViewDeclarationType = {
+ name: "events_traces",
+ description:
+ "Traces built from events table aggregation - mirrors v1 traces view with 100% API compatibility.",
+ dimensions: {
+ id: {
+ sql: "events.trace_id",
+ alias: "id",
+ type: "string",
+ description: "Unique identifier of the trace.",
+ // This is the GROUP BY identity column
+ },
+ name: {
+ sql: "events.trace_name",
+ alias: "name",
+ type: "string",
+ description:
+ "Name assigned to the trace (often the endpoint or operation).",
+ aggregationFunction:
+ "argMaxIf(events.trace_name, events.event_ts, events.trace_name <> '')",
+ },
+ tags: {
+ sql: "events.tags",
+ alias: "tags",
+ type: "string[]",
+ description: "User-defined tags associated with the trace.",
+ aggregationFunction: "arrayDistinct(flatten(groupArray(events.tags)))",
+ },
+ userId: {
+ sql: "events.user_id",
+ alias: "userId",
+ type: "string",
+ description: "Identifier of the user triggering the trace.",
+ aggregationFunction:
+ "argMaxIf(events.user_id, events.event_ts, events.user_id <> '')",
+ },
+ sessionId: {
+ sql: "events.session_id",
+ alias: "sessionId",
+ type: "string",
+ description: "Identifier of the session triggering the trace.",
+ aggregationFunction:
+ "argMaxIf(events.session_id, events.event_ts, events.session_id <> '')",
+ },
+ release: {
+ sql: "events.release",
+ alias: "release",
+ type: "string",
+ description: "Release version of the trace.",
+ aggregationFunction:
+ "argMaxIf(events.release, events.event_ts, events.release <> '')",
+ },
+ version: {
+ sql: "events.version",
+ alias: "version",
+ type: "string",
+ description: "Version of the trace.",
+ aggregationFunction:
+ "argMaxIf(events.version, events.event_ts, events.version <> '')",
+ },
+ environment: {
+ sql: "events.environment",
+ alias: "environment",
+ type: "string",
+ description: "Deployment environment (e.g., production, staging).",
+ aggregationFunction:
+ "argMaxIf(events.environment, events.event_ts, events.environment <> '')",
+ },
+ timestampMonth: {
+ sql: "events.start_time",
+ alias: "timestampMonth",
+ type: "string",
+ description: "Month of the trace timestamp in YYYY-MM format.",
+ aggregationFunction: "formatDateTime(min(events.start_time), '%Y-%m')",
+ },
+ },
+ measures: {
+ count: {
+ sql: "count(*)",
+ alias: "count",
+ type: "integer",
+ description: "Total number of traces.",
+ unit: "traces",
+ },
+ observationsCount: {
+ sql: "uniq(events.span_id)",
+ alias: "observationsCount",
+ type: "integer",
+ description: "Unique observations linked to the trace.",
+ unit: "observations",
+ },
+ scoresCount: {
+ sql: "uniq(scores.id)",
+ alias: "scoresCount",
+ type: "integer",
+ relationTable: "scores",
+ description: "Unique scores attached to the trace.",
+ unit: "scores",
+ },
+ uniqueUserIds: {
+ sql: "uniq(events.user_id)",
+ alias: "uniqueUserIds",
+ type: "integer",
+ description: "Count of unique userIds.",
+ unit: "users",
+ },
+ uniqueSessionIds: {
+ sql: "uniq(events.session_id)",
+ alias: "uniqueSessionIds",
+ type: "integer",
+ description: "Count of unique sessionIds.",
+ unit: "sessions",
+ },
+ latency: {
+ sql: "date_diff('microsecond', min(events.start_time), max(events.end_time)) / 1000",
+ alias: "latency",
+ type: "integer",
+ description:
+ "Elapsed time between the first and last observation inside the trace (converted from microseconds to milliseconds).",
+ unit: "millisecond",
+ },
+ totalTokens: {
+ sql: "sumMap(events.usage_details)['total']",
+ alias: "totalTokens",
+ type: "integer",
+ description: "Sum of tokens consumed by all observations in the trace.",
+ unit: "tokens",
+ },
+ totalCost: {
+ sql: "sum(events.total_cost)",
+ alias: "totalCost",
+ type: "decimal",
+ description: "Total cost accumulated across observations in the trace.",
+ unit: "USD",
+ },
+ },
+ tableRelations: {
+ scores: {
+ name: "scores",
+ joinConditionSql:
+ "ON events.trace_id = scores.trace_id AND events.project_id = scores.project_id",
+ timeDimension: "timestamp",
+ },
+ },
+ segments: [],
+ timeDimension: "start_time",
+ baseCte: `events`,
+};
+
export const observationsView: ViewDeclarationType = {
name: "observations",
description:
@@ -480,6 +629,13 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {
description: "Identifier of the session.",
},
// Trace metadata on events table (accessed via events JOIN)
+ traceName: {
+ sql: "events.trace_name",
+ alias: "traceName",
+ type: "string",
+ relationTable: "events",
+ description: "Name of the parent trace.",
+ },
userId: {
sql: "events.user_id",
alias: "userId",
@@ -494,13 +650,20 @@ const scoresV2BaseDimensions: DimensionsDeclarationType = {
relationTable: "events",
description: "User-defined tags.",
},
- release: {
+ traceRelease: {
sql: "events.release",
- alias: "release",
+ alias: "traceRelease",
type: "string",
relationTable: "events",
description: "Release version.",
},
+ traceVersion: {
+ sql: "events.version",
+ alias: "traceVersion",
+ type: "string",
+ relationTable: "events",
+ description: "Version of the parent trace.",
+ },
// Observation fields from events table
observationName: {
sql: "events.name",
@@ -814,6 +977,27 @@ export const eventsObservationsView: ViewDeclarationType = {
type: "string",
description: "Release version.",
},
+ // Backwards-compatible field definitions (for API parity with v1)
+ traceName: {
+ sql: "events_observations.trace_name",
+ alias: "traceName",
+ type: "string",
+ description: "Name of the parent trace (backwards-compatible with v1).",
+ },
+ traceRelease: {
+ sql: "events_observations.release",
+ alias: "traceRelease",
+ type: "string",
+ description:
+ "Release version of the parent trace (backwards-compatible with v1, maps to denormalized release field).",
+ },
+ traceVersion: {
+ sql: "events_observations.version",
+ alias: "traceVersion",
+ type: "string",
+ description:
+ "Version of the parent trace (backwards-compatible with v1, maps to denormalized version field).",
+ },
providedModelName: {
sql: "events_observations.provided_model_name",
alias: "providedModelName",
@@ -953,19 +1137,11 @@ export const eventsObservationsView: ViewDeclarationType = {
};
// Define versioned structure type
-// v1 has all views including traces (normalized model with traces table)
-// v2 omits traces (denormalized model with events table only)
+// Both v1 and v2 have all views (traces, observations, scores-numeric, scores-categorical)
+// v1 uses normalized tables (traces, observations), v2 uses events table
type VersionedViewDeclarations = {
- readonly v1: {
- readonly traces: ViewDeclarationType;
- readonly observations: ViewDeclarationType;
- readonly "scores-numeric": ViewDeclarationType;
- readonly "scores-categorical": ViewDeclarationType;
- };
- readonly v2: {
- readonly observations: ViewDeclarationType;
- readonly "scores-numeric": ViewDeclarationType;
- readonly "scores-categorical": ViewDeclarationType;
+ readonly [version in ViewVersion]: {
+ readonly [K in z.infer<typeof views>]: ViewDeclarationType;
};
};
@@ -978,7 +1154,7 @@ export const viewDeclarations: VersionedViewDeclarations = {
"scores-categorical": scoresCategoricalView,
},
v2: {
- // No traces in v2 - trace metadata is denormalized in events table
+ traces: eventsTracesView,
observations: eventsObservationsView,
"scores-numeric": scoresNumericViewV2,
"scores-categorical": scoresCategoricalViewV2,
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index 5223eba1da..c49b95bf02 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -24,6 +24,7 @@ type AppliedDimensionType = {
sql: string;
alias?: string;
relationTable?: string;
+ aggregationFunction?: string;
};
type AppliedMetricType = {
@@ -265,7 +266,7 @@ export class QueryBuilder {
uiTableId: "project_id",
clickhouseTableName: actualTableName,
clickhouseSelect: "project_id",
- queryPrefix: view.name,
+ queryPrefix: actualTableName,
type: "string",
};
@@ -274,7 +275,7 @@ export class QueryBuilder {
uiTableId: view.timeDimension,
clickhouseTableName: actualTableName,
clickhouseSelect: view.timeDimension,
- queryPrefix: view.name,
+ queryPrefix: actualTableName,
type: "datetime",
};
@@ -515,10 +516,14 @@ export class QueryBuilder {
// Add regular dimensions
if (appliedDimensions.length > 0) {
dimensions += `${appliedDimensions
- .map(
- (dimension) =>
- `any(${dimension.sql}) as ${dimension.alias ?? dimension.sql}`,
- )
+ .map((dimension) => {
+ // Use custom aggregation function if specified (e.g., argMaxIf for events table traces)
+ if (dimension.aggregationFunction) {
+ return `${dimension.aggregationFunction} as ${dimension.alias ?? dimension.sql}`;
+ }
+ // Default: wrap in any()
+ return `any(${dimension.sql}) as ${dimension.alias ?? dimension.sql}`;
+ })
.join(",\n")},`;
}
@@ -554,9 +559,10 @@ export class QueryBuilder {
innerMetricsPart: string,
fromClause: string,
) {
+ const actualTableName = this.actualTableName(view);
// Use actual SQL from view definition for id column (handles events.span_id -> id mapping)
- const idSql = view.dimensions.id?.sql || `${view.name}.id`;
- const projectIdSql = `${view.name}.project_id`;
+ const idSql = view.dimensions.id?.sql || `${actualTableName}.id`;
+ const projectIdSql = `${actualTableName}.project_id`;
return `
SELECT
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index e971a35cdf..b8a5f0c61d 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -20,6 +20,7 @@ export const viewDeclaration = z.object({
description: z.string().optional(),
type: z.string().optional(),
unit: z.string().optional(),
+ aggregationFunction: z.string().optional(),
}),
),
measures: z.record(
diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.ts
index bf1040321c..98bbab2dac 100644
--- a/web/src/pages/api/public/v2/metrics.ts
+++ b/web/src/pages/api/public/v2/metrics.ts
@@ -2,8 +2,8 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddleware
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { logger } from "@langfuse/shared/src/server";
import {
- GetMetricsV2Query,
- GetMetricsV2Response,
+ GetMetricsV1Query,
+ GetMetricsV1Response,
} from "@/src/features/public-api/types/metrics";
import { executeQuery } from "@/src/features/query/server/queryExecutor";
@@ -11,8 +11,8 @@ export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
name: "Get Metrics V2",
rateLimitResource: "public-api-metrics", // Same rate limit as v1
- querySchema: GetMetricsV2Query,
- responseSchema: GetMetricsV2Response,
+ querySchema: GetMetricsV1Query,
+ responseSchema: GetMetricsV1Response,
fn: async ({ query, auth }) => {
try {
const queryParams = query.query;