Skip to content

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

feat(api): metrics v2 API endpoint based on events table (#10864)

Valery Meleshkin9efe5daf7114
diff --git a/web/src/__tests__/async/metrics-v2-api.servertest.ts b/web/src/__tests__/async/metrics-v2-api.servertest.ts
new file mode 100644
index 0000000000..fabee39b44
--- /dev/null
+++ b/web/src/__tests__/async/metrics-v2-api.servertest.ts
@@ -0,0 +1,617 @@
+import { randomUUID } from "crypto";
+import {
+ makeZodVerifiedAPICall,
+ makeAPICall,
+} from "@/src/__tests__/test-utils";
+import { GetMetricsV2Response } from "@/src/features/public-api/types/metrics";
+import {
+ createEvent,
+ createTrace,
+ createTracesCh,
+ createEventsCh,
+} from "@langfuse/shared/src/server";
+import { env } from "@/src/env.mjs";
+
+const hasEvents = env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";
+const maybe = hasEvents ? describe : describe.skip;
+
+describe("/api/public/v2/metrics API Endpoint", () => {
+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+ let traceId: string;
+ let observationIds: string[];
+
+ const timestamp = new Date();
+ const timeValue = timestamp.getTime() * 1000; // microseconds for events table
+ const testMetadataValue = randomUUID();
+
+ beforeAll(async () => {
+ if (!hasEvents) {
+ // don't attempt data setup if events table is disabled
+ return;
+ }
+
+ traceId = randomUUID();
+ observationIds = [];
+
+ // Create trace in ClickHouse
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ user_id: "test-user-v2",
+ session_id: "test-session-v2",
+ tags: ["v2-test", "events-table"],
+ release: "v2.0.0",
+ });
+ await createTracesCh([trace]);
+
+ // Create observations in events table
+ const observations = [];
+ for (let i = 0; i < 5; i++) {
+ const obsId = randomUUID();
+ observationIds.push(obsId);
+
+ observations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: traceId,
+ project_id: projectId,
+ type: i % 2 === 0 ? "GENERATION" : "SPAN",
+ name: `v2-test-observation-${i}`,
+ level: "DEFAULT",
+ start_time: timeValue + i * 1000000, // Spread over 5 seconds
+ end_time: timeValue + (i + 1) * 1000000,
+ provided_model_name: i % 2 === 0 ? "gpt-4" : null,
+ user_id: "test-user-v2",
+ session_id: "test-session-v2",
+ tags: ["v2-test", "events-table"],
+ release: "v2.0.0",
+ usage_details: {
+ input: 100 * (i + 1),
+ output: 50 * (i + 1),
+ total: 150 * (i + 1),
+ },
+ cost_details: {
+ input: 0.001 * (i + 1),
+ output: 0.002 * (i + 1),
+ },
+ total_cost: 0.003 * (i + 1),
+ }),
+ );
+ }
+
+ await createEventsCh(observations);
+
+ // Wait a bit for ClickHouse to process
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ });
+
+ it("should kill redis connection", () => {
+ // we need at least one test case to avoid hanging
+ // redis connection when everything else is skipped.
+ });
+
+ maybe("Basic Functionality", () => {
+ it("should return correct count metrics", async () => {
+ const query = {
+ view: "observations",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(Array.isArray(response.body.data)).toBe(true);
+ });
+
+ it("should support latency metrics with microsecond to millisecond conversion", async () => {
+ const query = {
+ view: "observations",
+ metrics: [{ measure: "latency", aggregation: "avg" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ // Latency should be in milliseconds (around 1000ms based on our test data)
+ if (response.body.data.length > 0) {
+ const avgLatency = response.body.data[0].avg_latency as number;
+ expect(avgLatency).toBeGreaterThan(0);
+ expect(avgLatency).toBeLessThan(10000); // Should be reasonable milliseconds
+ }
+ });
+
+ it("should support cost and token metrics", async () => {
+ const query = {
+ view: "observations",
+ metrics: [
+ { measure: "totalCost", aggregation: "sum" },
+ { measure: "totalTokens", aggregation: "sum" },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+
+ it("should handle histogram aggregation with custom bin count", async () => {
+ const histogramTraceId = randomUUID();
+
+ // Create observations with varying costs to test histogram
+ const histogramObservations: Array<ReturnType<typeof createEvent>> = [];
+ const costValues = [
+ // Low cost cluster - 5 observations
+ 0.001, 0.002, 0.003, 0.004, 0.005,
+ // Medium cost cluster - 5 observations
+ 0.05, 0.06, 0.07, 0.08, 0.09,
+ // High cost cluster - 5 observations
+ 0.5, 0.6, 0.7, 0.8, 0.9,
+ ];
+
+ costValues.forEach((cost, index) => {
+ const obsId = randomUUID();
+ histogramObservations.push(
+ createEvent({
+ id: obsId,
+ span_id: obsId,
+ trace_id: histogramTraceId,
+ project_id: projectId,
+ name: `histogram-observation-${index}`,
+ type: "GENERATION",
+ start_time: timeValue,
+ total_cost: cost,
+ metadata_names: ["test"],
+ metadata_raw_values: [testMetadataValue],
+ }),
+ );
+ });
+
+ await createEventsCh(
+ histogramObservations as ReturnType<typeof createEvent>[],
+ );
+
+ const twoDaysAgo = new Date(new Date().getTime() - 3600 * 24 * 2 * 1000);
+ const tomorrow = new Date(new Date().getTime() + 3600 * 24 * 1000);
+
+ // Test histogram query with custom bin count
+ const histogramQuery = {
+ view: "observations",
+ dimensions: [],
+ metrics: [{ measure: "totalCost", aggregation: "histogram" }],
+ filters: [
+ {
+ column: "metadata",
+ operator: "contains",
+ key: "test",
+ value: testMetadataValue,
+ type: "stringObject",
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: twoDaysAgo.toISOString(),
+ toTimestamp: tomorrow.toISOString(),
+ orderBy: null,
+ config: { bins: 15 },
+ };
+
+ // Make the API call
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(histogramQuery))}`,
+ );
+
+ // Validate response format
+ expect(response.status).toBe(200);
+ expect(Array.isArray(response.body.data)).toBe(true);
+ expect(response.body.data).toHaveLength(1);
+
+ // Validate histogram data structure
+ const histogramData = response.body.data[0].histogram_totalCost as [
+ number,
+ number,
+ number,
+ ][];
+ expect(Array.isArray(histogramData)).toBe(true);
+ expect(histogramData.length).toBeGreaterThan(0);
+ expect(histogramData.length).toBeLessThanOrEqual(15); // Should not exceed requested bins
+
+ // Verify histogram tuple structure [lower, upper, height]
+ histogramData.forEach((bin: [number, number, number]) => {
+ expect(Array.isArray(bin)).toBe(true);
+ expect(bin).toHaveLength(3);
+ const [lower, upper, height] = bin;
+ expect(typeof lower).toBe("number");
+ expect(typeof upper).toBe("number");
+ expect(typeof height).toBe("number");
+ expect(lower).toBeLessThanOrEqual(upper);
+ expect(height).toBeGreaterThanOrEqual(0);
+ });
+ });
+ });
+
+ maybe("Denormalized Trace Fields", () => {
+ ["traceId", "userId", "sessionId", "tags", "release"].forEach((field) => {
+ it(`should support ${field} dimension from events table`, async () => {
+ const query = {
+ view: "observations",
+ dimensions: [{ field }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "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);
+ expect(
+ response.body.data.filter((x) =>
+ 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 = {
+ view: "observations",
+ dimensions: [
+ { field: "userId" },
+ { field: "sessionId" },
+ { field: "tags" },
+ ],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+ });
+
+ 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(),
+ };
+
+ 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");
+ });
+ });
+
+ maybe("Validation - View Support", () => {
+ it("should reject traces view (not supported in V2)", async () => {
+ const query = {
+ view: "traces",
+ 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);
+ });
+
+ it("should support scores-numeric view", async () => {
+ const query = {
+ view: "scores-numeric",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ });
+ });
+
+ maybe("Time Dimension", () => {
+ it("should support time dimension with granularity", async () => {
+ const query = {
+ view: "observations",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ timeDimension: { granularity: "day" },
+ fromTimestamp: new Date(Date.now() - 86400000 * 7).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+ });
+
+ maybe("Filters", () => {
+ it("should support filtering by observation-level dimensions", async () => {
+ const query = {
+ view: "observations",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "type",
+ operator: "=",
+ value: "GENERATION",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+
+ it("should support filtering by denormalized userId", async () => {
+ const query = {
+ view: "observations",
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "userId",
+ operator: "=",
+ value: "test-user-v2",
+ type: "string",
+ },
+ ],
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ });
+ });
+
+ maybe("LFE-6148: Comprehensive filter validation", () => {
+ it("should return 400 error for invalid array field filters", async () => {
+ // Test using string type on array field (tags) - should return validation error
+ const invalidStringTypeQuery = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "tags",
+ operator: "contains",
+ value: "test-tag",
+ type: "string", // Invalid: array fields require arrayOptions type
+ },
+ ],
+ timeDimension: {
+ granularity: "day",
+ },
+ fromTimestamp: new Date(Date.now() - 86400000 * 2).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ orderBy: null,
+ };
+
+ // Make API call and expect 400 error
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(invalidStringTypeQuery))}`,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body).toMatchObject({
+ error: "InvalidRequestError",
+ message: expect.stringContaining(
+ "Array fields require type 'arrayOptions', not 'string'",
+ ),
+ });
+ });
+
+ it("should return 400 error for invalid metadata filters", async () => {
+ // Test using wrong type for metadata field
+ const invalidMetadataTypeQuery = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "metadata",
+ operator: "contains",
+ value: "test-value",
+ type: "string", // Invalid: metadata requires stringObject type
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ orderBy: null,
+ };
+
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(invalidMetadataTypeQuery))}`,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body).toMatchObject({
+ error: "InvalidRequestError",
+ message: expect.stringContaining(
+ "Metadata filters require type 'stringObject'",
+ ),
+ });
+ });
+
+ it("should work correctly with proper array field filter configuration", async () => {
+ // Create observation with tags for this test
+ const taggedObsId = randomUUID();
+ const taggedTraceId = randomUUID();
+
+ await createTracesCh([
+ createTrace({
+ id: taggedTraceId,
+ name: "tagged-observation-trace",
+ project_id: projectId,
+ timestamp: Date.now(),
+ tags: ["v2-filter-test", "array-test"],
+ }),
+ ]);
+
+ await createEventsCh([
+ createEvent({
+ id: taggedObsId,
+ span_id: taggedObsId,
+ trace_id: taggedTraceId,
+ project_id: projectId,
+ type: "SPAN",
+ name: "tagged-observation",
+ start_time: Date.now() * 1000,
+ tags: ["v2-filter-test", "array-test"],
+ user_id: "filter-test-user",
+ }),
+ ]);
+
+ // Test with correct arrayOptions filter on observations view
+ const validQuery = {
+ view: "observations",
+ dimensions: [{ field: "name" }],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [
+ {
+ column: "tags",
+ operator: "any of", // Correct operator for array fields
+ value: ["v2-filter-test"],
+ type: "arrayOptions", // Correct type for array fields
+ },
+ ],
+ timeDimension: null,
+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
+ toTimestamp: new Date().toISOString(),
+ orderBy: null,
+ };
+
+ // Make the API call
+ const response = await makeZodVerifiedAPICall(
+ GetMetricsV2Response,
+ "GET",
+ `/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(validQuery))}`,
+ );
+
+ // Should succeed and return data
+ expect(response.status).toBe(200);
+ expect(Array.isArray(response.body.data)).toBe(true);
+ expect(response.body.data.length).toBeGreaterThan(0);
+
+ // Verify we got the tagged observation
+ const taggedObsResult = response.body.data.find(
+ (row: any) => row.name === "tagged-observation",
+ );
+ expect(taggedObsResult).toBeDefined();
+ expect(Number(taggedObsResult.count_count)).toBeGreaterThanOrEqual(1);
+ });
+ });
+});
diff --git a/web/src/features/public-api/types/metrics.ts b/web/src/features/public-api/types/metrics.ts
index 1a73de8bc7..c8216cff8f 100644
--- a/web/src/features/public-api/types/metrics.ts
+++ b/web/src/features/public-api/types/metrics.ts
@@ -119,3 +119,94 @@ 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/dashboardUiTableToViewMapping.ts b/web/src/features/query/dashboardUiTableToViewMapping.ts
index 7fa1a8d85e..21b9b439c5 100644
--- a/web/src/features/query/dashboardUiTableToViewMapping.ts
+++ b/web/src/features/query/dashboardUiTableToViewMapping.ts
@@ -99,6 +99,53 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {
viewName: "traceVersion",
},
],
+ "events-observations": [
+ // Similar to observations but without trace-JOIN fields (traceName, traceRelease, traceVersion)
+ {
+ uiTableName: "Observation Name",
+ viewName: "name",
+ },
+ {
+ uiTableName: "Score Name",
+ viewName: "scoreName",
+ },
+ {
+ uiTableName: "User",
+ viewName: "userId",
+ },
+ {
+ uiTableName: "Session",
+ viewName: "sessionId",
+ },
+ {
+ uiTableName: "Metadata",
+ viewName: "metadata",
+ },
+ {
+ uiTableName: "Type",
+ viewName: "type",
+ },
+ {
+ uiTableName: "Tags",
+ viewName: "tags",
+ },
+ {
+ uiTableName: "Model",
+ viewName: "providedModelName",
+ },
+ {
+ uiTableName: "Environment",
+ viewName: "environment",
+ },
+ {
+ uiTableName: "Release",
+ viewName: "release",
+ },
+ {
+ uiTableName: "Version",
+ viewName: "version",
+ },
+ ],
"scores-numeric": [
{
uiTableName: "Score Name",
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index 55242eefa7..82eeca6f83 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -694,12 +694,235 @@ export const scoresCategoricalView: ViewDeclarationType = {
baseCte: `scores scores_categorical FINAL`,
};
+// Events-Observations View - queries from events table instead of observations table
+export const eventsObservationsView: ViewDeclarationType = {
+ name: "events_observations",
+ description:
+ "Observations from the events table. Supports denormalized trace fields (userId, sessionId, tags, release) but not trace-JOIN dimensions (traceName, traceRelease, traceVersion).",
+ dimensions: {
+ id: {
+ sql: "events_observations.span_id",
+ alias: "id",
+ type: "string",
+ description: "Unique identifier for the observation.",
+ },
+ traceId: {
+ sql: "events_observations.trace_id",
+ alias: "traceId",
+ type: "string",
+ description: "Identifier linking the observation to its parent trace.",
+ },
+ environment: {
+ sql: "events_observations.environment",
+ alias: "environment",
+ type: "string",
+ description: "Deployment environment (e.g., production, staging).",
+ },
+ parentObservationId: {
+ sql: "events_observations.parent_span_id",
+ alias: "parentObservationId",
+ type: "string",
+ description:
+ "Identifier of the parent observation. Empty for the root span.",
+ },
+ type: {
+ sql: "events_observations.type",
+ alias: "type",
+ type: "string",
+ description:
+ "Type of the observation. Can be a SPAN, GENERATION, or EVENT.",
+ },
+ name: {
+ sql: "events_observations.name",
+ alias: "name",
+ type: "string",
+ description: "Name of the observation.",
+ },
+ level: {
+ sql: "events_observations.level",
+ alias: "level",
+ type: "string",
+ description: "Logging level of the observation.",
+ },
+ version: {
+ sql: "events_observations.version",
+ alias: "version",
+ type: "string",
+ description: "Version of the observation.",
+ },
+ // Denormalized trace fields from events table
+ userId: {
+ sql: "events_observations.user_id",
+ alias: "userId",
+ type: "string",
+ description:
+ "Identifier of the user triggering the observation (denormalized from trace).",
+ },
+ sessionId: {
+ sql: "events_observations.session_id",
+ alias: "sessionId",
+ type: "string",
+ description:
+ "Identifier of the session triggering the observation (denormalized from trace).",
+ },
+ tags: {
+ sql: "events_observations.tags",
+ alias: "tags",
+ type: "string[]",
+ description:
+ "User-defined tags associated with the trace (denormalized from trace).",
+ },
+ release: {
+ sql: "events_observations.release",
+ alias: "release",
+ type: "string",
+ description: "Release version (denormalized from trace).",
+ },
+ providedModelName: {
+ sql: "events_observations.provided_model_name",
+ alias: "providedModelName",
+ type: "string",
+ description: "Name of the model used for the observation.",
+ },
+ promptName: {
+ sql: "events_observations.prompt_name",
+ alias: "promptName",
+ type: "string",
+ description: "Name of the prompt used for the observation.",
+ },
+ promptVersion: {
+ sql: "events_observations.prompt_version",
+ alias: "promptVersion",
+ type: "string",
+ description: "Version of the prompt used for the observation.",
+ },
+ startTimeMonth: {
+ sql: "formatDateTime(events.start_time, '%Y-%m')",
+ alias: "startTimeMonth",
+ type: "string",
+ description: "Month of the observation start_time in YYYY-MM format.",
+ },
+ },
+ measures: {
+ count: {
+ sql: "count(*)",
+ alias: "count",
+ type: "integer",
+ description: "Total number of observations.",
+ unit: "observations",
+ },
+ // Convert microseconds to milliseconds for consistency
+ latency: {
+ sql: "date_diff('microsecond', any(events.start_time), any(events.end_time)) / 1000",
+ alias: "latency",
+ type: "integer",
+ description:
+ "Latency of an individual observation (start time to end time).",
+ unit: "millisecond",
+ },
+ streamingLatency: {
+ sql: "if(isNull(any(events.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('microsecond', any(events.completion_start_time), any(events.end_time)) / 1000)",
+ alias: "streamingLatency",
+ type: "integer",
+ description:
+ "Latency of the generation step (completion start time to end time).",
+ unit: "millisecond",
+ },
+ inputTokens: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(usage_details))))",
+ alias: "inputTokens",
+ type: "integer",
+ description: "Sum of input tokens consumed by the observation.",
+ unit: "tokens",
+ },
+ outputTokens: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details))))",
+ alias: "outputTokens",
+ type: "integer",
+ description: "Sum of output tokens produced by the observation.",
+ unit: "tokens",
+ },
+ totalTokens: {
+ sql: "sumMap(usage_details)['total']",
+ alias: "totalTokens",
+ type: "integer",
+ description: "Sum of tokens consumed by the observation.",
+ unit: "tokens",
+ },
+ outputTokensPerSecond: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details)))) / nullIf(date_diff('second', any(events.completion_start_time), any(events.end_time)), 0)",
+ alias: "outputTokensPerSecond",
+ type: "decimal",
+ description:
+ "Average number of output tokens produced per second between completion start time and span end time.",
+ unit: "tokens/s",
+ },
+ tokensPerSecond: {
+ sql: "sumMap(usage_details)['total'] / date_diff('second', any(events.start_time), any(events.end_time))",
+ alias: "tokensPerSecond",
+ type: "decimal",
+ description:
+ "Average number of tokens consumed per second by the observation.",
+ unit: "tokens/s",
+ },
+ inputCost: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(cost_details))))",
+ alias: "inputCost",
+ type: "decimal",
+ description: "Sum of input cost incurred by the observation.",
+ unit: "USD",
+ },
+ outputCost: {
+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(cost_details))))",
+ alias: "outputCost",
+ type: "decimal",
+ description: "Sum of output cost incurred by the observation.",
+ unit: "USD",
+ },
+ totalCost: {
+ sql: "sum(total_cost)",
+ alias: "totalCost",
+ type: "decimal",
+ description: "Total cost incurred by the observation.",
+ unit: "USD",
+ },
+ timeToFirstToken: {
+ sql: "if(isNull(any(events.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('microsecond', any(events.start_time), any(events.completion_start_time)) / 1000)",
+ alias: "timeToFirstToken",
+ type: "integer",
+ description: "Time to first token for the observation.",
+ unit: "millisecond",
+ },
+ countScores: {
+ sql: "uniq(scores.id)",
+ alias: "countScores",
+ type: "integer",
+ relationTable: "scores",
+ description: "Unique scores attached to the observation.",
+ unit: "scores",
+ },
+ },
+ tableRelations: {
+ // No traces relation - userId, sessionId, tags are denormalized on events table
+ scores: {
+ name: "scores",
+ joinConditionSql:
+ "ON events_observations.span_id = scores.observation_id AND events_observations.project_id = scores.project_id",
+ timeDimension: "timestamp",
+ },
+ },
+ segments: [],
+ timeDimension: "start_time",
+ baseCte: "events events_observations", // No FINAL modifier needed for events table
+};
+
export const viewDeclarations: Record<
z.infer<typeof views>,
ViewDeclarationType
> = {
traces: traceView,
observations: observationsView,
+ "events-observations": eventsObservationsView,
"scores-numeric": scoresNumericView,
"scores-categorical": scoresCategoricalView,
};
diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.ts
index 897bcd6194..c4829dacbb 100644
--- a/web/src/features/query/server/queryBuilder.ts
+++ b/web/src/features/query/server/queryBuilder.ts
@@ -178,6 +178,11 @@ export class QueryBuilder {
}
}
+ private actualTableName(view: ViewDeclarationType): string {
+ // Extract actual table name from baseCte (handles cases like "events-observations" -> "events")
+ return view.baseCte.split(" ")[0];
+ }
+
private mapFilters(
filters: z.infer<typeof queryModel>["filters"],
view: ViewDeclarationType,
@@ -185,11 +190,13 @@ export class QueryBuilder {
// Validate all filters before processing
this.validateFilters(filters, view);
+ const actualTableName = this.actualTableName(view);
+
// Transform our filters to match the column mapping format expected by createFilterFromFilterState
const columnMappings = filters.map((filter) => {
let clickhouseSelect: string;
let queryPrefix: string = "";
- let clickhouseTableName: string = view.name;
+ let clickhouseTableName: string = actualTableName;
let type: string;
if (filter.column in view.dimensions) {
@@ -249,11 +256,13 @@ export class QueryBuilder {
fromTimestamp: string,
toTimestamp: string,
) {
+ const actualTableName = this.actualTableName(view);
+
// Create column mappings for standard filters
const projectIdMapping = {
uiTableName: "project_id",
uiTableId: "project_id",
- clickhouseTableName: view.name,
+ clickhouseTableName: actualTableName,
clickhouseSelect: "project_id",
queryPrefix: view.name,
type: "string",
@@ -262,7 +271,7 @@ export class QueryBuilder {
const timeDimensionMapping = {
uiTableName: view.timeDimension,
uiTableId: view.timeDimension,
- clickhouseTableName: view.name,
+ clickhouseTableName: actualTableName,
clickhouseSelect: view.timeDimension,
queryPrefix: view.name,
type: "datetime",
@@ -339,6 +348,8 @@ export class QueryBuilder {
filters: FilterList,
) {
const relationTables = new Set<string>();
+ const actualTableName = this.actualTableName(view);
+
appliedDimensions.forEach((dimension) => {
if (dimension.relationTable) {
relationTables.add(dimension.relationTable);
@@ -350,7 +361,11 @@ export class QueryBuilder {
}
});
filters.forEach((filter) => {
- if (filter.clickhouseTable !== view.name) {
+ // Only add as relation table if it's not the base table
+ if (
+ filter.clickhouseTable !== view.name &&
+ filter.clickhouseTable !== actualTableName
+ ) {
relationTables.add(filter.clickhouseTable);
}
});
@@ -538,14 +553,18 @@ export class QueryBuilder {
innerMetricsPart: string,
fromClause: string,
) {
+ // 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`;
+
return `
SELECT
- ${view.name}.project_id,
- ${view.name}.id,
+ ${projectIdSql},
+ ${idSql},
${innerDimensionsPart}
${innerMetricsPart}
${fromClause}
- GROUP BY ${view.name}.project_id, ${view.name}.id`;
+ GROUP BY ${projectIdSql}, ${idSql}`;
}
private buildOuterDimensionsPart(
@@ -810,8 +829,14 @@ export class QueryBuilder {
// Check if we should skip FINAL modifier for observations (OTEL optimization)
const skipObservationsFinal = await shouldSkipObservationsFinal(projectId);
let view = this.getViewDeclaration(query.view);
+
+ // Events table never needs FINAL modifier (already deduplicated)
+ if (view.name === "events-observations") {
+ // baseCte already set to "events" in view definition (no FINAL)
+ // No changes needed, just using as-is
+ }
// Skip FINAL on observations base table if OTEL project
- if (view.name === "observations" && skipObservationsFinal) {
+ else if (view.name === "observations" && skipObservationsFinal) {
view = {
...view,
baseCte: "observations", // Remove FINAL (was "observations FINAL")
diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.ts
index b885c20421..cfff796b22 100644
--- a/web/src/features/query/types.ts
+++ b/web/src/features/query/types.ts
@@ -51,6 +51,7 @@ export const stringDateTime = z.string().datetime({ offset: true });
export const views = z.enum([
"traces",
"observations",
+ "events-observations", // Events table observations (V2 API)
"scores-numeric",
"scores-categorical",
// "sessions",
diff --git a/web/src/pages/api/public/v2/metrics.ts b/web/src/pages/api/public/v2/metrics.ts
new file mode 100644
index 0000000000..1bbceee5bf
--- /dev/null
+++ b/web/src/pages/api/public/v2/metrics.ts
@@ -0,0 +1,45 @@
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { logger } from "@langfuse/shared/src/server";
+import {
+ GetMetricsV2Query,
+ GetMetricsV2Response,
+} from "@/src/features/public-api/types/metrics";
+import { executeQuery } from "@/src/features/query/server/queryExecutor";
+import { type QueryType } from "@/src/features/query/types";
+
+export default withMiddlewares({
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Metrics V2",
+ rateLimitResource: "public-api-metrics", // Same rate limit as v1
+ querySchema: GetMetricsV2Query,
+ responseSchema: GetMetricsV2Response,
+ fn: async ({ query, auth }) => {
+ try {
+ const queryParams = query.query;
+
+ // Map observations view to events-observations internally
+ let resolvedQuery: QueryType = queryParams;
+ if (queryParams.view === "observations") {
+ resolvedQuery = {
+ ...queryParams,
+ view: "events-observations", // Always use events table
+ };
+ }
+
+ logger.info("Received v2 metrics query", {
+ query: resolvedQuery,
+ version: "v2",
+ projectId: auth.scope.projectId,
+ });
+
+ const result = await executeQuery(auth.scope.projectId, resolvedQuery);
+
+ return { data: result };
+ } catch (error) {
+ logger.error("Error in v2 metrics API", { error, query });
+ throw error;
+ }
+ },
+ }),
+});